diff --git a/.github/workflows/spec-drift.yml b/.github/workflows/spec-drift.yml index 2c14a9c..242e63c 100644 --- a/.github/workflows/spec-drift.yml +++ b/.github/workflows/spec-drift.yml @@ -85,6 +85,14 @@ jobs: > /tmp/drift.log 2>&1 || true # Keep the last 200 lines so the body stays inside GitHub's limits. tail -n 200 /tmp/drift.log > /tmp/drift.tail + # Failing-set fingerprint: sha256 over the sorted, unique failing test + # IDs. Deterministic upstream yields an identical set every night, so + # the tracker step below re-comments only when this fingerprint CHANGES + # (kills the daily "Still failing" spam that made #467 noisy). + grep -oE '^FAILED [^ ]+' /tmp/drift.log | awk '{print $2}' | sort -u \ + > /tmp/fail_ids.txt || true + fail_fp=$(sha256sum /tmp/fail_ids.txt | awk '{print $1}') + echo "fail_fp=${fail_fp}" >> "$GITHUB_OUTPUT" - name: Ensure spec-drift label exists env: @@ -100,11 +108,12 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + FAIL_FP: ${{ steps.repro.outputs.fail_fp }} run: | set -euo pipefail # Stable marker (NOT a content fingerprint): exactly one open tracker - # at a time. Re-runs append a dated comment instead of duplicating. + # at a time. Re-runs comment only when the FAILING SET changes. readonly MARKER='nightly-spec-drift-tracker' today=$(date -u '+%Y-%m-%d') @@ -120,9 +129,9 @@ jobs: # heredoc) so upstream-sourced log text is never shell-expanded. { printf '## Nightly strict contract tests failed\n\n' - printf 'The scheduled `Spec Drift Detection` run promoted additive drift to an error.\n' - printf 'This means upstream OpenAPI/AsyncAPI changed and the SDK contract suite no longer matches.\n\n' - printf '**To resolve:** locally run `uv run python scripts/sync_spec.py` + `uv run python scripts/generate.py`, reconcile models/maps, and open a PR with `Closes #`.\n\n' + printf 'The scheduled `Spec Drift Detection` run found the SDK contract suite no longer matches upstream OpenAPI/AsyncAPI.\n\n' + printf '**To resolve:** locally run `uv run python scripts/sync_spec.py` + `uv run python scripts/generate.py`, reconcile models/maps, and open a PR with `Closes #`. This tracker auto-closes on the next green scheduled run.\n\n' + printf '**To silence** while a reconcile is in flight, add the `spec-drift-ack` label — nightly runs then stop commenting until the failing set changes.\n\n' printf -- '- Failing run: %s\n\n' "${RUN_URL}" printf '### Failing test output (last 200 lines)\n\n```\n' cat /tmp/drift.tail @@ -130,24 +139,89 @@ jobs: } > /tmp/body.md if [ -n "${existing}" ]; then + # Ack/snooze gate: a maintainer already on this drift can add the + # `spec-drift-ack` (or `snoozed`) label to silence nightly noise + # without closing the tracker. + labels=$(gh issue view "${existing}" --repo "${GITHUB_REPOSITORY}" \ + --json labels --jq '[.labels[].name] | join(",")') + case ",${labels}," in + *,spec-drift-ack,*|*,snoozed,*) + echo "Tracker #${existing} is ack'd/snoozed; not commenting." + exit 0 ;; + esac + + # Only comment when the FAILING SET changed. A deterministic upstream + # produces an identical set every night; re-posting it is spam. + last_fp=$(gh issue view "${existing}" --repo "${GITHUB_REPOSITORY}" \ + --json body,comments --jq '[.body, (.comments[].body)] | .[]' \ + | grep -oE 'fail-fingerprint:[0-9a-f]+' | tail -1 | cut -d: -f2 || true) + if [ "${last_fp}" = "${FAIL_FP}" ]; then + echo "Failing set unchanged (fingerprint ${FAIL_FP}); no new comment." + exit 0 + fi + { - printf 'Still failing as of **%s** ([run](%s)).\n\n' "${today}" "${RUN_URL}" + printf 'Failing set changed as of **%s** ([run](%s)).\n\n' "${today}" "${RUN_URL}" printf '### Latest failing output (last 200 lines)\n\n```\n' cat /tmp/drift.tail printf '\n```\n' + printf '\n\n' "${FAIL_FP}" } > /tmp/comment.md - echo "Tracker already open as #${existing}; appending dated comment." + echo "Failing set changed (${last_fp:-none} -> ${FAIL_FP}); appending comment." gh issue comment "${existing}" \ --repo "${GITHUB_REPOSITORY}" \ --body-file /tmp/comment.md exit 0 fi - # Hidden marker so the dedup query above matches future runs. + # Hidden markers so future runs match this tracker (MARKER) and can + # diff the failing set (fail-fingerprint). printf '\n\n' "${MARKER}" >> /tmp/body.md + printf '\n' "${FAIL_FP}" >> /tmp/body.md gh issue create \ --repo "${GITHUB_REPOSITORY}" \ --label spec-drift \ --title "Nightly spec-drift: strict contract tests failing (since ${today})" \ --body-file /tmp/body.md + + # Companion to report-failure: when a scheduled strict run goes GREEN, the + # drift has been reconciled — close the open nightly tracker so it doesn't + # linger open forever (the old workflow only ever opened/commented). Least + # privilege: issues:write lives only on this job, and it runs no third-party + # actions and no untrusted upstream code (pure `gh` against the repo), so it + # needs neither a checkout nor SHA-pinning. + report-success: + needs: drift-check + if: success() && github.event_name == 'schedule' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - name: Close resolved nightly drift tracker + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + readonly MARKER='nightly-spec-drift-tracker' + today=$(date -u '+%Y-%m-%d') + + existing=$(gh issue list \ + --repo "${GITHUB_REPOSITORY}" \ + --state open \ + --label spec-drift \ + --limit 200 \ + --json number,body \ + --jq '[.[] | select(.body | contains("'"${MARKER}"'"))] | first | .number // empty') + + if [ -z "${existing}" ]; then + echo "No open nightly tracker; nothing to close." + exit 0 + fi + + gh issue close "${existing}" \ + --repo "${GITHUB_REPOSITORY}" \ + --reason completed \ + --comment "Resolved — strict contract suite green as of ${today} ([run](${RUN_URL})). Auto-closed by the nightly spec-drift workflow." diff --git a/.github/workflows/spec-sync.yml b/.github/workflows/spec-sync.yml index b2febe6..aaecaa0 100644 --- a/.github/workflows/spec-sync.yml +++ b/.github/workflows/spec-sync.yml @@ -225,14 +225,16 @@ jobs: "${PERPS_ASYNCAPI_SHA}" "${PERPS_SCM_SHA}" | sha256sum | awk '{print $1}') export FINGERPRINT - # Dedup: skip if an open spec-drift issue already embeds this fingerprint. + # Dedup: skip if an open weekly (spec-sync-bot) drift issue already + # embeds this fingerprint. Scoped to spec-sync-bot so the nightly + # tracker (spec-drift-bot) is never mistaken for a weekly snapshot. existing=$(gh issue list \ --repo "${GITHUB_REPOSITORY}" \ --state open \ --label spec-drift \ --limit 200 \ --json number,body \ - --jq '[.[] | select(.body | contains("fingerprint:'"${FINGERPRINT}"'"))] | first | .number // empty') + --jq '[.[] | select(.body | contains("spec-sync-bot")) | select(.body | contains("fingerprint:'"${FINGERPRINT}"'"))] | first | .number // empty') if [ -n "${existing}" ]; then echo "Drift fingerprint ${FINGERPRINT} already tracked in issue #${existing}; nothing to do." @@ -246,10 +248,40 @@ jobs: python3 scripts/render_drift_body.py > "${body_file}" today=$(date -u '+%Y-%m-%d') - title="Spec drift ${today}: openapi ${OLD_VERSION} → ${NEW_VERSION}" + short_fp=${FINGERPRINT:0:8} + # Lead the title with a CONTENT signal, not just info.version: Kalshi + # changes spec content in place without bumping the version, so a bare + # "3.23.0 → 3.23.0" reads like a no-op false alarm. Tag content-only + # changes and always surface the path delta + short fingerprint. + if [ "${OLD_VERSION}" = "${NEW_VERSION}" ]; then + title="Spec drift ${today}: openapi ${NEW_VERSION} [content-changed] (paths ${OLD_PATH_COUNT}→${NEW_PATH_COUNT}, fp ${short_fp})" + else + title="Spec drift ${today}: openapi ${OLD_VERSION} → ${NEW_VERSION} (paths ${OLD_PATH_COUNT}→${NEW_PATH_COUNT}, fp ${short_fp})" + fi - gh issue create \ + new_url=$(gh issue create \ --repo "${GITHUB_REPOSITORY}" \ --label spec-drift \ --title "${title}" \ - --body-file "${body_file}" + --body-file "${body_file}") + echo "Opened ${new_url}" + + # Supersede older weekly drift snapshots whose fingerprint no longer + # matches live upstream — keep exactly one open weekly issue instead of + # piling up one per upstream micro-revision. Scoped to spec-sync-bot so + # the nightly tracker is never touched here; the freshly-created issue + # carries the current fingerprint and is therefore excluded. + stale=$(gh issue list \ + --repo "${GITHUB_REPOSITORY}" \ + --state open \ + --label spec-drift \ + --limit 200 \ + --json number,body \ + --jq '[.[] | select(.body | contains("spec-sync-bot")) | select((.body | contains("fingerprint:'"${FINGERPRINT}"'")) | not) | .number] | .[]') + for n in ${stale}; do + gh issue close "${n}" \ + --repo "${GITHUB_REPOSITORY}" \ + --reason "not planned" \ + --comment "Superseded by ${new_url} — upstream specs moved again, so this drift snapshot is stale. Reconcile against current upstream." + echo "Superseded #${n}" + done diff --git a/CHANGELOG.md b/CHANGELOG.md index f5693eb..b1acecd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,56 @@ All notable changes to kalshi-sdk will be documented in this file. +## 7.0.0 — 2026-07-10 + +Syncs the upstream OpenAPI/AsyncAPI specs **3.23.0 → 3.24.0** (Closes #467, #470). +One **breaking** rename on the subaccounts surface, a soft-deprecation, three new +endpoints, and additive drift fixes. Kalshi changed spec content without always +bumping `info.version`, so this also absorbs in-place edits made under the same string. + +### Changed (breaking) + +- **Position-transfer price is now fixed-point dollars, not integer cents.** The + `price_cents` field/kwarg (integer cents, 0-100) on + `ApplySubaccountPositionTransferRequest`, `SubaccountTransfer`, and + `subaccounts.transfer_position()` (sync + async) is renamed **`price`** and + typed `OrderPrice` / `DollarDecimal` (fixed-point dollars, `Decimal`). Pass + `price=Decimal("0.50")` where you previously passed `price_cents=50`. The old + client-side cap (`le=100` cents) is gone — `OrderPrice` guards only + non-negativity and the `$0.0001` tick, leaving the upper bound to the server + (matches `CreateOrderRequest`). Upstream renamed the wire field `price_cents` + → `price` (`FixedPointDollars`) in 3.24.0. + +### Deprecated + +- **`exchange.announcements()`** (sync + async) now emits a `DeprecationWarning`. + Kalshi removed `GET /exchange/announcements` and the `Announcement` schema from + the spec in 3.24.0, so the live endpoint 404s. The method and the `Announcement` + model are **retained** (soft-deprecated) pending confirmation the removal is + permanent — upstream has transiently dropped endpoints as publishing glitches + before (see #452). A future major release removes them once confirmed. + +### Added + +- **`communications.quotes.get_for_rfq(rfq_id, quote_id)`** (sync + async) — + `GET /communications/rfqs/{rfq_id}/quotes/{quote_id}`, the RFQ-scoped + get-a-quote (returns `GetQuoteResponse`, the same payload as the flat + `quotes.get`). +- **`klear.margin.active_obligations()`** (sync + async) — + `GET /margin/active_obligations`, all currently-active settlement obligations + (`GetActiveMarginObligationsResponse`; the plural sibling of the single-obligation + `active_obligation()`). +- **`klear.margin.settlement_estimate_by_asset_class()`** (sync + async) — + `GET /margin/settlement_estimate_by_asset_class`, next-settlement estimates keyed + by asset class (`GetSettlementEstimateByAssetClassResponse` + + `AssetClassSettlementEstimate`). +- **`SubaccountNettingConfig.exchange_index`** (`int`, required) — exchange index + of the subaccount. +- **`portfolio.balance()`** (sync + async) gains an optional **`exchange_index`** + query param — target a specific exchange shard (defaults to 0 server-side). +- **`ObligationEntry.asset_class`** (perps SCM / Klear; `AssetClassLiteral` = + `Literal["Crypto"]`, required) — asset class of the settlement obligation. + ## 6.0.0 — 2026-07-04 Syncs the upstream OpenAPI/AsyncAPI specs **3.22.0 → 3.23.0** (#463). The diff --git a/kalshi/__init__.py b/kalshi/__init__.py index d663f94..46d7953 100644 --- a/kalshi/__init__.py +++ b/kalshi/__init__.py @@ -379,4 +379,4 @@ "Withdrawal", ] -__version__ = "6.0.0" +__version__ = "7.0.0" diff --git a/kalshi/_contract_map.py b/kalshi/_contract_map.py index 9caced2..ee83700 100644 --- a/kalshi/_contract_map.py +++ b/kalshi/_contract_map.py @@ -82,10 +82,11 @@ class ContractEntry: spec_schema="MarketOrderbookFp", notes="Spec uses 'MarketOrderbookFp', SDK uses 'Orderbook'", ), - ContractEntry( - sdk_model="kalshi.models.exchange.Announcement", - spec_schema="Announcement", - ), + # Announcement intentionally unmapped: spec sync 3.24.0 removed the + # `Announcement` schema and GET /exchange/announcements. The SDK model + + # method are soft-deprecated (retained pending confirmation the removal is + # permanent), so they no longer have a spec schema to drift-check against. + # See _SOFT_DEPRECATED_MODELS in tests/test_contracts.py. ContractEntry( sdk_model="kalshi.models.historical.HistoricalCutoff", spec_schema="GetHistoricalCutoffResponse", @@ -827,6 +828,10 @@ class ContractEntry: sdk_model="kalshi.perps.klear.models.margin.GetActiveMarginObligationResponse", spec_schema="GetActiveMarginObligationResponse", ), + ContractEntry( + sdk_model="kalshi.perps.klear.models.margin.GetActiveMarginObligationsResponse", + spec_schema="GetActiveMarginObligationsResponse", + ), ContractEntry( sdk_model="kalshi.perps.klear.models.margin.MarketSettlementEstimate", spec_schema="MarketSettlementEstimate", @@ -839,6 +844,14 @@ class ContractEntry: sdk_model="kalshi.perps.klear.models.margin.GetSettlementEstimateResponse", spec_schema="GetSettlementEstimateResponse", ), + ContractEntry( + sdk_model="kalshi.perps.klear.models.margin.AssetClassSettlementEstimate", + spec_schema="AssetClassSettlementEstimate", + ), + ContractEntry( + sdk_model="kalshi.perps.klear.models.margin.GetSettlementEstimateByAssetClassResponse", + spec_schema="GetSettlementEstimateByAssetClassResponse", + ), ContractEntry( sdk_model="kalshi.perps.klear.models.margin.GetSettlementBalanceResponse", spec_schema="GetSettlementBalanceResponse", diff --git a/kalshi/models/subaccounts.py b/kalshi/models/subaccounts.py index b6744aa..46cd22e 100644 --- a/kalshi/models/subaccounts.py +++ b/kalshi/models/subaccounts.py @@ -7,7 +7,7 @@ from pydantic import BaseModel, Field -from kalshi.types import DollarDecimal, StrictInt +from kalshi.types import DollarDecimal, OrderPrice, StrictInt class CreateSubaccountRequest(BaseModel): @@ -58,15 +58,20 @@ class ApplySubaccountTransferRequest(BaseModel): class ApplySubaccountPositionTransferRequest(BaseModel): - """Body for POST /portfolio/subaccounts/positions/transfer (spec v3.23.0). + """Body for POST /portfolio/subaccounts/positions/transfer (spec v3.24.0). Moves an open **position** (contracts) between subaccounts — distinct from - the cash-only :class:`ApplySubaccountTransferRequest`. ``price_cents`` is the - per-contract price in cents (``0``-``100``) used to set the cost basis on the - destination subaccount; ``count`` is the number of contracts and must be - positive. ``from_subaccount`` / ``to_subaccount`` use ``0`` for the primary - account; the SDK enforces only the lower bound (``ge=0``), leaving the upper - bound to the server (mirrors :class:`ApplySubaccountTransferRequest`). + the cash-only :class:`ApplySubaccountTransferRequest`. ``price`` is the + per-contract price in **fixed-point dollars** (``0``-``1.0``) used to set the + cost basis on the destination subaccount; ``count`` is the number of contracts + and must be positive. ``from_subaccount`` / ``to_subaccount`` use ``0`` for the + primary account; the SDK enforces only the lower bound (``ge=0``), leaving the + upper bound to the server (mirrors :class:`ApplySubaccountTransferRequest`). + + Spec v3.24.0 renamed ``price_cents`` (integer cents) → ``price`` + (``FixedPointDollars``); pass a ``Decimal`` in dollars, e.g. ``Decimal("0.50")`` + for a 50¢ cost basis. Uses :data:`~kalshi.types.OrderPrice` so a negative or + sub-$0.0001-tick value fails at construction rather than as a server 400. """ client_transfer_id: UUID @@ -75,7 +80,7 @@ class ApplySubaccountPositionTransferRequest(BaseModel): market_ticker: str side: Literal["yes", "no"] count: StrictInt = Field(gt=0) - price_cents: StrictInt = Field(ge=0, le=100) + price: OrderPrice model_config = {"extra": "forbid"} @@ -128,8 +133,10 @@ class SubaccountTransfer(BaseModel): Spec v3.23.0 split transfers into two kinds via ``transfer_type``: ``cash`` (money moved; ``amount_cents`` set) and ``position`` (contracts moved). The - ``market_ticker`` / ``side`` / ``count`` / ``price_cents`` fields are - populated only for ``position`` transfers, so they are optional here. + ``market_ticker`` / ``side`` / ``count`` / ``price`` fields are populated only + for ``position`` transfers, so they are optional here. Spec v3.24.0 renamed the + per-contract ``price_cents`` (integer cents) → ``price`` + (``FixedPointDollars``), surfacing as a ``Decimal`` in dollars. """ transfer_id: str @@ -144,7 +151,7 @@ class SubaccountTransfer(BaseModel): market_ticker: str | None = None side: Literal["yes", "no"] | None = None count: int | None = None - price_cents: int | None = None + price: DollarDecimal | None = None model_config = {"extra": "allow"} @@ -163,6 +170,8 @@ class SubaccountNettingConfig(BaseModel): subaccount_number: int enabled: bool + # Spec v3.24.0: exchange index of the subaccount (required). + exchange_index: int model_config = {"extra": "allow"} diff --git a/kalshi/perps/klear/models/__init__.py b/kalshi/perps/klear/models/__init__.py index b46831e..0d02761 100644 --- a/kalshi/perps/klear/models/__init__.py +++ b/kalshi/perps/klear/models/__init__.py @@ -4,13 +4,17 @@ from kalshi.perps.klear.models.common import Error from kalshi.perps.klear.models.margin import ( + AssetClassLiteral, + AssetClassSettlementEstimate, GetActiveMarginObligationResponse, + GetActiveMarginObligationsResponse, GetGuarantyFundBalanceResponse, GetMarginReportsResponse, GetObligationHistoryResponse, GetSettlementBalanceHistoryResponse, GetSettlementBalanceResponse, GetSettlementBalanceWithdrawalResponse, + GetSettlementEstimateByAssetClassResponse, GetSettlementEstimateResponse, MaintenanceMarginDetail, MarginReport, @@ -27,14 +31,18 @@ ) __all__ = [ + "AssetClassLiteral", + "AssetClassSettlementEstimate", "Error", "GetActiveMarginObligationResponse", + "GetActiveMarginObligationsResponse", "GetGuarantyFundBalanceResponse", "GetMarginReportsResponse", "GetObligationHistoryResponse", "GetSettlementBalanceHistoryResponse", "GetSettlementBalanceResponse", "GetSettlementBalanceWithdrawalResponse", + "GetSettlementEstimateByAssetClassResponse", "GetSettlementEstimateResponse", "MaintenanceMarginDetail", "MarginReport", diff --git a/kalshi/perps/klear/models/margin.py b/kalshi/perps/klear/models/margin.py index 7cd2ade..8bfc446 100644 --- a/kalshi/perps/klear/models/margin.py +++ b/kalshi/perps/klear/models/margin.py @@ -73,6 +73,11 @@ def _require_positive_withdrawal(value: Decimal) -> Decimal: # Spec ``GetSettlementBalanceWithdrawalResponse.status`` enum. WithdrawalStatusLiteral = Literal["pending", "processing", "processed", "failed"] + +# Spec ``AssetClass`` enum (single value today). Named alias mirrors the other +# *Literal aliases; shared by ObligationEntry.asset_class and the settlement +# estimates keyed by asset class (spec sync 3.24.0). +AssetClassLiteral = Literal["Crypto"] """Spec withdrawal ``status`` — lifecycle of an async settlement-balance withdrawal.""" @@ -169,6 +174,8 @@ class ObligationEntry(BaseModel): pnl_centicents: int execution_time: AwareDatetime last_updated_ts: AwareDatetime + # Spec (perps SCM) added a required ``asset_class`` on ``ObligationInfo``. + asset_class: AssetClassLiteral # From the inline allOf object. receives: NullableList[ObligationReceiveInfo] settlement_details: NullableList[SettlementDetail] @@ -248,6 +255,53 @@ class GetSettlementEstimateResponse(BaseModel): model_config = {"extra": "allow"} +# ── Spec sync 3.24.0 additions (perps SCM) ────────────────────────────────── + + +class GetActiveMarginObligationsResponse(BaseModel): + """Spec ``GetActiveMarginObligationsResponse`` — all currently-active obligations. + + Plural sibling of ``GetActiveMarginObligationResponse`` (the single-obligation + ``/margin/active_obligation`` endpoint): wraps the full list rather than one + nullable entry. Backs ``GET /margin/active_obligations``. + """ + + obligations: NullableList[ObligationEntry] + + model_config = {"extra": "allow"} + + +class AssetClassSettlementEstimate(BaseModel): + """Spec ``AssetClassSettlementEstimate`` — settlement estimate for one asset class. + + Mirrors :class:`GetSettlementEstimateResponse` (user + per-subtrader breakdowns + + previous settlement prices) and adds ``next_runtime``, the next + settlement-cycle time. Only ``next_runtime`` is spec-required; the breakdowns + are optional. + """ + + next_runtime: AwareDatetime + user_breakdown: SettlementEstimate | None = None + subtrader_breakdowns: dict[str, SettlementEstimate] | None = None + prev_settlement_prices: dict[str, int] | None = None + + model_config = {"extra": "allow"} + + +class GetSettlementEstimateByAssetClassResponse(BaseModel): + """Spec ``GetSettlementEstimateByAssetClassResponse`` — estimates keyed by asset class. + + ``estimates`` is the spec ``additionalProperties`` map (asset class → + :class:`AssetClassSettlementEstimate`). Backs + ``GET /margin/settlement_estimate_by_asset_class``. + """ + + estimates: dict[str, AssetClassSettlementEstimate] + settlement_balance_centicents: int + + model_config = {"extra": "allow"} + + class GetSettlementBalanceResponse(BaseModel): """Spec ``GetSettlementBalanceResponse`` — settlement-buffer balance. diff --git a/kalshi/perps/klear/resources/margin.py b/kalshi/perps/klear/resources/margin.py index ddeba53..b7ebd28 100644 --- a/kalshi/perps/klear/resources/margin.py +++ b/kalshi/perps/klear/resources/margin.py @@ -33,10 +33,12 @@ from kalshi.models.common import Page from kalshi.perps.klear.models.margin import ( GetActiveMarginObligationResponse, + GetActiveMarginObligationsResponse, GetGuarantyFundBalanceResponse, GetMarginReportsResponse, GetSettlementBalanceResponse, GetSettlementBalanceWithdrawalResponse, + GetSettlementEstimateByAssetClassResponse, GetSettlementEstimateResponse, ObligationEntry, SettlementBalanceHistoryEntry, @@ -108,6 +110,13 @@ def active_obligation( data = self._get("/margin/active_obligation", extra_headers=extra_headers) return GetActiveMarginObligationResponse.model_validate(data) + def active_obligations( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetActiveMarginObligationsResponse: + """``GET /margin/active_obligations`` — all currently-active obligations (spec v3.24.0).""" + data = self._get("/margin/active_obligations", extra_headers=extra_headers) + return GetActiveMarginObligationsResponse.model_validate(data) + def obligation_history( self, *, @@ -153,6 +162,18 @@ def settlement_estimate( data = self._get("/margin/settlement_estimate", extra_headers=extra_headers) return GetSettlementEstimateResponse.model_validate(data) + def settlement_estimate_by_asset_class( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetSettlementEstimateByAssetClassResponse: + """``GET /margin/settlement_estimate_by_asset_class`` (spec v3.24.0). + + Next-settlement estimates keyed by asset class. + """ + data = self._get( + "/margin/settlement_estimate_by_asset_class", extra_headers=extra_headers + ) + return GetSettlementEstimateByAssetClassResponse.model_validate(data) + def settlement_balance( self, *, extra_headers: dict[str, str] | None = None ) -> GetSettlementBalanceResponse: @@ -261,6 +282,13 @@ async def active_obligation( data = await self._get("/margin/active_obligation", extra_headers=extra_headers) return GetActiveMarginObligationResponse.model_validate(data) + async def active_obligations( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetActiveMarginObligationsResponse: + """Async :meth:`MarginResource.active_obligations` (spec v3.24.0).""" + data = await self._get("/margin/active_obligations", extra_headers=extra_headers) + return GetActiveMarginObligationsResponse.model_validate(data) + async def obligation_history( self, *, @@ -306,6 +334,15 @@ async def settlement_estimate( data = await self._get("/margin/settlement_estimate", extra_headers=extra_headers) return GetSettlementEstimateResponse.model_validate(data) + async def settlement_estimate_by_asset_class( + self, *, extra_headers: dict[str, str] | None = None + ) -> GetSettlementEstimateByAssetClassResponse: + """Async :meth:`MarginResource.settlement_estimate_by_asset_class` (spec v3.24.0).""" + data = await self._get( + "/margin/settlement_estimate_by_asset_class", extra_headers=extra_headers + ) + return GetSettlementEstimateByAssetClassResponse.model_validate(data) + async def settlement_balance( self, *, extra_headers: dict[str, str] | None = None ) -> GetSettlementBalanceResponse: diff --git a/kalshi/resources/communications.py b/kalshi/resources/communications.py index 4312179..e68333d 100644 --- a/kalshi/resources/communications.py +++ b/kalshi/resources/communications.py @@ -654,6 +654,22 @@ def confirm(self, quote_id: str, *, extra_headers: dict[str, str] | None = None) # /communications/rfqs/{rfq_id}/quotes/{quote_id}[/accept|/confirm]. # Same semantics as the flat quote actions above, but scoped to the RFQ. + def get_for_rfq( + self, rfq_id: str, quote_id: str, *, extra_headers: dict[str, str] | None = None + ) -> GetQuoteResponse: + """Get a quote scoped to its RFQ (spec v3.24.0). + + ``GET /communications/rfqs/{rfq_id}/quotes/{quote_id}`` — same payload as + the flat :meth:`get`, addressed through the parent RFQ. + """ + self._require_auth() + data = self._get( + f"/communications/rfqs/{_seg(rfq_id, name='rfq_id')}" + f"/quotes/{_seg(quote_id, name='quote_id')}", + extra_headers=extra_headers, + ) + return GetQuoteResponse.model_validate(data) + def delete_for_rfq( self, rfq_id: str, quote_id: str, *, extra_headers: dict[str, str] | None = None ) -> None: @@ -1456,6 +1472,18 @@ async def confirm( # -- RFQ-scoped quote actions (spec v3.22.0) ------------------------------- + async def get_for_rfq( + self, rfq_id: str, quote_id: str, *, extra_headers: dict[str, str] | None = None + ) -> GetQuoteResponse: + """Async :meth:`QuotesResource.get_for_rfq` (spec v3.24.0).""" + self._require_auth() + data = await self._get( + f"/communications/rfqs/{_seg(rfq_id, name='rfq_id')}" + f"/quotes/{_seg(quote_id, name='quote_id')}", + extra_headers=extra_headers, + ) + return GetQuoteResponse.model_validate(data) + async def delete_for_rfq( self, rfq_id: str, quote_id: str, *, extra_headers: dict[str, str] | None = None ) -> None: diff --git a/kalshi/resources/exchange.py b/kalshi/resources/exchange.py index d82b8b2..c2b4683 100644 --- a/kalshi/resources/exchange.py +++ b/kalshi/resources/exchange.py @@ -3,6 +3,7 @@ from __future__ import annotations import builtins +import warnings from kalshi.models.exchange import ( Announcement, @@ -12,6 +13,20 @@ ) from kalshi.resources._base import AsyncResource, SyncResource +# Soft-deprecation (spec sync 3.23.0 → 3.24.0): Kalshi removed +# GET /exchange/announcements from the OpenAPI spec. The method is RETAINED +# (not deleted) pending confirmation the removal is permanent — upstream has +# transiently dropped endpoints as publishing glitches before (see the +# CreateOrder/BatchCreateOrders drop reverted in #452). It now emits a +# DeprecationWarning and will 404 against the live API until/unless the endpoint +# returns; a future major release removes it once the removal is confirmed. +_ANNOUNCEMENTS_DEPRECATED = ( + "exchange.announcements() is deprecated: Kalshi removed " + "GET /exchange/announcements from the OpenAPI spec in v3.24.0, so the live " + "endpoint now returns 404. The method is retained pending confirmation the " + "removal is permanent and will be removed in a future major release." +) + class ExchangeResource(SyncResource): """Sync exchange API.""" @@ -28,6 +43,7 @@ def schedule(self, *, extra_headers: dict[str, str] | None = None) -> Schedule: def announcements( self, *, extra_headers: dict[str, str] | None = None ) -> builtins.list[Announcement]: + warnings.warn(_ANNOUNCEMENTS_DEPRECATED, DeprecationWarning, stacklevel=2) data = self._get("/exchange/announcements", extra_headers=extra_headers) raw = data.get("announcements", []) return [Announcement.model_validate(a) for a in raw] @@ -59,6 +75,7 @@ async def schedule(self, *, extra_headers: dict[str, str] | None = None) -> Sche async def announcements( self, *, extra_headers: dict[str, str] | None = None ) -> builtins.list[Announcement]: + warnings.warn(_ANNOUNCEMENTS_DEPRECATED, DeprecationWarning, stacklevel=2) data = await self._get("/exchange/announcements", extra_headers=extra_headers) raw = data.get("announcements", []) return [Announcement.model_validate(a) for a in raw] diff --git a/kalshi/resources/portfolio.py b/kalshi/resources/portfolio.py index b2899b9..86ce7d2 100644 --- a/kalshi/resources/portfolio.py +++ b/kalshi/resources/portfolio.py @@ -73,10 +73,16 @@ class PortfolioResource(SyncResource): """Sync portfolio API.""" def balance( - self, *, subaccount: int | None = None, extra_headers: dict[str, str] | None = None + self, + *, + subaccount: int | None = None, + exchange_index: int | None = None, + extra_headers: dict[str, str] | None = None, ) -> Balance: self._require_auth() - params = _params(subaccount=subaccount) + # Spec v3.24.0 added the optional `exchange_index` query param (target a + # specific exchange shard; defaults to 0 server-side). + params = _params(subaccount=subaccount, exchange_index=exchange_index) data = self._get("/portfolio/balance", params=params, extra_headers=extra_headers) return Balance.model_validate(data) @@ -360,10 +366,16 @@ class AsyncPortfolioResource(AsyncResource): """Async portfolio API.""" async def balance( - self, *, subaccount: int | None = None, extra_headers: dict[str, str] | None = None + self, + *, + subaccount: int | None = None, + exchange_index: int | None = None, + extra_headers: dict[str, str] | None = None, ) -> Balance: self._require_auth() - params = _params(subaccount=subaccount) + # Spec v3.24.0 added the optional `exchange_index` query param (target a + # specific exchange shard; defaults to 0 server-side). + params = _params(subaccount=subaccount, exchange_index=exchange_index) data = await self._get("/portfolio/balance", params=params, extra_headers=extra_headers) return Balance.model_validate(data) diff --git a/kalshi/resources/subaccounts.py b/kalshi/resources/subaccounts.py index e6d6e1d..4cdf6be 100644 --- a/kalshi/resources/subaccounts.py +++ b/kalshi/resources/subaccounts.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import AsyncIterator, Iterator +from decimal import Decimal from typing import Any, Literal, overload from uuid import UUID @@ -79,7 +80,7 @@ def _build_position_transfer_body( market_ticker: str | None, side: Literal["yes", "no"] | None, count: int | None, - price_cents: int | None, + price: Decimal | None, ) -> dict[str, Any]: _check_request_exclusive( request, @@ -89,7 +90,7 @@ def _build_position_transfer_body( market_ticker=market_ticker, side=side, count=count, - price_cents=price_cents, + price=price, ) if request is None: if ( @@ -99,11 +100,11 @@ def _build_position_transfer_body( or market_ticker is None or side is None or count is None - or price_cents is None + or price is None ): raise TypeError( "transfer_position() requires `client_transfer_id`, `from_subaccount`, " - "`to_subaccount`, `market_ticker`, `side`, `count`, and `price_cents` " + "`to_subaccount`, `market_ticker`, `side`, `count`, and `price` " "(or pass `request=...`)" ) # Accept str for caller ergonomics; coerce once to surface a clean @@ -118,7 +119,7 @@ def _build_position_transfer_body( market_ticker=market_ticker, side=side, count=count, - price_cents=price_cents, + price=price, ) return request.model_dump(exclude_none=True, by_alias=True, mode="json") @@ -228,7 +229,7 @@ def transfer_position( market_ticker: str, side: Literal["yes", "no"], count: int, - price_cents: int, + price: Decimal, extra_headers: dict[str, str] | None = None, ) -> ApplySubaccountPositionTransferResponse: ... def transfer_position( @@ -241,15 +242,16 @@ def transfer_position( market_ticker: str | None = None, side: Literal["yes", "no"] | None = None, count: int | None = None, - price_cents: int | None = None, + price: Decimal | None = None, extra_headers: dict[str, str] | None = None, ) -> ApplySubaccountPositionTransferResponse: - """Move an open position between subaccounts (spec v3.23.0). + """Move an open position between subaccounts (spec v3.24.0). Unlike the cash-only :meth:`transfer`, this moves ``count`` contracts of ``market_ticker`` (``side``) and returns the server-generated - ``position_transfer_id``. ``price_cents`` (0-100) sets the cost basis on - the destination. + ``position_transfer_id``. ``price`` is the per-contract cost basis in + fixed-point dollars (0-1.0) — pass a ``Decimal``, e.g. ``Decimal("0.50")``. + Spec v3.24.0 renamed this ``price_cents`` (integer cents) → ``price``. """ self._require_auth() body = _build_position_transfer_body( @@ -260,7 +262,7 @@ def transfer_position( market_ticker=market_ticker, side=side, count=count, - price_cents=price_cents, + price=price, ) data = self._post( "/portfolio/subaccounts/positions/transfer", json=body, extra_headers=extra_headers @@ -420,7 +422,7 @@ async def transfer_position( market_ticker: str, side: Literal["yes", "no"], count: int, - price_cents: int, + price: Decimal, extra_headers: dict[str, str] | None = None, ) -> ApplySubaccountPositionTransferResponse: ... async def transfer_position( @@ -433,7 +435,7 @@ async def transfer_position( market_ticker: str | None = None, side: Literal["yes", "no"] | None = None, count: int | None = None, - price_cents: int | None = None, + price: Decimal | None = None, extra_headers: dict[str, str] | None = None, ) -> ApplySubaccountPositionTransferResponse: """Move an open position between subaccounts (spec v3.23.0). @@ -449,7 +451,7 @@ async def transfer_position( market_ticker=market_ticker, side=side, count=count, - price_cents=price_cents, + price=price, ) data = await self._post( "/portfolio/subaccounts/positions/transfer", json=body, extra_headers=extra_headers diff --git a/pyproject.toml b/pyproject.toml index 3ec1cfd..e045481 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kalshi-sdk" -version = "6.0.0" +version = "7.0.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/asyncapi.yaml b/specs/asyncapi.yaml index 557a4c2..7390a60 100644 --- a/specs/asyncapi.yaml +++ b/specs/asyncapi.yaml @@ -3177,6 +3177,13 @@ components: - linear_cent - deci_cent - tapered_deci_cent + - center_whole_edge_half_cent + - center_whole_edge_quint_cent + - center_half_edge_half_cent + - center_half_edge_quint_cent + - center_half_edge_deci_cent + - center_quint_edge_quint_cent + - center_quint_edge_deci_cent price_ranges: type: array description: >- diff --git a/specs/openapi.yaml b/specs/openapi.yaml index 215876d..0ba6d91 100644 --- a/specs/openapi.yaml +++ b/specs/openapi.yaml @@ -1,9 +1,10 @@ openapi: 3.0.0 info: title: Kalshi Trade API Manual Endpoints - version: 3.23.0 - description: Manually defined OpenAPI spec for endpoints being migrated to spec-first approach - + version: 3.24.0 + description: >- + Manually defined OpenAPI spec for endpoints being migrated to spec-first + approach servers: - url: https://external-api.kalshi.com/trade-api/v2 description: Production Trade API server @@ -13,7 +14,6 @@ servers: description: Demo Trade API server - url: https://demo-api.kalshi.co/trade-api/v2 description: Demo shared API server, also supported - paths: /exchange/status: get: @@ -47,24 +47,6 @@ paths: application/json: schema: $ref: '#/components/schemas/ExchangeStatus' - - /exchange/announcements: - get: - operationId: GetExchangeAnnouncements - summary: Get Exchange Announcements - description: ' Endpoint for getting all exchange-wide announcements.' - tags: - - exchange - responses: - '200': - description: Exchange announcements retrieved successfully - content: - application/json: - schema: - $ref: '#/components/schemas/GetExchangeAnnouncementsResponse' - '500': - description: Internal server error - /series/fee_changes: get: operationId: GetSeriesFeeChanges @@ -96,7 +78,6 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /exchange/schedule: get: operationId: GetExchangeSchedule @@ -113,7 +94,6 @@ paths: $ref: '#/components/schemas/GetExchangeScheduleResponse' '500': description: Internal server error - /exchange/user_data_timestamp: get: operationId: GetUserDataTimestamp @@ -130,14 +110,19 @@ paths: $ref: '#/components/schemas/GetUserDataTimestampResponse' '500': description: Internal server error - /series/{series_ticker}/markets/{ticker}/candlesticks: get: operationId: GetMarketCandlesticks summary: Get Market Candlesticks - description: | - Time period length of each candlestick in minutes. Valid values: 1 (1 minute), 60 (1 hour), 1440 (1 day). - Candlesticks for markets that settled before the historical cutoff are only available via `GET /historical/markets/{ticker}/candlesticks`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. + description: > + Time period length of each candlestick in minutes. Valid values: 1 (1 + minute), 60 (1 hour), 1440 (1 day). + + Candlesticks for markets that settled before the historical cutoff are + only available via `GET /historical/markets/{ticker}/candlesticks`. See + [Historical + Data](https://docs.kalshi.com/getting_started/historical_data) for + details. tags: - market parameters: @@ -156,38 +141,53 @@ paths: - name: start_ts in: query required: true - description: Start timestamp (Unix timestamp). Candlesticks will include those ending on or after this time. + description: >- + Start timestamp (Unix timestamp). Candlesticks will include those + ending on or after this time. schema: type: integer format: int64 - name: end_ts in: query required: true - description: End timestamp (Unix timestamp). Candlesticks will include those ending on or before this time. + description: >- + End timestamp (Unix timestamp). Candlesticks will include those + ending on or before this time. schema: type: integer format: int64 - name: period_interval in: query required: true - description: Time period length of each candlestick in minutes. Valid values are 1 (1 minute), 60 (1 hour), or 1440 (1 day). + description: >- + Time period length of each candlestick in minutes. Valid values are + 1 (1 minute), 60 (1 hour), or 1440 (1 day). schema: type: integer - enum: [1, 60, 1440] + enum: + - 1 + - 60 + - 1440 x-enum-varnames: - GetMarketCandlesticksParamsPeriodIntervalN1 - GetMarketCandlesticksParamsPeriodIntervalN60 - GetMarketCandlesticksParamsPeriodIntervalN1440 x-oapi-codegen-extra-tags: - validate: "required,oneof=1 60 1440" + validate: required,oneof=1 60 1440 - name: include_latest_before_start in: query required: false - description: | - If true, prepends the latest candlestick available before the start_ts. This synthetic candlestick is created by: + description: > + If true, prepends the latest candlestick available before the + start_ts. This synthetic candlestick is created by: + 1. Finding the most recent real candlestick before start_ts - 2. Projecting it forward to the first period boundary (calculated as the next period interval after start_ts) - 3. Setting all OHLC prices to null, and `previous_price` to the close price from the real candlestick + + 2. Projecting it forward to the first period boundary (calculated as + the next period interval after start_ts) + + 3. Setting all OHLC prices to null, and `previous_price` to the + close price from the real candlestick schema: type: boolean default: false @@ -204,13 +204,21 @@ paths: description: Not found '500': description: Internal server error - /markets/trades: get: operationId: GetTrades summary: Get Trades - description: | - Endpoint for getting all trades for all markets. A trade represents a completed transaction between two users on a specific market. Each trade includes the market ticker, price, quantity, and timestamp information. Block trades are included in the response by default and identified by the `is_block_trade` field; use the `is_block_trade` query parameter to filter by block / non-block. This endpoint returns a paginated response. Use the 'limit' parameter to control page size (1-1000, defaults to 100). The response includes a 'cursor' field - pass this value in the 'cursor' parameter of your next request to get the next page. An empty cursor indicates no more pages are available. + description: > + Endpoint for getting all trades for all markets. A trade represents a + completed transaction between two users on a specific market. Each trade + includes the market ticker, price, quantity, and timestamp information. + Block trades are included in the response by default and identified by + the `is_block_trade` field; use the `is_block_trade` query parameter to + filter by block / non-block. This endpoint returns a paginated response. + Use the 'limit' parameter to control page size (1-1000, defaults to + 100). The response includes a 'cursor' field - pass this value in the + 'cursor' parameter of your next request to get the next page. An empty + cursor indicates no more pages are available. tags: - market parameters: @@ -231,7 +239,6 @@ paths: description: Bad request '500': description: Internal server error - /markets/{ticker}/orderbook: get: operationId: GetMarketOrderbook @@ -247,7 +254,9 @@ paths: - $ref: '#/components/parameters/TickerPath' - name: depth in: query - description: Depth of the orderbook to retrieve (0 or negative means all levels, 1-100 for specific depth) + description: >- + Depth of the orderbook to retrieve (0 or negative means all levels, + 1-100 for specific depth) required: false schema: type: integer @@ -269,12 +278,20 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /markets/orderbooks: get: operationId: GetMarketOrderbooks summary: Get Multiple Market Orderbooks - description: 'Endpoint for getting the current order books for multiple markets in a single request. The order book shows all active bid orders for both yes and no sides of a binary market. It returns yes bids and no bids only (no asks are returned). This is because in binary markets, a bid for yes at price X is equivalent to an ask for no at price (100-X). For example, a yes bid at 7¢ is the same as a no ask at 93¢, with identical contract sizes. Each side shows price levels with their corresponding quantities and order counts, organized from best to worst prices. Returns one orderbook per requested market ticker.' + description: >- + Endpoint for getting the current order books for multiple markets in a + single request. The order book shows all active bid orders for both yes + and no sides of a binary market. It returns yes bids and no bids only + (no asks are returned). This is because in binary markets, a bid for yes + at price X is equivalent to an ask for no at price (100-X). For example, + a yes bid at 7¢ is the same as a no ask at 93¢, with identical contract + sizes. Each side shows price levels with their corresponding quantities + and order counts, organized from best to worst prices. Returns one + orderbook per requested market ticker. tags: - market security: @@ -310,7 +327,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /series/{series_ticker}: get: operationId: GetSeries @@ -332,7 +348,9 @@ paths: type: boolean default: false x-go-type-skip-optional-pointer: true - description: If true, includes the total volume traded across all events in this series. + description: >- + If true, includes the total volume traded across all events in this + series. responses: '200': description: Series retrieved successfully @@ -344,7 +362,6 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /series: get: operationId: GetSeriesList @@ -379,11 +396,15 @@ paths: type: boolean default: false x-go-type-skip-optional-pointer: true - description: If true, includes the total volume traded across all events in each series. + description: >- + If true, includes the total volume traded across all events in each + series. - name: min_updated_ts in: query required: false - description: Filter series with metadata updated after this Unix timestamp (in seconds). Use this to efficiently poll for changes. + description: >- + Filter series with metadata updated after this Unix timestamp (in + seconds). Use this to efficiently poll for changes. schema: type: integer format: int64 @@ -398,25 +419,24 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /markets: get: operationId: GetMarkets summary: Get Markets - description: | - Filter by market status. Possible values: `unopened`, `open`, `closed`, `settled`. Leave empty to return markets with any status. - - Only one `status` filter may be supplied at a time. - - Timestamp filters will be mutually exclusive from other timestamp filters and certain status filters. - - | Compatible Timestamp Filters | Additional Status Filters| Extra Notes | - |------------------------------|--------------------------|-------------| - | min_created_ts, max_created_ts | `unopened`, `open`, *empty* | | - | min_close_ts, max_close_ts | `closed`, *empty* | | - | min_settled_ts, max_settled_ts | `settled`, *empty* | | - | min_updated_ts | *empty* | Incompatible with all filters besides `mve_filter=exclude`. May be combined with `series_ticker`, which requires `mve_filter=exclude` | - - Markets that settled before the historical cutoff are only available via `GET /historical/markets`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. - + description: > + Filter by market status. Possible values: `unopened`, `open`, `closed`, + `settled`. Leave empty to return markets with any status. + - Only one `status` filter may be supplied at a time. + - Timestamp filters will be mutually exclusive from other timestamp filters and certain status filters. + + | Compatible Timestamp Filters | Additional Status Filters| Extra Notes | + |------------------------------|--------------------------|-------------| + | min_created_ts, max_created_ts | `unopened`, `open`, *empty* | | + | min_close_ts, max_close_ts | `closed`, *empty* | | + | min_settled_ts, max_settled_ts | `settled`, *empty* | | + | min_updated_ts | *empty* | Incompatible with all filters besides `mve_filter=exclude`. May be combined with `series_ticker`, which requires `mve_filter=exclude` | + + Markets that settled before the historical cutoff are only available via `GET /historical/markets`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. tags: - market parameters: @@ -447,7 +467,6 @@ paths: description: Unauthorized '500': description: Internal server error - /markets/{ticker}: get: operationId: GetMarket @@ -470,18 +489,22 @@ paths: description: Not found '500': description: Internal server error - /markets/candlesticks: get: operationId: BatchGetMarketCandlesticks summary: Batch Get Market Candlesticks - description: | + description: > Endpoint for retrieving candlestick data for multiple markets. + - Accepts up to 100 market tickers per request + - Returns up to 10,000 candlesticks total across all markets + - Returns candlesticks grouped by market_id - - Optionally includes a synthetic initial candlestick for price continuity (see `include_latest_before_start` parameter) + + - Optionally includes a synthetic initial candlestick for price + continuity (see `include_latest_before_start` parameter) tags: - market parameters: @@ -516,11 +539,17 @@ paths: - name: include_latest_before_start in: query required: false - description: | - If true, prepends the latest candlestick available before the start_ts. This synthetic candlestick is created by: + description: > + If true, prepends the latest candlestick available before the + start_ts. This synthetic candlestick is created by: + 1. Finding the most recent real candlestick before start_ts - 2. Projecting it forward to the first period boundary (calculated as the next period interval after start_ts) - 3. Setting all OHLC prices to null, and `previous_price` to the close price from the real candlestick + + 2. Projecting it forward to the first period boundary (calculated as + the next period interval after start_ts) + + 3. Setting all OHLC prices to null, and `previous_price` to the + close price from the real candlestick schema: type: boolean default: false @@ -537,7 +566,6 @@ paths: description: Unauthorized '500': description: Internal server error - /series/{series_ticker}/events/{ticker}/candlesticks: get: operationId: GetMarketCandlesticksByEvent @@ -566,7 +594,7 @@ paths: type: integer format: int64 x-oapi-codegen-extra-tags: - validate: "required" + validate: required - name: end_ts in: query required: true @@ -575,17 +603,22 @@ paths: type: integer format: int64 x-oapi-codegen-extra-tags: - validate: "required" + validate: required - name: period_interval in: query required: true - description: Specifies the length of each candlestick period, in minutes. Must be one minute, one hour, or one day. + description: >- + Specifies the length of each candlestick period, in minutes. Must be + one minute, one hour, or one day. schema: type: integer format: int32 - enum: [1, 60, 1440] + enum: + - 1 + - 60 + - 1440 x-oapi-codegen-extra-tags: - validate: "required,oneof=1 60 1440" + validate: required,oneof=1 60 1440 responses: '200': description: Event candlesticks retrieved successfully @@ -599,22 +632,27 @@ paths: description: Unauthorized '500': description: Internal server error - /events: get: operationId: GetEvents summary: Get Events - description: | + description: > Get all events. This endpoint excludes multivariate events. - To retrieve multivariate events, use the GET /events/multivariate endpoint. - All events are accessible through this endpoint, even if their associated markets are older than the historical cutoff. + + To retrieve multivariate events, use the GET /events/multivariate + endpoint. + + All events are accessible through this endpoint, even if their + associated markets are older than the historical cutoff. tags: - events parameters: - name: limit in: query required: false - description: Parameter to specify the number of results per page. Defaults to 200. Maximum value is 200. + description: >- + Parameter to specify the number of results per page. Defaults to + 200. Maximum value is 200. schema: type: integer minimum: 1 @@ -623,13 +661,21 @@ paths: - name: cursor in: query required: false - description: Parameter to specify the pagination cursor. Use the cursor value returned from the previous response to get the next page of results. Leave empty for the first page. + description: >- + Parameter to specify the pagination cursor. Use the cursor value + returned from the previous response to get the next page of results. + Leave empty for the first page. schema: type: string - name: with_nested_markets in: query required: false - description: Parameter to specify if nested markets should be included in the response. When true, each event will include a 'markets' field containing a list of Market objects associated with that event. Historical markets settled before the historical cutoff will not be included. + description: >- + Parameter to specify if nested markets should be included in the + response. When true, each event will include a 'markets' field + containing a list of Market objects associated with that event. + Historical markets settled before the historical cutoff will not be + included. schema: type: boolean default: false @@ -645,23 +691,33 @@ paths: - name: status in: query required: false - description: Filter by event status. Possible values are 'unopened', 'open', 'closed', 'settled'. Leave empty to return events with any status. + description: >- + Filter by event status. Possible values are 'unopened', 'open', + 'closed', 'settled'. Leave empty to return events with any status. schema: type: string - enum: ['unopened', 'open', 'closed', 'settled'] + enum: + - unopened + - open + - closed + - settled - $ref: '#/components/parameters/SeriesTickerQuery' - $ref: '#/components/parameters/EventTickersQuery' - name: min_close_ts in: query required: false - description: Filter events with at least one market with close timestamp greater than this Unix timestamp (in seconds). + description: >- + Filter events with at least one market with close timestamp greater + than this Unix timestamp (in seconds). schema: type: integer format: int64 - name: min_updated_ts in: query required: false - description: Filter events with metadata updated after this Unix timestamp (in seconds). Use this to efficiently poll for changes. + description: >- + Filter events with metadata updated after this Unix timestamp (in + seconds). Use this to efficiently poll for changes. schema: type: integer format: int64 @@ -678,12 +734,14 @@ paths: description: Unauthorized '500': description: Internal server error - /events/multivariate: get: operationId: GetMultivariateEvents summary: Get Multivariate Events - description: 'Retrieve multivariate (combo) events. These are dynamically created events from multivariate event collections. Supports filtering by series and collection ticker.' + description: >- + Retrieve multivariate (combo) events. These are dynamically created + events from multivariate event collections. Supports filtering by series + and collection ticker. tags: - events parameters: @@ -699,20 +757,28 @@ paths: - name: cursor in: query required: false - description: Pagination cursor. Use the cursor value returned from the previous response to get the next page of results. + description: >- + Pagination cursor. Use the cursor value returned from the previous + response to get the next page of results. schema: type: string - $ref: '#/components/parameters/SeriesTickerQuery' - name: collection_ticker in: query required: false - description: Filter events by collection ticker. Returns only multivariate events belonging to the specified collection. Cannot be used together with series_ticker. + description: >- + Filter events by collection ticker. Returns only multivariate events + belonging to the specified collection. Cannot be used together with + series_ticker. schema: type: string - name: with_nested_markets in: query required: false - description: Parameter to specify if nested markets should be included in the response. When true, each event will include a 'markets' field containing a list of Market objects associated with that event. + description: >- + Parameter to specify if nested markets should be included in the + response. When true, each event will include a 'markets' field + containing a list of Market objects associated with that event. schema: type: boolean default: false @@ -729,13 +795,14 @@ paths: description: Unauthorized '500': description: Internal server error - /events/fee_changes: get: operationId: GetEventFeeChanges summary: Get Event Fee Changes - description: | - Event fees are an override layered on top of the parent series' fee structure. If `fee_type_override` and `fee_multiplier_override` are null, that indicates the override is cleared. + description: > + Event fees are an override layered on top of the parent series' fee + structure. If `fee_type_override` and `fee_multiplier_override` are + null, that indicates the override is cleared. tags: - events parameters: @@ -758,15 +825,20 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /events/{event_ticker}: get: operationId: GetEvent summary: Get Event - description: | - Endpoint for getting data about an event by its ticker. An event represents a real-world occurrence that can be traded on, such as an election, sports game, or economic indicator release. - Events contain one or more markets where users can place trades on different outcomes. - All events are accessible through this endpoint, even if their associated markets are older than the historical cutoff. + description: > + Endpoint for getting data about an event by its ticker. An event + represents a real-world occurrence that can be traded on, such as an + election, sports game, or economic indicator release. + + Events contain one or more markets where users can place trades on + different outcomes. + + All events are accessible through this endpoint, even if their + associated markets are older than the historical cutoff. tags: - events parameters: @@ -779,7 +851,11 @@ paths: - name: with_nested_markets in: query required: false - description: If true, markets are included within the event object. If false (default), markets are returned as a separate top-level field in the response. Historical markets settled before the historical cutoff will not be included. + description: >- + If true, markets are included within the event object. If false + (default), markets are returned as a separate top-level field in the + response. Historical markets settled before the historical cutoff + will not be included. schema: type: boolean default: false @@ -793,13 +869,12 @@ paths: $ref: '#/components/schemas/GetEventResponse' '400': description: Bad request - '404': - description: Event not found '401': description: Unauthorized + '404': + description: Event not found '500': description: Internal server error - /events/{event_ticker}/metadata: get: operationId: GetEventMetadata @@ -823,18 +898,19 @@ paths: $ref: '#/components/schemas/GetEventMetadataResponse' '400': description: Bad request - '404': - description: Event not found '401': description: Unauthorized + '404': + description: Event not found '500': description: Internal server error - /series/{series_ticker}/events/{ticker}/forecast_percentile_history: get: operationId: GetEventForecastPercentilesHistory summary: Get Event Forecast Percentile History - description: Endpoint for getting the historical raw and formatted forecast numbers for an event at specific percentiles. + description: >- + Endpoint for getting the historical raw and formatted forecast numbers + for an event at specific percentiles. tags: - events security: @@ -885,32 +961,44 @@ paths: - name: period_interval in: query required: true - description: Specifies the length of each forecast period, in minutes. 0 for 5-second intervals, or 1, 60, or 1440 for minute-based intervals. + description: >- + Specifies the length of each forecast period, in minutes. 0 for + 5-second intervals, or 1, 60, or 1440 for minute-based intervals. schema: type: integer format: int32 - enum: [0, 1, 60, 1440] + enum: + - 0 + - 1 + - 60 + - 1440 responses: '200': description: Event forecast percentile history retrieved successfully content: application/json: schema: - $ref: '#/components/schemas/GetEventForecastPercentilesHistoryResponse' + $ref: >- + #/components/schemas/GetEventForecastPercentilesHistoryResponse '400': description: Bad request '401': description: Unauthorized '500': description: Internal server error - /portfolio/orders: get: operationId: GetOrders summary: Get Orders - description: | - Restricts the response to orders that have a certain status: resting, canceled, or executed. - Orders that have been canceled or fully executed before the historical cutoff are only available via `GET /historical/orders`. Resting orders will always be available through this endpoint. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. + description: > + Restricts the response to orders that have a certain status: resting, + canceled, or executed. + + Orders that have been canceled or fully executed before the historical + cutoff are only available via `GET /historical/orders`. Resting orders + will always be available through this endpoint. See [Historical + Data](https://docs.kalshi.com/getting_started/historical_data) for + details. tags: - orders security: @@ -939,16 +1027,19 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/orders/{order_id}: get: operationId: GetOrder summary: Get Order description: ' Endpoint for getting a single order.' x-mint: - content: | + content: > - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - orders @@ -971,7 +1062,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/orders/queue_positions: get: operationId: GetOrderQueuePositions @@ -1008,7 +1098,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/orders/{order_id}/queue_position: get: operationId: GetOrderQueuePosition @@ -1035,12 +1124,16 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/events/orders: post: operationId: CreateOrderV2 summary: Create Order (V2) - description: 'Endpoint for submitting event-market orders using the V2 request/response shape (single-book `bid`/`ask` side and fixed-point dollar prices). The legacy `/portfolio/orders` endpoint will be deprecated no earlier than May 6, 2026 — clients should migrate to this path.' + description: >- + Endpoint for submitting event-market orders using the V2 + request/response shape (single-book `bid`/`ask` side and fixed-point + dollar prices). The legacy `/portfolio/orders` endpoint will be + deprecated no earlier than May 6, 2026 — clients should migrate to this + path. tags: - orders security: @@ -1070,16 +1163,24 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/events/orders/batched: post: operationId: BatchCreateOrdersV2 summary: Batch Create Orders (V2) - description: 'Endpoint for submitting a batch of event-market orders using the V2 request/response shape. The maximum batch size scales with your tier''s write budget — see [Rate Limits and Tiers](/getting_started/rate_limits).' + description: >- + Endpoint for submitting a batch of event-market orders using the V2 + request/response shape. The maximum batch size scales with your tier's + write budget — see [Rate Limits and + Tiers](/getting_started/rate_limits). x-mint: - content: | + content: > - **Rate limit:** 10 tokens per order in the batch — billed per item, so total cost for a batch of N orders is N × 10. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 10 tokens per order in the batch — billed per item, so + total cost for a batch of N orders is N × 10. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - orders @@ -1108,15 +1209,22 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - delete: operationId: BatchCancelOrdersV2 summary: Batch Cancel Orders (V2) - description: 'Endpoint for cancelling a batch of event-market orders using the V2 response shape. The maximum batch size scales with your tier''s write budget — see [Rate Limits and Tiers](/getting_started/rate_limits).' + description: >- + Endpoint for cancelling a batch of event-market orders using the V2 + response shape. The maximum batch size scales with your tier's write + budget — see [Rate Limits and Tiers](/getting_started/rate_limits). x-mint: - content: | + content: > - **Rate limit:** 2 tokens per order in the batch — billed per item, so total cost for a batch of N cancels is N × 2. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per order in the batch — billed per item, so + total cost for a batch of N cancels is N × 2. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - orders @@ -1145,16 +1253,22 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/events/orders/{order_id}: delete: operationId: CancelOrderV2 summary: Cancel Order (V2) - description: 'Endpoint for cancelling event-market orders using the V2 response shape. Returns `{order_id, client_order_id, reduced_by}` rather than a full order object.' + description: >- + Endpoint for cancelling event-market orders using the V2 response shape. + Returns `{order_id, client_order_id, reduced_by}` rather than a full + order object. x-mint: - content: | + content: > - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - orders @@ -1185,16 +1299,25 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/events/orders/{order_id}/amend: post: operationId: AmendOrderV2 summary: Amend Order (V2) - description: 'Endpoint for amending the price and/or max fillable count of an existing event-market order using the V2 request/response shape. The request `count` is the updated total/max fillable count, equal to already filled count plus desired resting remaining count. This behavior matches the v1 amend endpoints; only the request/response shape differs.' + description: >- + Endpoint for amending the price and/or max fillable count of an existing + event-market order using the V2 request/response shape. The request + `count` is the updated total/max fillable count, equal to already filled + count plus desired resting remaining count. This behavior matches the v1 + amend endpoints; only the request/response shape differs. x-mint: - content: | + content: > - Amending a resting order preserves queue position only when the amendment decreases size. All other amendments — like increasing size or changing price forfeit queue position and place the order at the back of the queue. + + Amending a resting order preserves queue position only when the + amendment decreases size. All other amendments — like increasing size + or changing price forfeit queue position and place the order at the + back of the queue. + tags: - orders @@ -1226,12 +1349,14 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/events/orders/{order_id}/decrease: post: operationId: DecreaseOrderV2 summary: Decrease Order (V2) - description: 'Endpoint for decreasing the remaining count of an existing event-market order using the V2 request/response shape. Exactly one of `reduce_by` or `reduce_to` must be provided.' + description: >- + Endpoint for decreasing the remaining count of an existing event-market + order using the V2 request/response shape. Exactly one of `reduce_by` or + `reduce_to` must be provided. tags: - orders security: @@ -1262,7 +1387,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/order_groups: get: operationId: GetOrderGroups @@ -1289,7 +1413,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/order_groups/create: post: operationId: CreateOrderGroup @@ -1320,7 +1443,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/order_groups/{order_group_id}: get: operationId: GetOrderGroup @@ -1375,7 +1497,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/order_groups/{order_group_id}/reset: put: operationId: ResetOrderGroup @@ -1410,7 +1531,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/order_groups/{order_group_id}/trigger: put: operationId: TriggerOrderGroup @@ -1445,7 +1565,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/order_groups/{order_group_id}/limit: put: operationId: UpdateOrderGroupLimit @@ -1481,13 +1600,14 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - - # Portfolio endpoints /portfolio/balance: get: operationId: GetBalance summary: Get Balance - description: "Endpoint for getting the balance and portfolio value of a member. Both values are returned in cents. This endpoint also accepts API keys with the 'read::portfolio_balance' scope." + description: >- + Endpoint for getting the balance and portfolio value of a member. Both + values are returned in cents. This endpoint also accepts API keys with + the 'read::portfolio_balance' scope. tags: - portfolio security: @@ -1496,6 +1616,7 @@ paths: kalshiAccessTimestamp: [] parameters: - $ref: '#/components/parameters/SubaccountQueryDefaultPrimary' + - $ref: '#/components/parameters/ExchangeIndexQuery' responses: '200': description: Balance retrieved successfully @@ -1507,12 +1628,15 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/subaccounts: post: operationId: CreateSubaccount summary: Create Subaccount - description: 'Creates a new subaccount for the authenticated user. This endpoint is currently only available to institutions and market makers. Subaccounts are numbered sequentially starting from 1. Maximum 63 numbered subaccounts per user (64 including the primary account).' + description: >- + Creates a new subaccount for the authenticated user. This endpoint is + currently only available to institutions and market makers. Subaccounts + are numbered sequentially starting from 1. Maximum 63 numbered + subaccounts per user (64 including the primary account). tags: - portfolio security: @@ -1538,12 +1662,15 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/subaccounts/transfer: post: operationId: ApplySubaccountTransfer summary: Transfer Between Subaccounts - description: 'Transfers funds between the authenticated user''s subaccounts. Use 0 for the primary account, or 1-63 for numbered subaccounts. Set exchange_index to apply the transfer on a specific exchange shard (defaults to 0).' + description: >- + Transfers funds between the authenticated user's subaccounts. Use 0 for + the primary account, or 1-63 for numbered subaccounts. Set + exchange_index to apply the transfer on a specific exchange shard + (defaults to 0). tags: - portfolio security: @@ -1569,16 +1696,20 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/subaccounts/positions/transfer: post: + x-excluded: true operationId: ApplySubaccountPositionTransfer summary: Transfer Position Between Subaccounts description: >- - Moves an existing position between two of the authenticated user's own subaccounts. - Use 0 for the primary account, or 1-63 for numbered subaccounts. - The transfer is idempotent on `client_transfer_id`: retrying with the same value returns 409. - `price_cents` is the per-contract transfer price — see the [Subaccounts](/getting_started/subaccounts) page for how it sets cost basis and P&L. + Moves an existing position between two of the authenticated user's own + subaccounts. Use 0 for the primary account, or 1-63 for numbered + subaccounts. The transfer is idempotent on `client_transfer_id`: + retrying with the same value returns 409. `price` is the per-contract + transfer price as a fixed-point dollar string, and is always the + YES-side price regardless of `side` — the receiving subaccount pays the + sending subaccount for the position at that price. See the + [Subaccounts](/getting_started/subaccounts) page for worked examples. tags: - portfolio security: @@ -1606,12 +1737,11 @@ paths: $ref: '#/components/responses/ConflictError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/subaccounts/balances: get: operationId: GetSubaccountBalances summary: Get All Subaccount Balances - description: 'Gets balances for all subaccounts including the primary account.' + description: Gets balances for all subaccounts including the primary account. tags: - portfolio security: @@ -1629,12 +1759,13 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/subaccounts/transfers: get: operationId: GetSubaccountTransfers summary: Get Subaccount Transfers - description: 'Gets a paginated list of all transfers between subaccounts for the authenticated user.' + description: >- + Gets a paginated list of all transfers between subaccounts for the + authenticated user. tags: - portfolio security: @@ -1655,12 +1786,13 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/subaccounts/netting: put: operationId: UpdateSubaccountNetting summary: Update Subaccount Netting - description: 'Updates the netting enabled setting for a specific subaccount. Use 0 for the primary account, or 1-63 for numbered subaccounts.' + description: >- + Updates the netting enabled setting for a specific subaccount. Use 0 for + the primary account, or 1-63 for numbered subaccounts. tags: - portfolio security: @@ -1685,7 +1817,7 @@ paths: get: operationId: GetSubaccountNetting summary: Get Subaccount Netting - description: 'Gets the netting enabled settings for all subaccounts.' + description: Gets the netting enabled settings for all subaccounts. tags: - portfolio security: @@ -1703,12 +1835,14 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/positions: get: operationId: GetPositions summary: Get Positions - description: 'Restricts the positions to those with any of following fields with non-zero values, as a comma separated list. The following values are accepted: position, total_traded' + description: >- + Restricts the positions to those with any of following fields with + non-zero values, as a comma separated list. The following values are + accepted: position, total_traded tags: - portfolio security: @@ -1735,7 +1869,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/settlements: get: operationId: GetSettlements @@ -1768,12 +1901,11 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/deposits: get: operationId: GetDeposits summary: Get Deposits - description: 'Endpoint for getting the member''s deposit history.' + description: Endpoint for getting the member's deposit history. tags: - portfolio security: @@ -1796,12 +1928,11 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/withdrawals: get: operationId: GetWithdrawals summary: Get Withdrawals - description: 'Endpoint for getting the member''s withdrawal history.' + description: Endpoint for getting the member's withdrawal history. tags: - portfolio security: @@ -1824,7 +1955,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/summary/total_resting_order_value: get: operationId: GetPortfolioRestingOrderTotalValue @@ -1842,19 +1972,24 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/GetPortfolioRestingOrderTotalValueResponse' + $ref: >- + #/components/schemas/GetPortfolioRestingOrderTotalValueResponse '401': $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/fills: get: operationId: GetFills summary: Get Fills - description: | - Endpoint for getting all fills for the member. A fill is when a trade you have is matched. - Fills that occurred before the historical cutoff are only available via `GET /historical/fills`. See [Historical Data](https://docs.kalshi.com/getting_started/historical_data) for details. + description: > + Endpoint for getting all fills for the member. A fill is when a trade + you have is matched. + + Fills that occurred before the historical cutoff are only available via + `GET /historical/fills`. See [Historical + Data](https://docs.kalshi.com/getting_started/historical_data) for + details. tags: - portfolio security: @@ -1882,7 +2017,6 @@ paths: description: Unauthorized '500': description: Internal server error - /communications/id: get: operationId: GetCommunicationsID @@ -1905,7 +2039,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /communications/block-trade-proposals: get: operationId: GetBlockTradeProposals @@ -1922,7 +2055,9 @@ paths: - $ref: '#/components/parameters/MarketTickerQuery' - name: limit in: query - description: Parameter to specify the number of results per page. Defaults to 100. + description: >- + Parameter to specify the number of results per page. Defaults to + 100. schema: type: integer format: int32 @@ -1947,7 +2082,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - post: operationId: ProposeBlockTrade summary: Propose Block Trade @@ -1979,7 +2113,6 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - /communications/block-trade-proposals/{block_trade_proposal_id}/accept: post: operationId: AcceptBlockTradeProposal @@ -2015,7 +2148,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/rfqs: get: operationId: GetRFQs @@ -2034,7 +2166,9 @@ paths: - $ref: '#/components/parameters/SubaccountQuery' - name: limit in: query - description: Parameter to specify the number of results per page. Defaults to 100. + description: >- + Parameter to specify the number of results per page. Defaults to + 100. schema: type: integer format: int32 @@ -2059,7 +2193,7 @@ paths: $ref: '#/components/schemas/UserFilter' x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: - validate: "omitempty,oneof=self" + validate: omitempty,oneof=self responses: '200': description: RFQs retrieved successfully @@ -2071,7 +2205,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - post: operationId: CreateRFQ summary: Create RFQ @@ -2103,7 +2236,6 @@ paths: $ref: '#/components/responses/ConflictError' '500': $ref: '#/components/responses/InternalServerError' - /communications/rfqs/{rfq_id}: get: operationId: GetRFQ @@ -2130,7 +2262,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - delete: operationId: DeleteRFQ summary: Delete RFQ @@ -2152,16 +2283,54 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/rfqs/{rfq_id}/quotes/{quote_id}: + get: + operationId: GetRFQQuote + summary: Get RFQ Quote + description: ' Endpoint for getting a particular quote scoped to its RFQ.' + x-mint: + content: > + + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + + + tags: + - communications + security: + - kalshiAccessKey: [] + kalshiAccessSignature: [] + kalshiAccessTimestamp: [] + parameters: + - $ref: '#/components/parameters/RfqIdPath' + - $ref: '#/components/parameters/QuoteIdPath' + responses: + '200': + description: Quote retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/GetQuoteResponse' + '401': + $ref: '#/components/responses/UnauthorizedError' + '404': + $ref: '#/components/responses/NotFoundError' + '500': + $ref: '#/components/responses/InternalServerError' delete: operationId: DeleteRFQQuote summary: Delete RFQ Quote description: ' Endpoint for deleting a quote scoped to its RFQ, which means it can no longer be accepted.' x-mint: - content: | + content: > - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - communications @@ -2181,7 +2350,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/rfqs/{rfq_id}/quotes/{quote_id}/accept: put: operationId: AcceptRFQQuote @@ -2213,7 +2381,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/rfqs/{rfq_id}/quotes/{quote_id}/confirm: put: operationId: ConfirmRFQQuote @@ -2243,7 +2410,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/quotes: get: operationId: GetQuotes @@ -2259,19 +2425,25 @@ paths: - $ref: '#/components/parameters/CursorQuery' - name: min_ts in: query - description: Restricts the response to quotes last updated after a timestamp, formatted as a Unix Timestamp + description: >- + Restricts the response to quotes last updated after a timestamp, + formatted as a Unix Timestamp schema: type: integer format: int64 - name: max_ts in: query - description: Restricts the response to quotes last updated before a timestamp, formatted as a Unix Timestamp + description: >- + Restricts the response to quotes last updated before a timestamp, + formatted as a Unix Timestamp schema: type: integer format: int64 - name: limit in: query - description: Parameter to specify the number of results per page. Defaults to 500. + description: >- + Parameter to specify the number of results per page. Defaults to + 500. schema: type: integer format: int32 @@ -2299,16 +2471,18 @@ paths: $ref: '#/components/schemas/UserFilter' x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: - validate: "omitempty,oneof=self" + validate: omitempty,oneof=self - name: rfq_user_filter in: query required: false - description: Filter for quotes responding to RFQs created by the authenticated user. + description: >- + Filter for quotes responding to RFQs created by the authenticated + user. schema: $ref: '#/components/schemas/UserFilter' x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: - validate: "omitempty,oneof=self" + validate: omitempty,oneof=self - name: rfq_creator_user_id in: query description: Filter quotes by RFQ creator user ID @@ -2339,15 +2513,18 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - post: operationId: CreateQuote summary: Create Quote description: ' Endpoint for creating a quote in response to an RFQ' x-mint: - content: | + content: > - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - communications @@ -2374,16 +2551,30 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /communications/quotes/{quote_id}: get: operationId: GetQuote summary: Get Quote - description: ' Endpoint for getting a particular quote' + deprecated: true + description: >- + DEPRECATED: Use GET /communications/rfqs/{rfq_id}/quotes/{quote_id} + instead. Endpoint for getting a particular quote. x-mint: - content: | + content: > + + + This endpoint is deprecated. Use `GET + /communications/rfqs/{rfq_id}/quotes/{quote_id}` instead. + + + + - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - communications @@ -2406,15 +2597,30 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - delete: operationId: DeleteQuote summary: Delete Quote - description: ' Endpoint for deleting a quote, which means it can no longer be accepted.' + deprecated: true + description: >- + DEPRECATED: Use DELETE /communications/rfqs/{rfq_id}/quotes/{quote_id} + instead. Endpoint for deleting a quote, which means it can no longer be + accepted. x-mint: - content: | + content: > + + + This endpoint is deprecated. Use `DELETE + /communications/rfqs/{rfq_id}/quotes/{quote_id}` instead. + + + + - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - communications @@ -2433,12 +2639,23 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/quotes/{quote_id}/accept: put: operationId: AcceptQuote summary: Accept Quote - description: ' Endpoint for accepting a quote. This will require the quoter to confirm' + deprecated: true + description: >- + DEPRECATED: Use PUT + /communications/rfqs/{rfq_id}/quotes/{quote_id}/accept instead. Endpoint + for accepting a quote. This will require the quoter to confirm. + x-mint: + content: > + + + This endpoint is deprecated. Use `PUT + /communications/rfqs/{rfq_id}/quotes/{quote_id}/accept` instead. + + tags: - communications security: @@ -2464,12 +2681,24 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /communications/quotes/{quote_id}/confirm: put: operationId: ConfirmQuote summary: Confirm Quote - description: ' Endpoint for confirming a quote. This will start a timer for order execution' + deprecated: true + description: >- + DEPRECATED: Use PUT + /communications/rfqs/{rfq_id}/quotes/{quote_id}/confirm instead. + Endpoint for confirming a quote. This will start a timer for order + execution. + x-mint: + content: > + + + This endpoint is deprecated. Use `PUT + /communications/rfqs/{rfq_id}/quotes/{quote_id}/confirm` instead. + + tags: - communications security: @@ -2493,8 +2722,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - - # Multivariate Event Collections endpoints /api_keys: get: operationId: GetApiKeys @@ -2517,7 +2744,6 @@ paths: description: Unauthorized '500': description: Internal server error - post: operationId: CreateApiKey summary: Create API Key @@ -2549,7 +2775,6 @@ paths: description: Forbidden - insufficient API usage level '500': description: Internal server error - /api_keys/generate: post: operationId: GenerateApiKey @@ -2580,7 +2805,6 @@ paths: description: Unauthorized '500': description: Internal server error - /api_keys/{api_key}: delete: operationId: DeleteApiKey @@ -2610,12 +2834,14 @@ paths: description: API key not found '500': description: Internal server error - /account/limits: get: operationId: GetAccountApiLimits - summary: Get Account API Limits - description: 'Endpoint to retrieve the authenticated user''s Predictions API usage tier and token-bucket limits. Public Predictions tiers include Basic, Advanced, Expert, Premier, Paragon, Prime, and Prestige.' + summary: Get Account API Limits + description: >- + Endpoint to retrieve the authenticated user's Predictions API usage tier + and token-bucket limits. Public Predictions tiers include Basic, + Advanced, Expert, Premier, Paragon, Prime, and Prestige. tags: - account security: @@ -2633,16 +2859,23 @@ paths: description: Unauthorized '500': description: Internal server error - /account/api_usage_level/upgrade: post: operationId: UpgradeAccountApiUsageLevel summary: Upgrade Account API Usage Level - description: 'Grants a permanent Advanced API usage-level grant. Currently only the Predictions exchange instance is supported. Criteria: at least 1 of the user''s last 100 Predictions orders was created via API. Use Get Account API Limits to inspect the resulting usage tier and grants.' + description: >- + Grants a permanent Advanced API usage-level grant. Currently only the + Predictions exchange instance is supported. Criteria: at least 1 of the + user's last 100 Predictions orders was created via API. Use Get Account + API Limits to inspect the resulting usage tier and grants. x-mint: - content: | + content: > - **Rate limit:** 30 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 30 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - account @@ -2656,17 +2889,24 @@ paths: '401': description: Unauthorized '403': - description: No API-created order was found in the user's latest 100 Predictions orders + description: >- + No API-created order was found in the user's latest 100 Predictions + orders '429': - description: Rate limit exceeded. This endpoint costs 30 tokens and uses the Predictions Write bucket. + description: >- + Rate limit exceeded. This endpoint costs 30 tokens and uses the + Predictions Write bucket. '500': description: Internal server error - /account/api_usage_level/volume_progress: get: operationId: GetAccountApiUsageLevelVolumeProgress summary: Get Account API Usage Level Volume Progress - description: 'Returns the authenticated user''s latest cron-computed trading volume progress toward volume-based API usage tiers for the predictions (event_contract) lane. Volume figures are reported as fixed-point contract counts.' + description: >- + Returns the authenticated user's latest cron-computed trading volume + progress toward volume-based API usage tiers for the predictions + (event_contract) lane. Volume figures are reported as fixed-point + contract counts. tags: - account security: @@ -2679,17 +2919,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/GetAccountApiUsageLevelVolumeProgressResponse' + $ref: >- + #/components/schemas/GetAccountApiUsageLevelVolumeProgressResponse '401': description: Unauthorized '500': description: Internal server error - /account/endpoint_costs: get: operationId: GetAccountEndpointCosts summary: List Non-Default Endpoint Costs - description: 'Lists API v2 endpoints whose configured token cost differs from the default cost. Endpoints that use the default cost are omitted.' + description: >- + Lists API v2 endpoints whose configured token cost differs from the + default cost. Endpoints that use the default cost are omitted. tags: - account responses: @@ -2701,15 +2943,16 @@ paths: $ref: '#/components/schemas/GetAccountEndpointCostsResponse' '500': description: Internal server error - /search/tags_by_categories: get: operationId: GetTagsForSeriesCategories summary: Get Tags for Series Categories - description: | + description: > Retrieve tags organized by series categories. - This endpoint returns a mapping of series categories to their associated tags, which can be used for filtering and search functionality. + + This endpoint returns a mapping of series categories to their associated + tags, which can be used for filtering and search functionality. tags: - search responses: @@ -2723,15 +2966,17 @@ paths: description: Unauthorized '500': description: Internal server error - /search/filters_by_sport: get: operationId: GetFiltersForSports summary: Get Filters for Sports - description: | + description: > Retrieve available filters organized by sport. - This endpoint returns filtering options available for each sport, including scopes and competitions. It also provides an ordered list of sports for display purposes. + + This endpoint returns filtering options available for each sport, + including scopes and competitions. It also provides an ordered list of + sports for display purposes. tags: - search responses: @@ -2745,7 +2990,6 @@ paths: description: Unauthorized '500': description: Internal server error - /live_data/milestone/{milestone_id}: get: operationId: GetLiveDataByMilestone @@ -2764,9 +3008,11 @@ paths: in: query required: false description: >- - When true, includes player-level statistics in the live data response. - Supported for Pro Football, Pro Basketball, and College Men's Basketball milestones that have player ID mappings configured. - Has no effect for other sports or milestones without player mappings. + When true, includes player-level statistics in the live data + response. Supported for Pro Football, Pro Basketball, and College + Men's Basketball milestones that have player ID mappings configured. + Has no effect for other sports or milestones without player + mappings. schema: type: boolean default: false @@ -2781,12 +3027,14 @@ paths: description: Live data not found '500': description: Internal server error - /live_data/{type}/milestone/{milestone_id}: get: operationId: GetLiveData summary: Get Live Data (with type) - description: Get live data for a specific milestone. This is the legacy endpoint that requires a type path parameter. Prefer using `/live_data/milestone/{milestone_id}` instead. + description: >- + Get live data for a specific milestone. This is the legacy endpoint that + requires a type path parameter. Prefer using + `/live_data/milestone/{milestone_id}` instead. tags: - live-data parameters: @@ -2806,9 +3054,11 @@ paths: in: query required: false description: >- - When true, includes player-level statistics in the live data response. - Supported for Pro Football, Pro Basketball, and College Men's Basketball milestones that have player ID mappings configured. - Has no effect for other sports or milestones without player mappings. + When true, includes player-level statistics in the live data + response. Supported for Pro Football, Pro Basketball, and College + Men's Basketball milestones that have player ID mappings configured. + Has no effect for other sports or milestones without player + mappings. schema: type: boolean default: false @@ -2823,7 +3073,6 @@ paths: description: Live data not found '500': description: Internal server error - /live_data/batch: get: operationId: GetLiveDatas @@ -2847,9 +3096,11 @@ paths: in: query required: false description: >- - When true, includes player-level statistics in the live data response. - Supported for Pro Football, Pro Basketball, and College Men's Basketball milestones that have player ID mappings configured. - Has no effect for other sports or milestones without player mappings. + When true, includes player-level statistics in the live data + response. Supported for Pro Football, Pro Basketball, and College + Men's Basketball milestones that have player ID mappings configured. + Has no effect for other sports or milestones without player + mappings. schema: type: boolean default: false @@ -2862,15 +3113,16 @@ paths: $ref: '#/components/schemas/GetLiveDatasResponse' '500': description: Internal server error - /live_data/milestone/{milestone_id}/game_stats: get: operationId: GetGameStats summary: Get Game Stats description: >- - Get play-by-play game statistics for a specific milestone. - Supported sports: Pro Football, College Football, Pro Basketball, College Men's Basketball, College Women's Basketball, WNBA, Soccer, Pro Hockey, and Pro Baseball. - Returns null for unsupported milestone types or milestones without a Sportradar ID. + Get play-by-play game statistics for a specific milestone. Supported + sports: Pro Football, College Football, Pro Basketball, College Men's + Basketball, College Women's Basketball, WNBA, Soccer, Pro Hockey, and + Pro Baseball. Returns null for unsupported milestone types or milestones + without a Sportradar ID. tags: - live-data parameters: @@ -2891,8 +3143,6 @@ paths: description: Game stats not found '500': description: Internal server error - - /structured_targets: get: operationId: GetStructuredTargets @@ -2903,7 +3153,9 @@ paths: parameters: - name: ids in: query - description: Filter by specific structured target IDs. Pass multiple IDs by repeating the parameter (e.g. `?ids=uuid1&ids=uuid2`). + description: >- + Filter by specific structured target IDs. Pass multiple IDs by + repeating the parameter (e.g. `?ids=uuid1&ids=uuid2`). required: false schema: type: array @@ -2921,7 +3173,9 @@ paths: example: basketball_player - name: competition in: query - description: 'Filter by competition. Matches against the league, conference, division, or tour in the structured target details.' + description: >- + Filter by competition. Matches against the league, conference, + division, or tour in the structured target details. required: false schema: type: string @@ -2953,7 +3207,6 @@ paths: description: Unauthorized '500': description: Internal server error - /structured_targets/{structured_target_id}: get: operationId: GetStructuredTarget @@ -2981,7 +3234,6 @@ paths: description: Not found '500': description: Internal server error - /milestones/{milestone_id}: get: operationId: GetMilestone @@ -3011,7 +3263,6 @@ paths: description: Not Found '500': description: Internal Server Error - /milestones: get: operationId: GetMilestones @@ -3037,14 +3288,18 @@ paths: format: date-time - name: category in: query - description: 'Filter by milestone category. E.g. Sports, Elections, Esports, Crypto.' + description: >- + Filter by milestone category. E.g. Sports, Elections, Esports, + Crypto. required: false schema: type: string example: Sports - name: competition in: query - description: 'Filter by competition. E.g. Pro Football, Pro Basketball (M), Pro Baseball, Pro Hockey, College Football.' + description: >- + Filter by competition. E.g. Pro Football, Pro Basketball (M), Pro + Baseball, Pro Hockey, College Football. required: false schema: type: string @@ -3057,7 +3312,10 @@ paths: type: string - name: type in: query - description: 'Filter by milestone type. E.g. football_game, basketball_game, soccer_tournament_multi_leg, baseball_game, hockey_match, political_race.' + description: >- + Filter by milestone type. E.g. football_game, basketball_game, + soccer_tournament_multi_leg, baseball_game, hockey_match, + political_race. required: false schema: type: string @@ -3070,14 +3328,18 @@ paths: type: string - name: cursor in: query - description: Pagination cursor. Use the cursor value returned from the previous response to get the next page of results + description: >- + Pagination cursor. Use the cursor value returned from the previous + response to get the next page of results required: false schema: type: string - name: min_updated_ts in: query required: false - description: Filter milestones with metadata updated after this Unix timestamp (in seconds). Use this to efficiently poll for changes. + description: >- + Filter milestones with metadata updated after this Unix timestamp + (in seconds). Use this to efficiently poll for changes. schema: type: integer format: int64 @@ -3094,8 +3356,6 @@ paths: description: Unauthorized '500': description: Internal Server Error - - # Communications endpoints /multivariate_event_collections/{collection_ticker}: get: operationId: GetMultivariateEventCollection @@ -3126,7 +3386,10 @@ paths: post: operationId: CreateMarketInMultivariateEventCollection summary: Create Market In Multivariate Event Collection - description: 'Endpoint for creating an individual market in a multivariate event collection. This endpoint must be hit at least once before trading or looking up a market. Users are limited to 5000 creations per week.' + description: >- + Endpoint for creating an individual market in a multivariate event + collection. This endpoint must be hit at least once before trading or + looking up a market. Users are limited to 5000 creations per week. tags: - multivariate security: @@ -3145,14 +3408,16 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/CreateMarketInMultivariateEventCollectionRequest' + $ref: >- + #/components/schemas/CreateMarketInMultivariateEventCollectionRequest responses: '200': description: Market created successfully content: application/json: schema: - $ref: '#/components/schemas/CreateMarketInMultivariateEventCollectionResponse' + $ref: >- + #/components/schemas/CreateMarketInMultivariateEventCollectionResponse '400': $ref: '#/components/responses/BadRequestError' '401': @@ -3161,7 +3426,6 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /multivariate_event_collections: get: operationId: GetMultivariateEventCollections @@ -3172,10 +3436,15 @@ paths: parameters: - name: status in: query - description: Only return collections of a certain status. Can be unopened, open, or closed. + description: >- + Only return collections of a certain status. Can be unopened, open, + or closed. schema: type: string - enum: [unopened, open, closed] + enum: + - unopened + - open + - closed - name: associated_event_ticker in: query description: Only return collections associated with a particular event ticker. @@ -3196,7 +3465,11 @@ paths: maximum: 200 - name: cursor in: query - description: The Cursor represents a pointer to the next page of records in the pagination. This optional parameter, when filled, should be filled with the cursor string returned in a previous request to this end-point. + description: >- + The Cursor represents a pointer to the next page of records in the + pagination. This optional parameter, when filled, should be filled + with the cursor string returned in a previous request to this + end-point. schema: type: string responses: @@ -3210,21 +3483,33 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /multivariate_event_collections/{collection_ticker}/lookup: put: operationId: LookupTickersForMarketInMultivariateEventCollection summary: Lookup Tickers For Market In Multivariate Event Collection deprecated: true - description: 'DEPRECATED: This endpoint predates RFQs and should not be used for new integrations. Endpoint for looking up an individual market in a multivariate event collection. If CreateMarketInMultivariateEventCollection has never been hit with that variable combination before, this will return a 404.' + description: >- + DEPRECATED: This endpoint predates RFQs and should not be used for new + integrations. Endpoint for looking up an individual market in a + multivariate event collection. If + CreateMarketInMultivariateEventCollection has never been hit with that + variable combination before, this will return a 404. x-mint: - content: | + content: > - This endpoint is deprecated and predates RFQs. Do not use it for new integrations. + + This endpoint is deprecated and predates RFQs. Do not use it for new + integrations. + + - **Rate limit:** 2 tokens per request. See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 2 tokens per request. See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - multivariate @@ -3244,14 +3529,16 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/LookupTickersForMarketInMultivariateEventCollectionRequest' + $ref: >- + #/components/schemas/LookupTickersForMarketInMultivariateEventCollectionRequest responses: '200': description: Market looked up successfully content: application/json: schema: - $ref: '#/components/schemas/LookupTickersForMarketInMultivariateEventCollectionResponse' + $ref: >- + #/components/schemas/LookupTickersForMarketInMultivariateEventCollectionResponse '400': $ref: '#/components/responses/BadRequestError' '401': @@ -3271,17 +3558,29 @@ paths: - name: status in: query required: false - description: 'Status filter. Can be "all", "active", "upcoming", "closed", or "paid_out". Default is "all".' + description: >- + Status filter. Can be "all", "active", "upcoming", "closed", or + "paid_out". Default is "all". schema: type: string - enum: [all, active, upcoming, closed, paid_out] + enum: + - all + - active + - upcoming + - closed + - paid_out - name: type in: query required: false - description: 'Type filter. Can be "all", "liquidity", or "volume". Default is "all".' + description: >- + Type filter. Can be "all", "liquidity", or "volume". Default is + "all". schema: type: string - enum: [all, liquidity, volume] + enum: + - all + - liquidity + - volume - name: incentive_description in: query required: false @@ -3321,14 +3620,15 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' - /fcm/orders: get: operationId: GetFCMOrders summary: Get FCM Orders - description: | + description: > Endpoint for FCM members to get orders filtered by subtrader ID. - This endpoint requires FCM member access level and allows filtering orders by subtrader ID. + + This endpoint requires FCM member access level and allows filtering + orders by subtrader ID. tags: - fcm security: @@ -3339,7 +3639,9 @@ paths: - name: subtrader_id in: query required: true - description: Restricts the response to orders for a specific subtrader (FCM members only) + description: >- + Restricts the response to orders for a specific subtrader (FCM + members only) schema: type: string - $ref: '#/components/parameters/CursorQuery' @@ -3347,13 +3649,17 @@ paths: - $ref: '#/components/parameters/TickerQuery' - name: min_ts in: query - description: Restricts the response to orders after a timestamp, formatted as a Unix Timestamp + description: >- + Restricts the response to orders after a timestamp, formatted as a + Unix Timestamp schema: type: integer format: int64 - name: max_ts in: query - description: Restricts the response to orders before a timestamp, formatted as a Unix Timestamp + description: >- + Restricts the response to orders before a timestamp, formatted as a + Unix Timestamp schema: type: integer format: int64 @@ -3362,7 +3668,10 @@ paths: description: Restricts the response to orders that have a certain status schema: type: string - enum: [resting, canceled, executed] + enum: + - resting + - canceled + - executed - name: limit in: query description: Parameter to specify the number of results per page. Defaults to 100 @@ -3385,14 +3694,16 @@ paths: description: Not found '500': description: Internal server error - /fcm/positions: get: operationId: GetFCMPositions summary: Get FCM Positions - description: | - Endpoint for FCM members to get market positions filtered by subtrader ID. - This endpoint requires FCM member access level and allows filtering positions by subtrader ID. + description: > + Endpoint for FCM members to get market positions filtered by subtrader + ID. + + This endpoint requires FCM member access level and allows filtering + positions by subtrader ID. tags: - fcm security: @@ -3403,7 +3714,9 @@ paths: - name: subtrader_id in: query required: true - description: Restricts the response to positions for a specific subtrader (FCM members only) + description: >- + Restricts the response to positions for a specific subtrader (FCM + members only) schema: type: string - name: ticker @@ -3420,7 +3733,9 @@ paths: x-go-type-skip-optional-pointer: true - name: count_filter in: query - description: Restricts the positions to those with any of following fields with non-zero values, as a comma separated list + description: >- + Restricts the positions to those with any of following fields with + non-zero values, as a comma separated list schema: type: string - name: settlement_status @@ -3428,7 +3743,10 @@ paths: description: Settlement status of the markets to return. Defaults to unsettled schema: type: string - enum: [all, unsettled, settled] + enum: + - all + - unsettled + - settled - name: limit in: query description: Parameter to specify the number of results per page. Defaults to 100 @@ -3438,7 +3756,9 @@ paths: maximum: 1000 - name: cursor in: query - description: The Cursor represents a pointer to the next page of records in the pagination + description: >- + The Cursor represents a pointer to the next page of records in the + pagination schema: type: string responses: @@ -3456,18 +3776,27 @@ paths: description: Not found '500': description: Internal server error - /historical/cutoff: get: operationId: GetHistoricalCutoff summary: Get Historical Cutoff Timestamps - description: | - Returns the cutoff timestamps that define the boundary between **live** and **historical** data. + description: > + Returns the cutoff timestamps that define the boundary between **live** + and **historical** data. + ## Cutoff fields - - `market_settled_ts` : Markets that **settled** before this timestamp, and their candlesticks, must be accessed via `GET /historical/markets` and `GET /historical/markets/{ticker}/candlesticks`. - - `trades_created_ts` : Trades that were **filled** before this timestamp must be accessed via `GET /historical/fills`. - - `orders_updated_ts` : Orders that were **canceled or fully executed** before this timestamp must be accessed via `GET /historical/orders`. Resting (active) orders are always available in `GET /portfolio/orders`. + + - `market_settled_ts` : Markets that **settled** before this timestamp, + and their candlesticks, must be accessed via `GET /historical/markets` + and `GET /historical/markets/{ticker}/candlesticks`. + + - `trades_created_ts` : Trades that were **filled** before this + timestamp must be accessed via `GET /historical/fills`. + + - `orders_updated_ts` : Orders that were **canceled or fully executed** + before this timestamp must be accessed via `GET /historical/orders`. + Resting (active) orders are always available in `GET /portfolio/orders`. tags: - historical responses: @@ -3479,7 +3808,6 @@ paths: $ref: '#/components/schemas/GetHistoricalCutoffResponse' '500': description: Internal server error - /historical/markets/{ticker}/candlesticks: get: operationId: GetMarketCandlesticksHistorical @@ -3497,26 +3825,35 @@ paths: - name: start_ts in: query required: true - description: Start timestamp (Unix timestamp). Candlesticks will include those ending on or after this time. + description: >- + Start timestamp (Unix timestamp). Candlesticks will include those + ending on or after this time. schema: type: integer format: int64 - name: end_ts in: query required: true - description: End timestamp (Unix timestamp). Candlesticks will include those ending on or before this time. + description: >- + End timestamp (Unix timestamp). Candlesticks will include those + ending on or before this time. schema: type: integer format: int64 - name: period_interval in: query required: true - description: Time period length of each candlestick in minutes. Valid values are 1 (1 minute), 60 (1 hour), or 1440 (1 day). + description: >- + Time period length of each candlestick in minutes. Valid values are + 1 (1 minute), 60 (1 hour), or 1440 (1 day). schema: type: integer - enum: [1, 60, 1440] + enum: + - 1 + - 60 + - 1440 x-oapi-codegen-extra-tags: - validate: "required,oneof=1 60 1440" + validate: required,oneof=1 60 1440 responses: '200': description: Candlesticks retrieved successfully @@ -3530,7 +3867,6 @@ paths: description: Not found '500': description: Internal server error - /historical/fills: get: operationId: GetFillsHistorical @@ -3562,12 +3898,11 @@ paths: $ref: '#/components/responses/NotFoundError' '500': description: Internal server error - /historical/orders: get: operationId: GetHistoricalOrders summary: Get Historical Orders - description: ' Endpoint for getting orders that have been archived to the historical database.' + description: ' Endpoint for getting orders that have been archived to the historical database.' tags: - historical security: @@ -3592,7 +3927,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /historical/trades: get: operationId: GetTradesHistorical @@ -3620,13 +3954,13 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /historical/markets: get: operationId: GetHistoricalMarkets summary: Get Historical Markets - description: | - Endpoint for getting markets that have been archived to the historical database. Filters are mutually exclusive. + description: > + Endpoint for getting markets that have been archived to the historical + database. Filters are mutually exclusive. tags: - historical parameters: @@ -3647,7 +3981,6 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /historical/markets/{ticker}: get: operationId: GetHistoricalMarket @@ -3668,7 +4001,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - components: securitySchemes: kalshiAccessKey: @@ -3686,7 +4018,6 @@ components: in: header name: KALSHI-ACCESS-TIMESTAMP description: Request timestamp in milliseconds - responses: BadRequestError: description: Bad request - invalid input @@ -3725,12 +4056,13 @@ components: schema: $ref: '#/components/schemas/ErrorResponse' RateLimitError: - description: 'Rate limit exceeded. The default cost is 10 tokens per request. Use GET /trade-api/v2/account/endpoint_costs to list non-default endpoint costs.' + description: >- + Rate limit exceeded. The default cost is 10 tokens per request. Use GET + /trade-api/v2/account/endpoint_costs to list non-default endpoint costs. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' - parameters: LimitQuery: name: limit @@ -3743,8 +4075,7 @@ components: maximum: 1000 default: 100 x-oapi-codegen-extra-tags: - validate: "omitempty,min=1,max=1000" - + validate: omitempty,min=1,max=1000 WithdrawalLimitQuery: name: limit in: query @@ -3756,8 +4087,7 @@ components: maximum: 500 default: 100 x-oapi-codegen-extra-tags: - validate: "omitempty,min=1,max=500" - + validate: omitempty,min=1,max=500 MarketLimitQuery: name: limit in: query @@ -3770,22 +4100,22 @@ components: default: 100 x-oapi-codegen-extra-tags: validate: omitempty,gte=0,lte=1000 - CursorQuery: name: cursor in: query - description: Pagination cursor. Use the cursor value returned from the previous response to get the next page of results. Leave empty for the first page. + description: >- + Pagination cursor. Use the cursor value returned from the previous + response to get the next page of results. Leave empty for the first + page. schema: type: string x-go-type-skip-optional-pointer: true - StatusQuery: name: status in: query description: Filter by status. Possible values depend on the endpoint. schema: type: string - OrderGroupIdPath: name: order_group_id in: path @@ -3793,7 +4123,6 @@ components: description: Order group ID schema: type: string - RfqIdPath: name: rfq_id in: path @@ -3801,7 +4130,6 @@ components: description: RFQ ID schema: type: string - QuoteIdPath: name: quote_id in: path @@ -3809,7 +4137,6 @@ components: description: Quote ID schema: type: string - MarketTickerQuery: name: market_ticker in: query @@ -3817,7 +4144,6 @@ components: schema: type: string x-go-type-skip-optional-pointer: true - TickerQuery: name: ticker in: query @@ -3825,15 +4151,15 @@ components: schema: type: string x-go-type-skip-optional-pointer: true - IsBlockTradeQuery: name: is_block_trade in: query - description: | - Filter trades by whether they are block trades. Omit to return all trades. Set to `true` to return only block trades. Set to `false` to return only non-block trades. + description: > + Filter trades by whether they are block trades. Omit to return all + trades. Set to `true` to return only block trades. Set to `false` to + return only non-block trades. schema: type: boolean - SingleEventTickerQuery: name: event_ticker in: query @@ -3841,7 +4167,6 @@ components: schema: type: string x-go-type-skip-optional-pointer: true - MultipleEventTickerQuery: name: event_ticker in: query @@ -3849,14 +4174,15 @@ components: schema: type: string x-go-type-skip-optional-pointer: true - 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: >- + 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. schema: type: string - PositionsLimitQuery: name: limit in: query @@ -3867,14 +4193,15 @@ components: minimum: 1 maximum: 1000 default: 100 - CountFilterQuery: name: count_filter in: query - description: Restricts the positions to those with any of following fields with non-zero values, as a comma separated list. The following values are accepted - position, total_traded + description: >- + Restricts the positions to those with any of following fields with + non-zero values, as a comma separated list. The following values are + accepted - position, total_traded schema: type: string - OrderIdQuery: name: order_id in: query @@ -3882,7 +4209,6 @@ components: schema: type: string x-go-type-skip-optional-pointer: true - MinTsQuery: name: min_ts in: query @@ -3890,7 +4216,6 @@ components: schema: type: integer format: int64 - MaxTsQuery: name: max_ts in: query @@ -3898,28 +4223,26 @@ components: schema: type: integer format: int64 - SubaccountQuery: name: subaccount in: query - description: Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, defaults to all subaccounts. + description: >- + Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, + defaults to all subaccounts. schema: type: integer - SubaccountQueryDefaultPrimary: name: subaccount in: query description: Subaccount number (0 for primary, 1-63 for subaccounts). Defaults to 0. schema: type: integer - ExchangeIndexQuery: name: exchange_index in: query schema: $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - OrderIdPath: name: order_id in: path @@ -3927,7 +4250,6 @@ components: description: Order ID schema: type: string - TickerPath: name: ticker in: path @@ -3935,7 +4257,6 @@ components: description: Market ticker schema: type: string - SeriesTickerQuery: name: series_ticker in: query @@ -3943,7 +4264,6 @@ components: schema: type: string x-go-type-skip-optional-pointer: true - MinCreatedTsQuery: name: min_created_ts in: query @@ -3951,7 +4271,6 @@ components: schema: type: integer format: int64 - MaxCreatedTsQuery: name: max_created_ts in: query @@ -3959,15 +4278,17 @@ components: schema: type: integer format: int64 - MinUpdatedTsQuery: name: min_updated_ts in: query - description: Return markets with metadata updated later than this Unix timestamp. Tracks non-trading changes only. Incompatible with any other filters except mve_filter=exclude. May be combined with series_ticker, which requires mve_filter=exclude. + description: >- + Return markets with metadata updated later than this Unix timestamp. + Tracks non-trading changes only. Incompatible with any other filters + except mve_filter=exclude. May be combined with series_ticker, which + requires mve_filter=exclude. schema: type: integer format: int64 - MaxCloseTsQuery: name: max_close_ts in: query @@ -3975,7 +4296,6 @@ components: schema: type: integer format: int64 - MinCloseTsQuery: name: min_close_ts in: query @@ -3983,7 +4303,6 @@ components: schema: type: integer format: int64 - MinSettledTsQuery: name: min_settled_ts in: query @@ -3991,7 +4310,6 @@ components: schema: type: integer format: int64 - MaxSettledTsQuery: name: max_settled_ts in: query @@ -3999,73 +4317,92 @@ components: schema: type: integer format: int64 - MarketStatusQuery: name: status in: query description: Filter by market status. Leave empty to return markets with any status. schema: type: string - enum: [unopened, open, paused, closed, settled] - + enum: + - unopened + - open + - paused + - closed + - settled TickersQuery: name: tickers in: query - description: Filter by specific market tickers. Comma-separated list of market tickers to retrieve. + description: >- + Filter by specific market tickers. Comma-separated list of market + tickers to retrieve. schema: type: string - EventTickersQuery: name: tickers in: query - description: Filter by specific event tickers. Comma-separated list of event tickers to retrieve. + description: >- + Filter by specific event tickers. Comma-separated list of event tickers + to retrieve. schema: type: string - MveFilterQuery: name: mve_filter in: query - description: Filter by multivariate events (combos). 'only' returns only multivariate events, 'exclude' excludes multivariate events. + description: >- + Filter by multivariate events (combos). 'only' returns only multivariate + events, 'exclude' excludes multivariate events. schema: type: string - enum: ['only', 'exclude'] - + enum: + - only + - exclude MveHistoricalFilterQuery: name: mve_filter in: query - description: Filter by multivariate events (combos). By default, MVE markets are included. + description: >- + Filter by multivariate events (combos). By default, MVE markets are + included. schema: type: string - enum: ['exclude'] + enum: + - exclude nullable: true default: null - schemas: - # Common schemas FixedPointDollars: type: string - description: US dollar amount as a fixed-point decimal string with up to 6 decimal places of precision. This is the maximum supported precision; valid quote intervals for a given market are constrained by that market's price level structure. - example: "0.5600" - + description: >- + US dollar amount as a fixed-point decimal string with up to 6 decimal + places of precision. This is the maximum supported precision; valid + quote intervals for a given market are constrained by that market's + price level structure. + example: '0.5600' FixedPointCount: type: string - description: Fixed-point contract count string (2 decimals, e.g., "10.00"; referred to as "fp" in field names). Requests accept 0-2 decimal places (e.g., "10", "10.0", "10.00"); responses always emit 2 decimals. Fractional contract values (e.g., "2.50") are supported; the minimum granularity is 0.01 contracts. - example: "10.00" - + description: >- + Fixed-point contract count string (2 decimals, e.g., "10.00"; referred + to as "fp" in field names). Requests accept 0-2 decimal places (e.g., + "10", "10.0", "10.00"); responses always emit 2 decimals. Fractional + contract values (e.g., "2.50") are supported; the minimum granularity is + 0.01 contracts. + example: '10.00' ExchangeIndex: type: integer - description: "Identifier for an exchange shard. Defaults to 0 if unspecified. Note: currently only 0 supported." + description: >- + Identifier for an exchange shard. Defaults to 0 if unspecified. Note: + currently only 0 supported. example: 0 - FeeType: type: string - enum: [quadratic, quadratic_with_maker_fees, flat] + enum: + - quadratic + - quadratic_with_maker_fees + - flat x-enum-varnames: - FeeTypeQuadratic - FeeTypeQuadraticWithMakerFees - FeeTypeFlat description: Fee type for a series or scheduled fee override. - GetMarketCandlesticksHistoricalResponse: type: object required: @@ -4080,7 +4417,6 @@ components: description: Array of candlestick data points for the specified time range. items: $ref: '#/components/schemas/MarketCandlestickHistorical' - MarketCandlestickHistorical: type: object required: @@ -4097,20 +4433,29 @@ components: description: Unix timestamp for the inclusive end of the candlestick period. yes_bid: $ref: '#/components/schemas/BidAskDistributionHistorical' - description: Open, high, low, close (OHLC) data for YES buy offers on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) data for YES buy offers on the market + during the candlestick period. yes_ask: $ref: '#/components/schemas/BidAskDistributionHistorical' - description: Open, high, low, close (OHLC) data for YES sell offers on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) data for YES sell offers on the market + during the candlestick period. price: $ref: '#/components/schemas/PriceDistributionHistorical' - description: Open, high, low, close (OHLC) and more data for trade YES contract prices on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) and more data for trade YES contract + prices on the market during the candlestick period. volume: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought on the market during the candlestick period. + description: >- + String representation of the number of contracts bought on the + market during the candlestick period. open_interest: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought on the market by end of the candlestick period (end_period_ts). - + description: >- + String representation of the number of contracts bought on the + market by end of the candlestick period (end_period_ts). BidAskDistributionHistorical: type: object required: @@ -4121,17 +4466,24 @@ components: properties: open: $ref: '#/components/schemas/FixedPointDollars' - description: Offer price on the market at the start of the candlestick period (in dollars). + description: >- + Offer price on the market at the start of the candlestick period (in + dollars). low: $ref: '#/components/schemas/FixedPointDollars' - description: Lowest offer price on the market during the candlestick period (in dollars). + description: >- + Lowest offer price on the market during the candlestick period (in + dollars). high: $ref: '#/components/schemas/FixedPointDollars' - description: Highest offer price on the market during the candlestick period (in dollars). + description: >- + Highest offer price on the market during the candlestick period (in + dollars). close: $ref: '#/components/schemas/FixedPointDollars' - description: Offer price on the market at the end of the candlestick period (in dollars). - + description: >- + Offer price on the market at the end of the candlestick period (in + dollars). PriceDistributionHistorical: type: object required: @@ -4146,33 +4498,44 @@ components: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Price of the first trade during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Price of the first trade during the candlestick period (in dollars). + Null if no trades occurred. low: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Lowest trade price during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Lowest trade price during the candlestick period (in dollars). Null + if no trades occurred. high: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Highest trade price during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Highest trade price during the candlestick period (in dollars). Null + if no trades occurred. close: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Price of the last trade during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Price of the last trade during the candlestick period (in dollars). + Null if no trades occurred. mean: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Volume-weighted average price during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Volume-weighted average price during the candlestick period (in + dollars). Null if no trades occurred. previous: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Close price from the previous candlestick period (in dollars). Null if this is the first candlestick or no prior trade exists. - + description: >- + Close price from the previous candlestick period (in dollars). Null + if this is the first candlestick or no prior trade exists. ErrorResponse: type: object properties: @@ -4188,40 +4551,74 @@ components: service: type: string description: The name of the service that generated the error - SelfTradePreventionType: type: string - enum: ['taker_at_cross', 'maker'] - description: | - The self-trade prevention type for orders. `taker_at_cross` cancels the taker order when it would trade against another order from the same user; execution stops and any partial fills already matched are executed. `maker` cancels the resting maker order and continues matching. - + enum: + - taker_at_cross + - maker + description: > + The self-trade prevention type for orders. `taker_at_cross` cancels the + taker order when it would trade against another order from the same + user; execution stops and any partial fills already matched are + executed. `maker` cancels the resting maker order and continues + matching. BookSide: type: string - enum: ['bid', 'ask'] - description: 'Side of the book for an order or trade. For event markets, this refers to the YES leg only: `bid` means buy YES, `ask` means sell YES. (Selling YES is economically equivalent to buying NO at `1 - price`, but this endpoint quotes everything from the YES side.)' - + enum: + - bid + - ask + description: >- + Side of the book for an order or trade. For event markets, this refers + to the YES leg only: `bid` means buy YES, `ask` means sell YES. (Selling + YES is economically equivalent to buying NO at `1 - price`, but this + endpoint quotes everything from the YES side.) OrderStatus: type: string - enum: ['resting', 'canceled', 'executed'] + enum: + - resting + - canceled + - executed description: The status of an order - ExchangeInstance: type: string - enum: ['event_contract', 'margined'] + enum: + - event_contract + - margined description: The exchange instance type - UserFilter: type: string - enum: ['self'] - x-enum-varnames: ['UserFilterSelf'] - description: Omit or leave empty to return all results. Use `self` to filter by the authenticated user. - + enum: + - self + x-enum-varnames: + - UserFilterSelf + description: >- + Omit or leave empty to return all results. Use `self` to filter by the + authenticated user. ApiKeyScope: type: string - enum: ['read', 'write', 'read::block_trade_accept', 'read::portfolio_balance', 'write::trade', 'write::transfer', 'write::block_trade_accept'] - x-enum-varnames: ['ApiKeyScopeRead', 'ApiKeyScopeWrite', 'ApiKeyScopeReadBlockTradeAccept', 'ApiKeyScopeReadPortfolioBalance', 'ApiKeyScopeWriteTrade', 'ApiKeyScopeWriteTransfer', 'ApiKeyScopeWriteBlockTradeAccept'] - description: Scope granted to an API key. Parent scopes grant broad access; for example, `read` grants all read endpoints and `write` grants all write endpoints. Child scopes such as `read::block_trade_accept`, `read::portfolio_balance`, `write::trade`, `write::transfer`, and `write::block_trade_accept` grant only their specific endpoint group and can be granted without the parent scope. - + enum: + - read + - write + - read::block_trade_accept + - read::portfolio_balance + - write::trade + - write::transfer + - write::block_trade_accept + x-enum-varnames: + - ApiKeyScopeRead + - ApiKeyScopeWrite + - ApiKeyScopeReadBlockTradeAccept + - ApiKeyScopeReadPortfolioBalance + - ApiKeyScopeWriteTrade + - ApiKeyScopeWriteTransfer + - ApiKeyScopeWriteBlockTradeAccept + description: >- + Scope granted to an API key. Parent scopes grant broad access; for + example, `read` grants all read endpoints and `write` grants all write + endpoints. Child scopes such as `read::block_trade_accept`, + `read::portfolio_balance`, `write::trade`, `write::transfer`, and + `write::block_trade_accept` grant only their specific endpoint group and + can be granted without the parent scope. ApiKey: type: object required: @@ -4245,8 +4642,10 @@ components: nullable: true minimum: 0 maximum: 63 - description: If set, the API key is restricted to this single sub-account and may only read and trade on it. Absent/null means the key is unrestricted. - + description: >- + If set, the API key is restricted to this single sub-account and may + only read and trade on it. Absent/null means the key is + unrestricted. GetApiKeysResponse: type: object required: @@ -4257,7 +4656,6 @@ components: description: List of all API keys associated with the user items: $ref: '#/components/schemas/ApiKey' - CreateApiKeyRequest: type: object required: @@ -4269,18 +4667,28 @@ components: description: Name for the API key. This helps identify the key's purpose public_key: type: string - description: RSA public key in PEM format. This will be used to verify signatures on API requests + description: >- + RSA public key in PEM format. This will be used to verify signatures + on API requests scopes: type: array - description: List of scopes to grant to the API key. If the broad `write` parent scope is included, `read` must also be included. Child scopes may be granted without the broad parent scope. Defaults to full access (`read`, `write`) if not provided. + description: >- + List of scopes to grant to the API key. If the broad `write` parent + scope is included, `read` must also be included. Child scopes may be + granted without the broad parent scope. Defaults to full access + (`read`, `write`) if not provided. items: $ref: '#/components/schemas/ApiKeyScope' subaccount: type: integer minimum: 0 maximum: 63 - description: If set, restricts the API key to a single sub-account (0-63) that you own. A restricted key may only read and trade on that sub-account; it cannot act on other sub-accounts, transfer funds between sub-accounts, or create sub-accounts. Omit to leave the key unrestricted. - + description: >- + If set, restricts the API key to a single sub-account (0-63) that + you own. A restricted key may only read and trade on that + sub-account; it cannot act on other sub-accounts, transfer funds + between sub-accounts, or create sub-accounts. Omit to leave the key + unrestricted. CreateApiKeyResponse: type: object required: @@ -4289,7 +4697,6 @@ components: api_key_id: type: string description: Unique identifier for the newly created API key - GenerateApiKeyRequest: type: object required: @@ -4300,15 +4707,23 @@ components: description: Name for the API key. This helps identify the key's purpose scopes: type: array - description: List of scopes to grant to the API key. If the broad `write` parent scope is included, `read` must also be included. Child scopes may be granted without the broad parent scope. Defaults to full access (`read`, `write`) if not provided. + description: >- + List of scopes to grant to the API key. If the broad `write` parent + scope is included, `read` must also be included. Child scopes may be + granted without the broad parent scope. Defaults to full access + (`read`, `write`) if not provided. items: $ref: '#/components/schemas/ApiKeyScope' subaccount: type: integer minimum: 0 maximum: 63 - description: If set, restricts the API key to a single sub-account (0-63) that you own. A restricted key may only read and trade on that sub-account; it cannot act on other sub-accounts, transfer funds between sub-accounts, or create sub-accounts. Omit to leave the key unrestricted. - + description: >- + If set, restricts the API key to a single sub-account (0-63) that + you own. A restricted key may only read and trade on that + sub-account; it cannot act on other sub-accounts, transfer funds + between sub-accounts, or create sub-accounts. Omit to leave the key + unrestricted. GenerateApiKeyResponse: type: object required: @@ -4320,8 +4735,9 @@ components: description: Unique identifier for the newly generated API key private_key: type: string - description: RSA private key in PEM format. This must be stored securely and cannot be retrieved again after this response - + description: >- + RSA private key in PEM format. This must be stored securely and + cannot be retrieved again after this response GetTagsForSeriesCategoriesResponse: type: object required: @@ -4334,7 +4750,6 @@ components: type: array items: type: string - ScopeList: type: object required: @@ -4345,7 +4760,6 @@ components: description: List of scopes items: type: string - SportFilterDetails: type: object required: @@ -4362,7 +4776,6 @@ components: description: Mapping of competitions to their scope lists additionalProperties: $ref: '#/components/schemas/ScopeList' - GetFiltersBySportsResponse: type: object required: @@ -4379,7 +4792,6 @@ components: description: Ordered list of sports for display items: type: string - BucketLimit: type: object description: | @@ -4403,7 +4815,6 @@ components: headroom that idle clients accumulate and can spend in a single pulse (e.g. write buckets at non-Basic tiers hold two seconds of budget). - GetAccountApiLimitsResponse: type: object required: @@ -4414,7 +4825,10 @@ components: properties: usage_tier: type: string - description: User's effective Predictions API usage tier for these limits (for example, basic, advanced, expert, premier, paragon, prime, or prestige). + description: >- + User's effective Predictions API usage tier for these limits (for + example, basic, advanced, expert, premier, paragon, prime, or + prestige). example: expert read: $ref: '#/components/schemas/BucketLimit' @@ -4422,10 +4836,12 @@ components: $ref: '#/components/schemas/BucketLimit' grants: type: array - description: The caller's active API usage level grants across exchange lanes, where each grant applies to its exchange_instance and usage_tier reflects the effective tier for the lane reported by this endpoint. + description: >- + The caller's active API usage level grants across exchange lanes, + where each grant applies to its exchange_instance and usage_tier + reflects the effective tier for the lane reported by this endpoint. items: $ref: '#/components/schemas/ApiUsageLevelGrant' - ApiUsageLevelGrant: type: object required: @@ -4437,17 +4853,22 @@ components: $ref: '#/components/schemas/ExchangeInstance' level: type: string - description: API usage level this grant confers (for example, expert, premier, paragon, prime, or prestige). + description: >- + API usage level this grant confers (for example, expert, premier, + paragon, prime, or prestige). example: prestige expires_ts: type: integer format: int64 nullable: true - description: Unix timestamp (seconds) when the grant expires. Absent for permanent grants. + description: >- + Unix timestamp (seconds) when the grant expires. Absent for + permanent grants. source: type: string - description: 'How the grant was created: "volume" (earned from trading volume) or "manual" (assigned by Kalshi).' - + description: >- + How the grant was created: "volume" (earned from trading volume) or + "manual" (assigned by Kalshi). GetAccountApiUsageLevelVolumeProgressResponse: type: object required: @@ -4455,10 +4876,12 @@ components: properties: volume_progress: type: array - description: Latest cron-computed trading volume progress toward volume-based API usage tiers for the predictions (event_contract) lane. Volume-based public tiers are Expert, Premier, Paragon, Prime, and Prestige. + description: >- + Latest cron-computed trading volume progress toward volume-based API + usage tiers for the predictions (event_contract) lane. Volume-based + public tiers are Expert, Premier, Paragon, Prime, and Prestige. items: $ref: '#/components/schemas/AccountApiUsageLevelVolumeProgress' - AccountApiUsageLevelVolumeProgress: type: object required: @@ -4469,14 +4892,16 @@ components: computed_ts: type: integer format: int64 - description: 'Unix timestamp (seconds) when this progress was computed; trailing_30d_volume_fp covers the trailing 30 days ending at this time.' + description: >- + Unix timestamp (seconds) when this progress was computed; + trailing_30d_volume_fp covers the trailing 30 days ending at this + time. trailing_30d_volume_fp: $ref: '#/components/schemas/FixedPointCount' goals: type: array items: $ref: '#/components/schemas/AccountApiUsageLevelVolumeGoal' - AccountApiUsageLevelVolumeGoal: type: object required: @@ -4492,7 +4917,6 @@ components: $ref: '#/components/schemas/FixedPointCount' keep_volume_goal_fp: $ref: '#/components/schemas/FixedPointCount' - EndpointTokenCost: type: object required: @@ -4508,8 +4932,9 @@ components: description: API route path for the endpoint. cost: type: integer - description: Configured token cost for an endpoint whose cost differs from the default cost. - + description: >- + Configured token cost for an endpoint whose cost differs from the + default cost. GetAccountEndpointCostsResponse: type: object required: @@ -4518,13 +4943,16 @@ components: properties: default_cost: type: integer - description: Default token cost applied to endpoints that are not listed in `endpoint_costs`. This is currently 10. + description: >- + Default token cost applied to endpoints that are not listed in + `endpoint_costs`. This is currently 10. endpoint_costs: type: array - description: API v2 endpoints whose configured token cost differs from `default_cost`. Endpoints that use the default cost are omitted. + description: >- + API v2 endpoints whose configured token cost differs from + `default_cost`. Endpoints that use the default cost are omitted. items: $ref: '#/components/schemas/EndpointTokenCost' - ExchangeStatus: type: object required: @@ -4533,24 +4961,36 @@ components: properties: exchange_active: type: boolean - description: False if the core Kalshi exchange is no longer taking any state changes at all. This includes but is not limited to trading, new users, and transfers. True unless we are under maintenance. + description: >- + False if the core Kalshi exchange is no longer taking any state + changes at all. This includes but is not limited to trading, new + users, and transfers. True unless we are under maintenance. trading_active: type: boolean - description: True if we are currently permitting trading on the exchange. This is true during trading hours and false outside exchange hours. Kalshi reserves the right to pause at any time in case issues are detected. + description: >- + True if we are currently permitting trading on the exchange. This is + true during trading hours and false outside exchange hours. Kalshi + reserves the right to pause at any time in case issues are detected. intra_exchange_transfers_active: type: boolean - description: True if intra-exchange transfers are currently permitted. False when transfers are temporarily blocked. + description: >- + True if intra-exchange transfers are currently permitted. False when + transfers are temporarily blocked. exchange_estimated_resume_time: type: string format: date-time - description: Estimated downtime for the current exchange maintenance window. However, this is not guaranteed and can be extended. + description: >- + Estimated downtime for the current exchange maintenance window. + However, this is not guaranteed and can be extended. nullable: true exchange_index_statuses: type: array - description: Status of each exchange index. The top-level fields above reflect the default exchange index (0). Absent when the per-index breakdown is unavailable. + description: >- + Status of each exchange index. The top-level fields above reflect + the default exchange index (0). Absent when the per-index breakdown + is unavailable. items: $ref: '#/components/schemas/ExchangeIndexStatus' - ExchangeIndexStatus: type: object required: @@ -4563,49 +5003,19 @@ components: $ref: '#/components/schemas/ExchangeIndex' exchange_active: type: boolean - description: False if this exchange index is no longer taking any state changes at all. True unless under maintenance. + description: >- + False if this exchange index is no longer taking any state changes + at all. True unless under maintenance. trading_active: type: boolean - description: True if trading is currently permitted on this exchange index. False outside exchange hours or during pauses. + description: >- + True if trading is currently permitted on this exchange index. False + outside exchange hours or during pauses. intra_exchange_transfers_active: type: boolean - description: True if intra-exchange transfers are currently permitted on this exchange index. False when transfers are temporarily blocked. - - GetExchangeAnnouncementsResponse: - type: object - required: - - announcements - properties: - announcements: - type: array - description: A list of exchange-wide announcements. - items: - $ref: '#/components/schemas/Announcement' - - Announcement: - type: object - required: - - type - - message - - delivery_time - - status - properties: - type: - type: string - enum: [info, warning, error] - description: The type of the announcement. - message: - type: string - description: The message contained within the announcement. - delivery_time: - type: string - format: date-time - description: The time the announcement was delivered. - status: - type: string - enum: [active, inactive] - description: The current status of this announcement. - + description: >- + True if intra-exchange transfers are currently permitted on this + exchange index. False when transfers are temporarily blocked. GetExchangeScheduleResponse: type: object required: @@ -4613,7 +5023,6 @@ components: properties: schedule: $ref: '#/components/schemas/Schedule' - Schedule: type: object required: @@ -4622,15 +5031,18 @@ components: properties: standard_hours: type: array - description: The standard operating hours of the exchange. All times are expressed in ET. Outside of these times trading will be unavailable. + description: >- + The standard operating hours of the exchange. All times are + expressed in ET. Outside of these times trading will be unavailable. items: $ref: '#/components/schemas/WeeklySchedule' maintenance_windows: type: array - description: Scheduled maintenance windows, during which the exchange may be unavailable. + description: >- + Scheduled maintenance windows, during which the exchange may be + unavailable. items: $ref: '#/components/schemas/MaintenanceWindow' - WeeklySchedule: type: object required: @@ -4651,7 +5063,9 @@ components: end_time: type: string format: date-time - description: End date and time for when this weekly schedule is no longer effective. + description: >- + End date and time for when this weekly schedule is no longer + effective. monday: type: array description: Trading hours for Monday. May contain multiple sessions. @@ -4687,7 +5101,6 @@ components: description: Trading hours for Sunday. May contain multiple sessions. items: $ref: '#/components/schemas/DailySchedule' - DailySchedule: type: object required: @@ -4700,7 +5113,6 @@ components: close_time: type: string description: Closing time in ET (Eastern Time) format HH:MM. - MaintenanceWindow: type: object required: @@ -4715,7 +5127,6 @@ components: type: string format: date-time description: End date and time of the maintenance window. - GetHistoricalCutoffResponse: type: object required: @@ -4726,19 +5137,25 @@ components: market_settled_ts: type: string format: date-time - description: | - Cutoff based on **market settlement time**. Markets and their candlesticks that settled before this timestamp must be accessed via `GET /historical/markets` and `GET /historical/markets/{ticker}/candlesticks`. + description: > + Cutoff based on **market settlement time**. Markets and their + candlesticks that settled before this timestamp must be accessed via + `GET /historical/markets` and `GET + /historical/markets/{ticker}/candlesticks`. trades_created_ts: type: string format: date-time - description: | - Cutoff based on **trade fill time**. Fills that occurred before this timestamp must be accessed via `GET /historical/fills`. + description: > + Cutoff based on **trade fill time**. Fills that occurred before this + timestamp must be accessed via `GET /historical/fills`. orders_updated_ts: type: string format: date-time - description: | - Cutoff based on **order cancellation or execution time**. Orders canceled or fully executed before this timestamp must be accessed via `GET /historical/orders`. Resting (active) orders are always available in `GET /portfolio/orders`. - + description: > + Cutoff based on **order cancellation or execution time**. Orders + canceled or fully executed before this timestamp must be accessed + via `GET /historical/orders`. Resting (active) orders are always + available in `GET /portfolio/orders`. GetUserDataTimestampResponse: type: object required: @@ -4748,7 +5165,6 @@ components: type: string format: date-time description: Timestamp when user data was last updated. - GetMarketCandlesticksResponse: type: object required: @@ -4763,7 +5179,6 @@ components: description: Array of candlestick data points for the specified time range. items: $ref: '#/components/schemas/MarketCandlestick' - GetEventCandlesticksResponse: type: object required: @@ -4778,7 +5193,9 @@ components: type: string market_candlesticks: type: array - description: Array of market candlestick arrays, one for each market in the event. + description: >- + Array of market candlestick arrays, one for each market in the + event. items: type: array items: @@ -4786,8 +5203,9 @@ components: adjusted_end_ts: type: integer format: int64 - description: Adjusted end timestamp if the requested candlesticks would be larger than maxAggregateCandidates. - + description: >- + Adjusted end timestamp if the requested candlesticks would be larger + than maxAggregateCandidates. BatchGetMarketCandlesticksResponse: type: object required: @@ -4798,7 +5216,6 @@ components: description: Array of market candlestick data, one entry per requested market. items: $ref: '#/components/schemas/MarketCandlesticksResponse' - MarketCandlesticksResponse: type: object required: @@ -4810,10 +5227,11 @@ components: description: Market ticker string (e.g., 'INXD-24JAN01'). candlesticks: type: array - description: Array of candlestick data points for the market. Includes an initial data point at the start timestamp when available. + description: >- + Array of candlestick data points for the market. Includes an initial + data point at the start timestamp when available. items: $ref: '#/components/schemas/MarketCandlestick' - MarketCandlestick: type: object required: @@ -4830,20 +5248,29 @@ components: description: Unix timestamp for the inclusive end of the candlestick period. yes_bid: $ref: '#/components/schemas/BidAskDistribution' - description: Open, high, low, close (OHLC) data for YES buy offers on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) data for YES buy offers on the market + during the candlestick period. yes_ask: $ref: '#/components/schemas/BidAskDistribution' - description: Open, high, low, close (OHLC) data for YES sell offers on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) data for YES sell offers on the market + during the candlestick period. price: $ref: '#/components/schemas/PriceDistribution' - description: Open, high, low, close (OHLC) and more data for trade YES contract prices on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) and more data for trade YES contract + prices on the market during the candlestick period. volume_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought on the market during the candlestick period. + description: >- + String representation of the number of contracts bought on the + market during the candlestick period. open_interest_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought on the market by end of the candlestick period (end_period_ts). - + description: >- + String representation of the number of contracts bought on the + market by end of the candlestick period (end_period_ts). BidAskDistribution: type: object required: @@ -4854,54 +5281,81 @@ components: properties: open_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Offer price on the market at the start of the candlestick period (in dollars). + description: >- + Offer price on the market at the start of the candlestick period (in + dollars). low_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Lowest offer price on the market during the candlestick period (in dollars). + description: >- + Lowest offer price on the market during the candlestick period (in + dollars). high_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Highest offer price on the market during the candlestick period (in dollars). + description: >- + Highest offer price on the market during the candlestick period (in + dollars). close_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Offer price on the market at the end of the candlestick period (in dollars). - + description: >- + Offer price on the market at the end of the candlestick period (in + dollars). PriceDistribution: type: object properties: open_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: First traded YES contract price on the market during the candlestick period (in dollars). May be null if there was no trade during the period. + description: >- + First traded YES contract price on the market during the candlestick + period (in dollars). May be null if there was no trade during the + period. low_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Lowest traded YES contract price on the market during the candlestick period (in dollars). May be null if there was no trade during the period. + description: >- + Lowest traded YES contract price on the market during the + candlestick period (in dollars). May be null if there was no trade + during the period. high_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Highest traded YES contract price on the market during the candlestick period (in dollars). May be null if there was no trade during the period. + description: >- + Highest traded YES contract price on the market during the + candlestick period (in dollars). May be null if there was no trade + during the period. close_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Last traded YES contract price on the market during the candlestick period (in dollars). May be null if there was no trade during the period. + description: >- + Last traded YES contract price on the market during the candlestick + period (in dollars). May be null if there was no trade during the + period. mean_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Mean traded YES contract price on the market during the candlestick period (in dollars). May be null if there was no trade during the period. + description: >- + Mean traded YES contract price on the market during the candlestick + period (in dollars). May be null if there was no trade during the + period. previous_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Last traded YES contract price on the market before the candlestick period (in dollars). May be null if there were no trades before the period. + description: >- + Last traded YES contract price on the market before the candlestick + period (in dollars). May be null if there were no trades before the + period. min_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Minimum close price of any market during the candlestick period (in dollars). + description: >- + Minimum close price of any market during the candlestick period (in + dollars). max_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Maximum close price of any market during the candlestick period (in dollars). - - # Live Data schemas + description: >- + Maximum close price of any market during the candlestick period (in + dollars). LiveData: type: object required: @@ -4919,7 +5373,6 @@ components: milestone_id: type: string description: Milestone ID - GetLiveDataResponse: type: object required: @@ -4927,7 +5380,6 @@ components: properties: live_data: $ref: '#/components/schemas/LiveData' - GetLiveDatasResponse: type: object required: @@ -4937,13 +5389,11 @@ components: type: array items: $ref: '#/components/schemas/LiveData' - GetGameStatsResponse: type: object properties: pbp: $ref: '#/components/schemas/PlayByPlay' - PlayByPlay: type: object description: Play-by-play data organized by period. @@ -4958,7 +5408,6 @@ components: items: type: object additionalProperties: true - IndexedBalance: type: object required: @@ -4969,7 +5418,6 @@ components: $ref: '#/components/schemas/ExchangeIndex' balance: $ref: '#/components/schemas/FixedPointDollars' - GetBalanceResponse: type: object required: @@ -4981,14 +5429,20 @@ components: balance: type: integer format: int64 - description: Member's available balance in cents. This represents the amount available for trading. + description: >- + Member's available balance in cents. This represents the amount + available for trading. balance_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Member's available balance as a fixed-point dollar string. This represents the amount available for trading. + description: >- + Member's available balance as a fixed-point dollar string. This + represents the amount available for trading. portfolio_value: type: integer format: int64 - description: Member's portfolio value in cents. This is the current value of all positions held. + description: >- + Member's portfolio value in cents. This is the current value of all + positions held. updated_ts: type: integer format: int64 @@ -4998,18 +5452,16 @@ components: items: $ref: '#/components/schemas/IndexedBalance' description: Balance broken down per exchange index. - CreateSubaccountRequest: type: object properties: exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' - description: "Identifier for an exchange shard. Defaults to 0 if unspecified." + description: Identifier for an exchange shard. Defaults to 0 if unspecified. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: - validate: "gte=0" - + validate: gte=0 CreateSubaccountResponse: type: object required: @@ -5018,7 +5470,6 @@ components: subaccount_number: type: integer description: The sequential number assigned to this subaccount (1-63). - ApplySubaccountTransferRequest: type: object required: @@ -5032,13 +5483,17 @@ components: format: uuid description: Unique client-provided transfer ID for idempotency. x-oapi-codegen-extra-tags: - validate: "required" + validate: required from_subaccount: type: integer - description: Source subaccount number (0 for primary, 1-63 for numbered subaccounts). + description: >- + Source subaccount number (0 for primary, 1-63 for numbered + subaccounts). to_subaccount: type: integer - description: Destination subaccount number (0 for primary, 1-63 for numbered subaccounts). + description: >- + Destination subaccount number (0 for primary, 1-63 for numbered + subaccounts). amount_cents: type: integer format: int64 @@ -5046,15 +5501,13 @@ components: exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' - description: "Identifier for an exchange shard. Defaults to 0 if unspecified." + description: Identifier for an exchange shard. Defaults to 0 if unspecified. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: - validate: "gte=0" - + validate: gte=0 ApplySubaccountTransferResponse: type: object description: Empty response indicating successful transfer. - ApplySubaccountPositionTransferRequest: type: object required: @@ -5064,50 +5517,62 @@ components: - market_ticker - side - count - - price_cents + - price properties: client_transfer_id: type: string format: uuid - description: Unique client-provided transfer ID for idempotency. Retrying with the same value returns 409. + description: >- + Unique client-provided transfer ID for idempotency. Retrying with + the same value returns 409. x-oapi-codegen-extra-tags: - validate: "required" + validate: required from_subaccount: type: integer nullable: true - description: Source subaccount number (0 for primary, 1-63 for numbered subaccounts). + description: >- + Source subaccount number (0 for primary, 1-63 for numbered + subaccounts). x-oapi-codegen-extra-tags: - validate: "required" + validate: required to_subaccount: type: integer nullable: true - description: Destination subaccount number (0 for primary, 1-63 for numbered subaccounts). + description: >- + Destination subaccount number (0 for primary, 1-63 for numbered + subaccounts). x-oapi-codegen-extra-tags: - validate: "required" + validate: required market_ticker: type: string - description: Ticker of the market whose position is being moved. The market must be on exchange shard 0; markets on any other shard are rejected. + description: >- + Ticker of the market whose position is being moved. The market must + be on exchange shard 0; markets on any other shard are rejected. x-oapi-codegen-extra-tags: - validate: "required" + validate: required side: type: string - enum: ["yes", "no"] + enum: + - 'yes' + - 'no' description: Side of the position to move. x-oapi-codegen-extra-tags: - validate: "required" + validate: required count: type: integer nullable: true description: Number of contracts to move (must be greater than 0). x-oapi-codegen-extra-tags: - validate: "required" - price_cents: - type: integer - nullable: true - description: Per-contract price in cents (0-100) used to set cost basis and realized P&L. - x-oapi-codegen-extra-tags: - validate: "required" - + validate: required + price: + $ref: '#/components/schemas/FixedPointDollars' + description: >- + Per-contract price in fixed-point dollars (0 to 1.00 inclusive): the + cash consideration the receiving subaccount pays the sending + subaccount for the position. Always the YES-side price, even when + `side` is `no`; a NO position transferred at `price` p carries a + per-contract NO-side value of 1.00 − p. + x-go-type-skip-optional-pointer: true ApplySubaccountPositionTransferResponse: type: object required: @@ -5116,7 +5581,6 @@ components: position_transfer_id: type: string description: Server-generated identifier for the position transfer. - GetSubaccountBalancesResponse: type: object required: @@ -5126,7 +5590,6 @@ components: type: array items: $ref: '#/components/schemas/SubaccountBalance' - SubaccountBalance: type: object required: @@ -5148,7 +5611,6 @@ components: type: integer format: int64 description: Unix timestamp of last balance update. - GetSubaccountTransfersResponse: type: object required: @@ -5161,7 +5623,6 @@ components: cursor: type: string description: Cursor for the next page of results. - SubaccountTransfer: type: object required: @@ -5195,23 +5656,30 @@ components: description: Exchange index the transfer was applied on. transfer_type: type: string - enum: [cash, position] - x-enum-varnames: [TransferTypeCash, TransferTypePosition] + enum: + - cash + - position + x-enum-varnames: + - TransferTypeCash + - TransferTypePosition description: Whether this row is a cash or position transfer. market_ticker: type: string description: Market ticker (position transfers only). side: type: string - enum: ["yes", "no"] + enum: + - 'yes' + - 'no' description: Position side (position transfers only). count: type: integer description: Number of contracts moved (position transfers only). - price_cents: - type: integer - description: Per-contract price in cents (position transfers only). - + price: + $ref: '#/components/schemas/FixedPointDollars' + description: >- + Per-contract transfer price in fixed-point dollars, always the + YES-side price (position transfers only). UpdateSubaccountNettingRequest: type: object required: @@ -5224,7 +5692,6 @@ components: enabled: type: boolean description: Whether netting is enabled for this subaccount. - GetSubaccountNettingResponse: type: object required: @@ -5234,12 +5701,12 @@ components: type: array items: $ref: '#/components/schemas/SubaccountNettingConfig' - SubaccountNettingConfig: type: object required: - subaccount_number - enabled + - exchange_index properties: subaccount_number: type: integer @@ -5247,8 +5714,9 @@ components: enabled: type: boolean description: Whether netting is enabled for this subaccount. - - # Portfolio schemas (specific to portfolio endpoints, not shared with IB) + exchange_index: + type: integer + description: Exchange index of the subaccount. GetSettlementsResponse: type: object required: @@ -5260,7 +5728,6 @@ components: $ref: '#/components/schemas/Settlement' cursor: type: string - Settlement: type: object required: @@ -5283,36 +5750,47 @@ components: description: The event ticker symbol of the market that was settled. market_result: type: string - enum: ['yes', 'no', 'scalar'] - description: The outcome of the market settlement. 'yes' = market resolved to YES, 'no' = market resolved to NO, 'scalar' = scalar market settled at a specific value. + enum: + - 'yes' + - 'no' + - scalar + description: >- + The outcome of the market settlement. 'yes' = market resolved to + YES, 'no' = market resolved to NO, 'scalar' = scalar market settled + at a specific value. yes_count_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of YES contracts owned at the time of settlement. + description: >- + String representation of the number of YES contracts owned at the + time of settlement. yes_total_cost_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Total cost basis of all YES contracts in fixed-point dollars. no_count_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of NO contracts owned at the time of settlement. + description: >- + String representation of the number of NO contracts owned at the + time of settlement. no_total_cost_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Total cost basis of all NO contracts in fixed-point dollars. revenue: type: integer - description: Total revenue earned from this settlement in cents (winning contracts pay out 100 cents each). + description: >- + Total revenue earned from this settlement in cents (winning + contracts pay out 100 cents each). settled_time: type: string format: date-time description: Timestamp when the market was settled and payouts were processed. fee_cost: $ref: '#/components/schemas/FixedPointDollars' - example: "0.3400" + example: '0.3400' description: Total fees paid in fixed point dollars. value: type: integer nullable: true description: Payout of a single yes contract in cents. - GetPortfolioRestingOrderTotalValueResponse: type: object required: @@ -5321,7 +5799,6 @@ components: total_resting_order_value: type: integer description: Total value of resting orders in cents - GetDepositsResponse: type: object required: @@ -5333,7 +5810,6 @@ components: $ref: '#/components/schemas/Deposit' cursor: type: string - Deposit: type: object required: @@ -5354,7 +5830,9 @@ components: - applied - failed - returned - description: Current status of the deposit. 'applied' means funds are reflected in balance. + description: >- + Current status of the deposit. 'applied' means funds are reflected + in balance. type: type: string enum: @@ -5380,8 +5858,9 @@ components: type: integer format: int64 nullable: true - description: Unix timestamp of when the deposit was finalized (applied, failed, or returned). - + description: >- + Unix timestamp of when the deposit was finalized (applied, failed, + or returned). GetWithdrawalsResponse: type: object required: @@ -5393,7 +5872,6 @@ components: $ref: '#/components/schemas/Withdrawal' cursor: type: string - Withdrawal: type: object required: @@ -5414,7 +5892,9 @@ components: - applied - failed - returned - description: Current status of the withdrawal. 'applied' means funds have been deducted from balance. + description: >- + Current status of the withdrawal. 'applied' means funds have been + deducted from balance. type: type: string enum: @@ -5440,9 +5920,9 @@ components: type: integer format: int64 nullable: true - description: Unix timestamp of when the withdrawal was finalized (applied, failed, or returned). - - # FCM schemas + description: >- + Unix timestamp of when the withdrawal was finalized (applied, + failed, or returned). Order: type: object required: @@ -5450,8 +5930,6 @@ components: - user_id - client_order_id - ticker - - side - - action - outcome_side - book_side - type @@ -5477,34 +5955,64 @@ components: type: string side: type: string - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' deprecated: true - description: | - Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order direction](/getting_started/order_direction). This field will not be removed before May 14, 2026. + x-go-type-skip-optional-pointer: true + description: > + Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order + direction](/getting_started/order_direction). This field will not be + removed before May 14, 2026. action: type: string - enum: [buy, sell] + enum: + - buy + - sell deprecated: true - description: | - Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order direction](/getting_started/order_direction). This field will not be removed before May 14, 2026. + x-go-type-skip-optional-pointer: true + description: > + Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order + direction](/getting_started/order_direction). This field will not be + removed before May 14, 2026. outcome_side: type: string - enum: ['yes', 'no'] - description: | - The outcome side this order is positioned for. buy-yes and sell-no produce 'yes'; buy-no and sell-yes produce 'no'. + enum: + - 'yes' + - 'no' + description: > + The outcome side this order is positioned for. buy-yes and sell-no + produce 'yes'; buy-no and sell-yes produce 'no'. - `outcome_side` describes directional exposure only; it does not change the order's price. An order at price `p` with `outcome_side=no` is matched by an order at the same price `p` with `outcome_side=yes` — both parties trade at the same price, just on opposite directions. - `outcome_side` and `book_side` will become the canonical way to determine order direction. The legacy `action`, `side`, and `is_yes` fields will be deprecated in a future release — please migrate to these new fields. + `outcome_side` describes directional exposure only; it does not + change the order's price. An order at price `p` with + `outcome_side=no` is matched by an order at the same price `p` with + `outcome_side=yes` — both parties trade at the same price, just on + opposite directions. + + + `outcome_side` and `book_side` will become the canonical way to + determine order direction. The legacy `action`, `side`, and `is_yes` + fields will be deprecated in a future release — please migrate to + these new fields. book_side: $ref: '#/components/schemas/BookSide' - description: | - Same directional bit as outcome_side in book vocabulary. 'bid' is equivalent to outcome_side 'yes'; 'ask' is equivalent to outcome_side 'no'. + description: > + Same directional bit as outcome_side in book vocabulary. 'bid' is + equivalent to outcome_side 'yes'; 'ask' is equivalent to + outcome_side 'no'. - `outcome_side` and `book_side` will become the canonical way to determine order direction. The legacy `action`, `side`, and `is_yes` fields will be deprecated in a future release — please migrate to these new fields. + + `outcome_side` and `book_side` will become the canonical way to + determine order direction. The legacy `action`, `side`, and `is_yes` + fields will be deprecated in a future release — please migrate to + these new fields. type: type: string - enum: [limit, market] + enum: + - limit + - market status: $ref: '#/components/schemas/OrderStatus' yes_price_dollars: @@ -5515,13 +6023,17 @@ components: description: The no price for this order in fixed-point dollars fill_count_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts that have been filled + description: >- + String representation of the number of contracts that have been + filled remaining_count_fp: $ref: '#/components/schemas/FixedPointCount' description: String representation of the remaining contracts for this order initial_count_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the initial size of the order (contract units) + description: >- + String representation of the initial size of the order (contract + units) taker_fill_cost_dollars: $ref: '#/components/schemas/FixedPointDollars' description: The cost of filled taker orders in dollars @@ -5559,7 +6071,9 @@ components: description: The order group this order is part of cancel_order_on_pause: type: boolean - description: If this flag is set to true, the order will be canceled if the order is open and trading on the exchange is paused for any reason. + description: >- + If this flag is set to true, the order will be canceled if the order + is open and trading on the exchange is paused for any reason. subaccount_number: type: integer nullable: true @@ -5569,7 +6083,6 @@ components: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - Milestone: type: object required: @@ -5589,11 +6102,14 @@ components: description: Unique identifier for the milestone. category: type: string - description: 'Category of the milestone. E.g. Sports, Elections, Esports, Crypto.' + description: Category of the milestone. E.g. Sports, Elections, Esports, Crypto. example: Sports type: type: string - description: 'Type of the milestone. E.g. football_game, basketball_game, soccer_tournament_multi_leg, baseball_game, hockey_match, golf_tournament, political_race.' + description: >- + Type of the milestone. E.g. football_game, basketball_game, + soccer_tournament_multi_leg, baseball_game, hockey_match, + golf_tournament, political_race. example: football_game start_date: type: string @@ -5632,12 +6148,13 @@ components: type: array items: type: string - description: List of event tickers directly related to the outcome of this milestone. + description: >- + List of event tickers directly related to the outcome of this + milestone. last_updated_ts: type: string format: date-time description: Last time this structured target was updated. - GetMilestoneResponse: type: object required: @@ -5646,7 +6163,6 @@ components: milestone: $ref: '#/components/schemas/Milestone' description: The milestone data. - GetMilestonesResponse: type: object required: @@ -5660,7 +6176,6 @@ components: cursor: type: string description: Cursor for pagination. - GetOrdersResponse: type: object required: @@ -5673,7 +6188,6 @@ components: $ref: '#/components/schemas/Order' cursor: type: string - GetOrderQueuePositionResponse: type: object required: @@ -5682,7 +6196,6 @@ components: queue_position_fp: $ref: '#/components/schemas/FixedPointCount' description: The number of preceding shares before the order in the queue. - OrderQueuePosition: type: object required: @@ -5699,7 +6212,6 @@ components: queue_position_fp: $ref: '#/components/schemas/FixedPointCount' description: The number of preceding shares before the order in the queue. - GetOrderQueuePositionsResponse: type: object required: @@ -5710,7 +6222,6 @@ components: description: Queue positions for all matching orders items: $ref: '#/components/schemas/OrderQueuePosition' - MarketPosition: type: object required: @@ -5731,7 +6242,9 @@ components: description: Total spent on this market in dollars position_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought in this market. Negative means NO contracts and positive means YES contracts + description: >- + String representation of the number of contracts bought in this + market. Negative means NO contracts and positive means YES contracts market_exposure_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Cost of the aggregate market position in dollars @@ -5745,7 +6258,6 @@ components: type: string format: date-time description: Last time the position is updated - EventPosition: type: object required: @@ -5764,7 +6276,9 @@ components: description: Total spent on this event in dollars total_cost_shares_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the total number of shares traded on this event (including both YES and NO contracts) + description: >- + String representation of the total number of shares traded on this + event (including both YES and NO contracts) event_exposure_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Cost of the aggregate event position in dollars @@ -5774,7 +6288,6 @@ components: fees_paid_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Fees paid on fill orders, in dollars - GetPositionsResponse: type: object required: @@ -5783,7 +6296,12 @@ components: properties: cursor: type: string - description: The Cursor represents a pointer to the next page of records in the pagination. Use the value returned here in the cursor query parameter for this end-point to get the next page containing limit records. An empty value of this field indicates there is no next page. + description: >- + The Cursor represents a pointer to the next page of records in the + pagination. Use the value returned here in the cursor query + parameter for this end-point to get the next page containing limit + records. An empty value of this field indicates there is no next + page. market_positions: type: array items: @@ -5794,7 +6312,6 @@ components: items: $ref: '#/components/schemas/EventPosition' description: List of event positions - Trade: type: object required: @@ -5803,7 +6320,6 @@ components: - count_fp - yes_price_dollars - no_price_dollars - - taker_side - taker_outcome_side - taker_book_side - created_time @@ -5817,7 +6333,9 @@ components: description: Unique identifier for the market count_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought or sold in this trade + description: >- + String representation of the number of contracts bought or sold in + this trade yes_price_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Yes price for this trade in dollars @@ -5826,35 +6344,64 @@ components: description: No price for this trade in dollars taker_side: type: string - enum: ['yes', 'no'] - x-enum-varnames: ['TradeTakerSideYes', 'TradeTakerSideNo'] + enum: + - 'yes' + - 'no' + x-enum-varnames: + - TradeTakerSideYes + - TradeTakerSideNo deprecated: true - description: | - Deprecated. Use `taker_outcome_side` (or `taker_book_side`) instead. See [Order direction](/getting_started/order_direction). This field will not be removed before May 14, 2026. + x-go-type-skip-optional-pointer: true + description: > + Deprecated. Use `taker_outcome_side` (or `taker_book_side`) instead. + See [Order direction](/getting_started/order_direction). This field + will not be removed before May 14, 2026. taker_outcome_side: type: string - enum: ['yes', 'no'] - x-enum-varnames: ['TradeTakerOutcomeSideYes', 'TradeTakerOutcomeSideNo'] - description: | - The outcome side the taker is positioned for. buy-yes and sell-no produce 'yes'; buy-no and sell-yes produce 'no'. - - `taker_outcome_side` describes directional exposure only; it does not change the trade's price. A trade at price `p` with `taker_outcome_side=no` is matched against the maker at the same price `p` with the opposite direction — both parties trade at the same price. - - `taker_outcome_side` and `taker_book_side` will become the canonical way to determine trade direction. The legacy `taker_side` field will be deprecated in a future release — please migrate to these new fields. + enum: + - 'yes' + - 'no' + x-enum-varnames: + - TradeTakerOutcomeSideYes + - TradeTakerOutcomeSideNo + description: > + The outcome side the taker is positioned for. buy-yes and sell-no + produce 'yes'; buy-no and sell-yes produce 'no'. + + + `taker_outcome_side` describes directional exposure only; it does + not change the trade's price. A trade at price `p` with + `taker_outcome_side=no` is matched against the maker at the same + price `p` with the opposite direction — both parties trade at the + same price. + + + `taker_outcome_side` and `taker_book_side` will become the canonical + way to determine trade direction. The legacy `taker_side` field will + be deprecated in a future release — please migrate to these new + fields. taker_book_side: $ref: '#/components/schemas/BookSide' - description: | - Same directional bit as taker_outcome_side in book vocabulary. 'bid' is equivalent to taker_outcome_side 'yes'; 'ask' is equivalent to taker_outcome_side 'no'. + description: > + Same directional bit as taker_outcome_side in book vocabulary. 'bid' + is equivalent to taker_outcome_side 'yes'; 'ask' is equivalent to + taker_outcome_side 'no'. + - `taker_outcome_side` and `taker_book_side` will become the canonical way to determine trade direction. The legacy `taker_side` field will be deprecated in a future release — please migrate to these new fields. + `taker_outcome_side` and `taker_book_side` will become the canonical + way to determine trade direction. The legacy `taker_side` field will + be deprecated in a future release — please migrate to these new + fields. created_time: type: string format: date-time description: Timestamp when this trade was executed is_block_trade: type: boolean - description: True if this trade was matched off-book as a block trade (e.g. via RFQ / negotiated block proposal); false for trades that filled on the standard order book. - + description: >- + True if this trade was matched off-book as a block trade (e.g. via + RFQ / negotiated block proposal); false for trades that filled on + the standard order book. GetIncentiveProgramsResponse: type: object required: @@ -5867,7 +6414,6 @@ components: next_cursor: type: string description: Cursor for pagination to get the next page of results - IncentiveProgram: type: object required: @@ -5886,13 +6432,19 @@ components: description: Unique identifier for the incentive program market_id: type: string - description: The unique identifier of the market associated with this incentive program + description: >- + The unique identifier of the market associated with this incentive + program market_ticker: type: string - description: The ticker symbol of the market associated with this incentive program + description: >- + The ticker symbol of the market associated with this incentive + program incentive_type: type: string - enum: ['liquidity', 'volume'] + enum: + - liquidity + - volume description: Type of incentive program incentive_description: type: string @@ -5920,8 +6472,9 @@ components: target_size_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the target size for the incentive program (optional) - + description: >- + String representation of the target size for the incentive program + (optional) GetTradesResponse: type: object required: @@ -5934,7 +6487,6 @@ components: $ref: '#/components/schemas/Trade' cursor: type: string - Fill: type: object required: @@ -5943,8 +6495,6 @@ components: - order_id - ticker - market_ticker - - side - - action - outcome_side - book_side - count_fp @@ -5970,34 +6520,64 @@ components: description: Unique identifier for the market (legacy field name, same as ticker) side: type: string - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' deprecated: true - description: | - Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order direction](/getting_started/order_direction). This field will not be removed before May 14, 2026. + x-go-type-skip-optional-pointer: true + description: > + Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order + direction](/getting_started/order_direction). This field will not be + removed before May 14, 2026. action: type: string - enum: ['buy', 'sell'] + enum: + - buy + - sell deprecated: true - description: | - Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order direction](/getting_started/order_direction). This field will not be removed before May 14, 2026. + x-go-type-skip-optional-pointer: true + description: > + Deprecated. Use `outcome_side` (or `book_side`) instead. See [Order + direction](/getting_started/order_direction). This field will not be + removed before May 14, 2026. outcome_side: type: string - enum: ['yes', 'no'] - description: | - The outcome side this fill positioned the user for. buy-yes and sell-no produce 'yes'; buy-no and sell-yes produce 'no'. + enum: + - 'yes' + - 'no' + description: > + The outcome side this fill positioned the user for. buy-yes and + sell-no produce 'yes'; buy-no and sell-yes produce 'no'. + + + `outcome_side` describes directional exposure only; it does not + change the fill's price. A fill at price `p` with `outcome_side=no` + is matched against an order at the same price `p` with + `outcome_side=yes` — both parties trade at the same price, just on + opposite directions. - `outcome_side` describes directional exposure only; it does not change the fill's price. A fill at price `p` with `outcome_side=no` is matched against an order at the same price `p` with `outcome_side=yes` — both parties trade at the same price, just on opposite directions. - `outcome_side` and `book_side` will become the canonical way to determine fill direction. The legacy `action` and `side` fields will be deprecated in a future release — please migrate to these new fields. + `outcome_side` and `book_side` will become the canonical way to + determine fill direction. The legacy `action` and `side` fields will + be deprecated in a future release — please migrate to these new + fields. book_side: $ref: '#/components/schemas/BookSide' - description: | - Same directional bit as outcome_side in book vocabulary. 'bid' is equivalent to outcome_side 'yes'; 'ask' is equivalent to outcome_side 'no'. + description: > + Same directional bit as outcome_side in book vocabulary. 'bid' is + equivalent to outcome_side 'yes'; 'ask' is equivalent to + outcome_side 'no'. + - `outcome_side` and `book_side` will become the canonical way to determine fill direction. The legacy `action` and `side` fields will be deprecated in a future release — please migrate to these new fields. + `outcome_side` and `book_side` will become the canonical way to + determine fill direction. The legacy `action` and `side` fields will + be deprecated in a future release — please migrate to these new + fields. count_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought or sold in this fill + description: >- + String representation of the number of contracts bought or sold in + this fill yes_price_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Fill price for the yes side in fixed-point dollars @@ -6006,7 +6586,9 @@ components: description: Fill price for the no side in fixed-point dollars is_taker: type: boolean - description: If true, this fill was a taker (removed liquidity from the order book) + description: >- + If true, this fill was a taker (removed liquidity from the order + book) created_time: type: string format: date-time @@ -6018,12 +6600,13 @@ components: type: integer nullable: true x-omitempty: true - description: Subaccount number (0 for primary, 1-63 for subaccounts). Present for direct users. + description: >- + Subaccount number (0 for primary, 1-63 for subaccounts). Present for + direct users. ts: type: integer format: int64 description: Unix timestamp when this fill was executed (legacy field name) - GetFillsResponse: type: object required: @@ -6036,8 +6619,6 @@ components: $ref: '#/components/schemas/Fill' cursor: type: string - - # Structured Target schemas StructuredTarget: type: object properties: @@ -6052,10 +6633,14 @@ components: description: Type of the structured target. details: type: object - description: Additional details about the structured target. Contains flexible JSON data specific to the target type. + description: >- + Additional details about the structured target. Contains flexible + JSON data specific to the target type. source_id: type: string - description: External source identifier for the structured target, if available (e.g., third-party data provider ID). + description: >- + External source identifier for the structured target, if available + (e.g., third-party data provider ID). source_ids: type: object additionalProperties: @@ -6065,7 +6650,6 @@ components: type: string format: date-time description: Timestamp when this structured target was last updated. - GetStructuredTargetsResponse: type: object properties: @@ -6075,19 +6659,17 @@ components: $ref: '#/components/schemas/StructuredTarget' cursor: type: string - description: Pagination cursor for the next page. Empty if there are no more results. - + description: >- + Pagination cursor for the next page. Empty if there are no more + results. GetStructuredTargetResponse: type: object properties: structured_target: $ref: '#/components/schemas/StructuredTarget' - - # Order Group schemas EmptyResponse: type: object description: An empty response body - IntraExchangeInstanceTransferRequest: type: object required: @@ -6115,7 +6697,6 @@ components: default: 0 x-go-type-skip-optional-pointer: true description: Destination exchange shard index (default 0) - IntraExchangeInstanceTransferResponse: type: object required: @@ -6124,7 +6705,6 @@ components: transfer_id: type: string description: The ID of the transfer that was created - OrderGroup: type: object required: @@ -6137,7 +6717,9 @@ components: x-go-type-skip-optional-pointer: true contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the current maximum contracts allowed over a rolling 15-second window. + description: >- + String representation of the current maximum contracts allowed over + a rolling 15-second window. x-go-type-skip-optional-pointer: true is_auto_cancel_enabled: type: boolean @@ -6147,7 +6729,6 @@ components: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - GetOrderGroupsResponse: type: object properties: @@ -6156,7 +6737,6 @@ components: items: $ref: '#/components/schemas/OrderGroup' x-go-type-skip-optional-pointer: true - GetOrderGroupResponse: type: object required: @@ -6168,7 +6748,9 @@ components: description: Whether auto-cancel is enabled for this order group contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the current maximum contracts allowed over a rolling 15-second window. + description: >- + String representation of the current maximum contracts allowed over + a rolling 15-second window. x-go-type-skip-optional-pointer: true orders: type: array @@ -6180,34 +6762,42 @@ components: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - CreateOrderGroupRequest: type: object properties: subaccount: type: integer minimum: 0 - description: Optional subaccount number to use for this order group (0 for primary, 1-63 for subaccounts) + description: >- + Optional subaccount number to use for this order group (0 for + primary, 1-63 for subaccounts) default: 0 x-go-type-skip-optional-pointer: true contracts_limit: type: integer format: int64 minimum: 1 - description: Specifies the maximum number of contracts that can be matched within this group over a rolling 15-second window. Whole contracts only. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + Specifies the maximum number of contracts that can be matched within + this group over a rolling 15-second window. Whole contracts only. + Provide contracts_limit or contracts_limit_fp; if both provided they + must match. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: validate: omitempty,gte=1 contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the maximum number of contracts that can be matched within this group over a rolling 15-second window. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + String representation of the maximum number of contracts that can be + matched within this group over a rolling 15-second window. Provide + contracts_limit or contracts_limit_fp; if both provided they must + match. exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 x-go-type-skip-optional-pointer: true - UpdateOrderGroupLimitRequest: type: object properties: @@ -6215,15 +6805,22 @@ components: type: integer format: int64 minimum: 1 - description: New maximum number of contracts that can be matched within this group over a rolling 15-second window. Whole contracts only. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + New maximum number of contracts that can be matched within this + group over a rolling 15-second window. Whole contracts only. Provide + contracts_limit or contracts_limit_fp; if both provided they must + match. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: validate: omitempty,gte=1 contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the new maximum number of contracts that can be matched within this group over a rolling 15-second window. Provide contracts_limit or contracts_limit_fp; if both provided they must match. - + description: >- + String representation of the new maximum number of contracts that + can be matched within this group over a rolling 15-second window. + Provide contracts_limit or contracts_limit_fp; if both provided they + must match. CreateOrderGroupResponse: type: object required: @@ -6236,13 +6833,14 @@ components: subaccount: type: integer minimum: 0 - description: Subaccount number that owns the created order group (0 for primary, 1-63 for subaccounts). + description: >- + Subaccount number that owns the created order group (0 for primary, + 1-63 for subaccounts). x-go-type-skip-optional-pointer: true exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - GetCommunicationsIDResponse: type: object required: @@ -6251,7 +6849,6 @@ components: communications_id: type: string description: A public communications ID which is used to identify the user - BlockTradeProposal: type: object required: @@ -6278,17 +6875,25 @@ components: description: User ID of the proposal creator buyer_user_id: type: string - description: User ID of the buyer. Empty when the authenticated user is not the buyer. + description: >- + User ID of the buyer. Empty when the authenticated user is not the + buyer. buyer_subtrader_id: type: string - description: Subtrader ID of the buyer. Empty when the authenticated user is not the buyer. + description: >- + Subtrader ID of the buyer. Empty when the authenticated user is not + the buyer. x-go-type-skip-optional-pointer: true seller_user_id: type: string - description: User ID of the seller. Empty when the authenticated user is not the seller. + description: >- + User ID of the seller. Empty when the authenticated user is not the + seller. seller_subtrader_id: type: string - description: Subtrader ID of the seller. Empty when the authenticated user is not the seller. + description: >- + Subtrader ID of the seller. Empty when the authenticated user is not + the seller. x-go-type-skip-optional-pointer: true market_ticker: type: string @@ -6304,7 +6909,9 @@ components: maker_side: type: string description: The maker side of the trade - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' expiration_ts: type: string format: date-time @@ -6346,7 +6953,6 @@ components: type: string description: Order ID for the seller after the proposal is executed x-go-type-skip-optional-pointer: true - GetBlockTradeProposalsResponse: type: object required: @@ -6361,7 +6967,6 @@ components: type: string description: Cursor for pagination to get the next page of results x-go-type-skip-optional-pointer: true - ProposeBlockTradeRequest: type: object required: @@ -6380,13 +6985,18 @@ components: validate: required buyer_subtrader_id: type: string - description: Subtrader ID of the buyer. Provide either this or buyer_subaccount, not both. + description: >- + Subtrader ID of the buyer. Provide either this or buyer_subaccount, + not both. x-go-type-skip-optional-pointer: true buyer_subaccount: type: integer minimum: 0 maximum: 63 - description: User-managed subaccount number of the buyer (0 for primary, 1-63 for numbered subaccounts). Provide either this or buyer_subtrader_id, not both. + description: >- + User-managed subaccount number of the buyer (0 for primary, 1-63 for + numbered subaccounts). Provide either this or buyer_subtrader_id, + not both. seller_user_id: type: string description: User ID of the seller @@ -6394,13 +7004,18 @@ components: validate: required seller_subtrader_id: type: string - description: Subtrader ID of the seller. Provide either this or seller_subaccount, not both. + description: >- + Subtrader ID of the seller. Provide either this or + seller_subaccount, not both. x-go-type-skip-optional-pointer: true seller_subaccount: type: integer minimum: 0 maximum: 63 - description: User-managed subaccount number of the seller (0 for primary, 1-63 for numbered subaccounts). Provide either this or seller_subtrader_id, not both. + description: >- + User-managed subaccount number of the seller (0 for primary, 1-63 + for numbered subaccounts). Provide either this or + seller_subtrader_id, not both. market_ticker: type: string description: The ticker of the market for this block trade @@ -6423,7 +7038,9 @@ components: maker_side: type: string description: The maker side of the trade - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' x-oapi-codegen-extra-tags: validate: required,oneof=yes no expiration_ts: @@ -6432,7 +7049,6 @@ components: description: Expiration time of the proposal x-oapi-codegen-extra-tags: validate: required - ProposeBlockTradeResponse: type: object required: @@ -6441,20 +7057,23 @@ components: block_trade_proposal_id: type: string description: The ID of the newly created block trade proposal - AcceptBlockTradeProposalRequest: type: object properties: subtrader_id: type: string - description: Subtrader ID to accept as. Provide either this or subaccount, not both. + description: >- + Subtrader ID to accept as. Provide either this or subaccount, not + both. x-go-type-skip-optional-pointer: true subaccount: type: integer minimum: 0 maximum: 63 - description: User-managed subaccount number to accept as (0 for primary, 1-63 for numbered subaccounts). Provide either this or subtrader_id, not both. - + description: >- + User-managed subaccount number to accept as (0 for primary, 1-63 for + numbered subaccounts). Provide either this or subtrader_id, not + both. RFQ: type: object required: @@ -6476,14 +7095,18 @@ components: description: The ticker of the market this RFQ is for contracts_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts requested in the RFQ + description: >- + String representation of the number of contracts requested in the + RFQ target_cost_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Total value of the RFQ in dollars status: type: string description: Current status of the RFQ (open, closed) - enum: [open, closed] + enum: + - open + - closed created_ts: type: string format: date-time @@ -6512,7 +7135,9 @@ components: x-go-type-skip-optional-pointer: true creator_subaccount: type: integer - description: Subaccount number of the RFQ creator (visible when the caller is the RFQ creator) + description: >- + Subaccount number of the RFQ creator (visible when the caller is the + RFQ creator) cancelled_ts: type: string format: date-time @@ -6521,7 +7146,6 @@ components: type: string format: date-time description: Timestamp when the RFQ was last updated - GetRFQsResponse: type: object required: @@ -6536,7 +7160,6 @@ components: type: string description: Cursor for pagination to get the next page of results x-go-type-skip-optional-pointer: true - GetRFQResponse: type: object required: @@ -6545,7 +7168,6 @@ components: rfq: $ref: '#/components/schemas/RFQ' description: The details of the requested RFQ - CreateRFQRequest: type: object required: @@ -6557,16 +7179,23 @@ components: description: The ticker of the market for which to create an RFQ contracts: type: integer - description: Whole-contract count for the RFQ. Use contracts_fp for partial contract values; if both are provided, they must match. + description: >- + Whole-contract count for the RFQ. Use contracts_fp for partial + contract values; if both are provided, they must match. x-go-type-skip-optional-pointer: true contracts_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: Fixed-point number of contracts for the RFQ. Supports partial contracts in 0.01-contract increments; if contracts is also provided, both values must match. + description: >- + Fixed-point number of contracts for the RFQ. Supports partial + contracts in 0.01-contract increments; if contracts is also + provided, both values must match. target_cost_centi_cents: type: integer format: int64 - description: 'DEPRECATED: The target cost for the RFQ in centi-cents. Use target_cost_dollars instead.' + description: >- + DEPRECATED: The target cost for the RFQ in centi-cents. Use + target_cost_dollars instead. deprecated: true x-go-type-skip-optional-pointer: true target_cost_dollars: @@ -6587,9 +7216,10 @@ components: x-go-type-skip-optional-pointer: true subaccount: type: integer - description: The subaccount number to create the RFQ for (direct members only; 0 for primary, 1-63 for subaccounts) + description: >- + The subaccount number to create the RFQ for (direct members only; 0 + for primary, 1-63 for subaccounts) x-go-type-skip-optional-pointer: true - CreateRFQResponse: type: object required: @@ -6598,7 +7228,6 @@ components: id: type: string description: The ID of the newly created RFQ - Quote: type: object required: @@ -6650,11 +7279,18 @@ components: status: type: string description: Current status of the quote - enum: [open, accepted, confirmed, executed, cancelled] + enum: + - open + - accepted + - confirmed + - executed + - cancelled accepted_side: type: string description: The side that was accepted (yes or no) - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' accepted_ts: type: string format: date-time @@ -6676,7 +7312,9 @@ components: description: Whether to rest the remainder of the quote after execution post_only: type: boolean - description: Whether the quote creator's order is post-only (visible when the caller is the quote creator) + description: >- + Whether the quote creator's order is post-only (visible when the + caller is the quote creator) cancellation_reason: type: string description: Reason for quote cancellation if cancelled @@ -6702,17 +7340,20 @@ components: x-go-type-skip-optional-pointer: true creator_subaccount: type: integer - description: Subaccount number of the quote creator (visible when the caller is the quote creator) + description: >- + Subaccount number of the quote creator (visible when the caller is + the quote creator) rfq_creator_subaccount: type: integer - description: Subaccount number of the RFQ creator (visible when the caller is the RFQ creator) + description: >- + Subaccount number of the RFQ creator (visible when the caller is the + RFQ creator) yes_contracts_fp: $ref: '#/components/schemas/FixedPointCount' description: Number of YES contracts offered in the quote (fixed-point) no_contracts_fp: $ref: '#/components/schemas/FixedPointCount' description: Number of NO contracts offered in the quote (fixed-point) - GetQuotesResponse: type: object required: @@ -6727,7 +7368,6 @@ components: type: string description: Cursor for pagination to get the next page of results x-go-type-skip-optional-pointer: true - GetQuoteResponse: type: object required: @@ -6736,7 +7376,6 @@ components: quote: $ref: '#/components/schemas/Quote' description: The details of the requested quote - CreateQuoteRequest: type: object required: @@ -6761,11 +7400,14 @@ components: description: Whether to rest the remainder of the quote after execution post_only: type: boolean - description: If true, the quote creator's resting order will be cancelled rather than crossed if it would take liquidity. Defaults to false. + description: >- + If true, the quote creator's resting order will be cancelled rather + than crossed if it would take liquidity. Defaults to false. subaccount: type: integer - description: Optional subaccount number to place the quote under (0 for primary, 1-63 for subaccounts) - + description: >- + Optional subaccount number to place the quote under (0 for primary, + 1-63 for subaccounts) CreateQuoteResponse: type: object required: @@ -6774,7 +7416,6 @@ components: id: type: string description: The ID of the newly created quote - AcceptQuoteRequest: type: object required: @@ -6783,9 +7424,9 @@ components: accepted_side: type: string description: The side of the quote to accept (yes or no) - enum: ['yes', 'no'] - - # Order schemas + enum: + - 'yes' + - 'no' GetOrderResponse: type: object required: @@ -6793,7 +7434,6 @@ components: properties: order: $ref: '#/components/schemas/Order' - CreateOrderRequest: type: object required: @@ -6810,25 +7450,33 @@ components: x-go-type-skip-optional-pointer: true side: type: string - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' x-oapi-codegen-extra-tags: validate: required,oneof=yes no action: type: string - enum: ['buy', 'sell'] + enum: + - buy + - sell x-oapi-codegen-extra-tags: validate: required,oneof=buy sell count: type: integer minimum: 1 - description: Order quantity in contracts (whole contracts only). Provide count or count_fp; if both provided they must match. + description: >- + Order quantity in contracts (whole contracts only). Provide count or + count_fp; if both provided they must match. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: validate: omitempty,gte=1 count_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the order quantity in contracts. Provide count or count_fp; if both provided they must match. + description: >- + String representation of the order quantity in contracts. Provide + count or count_fp; if both provided they must match. yes_price: type: integer minimum: 1 @@ -6848,33 +7496,50 @@ components: expiration_ts: type: integer format: int64 - description: | - Optional Unix timestamp in seconds for when the order expires. To place + description: > + Optional Unix timestamp in seconds for when the order expires. To + place + an expiring order, set `time_in_force` to `good_till_canceled` and - provide this `expiration_ts`. `GTT` is an internal execution type and is + + provide this `expiration_ts`. `GTT` is an internal execution type + and is + not a valid API value for `time_in_force`. The `immediate_or_cancel` + time-in-force value cannot be combined with `expiration_ts`. time_in_force: type: string - description: | - Specifies how long the order remains active. Use `good_till_canceled` + description: > + Specifies how long the order remains active. Use + `good_till_canceled` + with `expiration_ts` for an order that should rest until a specific + expiration time; without `expiration_ts`, `good_till_canceled` is a + true good-till-canceled order. `GTT` is not a valid API value. - enum: ['fill_or_kill', 'good_till_canceled', 'immediate_or_cancel'] + enum: + - fill_or_kill + - good_till_canceled + - immediate_or_cancel x-oapi-codegen-extra-tags: - validate: omitempty,oneof=fill_or_kill good_till_canceled immediate_or_cancel + validate: >- + omitempty,oneof=fill_or_kill good_till_canceled + immediate_or_cancel x-go-type-skip-optional-pointer: true buy_max_cost: type: integer - description: Maximum cost in cents. When specified, the order will automatically have Fill-or-Kill (FoK) behavior. + description: >- + Maximum cost in cents. When specified, the order will automatically + have Fill-or-Kill (FoK) behavior. post_only: type: boolean reduce_only: type: boolean sell_position_floor: type: integer - description: "Deprecated: Use reduce_only instead. Only accepts value of 0." + description: 'Deprecated: Use reduce_only instead. Only accepts value of 0.' self_trade_prevention_type: allOf: - $ref: '#/components/schemas/SelfTradePreventionType' @@ -6887,20 +7552,25 @@ components: x-go-type-skip-optional-pointer: true cancel_order_on_pause: type: boolean - description: If this flag is set to true, the order will be canceled if the order is open and trading on the exchange is paused for any reason. + description: >- + If this flag is set to true, the order will be canceled if the order + is open and trading on the exchange is paused for any reason. subaccount: type: integer minimum: 0 default: 0 - description: The subaccount number to use for this order. 0 is the primary subaccount. + description: >- + The subaccount number to use for this order. 0 is the primary + subaccount. x-go-type-skip-optional-pointer: true exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 - description: "Exchange shard index. Defaults to 0. Use -1 to auto-route by market ticker." + description: >- + Exchange shard index. Defaults to 0. Use -1 to auto-route by market + ticker. x-go-type-skip-optional-pointer: true - CreateOrderResponse: type: object required: @@ -6908,7 +7578,6 @@ components: properties: order: $ref: '#/components/schemas/Order' - BatchCreateOrdersRequest: type: object required: @@ -6920,7 +7589,6 @@ components: validate: required,dive items: $ref: '#/components/schemas/CreateOrderRequest' - BatchCreateOrdersResponse: type: object required: @@ -6930,7 +7598,6 @@ components: type: array items: $ref: '#/components/schemas/BatchCreateOrdersIndividualResponse' - BatchCreateOrdersIndividualResponse: type: object properties: @@ -6939,13 +7606,12 @@ components: nullable: true order: allOf: - - $ref: '#/components/schemas/Order' + - $ref: '#/components/schemas/Order' nullable: true error: allOf: - - $ref: '#/components/schemas/ErrorResponse' + - $ref: '#/components/schemas/ErrorResponse' nullable: true - BatchCancelOrdersRequest: type: object properties: @@ -6959,8 +7625,9 @@ components: type: array items: $ref: '#/components/schemas/BatchCancelOrdersRequestOrder' - description: An array of orders to cancel, each optionally specifying a subaccount - + description: >- + An array of orders to cancel, each optionally specifying a + subaccount BatchCancelOrdersRequestOrder: type: object required: @@ -6973,19 +7640,22 @@ components: type: integer minimum: 0 default: 0 - description: Optional subaccount number to use for this cancellation (0 for primary, 1-63 for subaccounts) + description: >- + Optional subaccount number to use for this cancellation (0 for + primary, 1-63 for subaccounts) x-go-type-skip-optional-pointer: true exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 - description: "Exchange shard index. Defaults to 0. Use -1 to auto-route by market ticker." + description: >- + Exchange shard index. Defaults to 0. Use -1 to auto-route by market + ticker. x-go-type-skip-optional-pointer: true market_ticker: type: string description: Market ticker. Required when exchange_index is -1 (auto). x-go-type-skip-optional-pointer: true - BatchCancelOrdersResponse: type: object required: @@ -6995,7 +7665,6 @@ components: type: array items: $ref: '#/components/schemas/BatchCancelOrdersIndividualResponse' - BatchCancelOrdersIndividualResponse: type: object required: @@ -7004,19 +7673,22 @@ components: properties: order_id: type: string - description: The order ID to identify which order had an error during batch cancellation + description: >- + The order ID to identify which order had an error during batch + cancellation order: allOf: - $ref: '#/components/schemas/Order' nullable: true reduced_by_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts that were successfully canceled from this order + description: >- + String representation of the number of contracts that were + successfully canceled from this order error: allOf: - $ref: '#/components/schemas/ErrorResponse' nullable: true - AmendOrderRequest: type: object required: @@ -7027,7 +7699,9 @@ components: subaccount: type: integer minimum: 0 - description: Optional subaccount number to use for this amendment (0 for primary, 1-63 for subaccounts) + description: >- + Optional subaccount number to use for this amendment (0 for primary, + 1-63 for subaccounts) default: 0 x-go-type-skip-optional-pointer: true ticker: @@ -7035,11 +7709,15 @@ components: description: Market ticker side: type: string - enum: ["yes", "no"] + enum: + - 'yes' + - 'no' description: Side of the order action: type: string - enum: ["buy", "sell"] + enum: + - buy + - sell description: Action of the order client_order_id: type: string @@ -7061,24 +7739,35 @@ components: description: Updated no price for the order in cents yes_price_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Updated yes price for the order in fixed-point dollars. Exactly one of yes_price, no_price, yes_price_dollars, and no_price_dollars must be passed. + description: >- + Updated yes price for the order in fixed-point dollars. Exactly one + of yes_price, no_price, yes_price_dollars, and no_price_dollars must + be passed. no_price_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Updated no price for the order in fixed-point dollars. Exactly one of yes_price, no_price, yes_price_dollars, and no_price_dollars must be passed. + description: >- + Updated no price for the order in fixed-point dollars. Exactly one + of yes_price, no_price, yes_price_dollars, and no_price_dollars must + be passed. count: type: integer minimum: 1 - description: Updated quantity for the order (whole contracts only). If updating quantity, provide count or count_fp; if both provided they must match. + description: >- + Updated quantity for the order (whole contracts only). If updating + quantity, provide count or count_fp; if both provided they must + match. count_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the updated quantity for the order. If updating quantity, provide count or count_fp; if both provided they must match. + description: >- + String representation of the updated quantity for the order. If + updating quantity, provide count or count_fp; if both provided they + must match. exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 x-go-type-skip-optional-pointer: true - AmendOrderResponse: type: object required: @@ -7091,7 +7780,6 @@ components: order: $ref: '#/components/schemas/Order' description: The order after amendment - CreateOrderV2Request: type: object required: @@ -7105,8 +7793,8 @@ components: ticker: HIGHNY-24JAN01-T60 client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 side: bid - count: "10.00" - price: "0.5600" + count: '10.00' + price: '0.5600' time_in_force: good_till_canceled self_trade_prevention_type: taker_at_cross post_only: false @@ -7136,21 +7824,37 @@ components: expiration_time: type: integer format: int64 - description: | - Optional Unix timestamp in seconds for when the order expires. To place + description: > + Optional Unix timestamp in seconds for when the order expires. To + place + an expiring order, set `time_in_force` to `good_till_canceled` and - provide this `expiration_time`. `GTT` is an internal execution type and + + provide this `expiration_time`. `GTT` is an internal execution type + and + is not a valid API value for `time_in_force`. The + `immediate_or_cancel` time-in-force value cannot be combined with + `expiration_time`. time_in_force: type: string - description: | - Specifies how long the order remains active. Use `good_till_canceled` - with `expiration_time` for an order that should rest until a specific - expiration time; without `expiration_time`, `good_till_canceled` is a + description: > + Specifies how long the order remains active. Use + `good_till_canceled` + + with `expiration_time` for an order that should rest until a + specific + + expiration time; without `expiration_time`, `good_till_canceled` is + a + true good-till-canceled order. `GTT` is not a valid API value. - enum: ['fill_or_kill', 'good_till_canceled', 'immediate_or_cancel'] + enum: + - fill_or_kill + - good_till_canceled + - immediate_or_cancel x-oapi-codegen-extra-tags: validate: required,oneof=fill_or_kill good_till_canceled immediate_or_cancel x-go-type-skip-optional-pointer: true @@ -7164,15 +7868,21 @@ components: x-go-type-skip-optional-pointer: true cancel_order_on_pause: type: boolean - description: If this flag is set to true, the order will be canceled if the order is open and trading on the exchange is paused for any reason. + description: >- + If this flag is set to true, the order will be canceled if the order + is open and trading on the exchange is paused for any reason. reduce_only: type: boolean - description: Specifies whether the order place count should be capped by the member's current position. + description: >- + Specifies whether the order place count should be capped by the + member's current position. subaccount: type: integer minimum: 0 default: 0 - description: The subaccount number to use for this order. 0 is the primary subaccount. + description: >- + The subaccount number to use for this order. 0 is the primary + subaccount. x-go-type-skip-optional-pointer: true order_group_id: type: string @@ -7182,9 +7892,10 @@ components: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 - description: "Exchange shard index. Defaults to 0. Use -1 to auto-route by market ticker." + description: >- + Exchange shard index. Defaults to 0. Use -1 to auto-route by market + ticker. x-go-type-skip-optional-pointer: true - CreateOrderV2Response: type: object required: @@ -7195,8 +7906,8 @@ components: example: order_id: 3b23c1c7-f4ef-4f0d-8b9a-9e53c61f1a0d client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 - fill_count: "0.00" - remaining_count: "10.00" + fill_count: '0.00' + remaining_count: '10.00' ts_ms: 1715793600123 properties: order_id: @@ -7208,18 +7919,25 @@ components: description: Number of contracts filled immediately upon placement. remaining_count: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts remaining after placement. For IOC orders, this reflects the final state after unfilled contracts are canceled. + description: >- + Number of contracts remaining after placement. For IOC orders, this + reflects the final state after unfilled contracts are canceled. average_fill_price: $ref: '#/components/schemas/FixedPointDollars' - description: Volume-weighted average fill price. Only present when fill_count > 0. + description: >- + Volume-weighted average fill price. Only present when fill_count > + 0. average_fee_paid: $ref: '#/components/schemas/FixedPointDollars' - description: Volume-weighted average fee paid per contract for fills resulting from this request. Only present when fill_count > 0. + description: >- + Volume-weighted average fee paid per contract for fills resulting + from this request. Only present when fill_count > 0. ts_ms: type: integer format: int64 - description: Matching engine timestamp at which the order was processed, as Unix epoch milliseconds. - + description: >- + Matching engine timestamp at which the order was processed, as Unix + epoch milliseconds. CancelOrderV2Response: type: object required: @@ -7229,7 +7947,7 @@ components: example: order_id: 3b23c1c7-f4ef-4f0d-8b9a-9e53c61f1a0d client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 - reduced_by: "10.00" + reduced_by: '10.00' ts_ms: 1715793660456 properties: order_id: @@ -7238,32 +7956,38 @@ components: type: string reduced_by: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts that were canceled (i.e. the remaining count at time of cancellation). + description: >- + Number of contracts that were canceled (i.e. the remaining count at + time of cancellation). ts_ms: type: integer format: int64 - description: Matching engine timestamp at which the cancellation was processed, as Unix epoch milliseconds. - + description: >- + Matching engine timestamp at which the cancellation was processed, + as Unix epoch milliseconds. DecreaseOrderV2Request: type: object example: - reduce_by: "2.00" + reduce_by: '2.00' exchange_index: 0 properties: reduce_by: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the number of contracts to reduce by. Exactly one of `reduce_by` or `reduce_to` must be provided. + description: >- + String representation of the number of contracts to reduce by. + Exactly one of `reduce_by` or `reduce_to` must be provided. reduce_to: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the number of contracts to reduce to. Exactly one of `reduce_by` or `reduce_to` must be provided. + description: >- + String representation of the number of contracts to reduce to. + Exactly one of `reduce_by` or `reduce_to` must be provided. exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 x-go-type-skip-optional-pointer: true - DecreaseOrderV2Response: type: object required: @@ -7273,7 +7997,7 @@ components: example: order_id: 3b23c1c7-f4ef-4f0d-8b9a-9e53c61f1a0d client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 - remaining_count: "8.00" + remaining_count: '8.00' ts_ms: 1715793680789 properties: order_id: @@ -7286,8 +8010,9 @@ components: ts_ms: type: integer format: int64 - description: Matching engine timestamp at which the decrease was processed, as Unix epoch milliseconds. - + description: >- + Matching engine timestamp at which the decrease was processed, as + Unix epoch milliseconds. AmendOrderV2Request: type: object required: @@ -7298,8 +8023,8 @@ components: example: ticker: HIGHNY-24JAN01-T60 side: bid - price: "0.5700" - count: "8.00" + price: '0.5700' + count: '8.00' client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 updated_client_order_id: 2a0e3fc9-b593-4aa3-96e5-82f7f7566c2a exchange_index: 0 @@ -7320,7 +8045,10 @@ components: x-go-type-skip-optional-pointer: true count: $ref: '#/components/schemas/FixedPointCount' - description: Updated total/max fillable count for the order. Set this to the order's already filled count plus the desired resting remaining count after the amend. + description: >- + Updated total/max fillable count for the order. Set this to the + order's already filled count plus the desired resting remaining + count after the amend. x-go-type-skip-optional-pointer: true client_order_id: type: string @@ -7335,7 +8063,6 @@ components: - $ref: '#/components/schemas/ExchangeIndex' default: 0 x-go-type-skip-optional-pointer: true - AmendOrderV2Response: type: object required: @@ -7344,8 +8071,8 @@ components: example: order_id: 3b23c1c7-f4ef-4f0d-8b9a-9e53c61f1a0d client_order_id: 2a0e3fc9-b593-4aa3-96e5-82f7f7566c2a - remaining_count: "8.00" - fill_count: "0.00" + remaining_count: '8.00' + fill_count: '0.00' ts_ms: 1715793690123 properties: order_id: @@ -7356,27 +8083,38 @@ components: $ref: '#/components/schemas/FixedPointCount' nullable: true x-omitempty: false - description: Number of resting contracts remaining after the amend. This is the actual post-amend resting quantity, not the request's total/max fillable count. Only present when the amend caused a fill or changed the resting size. + description: >- + Number of resting contracts remaining after the amend. This is the + actual post-amend resting quantity, not the request's total/max + fillable count. Only present when the amend caused a fill or changed + the resting size. fill_count: $ref: '#/components/schemas/FixedPointCount' nullable: true x-omitempty: false - description: Number of contracts filled as a result of the amend crossing the book. Only present when fills occurred or remaining size changed. + description: >- + Number of contracts filled as a result of the amend crossing the + book. Only present when fills occurred or remaining size changed. average_fill_price: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: false - description: Volume-weighted average fill price for fills resulting from the amend. Only present when fills occurred. + description: >- + Volume-weighted average fill price for fills resulting from the + amend. Only present when fills occurred. average_fee_paid: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: false - description: Volume-weighted average fee paid per contract for fills resulting from the amend. Only present when fills occurred. + description: >- + Volume-weighted average fee paid per contract for fills resulting + from the amend. Only present when fills occurred. ts_ms: type: integer format: int64 - description: Matching engine timestamp at which the amend was processed, as Unix epoch milliseconds. - + description: >- + Matching engine timestamp at which the amend was processed, as Unix + epoch milliseconds. BatchCreateOrdersV2Request: type: object required: @@ -7386,16 +8124,16 @@ components: - ticker: HIGHNY-24JAN01-T60 client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 side: bid - count: "10.00" - price: "0.5600" + count: '10.00' + price: '0.5600' time_in_force: good_till_canceled self_trade_prevention_type: taker_at_cross exchange_index: 0 - ticker: HIGHNY-24JAN01-T60 client_order_id: 2a0e3fc9-b593-4aa3-96e5-82f7f7566c2a side: ask - count: "5.00" - price: "0.5800" + count: '5.00' + price: '0.5800' time_in_force: immediate_or_cancel self_trade_prevention_type: maker exchange_index: 0 @@ -7406,7 +8144,6 @@ components: validate: required,dive items: $ref: '#/components/schemas/CreateOrderV2Request' - BatchCreateOrdersV2Response: type: object required: @@ -7415,15 +8152,15 @@ components: orders: - order_id: 3b23c1c7-f4ef-4f0d-8b9a-9e53c61f1a0d client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 - fill_count: "0.00" - remaining_count: "10.00" + fill_count: '0.00' + remaining_count: '10.00' ts_ms: 1715793600123 - order_id: a6d6010d-6d5f-40a1-a7e7-5501386bb621 client_order_id: 2a0e3fc9-b593-4aa3-96e5-82f7f7566c2a - fill_count: "5.00" - remaining_count: "0.00" - average_fill_price: "0.5800" - average_fee_paid: "0.0012" + fill_count: '5.00' + remaining_count: '0.00' + average_fill_price: '0.5800' + average_fee_paid: '0.0012' ts_ms: 1715793600456 properties: orders: @@ -7450,23 +8187,28 @@ components: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: false - description: Volume-weighted average fill price. Only present when fill_count > 0. + description: >- + Volume-weighted average fill price. Only present when + fill_count > 0. average_fee_paid: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: false - description: Volume-weighted average fee paid per contract. Only present when fill_count > 0. + description: >- + Volume-weighted average fee paid per contract. Only present + when fill_count > 0. ts_ms: type: integer format: int64 nullable: true x-omitempty: false - description: Matching engine timestamp at which the order was processed, as Unix epoch milliseconds. Absent when the request errored. + description: >- + Matching engine timestamp at which the order was processed, as + Unix epoch milliseconds. Absent when the request errored. error: allOf: - $ref: '#/components/schemas/ErrorResponse' nullable: true - BatchCancelOrdersV2Request: type: object required: @@ -7484,7 +8226,9 @@ components: type: array x-oapi-codegen-extra-tags: validate: required,dive - description: An array of orders to cancel, each optionally specifying a subaccount. + description: >- + An array of orders to cancel, each optionally specifying a + subaccount. items: type: object required: @@ -7497,19 +8241,22 @@ components: type: integer minimum: 0 default: 0 - description: Optional subaccount number to use for this cancellation (0 for primary, 1-63 for subaccounts). + description: >- + Optional subaccount number to use for this cancellation (0 for + primary, 1-63 for subaccounts). x-go-type-skip-optional-pointer: true exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' default: 0 - description: "Exchange shard index. Defaults to 0. Use -1 to auto-route by market ticker." + description: >- + Exchange shard index. Defaults to 0. Use -1 to auto-route by + market ticker. x-go-type-skip-optional-pointer: true market_ticker: type: string description: Market ticker. Required when exchange_index is -1 (auto). x-go-type-skip-optional-pointer: true - BatchCancelOrdersV2Response: type: object required: @@ -7518,11 +8265,11 @@ components: orders: - order_id: 3b23c1c7-f4ef-4f0d-8b9a-9e53c61f1a0d client_order_id: 8c35ecb3-328f-4f52-8c7c-0f4b9862f8d1 - reduced_by: "10.00" + reduced_by: '10.00' ts_ms: 1715793660456 - order_id: a6d6010d-6d5f-40a1-a7e7-5501386bb621 client_order_id: 2a0e3fc9-b593-4aa3-96e5-82f7f7566c2a - reduced_by: "5.00" + reduced_by: '5.00' ts_ms: 1715793660789 properties: orders: @@ -7535,25 +8282,30 @@ components: properties: order_id: type: string - description: The order ID identifying which order this entry corresponds to. + description: >- + The order ID identifying which order this entry corresponds + to. client_order_id: type: string nullable: true reduced_by: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts that were canceled (i.e. the remaining count at time of cancellation). Zero if the cancel errored. + description: >- + Number of contracts that were canceled (i.e. the remaining + count at time of cancellation). Zero if the cancel errored. ts_ms: type: integer format: int64 nullable: true x-omitempty: false - description: Matching engine timestamp at which the cancellation was processed, as Unix epoch milliseconds. Absent when the cancel errored. + description: >- + Matching engine timestamp at which the cancellation was + processed, as Unix epoch milliseconds. Absent when the cancel + errored. error: allOf: - $ref: '#/components/schemas/ErrorResponse' nullable: true - - # Multivariate Event Collection schemas AssociatedEvent: type: object required: @@ -7571,18 +8323,21 @@ components: type: integer format: int32 nullable: true - description: Maximum number of markets from this event (inclusive). Null means no limit. + description: >- + Maximum number of markets from this event (inclusive). Null means no + limit. size_min: type: integer format: int32 nullable: true - description: Minimum number of markets from this event (inclusive). Null means no limit. + description: >- + Minimum number of markets from this event (inclusive). Null means no + limit. active_quoters: type: array items: type: string description: List of active quoters for this event. - MultivariateEventCollection: type: object required: @@ -7606,7 +8361,9 @@ components: description: Unique identifier for the collection. series_ticker: type: string - description: Series associated with the collection. Events produced in the collection will be associated with this series. + description: >- + Series associated with the collection. Events produced in the + collection will be associated with this series. title: type: string description: Title of the collection. @@ -7616,11 +8373,15 @@ components: open_date: type: string format: date-time - description: The open date of the collection. Before this time, the collection cannot be interacted with. + description: >- + The open date of the collection. Before this time, the collection + cannot be interacted with. close_date: type: string format: date-time - description: The close date of the collection. After this time, the collection cannot be interacted with. + description: >- + The close date of the collection. After this time, the collection + cannot be interacted with. associated_events: type: array items: @@ -7630,28 +8391,44 @@ components: type: array items: type: string - description: '[DEPRECATED - Use associated_events instead] A list of events associated with the collection. Markets in these events can be passed as inputs to the Lookup and Create endpoints.' + description: >- + [DEPRECATED - Use associated_events instead] A list of events + associated with the collection. Markets in these events can be + passed as inputs to the Lookup and Create endpoints. is_ordered: type: boolean - description: Whether the collection is ordered. If true, the order of markets passed into Lookup/Create affects the output. If false, the order does not matter. + description: >- + Whether the collection is ordered. If true, the order of markets + passed into Lookup/Create affects the output. If false, the order + does not matter. is_single_market_per_event: type: boolean - description: '[DEPRECATED - Use associated_events instead] Whether the collection accepts multiple markets from the same event passed into Lookup/Create.' + description: >- + [DEPRECATED - Use associated_events instead] Whether the collection + accepts multiple markets from the same event passed into + Lookup/Create. is_all_yes: type: boolean - description: '[DEPRECATED - Use associated_events instead] Whether the collection requires that only the market side of ''yes'' may be used.' + description: >- + [DEPRECATED - Use associated_events instead] Whether the collection + requires that only the market side of 'yes' may be used. size_min: type: integer format: int32 - description: The minimum number of markets that must be passed into Lookup/Create (inclusive). + description: >- + The minimum number of markets that must be passed into Lookup/Create + (inclusive). size_max: type: integer format: int32 - description: The maximum number of markets that must be passed into Lookup/Create (inclusive). + description: >- + The maximum number of markets that must be passed into Lookup/Create + (inclusive). functional_description: type: string - description: A functional description of the collection describing how inputs affect the output. - + description: >- + A functional description of the collection describing how inputs + affect the output. GetMultivariateEventCollectionResponse: type: object required: @@ -7660,7 +8437,6 @@ components: multivariate_contract: $ref: '#/components/schemas/MultivariateEventCollection' description: The multivariate event collection. - GetMultivariateEventCollectionsResponse: type: object required: @@ -7673,9 +8449,13 @@ components: description: List of multivariate event collections. cursor: type: string - description: The Cursor represents a pointer to the next page of records in the pagination. Use the value returned here in the cursor query parameter for this end-point to get the next page containing limit records. An empty value of this field indicates there is no next page. + description: >- + The Cursor represents a pointer to the next page of records in the + pagination. Use the value returned here in the cursor query + parameter for this end-point to get the next page containing limit + records. An empty value of this field indicates there is no next + page. x-go-type-skip-optional-pointer: true - TickerPair: type: object required: @@ -7691,11 +8471,12 @@ components: description: Event ticker identifier. side: type: string - enum: ['yes', 'no'] + enum: + - 'yes' + - 'no' description: Side of the market (yes or no). x-oapi-codegen-extra-tags: validate: required,oneof=yes no - LookupTickersForMarketInMultivariateEventCollectionRequest: type: object required: @@ -7705,8 +8486,9 @@ components: type: array items: $ref: '#/components/schemas/TickerPair' - description: List of selected markets that act as parameters to determine which market is produced. - + description: >- + List of selected markets that act as parameters to determine which + market is produced. LookupTickersForMarketInMultivariateEventCollectionResponse: type: object required: @@ -7719,7 +8501,6 @@ components: market_ticker: type: string description: Market ticker for the looked up market. - CreateMarketInMultivariateEventCollectionRequest: type: object required: @@ -7729,13 +8510,14 @@ components: type: array items: $ref: '#/components/schemas/TickerPair' - description: List of selected markets that act as parameters to determine which market is created. + description: >- + List of selected markets that act as parameters to determine which + market is created. x-oapi-codegen-extra-tags: validate: required,dive with_market_payload: type: boolean description: Whether to include the market payload in the response. - CreateMarketInMultivariateEventCollectionResponse: type: object required: @@ -7751,16 +8533,20 @@ components: market: $ref: '#/components/schemas/Market' description: Market payload of the created market. - # Market Orderbook schemas PriceLevelDollarsCountFp: type: array minItems: 2 maxItems: 2 - example: ["0.1500", "100.00"] + example: + - '0.1500' + - '100.00' items: type: string - description: Price level in dollars represented as [dollars_string, fp] where dollars_string is like "0.1500" and fp is a FixedPointCount string (fixed-point contract count). The second element is the contract quantity (not price). - + description: >- + Price level in dollars represented as [dollars_string, fp] where + dollars_string is like "0.1500" and fp is a FixedPointCount string + (fixed-point contract count). The second element is the contract + quantity (not price). OrderbookCountFp: type: object required: @@ -7775,8 +8561,9 @@ components: type: array items: $ref: '#/components/schemas/PriceLevelDollarsCountFp' - description: Orderbook with fixed-point contract counts (fp) in all dollar price levels. - + description: >- + Orderbook with fixed-point contract counts (fp) in all dollar price + levels. GetMarketOrderbooksResponse: type: object required: @@ -7786,7 +8573,6 @@ components: type: array items: $ref: '#/components/schemas/MarketOrderbookFp' - MarketOrderbookFp: type: object required: @@ -7797,7 +8583,6 @@ components: type: string orderbook_fp: $ref: '#/components/schemas/OrderbookCountFp' - GetMarketOrderbookResponse: type: object required: @@ -7806,7 +8591,6 @@ components: orderbook_fp: $ref: '#/components/schemas/OrderbookCountFp' description: Orderbook with fixed-point contract counts (fp) in all price levels. - GetEventsResponse: type: object required: @@ -7825,8 +8609,9 @@ components: $ref: '#/components/schemas/Milestone' cursor: type: string - description: Pagination cursor for the next page. Empty if there are no more results. - + description: >- + Pagination cursor for the next page. Empty if there are no more + results. GetMultivariateEventsResponse: type: object required: @@ -7840,8 +8625,9 @@ components: $ref: '#/components/schemas/EventData' cursor: type: string - description: Pagination cursor for the next page. Empty if there are no more results. - + description: >- + Pagination cursor for the next page. Empty if there are no more + results. EventFeeChange: type: object required: @@ -7866,17 +8652,21 @@ components: - $ref: '#/components/schemas/FeeType' nullable: true example: quadratic - description: New fee type override for the event. When null, the event clears any prior override and falls back to the parent series' fee structure. + description: >- + New fee type override for the event. When null, the event clears any + prior override and falls back to the parent series' fee structure. fee_multiplier_override: type: number format: double nullable: true - description: New fee multiplier override for the event. When null, the event clears any prior override and falls back to the parent series' fee multiplier. + description: >- + New fee multiplier override for the event. When null, the event + clears any prior override and falls back to the parent series' fee + multiplier. scheduled_ts: type: string format: date-time description: Timestamp when this fee change is scheduled to take effect - GetEventFeeChangesResponse: type: object required: @@ -7889,8 +8679,9 @@ components: $ref: '#/components/schemas/EventFeeChange' cursor: type: string - description: Pagination cursor for the next page. Empty if there are no more results. - + description: >- + Pagination cursor for the next page. Empty if there are no more + results. GetEventResponse: type: object required: @@ -7902,10 +8693,13 @@ components: description: Data for the event. markets: type: array - description: Data for the markets in this event. This field is deprecated in favour of the "markets" field inside the event. Which will be filled with the same value if you use the query parameter "with_nested_markets=true". + description: >- + Data for the markets in this event. This field is deprecated in + favour of the "markets" field inside the event. Which will be filled + with the same value if you use the query parameter + "with_nested_markets=true". items: $ref: '#/components/schemas/Market' - MarketMetadata: type: object required: @@ -7922,7 +8716,6 @@ components: color_code: type: string description: The color code for the market. - GetEventMetadataResponse: type: object required: @@ -7958,7 +8751,6 @@ components: x-omitempty: true description: Event scope, based on the competition. x-go-type-skip-optional-pointer: true - GetEventForecastPercentilesHistoryResponse: type: object required: @@ -7969,7 +8761,6 @@ components: description: Array of forecast percentile data points over time. items: $ref: '#/components/schemas/ForecastPercentilesPoint' - ForecastPercentilesPoint: type: object required: @@ -7994,7 +8785,6 @@ components: description: Array of forecast values at different percentiles. items: $ref: '#/components/schemas/PercentilePoint' - PercentilePoint: type: object required: @@ -8016,7 +8806,6 @@ components: formatted_forecast: type: string description: The human-readable formatted forecast value. - EventData: type: object required: @@ -8043,10 +8832,14 @@ components: description: Full title of the event. collateral_return_type: type: string - description: Specifies how collateral is returned when markets settle (e.g., 'binary' for standard yes/no markets). + description: >- + Specifies how collateral is returned when markets settle (e.g., + 'binary' for standard yes/no markets). mutually_exclusive: type: boolean - description: If true, only one market in this event can resolve to 'yes'. If false, multiple markets can resolve to 'yes'. + description: >- + If true, only one market in this event can resolve to 'yes'. If + false, multiple markets can resolve to 'yes'. category: type: string description: Event category (deprecated, use series-level category instead). @@ -8057,16 +8850,23 @@ components: format: date-time nullable: true x-omitempty: true - description: The specific date this event is based on. Only filled when the event uses a date strike (mutually exclusive with strike_period). + description: >- + The specific date this event is based on. Only filled when the event + uses a date strike (mutually exclusive with strike_period). strike_period: type: string nullable: true x-omitempty: true - description: The time period this event covers (e.g., 'week', 'month'). Only filled when the event uses a period strike (mutually exclusive with strike_date). + description: >- + The time period this event covers (e.g., 'week', 'month'). Only + filled when the event uses a period strike (mutually exclusive with + strike_date). markets: type: array x-omitempty: true - description: Array of markets associated with this event. Only populated when 'with_nested_markets=true' is specified in the request. + description: >- + Array of markets associated with this event. Only populated when + 'with_nested_markets=true' is specified in the request. items: $ref: '#/components/schemas/Market' x-go-type-skip-optional-pointer: true @@ -8084,7 +8884,9 @@ components: nullable: true items: $ref: '#/components/schemas/SettlementSource' - description: The official sources used for the determination of markets within this event. Methodology is defined in the rulebook. + description: >- + The official sources used for the determination of markets within + this event. Methodology is defined in the rulebook. last_updated_ts: type: string format: date-time @@ -8093,18 +8895,21 @@ components: type: string nullable: true x-omitempty: true - description: Fee type override for this event. When present, takes precedence over the series-level fee for this event's markets. + description: >- + Fee type override for this event. When present, takes precedence + over the series-level fee for this event's markets. fee_multiplier_override: type: number format: double nullable: true x-omitempty: true - description: Fee multiplier override for this event. Paired with fee_type_override. + description: >- + Fee multiplier override for this event. Paired with + fee_type_override. exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - Series: type: object required: @@ -8125,10 +8930,16 @@ components: description: Ticker that identifies this series. frequency: type: string - description: Description of the frequency of the series. There is no fixed value set here, but will be something human-readable like weekly, daily, one-off. + description: >- + Description of the frequency of the series. There is no fixed value + set here, but will be something human-readable like weekly, daily, + one-off. title: type: string - description: Title describing the series. For full context use you should use this field with the title field of the events belonging to this series. + description: >- + Title describing the series. For full context use you should use + this field with the title field of the events belonging to this + series. category: type: string description: Category specifies the category which this series belongs to. @@ -8137,19 +8948,28 @@ components: nullable: true items: type: string - description: Tags specifies the subjects that this series relates to, multiple series from different categories can have the same tags. + description: >- + Tags specifies the subjects that this series relates to, multiple + series from different categories can have the same tags. settlement_sources: type: array nullable: true items: $ref: '#/components/schemas/SettlementSource' - description: SettlementSources specifies the official sources used for the determination of markets within the series. Methodology is defined in the rulebook. + description: >- + SettlementSources specifies the official sources used for the + determination of markets within the series. Methodology is defined + in the rulebook. contract_url: type: string - description: ContractUrl provides a direct link to the original filing of the contract which underlies the series. + description: >- + ContractUrl provides a direct link to the original filing of the + contract which underlies the series. contract_terms_url: type: string - description: ContractTermsUrl is the URL to the current terms of the contract underlying the series. + description: >- + ContractTermsUrl is the URL to the current terms of the contract + underlying the series. product_metadata: type: object nullable: true @@ -8158,24 +8978,36 @@ components: fee_type: allOf: - $ref: '#/components/schemas/FeeType' - description: "FeeType is a string representing the series' fee structure. Fee structures can be found at https://kalshi.com/docs/kalshi-fee-schedule.pdf. 'quadratic' is described by the General Trading Fees Table, 'quadratic_with_maker_fees' is described by the General Trading Fees Table with maker fees described in the Maker Fees section, 'flat' is described by the Specific Trading Fees Table." + description: >- + FeeType is a string representing the series' fee structure. Fee + structures can be found at + https://kalshi.com/docs/kalshi-fee-schedule.pdf. 'quadratic' is + described by the General Trading Fees Table, + 'quadratic_with_maker_fees' is described by the General Trading Fees + Table with maker fees described in the Maker Fees section, 'flat' is + described by the Specific Trading Fees Table. fee_multiplier: type: number format: double - description: FeeMultiplier is a floating point multiplier applied to the fee calculations. + description: >- + FeeMultiplier is a floating point multiplier applied to the fee + calculations. additional_prohibitions: type: array items: type: string - description: AdditionalProhibitions is a list of additional trading prohibitions for this series. + description: >- + AdditionalProhibitions is a list of additional trading prohibitions + for this series. volume_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the total number of contracts traded across all events in this series. + description: >- + String representation of the total number of contracts traded across + all events in this series. last_updated_ts: type: string format: date-time description: Timestamp of when this series' metadata was last updated. - SeriesFeeChange: type: object required: @@ -8203,7 +9035,6 @@ components: type: string format: date-time description: Timestamp when this fee change is scheduled to take effect - GetSeriesResponse: type: object required: @@ -8211,7 +9042,6 @@ components: properties: series: $ref: '#/components/schemas/Series' - GetSeriesListResponse: type: object required: @@ -8221,7 +9051,6 @@ components: type: array items: $ref: '#/components/schemas/Series' - GetSeriesFeeChangesResponse: type: object required: @@ -8231,7 +9060,6 @@ components: type: array items: $ref: '#/components/schemas/SeriesFeeChange' - SettlementSource: type: object properties: @@ -8243,7 +9071,6 @@ components: type: string description: URL to the settlement source x-go-type-skip-optional-pointer: true - GetMarketsResponse: type: object required: @@ -8256,7 +9083,6 @@ components: $ref: '#/components/schemas/Market' cursor: type: string - GetMarketResponse: type: object required: @@ -8264,7 +9090,6 @@ components: properties: market: $ref: '#/components/schemas/Market' - MveSelectedLeg: type: object properties: @@ -8284,8 +9109,9 @@ components: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: true - description: The settlement value of the YES/LONG side of the contract in dollars. Only filled after determination - + description: >- + The settlement value of the YES/LONG side of the contract in + dollars. Only filled after determination PriceRange: type: object required: @@ -8302,7 +9128,6 @@ components: step: type: string description: Price step/tick size for this range in dollars - Market: type: object required: @@ -8331,7 +9156,6 @@ components: - previous_price_dollars - volume_fp - volume_24h_fp - - liquidity_dollars - open_interest_fp - result - can_close_early @@ -8347,7 +9171,9 @@ components: type: string market_type: type: string - enum: [binary, scalar] + enum: + - binary + - scalar description: Identifies the type of market title: type: string @@ -8396,20 +9222,32 @@ components: description: The amount of time after determination that the market settles status: type: string - enum: [initialized, inactive, active, closed, determined, disputed, amended, finalized] + enum: + - initialized + - inactive + - active + - closed + - determined + - disputed + - amended + - finalized description: The current status of the market in its lifecycle. yes_bid_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Price for the highest YES buy offer on this market in dollars yes_bid_size_fp: $ref: '#/components/schemas/FixedPointCount' - description: Total contract size of orders to buy YES at the best bid price (fixed-point count string). + description: >- + Total contract size of orders to buy YES at the best bid price + (fixed-point count string). yes_ask_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Price for the lowest YES sell offer on this market in dollars yes_ask_size_fp: $ref: '#/components/schemas/FixedPointCount' - description: Total contract size of orders to sell YES at the best ask price (fixed-point count string). + description: >- + Total contract size of orders to sell YES at the best ask price + (fixed-point count string). no_bid_dollars: $ref: '#/components/schemas/FixedPointDollars' description: Price for the highest NO buy offer on this market in dollars @@ -8427,39 +9265,59 @@ components: description: String representation of the 24h market volume in contracts result: type: string - enum: ['yes', 'no', 'scalar', ''] + enum: + - 'yes' + - 'no' + - scalar + - '' can_close_early: type: boolean open_interest_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the number of contracts bought on this market disconsidering netting + description: >- + String representation of the number of contracts bought on this + market disconsidering netting notional_value_dollars: $ref: '#/components/schemas/FixedPointDollars' description: The total value of a single contract at settlement in dollars previous_yes_bid_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Price for the highest YES buy offer on this market a day ago in dollars + description: >- + Price for the highest YES buy offer on this market a day ago in + dollars previous_yes_ask_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Price for the lowest YES sell offer on this market a day ago in dollars + description: >- + Price for the lowest YES sell offer on this market a day ago in + dollars previous_price_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Price for the last traded YES contract on this market a day ago in dollars + description: >- + Price for the last traded YES contract on this market a day ago in + dollars liquidity_dollars: - $ref: '#/components/schemas/FixedPointDollars' + allOf: + - $ref: '#/components/schemas/FixedPointDollars' deprecated: true - description: 'DEPRECATED: This field is deprecated and will always return "0.0000".' + x-go-type-skip-optional-pointer: true + description: >- + DEPRECATED: This field is deprecated and will always return + "0.0000". settlement_value_dollars: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: true - description: The settlement value of the YES/LONG side of the contract in dollars. Only filled after determination + description: >- + The settlement value of the YES/LONG side of the contract in + dollars. Only filled after determination settlement_ts: type: string format: date-time nullable: true x-omitempty: true - description: Timestamp when the market was settled. Only filled for settled markets + description: >- + Timestamp when the market was settled. Only filled for settled + markets expiration_value: type: string description: The value that was considered for the settlement @@ -8467,7 +9325,9 @@ components: type: string format: date-time nullable: true - description: The recorded datetime when the underlying event occurred, if available + description: >- + The recorded datetime when the underlying event occurred, if + available fee_waiver_expiration_time: type: string format: date-time @@ -8482,7 +9342,15 @@ components: x-go-type-skip-optional-pointer: true strike_type: type: string - enum: [greater, greater_or_equal, less, less_or_equal, between, functional, custom, structured] + enum: + - greater + - greater_or_equal + - less + - less_or_equal + - between + - functional + - custom + - structured x-omitempty: true description: Strike type defines how the market strike is defined and evaluated x-go-type-skip-optional-pointer: true @@ -8531,7 +9399,9 @@ components: x-omitempty: true price_level_structure: type: string - description: Price level structure for this market, defining price ranges and tick sizes + description: >- + Price level structure for this market, defining price ranges and + tick sizes price_ranges: type: array description: Valid price ranges for orders on this market @@ -8540,13 +9410,14 @@ components: is_provisional: type: boolean x-omitempty: true - description: If true, the market may be removed after determination if there is no activity on it + description: >- + If true, the market may be removed after determination if there is + no activity on it x-go-type-skip-optional-pointer: true exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - tags: - name: api-keys description: API key management endpoints diff --git a/specs/perps_openapi.yaml b/specs/perps_openapi.yaml index 814f1ca..9deaf8d 100644 --- a/specs/perps_openapi.yaml +++ b/specs/perps_openapi.yaml @@ -2,14 +2,14 @@ openapi: 3.0.0 info: title: Kalshi Trade API Manual Endpoints version: 0.0.1 - description: Manually defined OpenAPI spec for endpoints being migrated to spec-first approach - + description: >- + Manually defined OpenAPI spec for endpoints being migrated to spec-first + approach servers: - url: https://external-api.kalshi.com/trade-api/v2 description: Production perps REST API server - url: https://external-api.demo.kalshi.co/trade-api/v2 description: Demo perps REST API server - paths: /account/limits/perps: get: @@ -33,12 +33,11 @@ paths: description: Unauthorized '500': description: Internal server error - /margin/exchange/status: get: operationId: GetMarginExchangeStatus summary: Get Exchange Status - description: 'Endpoint for getting the margin exchange status.' + description: Endpoint for getting the margin exchange status. tags: - exchange responses: @@ -66,12 +65,13 @@ paths: application/json: schema: $ref: '#/components/schemas/ExchangeStatus' - /margin/risk_parameters: get: operationId: GetMarginRiskParameters summary: Get Risk Parameters - description: 'Returns system-wide margin risk parameters including liquidation thresholds and per-market initial margin multipliers.' + description: >- + Returns system-wide margin risk parameters including liquidation + thresholds and per-market initial margin multipliers. tags: - risk responses: @@ -81,12 +81,11 @@ paths: application/json: schema: $ref: '#/components/schemas/GetMarginRiskParametersResponse' - /margin/orders: get: operationId: GetMarginOrders summary: Get Orders - description: 'Endpoint for listing margin orders with optional filtering.' + description: Endpoint for listing margin orders with optional filtering. tags: - orders security: @@ -147,14 +146,15 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /margin/fcm/orders: get: operationId: GetMarginFCMOrders summary: Get FCM Orders - description: | + description: > Endpoint for FCM members to get margin orders filtered by subtrader ID. - This endpoint requires FCM member access level and allows filtering margin orders by subtrader ID. + + This endpoint requires FCM member access level and allows filtering + margin orders by subtrader ID. tags: - fcm security: @@ -165,7 +165,9 @@ paths: - name: subtrader_id in: query required: true - description: Restricts the response to margin orders for a specific subtrader (FCM members only) + description: >- + Restricts the response to margin orders for a specific subtrader + (FCM members only) schema: type: string - $ref: '#/components/parameters/TickerQuery' @@ -187,7 +189,6 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/orders/{order_id}: get: operationId: GetMarginOrder @@ -214,11 +215,12 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - delete: operationId: CancelMarginOrder summary: Cancel Order - description: Endpoint for canceling an order. Cancels all remaining resting contracts and returns the canceled order details. + description: >- + Endpoint for canceling an order. Cancels all remaining resting contracts + and returns the canceled order details. tags: - orders security: @@ -241,12 +243,14 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/orders/{order_id}/decrease: post: operationId: DecreaseMarginOrder summary: Decrease Order - description: Endpoint for decreasing the number of contracts in an existing order. Exactly one of `reduce_by` or `reduce_to` must be provided. Canceling an order is equivalent to decreasing to zero. + description: >- + Endpoint for decreasing the number of contracts in an existing order. + Exactly one of `reduce_by` or `reduce_to` must be provided. Canceling an + order is equivalent to decreasing to zero. tags: - orders security: @@ -277,16 +281,22 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/orders/{order_id}/amend: post: operationId: AmendMarginOrder summary: Amend Order - description: Endpoint for amending the price and/or max number of fillable contracts in an existing margin order. + description: >- + Endpoint for amending the price and/or max number of fillable contracts + in an existing margin order. x-mint: - content: | + content: > - Amending a resting order preserves queue position only when the amendment decreases size. All other amendments — like increasing size or changing price forfeit queue position and place the order at the back of the queue. + + Amending a resting order preserves queue position only when the + amendment decreases size. All other amendments — like increasing size + or changing price forfeit queue position and place the order at the + back of the queue. + tags: - orders @@ -318,7 +328,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/markets: get: operationId: GetMarginMarkets @@ -347,12 +356,13 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /margin/markets/{ticker}: get: operationId: GetMarginMarket summary: Get Market - description: Endpoint for fetching a margin market with trading stats (price, volume, open interest). + description: >- + Endpoint for fetching a margin market with trading stats (price, volume, + open interest). tags: - market parameters: @@ -377,7 +387,6 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /margin/markets/{ticker}/orderbook: get: operationId: GetMarginMarketOrderbook @@ -402,7 +411,9 @@ paths: default: 0 - name: aggregation_tick_size in: query - description: Tick size in dollars for aggregating price levels (e.g., 0.10 for 10 cent buckets) + description: >- + Tick size in dollars for aggregating price levels (e.g., 0.10 for 10 + cent buckets) required: false schema: type: string @@ -421,7 +432,6 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /margin/markets/{ticker}/candlesticks: get: operationId: GetMarginMarketCandlesticks @@ -439,34 +449,49 @@ paths: - name: start_ts in: query required: true - description: Start timestamp (Unix timestamp). Candlesticks will include those ending on or after this time. + description: >- + Start timestamp (Unix timestamp). Candlesticks will include those + ending on or after this time. schema: type: integer format: int64 - name: end_ts in: query required: true - description: End timestamp (Unix timestamp). Candlesticks will include those ending on or before this time. + description: >- + End timestamp (Unix timestamp). Candlesticks will include those + ending on or before this time. schema: type: integer format: int64 - name: period_interval in: query required: true - description: Time period length of each candlestick in minutes. Valid values are 1 (1 minute), 60 (1 hour), or 1440 (1 day). + description: >- + Time period length of each candlestick in minutes. Valid values are + 1 (1 minute), 60 (1 hour), or 1440 (1 day). schema: type: integer - enum: [1, 60, 1440] + enum: + - 1 + - 60 + - 1440 x-oapi-codegen-extra-tags: - validate: "required,oneof=1 60 1440" + validate: required,oneof=1 60 1440 - name: include_latest_before_start in: query required: false - description: | - If true, prepends the latest candlestick available before the start_ts. This synthetic candlestick is created by: + description: > + If true, prepends the latest candlestick available before the + start_ts. This synthetic candlestick is created by: + 1. Finding the most recent real candlestick before start_ts - 2. Projecting it forward to the first period boundary (calculated as the next period interval after start_ts) - 3. Setting all OHLC prices to null, and `price.previous` to the close price from the real candlestick + + 2. Projecting it forward to the first period boundary (calculated as + the next period interval after start_ts) + + 3. Setting all OHLC prices to null, and `price.previous` to the + close price from the real candlestick schema: type: boolean default: false @@ -483,7 +508,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/fills: get: operationId: GetMarginFills @@ -547,12 +571,11 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/positions: get: operationId: GetMarginPositions summary: Get Positions - description: 'Endpoint for retrieving the authenticated user''s margin positions.' + description: Endpoint for retrieving the authenticated user's margin positions. tags: - portfolio security: @@ -586,12 +609,14 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/trades: get: operationId: GetMarginTrades summary: Get Trades - description: 'Endpoint for retrieving public margin trades for a given market ticker. Returns a paginated response. Use the cursor value from the previous response to get the next page.' + description: >- + Endpoint for retrieving public margin trades for a given market ticker. + Returns a paginated response. Use the cursor value from the previous + response to get the next page. tags: - market parameters: @@ -643,12 +668,13 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /margin/enabled: get: operationId: GetMarginEnabled summary: Get Enabled Status - description: Endpoint for checking if margin trading is enabled for the authenticated user. + description: >- + Endpoint for checking if margin trading is enabled for the authenticated + user. tags: - exchange security: @@ -666,12 +692,13 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/notional_risk_limit: get: operationId: GetMarginNotionalRiskLimit summary: Get Notional Risk Limit - description: 'Endpoint for retrieving the notional value risk limit for the authenticated margin user.' + description: >- + Endpoint for retrieving the notional value risk limit for the + authenticated margin user. tags: - risk security: @@ -689,16 +716,24 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/balance: get: operationId: GetMarginBalance summary: Get Balance - description: 'Endpoint for retrieving the balance breakdown for the authenticated direct margin user. Returns cash balance (aggregate and per-subaccount), position value, total balance, and maintenance margin requirement.' + description: >- + Endpoint for retrieving the balance breakdown for the authenticated + direct margin user. Returns cash balance (aggregate and per-subaccount), + position value, total balance, and maintenance margin requirement. x-mint: - content: | + content: > - **Rate limit:** 5 tokens per request, or 50 tokens when `compute_available_balance=true` (the available-balance computation scans all resting orders). See `GET /trade-api/v2/account/endpoint_costs` for current non-default endpoint costs. + + **Rate limit:** 5 tokens per request, or 50 tokens when + `compute_available_balance=true` (the available-balance computation + scans all resting orders). See `GET + /trade-api/v2/account/endpoint_costs` for current non-default endpoint + costs. + tags: - portfolio @@ -714,7 +749,10 @@ paths: type: boolean default: false x-go-type-skip-optional-pointer: true - description: 'When true, computes available_balance per subaccount at an increased rate limit cost. Available balance is 0 when the flag is false or omitted.' + description: >- + When true, computes available_balance per subaccount at an increased + rate limit cost. Available balance is 0 when the flag is false or + omitted. responses: '200': description: Margin balance retrieved successfully @@ -730,12 +768,15 @@ paths: $ref: '#/components/responses/RateLimitError' '500': $ref: '#/components/responses/InternalServerError' - /margin/risk: get: operationId: GetMarginRisk summary: Get Risk - description: 'Endpoint for retrieving leverage and liquidation price data for the authenticated direct margin user. Returns account-level leverage plus per-position leverage and liquidation prices, grouped by subaccount and market.' + description: >- + Endpoint for retrieving leverage and liquidation price data for the + authenticated direct margin user. Returns account-level leverage plus + per-position leverage and liquidation prices, grouped by subaccount and + market. tags: - risk security: @@ -755,12 +796,14 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - /margin/fee_tiers: get: operationId: GetMarginFeeTiers summary: Get Fee Tiers - description: 'Endpoint for retrieving the margin fee tiers for the authenticated direct margin user. Returns a map of margin market tickers to their fee tier strings.' + description: >- + Endpoint for retrieving the margin fee tiers for the authenticated + direct margin user. Returns a map of margin market tickers to their fee + tier strings. tags: - fees security: @@ -778,12 +821,15 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/funding_history: get: operationId: GetMarginFundingHistory summary: Get Funding History - description: 'Endpoint for retrieving the authenticated user''s historical margin funding payments joined with funding rates for a specific market, or across all markets when ticker is empty, over an inclusive UTC date range.' + description: >- + Endpoint for retrieving the authenticated user's historical margin + funding payments joined with funding rates for a specific market, or + across all markets when ticker is empty, over an inclusive UTC date + range. tags: - funding security: @@ -794,14 +840,18 @@ paths: - name: ticker in: query required: false - description: Market ticker for funding history. Leave empty to query across all markets. + description: >- + Market ticker for funding 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 funding history range (YYYY-MM-DD format) + description: >- + Inclusive UTC start date for funding history range (YYYY-MM-DD + format) schema: type: string format: date @@ -834,12 +884,13 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - /margin/funding_rates/historical: get: operationId: GetMarginHistoricalFundingRates summary: Get Historical Funding Rates - description: Endpoint for retrieving historical margin funding rates for a market, or across all markets when ticker is empty. + description: >- + Endpoint for retrieving historical margin funding rates for a market, or + across all markets when ticker is empty. tags: - funding parameters: @@ -853,14 +904,18 @@ paths: - name: start_ts in: query required: false - description: Start timestamp (Unix timestamp in seconds). If omitted, defaults to the earliest available data. + description: >- + Start timestamp (Unix timestamp in seconds). If omitted, defaults to + the earliest available data. schema: type: integer format: int64 - name: end_ts in: query required: false - description: End timestamp (Unix timestamp in seconds). If omitted, defaults to the current time. + description: >- + End timestamp (Unix timestamp in seconds). If omitted, defaults to + the current time. schema: type: integer format: int64 @@ -875,13 +930,16 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /margin/funding_rates/estimate: get: operationId: GetMarginFundingRateEstimate summary: Get Funding Rate Estimate - description: | - Returns the estimated funding rate for the current, in-progress funding period. The value is a time-weighted average of the premium index computed over `[last_funding_time, now)`, so it continues to move as new data accumulates through the window and is only finalized at `next_funding_time`. + description: > + Returns the estimated funding rate for the current, in-progress funding + period. The value is a time-weighted average of the premium index + computed over `[last_funding_time, now)`, so it continues to move as new + data accumulates through the window and is only finalized at + `next_funding_time`. tags: - funding parameters: @@ -905,7 +963,6 @@ paths: $ref: '#/components/responses/BadRequestError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/intra_exchange_instance_transfer: post: operationId: IntraExchangeInstanceTransfer @@ -938,12 +995,14 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/margin/subaccounts: post: operationId: CreateMarginSubaccount summary: Create Subaccount - description: 'Creates a new subaccount for the authenticated user in the margin exchange. Subaccounts are numbered sequentially starting from 1. Maximum 63 numbered subaccounts per user (64 including the primary account).' + description: >- + Creates a new subaccount for the authenticated user in the margin + exchange. Subaccounts are numbered sequentially starting from 1. Maximum + 63 numbered subaccounts per user (64 including the primary account). tags: - portfolio security: @@ -965,12 +1024,13 @@ paths: $ref: '#/components/responses/ForbiddenError' '500': $ref: '#/components/responses/InternalServerError' - /portfolio/margin/subaccounts/transfer: post: operationId: ApplyMarginSubaccountTransfer summary: Transfer Between Subaccounts - description: 'Transfers funds between the authenticated user''s margin subaccounts. Use 0 for the primary account, or 1-63 for numbered subaccounts.' + description: >- + Transfers funds between the authenticated user's margin subaccounts. Use + 0 for the primary account, or 1-63 for numbered subaccounts. tags: - portfolio security: @@ -996,12 +1056,13 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/order_groups: get: operationId: GetMarginOrderGroups summary: Get Order Groups - description: 'Retrieves all order groups for the authenticated user on the margin exchange.' + description: >- + Retrieves all order groups for the authenticated user on the margin + exchange. tags: - order-groups security: @@ -1023,12 +1084,14 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/order_groups/create: post: operationId: CreateMarginOrderGroup summary: Create Order Group - description: 'Creates a new order group on the margin exchange with a contracts limit measured over a rolling window. When the limit is hit, all orders in the group are cancelled and no new orders can be placed until reset.' + description: >- + Creates a new order group on the margin exchange with a contracts limit + measured over a rolling window. When the limit is hit, all orders in the + group are cancelled and no new orders can be placed until reset. tags: - order-groups security: @@ -1054,12 +1117,13 @@ paths: $ref: '#/components/responses/UnauthorizedError' '500': $ref: '#/components/responses/InternalServerError' - /margin/order_groups/{order_group_id}: get: operationId: GetMarginOrderGroup summary: Get Order Group - description: 'Retrieves details for a single order group on the margin exchange including all order IDs and auto-cancel status.' + description: >- + Retrieves details for a single order group on the margin exchange + including all order IDs and auto-cancel status. tags: - order-groups security: @@ -1085,7 +1149,9 @@ paths: delete: operationId: DeleteMarginOrderGroup summary: Delete Order Group - description: 'Deletes an order group on the margin exchange and cancels all orders within it.' + description: >- + Deletes an order group on the margin exchange and cancels all orders + within it. tags: - order-groups security: @@ -1108,12 +1174,14 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/order_groups/{order_group_id}/reset: put: operationId: ResetMarginOrderGroup summary: Reset Order Group - description: 'Resets the order group matched contracts counter to zero on the margin exchange, allowing new orders to be placed again after the limit was hit.' + description: >- + Resets the order group matched contracts counter to zero on the margin + exchange, allowing new orders to be placed again after the limit was + hit. tags: - order-groups security: @@ -1142,12 +1210,13 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/order_groups/{order_group_id}/trigger: put: operationId: TriggerMarginOrderGroup summary: Trigger Order Group - description: 'Triggers the order group on the margin exchange, canceling all orders in the group and preventing new orders until the group is reset.' + description: >- + Triggers the order group on the margin exchange, canceling all orders in + the group and preventing new orders until the group is reset. tags: - order-groups security: @@ -1176,12 +1245,14 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - /margin/order_groups/{order_group_id}/limit: put: operationId: UpdateMarginOrderGroupLimit summary: Update Order Group Limit - description: 'Updates the order group contracts limit on the margin exchange. If the updated limit would immediately trigger the group, all orders in the group are canceled and the group is triggered.' + description: >- + Updates the order group contracts limit on the margin exchange. If the + updated limit would immediately trigger the group, all orders in the + group are canceled and the group is triggered. tags: - order-groups security: @@ -1212,7 +1283,6 @@ paths: $ref: '#/components/responses/NotFoundError' '500': $ref: '#/components/responses/InternalServerError' - components: securitySchemes: kalshiAccessKey: @@ -1262,7 +1332,9 @@ components: schema: $ref: '#/components/schemas/ErrorResponse' RateLimitError: - description: 'Rate limit exceeded. The default cost is 10 tokens per request. Use GET /trade-api/v2/account/endpoint_costs to list non-default endpoint costs.' + description: >- + Rate limit exceeded. The default cost is 10 tokens per request. Use GET + /trade-api/v2/account/endpoint_costs to list non-default endpoint costs. content: application/json: schema: @@ -1287,13 +1359,17 @@ components: format: uuid description: Unique client-provided transfer ID for idempotency. x-oapi-codegen-extra-tags: - validate: "required" + validate: required from_subaccount: type: integer - description: Source subaccount number (0 for primary, 1-63 for numbered subaccounts). + description: >- + Source subaccount number (0 for primary, 1-63 for numbered + subaccounts). to_subaccount: type: integer - description: Destination subaccount number (0 for primary, 1-63 for numbered subaccounts). + description: >- + Destination subaccount number (0 for primary, 1-63 for numbered + subaccounts). amount_cents: type: integer format: int64 @@ -1307,21 +1383,31 @@ components: subaccount: type: integer minimum: 0 - description: Optional subaccount number to use for this order group (0 for primary, 1-63 for subaccounts) + description: >- + Optional subaccount number to use for this order group (0 for + primary, 1-63 for subaccounts) default: 0 x-go-type-skip-optional-pointer: true contracts_limit: type: integer format: int64 minimum: 1 - description: Specifies the maximum number of contracts that can be matched within this group over a rolling 15-second window. Whole contracts only. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + Specifies the maximum number of contracts that can be matched within + this group over a rolling 15-second window. Whole contracts only. + Provide contracts_limit or contracts_limit_fp; if both provided they + must match. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: validate: omitempty,gte=1 contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the maximum number of contracts that can be matched within this group over a rolling 15-second window. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + String representation of the maximum number of contracts that can be + matched within this group over a rolling 15-second window. Provide + contracts_limit or contracts_limit_fp; if both provided they must + match. exchange_index: allOf: - $ref: '#/components/schemas/ExchangeIndex' @@ -1339,7 +1425,9 @@ components: subaccount: type: integer minimum: 0 - description: Subaccount number that owns the created order group (0 for primary, 1-63 for subaccounts). + description: >- + Subaccount number that owns the created order group (0 for primary, + 1-63 for subaccounts). x-go-type-skip-optional-pointer: true exchange_index: allOf: @@ -1353,7 +1441,6 @@ components: subaccount_number: type: integer description: The sequential number assigned to this subaccount (1-63). - # Order Group schemas EmptyResponse: type: object description: An empty response body @@ -1374,11 +1461,15 @@ components: description: The name of the service that generated the error ExchangeIndex: type: integer - description: "Identifier for an exchange shard. Defaults to 0 if unspecified. Note: currently only 0 supported." + description: >- + Identifier for an exchange shard. Defaults to 0 if unspecified. Note: + currently only 0 supported. example: 0 ExchangeInstance: type: string - enum: ['event_contract', 'margined'] + enum: + - event_contract + - margined description: The exchange instance type BucketLimit: type: object @@ -1420,7 +1511,10 @@ components: $ref: '#/components/schemas/BucketLimit' grants: type: array - description: The caller's active API usage level grants across exchange lanes, where each grant applies to its exchange_instance and usage_tier reflects the effective tier for the lane reported by this endpoint. + description: >- + The caller's active API usage level grants across exchange lanes, + where each grant applies to its exchange_instance and usage_tier + reflects the effective tier for the lane reported by this endpoint. items: $ref: '#/components/schemas/ApiUsageLevelGrant' ApiUsageLevelGrant: @@ -1439,19 +1533,31 @@ components: type: integer format: int64 nullable: true - description: Unix timestamp (seconds) when the grant expires. Absent for permanent grants. + description: >- + Unix timestamp (seconds) when the grant expires. Absent for + permanent grants. source: type: string - description: 'How the grant was created: "volume" (earned from trading volume) or "manual" (assigned by Kalshi).' + description: >- + How the grant was created: "volume" (earned from trading volume) or + "manual" (assigned by Kalshi). FixedPointCount: type: string - description: Fixed-point contract count string (2 decimals, e.g., "10.00"; referred to as "fp" in field names). Requests accept 0-2 decimal places (e.g., "10", "10.0", "10.00"); responses always emit 2 decimals. Fractional contract values (e.g., "2.50") are supported; the minimum granularity is 0.01 contracts. - example: "10.00" - # Common schemas + description: >- + Fixed-point contract count string (2 decimals, e.g., "10.00"; referred + to as "fp" in field names). Requests accept 0-2 decimal places (e.g., + "10", "10.0", "10.00"); responses always emit 2 decimals. Fractional + contract values (e.g., "2.50") are supported; the minimum granularity is + 0.01 contracts. + example: '10.00' FixedPointDollars: type: string - description: US dollar amount as a fixed-point decimal string with up to 6 decimal places of precision. This is the maximum supported precision; valid quote intervals for a given market are constrained by that market's price level structure. - example: "0.5600" + description: >- + US dollar amount as a fixed-point decimal string with up to 6 decimal + places of precision. This is the maximum supported precision; valid + quote intervals for a given market are constrained by that market's + price level structure. + example: '0.5600' GetOrderGroupResponse: type: object required: @@ -1463,7 +1569,9 @@ components: description: Whether auto-cancel is enabled for this order group contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the current maximum contracts allowed over a rolling 15-second window. + description: >- + String representation of the current maximum contracts allowed over + a rolling 15-second window. x-go-type-skip-optional-pointer: true orders: type: array @@ -1530,7 +1638,9 @@ components: x-go-type-skip-optional-pointer: true contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' - description: String representation of the current maximum contracts allowed over a rolling 15-second window. + description: >- + String representation of the current maximum contracts allowed over + a rolling 15-second window. x-go-type-skip-optional-pointer: true is_auto_cancel_enabled: type: boolean @@ -1540,20 +1650,31 @@ components: allOf: - $ref: '#/components/schemas/ExchangeIndex' x-go-type-skip-optional-pointer: true - # Market Orderbook schemas PriceLevelDollarsCountFp: type: array minItems: 2 maxItems: 2 - example: ["0.1500", "100.00"] + example: + - '0.1500' + - '100.00' items: type: string - description: Price level in dollars represented as [dollars_string, fp] where dollars_string is like "0.1500" and fp is a FixedPointCount string (fixed-point contract count). The second element is the contract quantity (not price). + description: >- + Price level in dollars represented as [dollars_string, fp] where + dollars_string is like "0.1500" and fp is a FixedPointCount string + (fixed-point contract count). The second element is the contract + quantity (not price). SelfTradePreventionType: type: string - enum: ['taker_at_cross', 'maker'] - description: | - The self-trade prevention type for orders. `taker_at_cross` cancels the taker order when it would trade against another order from the same user; execution stops and any partial fills already matched are executed. `maker` cancels the resting maker order and continues matching. + enum: + - taker_at_cross + - maker + description: > + The self-trade prevention type for orders. `taker_at_cross` cancels the + taker order when it would trade against another order from the same + user; execution stops and any partial fills already matched are + executed. `maker` cancels the resting maker order and continues + matching. UpdateOrderGroupLimitRequest: type: object properties: @@ -1561,14 +1682,22 @@ components: type: integer format: int64 minimum: 1 - description: New maximum number of contracts that can be matched within this group over a rolling 15-second window. Whole contracts only. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + New maximum number of contracts that can be matched within this + group over a rolling 15-second window. Whole contracts only. Provide + contracts_limit or contracts_limit_fp; if both provided they must + match. x-go-type-skip-optional-pointer: true x-oapi-codegen-extra-tags: validate: omitempty,gte=1 contracts_limit_fp: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the new maximum number of contracts that can be matched within this group over a rolling 15-second window. Provide contracts_limit or contracts_limit_fp; if both provided they must match. + description: >- + String representation of the new maximum number of contracts that + can be matched within this group over a rolling 15-second window. + Provide contracts_limit or contracts_limit_fp; if both provided they + must match. ExchangeStatus: type: object required: @@ -1577,11 +1706,14 @@ components: properties: exchange_active: type: boolean - description: False if the exchange is no longer taking any state changes at all. True unless under maintenance. + description: >- + False if the exchange is no longer taking any state changes at all. + True unless under maintenance. trading_active: type: boolean - description: True if trading is currently permitted on the exchange. False outside exchange hours or during pauses. - + description: >- + True if trading is currently permitted on the exchange. False + outside exchange hours or during pauses. GetMarginRiskParametersResponse: type: object required: @@ -1602,7 +1734,10 @@ components: additionalProperties: type: number format: double - description: Map of market ticker to initial margin multiplier. The initial margin requirement is the maintenance margin multiplied by this value. + description: >- + Map of market ticker to initial margin multiplier. The initial + margin requirement is the maintenance margin multiplied by this + value. CreateMarginOrderRequest: type: object required: @@ -1637,7 +1772,10 @@ components: format: int64 time_in_force: type: string - enum: ['fill_or_kill', 'good_till_canceled', 'immediate_or_cancel'] + enum: + - fill_or_kill + - good_till_canceled + - immediate_or_cancel x-oapi-codegen-extra-tags: validate: required,oneof=fill_or_kill good_till_canceled immediate_or_cancel x-go-type-skip-optional-pointer: true @@ -1651,21 +1789,28 @@ components: x-go-type-skip-optional-pointer: true cancel_order_on_pause: type: boolean - description: If this flag is set to true, the order will be canceled if the order is open and trading on the exchange is paused for any reason. + description: >- + If this flag is set to true, the order will be canceled if the order + is open and trading on the exchange is paused for any reason. reduce_only: type: boolean - description: Specifies whether the order place count should be capped by the member's current position. Orders with reduce_only set to true will be rejected unless time_in_force is immediate_or_cancel or fill_or_kill. + description: >- + Specifies whether the order place count should be capped by the + member's current position. Orders with reduce_only set to true will + be rejected unless time_in_force is immediate_or_cancel or + fill_or_kill. subaccount: type: integer minimum: 0 default: 0 - description: The subaccount number to use for this margin order. 0 is the primary subaccount. + description: >- + The subaccount number to use for this margin order. 0 is the primary + subaccount. x-go-type-skip-optional-pointer: true order_group_id: type: string description: The order group this order is part of x-go-type-skip-optional-pointer: true - CreateMarginOrderResponse: type: object required: @@ -1682,14 +1827,19 @@ components: description: Number of contracts filled immediately upon placement. remaining_count: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts remaining after placement. For IOC orders, this reflects the final state after unfilled contracts are canceled. + description: >- + Number of contracts remaining after placement. For IOC orders, this + reflects the final state after unfilled contracts are canceled. average_fill_price: $ref: '#/components/schemas/FixedPointDollars' - description: Volume-weighted average fill price. Only present when fill_count > 0. + description: >- + Volume-weighted average fill price. Only present when fill_count > + 0. average_fee_paid: $ref: '#/components/schemas/FixedPointDollars' - description: Volume-weighted average fee paid per contract for fills resulting from this request. Only present when fill_count > 0. - + description: >- + Volume-weighted average fee paid per contract for fills resulting + from this request. Only present when fill_count > 0. GetMarginOrderResponse: type: object required: @@ -1697,7 +1847,6 @@ components: properties: order: $ref: '#/components/schemas/MarginOrder' - GetMarginOrdersResponse: type: object required: @@ -1710,7 +1859,6 @@ components: $ref: '#/components/schemas/MarginOrder' cursor: type: string - MarginOrder: type: object required: @@ -1767,17 +1915,20 @@ components: x-omitempty: false cancel_order_on_pause: type: boolean - description: If this flag is set to true, the order will be canceled if the order is open and trading on the exchange is paused for any reason. + description: >- + If this flag is set to true, the order will be canceled if the order + is open and trading on the exchange is paused for any reason. order_group_id: type: string description: The order group this order is part of order_source: $ref: '#/components/schemas/OrderSource' - description: The source of the order. Indicates whether the order was placed by the user or by the system on behalf of the user. + description: >- + The source of the order. Indicates whether the order was placed by + the user or by the system on behalf of the user. order_reason: $ref: '#/components/schemas/OrderReason' description: The reason for a system-generated order, when applicable. - CancelMarginOrderResponse: type: object required: @@ -1790,20 +1941,24 @@ components: type: string reduced_by: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts that were canceled (i.e. the remaining count at time of cancellation). - + description: >- + Number of contracts that were canceled (i.e. the remaining count at + time of cancellation). DecreaseMarginOrderRequest: type: object properties: reduce_by: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the number of contracts to reduce by. Exactly one of `reduce_by` or `reduce_to` must be provided. + description: >- + String representation of the number of contracts to reduce by. + Exactly one of `reduce_by` or `reduce_to` must be provided. reduce_to: $ref: '#/components/schemas/FixedPointCount' nullable: true - description: String representation of the number of contracts to reduce to. Exactly one of `reduce_by` or `reduce_to` must be provided. - + description: >- + String representation of the number of contracts to reduce to. + Exactly one of `reduce_by` or `reduce_to` must be provided. DecreaseMarginOrderResponse: type: object required: @@ -1817,7 +1972,6 @@ components: remaining_count: $ref: '#/components/schemas/FixedPointCount' description: Number of contracts remaining after the decrease. - AmendMarginOrderRequest: type: object required: @@ -1852,7 +2006,6 @@ components: type: string description: The new client-specified order ID after amendment x-go-type-skip-optional-pointer: true - AmendMarginOrderResponse: type: object required: @@ -1866,23 +2019,30 @@ components: $ref: '#/components/schemas/FixedPointCount' nullable: true x-omitempty: false - description: Number of contracts remaining after the amend. Only present when the amend caused a fill or changed the resting size. + description: >- + Number of contracts remaining after the amend. Only present when the + amend caused a fill or changed the resting size. fill_count: $ref: '#/components/schemas/FixedPointCount' nullable: true x-omitempty: false - description: Number of contracts filled as a result of the amend crossing the book. Only present when fills occurred or remaining size changed. + description: >- + Number of contracts filled as a result of the amend crossing the + book. Only present when fills occurred or remaining size changed. average_fill_price: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: false - description: Volume-weighted average fill price for fills resulting from the amend. Only present when fills occurred. + description: >- + Volume-weighted average fill price for fills resulting from the + amend. Only present when fills occurred. average_fee_paid: $ref: '#/components/schemas/FixedPointDollars' nullable: true x-omitempty: false - description: Volume-weighted average fee paid per contract for fills resulting from the amend. Only present when fills occurred. - + description: >- + Volume-weighted average fee paid per contract for fills resulting + from the amend. Only present when fills occurred. MarginOrderbookCount: type: object required: @@ -1891,15 +2051,18 @@ components: properties: bids: type: array - description: Bid price levels, ordered from best bid downward. Each level is [price, quantity]. + description: >- + Bid price levels, ordered from best bid downward. Each level is + [price, quantity]. items: $ref: '#/components/schemas/PriceLevelDollarsCountFp' asks: type: array - description: Ask price levels, ordered from best ask upward. Each level is [price, quantity]. + description: >- + Ask price levels, ordered from best ask upward. Each level is + [price, quantity]. items: $ref: '#/components/schemas/PriceLevelDollarsCountFp' - MarginOrderbookResponse: type: object required: @@ -1907,7 +2070,6 @@ components: properties: orderbook: $ref: '#/components/schemas/MarginOrderbookCount' - MarginMarket: type: object required: @@ -1936,8 +2098,9 @@ components: type: number format: double description: > - Leverage estimate (1 / margin_rate) evaluated at a small retail-sized notional position. - Actual leverage may be lower for larger positions as the liquidation margin rate grows with size. + Leverage estimate (1 / margin_rate) evaluated at a small + retail-sized notional position. Actual leverage may be lower for + larger positions as the liquidation margin rate grows with size. Null when margin config or price data is unavailable. leverage_estimates: type: object @@ -1945,10 +2108,10 @@ components: type: number format: double description: > - Leverage estimates (1 / margin_rate) keyed by notional position size in dollars - ("1000", "10000", "100000", "1000000"). Leverage decreases at larger notionals as - the liquidation margin rate grows with size. - Null when margin config or price data is unavailable. + Leverage estimates (1 / margin_rate) keyed by notional position size + in dollars ("1000", "10000", "100000", "1000000"). Leverage + decreases at larger notionals as the liquidation margin rate grows + with size. Null when margin config or price data is unavailable. price: $ref: '#/components/schemas/FixedPointDollars' description: Last trade price in dollars. @@ -1969,7 +2132,9 @@ components: description: One sided trade volume in the last 24 hours. volume_24h_notional_value_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Total notional value of one sided trade volume in the last 24 hours in dollars. + 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. @@ -1985,7 +2150,6 @@ components: reference_price: $ref: '#/components/schemas/TickerPrice' description: Underlying reference price, scaled per contract. - TickerPrice: type: object required: @@ -1999,26 +2163,40 @@ components: type: integer format: int64 description: Source timestamp in epoch milliseconds. - MarginMarketStatus: type: string - enum: [inactive, active, closed] + enum: + - inactive + - active + - closed description: The status of a margin market - OrderSource: type: string - enum: ['user', 'system'] - description: The source of the order. 'user' indicates a user-placed order, 'system' indicates a system-generated order. - + enum: + - user + - system + description: >- + The source of the order. 'user' indicates a user-placed order, 'system' + indicates a system-generated order. OrderReason: type: string - enum: ['liquidation', 'take_profit_stop_loss'] - description: The reason for a system-generated order. Present for liquidation and TP/SL orders. - + enum: + - liquidation + - take_profit_stop_loss + description: >- + The reason for a system-generated order. Present for liquidation and + TP/SL orders. LastUpdateReason: type: string - enum: ['', 'Decrease', 'Amend', 'MarginCancel', 'SelfTradeCancel', 'ExpiryCancel', 'Trade', 'PostOnlyCrossCancel'] - + enum: + - '' + - Decrease + - Amend + - MarginCancel + - SelfTradeCancel + - ExpiryCancel + - Trade + - PostOnlyCrossCancel MarginMarketResponse: type: object required: @@ -2026,7 +2204,6 @@ components: properties: market: $ref: '#/components/schemas/MarginMarket' - GetMarginMarketsResponse: type: object required: @@ -2036,7 +2213,6 @@ components: type: array items: $ref: '#/components/schemas/MarginMarket' - GetMarginFillsResponse: type: object required: @@ -2049,7 +2225,6 @@ components: $ref: '#/components/schemas/MarginFill' cursor: type: string - MarginFill: type: object required: @@ -2090,16 +2265,19 @@ components: description: Fill price in fixed-point dollars entry_price: type: string - description: Position entry price used to compute incremental realized PnL for this fill + description: >- + Position entry price used to compute incremental realized PnL for + this fill fees: type: string 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 order_source: $ref: '#/components/schemas/OrderSource' - GetMarginPositionsResponse: type: object required: @@ -2109,7 +2287,6 @@ components: type: array items: $ref: '#/components/schemas/MarginPosition' - MarginPosition: type: object required: @@ -2123,13 +2300,17 @@ 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) market_ticker: type: string description: Market ticker symbol position: $ref: '#/components/schemas/FixedPointCount' - description: Position size as a fixed-point count string (positive = long, negative = short) + description: >- + Position size as a fixed-point count string (positive = long, + negative = short) entry_price: $ref: '#/components/schemas/FixedPointDollars' description: Weighted average entry price of the open position @@ -2139,19 +2320,30 @@ components: margin_used: $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Maintenance-margin-based capital usage for the open position. Null when the position shares its asset class with other portfolio-margin positions in the subaccount, since margin is then computed jointly for the group and cannot be attributed to a single market. + description: >- + Maintenance-margin-based capital usage for the open position. Null + when the position shares its asset class with other portfolio-margin + positions in the subaccount, since margin is then computed jointly + for the group and cannot be attributed to a single market. fees: $ref: '#/components/schemas/FixedPointDollars' - description: Total fees accumulated over the lifetime of the current open position, resets when position is fully closed + description: >- + Total fees accumulated over the lifetime of the current open + position, resets when position is fully closed roe: type: number format: double nullable: true - description: Return on equity as a percentage (unrealized_pnl / margin_used * 100). Null when margin_used is zero or not attributable to this market. + description: >- + Return on equity as a percentage (unrealized_pnl / margin_used * + 100). Null when margin_used is zero or not attributable to this + market. is_portfolio: type: boolean - description: 'True when this position is hedged within a portfolio, so margin_used and roe cannot be attributed to it individually and are not reported.' - + description: >- + True when this position is hedged within a portfolio, so margin_used + and roe cannot be attributed to it individually and are not + reported. GetMarginTradesResponse: type: object required: @@ -2164,7 +2356,6 @@ components: $ref: '#/components/schemas/MarginTrade' cursor: type: string - MarginTrade: type: object required: @@ -2196,9 +2387,10 @@ components: description: Side of the taker in this trade BookSide: type: string - enum: ['bid', 'ask'] + enum: + - bid + - ask description: The side of an order or trade (bid or ask) - MarginEnabledResponse: type: object required: @@ -2207,7 +2399,6 @@ components: enabled: type: boolean description: Indicates whether margin trading is enabled for the user - NotionalRiskLimitResponse: type: object required: @@ -2216,16 +2407,21 @@ components: properties: default_notional_value_risk_limit: type: string - description: The notional value risk limit for the user as a fixed-point dollar string with 4 decimal places (e.g., "5000.0000") - example: "5000.0000" + description: >- + The notional value risk limit for the user as a fixed-point dollar + string with 4 decimal places (e.g., "5000.0000") + example: '5000.0000' notional_value_risk_limits_by_market_ticker: type: object additionalProperties: type: string - description: Map of market_ticker to notional value risk limit as a fixed-point dollar string with 4 decimal places (e.g., "5000.0000"). If present, the market-level risk limit overrides the default notional value risk limit. + description: >- + Map of market_ticker to notional value risk limit as a fixed-point + dollar string with 4 decimal places (e.g., "5000.0000"). If present, + the market-level risk limit overrides the default notional value + risk limit. example: - "market-abc-123": "5000.0000" - + market-abc-123: '5000.0000' MarginSubaccountBalance: type: object required: @@ -2242,23 +2438,34 @@ components: description: The subaccount number (0 for primary, 1-63 for subaccounts) position_value: $ref: '#/components/schemas/FixedPointDollars' - description: Mark-to-market value of open positions for this subaccount in fixed-point dollars + description: >- + Mark-to-market value of open positions for this subaccount in + fixed-point dollars account_equity: $ref: '#/components/schemas/FixedPointDollars' - description: Account equity for this subaccount in fixed-point dollars. 0 for self clearing members. + description: >- + Account equity for this subaccount in fixed-point dollars. 0 for + self clearing members. maintenance_margin: $ref: '#/components/schemas/FixedPointDollars' - description: Maintenance margin requirement for this subaccount in fixed-point dollars + description: >- + Maintenance margin requirement for this subaccount in fixed-point + dollars initial_margin: $ref: '#/components/schemas/FixedPointDollars' - description: Initial margin requirement for this subaccount in fixed-point dollars. 0 for self clearing members. + description: >- + Initial margin requirement for this subaccount in fixed-point + dollars. 0 for self clearing members. resting_orders_margin: $ref: '#/components/schemas/FixedPointDollars' - description: Margin locked by resting orders for this subaccount in fixed-point dollars. 0 unless compute_available_balance is passed. + description: >- + Margin locked by resting orders for this subaccount in fixed-point + dollars. 0 unless compute_available_balance is passed. available_balance: $ref: '#/components/schemas/FixedPointDollars' - description: Available balance for this subaccount in fixed-point dollars. 0 for institutional users or if compute_available_balance was not passed. - + description: >- + Available balance for this subaccount in fixed-point dollars. 0 for + institutional users or if compute_available_balance was not passed. GetMarginBalanceResponse: type: object required: @@ -2273,7 +2480,6 @@ components: settled_funds: $ref: '#/components/schemas/FixedPointDollars' description: Total settled funds across all subaccounts in fixed-point dollars - MarginRiskPosition: type: object required: @@ -2298,24 +2504,36 @@ components: description: Current mark price for the market in fixed-point dollars position_notional: $ref: '#/components/schemas/FixedPointDollars' - description: Absolute notional value of the position (|qty| * mark_price) in fixed-point dollars + description: >- + Absolute notional value of the position (|qty| * mark_price) in + fixed-point dollars maintenance_margin_required: $ref: '#/components/schemas/FixedPointDollars' - description: Maintenance margin requirement for this position in fixed-point dollars. Null if margin config is missing. + description: >- + Maintenance margin requirement for this position in fixed-point + dollars. Null if margin config is missing. nullable: true position_leverage: type: number format: double - description: 'Position leverage ratio (position_notional / maintenance_margin_required). Null when maintenance margin is zero or config is missing.' + description: >- + Position leverage ratio (position_notional / + maintenance_margin_required). Null when maintenance margin is zero + or config is missing. nullable: true estimated_liquidation_price: $ref: '#/components/schemas/FixedPointDollars' - description: 'Estimated portfolio-aware liquidation price for this position within the subaccount. Null when no valid liquidation price exists.' + description: >- + Estimated portfolio-aware liquidation price for this position within + the subaccount. Null when no valid liquidation price exists. nullable: true is_portfolio: type: boolean - description: 'True when this position is hedged within a portfolio, so maintenance_margin_required, position_leverage, and estimated_liquidation_price cannot be attributed to it individually and are not reported.' - + description: >- + True when this position is hedged within a portfolio, so + maintenance_margin_required, position_leverage, and + estimated_liquidation_price cannot be attributed to it individually + and are not reported. GetMarginRiskResponse: type: object required: @@ -2326,20 +2544,26 @@ components: account_leverage: type: number format: double - description: 'Account-level leverage (total_position_notional / total_maintenance_margin). Null when total maintenance margin is zero.' + description: >- + Account-level leverage (total_position_notional / + total_maintenance_margin). Null when total maintenance margin is + zero. nullable: true total_position_notional: $ref: '#/components/schemas/FixedPointDollars' - description: Sum of absolute position notional values across all positions in fixed-point dollars + description: >- + Sum of absolute position notional values across all positions in + fixed-point dollars total_maintenance_margin: $ref: '#/components/schemas/FixedPointDollars' - description: Sum of maintenance margin requirements across all positions in fixed-point dollars + description: >- + Sum of maintenance margin requirements across all positions in + fixed-point dollars positions: type: array items: $ref: '#/components/schemas/MarginRiskPosition' description: Per-position risk breakdown grouped by subaccount and market - GetMarginFeeTiersResponse: type: object required: @@ -2351,14 +2575,19 @@ components: additionalProperties: type: number format: double - description: A map of margin market ticker to the maker-side fee rate as a decimal fraction of notional (e.g. 0.0005 = 0.05% = 5 bps). Multiply notional by this value to compute the fee. + description: >- + A map of margin market ticker to the maker-side fee rate as a + decimal fraction of notional (e.g. 0.0005 = 0.05% = 5 bps). Multiply + notional by this value to compute the fee. taker_fee_rates: type: object additionalProperties: type: number format: double - description: A map of margin market ticker to the taker-side fee rate as a decimal fraction of notional (e.g. 0.0012 = 0.12% = 12 bps). Multiply notional by this value to compute the fee. - + description: >- + A map of margin market ticker to the taker-side fee rate as a + decimal fraction of notional (e.g. 0.0012 = 0.12% = 12 bps). + Multiply notional by this value to compute the fee. MarginFundingHistoryEntry: type: object required: @@ -2386,7 +2615,9 @@ components: description: Mark price at the time of funding funding_amount: $ref: '#/components/schemas/FixedPointDollars' - description: Dollar amount of the funding payment (positive = received, negative = paid) + description: >- + Dollar amount of the funding payment (positive = received, negative + = paid) quantity: $ref: '#/components/schemas/FixedPointCount' description: Position size at time of funding as a fixed-point count string @@ -2394,7 +2625,6 @@ components: type: integer nullable: true description: Subaccount number (0 for primary) - GetMarginFundingHistoryResponse: type: object required: @@ -2405,7 +2635,6 @@ components: items: $ref: '#/components/schemas/MarginFundingHistoryEntry' description: Array of historical funding payment entries - MarginFundingRate: type: object required: @@ -2428,7 +2657,6 @@ components: mark_price: $ref: '#/components/schemas/FixedPointDollars' description: Mark price at the time of funding - GetMarginHistoricalFundingRatesResponse: type: object required: @@ -2439,7 +2667,6 @@ components: items: $ref: '#/components/schemas/MarginFundingRate' description: Array of historical funding rate entries - GetMarginFundingRateEstimateResponse: type: object required: @@ -2463,7 +2690,6 @@ components: type: string format: date-time description: Timestamp of the next scheduled funding event - GetMarginMarketCandlesticksResponse: type: object required: @@ -2478,7 +2704,6 @@ components: description: Array of candlestick data points for the specified time range. items: $ref: '#/components/schemas/MarginMarketCandlestick' - MarginMarketCandlestick: type: object required: @@ -2497,26 +2722,39 @@ components: description: Unix timestamp for the inclusive end of the candlestick period. bid: $ref: '#/components/schemas/BidAskDistributionHistorical' - description: Open, high, low, close (OHLC) data for buy offers on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) data for buy offers on the market + during the candlestick period. ask: $ref: '#/components/schemas/BidAskDistributionHistorical' - description: Open, high, low, close (OHLC) data for sell offers on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) data for sell offers on the market + during the candlestick period. price: $ref: '#/components/schemas/PriceDistributionHistorical' - description: Open, high, low, close (OHLC) and more data for trade prices on the market during the candlestick period. + description: >- + Open, high, low, close (OHLC) and more data for trade prices on the + market during the candlestick period. volume: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts traded on the market during the candlestick period. + description: >- + Number of contracts traded on the market during the candlestick + period. volume_notional_value_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Notional value of contracts traded on the market during the candlestick period. + description: >- + Notional value of contracts traded on the market during the + candlestick period. open_interest: $ref: '#/components/schemas/FixedPointCount' - description: Number of contracts held on the market by end of the candlestick period (end_period_ts). + description: >- + Number of contracts held on the market by end of the candlestick + period (end_period_ts). open_interest_notional_value_dollars: $ref: '#/components/schemas/FixedPointDollars' - description: Notional value of contracts held on the market by end of the candlestick period (end_period_ts). - + description: >- + Notional value of contracts held on the market by end of the + candlestick period (end_period_ts). BidAskDistributionHistorical: type: object required: @@ -2524,7 +2762,10 @@ components: - low - high - close - description: OHLC data for quoted prices on one side of the orderbook during the candlestick period. These values reflect bid or ask quotes, not executed trade prices. + description: >- + OHLC data for quoted prices on one side of the orderbook during the + candlestick period. These values reflect bid or ask quotes, not executed + trade prices. properties: open: $ref: '#/components/schemas/FixedPointDollars' @@ -2538,7 +2779,6 @@ components: close: $ref: '#/components/schemas/FixedPointDollars' description: Quoted price at the end of the candlestick period (in dollars). - PriceDistributionHistorical: type: object required: @@ -2553,38 +2793,52 @@ components: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Price of the first trade during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Price of the first trade during the candlestick period (in dollars). + Null if no trades occurred. low: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Lowest trade price during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Lowest trade price during the candlestick period (in dollars). Null + if no trades occurred. high: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Highest trade price during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Highest trade price during the candlestick period (in dollars). Null + if no trades occurred. close: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Price of the last trade during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Price of the last trade during the candlestick period (in dollars). + Null if no trades occurred. mean: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Volume-weighted average price during the candlestick period (in dollars). Null if no trades occurred. + description: >- + Volume-weighted average price during the candlestick period (in + dollars). Null if no trades occurred. previous: allOf: - $ref: '#/components/schemas/FixedPointDollars' nullable: true - description: Close price from the previous candlestick period (in dollars). Null if this is the first candlestick or no prior trade exists. - + description: >- + Close price from the previous candlestick period (in dollars). Null + if this is the first candlestick or no prior trade exists. parameters: CursorQuery: name: cursor in: query - description: Pagination cursor. Use the cursor value returned from the previous response to get the next page of results. Leave empty for the first page. + description: >- + Pagination cursor. Use the cursor value returned from the previous + response to get the next page of results. Leave empty for the first + page. schema: type: string x-go-type-skip-optional-pointer: true @@ -2599,7 +2853,7 @@ components: maximum: 1000 default: 100 x-oapi-codegen-extra-tags: - validate: "omitempty,min=1,max=1000" + validate: omitempty,min=1,max=1000 MarginOrdersLimitQuery: name: limit in: query @@ -2611,7 +2865,7 @@ components: maximum: 10000 default: 10000 x-oapi-codegen-extra-tags: - validate: "omitempty,min=1,max=10000" + validate: omitempty,min=1,max=10000 MaxTsQuery: name: max_ts in: query @@ -2657,7 +2911,9 @@ components: name: subaccount in: query required: false - description: Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, defaults to all subaccounts. + description: >- + Subaccount number (0 for primary, 1-63 for subaccounts). If omitted, + defaults to all subaccounts. schema: type: integer minimum: 0 diff --git a/specs/perps_scm_openapi.yaml b/specs/perps_scm_openapi.yaml index e6e6ae4..3a7fbbd 100644 --- a/specs/perps_scm_openapi.yaml +++ b/specs/perps_scm_openapi.yaml @@ -53,12 +53,16 @@ paths: /margin/active_obligation: get: operationId: GetActiveMarginObligation - summary: Get Active Margin Obligation + summary: Get Active Margin Obligation (Deprecated) + deprecated: true description: | - Returns the clearing member's outstanding settlement obligation for the - current cycle, if one exists. A negative amount indicates a net payable - to Kalshi Klear; a positive amount indicates a net receivable. Returns - null when no obligation is pending. + Deprecated: use `/margin/active_obligations`, which covers all asset + classes. This endpoint only returns the crypto obligation. + + Returns the clearing member's outstanding crypto settlement obligation + for the current cycle, if one exists. A negative amount indicates a net + payable to Kalshi Klear; a positive amount indicates a net receivable. + Returns null when no obligation is pending. responses: '200': @@ -70,6 +74,27 @@ paths: '403': { $ref: '#/components/responses/ForbiddenError' } '500': { $ref: '#/components/responses/InternalServerError' } + /margin/active_obligations: + get: + operationId: GetActiveMarginObligations + summary: Get Active Margin Obligations + description: | + Returns the clearing member's outstanding settlement obligations for + the current cycle across all asset classes, ordered by asset class + then obligation ID. A negative amount indicates a net payable to + Kalshi Klear; a positive amount indicates a net receivable. Empty + when no obligation is pending. + + responses: + '200': + description: Successful response + content: + application/json: + schema: { $ref: '#/components/schemas/GetActiveMarginObligationsResponse' } + '401': { $ref: '#/components/responses/UnauthorizedError' } + '403': { $ref: '#/components/responses/ForbiddenError' } + '500': { $ref: '#/components/responses/InternalServerError' } + /margin/obligation_history: get: operationId: GetObligationHistory @@ -122,8 +147,15 @@ paths: /margin/settlement_estimate: get: operationId: GetSettlementEstimate - summary: Get Settlement Estimate - description: Estimated next settlement amounts for the authenticated clearing member, including per-subtrader breakdowns. + summary: Get Settlement Estimate (Deprecated) + deprecated: true + description: | + Deprecated: use `/margin/settlement_estimate_by_asset_class`, which + covers all asset classes. This endpoint only returns the crypto + settlement estimate. + + Estimated next crypto settlement amounts for the authenticated + clearing member, including per-subtrader breakdowns. responses: '200': @@ -135,6 +167,25 @@ paths: '403': { $ref: '#/components/responses/ForbiddenError' } '500': { $ref: '#/components/responses/InternalServerError' } + /margin/settlement_estimate_by_asset_class: + get: + operationId: GetSettlementEstimateByAssetClass + summary: Get Settlement Estimate By Asset Class + description: >- + Estimated next settlement amounts for the authenticated clearing + member, keyed by asset class, including per-subtrader breakdowns. + Asset classes where the member has no margin activity are omitted. + + responses: + '200': + description: Successful response + content: + application/json: + schema: { $ref: '#/components/schemas/GetSettlementEstimateByAssetClassResponse' } + '401': { $ref: '#/components/responses/UnauthorizedError' } + '403': { $ref: '#/components/responses/ForbiddenError' } + '500': { $ref: '#/components/responses/InternalServerError' } + /margin/settlement_balance: get: operationId: GetSettlementBalance @@ -300,6 +351,12 @@ components: type: array items: { $ref: '#/components/schemas/MarginReport' } + AssetClass: + type: string + # TODO(randy): add other enums once SCMs should be aware of other asset classes + enum: [Crypto] + description: Asset class of the margin markets covered by this entry. + ObligationInfo: type: object required: @@ -311,6 +368,7 @@ components: - pnl_centicents - execution_time - last_updated_ts + - asset_class properties: id: { type: string } user_id: { type: string } @@ -329,6 +387,7 @@ components: pnl_centicents: { type: integer, format: int64, description: Realized PnL for this settlement period. } execution_time: { type: string, format: date-time, description: Settlement cycle time this obligation belongs to. } last_updated_ts: { type: string, format: date-time, description: Timestamp of the last status change on this obligation. } + asset_class: { $ref: '#/components/schemas/AssetClass' } ObligationReceiveInfo: type: object @@ -400,6 +459,15 @@ components: $ref: '#/components/schemas/ObligationEntry' description: The outstanding settlement obligation for the current cycle, or null when no obligation is pending. + GetActiveMarginObligationsResponse: + type: object + required: [obligations] + properties: + obligations: + type: array + description: Outstanding settlement obligations for the current cycle across all asset classes, ordered by asset class then obligation ID. Empty when no obligation is pending. + items: { $ref: '#/components/schemas/ObligationEntry' } + GetLargeTraderPositionsResponse: type: object properties: @@ -470,6 +538,33 @@ components: additionalProperties: { type: integer, format: int64 } settlement_balance_centicents: { type: integer, format: int64, description: Current settlement buffer balance. } + AssetClassSettlementEstimate: + type: object + required: [next_runtime] + properties: + user_breakdown: + $ref: '#/components/schemas/SettlementEstimate' + description: Estimated next settlement for this asset class. Null when the member has no activity in this asset class. + subtrader_breakdowns: + type: object + description: Map of subtrader ID to that subtrader's settlement estimate. + additionalProperties: { $ref: '#/components/schemas/SettlementEstimate' } + prev_settlement_prices: + type: object + description: Map of market ticker to that market's most recent settlement (mark) price, in centicents. + additionalProperties: { type: integer, format: int64 } + next_runtime: { type: string, format: date-time, description: Next settlement time for this asset class. } + + GetSettlementEstimateByAssetClassResponse: + type: object + required: [estimates, settlement_balance_centicents] + properties: + estimates: + type: object + description: Map of asset class to the estimated next settlement for that asset class. + additionalProperties: { $ref: '#/components/schemas/AssetClassSettlementEstimate' } + settlement_balance_centicents: { type: integer, format: int64, description: Current settlement buffer balance. } + GetSettlementBalanceResponse: type: object required: [user_id, balance_available_centicents] diff --git a/tests/_contract_support.py b/tests/_contract_support.py index 6167cd3..c4ce9f3 100644 --- a/tests/_contract_support.py +++ b/tests/_contract_support.py @@ -286,11 +286,10 @@ class Exclusion: http_method="GET", path_template="/exchange/schedule", ), - MethodEndpointEntry( - sdk_method="kalshi.resources.exchange.ExchangeResource.announcements", - http_method="GET", - path_template="/exchange/announcements", - ), + # announcements() intentionally unmapped: spec sync 3.24.0 removed + # GET /exchange/announcements. The method is soft-deprecated (retained, + # emits DeprecationWarning) so there is no spec operation to param-drift + # against. See _SOFT_DEPRECATED_MODELS in tests/test_contracts.py. MethodEndpointEntry( sdk_method="kalshi.resources.exchange.ExchangeResource.user_data_timestamp", http_method="GET", @@ -601,6 +600,11 @@ class Exclusion: path_template="/communications/quotes/{quote_id}/confirm", ), # RFQ-scoped quote actions (spec v3.22.0) + MethodEndpointEntry( + sdk_method="kalshi.resources.communications.QuotesResource.get_for_rfq", + http_method="GET", + path_template="/communications/rfqs/{rfq_id}/quotes/{quote_id}", + ), MethodEndpointEntry( sdk_method="kalshi.resources.communications.QuotesResource.delete_for_rfq", http_method="DELETE", @@ -1527,6 +1531,11 @@ class Exclusion: http_method="GET", path_template="/margin/active_obligation", ), + MethodEndpointEntry( + sdk_method="kalshi.perps.klear.resources.margin.MarginResource.active_obligations", + http_method="GET", + path_template="/margin/active_obligations", + ), MethodEndpointEntry( sdk_method="kalshi.perps.klear.resources.margin.MarginResource.obligation_history", http_method="GET", @@ -1542,6 +1551,14 @@ class Exclusion: http_method="GET", path_template="/margin/settlement_estimate", ), + MethodEndpointEntry( + sdk_method=( + "kalshi.perps.klear.resources.margin.MarginResource" + ".settlement_estimate_by_asset_class" + ), + http_method="GET", + path_template="/margin/settlement_estimate_by_asset_class", + ), MethodEndpointEntry( sdk_method="kalshi.perps.klear.resources.margin.MarginResource.settlement_balance", http_method="GET", diff --git a/tests/integration/test_exchange.py b/tests/integration/test_exchange.py index c1c9c30..19d2259 100644 --- a/tests/integration/test_exchange.py +++ b/tests/integration/test_exchange.py @@ -35,8 +35,13 @@ def test_schedule(self, sync_client: KalshiClient) -> None: assert isinstance(result, Schedule) assert_model_fields(result) + @pytest.mark.skip( + reason="GET /exchange/announcements removed upstream in spec v3.24.0; the " + "SDK method is soft-deprecated and 404s live (retained pending confirmation)." + ) def test_announcements(self, sync_client: KalshiClient) -> None: - result = sync_client.exchange.announcements() + with pytest.warns(DeprecationWarning): + result = sync_client.exchange.announcements() assert isinstance(result, list) for item in result: assert isinstance(item, Announcement) @@ -61,8 +66,13 @@ async def test_schedule(self, async_client: AsyncKalshiClient) -> None: assert isinstance(result, Schedule) assert_model_fields(result) + @pytest.mark.skip( + reason="GET /exchange/announcements removed upstream in spec v3.24.0; the " + "SDK method is soft-deprecated and 404s live (retained pending confirmation)." + ) async def test_announcements(self, async_client: AsyncKalshiClient) -> None: - result = await async_client.exchange.announcements() + with pytest.warns(DeprecationWarning): + result = await async_client.exchange.announcements() assert isinstance(result, list) for item in result: assert isinstance(item, Announcement) diff --git a/tests/integration/test_subaccounts.py b/tests/integration/test_subaccounts.py index 4d5d86f..aeb5e27 100644 --- a/tests/integration/test_subaccounts.py +++ b/tests/integration/test_subaccounts.py @@ -18,6 +18,7 @@ import logging import time import uuid +from decimal import Decimal import pytest @@ -179,8 +180,9 @@ def test_transfer_rejects_invalid_amount( def test_transfer_position_rejects_invalid_price( self, sync_client: KalshiClient, ) -> None: - # price_cents is bounded 0-100 at the SDK model — a 101c price rejects - # before any network call, independent of demo position state. + # v3.24.0: `price` is OrderPrice (fixed-point dollars). A negative price + # rejects before any network call, independent of demo position state + # (the old 0-100c cap is gone; the server enforces the upper bound). with pytest.raises(ValueError): sync_client.subaccounts.transfer_position( client_transfer_id=str(uuid.uuid4()), @@ -189,7 +191,7 @@ def test_transfer_position_rejects_invalid_price( market_ticker="MKT-DOES-NOT-MATTER", side="yes", count=1, - price_cents=101, + price=Decimal("-0.01"), ) def test_transfer_position_smoke( @@ -208,7 +210,7 @@ def test_transfer_position_smoke( market_ticker="KXBTCD-99DEC31-B1", side="yes", count=1, - price_cents=1, + price=Decimal("0.01"), ) except KalshiError as e: pytest.skip(f"demo refused position transfer (no position to move?): {e}") diff --git a/tests/perps/klear/test_margin.py b/tests/perps/klear/test_margin.py index 4320a27..23a6373 100644 --- a/tests/perps/klear/test_margin.py +++ b/tests/perps/klear/test_margin.py @@ -86,6 +86,7 @@ def _obligation(amount: int = -12345) -> dict[str, object]: "pnl_centicents": -200, "execution_time": "2026-06-01T00:00:00Z", "last_updated_ts": "2026-06-01T01:00:00Z", + "asset_class": "Crypto", "receives": [ { "id": "r1", @@ -271,6 +272,115 @@ async def test_async_null(self, auth_async_klear_client: AsyncKlearClient) -> No await auth_async_klear_client.close() +# --------------------------------------------------------------------------- # +# active_obligations (plural; spec v3.24.0) +# --------------------------------------------------------------------------- # + + +class TestActiveObligations: + @respx.mock + def test_happy_list(self, auth_klear_client: KlearClient) -> None: + respx.get(f"{BASE}/margin/active_obligations").mock( + return_value=httpx.Response( + 200, + json={"obligations": [_obligation(amount=-99999), _obligation(amount=5000)]}, + ) + ) + resp = auth_klear_client.margin.active_obligations() + assert len(resp.obligations) == 2 + assert all(isinstance(o, ObligationEntry) for o in resp.obligations) + assert resp.obligations[0].amount_centicents == -99999 + assert resp.obligations[0].asset_class == "Crypto" + auth_klear_client.close() + + @respx.mock + def test_null_obligations_coerces_to_empty(self, auth_klear_client: KlearClient) -> None: + respx.get(f"{BASE}/margin/active_obligations").mock( + return_value=httpx.Response(200, json={"obligations": None}) + ) + resp = auth_klear_client.margin.active_obligations() + assert resp.obligations == [] + auth_klear_client.close() + + @respx.mock + async def test_async_happy(self, auth_async_klear_client: AsyncKlearClient) -> None: + respx.get(f"{BASE}/margin/active_obligations").mock( + return_value=httpx.Response(200, json={"obligations": [_obligation()]}) + ) + resp = await auth_async_klear_client.margin.active_obligations() + assert len(resp.obligations) == 1 + await auth_async_klear_client.close() + + +# --------------------------------------------------------------------------- # +# settlement_estimate_by_asset_class (spec v3.24.0) +# --------------------------------------------------------------------------- # + + +class TestSettlementEstimateByAssetClass: + @respx.mock + def test_happy(self, auth_klear_client: KlearClient) -> None: + respx.get(f"{BASE}/margin/settlement_estimate_by_asset_class").mock( + return_value=httpx.Response( + 200, + json={ + "estimates": { + "Crypto": { + "next_runtime": "2026-06-02T00:00:00Z", + "user_breakdown": _estimate(), + "subtrader_breakdowns": {"st1": _estimate()}, + "prev_settlement_prices": {"BTC-PERP": 5000}, + } + }, + "settlement_balance_centicents": 123456, + }, + ) + ) + resp = auth_klear_client.margin.settlement_estimate_by_asset_class() + assert resp.settlement_balance_centicents == 123456 + crypto = resp.estimates["Crypto"] + assert crypto.next_runtime.tzinfo is not None + assert crypto.user_breakdown is not None + assert crypto.user_breakdown.total_amount_centicents == 1630 + assert crypto.subtrader_breakdowns is not None + assert crypto.subtrader_breakdowns["st1"].variation_margin_centicents == 1000 + assert crypto.prev_settlement_prices == {"BTC-PERP": 5000} + auth_klear_client.close() + + @respx.mock + def test_optional_breakdowns_omitted(self, auth_klear_client: KlearClient) -> None: + respx.get(f"{BASE}/margin/settlement_estimate_by_asset_class").mock( + return_value=httpx.Response( + 200, + json={ + "estimates": {"Crypto": {"next_runtime": "2026-06-02T00:00:00Z"}}, + "settlement_balance_centicents": 0, + }, + ) + ) + resp = auth_klear_client.margin.settlement_estimate_by_asset_class() + crypto = resp.estimates["Crypto"] + assert crypto.user_breakdown is None + assert crypto.subtrader_breakdowns is None + assert crypto.prev_settlement_prices is None + auth_klear_client.close() + + @respx.mock + async def test_async_happy(self, auth_async_klear_client: AsyncKlearClient) -> None: + respx.get(f"{BASE}/margin/settlement_estimate_by_asset_class").mock( + return_value=httpx.Response( + 200, + json={ + "estimates": {"Crypto": {"next_runtime": "2026-06-02T00:00:00Z"}}, + "settlement_balance_centicents": 7, + }, + ) + ) + resp = await auth_async_klear_client.margin.settlement_estimate_by_asset_class() + assert resp.settlement_balance_centicents == 7 + await auth_async_klear_client.close() + + # --------------------------------------------------------------------------- # # obligation_history / obligation_history_all # --------------------------------------------------------------------------- # diff --git a/tests/test_communications.py b/tests/test_communications.py index 16b1ba5..1bc4d95 100644 --- a/tests/test_communications.py +++ b/tests/test_communications.py @@ -619,6 +619,15 @@ class TestRFQScopedQuoteActions: """RFQ-scoped quote actions (spec v3.22.0): ``/communications/rfqs/{rfq_id}/quotes/{quote_id}[/accept|/confirm]``.""" + @respx.mock + def test_get_for_rfq_returns_quote(self, comms: CommunicationsResource) -> None: + route = respx.get( + "https://test.kalshi.com/trade-api/v2/communications/rfqs/r-1/quotes/q-1", + ).mock(return_value=httpx.Response(200, json={"quote": _MINIMAL_QUOTE})) + resp = comms.quotes.get_for_rfq("r-1", "q-1") + assert isinstance(resp, GetQuoteResponse) + assert route.called + @respx.mock def test_delete_for_rfq_sends_delete(self, comms: CommunicationsResource) -> None: route = respx.delete( @@ -781,6 +790,18 @@ async def test_confirm_for_rfq( await async_comms.quotes.confirm_for_rfq("r-1", "q-1") assert route.calls[0].request.content == b"{}" + async def test_get_for_rfq( + self, + async_comms: AsyncCommunicationsResource, + respx_mock: respx.MockRouter, + ) -> None: + route = respx_mock.get( + "https://test.kalshi.com/trade-api/v2/communications/rfqs/r-1/quotes/q-1", + ).mock(return_value=httpx.Response(200, json={"quote": _MINIMAL_QUOTE})) + resp = await async_comms.quotes.get_for_rfq("r-1", "q-1") + assert isinstance(resp, GetQuoteResponse) + assert route.called + async def test_delete_for_rfq( self, async_comms: AsyncCommunicationsResource, @@ -938,6 +959,12 @@ def test_confirm_quote_requires_auth( with pytest.raises(AuthRequiredError): unauth_comms.confirm_quote("q-1") + def test_get_for_rfq_requires_auth( + self, unauth_comms: CommunicationsResource, + ) -> None: + with pytest.raises(AuthRequiredError): + unauth_comms.quotes.get_for_rfq("r-1", "q-1") + def test_delete_for_rfq_requires_auth( self, unauth_comms: CommunicationsResource, ) -> None: diff --git a/tests/test_contract_support.py b/tests/test_contract_support.py index dabc852..0d3961d 100644 --- a/tests/test_contract_support.py +++ b/tests/test_contract_support.py @@ -275,6 +275,13 @@ def test_every_public_method_has_entry(self) -> None: ) mapped = {entry.sdk_method for entry in METHOD_ENDPOINT_MAP} + # Soft-deprecated methods intentionally have NO METHOD_ENDPOINT_MAP entry: + # their spec operation was removed upstream but the method is retained + # (emits DeprecationWarning) pending confirmation the removal is permanent. + # See kalshi/resources/exchange.py::_ANNOUNCEMENTS_DEPRECATED. + soft_deprecated = { + "kalshi.resources.exchange.ExchangeResource.announcements", + } missing: list[str] = [] discovered: list[str] = [] @@ -302,7 +309,7 @@ def test_every_public_method_has_entry(self) -> None: continue fqn = f"{mod_path}.{cls_name}.{method_name}" discovered.append(fqn) - if fqn not in mapped: + if fqn not in mapped and fqn not in soft_deprecated: missing.append(fqn) # Guard against tautological pass: if discovery silently returns zero diff --git a/tests/test_contracts.py b/tests/test_contracts.py index de20584..f0f79f8 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -1,11 +1,30 @@ """Contract tests: verify hand-written SDK models match OpenAPI / AsyncAPI spec schemas. Drift detection: -- Additive drift (spec has fields SDK doesn't): **FAILURE** (#163) -- Unmapped WS payload models: **FAILURE** (#163) -- Unmapped REST models: WARNING (sub-models / V2 family — separate mapping pass) -- Required mismatch (spec required, SDK optional): WARNING (SDK is intentionally permissive) +- Additive drift, spec has a **required** field the SDK doesn't map: **FAILURE** + (a new required field is a meaningful model change the SDK must absorb). +- Additive drift, spec has an **optional** field the SDK doesn't map: soft + **WARNING** (``AdditiveOptionalDriftWarning``) — benign, since pydantic ignores + extras and existing calls are unaffected. Deliberately a plain ``Warning`` (not + ``UserWarning``) so the nightly ``-W error::UserWarning`` gate does not promote + it: purely-additive optional drift against a fast-moving upstream should not red + CI. Reconcile these in a batch, not per micro-revision. +- Unmapped WS payload models / additive WS required fields: **FAILURE** (#163) +- Unmapped REST models: **FAILURE** (#171) via ``test_contract_map_completeness``. +- Required mismatch (spec required, SDK optional): **FAILURE** (#172) - Missing schema in spec: FAILURE +- Spec operation not in a ``METHOD_ENDPOINT_MAP``: **FAILURE** via + ``test_every_spec_endpoint_is_mapped`` (an ADDED upstream endpoint reds CI + instead of shipping silently unmapped) unless recorded in + ``_UNIMPLEMENTED_ENDPOINTS`` with a reason. +- SDK **response** field absent from the spec: intentionally NOT gated on the + REST response side. The vendored "Kalshi Trade API Manual Endpoints" spec is a + curated SUBSET, so the SDK response models are a superset by design (client + reshapes like ``Orderbook.yes/no`` and real-but-undocumented fields). Gating it + would red CI on every intentional SDK field. Request-BODY drift DOES gate + removals (``_check_model_drift``), which is where a rename's dropped old name is + caught; a response-only optional rename is the one residual gap (the new name + surfaces as an ``AdditiveOptionalDriftWarning`` and is reconciled on the next sync). Intentional deviations require an entry in ``EXCLUSIONS`` (``tests/_contract_support.py``) with a typed ``kind`` and ``reason``. @@ -16,6 +35,7 @@ import importlib import inspect import typing +import warnings from datetime import datetime from decimal import Decimal from pathlib import Path @@ -455,6 +475,28 @@ def _build_spec_to_sdk_map( # --------------------------------------------------------------------------- +class AdditiveOptionalDriftWarning(Warning): + """A spec added an OPTIONAL field the SDK doesn't map — benign, non-blocking. + + Deliberately subclasses ``Warning`` and NOT ``UserWarning`` so the nightly + strict gate (``pytest -W error::UserWarning``) does not promote it to a + failure. Optional additive drift is benign: pydantic ignores unknown fields, + so existing calls keep working; the only cost is the SDK not yet exposing the + new field. Batch these into a periodic reconcile rather than redding CI on + every upstream micro-revision. + """ + + +def _warn_additive_optional(sdk_model: str, additive_optional: list[str]) -> None: + """Emit the non-blocking soft signal for benign additive-optional drift.""" + for msg in additive_optional: + warnings.warn( + f"Additive-optional drift in {sdk_model}: {msg}", + AdditiveOptionalDriftWarning, + stacklevel=2, + ) + + def _classify_drift( entry: ContractEntry, spec: dict[str, Any], @@ -462,11 +504,19 @@ def _classify_drift( model_class: type[PydanticBase], *, exclusions: dict[tuple[str, str], Exclusion] = EXCLUSIONS, -) -> tuple[list[str], list[str]]: +) -> tuple[list[str], list[str], list[str]]: """Compare spec fields against SDK model fields. - Returns (additive_issues, required_issues). - Both are warnings, not failures (SDK is intentionally permissive). + Returns ``(additive_required, additive_optional, required_issues)``: + + - ``additive_required`` — spec fields the SDK does not map that the spec marks + ``required``. Hard failure: the server always sends them, so a new required + field is a meaningful model change the SDK must absorb. + - ``additive_optional`` — unmapped spec fields the spec marks optional. Benign; + callers emit a non-blocking ``AdditiveOptionalDriftWarning`` (via + :func:`_warn_additive_optional`) instead of failing. + - ``required_issues`` — fields the spec marks required but the SDK models as + optional (SDK too permissive). Per-field skips are honored in this order: 1. ``entry.ignored_fields`` — per-contract-entry allowlist (legacy). @@ -477,22 +527,29 @@ def _classify_drift( drift classes pass ``PERPS_EXCLUSIONS`` so perps deviations resolve against their own allowlist. """ - additive: list[str] = [] + additive_required: list[str] = [] + additive_optional: list[str] = [] required_issues: list[str] = [] reverse_map = _build_spec_to_sdk_map(model_class) + required_fields = _get_required_fields(spec, entry.spec_schema) - # Check every spec field has a corresponding SDK field + # Every spec field should have a corresponding SDK field. Partition the + # unmapped ones by whether the spec marks them required (act-now, hard fail) + # or optional (benign additive drift, soft warning). for spec_field_name in spec_fields: if spec_field_name in entry.ignored_fields: continue if (entry.sdk_model, spec_field_name) in exclusions: continue if spec_field_name not in reverse_map: - additive.append(f"Spec field '{spec_field_name}' has no SDK mapping") + msg = f"Spec field '{spec_field_name}' has no SDK mapping" + if spec_field_name in required_fields: + additive_required.append(msg) + else: + additive_optional.append(msg) - # Check required fields in spec vs SDK (warning, not failure) - required_fields = _get_required_fields(spec, entry.spec_schema) + # Spec-required fields the SDK models as optional (SDK too permissive). for req_field in required_fields: if req_field in entry.ignored_fields: continue @@ -506,7 +563,7 @@ def _classify_drift( f"Spec requires '{req_field}' but SDK field '{sdk_name}' is optional" ) - return additive, required_issues + return additive_required, additive_optional, required_issues # --------------------------------------------------------------------------- @@ -743,6 +800,19 @@ def _ws_field_type_violations( # --------------------------------------------------------------------------- +# SDK models intentionally retained after their spec schema was removed upstream +# (soft-deprecation). They carry no CONTRACT_MAP entry — there is no spec schema +# left to drift-check — so test_contract_map_completeness must NOT flag them as +# unmapped. Each entry pairs with a DeprecationWarning on the owning method and +# is removed once the upstream removal is confirmed permanent (then the model +# itself goes too). See kalshi/resources/exchange.py::_ANNOUNCEMENTS_DEPRECATED. +_SOFT_DEPRECATED_MODELS: frozenset[str] = frozenset( + { + "kalshi.models.exchange.Announcement", + } +) + + class TestSpecDrift: """Verify hand-written SDK models match the OpenAPI spec.""" @@ -758,13 +828,17 @@ def _load(self) -> None: ids=[e.sdk_model.rsplit(".", 1)[1] for e in CONTRACT_MAP], ) def test_additive_drift(self, entry: ContractEntry) -> None: - """Warn about spec fields not present in SDK models.""" + """Fail on new spec-**required** fields the SDK lacks; soft-warn on optional ones.""" spec_fields = _get_schema_fields(self.spec, entry.spec_schema) model_class = _get_sdk_model_class(entry.sdk_model) - additive, _ = _classify_drift(entry, self.spec, spec_fields, model_class) - if additive: + additive_required, additive_optional, _ = _classify_drift( + entry, self.spec, spec_fields, model_class + ) + _warn_additive_optional(entry.sdk_model, additive_optional) + if additive_required: pytest.fail( - f"Additive drift in {entry.sdk_model}:\n" + "\n".join(f" - {a}" for a in additive), + f"Additive drift (new required fields) in {entry.sdk_model}:\n" + + "\n".join(f" - {a}" for a in additive_required), ) @pytest.mark.parametrize( @@ -782,7 +856,7 @@ def test_required_drift(self, entry: ContractEntry) -> None: """ spec_fields = _get_schema_fields(self.spec, entry.spec_schema) model_class = _get_sdk_model_class(entry.sdk_model) - _, required_issues = _classify_drift(entry, self.spec, spec_fields, model_class) + _, _, required_issues = _classify_drift(entry, self.spec, spec_fields, model_class) if required_issues: pytest.fail( f"Required drift in {entry.sdk_model}:\n" @@ -790,10 +864,23 @@ def test_required_drift(self, entry: ContractEntry) -> None: ) def test_schema_coverage(self) -> None: - """Every mapped schema must resolve (supports dotted-path syntax).""" + """Every mapped schema must resolve (supports dotted-path syntax). + + Collects ALL unresolved schemas and reports them together, so several + simultaneous upstream removals surface in one run instead of one-per-rerun + (``_resolve_schema`` ``pytest.fail``\\s on the first miss). + """ + missing: list[str] = [] for entry in CONTRACT_MAP: - # _resolve_schema fails the test internally if the path doesn't resolve. - _resolve_schema(self.spec, entry.spec_schema) + try: + _resolve_schema(self.spec, entry.spec_schema) + except pytest.fail.Exception as exc: + missing.append(f"{entry.spec_schema} — {exc}") + if missing: + pytest.fail( + "Mapped schemas that no longer resolve in the spec:\n" + + "\n".join(f" - {m}" for m in missing) + ) def test_contract_map_completeness(self) -> None: """Fail if any SDK model under ``kalshi.models.*`` lacks a ``CONTRACT_MAP`` entry. @@ -825,7 +912,7 @@ def test_contract_map_completeness(self) -> None: and obj.__module__ == module.__name__ ): fqn = f"kalshi.models.{module_name}.{name}" - if fqn not in mapped_models: + if fqn not in mapped_models and fqn not in _SOFT_DEPRECATED_MODELS: unmapped.append(fqn) if unmapped: @@ -835,6 +922,72 @@ def test_contract_map_completeness(self) -> None: ) +class TestAdditiveDriftClassification: + """Guards the optional-vs-required additive-drift split (soft signal policy). + + Additive drift on a spec-**required** field hard-fails (act now); on a + spec-**optional** field it is a non-blocking ``AdditiveOptionalDriftWarning``. + The warning is deliberately NOT a ``UserWarning`` so the nightly + ``-W error::UserWarning`` gate never promotes benign optional drift to a red + build. These tests lock that contract so a future refactor can't silently + re-brittle CI against a fast-moving upstream. + """ + + @staticmethod + def _entry() -> ContractEntry: + return ContractEntry( + sdk_model="tests.synthetic.Fake", + spec_schema="Fake", + ignored_fields=frozenset(), + notes="", + ) + + @staticmethod + def _spec(required: list[str]) -> dict[str, Any]: + return { + "components": { + "schemas": { + "Fake": { + "type": "object", + "properties": {"known": {}, "opt_new": {}, "req_new": {}}, + "required": required, + } + } + } + } + + def test_partitions_unmapped_fields_by_required(self) -> None: + class Fake(PydanticBase): + known: str + + spec = self._spec(required=["known", "req_new"]) + spec_fields = spec["components"]["schemas"]["Fake"]["properties"] + additive_required, additive_optional, required_issues = _classify_drift( + self._entry(), spec, spec_fields, Fake + ) + + assert len(additive_required) == 1 and "req_new" in additive_required[0] + assert len(additive_optional) == 1 and "opt_new" in additive_optional[0] + # 'known' is mapped and required in both; 'req_new' is unmapped so it + # can't be an SDK-optional/spec-required mismatch. No required_issues. + assert required_issues == [] + + def test_optional_drift_warning_is_not_a_userwarning(self) -> None: + # The load-bearing property: nightly runs `-W error::UserWarning`. If this + # warning ever became a UserWarning subclass, benign optional drift would + # red CI again — exactly the churn this policy removes. + assert not issubclass(AdditiveOptionalDriftWarning, UserWarning) + + def test_optional_drift_survives_the_nightly_strict_gate(self) -> None: + msgs = ["Spec field 'opt_new' has no SDK mapping"] + with pytest.warns(AdditiveOptionalDriftWarning): + _warn_additive_optional("tests.synthetic.Fake", msgs) + # Under the exact nightly filter, emitting the soft signal must NOT raise. + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + _warn_additive_optional("tests.synthetic.Fake", msgs) + + # --------------------------------------------------------------------------- # WS Spec Drift Tests # --------------------------------------------------------------------------- @@ -863,14 +1016,17 @@ def _load(request: pytest.FixtureRequest) -> None: ids=[e.sdk_model.rsplit(".", 1)[1] for e in WS_CONTRACT_MAP], ) def test_ws_additive_drift(self, entry: ContractEntry) -> None: - """Warn about AsyncAPI fields not present in SDK WS models.""" + """Fail on new spec-**required** WS fields the SDK lacks; soft-warn on optional ones.""" spec_fields = _get_ws_msg_fields(self.spec, entry.spec_schema) model_class = _get_sdk_model_class(entry.sdk_model) - additive, _ = _classify_drift(entry, self.spec, spec_fields, model_class) - if additive: + additive_required, additive_optional, _ = _classify_drift( + entry, self.spec, spec_fields, model_class + ) + _warn_additive_optional(entry.sdk_model, additive_optional) + if additive_required: pytest.fail( - f"WS additive drift in {entry.sdk_model}:\n" - + "\n".join(f" - {a}" for a in additive), + f"WS additive drift (new required fields) in {entry.sdk_model}:\n" + + "\n".join(f" - {a}" for a in additive_required), ) @pytest.mark.parametrize( @@ -1086,6 +1242,63 @@ def _path_params_from_template(path_template: str) -> set[str]: return set(re.findall(r"\{([^}]+)\}", path_template)) +# Spec operations that exist in a vendored spec but are intentionally NOT +# implemented in the SDK. Each MUST carry a reason. ``test_every_spec_endpoint_is_mapped`` +# fails if a spec operation is neither mapped in a METHOD_ENDPOINT_MAP nor listed +# here — so a newly-ADDED upstream endpoint reds CI instead of shipping silently +# unmapped (the gap that let perps_scm's /margin/active_obligations and +# /margin/settlement_estimate_by_asset_class appear undetected by the schema diff). +_UNIMPLEMENTED_ENDPOINTS: dict[tuple[str, str], str] = { + ("GET", "/margin/large_trader_positions"): ( + "perps SCM large-trader surveillance endpoint; outside the client SDK surface" + ), +} + + +def _spec_operations(spec: dict[str, Any]) -> set[tuple[str, str]]: + """Return the set of ``(HTTP_METHOD, path_template)`` operations in a spec.""" + ops: set[tuple[str, str]] = set() + for path, item in (spec.get("paths") or {}).items(): + if not isinstance(item, dict): + continue + for method in ("get", "post", "put", "delete", "patch"): + if method in item: + ops.add((method.upper(), path)) + return ops + + +@pytest.mark.parametrize( + ("spec_loader", "endpoint_map", "label"), + [ + (_load_spec, METHOD_ENDPOINT_MAP, "core"), + (_load_perps_spec, PERPS_METHOD_ENDPOINT_MAP, "perps"), + (_load_perps_scm_spec, PERPS_SCM_METHOD_ENDPOINT_MAP, "perps_scm"), + ], + ids=["core", "perps", "perps_scm"], +) +def test_every_spec_endpoint_is_mapped( + spec_loader: Any, + endpoint_map: list[MethodEndpointEntry], + label: str, +) -> None: + """Fail if a spec operation is neither mapped nor explicitly unimplemented. + + Closes the false-negative gap where a newly-ADDED upstream endpoint shipped + untested because nothing asserted spec paths ⊆ ``METHOD_ENDPOINT_MAP``. The + reverse direction (a map entry whose path the spec dropped) is caught by the + param-drift tests, which fail loud when the path is absent from the spec. + """ + spec_ops = _spec_operations(spec_loader()) + mapped = {(e.http_method.upper(), e.path_template) for e in endpoint_map} + unmapped = spec_ops - mapped - set(_UNIMPLEMENTED_ENDPOINTS) + if unmapped: + pytest.fail( + f"{label}: spec operations not in the endpoint map (add a " + f"MethodEndpointEntry, or record in _UNIMPLEMENTED_ENDPOINTS with a reason):\n" + + "\n".join(f" - {m} {p}" for m, p in sorted(unmapped)) + ) + + @pytest.mark.parametrize( "entry", [e for e in METHOD_ENDPOINT_MAP if e.http_method in ("GET", "DELETE")], @@ -1644,6 +1857,40 @@ def test_exclusion_map_is_current() -> None: f"entry is stale. reason={excl.reason!r}" ) + # kwarg_rename anchors a spec param name to a renamed SDK kwarg. It + # registers BOTH names: the SDK-side name is validated above (it's in + # the signature by design); the SPEC-side name (NOT in the signature) + # must still be a real spec parameter for the endpoint. Without this, + # a rename silently masks an upstream param removal/rename — the entry + # keeps suppressing drift for a param the spec no longer has. + if excl.kind == "kwarg_rename" and name not in sdk_params: + map_entry = next( + (e for e in METHOD_ENDPOINT_MAP if e.sdk_method == fqn), None + ) + if map_entry is None: + stale.append( + f"EXCLUSIONS[{(fqn, name)}] is a kwarg_rename but {fqn} has " + f"no METHOD_ENDPOINT_MAP entry to anchor the spec param." + ) + else: + try: + spec_param_names = { + p.get("name") + for p in _resolve_path_params( + spec, map_entry.path_template, map_entry.http_method + ) + } + except KeyError: + spec_param_names = set() + if name not in spec_param_names: + stale.append( + f"EXCLUSIONS[{(fqn, name)}] renames spec param {name!r} " + f"on {fqn}, but the spec no longer declares it for " + f"{map_entry.http_method} {map_entry.path_template} — the " + f"rename is stale (upstream removed/renamed the param). " + f"reason={excl.reason!r}" + ) + else: stale.append( f"EXCLUSIONS[{(fqn, name)}] has unexpected FQN prefix; " @@ -1831,10 +2078,11 @@ def _assert_perps_response_drift(entry: ContractEntry, spec: dict[str, Any]) -> """Response-side drift assertion for one perps contract entry.""" spec_fields = _get_schema_fields(spec, entry.spec_schema) model_class = _get_sdk_model_class(entry.sdk_model) - additive, required_issues = _classify_drift( + additive_required, additive_optional, required_issues = _classify_drift( entry, spec, spec_fields, model_class, exclusions=PERPS_EXCLUSIONS ) - problems = additive + required_issues + _warn_additive_optional(entry.sdk_model, additive_optional) + problems = additive_required + required_issues if problems: pytest.fail( f"Perps spec drift in {entry.sdk_model}:\n" diff --git a/tests/test_exchange.py b/tests/test_exchange.py index f40a473..0f4a3f0 100644 --- a/tests/test_exchange.py +++ b/tests/test_exchange.py @@ -227,7 +227,8 @@ def test_returns_announcements(self, exchange: ExchangeResource) -> None: }, ) ) - announcements = exchange.announcements() + with pytest.warns(DeprecationWarning, match="announcements"): + announcements = exchange.announcements() assert len(announcements) == 2 assert announcements[0].type == "info" assert announcements[0].message == "Exchange will be down for maintenance." @@ -242,7 +243,8 @@ def test_empty_announcements(self, exchange: ExchangeResource) -> None: json={"announcements": []}, ) ) - announcements = exchange.announcements() + with pytest.warns(DeprecationWarning, match="announcements"): + announcements = exchange.announcements() assert announcements == [] @@ -423,7 +425,8 @@ async def test_returns_announcements( }, ) ) - announcements = await async_exchange.announcements() + with pytest.warns(DeprecationWarning, match="announcements"): + announcements = await async_exchange.announcements() assert len(announcements) == 1 assert announcements[0].type == "error" assert announcements[0].status == "inactive" @@ -436,5 +439,6 @@ async def test_empty_announcements( respx.get("https://test.kalshi.com/trade-api/v2/exchange/announcements").mock( return_value=httpx.Response(200, json={"announcements": []}) ) - announcements = await async_exchange.announcements() + with pytest.warns(DeprecationWarning, match="announcements"): + announcements = await async_exchange.announcements() assert announcements == [] diff --git a/tests/test_subaccounts.py b/tests/test_subaccounts.py index 3a705b3..b5fd33c 100644 --- a/tests/test_subaccounts.py +++ b/tests/test_subaccounts.py @@ -112,7 +112,8 @@ def test_subaccount_transfer_parses(self) -> None: assert t.side is None def test_subaccount_position_transfer_parses(self) -> None: - # v3.23.0: position transfers carry market_ticker/side/count/price_cents. + # v3.24.0: position transfers carry market_ticker/side/count/price (the + # per-contract price is now FixedPointDollars, renamed from price_cents). t = SubaccountTransfer.model_validate( { "transfer_id": "xfer-2", @@ -125,14 +126,14 @@ def test_subaccount_position_transfer_parses(self) -> None: "market_ticker": "MKT-1", "side": "yes", "count": 10, - "price_cents": 55, + "price": "0.55", } ) assert t.transfer_type == "position" assert t.market_ticker == "MKT-1" assert t.side == "yes" assert t.count == 10 - assert t.price_cents == 55 + assert t.price == Decimal("0.55") def test_subaccount_transfer_requires_v3_23_fields(self) -> None: # exchange_index and transfer_type are spec-required (v3.23.0). A @@ -153,10 +154,11 @@ def test_subaccount_transfer_requires_v3_23_fields(self) -> None: def test_subaccount_netting_config_parses(self) -> None: cfg = SubaccountNettingConfig.model_validate( - {"subaccount_number": 2, "enabled": True}, + {"subaccount_number": 2, "enabled": True, "exchange_index": 0}, ) assert cfg.subaccount_number == 2 assert cfg.enabled is True + assert cfg.exchange_index == 0 def test_get_balances_response_wraps_list(self) -> None: resp = GetSubaccountBalancesResponse.model_validate( @@ -176,7 +178,7 @@ def test_get_balances_response_wraps_list(self) -> None: def test_get_netting_response_wraps_list(self) -> None: resp = GetSubaccountNettingResponse.model_validate( - {"netting_configs": [{"subaccount_number": 1, "enabled": False}]}, + {"netting_configs": [{"subaccount_number": 1, "enabled": False, "exchange_index": 0}]}, ) assert len(resp.netting_configs) == 1 @@ -293,7 +295,7 @@ def test_position_transfer_request_serializes(self) -> None: market_ticker="MKT-1", side="yes", count=5, - price_cents=50, + price=Decimal("0.50"), ) body = req.model_dump(exclude_none=True, by_alias=True, mode="json") assert body == { @@ -303,7 +305,7 @@ def test_position_transfer_request_serializes(self) -> None: "market_ticker": "MKT-1", "side": "yes", "count": 5, - "price_cents": 50, + "price": "0.50", } def test_position_transfer_request_forbids_extra(self) -> None: @@ -315,7 +317,7 @@ def test_position_transfer_request_forbids_extra(self) -> None: market_ticker="MKT-1", side="yes", count=5, - price_cents=50, + price=Decimal("0.50"), phantom=1, ) @@ -328,7 +330,7 @@ def test_position_transfer_request_rejects_bad_side(self) -> None: market_ticker="MKT-1", side="maybe", # type: ignore[arg-type] count=5, - price_cents=50, + price=Decimal("0.50"), ) def test_position_transfer_request_rejects_zero_count(self) -> None: @@ -340,11 +342,14 @@ def test_position_transfer_request_rejects_zero_count(self) -> None: market_ticker="MKT-1", side="yes", count=0, - price_cents=50, + price=Decimal("0.50"), ) - @pytest.mark.parametrize("bad_price", [-1, 101]) - def test_position_transfer_request_rejects_price_out_of_range(self, bad_price: int) -> None: + @pytest.mark.parametrize("bad_price", [Decimal("-0.01"), Decimal("0.123456")]) + def test_position_transfer_request_rejects_bad_price(self, bad_price: Decimal) -> None: + # v3.24.0: `price` is OrderPrice (fixed-point dollars). Negatives and + # sub-$0.0001-tick precision fail at construction; the upper bound is the + # server's to enforce (mirrors CreateOrderRequest — no client-side cap). with pytest.raises(ValidationError): ApplySubaccountPositionTransferRequest( client_transfer_id=_TEST_XFER_ID, @@ -353,7 +358,7 @@ def test_position_transfer_request_rejects_price_out_of_range(self, bad_price: i market_ticker="MKT-1", side="yes", count=5, - price_cents=bad_price, + price=bad_price, ) @@ -410,7 +415,7 @@ def test_transfer_position_sends_body_and_returns_id( market_ticker="MKT-1", side="yes", count=10, - price_cents=55, + price=Decimal("0.55"), ) assert isinstance(resp, ApplySubaccountPositionTransferResponse) assert resp.position_transfer_id == "pt-1" @@ -421,7 +426,7 @@ def test_transfer_position_sends_body_and_returns_id( "market_ticker": "MKT-1", "side": "yes", "count": 10, - "price_cents": 55, + "price": "0.55", } @respx.mock @@ -438,7 +443,7 @@ def test_transfer_position_with_request_model( market_ticker="MKT-2", side="no", count=3, - price_cents=0, + price=Decimal("0"), ) resp = subaccounts.transfer_position(request=req) assert resp.position_transfer_id == "pt-2" @@ -461,7 +466,7 @@ def test_transfer_position_rejects_malformed_uuid( market_ticker="MKT-1", side="yes", count=1, - price_cents=1, + price=Decimal("0.01"), ) @respx.mock @@ -479,7 +484,7 @@ def test_transfer_position_400_maps( market_ticker="MKT-1", side="yes", count=1, - price_cents=1, + price=Decimal("0.01"), ) def test_transfer_position_unauthenticated_raises_before_http( @@ -494,7 +499,7 @@ def test_transfer_position_unauthenticated_raises_before_http( market_ticker="MKT-1", side="yes", count=1, - price_cents=1, + price=Decimal("0.01"), ) @@ -698,8 +703,8 @@ def test_get_netting_returns_configs( 200, json={ "netting_configs": [ - {"subaccount_number": 0, "enabled": True}, - {"subaccount_number": 1, "enabled": False}, + {"subaccount_number": 0, "enabled": True, "exchange_index": 0}, + {"subaccount_number": 1, "enabled": False, "exchange_index": 0}, ], }, ), @@ -764,13 +769,13 @@ async def test_transfer_position( market_ticker="MKT-1", side="no", count=4, - price_cents=25, + price=Decimal("0.25"), ) assert isinstance(resp, ApplySubaccountPositionTransferResponse) assert resp.position_transfer_id == "pt-async" body = json.loads(route.calls[0].request.content) assert body["side"] == "no" - assert body["price_cents"] == 25 + assert body["price"] == "0.25" async def test_list_balances( self,