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

# Orders and idempotency

> Place, retry, cancel and reconcile orders safely.

One call places an order. Lean picks the venues and, when the account's cash is on the other
venue, moves it there for you. This example uses a test key, so nothing real moves:

```bash theme={"dark"}
curl -sS -X POST "$LEAN_API_URL/v1/orders" \
  -H "Authorization: Bearer $LEAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "client_order_id": "bot-2026-10-29-0001",
    "market_id": "'"$MARKET_ID"'",
    "action": "buy",
    "quantity": "5",
    "limit_price": "0.42",
    "time_in_force": "ioc"
  }'
```

| Field | Meaning |
| - | - |
| `client_order_id` | Required. Your ID for this order: letters, digits, `_` and `-`, up to 64 characters. Unique per key. |
| `market_id` | A `mkt_…` ID from `GET /v1/markets`, or a venue symbol for the market. |
| `action` | `buy` or `sell`. |
| `quantity` | Shares, as a decimal string in steps of 0.01. Hyperliquid takes whole shares only. A sell of your whole position is rounded down to the step rather than refused. See [Quantity steps](#quantity-steps). Send exactly one of `quantity` or `notional`. |
| `notional` | Dollars to spend, in place of `quantity`, with at most two decimals. Only for an `ioc` or `fok` buy. See [Buying a dollar amount](#buying-a-dollar-amount). |
| `type` | `limit` or `market`. The default is `limit`. See [Market orders](#market-orders). |
| `limit_price` | The worst price per share you accept. Required with `quantity` on a `limit` order. With `notional` or on a `market` order it is optional: a buy defaults to `0.99` and a sell to `0.01`. A `market` order is placed 1 cent past the worst price its quantity reaches. |
| `time_in_force` | `gtc` rests until filled or canceled. `ioc` fills what it can at once and cancels the rest. `fok` fills in full at once or not at all. `gtd` rests until `expires_at`. The default is `gtc`. A crypto market takes `gtd` or `ioc` only, so send one of them there. See [Lighter](https://docs.lean.xyz/venues.md#lighter). Polymarket takes `ioc` and `fok` buys by dollar amount only, so send `notional` for an immediate buy that should fill there. |
| `expires_at` | Required with `gtd` and refused without it. When the order expires, as an ISO 8601 time, or `game_start` to expire it when the market's game starts. A crypto market takes an ISO 8601 time only. See [Fill or kill and expiring orders](#fill-or-kill-and-expiring-orders). |
| `venues` | Optional. Only these venues may fill or pay for the order, such as `["polymarket"]`. Leave it out to use every venue the account allows. See [Choosing venues](#choosing-venues). |
| `best_price` | Optional, `false` by default. With `true`, a buy pays from the other venue whenever that costs less in all than buying where the account's cash is. See [Best price across venues](#best-price-across-venues). |
| `max_slippage_bps` | Optional. How far each venue order may trade from that venue's best price, in basis points, from `0` to `10000`. Leave it out to use the account's `max_slippage_bps`, if it sets one. See [Slippage](#slippage). |
| `all_or_none` | Optional, `false` by default. With `true`, the order is placed only if the books can fill the whole quantity. Only with `time_in_force` `ioc` or `fok`. See [All or none](#all-or-none). |
| `post_only` | Optional, `false` by default. With `true`, the order only rests on the book and never takes. See [Post only orders](#post-only-orders). |

Send the body as JSON with `Content-Type: application/json`, here and for `POST /v1/orders/preview`. A body
sent without that header is refused with `400 VALIDATION_ERROR`.

The response is the order, plus `route`. Here the account had no cash on Polymarket, so Lean paid
with its cash on Hyperliquid and bought on Polymarket:

```json theme={"dark"}
{
  "success": true,
  "data": {
    "id": "3f6c2a8e-91d4-4b7a-8c25-0e4d7b19a6f3",
    "client_order_id": "bot-2026-10-29-0001",
    "market_id": "mkt_...",
    "title": "Denver Broncos at Los Angeles Chargers: Moneyline, Denver Broncos",
    "outcome": "DEN",
    "venue": "polymarket",
    "ticker": "<venue ticker>",
    "side": "yes",
    "action": "buy",
    "time_in_force": "ioc",
    "quantity": "5",
    "filled_quantity": "5",
    "remaining_quantity": "0",
    "limit_price": "0.42",
    "avg_fill_price": "0.42",
    "notional_usd": "2.11",
    "filled_notional_usd": "2.1",
    "status": "filled",
    "status_reason": null,
    "legs": [
      {
        "venue": "polymarket",
        "ticker": "<venue ticker>",
        "side": "yes",
        "quantity": "5",
        "filled_quantity": "5",
        "limit_price": "0.42",
        "avg_fill_price": "0.42",
        "status": "filled",
        "venue_order_id": null,
        "cancel_requested_at": null,
        "status_reason": null
      }
    ],
    "route": {
      "funding_venue": "hyperliquid",
      "execution_venue": "polymarket",
      "notional_usd": "2.11",
      "costs": {
        "rebalance_fee_usd": "0.01",
        "gas_usd": "0",
        "activation_fee_usd": "0",
        "network_cost_usd": "0.01"
      }
    },
    "created_at": "2026-11-02T18:00:02.114Z",
    "updated_at": "2026-11-02T18:00:02.587Z",
    "livemode": false
  },
  "meta": { "requestId": "<request id>" }
}
```

Some fields are left out here. Read the order back by its `id`:

```bash theme={"dark"}
curl -sS "$LEAN_API_URL/v1/orders/$ORDER_ID" -H "Authorization: Bearer $LEAN_API_KEY"
```

`route` is on the placement response only, including a replay of the same `client_order_id`. It is
`null` when Lean paid for the order on the venue it bought on. See
[Paying from the other venue](#paying-from-the-other-venue).

Lean routes each order across the venues it may use:

* A buy is split across eligible venues by best price.
* A sell takes the best bids across the venues that hold the shares, up to what each venue holds.
* Live orders route to Kalshi, Polymarket, Polymarket US, Hyperliquid and Lighter. An order on a
  market with a time window, such as a short crypto price market, goes whole to Lighter and is never
  split. Test orders are simulated and never reach a venue.

`title` and `outcome` name the order's market as `GET /v1/markets` does. They are `null` for a
market whose fixture started more than 7 days ago, and for a moment after an API restart.

`legs` has one entry per venue order, with its `venue`, `ticker`, `side`, `quantity`,
`filled_quantity`, `avg_fill_price`, `status` and `status_reason`. When the order went to one venue,
the order's own `venue`, `ticker` and `side` name it. When it was split, they are `null`; read `legs`
instead. `status`, `filled_quantity` and `avg_fill_price` on the order always cover every leg:
`avg_fill_price` is the price weighted by size across the legs that filled, before fees, and `null`
until every filled leg has a price. Kalshi, Polymarket and Hyperliquid report a leg's price with
its fill. Polymarket US and Lighter report none, so Lean prices those legs from their fills once it
has recorded every one of them. `remaining_quantity` is the shares still working on the venues,
the unfilled size of each live leg, and `0` once the order is final.

`notional_usd` is the order at its own limit, the amount checked against your key's limits. A
sell counts at the limits of its `legs`, the least it sells for, and toward the rolling day, but
only takes risk off, so no notional limit refuses it: a close works however much the day has traded.
`filled_notional_usd` is what the filled shares traded for across every leg, `0` before any fill,
and `null` until every filled leg has a price, as with `avg_fill_price`. A sell at `0.01`, as a close without a `limit_price`
places, sells into the bids, down to the slippage bound below the best bid when one is set. Its `limit_price` shows the lowest
limit among its `legs`, the price the venue orders are protected by, rather than `0.01`.

[Preview](https://docs.lean.xyz/preview.md) shows the split before you place the order, in `execution.legs`.

## Kalshi and Polymarket US

Kalshi and Polymarket US accounts belong to the user, not to one trading account. Every trading
account and key of the user shares the same cash and shares there, so `GET /v1/balances` and
`GET /v1/positions` show the same Kalshi and Polymarket US figures under each of them.

* A live order on either venue goes out under the user's own API key for that venue, connected in
  the Lean app. Without one, an order that needs that venue is refused with `403 FORBIDDEN`.
  `venues` in [Get account config](https://docs.lean.xyz/api-reference/account/retrieve-account-config.md) reads each
  venue `ready` when an order can be placed there, `not_configured` until its key is connected, or
  `unavailable` when the connected key can't trade right now. Keys are connected in the Lean app
  only.
* Polymarket US reads its book from a live copy that starts on the first read of a market, and
  that read waits up to a second for it. If it is still not ready, a quote, preview or order that
  needs that book is refused with `503 UPSTREAM_ERROR`, and a book or price read lists
  `polymarket_us` in `unavailable`. It is safe to retry after a moment.
* Cash can't move to or from these venues through Lean. A buy there is paid with the cash already
  on that venue.

## Post only orders

Set `post_only: true` to make sure an order adds liquidity and never trades against a resting
order when it arrives. A post only order:

* needs `time_in_force` `gtc` and cannot use `best_price`. Any other combination is refused with
  `400 VALIDATION_ERROR`. On a crypto market it needs `gtd` instead, and rests on Lighter.
* is placed on Kalshi, Polymarket US and Hyperliquid, since Polymarket cannot rest a post only
  order. On a market with none of those listings, or with `venues` that leave all three out, it is
  refused with `400 VALIDATION_ERROR`.
* is refused with `422 VALIDATION_ERROR` and `details.reason: "POST_ONLY_WOULD_CROSS"` when the
  books, as Lean last read them, would fill any of it at once. The `client_order_id` is not used up,
  so you can send it again at a price further from the other side of the book.

The books can move between Lean's read and the order reaching the venue. If the order would trade
by then, the venue refuses it instead of filling it, and the order ends `rejected` with no fills.
[Preview](https://docs.lean.xyz/preview.md) shows the same refusal as a `POST_ONLY_WOULD_CROSS` warning.

## Market orders

Set `type: "market"` to trade at once at the best prices the books offer. A market order:

* needs `time_in_force` `ioc` or `fok`. With `gtc` or `gtd` it is refused with
  `400 VALIDATION_ERROR`.
* places each venue order 1 cent past the worst price its quantity reaches in that venue's book,
  above it for a buy and below it for a sell, as the Lean trading terminal does.
* takes `limit_price` and `max_slippage_bps` as optional extra caps. Without `limit_price` a buy is
  capped at `0.99` and a sell at `0.01`.
* fills a buy on Polymarket only when the buy is sized with `notional`, like any immediate buy
  there. A sell is sized with `quantity`.

The order and its preview show `type`, so you can read back what was placed.

## Fill or kill and expiring orders

`time_in_force` `fok` fills the whole order at once or cancels all of it. Nothing fills in part. A
`fok` order that cannot fill in full ends `canceled` with `filled_quantity` `0`.

`time_in_force` `gtd` rests like `gtc` until `expires_at`, then what is left expires and the order
reads `expired`. Any shares that filled before then stay filled. Kalshi, Polymarket, Polymarket
US and Lighter expire the order on the venue. Hyperliquid has no order expiry, so Lean places the
order there as `gtc` and cancels what is left at `expires_at`, usually within a few seconds.
`expires_at` must be at least three minutes and at most thirty days away. On a crypto market it
must be at least 6 minutes away and at or before the window end, and the order rests on Lighter.
See [Lighter](https://docs.lean.xyz/venues.md#lighter).

To expire an order when its game starts, send `expires_at` `game_start` in place of a time. Lean
sets the expiry to the market's `fixture.starts_at`, and the order and its preview show that time.
Once the game has started, or when it starts less than three minutes or more than thirty days
away, `game_start` is refused with `400 VALIDATION_ERROR`.

Hyperliquid has no fill or kill, and Polymarket US can fill part of a fill or kill order and expire
the rest. So:

* a `fok` order is placed whole on one venue: Polymarket, else Kalshi. Fill or kill holds only
  within one venue's book.
* on a market with neither listing, or with `venues` that leave both out, a `fok` order is refused
  with `400 VALIDATION_ERROR`. On a market listed only on Polymarket US, send `ioc` instead.
* Polymarket takes a `fok` buy by `notional` only, so a `fok` buy sized with `quantity` goes to
  Kalshi. Without a Kalshi listing, it is refused with `400 VALIDATION_ERROR`.
* `expires_at` without `gtd`, `gtd` without `expires_at`, or an expiry outside the window is refused
  with `400 VALIDATION_ERROR`.

The order and its preview show `expires_at`, and `null` for any order without one.

## Choosing venues

By default an order may use every venue the trading account allows. To keep it on some of them,
list them in `venues`:

* With one venue, the order is placed only there. If that venue can't fill or pay for it, the order
  is refused; Lean does not send it elsewhere.
* `venues` can only narrow the account's venues. Naming a venue the account doesn't allow refuses
  the order with `422 VALIDATION_ERROR` and `details.reason: "VENUE_NOT_ALLOWED"`, even beside one
  it allows. `details.allowed_venues` lists the venues the account allows.
* Paying from the other venue also stays inside `venues`. With `["polymarket"]`, Lean never uses
  cash on Hyperliquid for the order.
* List each venue once. An empty list is refused with `400 VALIDATION_ERROR`.
* A retry with the same `client_order_id` must name the same venues, in any order. Other venues
  make it a different body, which returns `409 CONFLICT`.

## Paying from the other venue

Each venue keeps its own cash. When a buy can't be paid for on the venues with a book for it, but
the account holds cash on the other venue, Lean moves that cash and buys on the venue with the
book, in the same call. This works between Polymarket and Hyperliquid only; a buy on Kalshi or
Polymarket US is paid with the cash already there. The response names both venues in `route`:

| Field | Meaning |
| - | - |
| `route.funding_venue` | The venue whose cash paid for the order. |
| `route.execution_venue` | The venue the order was bought on. |
| `route.notional_usd` | The most the route's payment can cost: the buy at its limit, its fees and `route.costs`. It is the order's `notional_usd`, and the amount checked against your key's limits. |
| `route.costs.rebalance_fee_usd` | The 20 bps fee on the cash Lean moves between venues. |
| `route.costs.gas_usd` | The network gas the route pays. |
| `route.costs.activation_fee_usd` | The \$1 Hyperliquid charges the first time funds reach an account it has not activated, when the route pays into one. Otherwise `0`. |
| `route.costs.network_cost_usd` | The sum of the three costs above. |

Lean pays from the other venue only when all of these hold:

* The key has the `route` scope as well as `trade`. A **Read and trade** key made in the Lean app
  has both, in test and live mode. A key made before one-call routing shipped (see the
  [changelog](https://docs.lean.xyz/changelog.md)) doesn't: create a new one, or create one with `route` through
  [Create an API key](https://docs.lean.xyz/api-reference/api-keys/create-api-key.md). See
  [Authentication](https://docs.lean.xyz/authentication.md#create-a-key).
* With a live key, the account has trading enabled in the Lean app. A test key doesn't need this.
* Routing is available for the order.
* `venues`, if set, names both Polymarket and Hyperliquid.
* The market is listed on both venues: the one whose cash pays as well as the one Lean buys on.
  The `legs` of `GET /v1/markets/{id}` name the venues that list it.

If any of them is missing, the order is refused as before: `422 VALIDATION_ERROR` with
`details.reason: "INSUFFICIENT_FUNDS"`.

* A live routed order can read `pending` while Lean moves the cash. Read it back with
  `GET /v1/orders/{id}` until it is final.
* With a test key, the same call routes between the simulated balances. No real funds move. See
  [Test mode](https://docs.lean.xyz/test-mode.md#how-test-orders-behave).
* Only buys move cash. A sell is placed on the venues that hold the shares. Shares can't move
  between venues.

To sign each payment yourself instead, see
[Advanced: self-signed routed orders](https://docs.lean.xyz/routed-orders.md).

## Best price across venues

By default Lean pays from the other venue only when the account can't pay for a buy where its cash
is. Set `best_price: true` to also do it when it is cheaper. Lean compares what the buy would cost
where the account's cash is with what it would cost through a route that moves cash from the other
venue, fees included, and takes the cheaper one:

```json theme={"dark"}
{
  "client_order_id": "bot-2026-10-29-0002",
  "market_id": "mkt_...",
  "action": "buy",
  "quantity": "5",
  "limit_price": "0.42",
  "time_in_force": "ioc",
  "best_price": true
}
```

* When the route costs less in all, the buy goes through it and `route` names both venues.
* Otherwise the buy is placed directly and `route` is `null`. That includes a route Lean can't
  price at the moment.
* The route needs everything [paying from the other venue](#paying-from-the-other-venue) needs,
  including the key's `route` scope. When any of it is missing, the buy is placed directly.
* It changes nothing when `venues` names a single venue.
* A test key prices a route at the order's `limit_price`, so in test mode the route wins only
  when the direct buy's fees cost more.
* Sells are unchanged. A sell already takes the best bids across every venue that holds the
  shares.
* `best_price` is part of the body a retry must repeat. The same `client_order_id` with a
  different `best_price` returns `409 CONFLICT`.

[Preview](https://docs.lean.xyz/preview.md) the same body to see the choice first: `route` is set when the buy would go
through a route.

## Slippage

`max_slippage_bps` is an optional extra cap on how far each venue order may trade from the best
price on its own venue's book: above that venue's best ask for a buy, below its best bid for a sell.
`100` is 1%. Without one, a limit order trades to its `limit_price` and a `market` order to 1 cent
past the worst price its quantity reaches, as the Lean trading terminal places them.

* Each venue order is placed at `limit_price`, tightened to the bound and moved onto the venue's
  [price tick](#price-ticks): down for a buy, up for a sell. With the best ask at `0.50` and
  `max_slippage_bps: 100`, a buy pays at most `0.505` on that venue, which is `0.50` on a `0.01`
  tick.
* The bound never loosens `limit_price`.
* Each venue is measured against its own book, not the best price across venues, so venues quoting
  different prices can each fill.
* Leave it out to use the account's `max_slippage_bps` in `GET /v1/account/config`, or no cap
  when that is `null`. `0` is a bound too: each venue order trades only at its venue's best price.
* [Preview](https://docs.lean.xyz/preview.md) shows the bound the order would use in `execution.max_slippage_bps`, `null` for none.
* A retry must send the same `max_slippage_bps`, or leave it out again. A different value, or a
  value where the first body had none, returns `409 CONFLICT`.

## All or none

With `all_or_none: true` and `time_in_force` `ioc` or `fok`, Lean places the order only if the
books, as it reads them, fill the whole quantity within `limit_price` and the slippage bound. If they
don't, the order is refused with `422 VALIDATION_ERROR` and `details.reason: "INSUFFICIENT_DEPTH"`,
and nothing is placed.

* It is best effort. Each venue order is placed on its own, and a book can change between the read
  and the fill, so a partial fill is still possible.
* `all_or_none` needs `time_in_force` `ioc` or `fok`. With `gtc` or `gtd` the order is refused with
  `400 VALIDATION_ERROR`.
* [Preview](https://docs.lean.xyz/preview.md) warns with `INSUFFICIENT_DEPTH` when the books can't fill it in full.
* `all_or_none` is part of the body a retry must repeat.

## Price ticks

Each venue takes prices only on its own grid, its tick:

| Venue | Tick | Prices |
| - | - | - |
| Kalshi | Set by Kalshi for each market, such as `0.01`. | From one tick to 1 minus one tick. |
| Polymarket | Set by Polymarket for each market, such as `0.01` or `0.001`. | From one tick to 1 minus one tick. |
| Polymarket US | Set by Polymarket US for each market, such as `0.01`. | From one tick to 1 minus one tick. |
| Hyperliquid | `0.00001` | From `0.00001` to `0.99999`. |

`limit_price` must be above `0` and below `1`, and on the tick of every venue that could place the
order. Lean never rounds it. A `limit_price` off a venue's tick, such as `0.425` for a market
Polymarket trades on a `0.01` tick, is refused with `400 VALIDATION_ERROR`: "limit\_price is finer
than the price tick of a venue that could place it". To trade at a finer price on one venue, name
only that venue in `venues`. [Preview](https://docs.lean.xyz/preview.md) refuses the same body the same way.

## Quantity steps

`quantity` moves in steps of `0.01`, and Hyperliquid takes whole shares only. A quantity that no
venue which could place the order can take is refused with `400 VALIDATION_ERROR`: "No venue can
accept this quantity". A buy of `5.155` is refused this way, and so is a buy of `30.5` that only
Hyperliquid could place.

A sell of your whole position is the one exception. When `quantity` is more than the venues can sell
on their steps, but no more than you hold, or your holding rounded to `0.01`, Lean sells the holding rounded down to the step
instead of refusing the order. On Hyperliquid that is whole shares. The order's `quantity` then
reads the shares it sells, not the quantity you sent, and the part below the step stays on the
venue. For example, with `5.155173` shares held on Polymarket, a sell of `5.1551` is placed for
`5.15`, the order reads `"quantity": "5.15"`, and `0.005173` shares stay held. That remainder is
smaller than one step, so no order can sell it.

## Idempotency

`client_order_id` makes placement safe to retry:

* The same ID with the same body returns the original order. Nothing new is placed.
* The same ID with a different body returns `409 CONFLICT`.
* An ID is used once, even if that order was rejected.
* [Close positions](https://docs.lean.xyz/api-reference/account/close-positions.md) takes a `client_order_id` of up to 40
  characters. Each sell it places gets `<close id>-close-<hash>-<hash>`, which only the close
  response returns.

**1. Choose and save the ID first**

Write `client_order_id` to your own storage before you send the request.

**2. On a timeout or network error, look it up**

```bash theme={"dark"}
curl -sS "$LEAN_API_URL/v1/orders?client_order_id=bot-2026-10-29-0001" \
  -H "Authorization: Bearer $LEAN_API_KEY"
```

The lookup covers orders from every key on the trading account, so it still finds the order
after you rotate keys. An empty `orders` list means Lean never recorded the order. Anything
else is the order; if two of your keys reused the ID, each one's order is listed.

**3. Retry only with the same ID**

Resending the same body with the same ID returns the stored order. Never resend the order
with a new ID until you know the first one was not placed.

### What placement returns

Once Lean has recorded the order, `POST /v1/orders` always answers `200` with the order after
every venue answered. What the venues did is in `status` and in each leg, not in an error:

| Outcome | Order `status` | `status_reason.code` |
| - | - | - |
| Filled, or resting on the book | `filled`, `partially_filled` or `open` | `null` |
| An `ioc` order that filled part, or nothing | `canceled`, with `filled_quantity` what filled, `0` if nothing matched | `IOC_REMAINDER_CANCELED` |
| A `fok` order that could not fill in full | `canceled`, with `filled_quantity` `0` | `null` |
| The venue refused the order | `rejected` | `VENUE_REJECTED` or the venue's own code |
| The venue did not confirm the order | `unconfirmed` | `SUBMISSION_UNKNOWN` |

An error status means Lean placed nothing, with these exceptions:

* `422 VALIDATION_ERROR`: a key limit or a check before any venue refused the order.
* `503 UPSTREAM_ERROR`: a venue failed before anything was placed. When the response carries
  `Retry-After`, a venue timed out or dropped the connection, so the order may or may not have
  reached it. Look it up by `client_order_id` before you send it again.
* Any error with `details.order_id`: Lean recorded the order before the failure, for example a
  buy that pays from the other venue whose payment was refused. Read it back with
  `GET /v1/orders/{id}` before you send it again.

### When the venue does not confirm

An `unconfirmed` order or leg reads: "The venue did not confirm this order. Read it back by
client\_order\_id; do not resend it." It may or may not be on the venue. Read it with
`GET /v1/orders?client_order_id=...` or `GET /v1/orders/{id}`:

* If the venue has it working, it reads `open` (or filled) and `status_reason` clears.
* If the venue still has no record of it ten minutes after placement, it reads `rejected` with
  `status_reason.code` `VENUE_UNKNOWN`. Only then is it safe to place it again, with a new
  `client_order_id`.

## Track and cancel

```bash theme={"dark"}
curl -sS "$LEAN_API_URL/v1/orders/$ORDER_ID" -H "Authorization: Bearer $LEAN_API_KEY"
curl -sS "$LEAN_API_URL/v1/orders?limit=50" -H "Authorization: Bearer $LEAN_API_KEY"
curl -sS -X POST "$LEAN_API_URL/v1/orders/$ORDER_ID/cancel" -H "Authorization: Bearer $LEAN_API_KEY"
```

* `GET /v1/orders/{id}` refreshes the order from its venue. A test order is never sent to a venue;
  reading it fills what rests against the public books. See [Test mode](https://docs.lean.xyz/test-mode.md#how-test-orders-behave).
* If a venue cannot be read or reached, `GET /v1/orders/{id}` returns `503 UPSTREAM_ERROR` and the
  stored order is unchanged. A cancel returns the same error when a venue cannot be reached: that
  venue's leg is not canceled, though legs on other venues may be. Read the order again before you
  assume a cancel happened.
* `GET /v1/orders` lists stored orders, newest first, with `next_cursor` for paging. Narrow it with
  `status`, `venue`, `market_id` or `client_order_id`, or with `search` for text in the title or
  outcome of the order's market. See [Find by text](#find-by-text).
* `status` takes one status, so `status=open` leaves out orders that are `pending`,
  `partially_filled` or `cancel_requested`. To list every working order, ask once for each of
  those statuses, or list without `status` and keep the ones that have not finished.
* `created_after` and `created_before` narrow the list to orders Lean recorded at or after, and
  before, a time. Send UTC ISO 8601 times ending in `Z`, such as `2026-11-10T12:00:00Z`. A time
  with an offset such as `+00:00`, or a date alone, returns `400 VALIDATION_ERROR`.
* `client_order_id` matches the orders any key of the account placed with that ID, and combines
  with the other filters like any of them.
* The list also shows orders placed in the Lean app that are still open, for a live key. They have
  no `client_order_id`, an empty `legs` list, and their market fields can be `null`. You can see
  them but not read, cancel or amend them through the API: those calls return `404 NOT_FOUND` with
  `details.reason` `APP_ORDER_NOT_ADDRESSABLE`. Orders placed by stop losses, limit chases and
  conditional sells are not listed here.
* Canceling a finished order, one the venue never confirmed, or a routed order whose payment is
  already under way returns `409 CONFLICT`.
* A cancel stops every leg that is still working. Most stop at once. A leg that can't be stopped
  at once reads `cancel_requested`, with a `cancel_requested_at` time, until its venue confirms it,
  and the order reads `cancel_requested` too. Read the order back until it is `canceled`, or
  `filled` if a fill beat the cancel.

To cancel several orders in one call, name them by `order_ids`, `client_order_ids` or both, up to
50 in all:

```bash theme={"dark"}
curl -sS -X POST "$LEAN_API_URL/v1/orders/cancel-batch" \
  -H "Authorization: Bearer $LEAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"order_ids": ["'"$ORDER_ID"'"], "client_order_ids": ["bot-0002"]}'
```

* Each order is canceled the same way a single cancel would cancel it, and one failure never stops
  the rest. The call answers `200` with one row in `results` for each name you sent, in the order
  you sent them: `order_ids` first, then `client_order_ids`.
* A row's `status` is `canceled`, `finished` for an order that had already finished (its `order`
  shows how), or `failed` with an `error`. A `canceled` row means every leg's cancel was accepted.
  Its `order` can still read `cancel_requested` until each venue confirms, as with a single cancel.
  An order ID that matches no order of the account in this key's mode, or a client order ID that matches no order this key placed, fails with `NOT_FOUND`. A row that failed for another reason carries the order as it stands, so you can see
  which legs are still open.
* An order named twice, by its id and by its `client_order_id`, is canceled once, and both rows
  show that one result. The same id listed twice in `order_ids`, or in `client_order_ids`,
  returns `400 VALIDATION_ERROR` and cancels nothing.
* Batch cancels draw on the same rate limit as other cancels and work while trading is paused.

`POST /v1/orders/cancel-after` sets a safety timer. Unless you call it again in time, every open
order of the trading account in the key's mode is canceled once `timeout_seconds` runs out.
`timeout_seconds` is `0`, which disarms the timer, or from `5` to `86400`; any other value returns
`400 VALIDATION_ERROR`. Each call restarts the timer, and it fires once. See
[Set a cancel timer](https://docs.lean.xyz/api-reference/orders/set-cancel-after.md).

## Amend an order

Change the price, the size or both of a resting order with `PATCH /v1/orders/{id}`:

```bash theme={"dark"}
curl -sS -X PATCH "$LEAN_API_URL/v1/orders/$ORDER_ID" \
  -H "Authorization: Bearer $LEAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"limit_price": "0.41", "quantity": "30"}'
```

| Field | Meaning |
| - | - |
| `limit_price` | Optional. The new worst price per share, in dollars. Omit it to keep the current price. |
| `quantity` | Optional. The new total size in shares, counting what already filled. Omit it to keep the current size. |
| `client_order_id` | Optional. The `client_order_id` of the new order that replaces this one. Omit it and Lean picks one. An [amend in place](#amend-in-place) keeps the order's own. |

Send at least one of `limit_price` and `quantity`. Only an `open` or `partially_filled` order with
`time_in_force` `gtc` that rests on one venue can be amended. A routed order, an order split across
venues, or an `ioc`, `fok` or `gtd` order is refused with `409 CONFLICT` and
`details.reason: "ORDER_NOT_AMENDABLE"`.
A finished order is refused with `ORDER_NOT_OPEN`. The new size must be more than what already
filled. Amends are refused while trading is paused.

### Amend in place

A live order on Kalshi or Polymarket US whose size you only lower, at the same price, with the key
that placed it, is changed at the venue in place. The answer is `200` with the same order: its ID,
`client_order_id` and fills stay, and its `quantity` is the new size. On Kalshi it keeps its place
in the queue. The order keeps its own `client_order_id`, so leave it out of such an amend; one
this key already used is still refused with `409 CONFLICT`. If the venue order changed while Lean
planned the amend, the amend is refused with `409 CONFLICT`; read the order back and try again.

### Cancel and replace

Any other amend cancels the order and places a new `gtc` order on the same venue, with the same
`post_only`, for the rest of the new size at the new price: a new price, a larger size, an amend
from another key, a test order, or an order on Polymarket or Hyperliquid. The answer is `200` with
the new order, whose `replaces_order_id` names the old one. The old order reads `canceled`, with
`replaced_by_order_id` naming the new one. Each order keeps the fills of its own venue order.

The new order is placed as the key that sends the amend places one. Before the old order is
canceled, Lean checks the new order as though the old one were already gone: the new price and size
against the venue, a `post_only` price that would trade at once (`POST_ONLY_WOULD_CROSS`), the
key's limits, the account's allowed venues, the rolling day and the account's cash or shares, with
what the old order holds counted as free. Any refusal leaves the order as it was.

The replacement waits for the cancel:

* The old order can fill until its cancel lands, so Lean places the new order only once the cancel
  is confirmed with the old order's final fill, and sizes it from what had filled by then.
  Hyperliquid confirms the cancel within the request. A live cancel on another venue, such as
  Polymarket, can be confirmed a moment after it is requested, so the first amend can answer
  `409 CONFLICT` with `details.reason: "REPLACEMENT_PENDING"` and nothing placed. Send the same
  amend again once the old order reads `canceled`; that amend places the new order.
* If the old order filled to the new size or more, nothing is placed and the amend is refused
  with `ORDER_NOT_OPEN`.
* If something changes between that check and the new order, for example another order spends
  the cash, the new order can still be refused once the old one is canceled. The old order then
  stays canceled and nothing rests in its place.
* An order that was already replaced is refused with `ORDER_REPLACED`, and
  `details.replaced_by_order_id` names the order to amend instead.

After any error, read the order back before you send the amend again.

## Pause trading

If your program misbehaves, a key with `trade` can stop new orders at once:

```bash theme={"dark"}
curl -sS -X POST "$LEAN_API_URL/v1/account/pause" \
  -H "Authorization: Bearer $LEAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"scope": "api_key", "reason": "Strategy halted"}'
```

* `scope` is `api_key` to pause this key, or `trading_account` to pause every key of its trading
  account. `reason` is optional, up to 200 characters.
* The pause also stops queued orders that have not reached a venue yet. Reads, cancels and resting
  orders are unaffected, so cancel resting orders yourself if you want them gone.
* The response lists what now pauses this key in `paused.key`, `paused.account` and
  `paused.global`, each `null` or `{ reason, source, since }`.
* A key cannot resume trading. Resume from the Lean dashboard. A pause with `source` `operator`
  was set by Lean, and only Lean can lift it.

While paused, placing an order returns `503 FEATURE_DISABLED` with `details.reason`
`TRADING_PAUSED` and `details.scope` `api_key` or `trading_account`. A preview answers with
`would_submit: false` and a `TRADING_UNAVAILABLE` warning.

## Reconcile

An accepted response is not proof of a fill. To reconcile an order:

1. Read the order with `GET /v1/orders/{id}`. Check `status`, `filled_quantity` and
   `avg_fill_price`, then each entry in `legs`: its `status`, `filled_quantity`, `avg_fill_price` and
   `venue_order_id`.
2. Read `GET /v1/positions` and check the position for each leg's `venue`, `ticker` and `side`.
   Match on those three fields. Each position also names its `market_id`, `title` and `outcome`, so
   you can match it to the market you ordered. `market_id` is `null` when the API lists no market
   for the holding, such as a season futures market. Its `title` and `outcome` then come from the
   venue market, and are `null` only when Lean has no title for it. Closing still works because the
   close path resolves the market from the ticker.
3. Read `GET /v1/balances` and compare the change on each venue with that leg's
   `filled_quantity × avg_fill_price` plus the `fee_usd` of its fills in `GET /v1/fills`. For an
   order with a `route`, the funding venue's change also includes `route.costs.network_cost_usd`.

A venue that cannot be read right now is listed in `unavailable`. It is never reported as an empty
position or a zero balance. Do not reconcile against a venue listed in `unavailable`.

## Read positions

`GET /v1/positions` lists what you hold on each venue. Narrow the list with any of these query
parameters:

| Parameter | Effect |
| - | - |
| `venue` | Only holdings on this venue. Lean reads only that venue, so only it can be listed in `unavailable`. |
| `market_id` | Only holdings on this market. A market Lean does not know returns an empty list. |
| `search` | Only holdings on a market whose title or outcome contains this text. See [Find by text](#find-by-text). |

A `venue` the API does not support returns `400 VALIDATION_ERROR`.

```bash theme={"dark"}
curl -sS "$LEAN_API_URL/v1/positions?venue=polymarket&search=lakers" \
  -H "Authorization: Bearer $LEAN_API_KEY"
```

Each position has `payout_usd`, what the whole holding pays once its market resolves, and
`redeemable`. Kalshi, Polymarket US, Hyperliquid and Lighter pay resolved holdings into your
balance on their own. A Polymarket holding of a resolved market that pays out stays a token until it is
redeemed, and is marked `redeemable: true` until then. A losing holding pays nothing and is never
redeemable.

`settled` is `true` once the holding's market has resolved. That row's `unrealized_pnl_usd` is its
settlement payout minus cost, as the Lean portfolio row shows it, but the account's unrealized PnL
in `GET /v1/pnl` leaves it out, as the Lean portfolio totals do. Add up only rows with
`settled: false` to match it. [Close positions](https://docs.lean.xyz/api-reference/account/close-positions.md) leaves a
settled holding out, since it pays out rather than sells.

## Redeem and merge

[Redeem positions](https://docs.lean.xyz/api-reference/account/redeem-positions.md) pays out every holding marked
`redeemable`, or only those on one `market_id`. Shares on the winning side pay 1 each and a void
market pays 0.5 a share; shares on the losing side pay nothing and are left as they are. The
response lists each holding
redeemed with its `payout_usd`, and is empty when nothing was redeemable.

A market can be listed more than once on Polymarket. A Polymarket token id or condition id as
`market_id` redeems only that listing, and a Lean market id redeems every Polymarket listing of the
market. A condition id redeems both sides of its listing, even when its YES and NO belong to two
markets.

```bash theme={"dark"}
curl -sS -X POST "$LEAN_API_URL/v1/positions/redeem" \
  -H "Authorization: Bearer $LEAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"market_id": "'"$MARKET_ID"'"}'
```

[Merge positions](https://docs.lean.xyz/api-reference/account/merge-positions.md) turns every pair of one YES share and
one NO share you hold on a market back into cash, 1 per pair, without trading. Send the
`market_id` and the `venue`, `polymarket` or `hyperliquid`. Kalshi and Polymarket US have no
merge. Holding only one side is refused with `422 VALIDATION_ERROR` and `details.reason`
`NOTHING_TO_MERGE`.

A Polymarket token id or a Hyperliquid book coin as `market_id` merges that one listing. A Lean
market id works when the market has one listing on the venue; when it has more, the merge is refused
with `400` and you send the token id or book coin of the listing instead. A `market_id` naming a
listing on another venue is refused with `400` too.

Both need the trade scope, follow the key's trading pause and venue limits, and on a live key need
trading enabled for the account in the Lean app. A live redeem or merge is sent to the venue once
and reads:

| `status` | Meaning |
| - | - |
| `settled` | The venue paid out. |
| `submitted` | The payout is on its way and may still fail. Read positions and balances again shortly. |
| `failed` | The venue refused it and paid nothing. `failure_reason` says why. |

After a timeout or a `5xx`, read `GET /v1/positions` before you try again: a holding no longer
marked `redeemable`, or a pair no longer held, was already paid out or is on its way.

## Read fills

`GET /v1/fills` lists your fills, newest first. Each fill names its `order_id` and its
`market_id`, with the market's `title` and `outcome`. Either ID is `null` when Lean cannot tie the
fill to one, for example a fill from an order placed outside the API on a market the API does not
list; `title` and `outcome` are then `null` too. A test order's fill names its order's market, and
its `title` and `outcome` are `null` once the market's fixture started more than 7 days ago.

Narrow the list with any of these query parameters:

| Parameter | Effect |
| - | - |
| `order_id` | Only fills of this order. |
| `market_id` | Only fills on this market. A market Lean does not know returns an empty list. |
| `venue` | Only fills on this venue. |
| `filled_after` | Only fills at or after this time, as an ISO 8601 timestamp. |
| `filled_before` | Only fills before this time, as an ISO 8601 timestamp. |
| `search` | Only fills on a market whose title or outcome contains this text. See [Find by text](#find-by-text). |

Send times in UTC ending in `Z`, such as `2026-11-10T12:00:00Z`. A time with an offset such as
`+00:00`, a date alone, or anything else returns `400 VALIDATION_ERROR`. To read every fill in a
window, page with `next_cursor` and keep the same parameters.

## Find by text

`GET /v1/positions`, `GET /v1/orders` and `GET /v1/fills` take `search`. It keeps the records on a
market whose `title` or `outcome` contains the text, in any letter case. A record on a market the
API does not list never matches.

* Spaces at either end are ignored. The text must then be 1 to 100 characters, or the request
  returns `400 VALIDATION_ERROR`.
* `search` combines with the other parameters. Each record must match all of them.
* Orders and fills page as usual. Pass `next_cursor` back as `cursor` with the same `search` to
  read the next page.

## Profit and loss

`GET /v1/pnl` returns your realized, unrealized and total profit and loss in USD, for the whole
account and for each venue. Realized counts what closed and reduced positions made after fees.
Unrealized values your open positions at their current price. Pass `venue` or `market_id` to read
one venue or one market.

A venue that cannot be read right now is listed in `unavailable`, and its unrealized and total are
`null`. Its realized amount still counts. A market Lean does not know returns `404 NOT_FOUND`.

`GET /v1/pnl/history` returns the same amounts as points over time, each one cumulative as of its
`ts`. Choose the spacing with `interval`, `1h` or `1d` (the default), and the range with `start`
and `end` as ISO 8601 timestamps. Without them you get the last 30 days. An `end` after now is
read as now, and the response's `end` shows the time used, so no point is reported for a time still
to come. A range longer than 365 days, or with more than 1000 points at the chosen interval, returns
`400 VALIDATION_ERROR`, as does a `start` that is not before the `end` used.

A test key replays its simulated fills for realized, with what each holding on a resolved market
paid less what it cost, and values its simulated positions at the
midpoint of their venue's public book for unrealized. Unrealized and total are `null` while one of
those positions has no mark. Its history has realized only, because past marks of test positions
aren't kept. See [Test mode](https://docs.lean.xyz/test-mode.md#how-test-orders-behave).

## Risk

`GET /v1/risk` sums up your exposure from the same data as positions, balances and orders, for the
whole account and for each venue:

| Field | What it holds |
| - | - |
| `cost_basis_usd` | Quantity times average price over your positions. |
| `mark_value_usd` | Quantity times current price over your positions. |
| `cash_usd` | Your cash on the venue, or across venues in the total. |
| `open_orders` | How many orders are open, and what their unfilled part costs or pays at the limit price. |
| `largest_positions` | Up to 10 positions, largest cost basis first, with each one's `share` of the total. |
| `by_market` | Cost basis on each market, largest first. |
| `by_category` | Cost basis by market category and sport, largest first. |

Each `share` is a fraction of the cost basis you know the cost of, from 0 to 1, to four decimal
places. A routed order whose venue order is not placed yet counts in the total `open_orders` but in
no venue's.

A venue that cannot be read right now is listed in `unavailable`. Its values are `null`, and so is
every total they feed, rather than a sum that leaves it out. A test key's positions are marked as
live ones are (see [Test mode](https://docs.lean.xyz/test-mode.md)), and a position with no mark makes the mark values it
counts toward `null`.

## Kickoff

Hyperliquid outcome markets do not cancel resting orders when a game starts. A `gtc` order left on
the book can fill in play at a price that no longer reflects the game.

To take an order off the book at kickoff, send it as `gtd` with `expires_at` `game_start`. This
works on every venue, Hyperliquid included, where Lean cancels what is left when the game starts.
See [Fill or kill and expiring orders](#fill-or-kill-and-expiring-orders).

## Buying a dollar amount

An `ioc` or `fok` buy can name the dollars to spend instead of the shares to buy. Send `notional` in
place of `quantity`:

```bash theme={"dark"}
curl -sS -X POST "$LEAN_API_URL/v1/orders" \
  -H "Authorization: Bearer $LEAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "client_order_id": "bot-2026-11-10-0001",
    "market_id": "'"$MARKET_ID"'",
    "action": "buy",
    "notional": "25",
    "time_in_force": "ioc"
  }'
```

* Lean walks the venue books from the best ask until the dollars are spent, within your
  `limit_price` and slippage bound, if set. The order's `limit_price` is the worst price that walk reaches,
  and its `quantity` is the shares the dollars buy at that price, rounded down to what the venues
  take. Hyperliquid takes whole shares only.
* The order never spends more than `notional` before fees. A better price than the limit spends
  less, and on Polymarket it can buy a few more shares than `quantity` for the same dollars.
* Polymarket spends a buy in whole cents, rounded down. The shares that rounding leaves out are
  worth less than a cent, so a Polymarket leg that falls short of `quantity` by that little reads
  `filled`, and `filled_quantity` shows the shares it bought.
* `notional_usd`, and the amount checked against your key's limits, is the order's `quantity` at
  its `limit_price`. It is never more than `notional`.
* `limit_price` is optional with `notional`. Without it the walk stops at `0.99`, or at the slippage
  bound when one is set.
* A sell and a `gtc` or `gtd` order are sized with `quantity`. Sending `notional` on one, or sending both
  `quantity` and `notional`, or neither, is refused with `422 VALIDATION_ERROR`.
* A buy sized with `notional` is paid with the cash on the venues it buys on. It doesn't take a
  [route](#paying-from-the-other-venue).
* `POST /v1/orders/preview` and `GET /v1/markets/{id}/quote` take `notional` the same way.

## Limitations

* Shares stay on the venue that bought them. A sell is placed only on venues that hold the shares.
* `filled_quantity` comes from the venue's answer at placement and from later reads. A resting order
  that later fills completely reads `filled`.
* An `ioc` buy sized with `quantity` is not placed directly on Polymarket. It goes only to the
  other venues it can use. When Polymarket is the only one, the order and its preview are refused
  with `400 VALIDATION_ERROR`; send `notional` instead, or send it as `gtc`. A buy [paid from the
  other venue](#paying-from-the-other-venue) can still fill on Polymarket, and never for more than
  `quantity`.
* Reading a filled order with `GET /v1/orders/{id}` brings its fills into
  `GET /v1/fills?order_id=`, so read the order first when you need its fills right away. A
  Polymarket fill whose trade Polygon has not confirmed yet, or a fill of an order you have not
  read, can still be listed a few seconds after the order reads `filled`. If the list is empty,
  read it again shortly.
* An order has no fee field. Its fees are the `fee_usd` of its fills in `GET /v1/fills`.
* A live Hyperliquid buy fill shows `fee_usd` `0`, because a Hyperliquid buy pays its fee when the
  position closes or settles; a sell pays the market's taker rate. `fee_usd` is `null` when the fee
  was charged in a token Lean cannot value in dollars.
* If the venue still has no record of an unconfirmed order ten minutes after placement, the order
  is marked `rejected` with `status_reason.code` `VENUE_UNKNOWN`.
* An order in `needs_attention` has a leg Lean cannot settle on its own. It stays live until Lean's
  operators resolve it. Do not place it again; read it back later.


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