> ## Documentation Index
> Fetch the complete documentation index at: https://docs.polysimulator.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Book By Token

> Get the order book for a single token.

**Level ordering is byte-identical to Polymarket's LIVE ``/book``
wire** (verified against ``clob.polymarket.com/book`` 2026-06-10):
``bids`` are ASCENDING by price (best/highest bid = ``bids[-1]``) and
``asks`` are DESCENDING by price (best/lowest ask = ``asks[-1]``)
the best level is at the TAIL on BOTH sides, exactly as PM's live
CLOB returns it. Note this is the *wire* ordering; PM's published
docs describe the opposite, but the live wire does not match the
docs and wire-parity is the contract here. ``mid`` and ``spread`` are
computed from the FULL book (true top-of-book), not from the
truncated slice — see ``_book_levels_and_summary``.

**RECOMMENDED — read order-independently**: do NOT index a fixed
position. Compute best bid as ``max(float(b["price"]) for b in
bids)`` and best ask as ``min(float(a["price"]) for a in asks)``.
This stays correct regardless of array order and survives any future
wire-format change on either side.

**MIGRATION NOTE (2026-06-10)**: book level ordering changed to PM
live-wire parity. History (3 changes in 24h): pre-2026-05-19 bids
were ASCENDING (best = ``bids[-1]``); the 2026-06-10 AM change flipped
to bids DESCENDING / asks ASCENDING (best = ``[0]``) to match PM's
*docs*; this change re-sorts to PM's *live wire* — bids ASCENDING /
asks DESCENDING (best = ``[-1]``). A bot that read ``bids[0]`` for the
best bid during the brief docs-aligned window now gets the WORST bid;
switch to the order-independent ``max``/``min`` reads above.



## OpenAPI

````yaml /openapi.json get /v1/book
openapi: 3.1.0
info:
  title: Polysimulator API
  summary: HFT-style paper-trading API for Polymarket simulation.
  description: >-
    PolySimulator HFT API v1 — Virtual trading environment for Polymarket
    prediction markets. Practice trading with real market data using paper
    money, then switch to live trading by changing only your API credentials.
  termsOfService: https://polysimulator.com/legal/terms
  contact:
    name: PolySimulator
    url: https://polysimulator.com
  license:
    name: Proprietary — usage subject to Polysimulator Terms of Service
    url: https://polysimulator.com/legal/terms
  version: 1.0.0-beta
servers:
  - url: https://api.polysimulator.com
    description: Production
  - url: https://staging-api.polysimulator.com
    description: Staging
security:
  - ApiKeyAuth: []
tags:
  - name: API Keys
    description: >-
      Bootstrap, create, list, revoke API keys, mint short-lived WebSocket
      tokens, list rate-limit tiers.
  - name: Account
    description: >-
      Balance, equity curve, portfolio composition, open positions, trade
      history.
  - name: Export
    description: >-
      Pro data export — streamed CSV downloads for offline analysis,
      backtesting, and tax/accounting. v1: GET /v1/export/trades.csv (FILLED
      trades, keyset-paginated). Dual session + API-key auth.
  - name: Profile Analysis
    description: >-
      Trading-profile analytics — Sharpe, win-rate, drawdown, holding-period
      histograms.
  - name: Wallets
    description: >-
      Multi-wallet management (MAIN / SANDBOX / API / COMPETITION). List, switch
      active wallet, per-wallet balance + history.
  - name: Trading
    description: >-
      Place, cancel, batch, and list orders. Cancel-all + cancel-market-orders
      sweep endpoints. PolySimulator-native order surface.
  - name: Market Data
    description: >-
      Polymarket market metadata + live prices (POST /v1/prices/batch,
      /v1/markets, /v1/markets/{condition_id}/candles).
  - name: CLOB Read (Public)
    description: >-
      Polymarket-shape read endpoints (book, midpoint, spread, price,
      last-trade-price, tick-size, neg-risk, time). Wire-compatible with
      py-clob-client.
  - name: CLOB Compat
    description: >-
      Polymarket-shape order surface (POST /v1/order with nested body, POST
      /v1/orders batch, GET /v1/data/orders PM-envelope). Use these for drop-in
      py-clob-client compatibility.
  - name: WebSocket
    description: >-
      WebSocket subscription endpoints — /v1/ws/prices for live market data,
      /v1/ws/executions for order-state updates.
  - name: Billing
    description: >-
      Stripe-backed subscriptions, top-ups, customer portal, refund policy,
      paid-tier resets.
  - name: Status
    description: System-status surface — uptime, component health, recent incident markers.
  - name: Health
    description: >-
      Health, liveness, readiness, and authenticated-identity probes
      (/v1/health, /v1/health/live, /v1/health/ready, /v1/me).
  - name: Football
    description: >-
      Football / World-Cup 2026 enrichment — live score, minute, momentum,
      possession, xG, shotmap, commentary, lineups, group standings, knockout
      bracket, and head-to-head. Public read-only sports facts the UI merges
      with tradable Polymarket prices; degrades to empty shapes on upstream
      failure.
