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

# Get Orderbook

> Retrieve the current LIVE GTC YES-side order book for one exact active CLOB market slug. The separately produced last mined trade price may be null without failing the request.

<Tip>
  For real-time orderbook updates, use the [WebSocket API](/developers/websocket/market-data) instead of polling this endpoint. Subscribe to `subscribe_market_prices` with `marketSlugs`. Subscribing also pushes this book once per slug as an initial `orderbookUpdate`, so you do not need this endpoint to seed local state.
</Tip>

<Note>
  **Current snapshot only, one market per request.** This endpoint returns the current LIVE GTC orderbook for one exact CLOB market slug. There is no batched form that accepts multiple slugs; to follow several markets at once use the WebSocket subscription above. It does not aggregate a group slug, and AMM markets do not have an orderbook. CLOB markets are available only while their status is `CREATED` or `FUNDED`.

  There is no historical orderbook endpoint. For past activity on a market, combine three sources:

  * [Get Historical Prices](/api-reference/trading/historical-price) for price series.
  * [Get Feed Events](/api-reference/markets/feed-events) for trade events.
  * [Get History](/api-reference/portfolio/history) for your own CLOB fills (filter `strategy` on `Limit Buy` / `Limit Sell` / `Market Buy` / `Market Sell`).
</Note>

## Snapshot and price freshness

`lastTradePrice` is a nullable YES-equivalent price and is not guaranteed to represent the same point in time as the order-book levels. No bound on response freshness is guaranteed.

`midpoint` uses the best displayed bid and ask. `adjustedMidpoint` excludes individual orders smaller than `minSize` before price-level aggregation and midpoint calculation. Every bid level has `side: "BUY"`; every ask level has `side: "SELL"`.

## Complementary token prices (deriving the NO book)

This endpoint returns a **single, YES-side book**. The `tokenId` in the response is the market's YES position ID, and `bids`/`asks` are quoted in YES-token terms. The two outcome tokens are complementary: a YES share and a NO share always redeem together for exactly \$1. Their prices therefore satisfy:

```
price(YES) + price(NO) = 1
```

The book you get back already merges **all** liquidity for the market: native NO orders are converted into their YES-side equivalent before aggregation, using the same identity:

```
NO bid  @ P   ≡   YES ask @ (1 - P)     (someone bidding for NO is offering YES)
NO ask  @ P   ≡   YES bid @ (1 - P)     (someone offering NO is bidding for YES)
```

So you never lose NO liquidity by reading the YES book. It's all there, expressed in YES prices.

### Deriving the NO orderbook

To quote or trade the **NO** token, mirror the returned YES book: flip bids ↔ asks and replace every price `p` with `1 - p` (sizes are unchanged).

| NO book                         | Derived from | Best level                     |
| ------------------------------- | ------------ | ------------------------------ |
| **NO bids** (orders to buy NO)  | YES **asks** | best NO bid = `1 - bestYesAsk` |
| **NO asks** (orders to sell NO) | YES **bids** | best NO ask = `1 - bestYesBid` |

The midpoint and spread carry over directly: `noMidpoint = 1 - yesMidpoint`, and the spread is identical.

<CodeGroup>
  ```typescript TypeScript theme={null}
  type Level = { price: number; size: number; side: "BUY" | "SELL" };
  type Book = { bids: Level[]; asks: Level[] };

  // Mirror the YES-side book into the NO-side book.
  function deriveNoBook(yes: Book): Book {
    const invert = (l: Level): Level => ({
      price: 1 - l.price,
      size: l.size,
      side: l.side === "BUY" ? "SELL" : "BUY",
    });
    return {
      bids: yes.asks.map(invert).sort((a, b) => b.price - a.price), // best (highest) first
      asks: yes.bids.map(invert).sort((a, b) => a.price - b.price), // best (lowest) first
    };
  }

  // To SELL NO, hit the best NO bid:  1 - bestYesAsk
  // To BUY  NO, lift the best NO ask: 1 - bestYesBid
  ```

  ```python Python theme={null}
  def derive_no_book(yes: dict) -> dict:
      """Mirror the YES-side book into the NO-side book."""
      invert = lambda l: {
          "price": 1 - l["price"],
          "size": l["size"],
          "side": "SELL" if l["side"] == "BUY" else "BUY",
      }
      return {
          "bids": sorted((invert(a) for a in yes["asks"]), key=lambda l: -l["price"]),  # best first
          "asks": sorted((invert(b) for b in yes["bids"]), key=lambda l: l["price"]),   # best first
      }

  # To SELL NO, hit the best NO bid:  1 - best_yes_ask
  # To BUY  NO, lift the best NO ask: 1 - best_yes_bid
  ```
