> ## 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.

# TypeScript SDK

> Official TypeScript SDK for the Limitless Exchange API

## Overview

The Limitless Exchange TypeScript SDK provides a type-safe client for interacting with both **CLOB** and **NegRisk** prediction markets. It handles authentication, EIP-712 order signing, market data fetching, portfolio tracking, and real-time WebSocket streaming out of the box.

<Note>
  Source code and issue tracker are available on [GitHub](https://github.com/limitless-labs-group/limitless-exchange-ts-sdk).
</Note>

## Installation

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @limitless-exchange/sdk
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @limitless-exchange/sdk
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @limitless-exchange/sdk
    ```
  </Tab>
</Tabs>

## Quick Start

<Steps>
  <Step title="Configure environment variables">
    Create a `.env` file in your project root (and add it to `.gitignore`):

    ```bash theme={null}
    LIMITLESS_API_KEY=lmts_your_api_key_here
    PRIVATE_KEY=0xYourPrivateKeyHere
    # Partner/programmatic mode (HMAC)
    LMTS_TOKEN_ID=your_token_id
    LMTS_TOKEN_SECRET=your_base64_secret
    ```

    The SDK automatically reads `LIMITLESS_API_KEY` from the environment if no `apiKey` is passed to the constructor.
  </Step>

  <Step title="Initialize the HTTP client">
    ```typescript theme={null}
    import { HttpClient } from '@limitless-exchange/sdk';

    const httpClient = new HttpClient({
      baseURL: 'https://api.limitless.exchange',
    });
    ```
  </Step>

  <Step title="Fetch active markets">
    ```typescript theme={null}
    import { MarketFetcher } from '@limitless-exchange/sdk';

    const marketFetcher = new MarketFetcher(httpClient);

    const { data: markets } = await marketFetcher.getActiveMarkets({
      limit: 10,
      sortBy: 'newest',
    });

    for (const market of markets) {
      console.log(market.slug, market.title);
    }
    ```
  </Step>

  <Step title="Authenticate for trading">
    For operations that require authentication (placing orders, fetching portfolio), supply your API key and wallet:

    ```typescript theme={null}
    import { ethers } from 'ethers';

    const httpClient = new HttpClient({
      baseURL: 'https://api.limitless.exchange',
      apiKey: process.env.LIMITLESS_API_KEY,
    });

    const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!);
    ```
  </Step>
</Steps>

## Environment Variables

| Variable            | Required                  | Description                                                                              |
| ------------------- | ------------------------- | ---------------------------------------------------------------------------------------- |
| `LIMITLESS_API_KEY` | Legacy auth only          | Deprecated API key value, auto-loaded by the SDK.                                        |
| `LMTS_TOKEN_ID`     | Partner/programmatic mode | Scoped token ID used for HMAC request signing.                                           |
| `LMTS_TOKEN_SECRET` | Partner/programmatic mode | Base64 token secret used for HMAC request signing.                                       |
| `PRIVATE_KEY`       | For order signing         | Ethereum private key used for EIP-712 order signatures. Never commit to version control. |

## Client constructor

The recommended entrypoint is the root `Client` class, which composes all domain services (markets, portfolio, orders, API tokens, partner accounts, delegated orders):

```typescript theme={null}
import { Client } from '@limitless-exchange/sdk';

const client = new Client({
  baseURL: 'https://api.limitless.exchange',
  apiKey: 'lmts_...',
});
```

For partner integrations using HMAC authentication:

```typescript theme={null}
const client = new Client({
  baseURL: 'https://api.limitless.exchange',
  hmacCredentials: {
    tokenId: process.env.LMTS_TOKEN_ID!,
    secret: process.env.LMTS_TOKEN_SECRET!,
  },
});
```

<Info>
  With `hmacCredentials` set, the SDK automatically generates and sends `lmts-api-key`, `lmts-timestamp`, and `lmts-signature` on each request. Do not manually build HMAC headers when using the SDK client.
</Info>

| Option              | Type                     | Default                         | Description                                                                                       |
| ------------------- | ------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------- |
| `baseURL`           | `string`                 | --                              | API base URL                                                                                      |
| `apiKey`            | `string`                 | `process.env.LIMITLESS_API_KEY` | Legacy API key authentication                                                                     |
| `hmacCredentials`   | `{ tokenId, secret }`    | --                              | HMAC credentials for scoped API token auth (see [Programmatic API](/developers/programmatic-api)) |
| `timeout`           | `number`                 | `30000`                         | Request timeout in milliseconds                                                                   |
| `additionalHeaders` | `Record<string, string>` | `{}`                            | Additional headers sent with every request                                                        |

### HttpClient (lower-level)

You can also use `HttpClient` directly for more control:

```typescript theme={null}
import { HttpClient } from '@limitless-exchange/sdk';