paths:
  /v1/book:
    get:
      tags:
        - CLOB Read (Public)
        - CLOB Read (Public)
      summary: Get Book By Token
      description: |-
        Get the order book for a single token.

        **Level ordering is byte-identical to Polymarket's LIVE ``/book``
        wire** (verified against ``clob.polymarket.com/book`` 2026-06-10):
        ``bids`` are ASCENDING by price (best/highest bid = ``bids[-1]``) and
        ``asks`` are DESCENDING by price (best/lowest ask = ``asks[-1]``)
        the best level is at the TAIL on BOTH sides, exactly as PM's live
        CLOB returns it. Note this is the *wire* ordering; PM's published
        docs describe the opposite, but the live wire does not match the
        docs and wire-parity is the contract here. ``mid`` and ``spread`` are
        computed from the FULL book (true top-of-book), not from the
        truncated slice — see ``_book_levels_and_summary``.

        **RECOMMENDED — read order-independently**: do NOT index a fixed
        position. Compute best bid as ``max(float(b["price"]) for b in
        bids)`` and best ask as ``min(float(a["price"]) for a in asks)``.
        This stays correct regardless of array order and survives any future
        wire-format change on either side.

        **MIGRATION NOTE (2026-06-10)**: book level ordering changed to PM
        live-wire parity. History (3 changes in 24h): pre-2026-05-19 bids
        were ASCENDING (best = ``bids[-1]``); the 2026-06-10 AM change flipped
        to bids DESCENDING / asks ASCENDING (best = ``[0]``) to match PM's
        *docs*; this change re-sorts to PM's *live wire* — bids ASCENDING /
        asks DESCENDING (best = ``[-1]``). A bot that read ``bids[0]`` for the
        best bid during the brief docs-aligned window now gets the WORST bid;
        switch to the order-independent ``max``/``min`` reads above.
      operationId: getOrderBook
      parameters:
        - name: token_id
          in: query
          required: true
          schema:
            type: string
            description: CLOB outcome token ID
            title: Token Id
          description: CLOB outcome token ID
        - name: depth
          in: query
          required: false
          schema:
            anyOf:
              - type: integer
                maximum: 500
                minimum: 1
              - type: 'null'
            description: >-
              OPTIONAL trim: keep only the best N levels per side. Default
              (omitted) returns the FULL book — Polymarket's wire contract (PM
              has no depth param). Pre-2026-06-11 the default silently truncated
              to 10 levels (max 50), so ported depth/imbalance/queue-position
              logic computed on a sliver of the real book.
            title: Depth
          description: >-
            OPTIONAL trim: keep only the best N levels per side. Default
            (omitted) returns the FULL book — Polymarket's wire contract (PM has
            no depth param). Pre-2026-06-11 the default silently truncated to 10
            levels (max 50), so ported depth/imbalance/queue-position logic
            computed on a sliver of the real book.
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderBookSnapshot'
          headers:
            X-RateLimit-Limit:
              description: >-
                Requests permitted in the current minute window for this key's
                tier.
              schema:
                type: string
            X-RateLimit-Remaining:
              description: Requests remaining in the current minute window.
              schema:
                type: string
            X-RateLimit-Reset:
              description: Unix-seconds timestamp when the current minute window resets.
              schema:
                type: string
            X-Polysim-RateLimit-Limit:
              description: Alias of X-RateLimit-Limit (requests per minute for this tier).
              schema:
                type: string
            X-Polysim-RateLimit-Remaining:
              description: Alias of X-RateLimit-Remaining (requests remaining this minute).
              schema:
                type: string
            X-Polysim-RateLimit-Reset:
              description: Alias of X-RateLimit-Reset (minute-window reset, unix seconds).
              schema:
                type: string
            X-Request-Id:
              description: >-
                Request id for log correlation. Echoes the caller's
                ``X-Request-Id`` when supplied, otherwise a server-minted UUID.
                Stamped on every response (success and error).
              schema:
                type: string
        '404':
          description: Resource not found (market / order / token).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
          headers:
            X-Polysim-Code:
              description: >-
                Stable short code identifying the error class. SDK consumers
                should branch on this header rather than the body text. Domain
                codes (INVALID_KEY, MARKET_NOT_FOUND, RATE_LIMIT_EXCEEDED, …)
                are preferred; HTTP_<status> fallbacks ship when no domain code
                applies. The full list is mirrored in /llms.txt under ‘Error
                Format’.
              schema:
                type: string
                enum:
                  - INVALID_KEY
                  - MISSING_API_KEY
                  - INSUFFICIENT_PERMISSION
                  - INSUFFICIENT_BALANCE
                  - MARKET_CLOSED
                  - INVALID_ORDER_MIN_TICK_SIZE
                  - MARKET_NOT_FOUND
                  - ORDER_NOT_FOUND
                  - RATE_LIMIT_EXCEEDED
                  - BOOK_UNAVAILABLE
                  - VALIDATION_FAILED
                  - UPGRADE_REQUIRED
                  - ACCESS_RESTRICTED
                  - COHORT_FULL
                  - AUTH_STATE_INCOMPLETE
                  - INTERNAL_ERROR
                  - TOKEN_NOT_FOUND
                  - INVALID_CURSOR
                  - UPSTREAM_UNAVAILABLE
                  - UNSUPPORTED_ORDER_TYPE
                  - DUPLICATE_CLIENT_ORDER_ID
                  - ORDER_EXECUTION_FAILED
                  - DEADLINE_OVERSHOT_BUT_PERSISTED
                  - PERSISTENCE_UNKNOWN
                  - INVALID_BODY
                  - INVALID_SOURCE
                  - CLOSED_BETA
                  - API_PRO_COMING_SOON
                  - TIER_KEY_LIMIT_EXCEEDED
                  - HTTP_400
                  - HTTP_401
                  - HTTP_403
                  - HTTP_404
                  - HTTP_409
                  - HTTP_422
                  - HTTP_429
                  - HTTP_500
                  - HTTP_502
                  - HTTP_503
            X-Request-Id:
              description: >-
                Request id for log correlation. Echoes the caller's
                ``X-Request-Id`` when supplied, otherwise a server-minted UUID.
                Stamped on every response (success and error).
              schema:
                type: string
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
          headers:
            X-Polysim-Code:
              description: >-
                Stable short code identifying the error class. SDK consumers
                should branch on this header rather than the body text. Domain
                codes (INVALID_KEY, MARKET_NOT_FOUND, RATE_LIMIT_EXCEEDED, …)
                are preferred; HTTP_<status> fallbacks ship when no domain code
                applies. The full list is mirrored in /llms.txt under ‘Error
                Format’.
              schema:
                type: string
                enum:
                  - INVALID_KEY
                  - MISSING_API_KEY
                  - INSUFFICIENT_PERMISSION
                  - INSUFFICIENT_BALANCE
                  - MARKET_CLOSED
                  - INVALID_ORDER_MIN_TICK_SIZE
                  - MARKET_NOT_FOUND
                  - ORDER_NOT_FOUND
                  - RATE_LIMIT_EXCEEDED
                  - BOOK_UNAVAILABLE
                  - VALIDATION_FAILED
                  - UPGRADE_REQUIRED
                  - ACCESS_RESTRICTED
                  - COHORT_FULL
                  - AUTH_STATE_INCOMPLETE
                  - INTERNAL_ERROR
                  - TOKEN_NOT_FOUND
                  - INVALID_CURSOR
                  - UPSTREAM_UNAVAILABLE
                  - UNSUPPORTED_ORDER_TYPE
                  - DUPLICATE_CLIENT_ORDER_ID
                  - ORDER_EXECUTION_FAILED
                  - DEADLINE_OVERSHOT_BUT_PERSISTED
                  - PERSISTENCE_UNKNOWN
                  - INVALID_BODY
                  - INVALID_SOURCE
                  - CLOSED_BETA
                  - API_PRO_COMING_SOON
                  - TIER_KEY_LIMIT_EXCEEDED
                  - HTTP_400
                  - HTTP_401
                  - HTTP_403
                  - HTTP_404
                  - HTTP_409
                  - HTTP_422
                  - HTTP_429
                  - HTTP_500
                  - HTTP_502
                  - HTTP_503
            X-Request-Id:
              description: >-
                Request id for log correlation. Echoes the caller's
                ``X-Request-Id`` when supplied, otherwise a server-minted UUID.
                Stamped on every response (success and error).
              schema:
                type: string
        '429':
          description: Rate limit exceeded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiError'
          headers:
            X-Polysim-Code:
              description: >-
                Stable short code identifying the error class. SDK consumers
                should branch on this header rather than the body text. Domain
                codes (INVALID_KEY, MARKET_NOT_FOUND, RATE_LIMIT_EXCEEDED, …)
                are preferred; HTTP_<status> fallbacks ship when no domain code
                applies. The full list is mirrored in /llms.txt under ‘Error
                Format’.
              schema:
                type: string
                enum:
                  - INVALID_KEY
                  - MISSING_API_KEY
                  - INSUFFICIENT_PERMISSION
                  - INSUFFICIENT_BALANCE
                  - MARKET_CLOSED
                  - INVALID_ORDER_MIN_TICK_SIZE
                  - MARKET_NOT_FOUND
                  - ORDER_NOT_FOUND
                  - RATE_LIMIT_EXCEEDED
                  - BOOK_UNAVAILABLE
                  - VALIDATION_FAILED
                  - UPGRADE_REQUIRED
                  - ACCESS_RESTRICTED
                  - COHORT_FULL
                  - AUTH_STATE_INCOMPLETE
                  - INTERNAL_ERROR
                  - TOKEN_NOT_FOUND
                  - INVALID_CURSOR
                  - UPSTREAM_UNAVAILABLE
                  - UNSUPPORTED_ORDER_TYPE
                  - DUPLICATE_CLIENT_ORDER_ID
                  - ORDER_EXECUTION_FAILED
                  - DEADLINE_OVERSHOT_BUT_PERSISTED
                  - PERSISTENCE_UNKNOWN
                  - INVALID_BODY
                  - INVALID_SOURCE
                  - CLOSED_BETA
                  - API_PRO_COMING_SOON
                  - TIER_KEY_LIMIT_EXCEEDED
                  - HTTP_400
                  - HTTP_401
                  - HTTP_403
                  - HTTP_404
                  - HTTP_409
                  - HTTP_422
                  - HTTP_429
                  - HTTP_500
                  - HTTP_502
                  - HTTP_503
            X-Request-Id:
              description: >-
                Request id for log correlation. Echoes the caller's
                ``X-Request-Id`` when supplied, otherwise a server-minted UUID.
                Stamped on every response (success and error).
              schema:
                type: string
      security: []