</CodeGroup>

When you then place a NO order, sign it against the NO `tokenId` (`noPositionId` from [Get Market](/api-reference/markets/get-market)) at the derived price. The price inversion only affects how you *read* the book, not how the order is signed.

## Multi-outcome (NegRisk) markets

In a [NegRisk](/user-guide/negrisk-overview) multi-outcome market, **each outcome is its own market** with its own slug, its own YES/NO tokens, and its own orderbook. Fetch each outcome's book by its slug and derive that outcome's NO book with the same inversion above. There is no single cross-outcome book to invert.

What links the outcomes is a soft pricing constraint, not a shared book. Across the *N* outcomes, the YES prices tend toward summing to 1 (exactly one outcome resolves YES). All the NO contracts are linked for [share conversion](/user-guide/converting-shares). To assemble a full picture of a multi-outcome market, request the orderbook for each outcome slug and mirror each one independently.

## Errors

| Status | Meaning                                                                                                                                                 |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | The exact market is an AMM (`Market does not support orderbook (AMM market)`) or its CLOB status is not `CREATED` or `FUNDED` (`Market is not active`). |
| `404`  | No exact market has the slug (`Market not found`). A group slug also produces this response.                                                            |
| `500`  | The orderbook could not be read unexpectedly.                                                                                                           |


## OpenAPI

