diff --git a/CHANGELOG.md b/CHANGELOG.md index 49343e9..60fba67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,38 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.16.0 — 2026-11-24 + +Reconciles nightly spec drift (#588). Additive only. No breaking changes. + +### Added + +- Perps **`SubaccountTypeLiteral`** gains `"swaps"` (a cross-margined swaps + wallet whose subaccount number is its swaps code). Shared by REST models + (`MarginPosition`, `MarginSubaccountBalance`, `MarginRiskPosition`, + `MarginFundingHistoryEntry`) and perps WS payloads (orderbook delta, fill, + user orders). Without this, REST responses carrying `subaccount_type` + `"swaps"` fail validation. + +### Docs + +- Historical fills (`fills` / `fills_all`, sync and async): `ticker` accepts + a comma-separated list of up to 100 market tickers. +- Weather point create: a new window must start at least 6 hours from now + (15 minutes on demo); title, rules, and `max_window_days` limits go by + the location's IANA zone; 429 includes a per-account daily creation limit. +- Concert cancellation create: the show must start more than 7 days from + now; an existing market is returned only while that is still true (else + 409). Cover is what the listing first shows from creation to scheduled + start; a move within six hours of the scheduled start is not a + postponement. 429 includes a per-account daily limit. +- Flight disruption 429 is a per-account or global daily creation limit. +- Klear `ObligationEntry.maintenance_margin_centicents` is the maintenance + margin change settled this cycle (sum of detail deltas, positive = + released), not the requirement. Detail delta is previous minus after. + Obligation history: at most one obligation per asset class per cycle, + none when nothing settles. + ## 22.15.0 — 2026-11-19 Adds on-request flight disruption markets (#586) against OpenAPI v3.37.0 diff --git a/docs/perps.md b/docs/perps.md index b50bc94..71cffd4 100644 --- a/docs/perps.md +++ b/docs/perps.md @@ -231,12 +231,13 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) - **Subaccounts** (since the v3.21.0 spec sync) — `MarginPosition` (the `portfolio.positions()` rows) carries a **required** `subaccount` (`int`) identifying which subaccount holds the position. `subaccount_type` - (`"cross"` / `"isolated"` / `"auto_rebalance"` / `"managed_isolated"`, or - `None` when the key is absent) is optional on `MarginPosition`, + (`"cross"` / `"isolated"` / `"auto_rebalance"` / `"managed_isolated"` / + `"swaps"`, or `None` when the key is absent) is optional on `MarginPosition`, `MarginSubaccountBalance`, `MarginRiskPosition`, and `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. + number as the market's isolated subaccount. `swaps` is a cross-margined + swaps wallet whose subaccount number is its swaps code. 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 @@ -371,7 +372,8 @@ Credentials can also come from the environment via `KlearClient.from_env()` (rea `klear.margin.active_obligations()` returns all currently-active settlement obligations. `klear.margin.obligation_history()` / `obligation_history_all()` -page historical obligations; optional `settlement_start_ts` / +page historical obligations; each cycle produces at most one obligation per +asset class, and none when nothing settles. Optional `settlement_start_ts` / `settlement_end_ts` (RFC3339 `datetime` or `str`) bound settlement time. `klear.margin.settlement_balance_history()` / `settlement_balance_history_all()` page settlement-buffer history; optional diff --git a/docs/resources/markets.md b/docs/resources/markets.md index 977593d..e3d38c8 100644 --- a/docs/resources/markets.md +++ b/docs/resources/markets.md @@ -180,9 +180,15 @@ print(resp.market_ticker, resp.created, resp.latitude, resp.longitude) unset optional fields are omitted from the wire body. The same request always returns the same market; `created` is false when it already existed. 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`. +three decimals share a market. A new market's window must start at least +6 hours from now (15 minutes on demo). `timezone` only says which span of +time `date` and the hours mean; the market's title and rules are written in +the location's IANA zone, and `max_window_days` limits go by that zone too. +Optional `end_date` (the day after `date`) opens a window that crosses +midnight in `timezone`, at most 24 hours. Whether a window across midnight +is offered does not go by `end_date`: where `max_window_days` is 1, a +request with `end_date` is accepted when the window lies within one date at +the location. ## Concert cancellation markets @@ -211,8 +217,13 @@ Take `jambase_event_id` and `scheduled_date` from `list_concerts` or `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`. +A new market's show must start more than 7 days from now. An existing market +is returned only while the show is more than 7 days away too; inside that, +create returns 409. Further out, `created` is false when a market for the +same request already existed. Cover is what the listing first shows from +creation to the show's scheduled start: a new start time on the scheduled +date, or within six hours of the scheduled start, is not a postponement. +Pass the returned `market_ticker` to `POST /communications/rfqs`. `list_concerts` is paged by the server (`page` / `total_pages`); there is no SDK paginator. diff --git a/kalshi/__init__.py b/kalshi/__init__.py index 384d5ad..d91e62f 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -553,4 +553,4 @@ "Withdrawal", ] -__version__ = "22.15.0" +__version__ = "22.16.0" diff --git a/kalshi/models/markets.py b/kalshi/models/markets.py index 5a08c7f..cffb1b1 100644 --- a/kalshi/models/markets.py +++ b/kalshi/models/markets.py @@ -390,7 +390,12 @@ class GetWeatherPointAvailabilityResponse(BaseModel): ConcertCoverLiteral = Literal["postponed", "cancelled", "either"] -"""What a concert cancellation market pays on. Spec: ConcertCover enum.""" +"""What a concert cancellation market pays on. Spec: ConcertCover enum. + +Pays on what the listing first shows from creation to the show's scheduled +start. A new start time on the scheduled date, or within six hours of the +scheduled start, is not a postponement. +""" class CreateConcertCancellationMarketRequest(BaseModel): diff --git a/kalshi/perps/klear/models/margin.py b/kalshi/perps/klear/models/margin.py index e86b83d..cce4b6b 100644 --- a/kalshi/perps/klear/models/margin.py +++ b/kalshi/perps/klear/models/margin.py @@ -176,10 +176,14 @@ class SettlementDetail(BaseModel): class MaintenanceMarginDetail(BaseModel): - """Spec ``MaintenanceMarginDetail`` — maintenance-margin requirement + delta. - - ``subtrader_id`` may be an empty string when not populated. - ``margin_group_id`` is set when the subtrader is part of a subtrader group. + """Spec ``MaintenanceMarginDetail`` — per-subtrader requirement after settlement. + + ``maintenance_margin_centicents`` is the requirement after this settlement + (0 when the subtrader goes flat). ``maintenance_margin_delta_centicents`` + is the previous settlement's requirement minus this one (positive means + margin released to the clearing member). ``subtrader_id`` may be an empty + string when not populated. ``margin_group_id`` is set when the subtrader + is part of a subtrader group. """ id: str @@ -270,6 +274,8 @@ class ObligationEntry(BaseModel): amount_centicents: int amount_fp: DollarDecimal | None = None fees_centicents: int + # Change settled this cycle (sum of detail deltas), not the requirement. + # Positive = released to the clearing member. maintenance_margin_centicents: int pnl_centicents: int pnl_fp: DollarDecimal | None = None @@ -294,8 +300,10 @@ class ObligationEntry(BaseModel): class GetObligationHistoryResponse(BaseModel): """Spec ``GetObligationHistoryResponse`` — cursor-paginated obligation page. - ``cursor`` is an RFC3339 date-time string; absent on the last page. The - resource consumes this via the generic ``Page[ObligationEntry]`` envelope. + Each settlement cycle produces at most one obligation per asset class, and + none when nothing settles. ``cursor`` is an RFC3339 date-time string; + absent on the last page. The resource consumes this via the generic + ``Page[ObligationEntry]`` envelope. """ obligations: NullableList[ObligationEntry] diff --git a/kalshi/perps/models/common.py b/kalshi/perps/models/common.py index 95da43e..110e0c9 100644 --- a/kalshi/perps/models/common.py +++ b/kalshi/perps/models/common.py @@ -103,14 +103,17 @@ class ExchangeInstance(StrEnum): MARGINED = "margined" -SubaccountTypeLiteral = Literal["cross", "isolated", "auto_rebalance", "managed_isolated"] +SubaccountTypeLiteral = Literal[ + "cross", "isolated", "auto_rebalance", "managed_isolated", "swaps" +] """Spec ``SubaccountType`` — how a 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 (shares its market's isolated subaccount number), and +isolated position (shares its market's isolated subaccount number), ``managed_isolated`` for a managed isolated position (subaccount number is -the same as the market's isolated subaccount number). +the same as the market's isolated subaccount number), and ``swaps`` for a +cross-margined swaps wallet (subaccount number is its swaps code). """ diff --git a/kalshi/resources/historical.py b/kalshi/resources/historical.py index 49bb8f9..f36787f 100644 --- a/kalshi/resources/historical.py +++ b/kalshi/resources/historical.py @@ -229,6 +229,10 @@ def fills( subaccount: int | None = None, extra_headers: dict[str, str] | None = None, ) -> Page[Fill]: + """List historical fills (``GET /historical/fills``). + + ``ticker`` accepts a comma-separated list of up to 100 market tickers. + """ self._require_auth() params = _historical_fills_or_orders_params( limit=limit, @@ -253,6 +257,10 @@ def fills_all( max_pages: int | None = None, extra_headers: dict[str, str] | None = None, ) -> Iterator[Fill]: + """Auto-paginate historical fills. + + ``ticker`` accepts a comma-separated list of up to 100 market tickers. + """ self._require_auth() _validate_max_pages(max_pages) params = _historical_fills_or_orders_params( @@ -540,6 +548,10 @@ async def fills( subaccount: int | None = None, extra_headers: dict[str, str] | None = None, ) -> Page[Fill]: + """List historical fills (``GET /historical/fills``, async). + + ``ticker`` accepts a comma-separated list of up to 100 market tickers. + """ self._require_auth() params = _historical_fills_or_orders_params( limit=limit, @@ -564,6 +576,10 @@ def fills_all( max_pages: int | None = None, extra_headers: dict[str, str] | None = None, ) -> AsyncIterator[Fill]: + """Auto-paginate historical fills (async). Use ``async for``. + + ``ticker`` accepts a comma-separated list of up to 100 market tickers. + """ self._require_auth() _validate_max_pages(max_pages) params = _historical_fills_or_orders_params( diff --git a/kalshi/resources/markets.py b/kalshi/resources/markets.py index 384e2b0..a4bbb13 100644 --- a/kalshi/resources/markets.py +++ b/kalshi/resources/markets.py @@ -667,8 +667,11 @@ 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. Optional ``end_date`` - (YYYY-MM-DD) is omitted when unset. + a market for the same request already existed. A new window must start + at least 6 hours from now (15 minutes on demo). ``timezone`` only + names the span of time; title, rules, and ``max_window_days`` limits + go by the location's IANA zone. Optional ``end_date`` (YYYY-MM-DD) is + omitted when unset. """ self._require_auth() body = _build_create_weather_point_market_body( @@ -723,8 +726,10 @@ def create_concert_cancellation_market( """``POST /concert_cancellation_markets``. Not retried. Returns the on-request concert cancellation market for a show, date and - cover, creating it if it does not exist. ``created`` is false when a - market for the same request already existed. + cover, creating it if it does not exist. The show must start more than + 7 days from now (an existing market is returned only while that is + still true; otherwise 409). ``created`` is false when a market for the + same request already existed. """ self._require_auth() body = _build_create_concert_cancellation_market_body( diff --git a/pyproject.toml b/pyproject.toml index 7a78dcd..337cfed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.15.0" +version = "22.16.0" description = "A professional Python SDK for the Kalshi prediction markets and Perps (margin) APIs" readme = "README.md" license = { text = "MIT" } diff --git a/specs/openapi.yaml b/specs/openapi.yaml index f96b14d..f5e21f3 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -4237,14 +4237,24 @@ paths: `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. + `max_window_days: 2`. A new market's window must start at least 6 + hours from now (15 minutes on demo) and within 365 days. + + `timezone` only says which span of time `date` and the hours mean. The + market is described in the IANA time zone of its location, which + Kalshi determines from the coordinates: its title and `rules_primary` + give the window there, with the weekday and the zone abbreviation in + force (`on Thu, Nov 19, 2026, 8pm–12am PST`), whatever zone the + request used. The limits on a window's dates go by the location's + zone as well: where `max_window_days` is 1, a new market whose window + crosses midnight at the location is refused even when the request + names one date in another zone, and one within one date at the + location is accepted even with `end_date`; and a window that crosses + midnight at the location is at most 24 hours long there. A market + that already exists is returned either way. An event created before + this applied keeps its description and its dates, in the time zone of + its first request, and so do thresholds added to it later: for those, + the `max_window_days` limit goes by the dates the event stores. A market is traded through RFQs: pass the returned `market_ticker` to `POST /communications/rfqs`. These markets are in series starting with @@ -4259,9 +4269,9 @@ 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` 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. | + | 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, in `timezone` or at the location, 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 in `timezone`. | + | 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 6 hours (15 minutes on demo), the market's window crosses midnight in the location's time zone where `max_window_days` is 1, or the location's time zone can't be determined. | + | 429 | `weather_point_market_limit_exceeded` | A creation limit was reached: the daily limit on new weather markets for your account, the daily limit across all users, or 40 markets for one variable, location and window. Returning an existing market never counts toward your account's limit. Retrying at once doesn't help. | | 429 | `too_many_requests` | Your API rate limit. This endpoint is charged against your write budget. | tags: - markets @@ -4342,11 +4352,17 @@ paths: refused when the show has moved to another date or has already been canceled or postponed. - 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. + A new market's show must start more than 7 days from now and within + the `max_days_ahead` that + `GET /concert_cancellation_markets/availability` reports. An existing + market is returned only while its show is more than 7 days away too: + inside that, counted to the market's close time or the show's start as + now listed, whichever is earlier, the request returns 409. Further + out, an existing market is usually returned even when new markets are + no longer offered; where creation or its cover is switched off, the + request returns 409. A 409 here changes nothing about the market + itself, which stays open until its close time and is still returned by + `GET /markets/{ticker}`. A market is traded through RFQs: pass the returned `market_ticker` to `POST /communications/rfqs`. These markets are in series starting with @@ -4363,8 +4379,8 @@ paths: | 400 | `missing_parameters` | A required field is missing or empty. | | 400 | `invalid_parameters` | A field is present but unusable: an unknown cover, a `jambase_event_id` that isn't `jambase:`, a `scheduled_date` that isn't YYYY-MM-DD, or a show scheduled further ahead than `max_days_ahead`. | | 404 | `not_found` | The listing source has no show with that id. | - | 409 | `concert_cancellation_market_unavailable` | The request is valid but the market isn't offered: concert markets or the cover are switched off, the show is now listed on another date, has already been canceled or postponed, starts too soon, isn't a concert, or its market has closed. | - | 429 | `concert_cancellation_market_limit_exceeded` | The daily limit on new concert markets across all users was reached. Retrying at once doesn't help. | + | 409 | `concert_cancellation_market_unavailable` | The request is valid but the market isn't offered: concert markets or the cover are switched off, the show is now listed on another date, has already been canceled or postponed, starts in 7 days or less (whether or not its market already exists), isn't a concert, or its market has closed. | + | 429 | `concert_cancellation_market_limit_exceeded` | A daily limit on new concert markets was reached: your account's, or the one across all users. Returning an existing market never counts toward your account's limit. Retrying at once doesn't help. | | 429 | `too_many_requests` | Your API rate limit. This endpoint is charged against your write budget. | tags: - markets @@ -4630,7 +4646,7 @@ paths: | 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 | `flight_disruption_market_limit_exceeded` | A daily limit on new flight markets was reached: your account's, or the one across all users. Returning an existing market never counts toward your account's limit. Retrying at once doesn't help. | | 429 | `too_many_requests` | Your API rate limit. This endpoint is charged against your write budget. | tags: - markets @@ -5674,7 +5690,12 @@ paths: kalshiAccessTimestamp: [] - kalshiOauthAccessToken: [] parameters: - - $ref: '#/components/parameters/TickerQuery' + - name: ticker + in: query + description: Filter by market ticker. Accepts a comma-separated list of up to 100 market tickers. + schema: + type: string + x-go-type-skip-optional-pointer: true - $ref: '#/components/parameters/MinTsQuery' - $ref: '#/components/parameters/MaxTsQuery' - $ref: '#/components/parameters/LimitQuery' @@ -11659,7 +11680,7 @@ components: 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. + 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 in `timezone`; `end_hour` is then read on this date, and the window is at most 24 hours long. Any other date is refused. Whether a window across midnight is offered (`max_window_days` 2 in availability) doesn't go by this field. For a market that starts a new event it goes by the dates at the market's location; where `max_window_days` is 1, a request with `end_date` is accepted when the window lies within one date at the location, and one without it is refused when the window crosses midnight there. A threshold added to an event that already exists goes by the dates that event stores, which on an older event are those of its first request. example: '2026-11-12' x-oapi-codegen-extra-tags: validate: omitempty,datetime=2006-01-02 @@ -11683,7 +11704,7 @@ components: 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. + description: IANA time zone that `date`, `end_date` and the hours are read in. It only says which span of time they mean, and needn't be the location's; the market's title and rules are written in the location's own time zone, whatever is sent here. 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 @@ -11804,11 +11825,19 @@ components: - ConcertCoverCancelled - ConcertCoverEither description: | - What a concert cancellation market pays on, read from the show's - listing after its scheduled date has ended: - - `postponed`: Yes when the show is listed as postponed, or as taking - place on any other date. A show listed as canceled resolves to No. - - `cancelled`: Yes when the show is listed as canceled. + What a concert cancellation market pays on: what the show's listing + first shows from the market's creation to the show's scheduled start + (the market's close time is one minute before it), whatever the + listing says afterwards. + - `postponed`: Yes when the show is postponed, or moved to a later + date. A new start time on the scheduled date, or within six hours + of the scheduled start, is not a postponement, even when it falls + on the next calendar day (11:30 PM moved to 12:30 AM). A + cancellation alone doesn't count: a show that is canceled and not + postponed resolves to No, and one that is canceled, reinstated and + then postponed was postponed. + - `cancelled`: Yes when the show is canceled, including after a + postponement. - `either`: Yes in both of those cases. CreateConcertCancellationMarketRequest: diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index 94716cc..aa1cdc6 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -3618,9 +3618,9 @@ components: SubaccountType: 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 the same as the market's isolated subaccount number. + enum: ['cross', 'isolated', 'auto_rebalance', 'managed_isolated', 'swaps'] + x-enum-varnames: [SubaccountTypeCross, SubaccountTypeIsolated, SubaccountTypeAutoRebalance, SubaccountTypeManagedIsolated, SubaccountTypeSwaps] + 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, `managed_isolated` for a managed isolated position, whose subaccount number is the same as the market's isolated subaccount number, and `swaps` for a cross-margined swaps wallet, whose subaccount number is its swaps code. LastUpdateReason: type: string diff --git a/specs/perps_scm_openapi.yaml b/specs/perps_scm_openapi.yaml index 9428ef7..5088926 100644 --- a/specs/perps_scm_openapi.yaml +++ b/specs/perps_scm_openapi.yaml @@ -75,7 +75,12 @@ paths: get: operationId: GetObligationHistory summary: Get Obligation History - description: Completed obligations from previous settlements, ordered by most recent first. + description: >- + Completed obligations from previous settlements, ordered by most recent + first. Each settlement cycle produces at most one obligation per asset + class, and none when nothing settles in it (no PnL in any market, no + fees and no maintenance margin change). Markets whose PnL offsets still + produce an obligation, at $0. parameters: - { name: limit, in: query, required: false, schema: { type: integer, default: 20, maximum: 100 }, description: Number of results per page. } @@ -824,7 +829,18 @@ components: Kalshi Klear; positive means Kalshi Klear pays the clearing member. amount_fp: { type: string, description: "amount_centicents as a fixed-point dollar string with 6 decimal places (e.g. \"10005.000000\")." } fees_centicents: { type: integer, format: int64, description: Trading fees incurred during the settlement period. } - maintenance_margin_centicents: { type: integer, format: int64, description: Current maintenance margin requirement for this obligation. } + maintenance_margin_centicents: + type: integer + format: int64 + description: | + Maintenance margin change settled by this obligation: the sum of + `maintenance_margin_delta_centicents` over all of its maintenance + margin details (when `maintenance_margin_details_truncated` is set, + page `/margin/obligations/{obligation_id}/maintenance_margin_details` + for the full set). Positive means margin released to the clearing + member; negative means additional margin the clearing member owes. + This is not the requirement: per-subtrader requirements are the + `maintenance_margin_centicents` values in the details. pnl_centicents: { type: integer, format: int64, description: "Total PnL for this settlement period; the sum of the settlement details for this settlement cycle." } pnl_fp: { type: string, description: pnl_centicents as a fixed-point dollar string with 6 decimal places. } execution_time: { type: string, format: date-time, description: Settlement cycle time this obligation belongs to. } @@ -937,7 +953,14 @@ components: subtrader_id: { type: string, description: Empty when not populated or when the subtrader is part of a subtrader group. } margin_group_id: { type: string, description: Set when the subtrader is part of a subtrader group. } maintenance_margin_centicents: { type: integer, format: int64, description: Maintenance margin requirement after this settlement. } - maintenance_margin_delta_centicents: { type: integer, format: int64, description: Change in maintenance margin between the previous settlement and this one. } + maintenance_margin_delta_centicents: + type: integer + format: int64 + description: | + Requirement at the previous settlement minus the requirement after + this one. Positive means margin released to the clearing member; + negative means the requirement rose and the clearing member owes + the increase. ObligationEntry: allOf: @@ -959,8 +982,12 @@ components: type: array items: { $ref: '#/components/schemas/MaintenanceMarginDetail' } description: | - Breakdown of the maintenance margin requirement and the delta - from the prior settlement. + Per-subtrader maintenance margin requirement after this + settlement and its delta from the prior settlement. Lists each + subtrader or subtrader group that holds positions at this + settlement or had a nonzero requirement at the prior one, so a + subtrader that goes flat appears with a requirement of 0. + Others are omitted. funding_payments: type: array items: { $ref: '#/components/schemas/FundingPaymentDetail' } diff --git a/tests/perps/test_funding.py b/tests/perps/test_funding.py index 1a0c50d..67d693d 100644 --- a/tests/perps/test_funding.py +++ b/tests/perps/test_funding.py @@ -496,6 +496,9 @@ def test_omitted_is_none_and_parses(self) -> None: present = _entry(funding_amount="1.00", subaccount_number=0) present["subaccount_type"] = "isolated" assert MarginFundingHistoryEntry.model_validate(present).subaccount_type == "isolated" + swaps = _entry(funding_amount="1.00", subaccount_number=0) + swaps["subaccount_type"] = "swaps" + assert MarginFundingHistoryEntry.model_validate(swaps).subaccount_type == "swaps" def test_invalid_raises(self) -> None: payload = _entry(funding_amount="1.00", subaccount_number=0) diff --git a/tests/perps/test_margin_account.py b/tests/perps/test_margin_account.py index 516e15e..ba5a647 100644 --- a/tests/perps/test_margin_account.py +++ b/tests/perps/test_margin_account.py @@ -937,6 +937,8 @@ def test_balance_omitted_is_none_and_parses(self) -> None: _balance_row(subaccount_type="isolated") ) assert parsed.subaccount_type == "isolated" + swaps = MarginSubaccountBalance.model_validate(_balance_row(subaccount_type="swaps")) + assert swaps.subaccount_type == "swaps" def test_balance_invalid_raises(self) -> None: with pytest.raises(ValidationError): @@ -946,6 +948,8 @@ def test_risk_omitted_is_none_and_parses(self) -> None: assert MarginRiskPosition.model_validate(_risk_row()).subaccount_type is None parsed = MarginRiskPosition.model_validate(_risk_row(subaccount_type="auto_rebalance")) assert parsed.subaccount_type == "auto_rebalance" + swaps = MarginRiskPosition.model_validate(_risk_row(subaccount_type="swaps")) + assert swaps.subaccount_type == "swaps" def test_risk_invalid_raises(self) -> None: with pytest.raises(ValidationError): diff --git a/tests/perps/test_portfolio.py b/tests/perps/test_portfolio.py index 498a3fa..761edb7 100644 --- a/tests/perps/test_portfolio.py +++ b/tests/perps/test_portfolio.py @@ -798,6 +798,11 @@ def test_parses_managed_isolated(self) -> None: MarginPosition.model_validate(payload).subaccount_type == "managed_isolated" ) + def test_parses_swaps(self) -> None: + payload = _long_position() + payload["subaccount_type"] = "swaps" + assert MarginPosition.model_validate(payload).subaccount_type == "swaps" + def test_invalid_raises(self) -> None: payload = _long_position() payload["subaccount_type"] = "hedged" diff --git a/tests/perps/ws/test_perps_ws_models.py b/tests/perps/ws/test_perps_ws_models.py index cf90aa4..5fa9183 100644 --- a/tests/perps/ws/test_perps_ws_models.py +++ b/tests/perps/ws/test_perps_ws_models.py @@ -366,7 +366,7 @@ def test_delta_subaccount_type_optional(self) -> None: } ) assert omitted.msg.subaccount_type is None - for value in ("cross", "isolated", "managed_isolated", "auto_rebalance"): + for value in ("cross", "isolated", "managed_isolated", "auto_rebalance", "swaps"): frame["msg"]["subaccount_type"] = value parsed = MarginOrderbookDeltaMessage.model_validate(frame) assert parsed.msg.subaccount_type == value @@ -578,7 +578,7 @@ def test_subaccount_type_optional(self) -> None: 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"): + for value in ("cross", "isolated", "managed_isolated", "auto_rebalance", "swaps"): frame["msg"]["subaccount_type"] = value parsed = MarginFillMessage.model_validate(frame) assert parsed.msg.subaccount_type == value @@ -647,7 +647,7 @@ def test_subaccount_type_optional(self) -> None: 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"): + for value in ("cross", "isolated", "managed_isolated", "auto_rebalance", "swaps"): frame["msg"]["subaccount_type"] = value parsed = MarginUserOrderMessage.model_validate(frame) assert parsed.msg.subaccount_type == value