> ## 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`. |
| `action` | `buy` or `sell`. |
| `quantity` | Shares, as a decimal string. 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`. 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. 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 and Hyperliquid. 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. `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. 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`.
* Polymarket US reads its book from a live copy that starts on the first read of a market. Until
  it is ready, a quote, preview or order that needs that book is refused with
  `503 UPSTREAM_ERROR`. 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`.
* 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 the venue expires it and it reads
`expired`. `expires_at` must be at least three minutes and at most thirty days away.

Hyperliquid has no fill or kill and no order expiry, so:

* a `fok` order is placed whole on one venue: Polymarket, else Kalshi, else Polymarket US. Fill or
  kill holds only within one venue's book.
* a `gtd` order is placed on Kalshi, Polymarket and Polymarket US.
* on a market with none of those listings, or with `venues` that leave them all out, the order is
  refused with `400 VALIDATION_ERROR`.
* Polymarket takes a `fok` buy by `notional` only, so a `fok` buy sized with `quantity` goes to
  Kalshi or Polymarket US. With neither listed, 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.

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.

## 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` |
| 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 one exception:

* `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.

### 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).
* `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.
* Canceling a finished order, or one the venue never confirmed, 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 name that matches no order of this key 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.
* Batch cancels draw on the same rate limit as other cancels and work while trading is paused.

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

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.

No venue order is changed in place. Lean 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. 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. All three are `null` when no listed market currently
   matches the holding, for example a fixture that started more than 7 days ago. They can also be
   `null` for a moment after an API restart or a failed market list load, until the market list
   loads. 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"
```

## 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. A range longer than 365
days, or with more than 1000 points at the chosen interval, returns `400 VALIDATION_ERROR`.

A test key replays its simulated fills for realized, 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.

> [!WARNING]
>
> Use `ioc` for orders near kickoff. Place `gtc` orders well before kickoff and cancel them
> yourself before the game starts.

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