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

# TypeScript SDK

> Call the Lean API from TypeScript, with a typed method for every endpoint.

[`@leanxyz/api-sdk`](https://www.npmjs.com/package/@leanxyz/api-sdk) is the Lean API client for
TypeScript and JavaScript. It is generated from the
[OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json), so every endpoint in the
[API reference](https://docs.lean.xyz/api-reference/markets/list-markets.md) is a method with typed requests and
responses.

The package is ESM only and needs Node.js 22 or later. It has no dependencies and uses the
platform `fetch` and `WebSocket`.

## Install

```bash npm theme={"dark"}
npm install @leanxyz/api-sdk
```

```bash bun theme={"dark"}
bun add @leanxyz/api-sdk
```

```bash pnpm theme={"dark"}
pnpm add @leanxyz/api-sdk
```

## Create a client

The examples use the same two environment variables as the [quickstart](https://docs.lean.xyz/quickstart.md):

```bash theme={"dark"}
export LEAN_API_URL="https://api.lean.xyz"
export LEAN_API_KEY="lean_sk_test_..."
```

```ts theme={"dark"}
import { createLeanClient } from '@leanxyz/api-sdk';

const lean = createLeanClient({
  apiKey: process.env.LEAN_API_KEY,
  baseUrl: process.env.LEAN_API_URL,
});
```

`baseUrl` defaults to `https://api.lean.xyz`. Keep the key in the environment and never log it.
[Authentication](https://docs.lean.xyz/authentication.md#create-a-key) shows how to create a key.

Each method returns the whole response: the result is in `data` and the request ID in
`meta.requestId`.

## Find a market

```ts theme={"dark"}
const { data } = await lean.listMarkets({ league: 'nfl', status: 'open', limit: 20 });
const market = data.markets.find((item) => item.legs.some((leg) => leg.tradable));
if (!market) throw new Error('No tradable market');

console.log(market.id, market.fixture.title, market.group.label, market.outcome);
```

Pick a market whose `legs` include one with `tradable: true`. [Markets and IDs](https://docs.lean.xyz/markets.md) explains
each field. `lean.getMarket(id)` reads one market.

## Quote and preview

Check what an order would do before you place it. Neither call places or reserves anything.

```ts theme={"dark"}
import type { CreateOrderRequest } from '@leanxyz/api-sdk';

const quote = await lean.quoteMarket(market.id, { action: 'buy', notional: '25' });
console.log(quote.data.executable_quantity, quote.data.expected_total_usd, quote.data.expires_at);

const order: CreateOrderRequest = {
  client_order_id: `bot-${crypto.randomUUID()}`,
  market_id: market.id,
  action: 'buy',
  notional: '25',
  time_in_force: 'ioc',
};

const preview = await lean.previewOrder(order);
console.log(preview.data.would_submit, preview.data.warnings);
```

Quote again after `expires_at`. A blocking warning means the order would be refused. See
[Preview](https://docs.lean.xyz/preview.md).

## Place an order

This buys 25 USD of the outcome at once and cancels whatever can't fill:

```ts theme={"dark"}
if (!preview.data.would_submit) throw new Error('The preview says this order would be refused');

const placed = await lean.createOrder(order);
console.log(placed.data.id, placed.data.status, placed.data.filled_quantity, placed.data.livemode);
```

`notional` is the dollars to spend, in place of `quantity`. Polymarket takes `ioc` buys by dollar
amount only, so size an immediate buy with `notional` when it should fill there. To buy a number of
shares instead, send `quantity` and `limit_price`. See
[Buying a dollar amount](https://docs.lean.xyz/orders.md#buying-a-dollar-amount).

Save `client_order_id` before you send the order, and reuse it on every retry of the same order.
Sending it again returns the original order, never a second one.

> [!WARNING]
>
> An accepted response is not a fill. Read `status` and `filled_quantity`, and confirm them by
> reading the order back.

## Read an order

```ts theme={"dark"}
const { data: read } = await lean.getOrder(placed.data.id);
console.log(read.status, read.filled_quantity, read.avg_fill_price);
```

If the response to `createOrder` never arrived, look the order up by its `client_order_id`:

```ts theme={"dark"}
const { data: found } = await lean.listOrders({ client_order_id: order.client_order_id });
console.log(found.orders.map((item) => [item.id, item.status]));
```

Then reconcile with `lean.getPositions()` and `lean.getBalances()`. See
[Orders and idempotency](https://docs.lean.xyz/orders.md#reconcile).

## Errors, timeouts and retries

A response that isn't a success throws `LeanApiError`. It has the HTTP `status`, the error `code`,
the `requestId` to quote when you report a problem, and the whole error response in `body`:

```ts theme={"dark"}
import { LeanApiError } from '@leanxyz/api-sdk';

try {
  await lean.createOrder(order);
} catch (error) {
  if (error instanceof LeanApiError) {
    console.error(error.status, error.code, error.requestId, error.body?.error.details);
  }
  throw error;
}
```

[Errors](https://docs.lean.xyz/errors.md) lists every code.

Each request times out after 30 seconds. Set `timeoutMs` on the client to change it, or pass
`{ signal }` as the last argument of any method to cancel a request yourself. A request that times
out or is canceled rejects with the error `fetch` raises, not a `LeanApiError`.

The client never retries a request. After a timeout on `createOrder`, look the order up with
`listOrders({ client_order_id })` before you send it again, and resend only with the same
`client_order_id` and body.

## Test mode

The key decides the mode, as it does for every call. With a `lean_sk_test_` key, orders and fills
are simulated and no money moves. Switch to a live key by changing `LEAN_API_KEY`; the code stays the
same.

Every successful response has `data.livemode`, which is `false` for a test key. Check it where
your program would act on money:

```ts theme={"dark"}
const { data: balances } = await lean.getBalances();
if (balances.livemode) throw new Error('This program expects a test key');
```

To start over with a test key, `lean.resetTestMode()` clears the simulated orders, positions,
withdrawals, transfers, stop losses and limit chases and returns test balances to the starting
amount. See [Test mode and live mode](https://docs.lean.xyz/test-mode.md).

## Stream updates

`@leanxyz/api-sdk/stream` keeps a WebSocket open. It reconnects with a new ticket after a drop and
reads the orders again over REST after each reconnect:

```ts theme={"dark"}
import { createLeanStream } from '@leanxyz/api-sdk/stream';

const stream = createLeanStream({ client: lean, baseUrl: process.env.LEAN_API_URL });
stream.on('order', (update) => console.log(update.id, update.status));
stream.subscribe([{ channel: 'orders' }, { channel: 'positions' }]);
```

Call `stream.close()` when you are done. See [Streaming](https://docs.lean.xyz/streaming.md) for each channel.

## Types

Every request and response type is exported by name, such as `CreateOrderRequest`,
`PreviewOrderResponse` and `GetOrderResponse`:

```ts theme={"dark"}
import type { GetOrderResponse, ListMarketsResponse } from '@leanxyz/api-sdk';

type Market = ListMarketsResponse['data']['markets'][number];
type Order = GetOrderResponse['data'];
```

## Methods

Method names follow the [API reference](https://docs.lean.xyz/api-reference/markets/list-markets.md). The ones used most:

| Method | Endpoint |
| - | - |
| `listMarkets`, `getMarket` | `GET /v1/markets`, `GET /v1/markets/{id}` |
| `quoteMarket` | `GET /v1/markets/{id}/quote` |
| `previewOrder` | `POST /v1/orders/preview` |
| `createOrder` | `POST /v1/orders` |
| `getOrder`, `listOrders` | `GET /v1/orders/{id}`, `GET /v1/orders` |
| `cancelOrder` | `POST /v1/orders/{id}/cancel` |
| `listFills` | `GET /v1/fills` |
| `getPositions`, `getBalances` | `GET /v1/positions`, `GET /v1/balances` |
| `resetTestMode` | `POST /v1/test/reset` |

Releases of the package are listed in the [changelog](https://docs.lean.xyz/changelog.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.