const httpClient = new HttpClient({
  baseURL: 'https://api.limitless.exchange',
  apiKey: 'lmts_...',
});
```

## What You Can Build

<CardGroup cols={2}>
  <Card title="Markets" icon="chart-line" href="/developers/sdk/typescript/markets">
    Discover markets, fetch orderbooks, and query NegRisk groups.
  </Card>

  <Card title="Market Pages" icon="compass" href="/developers/sdk/typescript/market-pages">
    Browse markets by category with navigation, filters, and pagination.
  </Card>

  <Card title="Trading and Orders" icon="arrow-right-arrow-left" href="/developers/sdk/typescript/orders">
    Create GTC and FOK orders, manage approvals, and cancel orders.
  </Card>

  <Card title="Portfolio and Positions" icon="wallet" href="/developers/sdk/typescript/portfolio">
    Track CLOB and AMM positions, PnL, and trade history.
  </Card>

  <Card title="API Tokens" icon="shield-halved" href="/developers/sdk/typescript/api-tokens">
    Derive, list, and revoke scoped HMAC tokens for partner integrations.
  </Card>

  <Card title="Partner Accounts" icon="users" href="/developers/sdk/typescript/partner-accounts">
    Create sub-accounts with server wallets or EOA verification.
  </Card>

  <Card title="Delegated Orders" icon="user-check" href="/developers/sdk/typescript/delegated-orders">
    Place orders on behalf of sub-accounts with server-side signing.
  </Card>

  <Card title="WebSocket Streaming" icon="plug" href="/developers/sdk/typescript/websocket">
    Real-time orderbook, price, position, and transaction events.
  </Card>
</CardGroup>

## Server Wallet Redemption and Withdrawal

For partner server-wallet sub-accounts, the SDK provides helper methods for payout settlement and treasury movement:

* [`POST /portfolio/redeem`](/api-reference/portfolio/redeem) — claim resolved positions
* [`POST /portfolio/withdraw`](/api-reference/portfolio/withdraw) — transfer ERC20 funds from managed sub-accounts
* [`POST /portfolio/withdrawal-addresses`](/api-reference/portfolio/add-withdrawal-address) — allowlist an explicit treasury destination with Privy identity auth
* [`DELETE /portfolio/withdrawal-addresses/:address`](/api-reference/portfolio/delete-withdrawal-address) — remove an allowlisted destination with Privy identity auth

Required scopes for `apiToken` auth: `trading` for redeem and `withdrawal` for withdraw. Allowlist add/delete calls use a Privy identity token instead of API-token/HMAC auth.

```typescript theme={null}
const identityToken = process.env.PRIVY_IDENTITY_TOKEN!;
const treasuryAddress = '0x0F3262730c909408042F9Da345a916dc0e1F9787';

await client.partnerAccounts.addWithdrawalAddress(identityToken, {
  address: treasuryAddress,
  label: 'treasury',
});

await client.serverWallets.withdraw({
  amount: '1000000',
  onBehalfOf: childProfileId,
  destination: treasuryAddress,
});
```

Set `onBehalfOf` when withdrawing from a child server-wallet profile. `destination` is optional for child withdrawals; when omitted, the API defaults to the authenticated partner smart wallet when present, otherwise the authenticated partner account. You can omit `onBehalfOf` only when withdrawing the authenticated caller's own server wallet to an explicit `destination`.

See the full flow and scope guidance in [Programmatic API](/developers/programmatic-api).

## Disclaimer

<Warning>
  **USE AT YOUR OWN RISK.** This SDK and the Limitless Exchange protocol are provided as-is with no warranties. You are solely responsible for any funds used or lost. By using this SDK, you acknowledge that prediction markets involve financial risk. The Limitless Exchange is not available to users in the United States or other restricted jurisdictions. Ensure compliance with your local laws before trading.
</Warning>