components:
  schemas:
    OrderBookSnapshot:
      properties:
        token_id:
          type: string
          title: Token Id
        bids:
          items:
            $ref: '#/components/schemas/BookLevel'
          type: array
          title: Bids
          default: []
        asks:
          items:
            $ref: '#/components/schemas/BookLevel'
          type: array
          title: Asks
          default: []
        timestamp:
          anyOf:
            - type: string
            - type: 'null'
          title: Timestamp
        market:
          anyOf:
            - type: string
            - type: 'null'
          title: Market
        asset_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Asset Id
        hash:
          anyOf:
            - type: string
            - type: 'null'
          title: Hash
        min_order_size:
          anyOf:
            - type: string
            - type: 'null'
          title: Min Order Size
        tick_size:
          anyOf:
            - type: string
            - type: 'null'
          title: Tick Size
        neg_risk:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Neg Risk
        last_trade_price:
          anyOf:
            - type: string
            - type: 'null'
          title: Last Trade Price
        spread:
          anyOf:
            - type: string
            - type: 'null'
          title: Spread
        mid:
          anyOf:
            - type: string
            - type: 'null'
          title: Mid
        stale:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Stale
      type: object
      required:
        - token_id
      title: OrderBookSnapshot
      description: |-
        Polymarket-compat ``OrderBookSummary``.

        The PM-CLOB ``GET /book`` response carries metadata fields
        (``market``, ``asset_id``, ``hash``, ``timestamp``,
        ``min_order_size``, ``tick_size``, ``neg_risk``,
        ``last_trade_price``) that SDK consumers ported from Polymarket
        clients depend on — particularly ``tick_size`` for client-side
        price quantization and ``neg_risk`` for routing through the
        correct contract. Pre-this-PR the response was a Polysimulator
        minimum (``token_id``, ``bids``, ``asks``, ``spread``, ``mid``)
        that would silently break PM-ported SDKs at parse time.

        The legacy fields (``spread``, ``mid``) are kept for back-compat
        with existing Polysimulator SDK consumers who relied on them.
        Polymarket's actual ``/book`` doesn't return either; they're
        Polysimulator extensions and documented as such.
    ApiError:
      properties:
        error:
          type: string
          title: Error
          description: >-
            Human-readable message (PM-shape default body) OR machine-readable
            error code (verbose body). The machine code is always available in
            the X-Polysim-Code response header.
        message:
          anyOf:
            - type: string
            - type: 'null'
          title: Message
          description: >-
            Human-readable error description — populated only on verbose body
            (X-Polysim-Verbose: true).
        details:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Details
          description: Additional context — populated only on verbose body.
        request_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Request Id
          description: >-
            Request id for support reference. Always exposed via X-Request-Id
            response header; only inlined in the verbose body.
      type: object
      required:
        - error
      title: ApiError
      description: |-
        Structured error response for all API v1 endpoints.

        * ``error`` carries the human-readable message in the default body
         and the machine code in the verbose body. The machine code is
         ALWAYS exposed via the ``X-Polysim-Code`` response header so SDK
         consumers can switch on a stable identifier without parsing the
         body.
        * ``request_id`` → exposed as the ``X-Request-Id`` response header
         on every response (success and error).

        All non-required fields are ``Optional`` so generated SDK code can
        deserialize *either* shape (PM-default or polysim-verbose) without
        choking on missing keys. Pre-PR ``message`` was required, which
        broke SDK deserialization of the new PM-shape body.
    BookLevel:
      properties:
        price:
          type: string
          title: Price
        size:
          type: string
          title: Size
      type: object
      required:
        - price
        - size
      title: BookLevel
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: Issue from /v1/keys (or admin-issued for enterprise tier).

````