````yaml GET /markets/{slug}/orderbook
openapi: 3.0.0
info:
  title: Limitless Exchange API
  description: >-

    # Limitless Exchange Trading API


    *Production-ready API for prediction market trading, portfolio management,
    and market data*


    > 🎯 **Quick Navigation**: [Authentication](#tag/authentication) |
    [Markets](#tag/markets) | [Trading](#tag/trading) |
    [Portfolio](#tag/portfolio)


    ---
      


    ## 🚀 Quick Start


    Choose your preferred programming language for complete end-to-end
    implementation:


    ### Overview


    The Limitless Exchange API offers both REST and WebSocket integration:


    **REST API (Trading)**:

    1. **🔐 Authentication**: Use API key for all programmatic access

    2. **📊 Fetch Market Data**: Get market info including venue contract
    addresses (once per market)

    3. **📋 Order Creation**: Build and sign orders using EIP-712 structured
    data

    4. **🚀 Order Submission**: Submit signed orders and receive confirmations


    **WebSocket API (Real-Time Data)**:

    1. **🔌 Connection**: Connect to `/markets` namespace for real-time updates

    2. **📊 Subscriptions**: Subscribe to market prices and position changes

    3. **📡 Events**: Handle live market data and transaction updates


    ### 🔐 Authentication for API Users


    > **⚠️ DEPRECATION NOTICE**: Cookie-based session authentication is
    deprecated and will be removed within weeks. Please migrate to API keys
    immediately.


    | Method | Header | Status |

    |--------|--------|--------|

    | **API Key** | `X-API-Key: lmts_...` | ✅ Required for programmatic access |

    | Cookie Session | `Cookie: limitless_session=...` | ⚠️ Deprecated (removal
    imminent) |


    **Getting an API Key**


    API keys can only be created via the Limitless Exchange UI:

    1. Log in to [limitless.exchange](https://limitless.exchange) using your
    wallet

    2. Click your profile menu (top right)

    3. Select "Api keys"

    4. Generate a new key


    **Using Your API Key**


    Include in all requests via the `X-API-Key` header:


    ```bash

    # REST API

    curl -H "X-API-Key: lmts_your_key_here"
    https://api.limitless.exchange/markets


    # WebSocket - pass X-API-Key header during connection handshake

    ```


    ### Migration from Cookie to API Key


    If you're currently using cookie-based authentication, migrate by:


    1. **Generate an API key** via the UI (profile menu → Api keys)

    2. **Replace cookie header** with API key header:


    ```diff

    # Before (deprecated)

    - Cookie: limitless_session=your_session_token


    # After

    + X-API-Key: lmts_your_key_here

    ```


    3. **Remove session management code** - no more login flow or cookie
    handling needed


    ### Important: Venue System for CLOB Markets


    CLOB markets use a **venue system** where each market is associated with
    specific contract addresses. Before placing orders:


    1. **Fetch market data once**: `GET /markets/:slug` returns venue
    information

    2. **Use venue.exchange**: This is the `verifyingContract` for EIP-712 order
    signing

    3. **Cache the venue**: Venue data is static per market - fetch once and
    reuse


    **Sample venue response:**

    ```json

    {
      "venue": {
        "exchange": "0xA1b2C3...",
        "adapter": "0xD4e5F6..."
      }
    }

    ```


    ### Required Approvals


    Before trading, set up token approvals based on order type:


    | Order Type | Market Type | Approve To |

    |------------|-------------|------------|

    | BUY | All CLOB | USDC → `venue.exchange` |

    | SELL | Simple CLOB | CT → `venue.exchange` |

    | SELL | NegRisk/Grouped | CT → `venue.exchange` AND `venue.adapter` |


    ### Checksummed Addresses


    All addresses must use **checksummed format** (EIP-55 mixed-case):

    - Authentication: `x-account` header

    - Orders: `maker` and `signer` fields

    - Example: `0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed`


    ### Implementation Guides


    **[🐍 Python Quick Start](#description/-python-quick-start)**

    - REST API: eth-account, requests, and web3.py libraries

    - WebSocket: python-socketio, asyncio integration


    **[☕ Java Quick Start](#description/-java-quick-start)**  

    - REST API: Web3j, OkHttp3, and Jackson libraries


    **[📦 Node.js/TypeScript Quick
    Start](#description/-nodejs-typescript-quick-start)**

    - REST API: viem, ethers, and cross-fetch libraries

    - WebSocket: socket.io-client for real-time trading

    - Full TypeScript support with end-to-end examples


    **[🔌 WebSocket Integration](#description/-websocket-integration)**

    - Real-time market data and position updates

    - Production-ready Python client with authentication


    ---
      


    ## 🐍 Python Quick Start


    Complete end-to-end Python implementation for Limitless Exchange API
    integration.
      


    ### 🐍 Python E2E Order Creation Guide


    Complete Python implementation guide is being loaded from external
    documentation...


    **Guide Contents:**

    - 🔐 Complete authentication flow with eth-account

    - 📋 Order construction with Web3.py calculations

    - ✍️ EIP-712 structured data signing

    - 🚀 Order submission with requests library

    - ⚠️ Comprehensive error handling

    - 🛠️ Production deployment considerations


    *For the complete Python guide, ensure the file is available at
    docs/scripts-samples/python-e2e-order-creation.md*
        


    ## ☕ Java Quick Start


    Complete end-to-end Java implementation for Limitless Exchange API
    integration.
      


    ### ☕ Java E2E Order Creation Guide


    Complete Java enterprise implementation guide is being loaded from external
    documentation...


    **Guide Contents:**

    - 🔐 Complete authentication flow with Web3j

    - 📋 Order construction with BigInteger precision

    - ✍️ EIP-712 structured data signing

    - 🚀 Order submission with OkHttp3

    - ⚠️ Enterprise error handling patterns

    - 🏗️ Production Maven project structure


    *For the complete Java guide, ensure the file is available at
    docs/scripts-samples/java-e2e-order-creation.md*
        


    ## 📦 Node.js/TypeScript Quick Start


    Complete end-to-end Node.js/TypeScript implementation for trading and
    WebSocket subscriptions.
      


    ### 📦 Node.js/TypeScript Trading & WebSocket Guide


    Complete Node.js/TypeScript implementation guide is being loaded from
    external documentation...


    **Guide Contents:**

    - 🔐 **Authentication**: Wallet-based auth with ethers and viem

    - 📋 **Order Creation**: EIP-712 signing with viem WalletClient

    - 🚀 **Order Submission**: REST API integration with cross-fetch

    - 🔌 **WebSocket Subscriptions**: socket.io-client for real-time updates

    - 📊 **Market Data**: AMM prices and CLOB orderbook subscriptions

    - ⚠️ **Type Safety**: Full TypeScript support with proper types

    - 🛠️ **Production Ready**: Complete end-to-end working example


    **Key Features:**

    - **Combined Subscriptions**: Subscribe to both AMM and CLOB markets
    simultaneously

    - **Authentication Flow**: Complete wallet-based authentication with session
    management

    - **Trading Integration**: Place orders and receive real-time updates

    - **TypeScript First**: Type-safe implementation with proper interfaces


    *For the complete Node.js guide, ensure the file is available at
    docs/scripts-samples/node-socket-trading-and-subscribe.md*
        


    ## 🔌 WebSocket Integration


    Real-time market data and position updates using WebSocket connections.
      


    ### 🔌 WebSocket Real-Time Integration Guide


    Complete WebSocket implementation guide is being loaded from external
    documentation...


    **Guide Contents:**

    - 🔌 **WebSocket Connection**: python-socketio client with async support

    - 🔐 **Authentication**: JWT session cookie integration

    - 📊 **Market Subscriptions**: Real-time price updates and position changes

    - ⚡ **Event Handling**: Comprehensive event processing patterns

    - 🔄 **Auto-Reconnection**: Production-ready reconnection logic

    - 🛠️ **Error Recovery**: Robust error handling and fallback strategies


    **Key Features:**

    - **Public Mode**: Market price updates without authentication

    - **Authenticated Mode**: Full access to positions and transactions

    - **Multi-Market Support**: Subscribe to multiple markets simultaneously

    - **Production Ready**: Tested patterns for production deployment


    *For the complete WebSocket guide, ensure the file is available at
    docs/scripts-samples/python-socket-subscribe.md*
        
  version: '1.0'
  contact:
    name: API Support
    url: https://limitless.exchange
    email: hey@limitless.network
servers:
  - url: https://api.limitless.exchange
    description: Production API
security: []
tags:
  - name: Authentication
    description: User authentication and session management
  - name: Markets
    description: Browse, search, and analyze prediction markets
  - name: Market Navigation
    description: Navigation tree, market pages, and property filters
  - name: Trading
    description: Create, manage, and cancel orders
  - name: Portfolio
    description: Position tracking, trade history, and performance
  - name: Feed
    description: Public trading activity feeds
paths:
  /markets/{slug}/orderbook:
    get:
      tags:
        - Trading
      summary: Get Orderbook
      description: >-
        Retrieve the current LIVE GTC YES-side order book for one exact active
        CLOB market slug. The separately produced last mined trade price may be
        null without failing the request.
      operationId: MarketOrderbookController_getOrderbook
      parameters:
        - name: slug
          required: true
          in: path
          description: Market slug identifier
          schema:
            example: presidential-election-2024
      responses:
        '200':
          description: Current orderbook with bids and asks
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MarketOrderbookResponse'
        '400':
          description: The market is an AMM or its CLOB status is not CREATED or FUNDED
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                properties:
                  message:
                    type: string
                    enum:
                      - Market is not active
                      - Market does not support orderbook (AMM market)
                required:
                  - message
        '404':
          description: No exact market has the slug; group slugs are not aggregated
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                properties:
                  message:
                    type: string
                    enum:
                      - Market not found
                required:
                  - message
        '500':
          description: >-
            Orderbook lookup failed unexpectedly; a last trade price lookup
            failure instead returns 200 with lastTradePrice null
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessageResponse'
components:
  schemas:
    MarketOrderbookResponse:
      type: object
      properties:
        adjustedMidpoint:
          type: number
          description: >-
            Midpoint after excluding individual orders below minSize before
            price-level aggregation.
          example: 0.75
        asks:
          description: YES asks in ascending price order. Each level has side SELL.
          type: array
          items:
            $ref: '#/components/schemas/MarketOrderbookLevel'
        bids:
          description: YES bids in descending price order. Each level has side BUY.
          type: array
          items:
            $ref: '#/components/schemas/MarketOrderbookLevel'
        lastTradePrice:
          type: number
          nullable: true
          description: >-
            Separately produced latest usable mined YES-equivalent trade price;
            null when no usable value is available, including when its lookup
            fails.
          example: 0.75
        maxSpread:
          type: number
          example: 0.05
        midpoint:
          type: number
          description: Midpoint from the best displayed bid and ask.
          example: 0.75
        minSize:
          type: number
          example: 1
        tokenId:
          type: string
          description: YES position token ID.
          example: >-
            19633204485790857949828516737993423758628930235371629943999544859324645414627
      additionalProperties: false
      required:
        - adjustedMidpoint
        - asks
        - bids
        - lastTradePrice
        - maxSpread
        - midpoint
        - minSize
        - tokenId
    ErrorMessageResponse:
      type: object
      properties:
        message:
          type: string
      additionalProperties: false
      required:
        - message
    MarketOrderbookLevel:
      type: object
      properties:
        price:
          type: number
          example: 0.74
        size:
          type: number
          example: 150
        side:
          type: string
          enum:
            - BUY
            - SELL
          example: BUY
      additionalProperties: false
      required:
        - price
        - size
        - side

````