From e72dfb31b2a4967c17b3d95ded10dcbdf89b4608 Mon Sep 17 00:00:00 2001 From: Jeff West Date: Thu, 26 Nov 2026 09:10:53 -0600 Subject: [PATCH 1/2] chore(spec): sync specs 2026-11-26 (core 3.38.0, perps corporate action payment history, exchange_status WS) --- specs/openapi.yaml | 15 +++- specs/perps_asyncapi.yaml | 76 ++++++++++++++++++- specs/perps_openapi.yaml | 151 ++++++++++++++++++++++++++++++++++---- 3 files changed, 220 insertions(+), 22 deletions(-) diff --git a/specs/openapi.yaml b/specs/openapi.yaml index f5e21f3..f649d8f 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.37.0 + version: 3.38.0 description: Manually defined OpenAPI spec for endpoints being migrated to spec-first approach servers: @@ -2037,6 +2037,13 @@ paths: - $ref: '#/components/parameters/PositionsLimitQuery' - $ref: '#/components/parameters/CountFilterQuery' - $ref: '#/components/parameters/PositionSettlementStatusQuery' + - name: sort_by + in: query + required: false + description: 'Order event groups by ticker ascending. Omit to use the default ordering.' + schema: + type: string + enum: [event_ticker] - $ref: '#/components/parameters/TickerQuery' - $ref: '#/components/parameters/SingleEventTickerQuery' - $ref: '#/components/parameters/SubaccountQueryDefaultPrimary' @@ -6082,7 +6089,7 @@ components: PositionsCursorQuery: name: cursor in: query - description: The Cursor represents a pointer to the next page of records in the pagination. Use the value returned from the previous response to get the next page. + description: 'Cursor returned by the previous page. Keep filters and sort_by unchanged while paginating.' schema: type: string @@ -8560,7 +8567,7 @@ components: description: Cost basis of the remaining position in dollars, excluding fees; not current market value or realized loss. realized_pnl_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Locked in profit and loss, in dollars + description: Locked in profit and loss, in dollars, before fees. Fees are reported separately in `fees_paid_dollars`. fees_paid_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Fees paid on fill orders, in dollars @@ -8596,7 +8603,7 @@ components: description: Cost of the aggregate event position in dollars realized_pnl_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Locked in profit and loss, in dollars + description: Locked in profit and loss, in dollars, before fees. Fees are reported separately in `fees_paid_dollars`. fees_paid_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Fees paid on fill orders, in dollars diff --git a/specs/perps_asyncapi.yaml b/specs/perps_asyncapi.yaml index ec5d7d1..c277ffd 100644 --- a/specs/perps_asyncapi.yaml +++ b/specs/perps_asyncapi.yaml @@ -14,6 +14,7 @@ info: - `order_group_updates` - `corporate_actions` - `market_lifecycle_v2` + - `exchange_status` contact: name: Kalshi Support url: https://kalshi.com @@ -241,6 +242,20 @@ channels: orderGroupUpdates: $ref: '#/components/messages/orderGroupUpdates' + exchange_status: + address: exchange_status + title: Exchange Status + description: | + Sent when trading is paused or resumed exchange-wide, or when the exchange status changes. + Trading messages carry `trading_active`. Exchange status messages carry `exchange_active`. + Both flags mean the same as in `GET /trade-api/v2/margin/exchange/status`, + and trading is open exchange-wide only while both are true. A message can repeat the current + value. Per-market halts and trading-hours closes are sent on `market_lifecycle_v2`, not on this + channel; a market is open only while both channels show it open. + messages: + exchangeStatus: + $ref: '#/components/messages/exchangeStatus' + operations: receiveCorporateActions: action: send @@ -263,6 +278,16 @@ operations: tags: - name: market-data + receiveExchangeStatus: + action: send + title: Receive Exchange Status + channel: + $ref: '#/channels/exchange_status' + messages: + - $ref: '#/channels/exchange_status/messages/exchangeStatus' + tags: + - name: market-data + sendPing: action: receive title: Send Ping @@ -712,6 +737,24 @@ components: order_group_id: "og_123" contracts_limit_fp: "150.00" ts_ms: 1733047200000 + exchangeStatus: + name: exchange_status + title: Exchange Status + summary: Exchange-wide trading and exchange status changes + contentType: application/json + payload: + $ref: '#/components/schemas/marginExchangeStatusPayload' + examples: + - name: tradingPaused + summary: Trading paused exchange-wide + payload: + type: exchange_status + sending_ts_ms: 1733047200123 + sid: 3 + seq: 1 + msg: + trading_active: false + ts_ms: 1733047200000 schemas: sendingTimestampMs: @@ -823,7 +866,7 @@ components: minItems: 1 items: type: string - enum: ["orderbook_delta", "ticker", "trade", "fill", "user_orders", "order_group_updates", "corporate_actions", "market_lifecycle_v2"] + enum: ["orderbook_delta", "ticker", "trade", "fill", "user_orders", "order_group_updates", "corporate_actions", "market_lifecycle_v2", "exchange_status"] market_ticker: type: string market_tickers: @@ -1155,7 +1198,7 @@ components: ts_ms: type: integer format: int64 - description: "Unix timestamp in milliseconds when the exchange applied the action." + description: "Unix timestamp in milliseconds when the exchange published the action." split: $ref: '#/components/schemas/marginCorporateActionSplitTerms' final_settlement: @@ -1550,6 +1593,35 @@ components: sending_ts_ms: $ref: '#/components/schemas/sendingTimestampMs' + marginExchangeStatusPayload: + type: object + required: ["type", "sid", "seq", "msg"] + properties: + type: + type: string + const: "exchange_status" + sid: + $ref: '#/components/schemas/subscriptionId' + seq: + $ref: '#/components/schemas/sequenceNumber' + msg: + type: object + required: ["ts_ms"] + properties: + exchange_active: + type: boolean + description: False while the exchange is paused and accepts no state changes. Present on exchange status messages. + trading_active: + type: boolean + description: False while trading is paused exchange-wide; trading is open only while both this and `exchange_active` are true. Present on trading messages. + ts_ms: + type: integer + format: int64 + description: Unix timestamp in milliseconds when the exchange published the change. + + sending_ts_ms: + $ref: '#/components/schemas/sendingTimestampMs' + securitySchemes: apiKey: type: apiKey diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index aa1cdc6..6e002cd 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -55,6 +55,67 @@ paths: '500': $ref: '#/components/responses/InternalServerError' + /margin/corporate_action_payment_history: + get: + operationId: GetMarginCorporateActionPaymentHistory + summary: Get Corporate Action Payment History + description: 'Endpoint for retrieving the cash the authenticated user received or paid for corporate actions (cash dividends, special dividends and cash spin-offs) for a specific market, or across all markets when ticker is empty, over an inclusive UTC date range. Each entry includes the gross payment, the amount withheld, and the position used to compute the payment. Stock split adjustments are not included.' + tags: + - corporate-actions + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + parameters: + - name: ticker + in: query + required: false + description: Market ticker for payment history. Leave empty to query across all markets. + schema: + type: string + x-go-type-skip-optional-pointer: true + - name: start_date + in: query + required: true + description: Inclusive UTC start date for the payment time range (YYYY-MM-DD format) + schema: + type: string + format: date + x-go-type-skip-optional-pointer: true + x-oapi-codegen-extra-tags: + validate: required + - name: end_date + in: query + required: true + description: Inclusive UTC end date for the payment time range (YYYY-MM-DD format) + schema: + type: string + format: date + x-go-type-skip-optional-pointer: true + x-oapi-codegen-extra-tags: + validate: required + - name: subaccount + in: query + required: false + description: Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, defaults to all subaccounts. Subaccount-restricted API keys must omit this or pass their locked subaccount, and read only that subaccount's payments. + schema: + type: integer + responses: + '200': + description: Corporate action payment history retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetMarginCorporateActionPaymentHistoryResponse' + '400': + $ref: '#/components/responses/BadRequestError' + '401': + $ref: '#/components/responses/UnauthorizedError' + '403': + $ref: '#/components/responses/ForbiddenError' + '500': + $ref: '#/components/responses/InternalServerError' + /margin/fcm/subtraders: post: operationId: CreateMarginFCMSubtrader @@ -723,7 +784,7 @@ paths: schema: $ref: '#/components/schemas/MarginMarketStatus' x-go-type-skip-optional-pointer: true - description: Filter by market status (e.g. active, inactive, closed) + description: Filter by market status (e.g. active, inactive, finalized) responses: '200': description: Markets retrieved successfully @@ -1039,7 +1100,7 @@ paths: - name: subaccount in: query required: false - description: Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, returns positions for all subaccounts. Subaccount-restricted API keys must omit this or pass their locked subaccount, and read only that subaccount's positions. + description: Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, returns positions for all subaccounts. `0` returns only the primary account's cross-margin positions; an isolated position is held in its market's isolated subaccount, so omit this parameter to include it. Subaccount-restricted API keys must omit this or pass their locked subaccount, and read only that subaccount's positions. schema: type: integer - name: ticker @@ -2590,8 +2651,9 @@ components: $ref: '#/components/schemas/FixedPointCount' description: >- Contracts this trigger closes when it fires. Omit it to cover the whole position, - which then requires that no partial or anchored trigger already covers part of it. - If supplied, it must be a whole number of contracts. + which for a bracket requires that no partial or anchored bracket covers part of it. + If supplied, it must be a whole number of contracts, or a multiple of `0.01` on a + market whose `fractional_trading_enabled` is true. anchor_order_id: type: string description: >- @@ -2727,7 +2789,9 @@ components: shorts. Trailing triggers only. count: $ref: '#/components/schemas/FixedPointCount' - description: Contracts this trigger closes when it fires. `0` means the whole position. + description: >- + Contracts this trigger closes when it fires. `0` means the whole position, except on + an order-anchored trigger whose order has not filled, which covers nothing. filled_count: $ref: '#/components/schemas/FixedPointCount' description: Contracts closed so far across fire attempts. @@ -3006,7 +3070,7 @@ components: description: String representation of the order quantity in contracts. price: $ref: '#/components/schemas/FixedPointDollars' - description: Price for the order in fixed-point dollars. + description: Price for the order in fixed-point dollars per contract, not per unit of the underlying. See Prices and contract size in the Perps API overview (https://docs.kalshi.com/margin#prices-and-contract-size). x-go-type-skip-optional-pointer: true expiration_time: type: integer @@ -3364,10 +3428,10 @@ components: description: "Deprecated: has no effect on order groups or rate limits. This field will be removed." contract_size: type: string - description: Fixed-point number with 6 decimal places + description: Size of one contract in the market's underlying units, as a fixed-point number with 6 decimal places. Prices are per contract, and track the underlying asset's price × `underlying_multiplier` × `contract_size`. underlying_multiplier: type: string - description: Underlying units per contract-size unit. + description: How many of the underlying asset make up one underlying unit, as a fixed-point number with 6 decimal places. For example, `1000.000000` on a market whose unit is a thousand of the asset. tick_size: $ref: '#/components/schemas/FixedPointDollars' description: Minimum price increment in dollars. @@ -3436,13 +3500,13 @@ components: description: Total notional value of one sided trade volume in the last 24 hours in dollars. bid: $ref: '#/components/schemas/FixedPointDollars' - description: Best bid price in dollars. + description: Best bid price in dollars. `0.0000` when there is no bid, so check `bid_size_fp` before using it. bid_size_fp: $ref: '#/components/schemas/FixedPointCount' description: Total number of contracts resting at the best bid price, as a fixed-point count string. Zero when there is no bid. Omitted when market stats are unavailable. ask: $ref: '#/components/schemas/FixedPointDollars' - description: Best ask price in dollars. + description: Best ask price in dollars. When there is no ask this is a placeholder, not a price (`922337203685477.5807` or `0.0000`), so check `ask_size_fp` before using it. ask_size_fp: $ref: '#/components/schemas/FixedPointCount' description: Total number of contracts resting at the best ask price, as a fixed-point count string. Zero when there is no ask. Omitted when market stats are unavailable. @@ -3603,7 +3667,7 @@ components: MarginMarketStatus: type: string - enum: [inactive, active, closed] + enum: [inactive, active, finalized] description: The status of a margin market OrderSource: @@ -3704,7 +3768,7 @@ components: description: Fees paid on filled contracts, in dollars realized_pnl: type: string - description: Incremental realized PnL contributed by this fill, in fixed-point dollars + description: Incremental realized PnL contributed by this fill, in fixed-point dollars, before fees order_source: $ref: '#/components/schemas/OrderSource' description: Whether the order behind this fill was placed by the user or by the system. `system` covers liquidation, TP/SL and auto-rebalance orders alike; to tell them apart, fetch the order by `order_id` and read its `order_reason`. @@ -3733,7 +3797,7 @@ components: properties: subaccount: type: integer - description: The subaccount number that holds this position (0 for primary, 1-63 for subaccounts) + description: The subaccount number that holds this position (0 for primary, 1-63 for subaccounts, 64-4095 for a market's isolated subaccount) subaccount_type: $ref: '#/components/schemas/SubaccountType' market_ticker: @@ -3747,7 +3811,7 @@ components: description: Weighted average entry price of the open position unrealized_pnl: $ref: '#/components/schemas/FixedPointDollars' - description: Mark-to-market unrealized PnL for the open position + description: Mark-to-market unrealized PnL for the open position, before fees. Fees are reported separately in `fees`. margin_used: $ref: '#/components/schemas/FixedPointDollars' nullable: true @@ -3896,7 +3960,7 @@ components: properties: subaccount: type: integer - description: The subaccount number (0 for primary, 1-63 for subaccounts) + description: The subaccount number (0 for primary, 1-63 for subaccounts, 64-4095 for a market's isolated subaccount) subaccount_type: $ref: '#/components/schemas/SubaccountType' position_value: @@ -3945,7 +4009,7 @@ components: properties: subaccount: type: integer - description: The subaccount number (0 for primary, 1-63 for subaccounts) + description: The subaccount number (0 for primary, 1-63 for subaccounts, 64-4095 for a market's isolated subaccount) subaccount_type: $ref: '#/components/schemas/SubaccountType' market_ticker: @@ -4118,6 +4182,61 @@ components: items: $ref: '#/components/schemas/MarginCorporateAction' + MarginCorporateActionPaymentHistoryEntry: + type: object + required: + - corporate_action_id + - type + - market_ticker + - payment_time + - payment_amount + - quantity + - subaccount_number + - subaccount_type + - withholding_amount + properties: + corporate_action_id: + type: string + description: "Corporate action id, matching `id` in `GET /margin/corporate_actions`." + type: + type: string + enum: [cash_dividend, special_dividend, spin_off] + x-enum-varnames: [MarginCorporateActionPaymentHistoryEntryTypeCashDividend, MarginCorporateActionPaymentHistoryEntryTypeSpecialDividend, MarginCorporateActionPaymentHistoryEntryTypeSpinOff] + description: Corporate action type + market_ticker: + type: string + description: Ticker of the margin market + payment_time: + type: string + format: date-time + description: The corporate action's execution time. The payment is computed on the position held just before this time; the cash can post to your balance after it. + payment_amount: + $ref: '#/components/schemas/FixedPointDollars' + description: Gross dollar amount before withholding (positive = received, negative = paid) + quantity: + $ref: '#/components/schemas/FixedPointCount' + description: Signed position size the payment was computed on (positive = long, negative = short) as a fixed-point count string + subaccount_number: + type: integer + nullable: true + description: Subaccount number (0 for primary) + subaccount_type: + $ref: '#/components/schemas/SubaccountType' + withholding_amount: + $ref: '#/components/schemas/FixedPointDollars' + description: Amount withheld from the payment in dollars. Subtract this from payment_amount for the net cash amount. + + GetMarginCorporateActionPaymentHistoryResponse: + type: object + required: + - payment_history + properties: + payment_history: + type: array + items: + $ref: '#/components/schemas/MarginCorporateActionPaymentHistoryEntry' + description: Array of corporate action payment entries, newest first + MarginCorporateAction: type: object description: >- From 2a23c7ce71ed351412a0d91ab1ef5674f98bbecb Mon Sep 17 00:00:00 2001 From: Jeff West Date: Thu, 26 Nov 2026 09:30:54 -0600 Subject: [PATCH 2/2] =?UTF-8?q?feat(perps):=20corporate=20action=20payment?= =?UTF-8?q?=20history,=20finalized=20status,=20exchange=5Fstatus=20WS;=20p?= =?UTF-8?q?ositions=20sort=5Fby=20(#590)=20=E2=80=94=2022.17.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 45 +++++ CLAUDE.md | 2 +- README.md | 4 +- docs/index.md | 4 +- docs/perps.md | 70 ++++++-- docs/resources/portfolio.md | 10 +- kalshi/__init__.py | 2 +- kalshi/_contract_map.py | 8 + kalshi/models/portfolio.py | 2 + kalshi/perps/__init__.py | 10 ++ kalshi/perps/models/__init__.py | 6 + kalshi/perps/models/common.py | 20 ++- kalshi/perps/models/margin_account.py | 48 ++++- kalshi/perps/models/markets.py | 15 +- kalshi/perps/models/orders.py | 1 + kalshi/perps/models/portfolio.py | 10 ++ kalshi/perps/resources/margin_account.py | 90 +++++++++- kalshi/perps/resources/portfolio.py | 3 +- kalshi/perps/ws/client.py | 22 ++- kalshi/perps/ws/dispatch.py | 2 + kalshi/perps/ws/models/__init__.py | 6 + kalshi/perps/ws/models/control.py | 1 + kalshi/perps/ws/models/exchange_status.py | 38 ++++ kalshi/resources/portfolio.py | 12 +- pyproject.toml | 2 +- tests/_contract_support.py | 5 + tests/perps/test_margin_account.py | 208 +++++++++++++++++++++- tests/perps/test_markets.py | 12 ++ tests/perps/test_models_common.py | 10 +- tests/perps/ws/test_dispatch.py | 1 + tests/perps/ws/test_perps_ws_channels.py | 27 +++ tests/perps/ws/test_perps_ws_models.py | 54 ++++++ tests/test_portfolio.py | 88 +++++++++ 33 files changed, 793 insertions(+), 45 deletions(-) create mode 100644 kalshi/perps/ws/models/exchange_status.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 60fba67..b8d46d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,51 @@ All notable changes to kalshi-sdk will be documented in this file. +## 22.17.0 — 2026-11-26 + +Reconciles nightly spec drift (#590). Additive only. No breaking changes. + +### Added + +- Perps **`margin.corporate_action_payment_history(*, start_date, end_date, + ticker=, subaccount=)`** (sync + async) — + `GET /margin/corporate_action_payment_history`. Auth required. Returns + cash received or paid for corporate actions (cash dividends, special + dividends, cash spin-offs) over an inclusive UTC date range. + `start_date` / `end_date` are required YYYY-MM-DD (`datetime.date` or + `str`). Optional `ticker` and `subaccount` are sent only when set. + Stock split adjustments are not included. (Closes #590). +- Perps **`MarginMarketStatus` / `MarginMarketStatusLiteral`** gain + `"finalized"`. The spec renamed `"closed"` to `"finalized"`; `"closed"` + is kept for compatibility. +- Optional **`sort_by="event_ticker"`** on core `portfolio.positions` and + `positions_all` (sync and async). Orders event groups by ticker + ascending; omit for the default ordering. Sent only when set. Keep + filters and `sort_by` unchanged while paginating. +- Perps WebSocket **`exchange_status`** channel and + **`subscribe_exchange_status()`**. Payload + `MarginExchangeStatusMessage`: trading messages carry `trading_active`, + exchange status messages carry `exchange_active`. Trading is open + exchange-wide only while both are true. + +### Changed + +- Perps **`MarginMarketStatus`** spec enum is now `inactive` / `active` / + `finalized`. SDK still accepts `"closed"`. + +### Docs + +- Core `MarketPosition` / `EventPosition` `realized_pnl` and perps + `MarginPosition.unrealized_pnl` / `MarginFill.realized_pnl` are before + fees (`fees_paid` / `fees` reported separately). +- Perps subaccount numbers 64–4095 are a market's isolated subaccount. + `portfolio.positions(subaccount=0)` returns only primary cross-margin + positions; omit `subaccount` to include isolated. +- Perps `MarginMarket.bid` is `0` when none; `ask` is a placeholder + (`922337203685477.5807` or `0`) when none — check size first. + `contract_size` / `underlying_multiplier` meanings; order `price` is + per contract; exit-trigger `count` fractional rule. + ## 22.16.0 — 2026-11-24 Reconciles nightly spec drift (#588). Additive only. No breaking changes. diff --git a/CLAUDE.md b/CLAUDE.md index a43dee9..b5cf2a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,7 +122,7 @@ tests/ ## API Reference -- 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) +- OpenAPI spec: https://docs.kalshi.com/openapi.yaml (v3.38.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 c848a28..3fba1ef 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ 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 (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). +- **Full coverage** of the Kalshi REST API (144 mapped of 145 operations across 19 resources, OpenAPI v3.38.0) and WebSocket API (13 typed `subscribe_*` channels + escape-hatch). +- **Perps (margin) API**: standalone `PerpsClient` / `AsyncPerpsClient` + `PerpsWebSocket` for the perpetual-futures exchange (55 REST operations, 9 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. - **Funding & cost introspection**: `portfolio.deposits()`, `portfolio.withdrawals()`, `account.endpoint_costs()`. diff --git a/docs/index.md b/docs/index.md index b4ca370..9c5a3b8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,7 +4,7 @@ A professional, spec-first Python SDK for the [Kalshi](https://kalshi.com) predi markets API. - **Full REST coverage** — 144 mapped of 145 operations across 19 resources - (OpenAPI v3.37.0), every kwarg drift-tested against the spec. + (OpenAPI v3.38.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. @@ -16,7 +16,7 @@ markets API. channels), backpressure strategies, and an in-memory orderbook builder. Async-only — access via `AsyncKalshiClient.ws`. - **Perps (margin) API** — standalone `PerpsClient` / `AsyncPerpsClient` + - `PerpsWebSocket` for the perpetual-futures exchange (54 REST operations, 6 WS + `PerpsWebSocket` for the perpetual-futures exchange (55 REST operations, 9 WS channels), and a `KlearClient` for the Self-Clearing-Member settlement API (26 of 27 operations, Bearer token auth). See [Perps](perps.md). - **FIX protocol** — a hand-rolled, async-first FIX engine (FIXT.1.1 / FIX50SP2) diff --git a/docs/perps.md b/docs/perps.md index 71cffd4..e4e1c2e 100644 --- a/docs/perps.md +++ b/docs/perps.md @@ -63,7 +63,7 @@ async with AsyncPerpsClient.from_env(demo=True) as perps: | `orders` | `create()`, `get()`, `list()` / `list_all()`, `cancel()`, `cancel_all()`, `decrease()`, `amend()` | | `order_groups` | `list()`, `get()`, `create()`, `delete()`, `reset()`, `trigger()`, `update_limit()` | | `portfolio` | `positions()`, `fills()` / `fills_all()`, `trades()` / `trades_all()`, cross/isolated exit triggers | -| `margin` | `balance()`, `risk()`, `notional_risk_limit()`, `fee_tiers()`, `fee_tier_rates()`, `api_limits()`, `corporate_actions()` | +| `margin` | `balance()`, `risk()`, `notional_risk_limit()`, `fee_tiers()`, `fee_tier_rates()`, `api_limits()`, `corporate_actions()`, `corporate_action_payment_history()` | | `funding` | `rate_estimate()`, `historical_rates()`, `premium_index()`, `history()` | | `transfers` | `transfer_instance()`, `create_subaccount()`, `transfer_subaccount()` | | `fcm` | `create_subtrader(subtrader_suffix=..., require_category_cap=...)`; `risk_controls` / `update_risk_controls` / `delete_risk_controls`; `update_notional_risk_limit` / `delete_notional_risk_limit`; `transfer_position(...)` | @@ -94,6 +94,7 @@ Empty cron arrays mean continuous trading except for `start` on `MarginHolidayWindow` (`until` is the exclusive end). The margin order side is `bid` / `ask` (not the prediction API's `yes` / `no`). +Order `price` is per contract, not per unit of the underlying. Orders create/cancel/decrease/amend are POSTs/DELETEs and are **never retried**. `orders.amend(..., expiration_time=)` is int64 Unix seconds: omit it to keep the current expiry, or pass `0` to clear it (good-till-canceled). @@ -106,9 +107,12 @@ stable exchange market UUID. It may be supplied with `ticker` (ticker takes precedence when both are set). Omit so the key is not sent. `orders.create(..., subaccount=)` is optional (0 = primary). Omit so the key is not sent. -`portfolio.fills()` / `portfolio.positions()` omit `subaccount` to return -rows across all subaccounts (subaccount-restricted API keys still only -see their locked subaccount). Pass `subaccount=0` for the primary. +`portfolio.fills()` omit `subaccount` to return rows across all +subaccounts (subaccount-restricted API keys still only see their locked +subaccount). Pass `subaccount=0` for the primary. `portfolio.positions()` +with `subaccount=0` returns only the primary account's cross-margin +positions; omit `subaccount` to include isolated positions held in a +market's isolated subaccount (64–4095). `portfolio.trades()` / `trades_all()` take an optional `ticker`; omit it to retrieve public trades across all margin markets. Optional `is_block_trade` filters by block / non-block: omit for all trades, @@ -160,7 +164,10 @@ the same subtrader). Each `FCMSubtraderRiskControls` row includes required Exit triggers (stop-loss / take-profit / trailing) sit on a position slot. Bracket `stop_loss_price` / `take_profit_price` must be strictly positive when -supplied; the client rejects zero and negative values. +supplied; the client rejects zero and negative values. Optional `count` is +the contracts the trigger closes when it fires; omit it to cover the whole +position. If supplied, it must be a whole number of contracts, or a multiple +of `0.01` on a market whose `fractional_trading_enabled` is true. ```python from decimal import Decimal @@ -199,7 +206,14 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) config / price data is unavailable. `MarginMarket.bid_size` / `ask_size` (`FixedPointCount | None`) are the resting size at the best bid/ask (`bid_size_fp` / `ask_size_fp` on the wire); omitted when market stats are - unavailable. `MarginMarket.funding_deadband` / `funding_cap` + unavailable. `MarginMarket.bid` is `0.0000` when there is no bid, so check + `bid_size` first. `MarginMarket.ask` is a placeholder when there is no + ask (`922337203685477.5807` or `0.0000`), so check `ask_size` first. + `MarginMarket.contract_size` is the size of one contract in the market's + underlying units; `underlying_multiplier` is how many of the underlying + asset make up one underlying unit. Prices are per contract and track the + underlying × `underlying_multiplier` × `contract_size`. + `MarginMarket.funding_deadband` / `funding_cap` (`MultiplierDecimal`) and `funding_limit_unit` (`"percentage"` / `"dollar"`) are required; they are the funding limits configured at market creation, expressed in `funding_limit_unit`. @@ -230,7 +244,9 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) null while open. - **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` + identifying which subaccount holds the position (0 for primary, 1–63 for + numbered subaccounts, 64–4095 for a market's isolated subaccount). + `subaccount_type` (`"cross"` / `"isolated"` / `"auto_rebalance"` / `"managed_isolated"` / `"swaps"`, or `None` when the key is absent) is optional on `MarginPosition`, `MarginSubaccountBalance`, `MarginRiskPosition`, and @@ -238,6 +254,8 @@ perps.portfolio.cancel_cross_exit_trigger("BTC-PERP", trig.id) 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. + `MarginPosition.unrealized_pnl` and `MarginFill.realized_pnl` are before + fees (`fees` is reported separately). - **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 @@ -299,6 +317,28 @@ for action in notices.corporate_actions: print(action.cash.cash_per_contract, action.cash.ex_date) ``` +`perps.margin.corporate_action_payment_history(*, start_date, end_date)` +(`GET /margin/corporate_action_payment_history`) returns cash received or +paid for corporate actions (cash dividends, special dividends, and cash +spin-offs) over an inclusive UTC date range. Auth required. `start_date` +and `end_date` are required YYYY-MM-DD (`datetime.date` or `str`). Optional +`ticker` filters to one market; omit for all markets. Optional +`subaccount`; omit for all subaccounts. Stock split adjustments are not +included. `payment_amount` is gross dollars before withholding (positive = +received, negative = paid). + +```python +from datetime import date + +history = perps.margin.corporate_action_payment_history( + start_date=date(2026, 10, 1), + end_date=date(2026, 10, 31), + ticker="AAPL-PERP", +) +for row in history.payment_history: + print(row.corporate_action_id, row.payment_amount, row.withholding_amount) +``` + ## WebSocket streaming ```python @@ -312,12 +352,13 @@ async with ws.connect() as session: print(msg.msg.funding_rate.rate, msg.msg.funding_rate.next_funding_time_ms) ``` -Eight data channels — `orderbook_delta` (snapshot + delta, sequenced), `ticker`, +Nine data channels — `orderbook_delta` (snapshot + delta, sequenced), `ticker`, `trade`, `fill`, `user_orders`, `order_group_updates`, `corporate_actions`, -`market_lifecycle_v2`. The connection, sequence-gap detection, reconnect, and -backpressure machinery are reused from the event-contract WS stack (see -[WebSocket](websockets.md)); the perps orderbook is `bid` / `ask`. The -prediction-only channels (`market_positions`, `multivariate*`, `communications`, +`market_lifecycle_v2`, `exchange_status`. The connection, sequence-gap +detection, reconnect, and backpressure machinery are reused from the +event-contract WS stack (see [WebSocket](websockets.md)); the perps +orderbook is `bid` / `ask`. The prediction-only channels +(`market_positions`, `multivariate*`, `communications`, `cfbenchmarks_value`) have no perps counterpart. `corporate_actions` streams applied split / final-settlement / ticker-change notices (cash actions are REST-only); subscribe with `session.subscribe(channel="corporate_actions")`. @@ -327,6 +368,11 @@ activation and deactivation of every margin market (`event_type` is `activated` or `deactivated`). `is_deactivated` is true when trading is paused because the market is halted or outside its trading hours. Ticker filters are not supported on that channel. +`subscribe_exchange_status()` yields `MarginExchangeStatusMessage` when +trading is paused or resumed exchange-wide, or when the exchange status +changes. Trading messages carry `trading_active`; exchange status messages +carry `exchange_active`. Trading is open exchange-wide only while both are +true. Per-market halts ride `market_lifecycle_v2`. ## FCM position transfer diff --git a/docs/resources/portfolio.md b/docs/resources/portfolio.md index 32a6bdc..1508e8e 100644 --- a/docs/resources/portfolio.md +++ b/docs/resources/portfolio.md @@ -8,7 +8,7 @@ Auth required throughout. | Method | Endpoint | |---|---| | `balance(*, subaccount=None, exchange_index=None)` | `GET /portfolio/balance` | -| `positions(*, ..., exchange_index=None)` | `GET /portfolio/positions` | +| `positions(*, ..., exchange_index=None, sort_by=None)` | `GET /portfolio/positions` | | `settlements(...)` / `settlements_all(...)` | `GET /portfolio/settlements` | | `fills(...)` / `fills_all(..., exchange_index=None)` | `GET /portfolio/fills` | | `total_resting_order_value()` | `GET /portfolio/summary/total_resting_order_value` (FCM only) | @@ -76,6 +76,7 @@ resp = client.portfolio.positions( settlement_status="unsettled", # "unsettled" (server default) | "settled" | "all" ticker="KXPRES-24-DJT", event_ticker="KXPRES-24", + sort_by="event_ticker", # order event groups by ticker; omit for default ) for mp in resp.market_positions: print(mp.ticker, mp.position, mp.realized_pnl) @@ -116,6 +117,10 @@ contracts, including closed markets awaiting determination) or `"total_traded"` (any contracts traded, including fully exited positions). Omit it for no count filter. +`sort_by="event_ticker"` orders event groups by ticker ascending. Omit it +for the default ordering. Keep filters and `sort_by` unchanged while +paginating with `cursor`. + `settlement_status` (`SettlementStatusLiteral`: `"unsettled"`, `"settled"`, `"all"`) filters settlement state, not trading status. Unsettled (the server default) includes closed markets awaiting determination or @@ -305,7 +310,8 @@ are unaffected; constructors/fixtures must pass it. wire-format aliases — on the wire you see `total_traded_dollars`, `market_exposure_dollars`, `realized_pnl_dollars`, `fees_paid_dollars`, `position_fp`. The SDK normalizes to short names returning `Decimal`. -`realized_pnl` is signed. Optional `netting_enabled` (`bool | None`) reports +`realized_pnl` is signed, before fees (`fees_paid` is reported separately). +Optional `netting_enabled` (`bool | None`) reports whether netting applies to the position's event (`None` when the server omits the key). diff --git a/kalshi/__init__.py b/kalshi/__init__.py index d91e62f..0a4b5a0 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -553,4 +553,4 @@ "Withdrawal", ] -__version__ = "22.16.0" +__version__ = "22.17.0" diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index 82afdea..8589f00 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -1059,6 +1059,14 @@ class ContractEntry: sdk_model="kalshi.perps.models.margin_account.MarginCorporateAction", spec_schema="MarginCorporateAction", ), + ContractEntry( + sdk_model="kalshi.perps.models.margin_account.GetMarginCorporateActionPaymentHistoryResponse", + spec_schema="GetMarginCorporateActionPaymentHistoryResponse", + ), + ContractEntry( + sdk_model="kalshi.perps.models.margin_account.MarginCorporateActionPaymentHistoryEntry", + spec_schema="MarginCorporateActionPaymentHistoryEntry", + ), ContractEntry( sdk_model="kalshi.perps.models.margin_account.MarginCorporateActionCashTerms", spec_schema="MarginCorporateActionCashTerms", diff --git a/kalshi/models/portfolio.py b/kalshi/models/portfolio.py index 00fae68..c50961d 100644 --- a/kalshi/models/portfolio.py +++ b/kalshi/models/portfolio.py @@ -93,6 +93,7 @@ class MarketPosition(BaseModel): market_exposure: DollarDecimal | None = Field( validation_alias=AliasChoices("market_exposure_dollars", "market_exposure"), ) + # Locked-in PnL in dollars, before fees. Fees are in ``fees_paid``. realized_pnl: DollarDecimal | None = Field( validation_alias=AliasChoices("realized_pnl_dollars", "realized_pnl"), ) @@ -125,6 +126,7 @@ class EventPosition(BaseModel): event_exposure: DollarDecimal | None = Field( validation_alias=AliasChoices("event_exposure_dollars", "event_exposure"), ) + # Locked-in PnL in dollars, before fees. Fees are in ``fees_paid``. realized_pnl: DollarDecimal | None = Field( validation_alias=AliasChoices("realized_pnl_dollars", "realized_pnl"), ) diff --git a/kalshi/perps/__init__.py b/kalshi/perps/__init__.py index 1159cbe..c396f47 100644 --- a/kalshi/perps/__init__.py +++ b/kalshi/perps/__init__.py @@ -102,6 +102,7 @@ from kalshi.perps.models.margin_account import ( FeeScheduleLiteral, GetMarginBalanceResponse, + GetMarginCorporateActionPaymentHistoryResponse, GetMarginCorporateActionsResponse, GetMarginFeeTierRatesResponse, GetMarginFeeTiersResponse, @@ -109,6 +110,8 @@ MarginCorporateAction, MarginCorporateActionCashTerms, MarginCorporateActionFinalSettlementTerms, + MarginCorporateActionPaymentHistoryEntry, + MarginCorporateActionPaymentHistoryTypeLiteral, MarginCorporateActionSplitTerms, MarginCorporateActionStatusLiteral, MarginCorporateActionTickerChangeTerms, @@ -221,6 +224,8 @@ ) from kalshi.perps.ws.models import ( FundingRate, + MarginExchangeStatusMessage, + MarginExchangeStatusPayload, MarginFillMessage, MarginFillPayload, MarginMarketLifecycleEventType, @@ -307,6 +312,7 @@ "GetFCMSubtraderRiskControlsResponse", "GetGuarantyFundBalanceResponse", "GetMarginBalanceResponse", + "GetMarginCorporateActionPaymentHistoryResponse", "GetMarginCorporateActionsResponse", "GetMarginFeeTierRatesResponse", "GetMarginFeeTiersResponse", @@ -342,11 +348,15 @@ "MarginCorporateAction", "MarginCorporateActionCashTerms", "MarginCorporateActionFinalSettlementTerms", + "MarginCorporateActionPaymentHistoryEntry", + "MarginCorporateActionPaymentHistoryTypeLiteral", "MarginCorporateActionSplitTerms", "MarginCorporateActionStatusLiteral", "MarginCorporateActionTickerChangeTerms", "MarginCorporateActionTypeLiteral", "MarginEnabledResponse", + "MarginExchangeStatusMessage", + "MarginExchangeStatusPayload", "MarginFeeTierRate", "MarginFill", "MarginFillMessage", diff --git a/kalshi/perps/models/__init__.py b/kalshi/perps/models/__init__.py index 886b6a0..afe74ad 100644 --- a/kalshi/perps/models/__init__.py +++ b/kalshi/perps/models/__init__.py @@ -48,6 +48,7 @@ from kalshi.perps.models.margin_account import ( FeeScheduleLiteral, GetMarginBalanceResponse, + GetMarginCorporateActionPaymentHistoryResponse, GetMarginCorporateActionsResponse, GetMarginFeeTierRatesResponse, GetMarginFeeTiersResponse, @@ -55,6 +56,8 @@ MarginCorporateAction, MarginCorporateActionCashTerms, MarginCorporateActionFinalSettlementTerms, + MarginCorporateActionPaymentHistoryEntry, + MarginCorporateActionPaymentHistoryTypeLiteral, MarginCorporateActionSplitTerms, MarginCorporateActionStatusLiteral, MarginCorporateActionTickerChangeTerms, @@ -164,6 +167,7 @@ "GetExitTriggersResponse", "GetFCMSubtraderRiskControlsResponse", "GetMarginBalanceResponse", + "GetMarginCorporateActionPaymentHistoryResponse", "GetMarginCorporateActionsResponse", "GetMarginFeeTierRatesResponse", "GetMarginFeeTiersResponse", @@ -184,6 +188,8 @@ "MarginCorporateAction", "MarginCorporateActionCashTerms", "MarginCorporateActionFinalSettlementTerms", + "MarginCorporateActionPaymentHistoryEntry", + "MarginCorporateActionPaymentHistoryTypeLiteral", "MarginCorporateActionSplitTerms", "MarginCorporateActionStatusLiteral", "MarginCorporateActionTickerChangeTerms", diff --git a/kalshi/perps/models/common.py b/kalshi/perps/models/common.py index 110e0c9..3d795ee 100644 --- a/kalshi/perps/models/common.py +++ b/kalshi/perps/models/common.py @@ -89,11 +89,16 @@ class OrderSource(StrEnum): class MarginMarketStatus(StrEnum): - """Spec ``MarginMarketStatus`` — the status of a margin market.""" + """Spec ``MarginMarketStatus`` — the status of a margin market. + + The spec renamed ``closed`` to ``finalized``. ``CLOSED`` is kept for + compatibility. + """ INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" + FINALIZED = "finalized" class ExchangeInstance(StrEnum): @@ -108,12 +113,13 @@ class ExchangeInstance(StrEnum): ] """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), -``managed_isolated`` for a managed isolated position (subaccount number is -the same as the market's isolated subaccount number), and ``swaps`` for a -cross-margined swaps wallet (subaccount number is its swaps code). +``cross`` for the primary account and numbered subaccounts (0-63), +``isolated`` for a market's isolated subaccount (64-4095), +``auto_rebalance`` for an auto-rebalanced 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), and ``swaps`` for a cross-margined swaps wallet +(subaccount number is its swaps code). """ diff --git a/kalshi/perps/models/margin_account.py b/kalshi/perps/models/margin_account.py index e12f2cd..781ec47 100644 --- a/kalshi/perps/models/margin_account.py +++ b/kalshi/perps/models/margin_account.py @@ -1,7 +1,9 @@ """Perps margin-account models — balance, risk, notional risk limit, fee tiers. Response models for the read-only direct-margin account endpoints (#394) plus -``GetMarginCorporateActions`` (#550). All are pure response models — every one +``GetMarginCorporateActions`` (#550) and +``GetMarginCorporateActionPaymentHistory`` (#590). All are pure response +models — every one carries ``model_config = {"extra": "allow"}`` so additive spec fields don't break parsing, and none have request bodies (the endpoints are GETs with at most query flags). @@ -257,3 +259,47 @@ class GetMarginCorporateActionsResponse(BaseModel): model_config = ConfigDict(extra="allow") corporate_actions: NullableList[MarginCorporateAction] + + +MarginCorporateActionPaymentHistoryTypeLiteral = Literal[ + "cash_dividend", + "special_dividend", + "spin_off", +] +"""Spec ``MarginCorporateActionPaymentHistoryEntry.type`` — cash payment kinds.""" + + +class MarginCorporateActionPaymentHistoryEntry(BaseModel): + """Spec ``MarginCorporateActionPaymentHistoryEntry`` — one cash payment. + + Wire field names already match the short Python names (no ``_dollars`` + / ``_fp`` suffix), so no ``validation_alias`` is used. ``payment_amount`` + is gross dollars before withholding (positive = received, negative = + paid). ``quantity`` is the signed position the payment was computed on. + """ + + model_config = ConfigDict(extra="allow") + + corporate_action_id: str + type: MarginCorporateActionPaymentHistoryTypeLiteral + market_ticker: str + payment_time: AwareDatetime + payment_amount: DollarDecimal + quantity: FixedPointCount + # Spec-required and nullable. + subaccount_number: int | None + subaccount_type: SubaccountTypeLiteral + withholding_amount: DollarDecimal + + +class GetMarginCorporateActionPaymentHistoryResponse(BaseModel): + """Spec ``GetMarginCorporateActionPaymentHistoryResponse``. + + ``payment_history`` is spec-required and uses + :data:`~kalshi.types.NullableList`: a missing key raises + ``ValidationError``, while a ``null`` array coerces to ``[]``. + """ + + model_config = ConfigDict(extra="allow") + + payment_history: NullableList[MarginCorporateActionPaymentHistoryEntry] diff --git a/kalshi/perps/models/markets.py b/kalshi/perps/models/markets.py index 81c9d29..6aa543e 100644 --- a/kalshi/perps/models/markets.py +++ b/kalshi/perps/models/markets.py @@ -22,12 +22,15 @@ from kalshi.types import DollarDecimal, FixedPointCount, MultiplierDecimal, NullableList -MarginMarketStatusLiteral = Literal["inactive", "active", "closed"] +MarginMarketStatusLiteral = Literal["inactive", "active", "closed", "finalized"] """Status filter for GET /margin/markets and ``MarginMarket.status``. Spec schema ``MarginMarketStatus`` (``type: string``). Defined here as a ``Literal`` for the query-param signature; the ``StrEnum`` form lives in :mod:`kalshi.perps.models.common` as :class:`~kalshi.perps.models.common.MarginMarketStatus`. + +The spec renamed ``closed`` to ``finalized``. ``closed`` is kept for +compatibility. """ @@ -80,8 +83,13 @@ class MarginMarket(BaseModel): status: MarginMarketStatusLiteral # Stable market UUID; remains unchanged if the ticker is renamed. market_id: str | None = None + # Size of one contract in the market's underlying units (6 decimal places). + # Prices are per contract, and track the underlying asset's price x + # ``underlying_multiplier`` x ``contract_size``. contract_size: DollarDecimal - # Spec 3.30.0: underlying units per contract-size unit (required string). + # How many of the underlying asset make up one underlying unit + # (6-decimal fixed-point string). e.g. ``1000.000000`` when the unit is + # a thousand of the asset. underlying_multiplier: str tick_size: DollarDecimal fractional_trading_enabled: bool @@ -128,11 +136,14 @@ class MarginMarket(BaseModel): long_leverage_estimates: dict[str, MultiplierDecimal] | None = None short_leverage_estimates: dict[str, MultiplierDecimal] | None = None price: DollarDecimal | None = None + # ``0.0000`` when there is no bid; check ``bid_size`` before using it. bid: DollarDecimal | None = None bid_size: FixedPointCount | None = Field( default=None, validation_alias=AliasChoices("bid_size_fp", "bid_size"), ) + # Placeholder when there is no ask (``922337203685477.5807`` or + # ``0.0000``); check ``ask_size`` before using it. ask: DollarDecimal | None = None ask_size: FixedPointCount | None = Field( default=None, diff --git a/kalshi/perps/models/orders.py b/kalshi/perps/models/orders.py index 2f92f93..b7ae37f 100644 --- a/kalshi/perps/models/orders.py +++ b/kalshi/perps/models/orders.py @@ -81,6 +81,7 @@ class CreateMarginOrderRequest(BaseModel): client_order_id: str side: BookSideLiteral count: FixedPointCount = Field(gt=0) + # Price per contract, not per unit of the underlying. price: OrderPrice time_in_force: TimeInForceLiteral self_trade_prevention_type: SelfTradePreventionTypeLiteral diff --git a/kalshi/perps/models/portfolio.py b/kalshi/perps/models/portfolio.py index a27fb91..c404606 100644 --- a/kalshi/perps/models/portfolio.py +++ b/kalshi/perps/models/portfolio.py @@ -52,6 +52,8 @@ class MarginPosition(BaseModel): friendlier :attr:`return_on_equity`. """ + # 0 for primary, 1-63 for numbered subaccounts, 64-4095 for a market's + # isolated subaccount. subaccount: int # Spec 3.35.0 marks subaccount_type required. Kept optional (None when # the key is absent) so fixtures and payloads from before the field @@ -60,6 +62,7 @@ class MarginPosition(BaseModel): market_ticker: str position: FixedPointCount entry_price: DollarDecimal + # Mark-to-market unrealized PnL, before fees. Fees are in ``fees``. unrealized_pnl: DollarDecimal # Spec 3.23.0 relaxed margin_used from required to optional (still a property). # Optional/defensive so a response omitting it does not hard-fail parsing. @@ -100,6 +103,7 @@ class MarginFill(BaseModel): price: DollarDecimal entry_price: DollarDecimal fees: DollarDecimal + # Incremental realized PnL contributed by this fill, before fees. realized_pnl: DollarDecimal order_source: OrderSourceLiteral | None = None @@ -182,6 +186,9 @@ class ExitTrigger(BaseModel): ticker: str kind: ExitTriggerKindLiteral status: ExitTriggerStatusLiteral + # Contracts this trigger closes when it fires. ``0`` means the whole + # position, except on an order-anchored trigger whose order has not + # filled, which covers nothing. count: FixedPointCount filled_count: FixedPointCount created_time: AwareDatetime @@ -212,6 +219,9 @@ class GetExitTriggersResponse(BaseModel): class SetCrossExitTriggerRequest(BaseModel): """Body for PUT /margin/cross/positions/{ticker}/exit_trigger.""" + # Omit to cover the whole position. If supplied, a whole number of + # contracts, or a multiple of ``0.01`` when the market has + # ``fractional_trading_enabled``. count: FixedPointCount | None = None anchor_order_id: str | None = None client_trigger_id: str | None = None diff --git a/kalshi/perps/resources/margin_account.py b/kalshi/perps/resources/margin_account.py index 36b3c8c..ccf0b20 100644 --- a/kalshi/perps/resources/margin_account.py +++ b/kalshi/perps/resources/margin_account.py @@ -1,13 +1,13 @@ """Perps margin-account resource — balance, risk, notional risk limit, fee tiers, API limits. Read-only GET endpoints. ``balance`` / ``risk`` / ``notional_risk_limit`` / -``fee_tiers`` / ``fee_tier_rates`` / ``api_limits`` carry a spec ``security`` -block, so each of those methods calls ``_require_auth()`` first — an -unauthenticated caller gets ``AuthRequiredError`` client-side instead of a -server 401. ``corporate_actions`` is public market data (no spec ``security`` -block) and does not require auth. None are paginated (no response carries a -cursor), so there are no ``list_all()`` iterators. All retry on 429/502/503/504 -(GET). +``fee_tiers`` / ``fee_tier_rates`` / ``api_limits`` / +``corporate_action_payment_history`` carry a spec ``security`` block, so each +of those methods calls ``_require_auth()`` first — an unauthenticated caller +gets ``AuthRequiredError`` client-side instead of a server 401. +``corporate_actions`` is public market data (no spec ``security`` block) and +does not require auth. None are paginated (no response carries a cursor), so +there are no ``list_all()`` iterators. All retry on 429/502/503/504 (GET). ``api_limits`` (``GET /account/limits/perps``) returns the Perps API tier limits in the same shape as the prediction API's :class:`~kalshi.models.account.AccountApiLimits`, @@ -16,9 +16,12 @@ from __future__ import annotations +from datetime import date, datetime + from kalshi.models.account import AccountApiLimits from kalshi.perps.models.margin_account import ( GetMarginBalanceResponse, + GetMarginCorporateActionPaymentHistoryResponse, GetMarginCorporateActionsResponse, GetMarginFeeTierRatesResponse, GetMarginFeeTiersResponse, @@ -28,8 +31,22 @@ from kalshi.resources._base import AsyncResource, SyncResource, _params +def _iso_date(value: date | str) -> str: + """Serialize a required date query param as ``YYYY-MM-DD``. + + Accepts :class:`datetime.date` or an already-formatted string. A + :class:`datetime.datetime` is reduced to its calendar date first because + ``datetime`` is a ``date`` subclass whose ``isoformat()`` includes time. + """ + if isinstance(value, datetime): + return value.date().isoformat() + if isinstance(value, date): + return value.isoformat() + return value + + class MarginAccountResource(SyncResource): - """Sync perps margin-account API (balance / risk / fee tiers / corporate_actions).""" + """Sync perps margin-account API (balance / risk / fee tiers / corporate actions).""" def balance( self, @@ -99,9 +116,40 @@ def corporate_actions( ) return GetMarginCorporateActionsResponse.model_validate(data) + def corporate_action_payment_history( + self, + *, + start_date: date | str, + end_date: date | str, + ticker: str | None = None, + subaccount: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> GetMarginCorporateActionPaymentHistoryResponse: + """Cash received or paid for corporate actions in a UTC date range. + + ``GET /margin/corporate_action_payment_history``. Auth required. + ``start_date`` and ``end_date`` are inclusive YYYY-MM-DD (accept + :class:`datetime.date` or ``str``). Optional ``ticker`` filters to + one market; omit for all markets. Optional ``subaccount``; omit for + all subaccounts. Stock split adjustments are not included. + """ + self._require_auth() + params = _params( + start_date=_iso_date(start_date), + end_date=_iso_date(end_date), + ticker=ticker, + subaccount=subaccount, + ) + data = self._get( + "/margin/corporate_action_payment_history", + params=params, + extra_headers=extra_headers, + ) + return GetMarginCorporateActionPaymentHistoryResponse.model_validate(data) + class AsyncMarginAccountResource(AsyncResource): - """Async perps margin-account API (balance / risk / fee tiers / corporate_actions).""" + """Async perps margin-account API (balance / risk / fee tiers / corporate actions).""" async def balance( self, @@ -166,3 +214,27 @@ async def corporate_actions( "/margin/corporate_actions", params=params, extra_headers=extra_headers ) return GetMarginCorporateActionsResponse.model_validate(data) + + async def corporate_action_payment_history( + self, + *, + start_date: date | str, + end_date: date | str, + ticker: str | None = None, + subaccount: int | None = None, + extra_headers: dict[str, str] | None = None, + ) -> GetMarginCorporateActionPaymentHistoryResponse: + """Async :meth:`MarginAccountResource.corporate_action_payment_history`.""" + self._require_auth() + params = _params( + start_date=_iso_date(start_date), + end_date=_iso_date(end_date), + ticker=ticker, + subaccount=subaccount, + ) + data = await self._get( + "/margin/corporate_action_payment_history", + params=params, + extra_headers=extra_headers, + ) + return GetMarginCorporateActionPaymentHistoryResponse.model_validate(data) diff --git a/kalshi/perps/resources/portfolio.py b/kalshi/perps/resources/portfolio.py index 9cc22ab..2355409 100644 --- a/kalshi/perps/resources/portfolio.py +++ b/kalshi/perps/resources/portfolio.py @@ -4,7 +4,8 @@ - ``positions`` — ``GET /margin/positions``: auth required, single non-paginated array (no ``_all()``). Omit ``subaccount`` to return - positions across all subaccounts. + positions across all subaccounts, including isolated. ``subaccount=0`` + returns only the primary account's cross-margin positions. - ``fills`` / ``fills_all`` — ``GET /margin/fills``: auth required, cursor-paginated (the authenticated user's margin fills). Omit ``subaccount`` to return fills across all subaccounts. diff --git a/kalshi/perps/ws/client.py b/kalshi/perps/ws/client.py index 65b87dc..789ad16 100644 --- a/kalshi/perps/ws/client.py +++ b/kalshi/perps/ws/client.py @@ -43,6 +43,7 @@ from kalshi.perps.ws.connection import ConnectionState, PerpsConnectionManager from kalshi.perps.ws.dispatch import PerpsMessageDispatcher from kalshi.perps.ws.models.control import PerpsErrorResponse, SubscriptionEntry +from kalshi.perps.ws.models.exchange_status import MarginExchangeStatusMessage from kalshi.perps.ws.models.fill import MarginFillMessage from kalshi.perps.ws.models.market_lifecycle import MarginMarketLifecycleV2Message from kalshi.perps.ws.models.order_group import OrderGroupUpdatesMessage @@ -600,7 +601,8 @@ async def subscribe( # ``corporate_actions`` is on :class:`PerpsChannel` and is subscribed # via the generic :meth:`subscribe`. ``market_lifecycle_v2`` is a perps # channel (activation / deactivation of every margin market; ticker - # filters are not supported). + # filters are not supported). ``exchange_status`` is exchange-wide + # pause/resume (no ticker filters). # # ``builtins.list[str]`` is used for ``tickers`` params: the surrounding # API has a ``list_subscriptions`` method, so the ``list`` builtin is @@ -737,6 +739,24 @@ async def subscribe_market_lifecycle( overflow=OverflowStrategy.DROP_OLDEST, maxsize=maxsize, ) + async def subscribe_exchange_status( + self, + *, + maxsize: int = 1000, + ) -> AsyncIterator[MarginExchangeStatusMessage]: + """Subscribe to ``exchange_status`` (exchange-wide pause/resume). + + Trading messages carry ``trading_active``. Exchange status messages + carry ``exchange_active``. Trading is open exchange-wide only while + both are true. Per-market halts ride ``market_lifecycle_v2``. Ticker + filters are not supported. Not sequence-gap tracked, so overflow is + ``DROP_OLDEST``. + """ + return await self._do_subscribe( + "exchange_status", + overflow=OverflowStrategy.DROP_OLDEST, maxsize=maxsize, + ) + async def unsubscribe(self, client_id: int) -> None: """Tear down a subscription and its associated local state. diff --git a/kalshi/perps/ws/dispatch.py b/kalshi/perps/ws/dispatch.py index 87d5a2d..d161789 100644 --- a/kalshi/perps/ws/dispatch.py +++ b/kalshi/perps/ws/dispatch.py @@ -36,6 +36,7 @@ UnsubscribeCommand, UnsubscribeParams, ) +from kalshi.perps.ws.models.exchange_status import MarginExchangeStatusMessage from kalshi.perps.ws.models.fill import MarginFillMessage from kalshi.perps.ws.models.market_lifecycle import MarginMarketLifecycleV2Message from kalshi.perps.ws.models.order_group import OrderGroupUpdatesMessage @@ -65,6 +66,7 @@ "user_order": MarginUserOrderMessage, "order_group_updates": OrderGroupUpdatesMessage, "market_lifecycle_v2": MarginMarketLifecycleV2Message, + "exchange_status": MarginExchangeStatusMessage, } # Control message types (not routed to subscription queues). diff --git a/kalshi/perps/ws/models/__init__.py b/kalshi/perps/ws/models/__init__.py index 8c89e39..02c8666 100644 --- a/kalshi/perps/ws/models/__init__.py +++ b/kalshi/perps/ws/models/__init__.py @@ -34,6 +34,10 @@ UpdateSubscriptionCommand, UpdateSubscriptionParams, ) +from kalshi.perps.ws.models.exchange_status import ( + MarginExchangeStatusMessage, + MarginExchangeStatusPayload, +) from kalshi.perps.ws.models.fill import MarginFillMessage, MarginFillPayload from kalshi.perps.ws.models.market_lifecycle import ( MarginMarketLifecycleV2Message, @@ -65,6 +69,8 @@ "FundingRate", "ListSubscriptionsCommand", "ListSubscriptionsResponse", + "MarginExchangeStatusMessage", + "MarginExchangeStatusPayload", "MarginFillMessage", "MarginFillPayload", "MarginMarketLifecycleEventType", diff --git a/kalshi/perps/ws/models/control.py b/kalshi/perps/ws/models/control.py index 9897c0e..b863a07 100644 --- a/kalshi/perps/ws/models/control.py +++ b/kalshi/perps/ws/models/control.py @@ -53,6 +53,7 @@ class PerpsChannel(StrEnum): ORDER_GROUP_UPDATES = "order_group_updates" CORPORATE_ACTIONS = "corporate_actions" MARKET_LIFECYCLE_V2 = "market_lifecycle_v2" + EXCHANGE_STATUS = "exchange_status" class UpdateSubscriptionAction(StrEnum): diff --git a/kalshi/perps/ws/models/exchange_status.py b/kalshi/perps/ws/models/exchange_status.py new file mode 100644 index 0000000..cf23b86 --- /dev/null +++ b/kalshi/perps/ws/models/exchange_status.py @@ -0,0 +1,38 @@ +"""Margin exchange-status channel message models. + +``exchange_status`` is sent when trading is paused or resumed exchange-wide, +or when the exchange status changes. Trading messages carry ``trading_active``; +exchange status messages carry ``exchange_active``. Trading is open +exchange-wide only while both flags are true. Per-market halts ride +``market_lifecycle_v2``. +""" + +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel + + +class MarginExchangeStatusPayload(BaseModel): + """Payload for ``exchange_status`` (``marginExchangeStatusPayload.msg``). + + ``ts_ms`` is required. ``exchange_active`` and ``trading_active`` are + optional; a given message typically carries one of them. + """ + + exchange_active: bool | None = None + trading_active: bool | None = None + ts_ms: int + model_config = {"extra": "allow", "populate_by_name": True} + + +class MarginExchangeStatusMessage(BaseModel): + """Exchange-wide trading or exchange status change. ``seq`` is required.""" + + type: Literal["exchange_status"] = "exchange_status" + sid: int + seq: int + msg: MarginExchangeStatusPayload + sending_ts_ms: int | None = None + model_config = {"extra": "allow", "populate_by_name": True} diff --git a/kalshi/resources/portfolio.py b/kalshi/resources/portfolio.py index 5f0d6d4..9622684 100644 --- a/kalshi/resources/portfolio.py +++ b/kalshi/resources/portfolio.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import AsyncIterator, Iterator -from typing import Any +from typing import Any, Literal from kalshi.errors import KalshiError from kalshi.models.common import Page @@ -52,6 +52,7 @@ def _positions_params( event_ticker: str | None, subaccount: int | None, exchange_index: int | None, + sort_by: Literal["event_ticker"] | None, ) -> dict[str, Any]: limit = _validate_limit(limit, hi=1000) return _params( @@ -63,6 +64,7 @@ def _positions_params( event_ticker=event_ticker, subaccount=subaccount, exchange_index=exchange_index, + sort_by=sort_by, ) @@ -115,6 +117,7 @@ def positions( event_ticker: str | None = None, subaccount: int | None = None, exchange_index: int | None = None, + sort_by: Literal["event_ticker"] | None = None, extra_headers: dict[str, str] | None = None, ) -> PositionsResponse: self._require_auth() @@ -127,6 +130,7 @@ def positions( event_ticker=event_ticker, subaccount=subaccount, exchange_index=exchange_index, + sort_by=sort_by, ) data = self._get("/portfolio/positions", params=params, extra_headers=extra_headers) return PositionsResponse.model_validate(data) @@ -141,6 +145,7 @@ def positions_all( event_ticker: str | None = None, subaccount: int | None = None, exchange_index: int | None = None, + sort_by: Literal["event_ticker"] | None = None, max_pages: int | None = None, extra_headers: dict[str, str] | None = None, ) -> Iterator[MarketPosition]: @@ -164,6 +169,7 @@ def positions_all( event_ticker=event_ticker, subaccount=subaccount, exchange_index=exchange_index, + sort_by=sort_by, ) return self._list_all( "/portfolio/positions", @@ -644,6 +650,7 @@ async def positions( event_ticker: str | None = None, subaccount: int | None = None, exchange_index: int | None = None, + sort_by: Literal["event_ticker"] | None = None, extra_headers: dict[str, str] | None = None, ) -> PositionsResponse: self._require_auth() @@ -656,6 +663,7 @@ async def positions( event_ticker=event_ticker, subaccount=subaccount, exchange_index=exchange_index, + sort_by=sort_by, ) data = await self._get("/portfolio/positions", params=params, extra_headers=extra_headers) return PositionsResponse.model_validate(data) @@ -670,6 +678,7 @@ def positions_all( event_ticker: str | None = None, subaccount: int | None = None, exchange_index: int | None = None, + sort_by: Literal["event_ticker"] | None = None, max_pages: int | None = None, extra_headers: dict[str, str] | None = None, ) -> AsyncIterator[MarketPosition]: @@ -693,6 +702,7 @@ def positions_all( event_ticker=event_ticker, subaccount=subaccount, exchange_index=exchange_index, + sort_by=sort_by, ) return self._list_all( "/portfolio/positions", diff --git a/pyproject.toml b/pyproject.toml index 337cfed..e795b8d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "22.16.0" +version = "22.17.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 b991c2e..78f6097 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -1871,6 +1871,11 @@ class Exclusion: http_method="GET", path_template="/margin/corporate_actions", ), + MethodEndpointEntry( + sdk_method="kalshi.perps.resources.margin_account.MarginAccountResource.corporate_action_payment_history", + http_method="GET", + path_template="/margin/corporate_action_payment_history", + ), # ── perps funding (#395) ─────────────────────────────────────────── MethodEndpointEntry( sdk_method="kalshi.perps.resources.funding.FundingResource.rate_estimate", diff --git a/tests/perps/test_margin_account.py b/tests/perps/test_margin_account.py index ba5a647..5f2ac40 100644 --- a/tests/perps/test_margin_account.py +++ b/tests/perps/test_margin_account.py @@ -18,7 +18,12 @@ import respx from pydantic import ValidationError -from kalshi.errors import AuthRequiredError, KalshiServerError, KalshiValidationError +from kalshi.errors import ( + AuthRequiredError, + KalshiAuthError, + KalshiServerError, + KalshiValidationError, +) from kalshi.perps import AsyncPerpsClient, PerpsClient, PerpsConfig from kalshi.perps.models.margin_account import MarginRiskPosition, MarginSubaccountBalance @@ -871,6 +876,207 @@ async def test_async_error_500(self, async_perps_client: AsyncPerpsClient) -> No await async_perps_client.close() +# ── corporate_action_payment_history ────────────────────────────────────────── + + +def _payment_entry(**overrides: object) -> dict[str, object]: + entry: dict[str, object] = { + "corporate_action_id": "ca-pay-1", + "type": "cash_dividend", + "market_ticker": "AAPL-PERP", + "payment_time": "2026-10-15T00:00:00Z", + "payment_amount": "12.5000", + "quantity": "10.00", + "subaccount_number": 0, + "subaccount_type": "cross", + "withholding_amount": "1.2500", + } + entry.update(overrides) + return entry + + +class TestCorporateActionPaymentHistory: + @respx.mock + def test_happy_path_serializes_dates_and_optionals( + self, perps_client: PerpsClient + ) -> None: + route = respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response( + 200, json={"payment_history": [_payment_entry()]} + ) + ) + resp = perps_client.margin.corporate_action_payment_history( + start_date=date(2026, 10, 1), + end_date=date(2026, 10, 31), + ticker="AAPL-PERP", + subaccount=2, + ) + assert route.called + params = route.calls.last.request.url.params + assert params["start_date"] == "2026-10-01" + assert params["end_date"] == "2026-10-31" + assert params["ticker"] == "AAPL-PERP" + assert params["subaccount"] == "2" + assert len(resp.payment_history) == 1 + entry = resp.payment_history[0] + assert entry.corporate_action_id == "ca-pay-1" + assert entry.type == "cash_dividend" + assert entry.market_ticker == "AAPL-PERP" + assert isinstance(entry.payment_time, datetime) + assert entry.payment_time.tzinfo is not None + assert entry.payment_amount == Decimal("12.5000") + assert isinstance(entry.payment_amount, Decimal) + assert entry.quantity == Decimal("10.00") + assert isinstance(entry.quantity, Decimal) + assert entry.subaccount_number == 0 + assert entry.subaccount_type == "cross" + assert entry.withholding_amount == Decimal("1.2500") + + @respx.mock + def test_str_dates_and_optional_params_omitted( + self, perps_client: PerpsClient + ) -> None: + route = respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response(200, json={"payment_history": []}) + ) + perps_client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ) + params = route.calls.last.request.url.params + assert params["start_date"] == "2026-01-01" + assert params["end_date"] == "2026-01-31" + assert "ticker" not in params + assert "subaccount" not in params + + @respx.mock + def test_null_payment_history_coerced_to_empty( + self, perps_client: PerpsClient + ) -> None: + respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response(200, json={"payment_history": None}) + ) + resp = perps_client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ) + assert resp.payment_history == [] + + @respx.mock + def test_negative_payment_amount_and_null_subaccount( + self, perps_client: PerpsClient + ) -> None: + respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response( + 200, + json={ + "payment_history": [ + _payment_entry( + type="spin_off", + payment_amount="-3.2500", + quantity="-5.00", + subaccount_number=None, + subaccount_type="isolated", + withholding_amount="0.0000", + ) + ] + }, + ) + ) + entry = perps_client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ).payment_history[0] + assert entry.type == "spin_off" + assert entry.payment_amount == Decimal("-3.2500") + assert entry.quantity == Decimal("-5.00") + assert entry.subaccount_number is None + assert entry.subaccount_type == "isolated" + + def test_start_and_end_date_required(self, perps_client: PerpsClient) -> None: + with pytest.raises(TypeError): + perps_client.margin.corporate_action_payment_history() # type: ignore[call-arg] + with pytest.raises(TypeError): + perps_client.margin.corporate_action_payment_history( # type: ignore[call-arg] + start_date="2026-01-01" + ) + + @respx.mock + def test_unauthenticated_raises_before_http(self) -> None: + route = respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response(200, json={"payment_history": []}) + ) + client = PerpsClient(config=PerpsConfig.demo()) + with pytest.raises(AuthRequiredError): + client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ) + assert not route.called + client.close() + + @respx.mock + def test_error_401_maps(self, perps_client: PerpsClient) -> None: + respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response(401, json={"error": {"code": "unauthorized"}}) + ) + with pytest.raises(KalshiAuthError): + perps_client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ) + + @respx.mock + def test_error_400_maps(self, perps_client: PerpsClient) -> None: + respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response(400, json={"error": {"code": "bad_request"}}) + ) + with pytest.raises(KalshiValidationError): + perps_client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ) + + @respx.mock + async def test_async_happy_and_optionals_omitted( + self, async_perps_client: AsyncPerpsClient + ) -> None: + route = respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response( + 200, + json={ + "payment_history": [ + _payment_entry(type="special_dividend", payment_amount="8.0000") + ] + }, + ) + ) + resp = await async_perps_client.margin.corporate_action_payment_history( + start_date=date(2026, 2, 1), + end_date="2026-02-28", + ) + params = route.calls.last.request.url.params + assert params["start_date"] == "2026-02-01" + assert params["end_date"] == "2026-02-28" + assert "ticker" not in params + assert "subaccount" not in params + assert resp.payment_history[0].type == "special_dividend" + assert resp.payment_history[0].payment_amount == Decimal("8.0000") + await async_perps_client.close() + + @respx.mock + async def test_async_error_401(self, async_perps_client: AsyncPerpsClient) -> None: + respx.get(f"{BASE}/margin/corporate_action_payment_history").mock( + return_value=httpx.Response(401, json={"error": {"code": "unauthorized"}}) + ) + with pytest.raises(KalshiAuthError): + await async_perps_client.margin.corporate_action_payment_history( + start_date="2026-01-01", + end_date="2026-01-31", + ) + await async_perps_client.close() + + # ── base URL / extra-field tolerance ────────────────────────────────────────── diff --git a/tests/perps/test_markets.py b/tests/perps/test_markets.py index 78209a3..ee54db0 100644 --- a/tests/perps/test_markets.py +++ b/tests/perps/test_markets.py @@ -247,6 +247,18 @@ def test_status_filter(self, perps_client: PerpsClient) -> None: perps_client.markets.list(status="active") assert route.calls[0].request.url.params["status"] == "active" + def test_finalized_status_parses(self) -> None: + m = MarginMarket.model_validate(_market_dict(status="finalized")) + assert m.status == "finalized" + + @respx.mock + def test_list_sends_finalized_status(self, perps_client: PerpsClient) -> None: + route = respx.get(f"{BASE}/margin/markets").mock( + return_value=httpx.Response(200, json={"markets": []}) + ) + perps_client.markets.list(status="finalized") + assert route.calls[0].request.url.params["status"] == "finalized" + @respx.mock def test_null_leverage_and_missing_optionals(self, perps_client: PerpsClient) -> None: respx.get(f"{BASE}/margin/markets").mock( diff --git a/tests/perps/test_models_common.py b/tests/perps/test_models_common.py index b3526b8..dfff378 100644 --- a/tests/perps/test_models_common.py +++ b/tests/perps/test_models_common.py @@ -46,7 +46,15 @@ def test_order_source_values(self) -> None: assert OrderSource("system") is OrderSource.SYSTEM def test_margin_market_status_values(self) -> None: - assert {s.value for s in MarginMarketStatus} == {"inactive", "active", "closed"} + assert {s.value for s in MarginMarketStatus} == { + "inactive", + "active", + "closed", + "finalized", + } + assert MarginMarketStatus("finalized") is MarginMarketStatus.FINALIZED + # Spec renamed closed → finalized; closed is kept for compatibility. + assert MarginMarketStatus("closed") is MarginMarketStatus.CLOSED def test_exchange_instance_values(self) -> None: assert ExchangeInstance("event_contract") is ExchangeInstance.EVENT_CONTRACT diff --git a/tests/perps/ws/test_dispatch.py b/tests/perps/ws/test_dispatch.py index 3621ebc..841fe8f 100644 --- a/tests/perps/ws/test_dispatch.py +++ b/tests/perps/ws/test_dispatch.py @@ -34,6 +34,7 @@ def test_control_types_and_message_models() -> None: "fill", "user_order", "order_group_updates", + "exchange_status", } diff --git a/tests/perps/ws/test_perps_ws_channels.py b/tests/perps/ws/test_perps_ws_channels.py index 9932579..d7e7504 100644 --- a/tests/perps/ws/test_perps_ws_channels.py +++ b/tests/perps/ws/test_perps_ws_channels.py @@ -16,6 +16,7 @@ from kalshi.perps.config import PerpsConfig from kalshi.perps.ws import PerpsWebSocket +from kalshi.perps.ws.models.exchange_status import MarginExchangeStatusMessage from kalshi.perps.ws.models.fill import MarginFillMessage from kalshi.perps.ws.models.market_lifecycle import MarginMarketLifecycleV2Message from kalshi.perps.ws.models.order_group import OrderGroupUpdatesMessage @@ -91,6 +92,32 @@ async def test_subscribe_market_lifecycle_yields_typed_message( assert frame.seq == 4 +async def test_subscribe_exchange_status_yields_typed_message( + fake_perps_ws: FakePerpsWS, perps_ws_config: PerpsConfig, perps_auth +) -> None: + ws = PerpsWebSocket(auth=perps_auth, config=perps_ws_config) + async with ws.connect() as session: + stream = await session.subscribe_exchange_status() + sid = await _sid(fake_perps_ws) + cmd = fake_perps_ws.received_commands[-1] + assert cmd["params"]["channels"] == ["exchange_status"] + assert "market_tickers" not in cmd["params"] + await fake_perps_ws.send_to_all({ + "type": "exchange_status", + "sid": sid, + "seq": 1, + "sending_ts_ms": 1733047200123, + "msg": { + "trading_active": False, + "ts_ms": 1733047200000, + }, + }) + frame = await asyncio.wait_for(stream.__anext__(), timeout=2.0) + assert isinstance(frame, MarginExchangeStatusMessage) + assert frame.msg.trading_active is False + assert frame.seq == 1 + + async def test_subscribe_trade_yields_typed_message( fake_perps_ws: FakePerpsWS, perps_ws_config: PerpsConfig, perps_auth ) -> None: diff --git a/tests/perps/ws/test_perps_ws_models.py b/tests/perps/ws/test_perps_ws_models.py index 5fa9183..cd11766 100644 --- a/tests/perps/ws/test_perps_ws_models.py +++ b/tests/perps/ws/test_perps_ws_models.py @@ -23,6 +23,10 @@ import pytest from pydantic import BaseModel, ValidationError +from kalshi.perps.ws.models.exchange_status import ( + MarginExchangeStatusMessage, + MarginExchangeStatusPayload, +) from kalshi.perps.ws.models.fill import MarginFillMessage, MarginFillPayload from kalshi.perps.ws.models.market_lifecycle import ( MarginMarketLifecycleV2Message, @@ -77,6 +81,10 @@ def _load_spec() -> dict[str, Any]: MarginMarketLifecycleV2Message, MarginMarketLifecycleV2Payload, ), + "marginExchangeStatusPayload": ( + MarginExchangeStatusMessage, + MarginExchangeStatusPayload, + ), "marginUserOrderPayload": (MarginUserOrderMessage, MarginUserOrderPayload), "orderGroupUpdatesPayload": ( OrderGroupUpdatesMessage, @@ -143,6 +151,7 @@ def test_sequenced_envelopes_require_seq(self) -> None: "orderGroupUpdatesPayload", "marginTradePayload", "marginMarketLifecycleV2Payload", + "marginExchangeStatusPayload", ): assert "seq" in spec["components"]["schemas"][schema_name]["required"] for schema_name in ( @@ -770,6 +779,49 @@ def test_missing_seq_or_bad_event_type_raises(self) -> None: MarginMarketLifecycleV2Message.model_validate(bad) +class TestExchangeStatus: + def test_parses_trading_paused_example(self) -> None: + spec = _load_spec() + example = spec["components"]["messages"]["exchangeStatus"]["examples"][0][ + "payload" + ] + msg = MarginExchangeStatusMessage.model_validate(example) + assert msg.type == "exchange_status" + assert msg.sid == 3 + assert msg.seq == 1 + assert msg.sending_ts_ms == 1733047200123 + assert msg.msg.trading_active is False + assert msg.msg.exchange_active is None + assert msg.msg.ts_ms == 1733047200000 + + def test_parses_exchange_active_variant(self) -> None: + msg = MarginExchangeStatusMessage.model_validate( + { + "type": "exchange_status", + "sid": 3, + "seq": 2, + "msg": { + "exchange_active": True, + "ts_ms": 1733047200000, + }, + } + ) + assert msg.msg.exchange_active is True + assert msg.msg.trading_active is None + assert msg.sending_ts_ms is None + + def test_missing_ts_ms_raises(self) -> None: + with pytest.raises(ValidationError): + MarginExchangeStatusMessage.model_validate( + { + "type": "exchange_status", + "sid": 3, + "seq": 1, + "msg": {"trading_active": False}, + } + ) + + class TestDispatcherRegistration: def test_message_models_registers_all_seven_types(self) -> None: from kalshi.perps.ws.dispatch import MESSAGE_MODELS @@ -783,6 +835,7 @@ def test_message_models_registers_all_seven_types(self) -> None: "user_order": MarginUserOrderMessage, "order_group_updates": OrderGroupUpdatesMessage, "market_lifecycle_v2": MarginMarketLifecycleV2Message, + "exchange_status": MarginExchangeStatusMessage, } == MESSAGE_MODELS @@ -798,6 +851,7 @@ def test_typed_helpers_present(self) -> None: "subscribe_user_orders", "subscribe_order_group", "subscribe_market_lifecycle", + "subscribe_exchange_status", ): assert callable(getattr(PerpsWebSocket, name)) diff --git a/tests/test_portfolio.py b/tests/test_portfolio.py index 81f12c3..0bc5a25 100644 --- a/tests/test_portfolio.py +++ b/tests/test_portfolio.py @@ -293,6 +293,26 @@ def test_positions_with_all_new_filters(self, portfolio: PortfolioResource) -> N assert params["subaccount"] == "7" assert params["exchange_index"] == "0" + @respx.mock + def test_sort_by_sent_when_set(self, portfolio: PortfolioResource) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": []} + ) + ) + portfolio.positions(sort_by="event_ticker") + assert route.calls[0].request.url.params["sort_by"] == "event_ticker" + + @respx.mock + def test_sort_by_omitted_by_default(self, portfolio: PortfolioResource) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": []} + ) + ) + portfolio.positions() + assert "sort_by" not in route.calls[0].request.url.params + class TestPortfolioPositionsAll: @respx.mock @@ -341,6 +361,7 @@ def test_positions_all_forwards_filters_and_omits_cursor( event_ticker="EVT-X", subaccount=3, exchange_index=1, + sort_by="event_ticker", ) ) params = dict(route.calls[0].request.url.params) @@ -351,8 +372,21 @@ def test_positions_all_forwards_filters_and_omits_cursor( assert params["event_ticker"] == "EVT-X" assert params["subaccount"] == "3" assert params["exchange_index"] == "1" + assert params["sort_by"] == "event_ticker" assert "cursor" not in params + @respx.mock + def test_positions_all_omits_sort_by_by_default( + self, portfolio: PortfolioResource + ) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": [], "cursor": ""} + ) + ) + list(portfolio.positions_all()) + assert "sort_by" not in route.calls[0].request.url.params + def test_positions_all_requires_auth(self, unauth_portfolio: PortfolioResource) -> None: with pytest.raises(AuthRequiredError): list(unauth_portfolio.positions_all()) @@ -851,6 +885,32 @@ async def test_positions_with_all_new_filters( assert params["subaccount"] == "7" assert params["exchange_index"] == "0" + @respx.mock + @pytest.mark.asyncio + async def test_sort_by_sent_when_set( + self, async_portfolio: AsyncPortfolioResource + ) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": []} + ) + ) + await async_portfolio.positions(sort_by="event_ticker") + assert route.calls[0].request.url.params["sort_by"] == "event_ticker" + + @respx.mock + @pytest.mark.asyncio + async def test_sort_by_omitted_by_default( + self, async_portfolio: AsyncPortfolioResource + ) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": []} + ) + ) + await async_portfolio.positions() + assert "sort_by" not in route.calls[0].request.url.params + class TestAsyncPortfolioSettlements: @respx.mock @@ -1186,6 +1246,34 @@ async def test_positions_all_forwards_settlement_status( assert route.calls[0].request.url.params["settlement_status"] == "settled" assert "cursor" not in route.calls[0].request.url.params + @pytest.mark.asyncio + @respx.mock + async def test_positions_all_sort_by_sent_when_set( + self, async_portfolio: AsyncPortfolioResource + ) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": [], "cursor": ""} + ) + ) + async for _ in async_portfolio.positions_all(sort_by="event_ticker"): + pass + assert route.calls[0].request.url.params["sort_by"] == "event_ticker" + + @pytest.mark.asyncio + @respx.mock + async def test_positions_all_sort_by_omitted_by_default( + self, async_portfolio: AsyncPortfolioResource + ) -> None: + route = respx.get("https://test.kalshi.com/trade-api/v2/portfolio/positions").mock( + return_value=httpx.Response( + 200, json={"market_positions": [], "event_positions": [], "cursor": ""} + ) + ) + async for _ in async_portfolio.positions_all(): + pass + assert "sort_by" not in route.calls[0].request.url.params + @pytest.mark.asyncio async def test_positions_all_requires_auth( self, unauth_async_portfolio: AsyncPortfolioResource