# Close positions Source: https://lean.mintlify.app/api-reference/account/close-positions api-reference/openapi.json POST /positions/close Sells each position of this key's trading account in this key's mode, optionally only on one venue or market, through the same checks and limits as POST /v1/orders. Each sell sells only what is held less what open sells already offer, on the venue that holds it, so a close never sells more than the account holds. Each placed sell is read back before the response, so one the venue matched at once reads filled with its filled quantity and average price. Cancel open orders first to close everything. A close answers 200 even when a sell fails: read outcome, which is failed or partial while positions are left unsold, and each failed leg's error. # Get profit and loss Source: https://lean.mintlify.app/api-reference/account/get-pnl api-reference/openapi.json GET /pnl Realized, unrealized and total profit and loss of this key’s trading account, overall and per venue. Filter by `venue` or `market_id`. A live key reads its account’s profit and loss ledger, or for one market its positions there. A test key replays its simulated fills for realized profit and loss, and totals unrealized profit and loss exactly as a live key does over its simulated positions, which are marked as the Lean portfolio marks live ones: Polymarket at the last trade, Hyperliquid at the venue’s mid. A position on a resolved market counts no unrealized profit and loss; unrealized and total are null while any other position has no mark. # Get profit and loss history Source: https://lean.mintlify.app/api-reference/account/get-pnl-history api-reference/openapi.json GET /pnl/history Cumulative profit and loss of this key’s trading account at evenly spaced times from `start` to `end`, each point as of its time. The range is at most 365 days and 1000 points. A test key’s points have realized profit and loss only. # Get risk Source: https://lean.mintlify.app/api-reference/account/get-risk api-reference/openapi.json GET /risk Exposure of this key’s trading account, per venue and in total: the cost basis and mark value of its positions, its cash, and the unfilled notional of its open orders. Also its largest positions and how its cost basis splits across markets and categories. Built from the same reads as positions, balances and orders; a venue that cannot be read is listed in `unavailable` and its values are null, never zero. A test key’s positions are marked as the Lean portfolio marks live ones: Polymarket at the last trade, Hyperliquid at the venue’s mid; a position with no mark makes the mark values it counts toward null. # List balances Source: https://lean.mintlify.app/api-reference/account/list-balances api-reference/openapi.json GET /balances Cash held by this key’s trading account on each venue, in the collateral the venue trades in. Kalshi and Polymarket US cash belongs to the user, so every trading account of the user reads the same balance there. A venue that could not be read is listed in `unavailable`. # List positions Source: https://lean.mintlify.app/api-reference/account/list-positions api-reference/openapi.json GET /positions Shares held by this key’s trading account on each venue, with average price, mark price and unrealized profit and loss. Each holding names its `market_id`, `title` and `outcome`, or null when no market is listed for it. Filter by venue, market or text in the market title. Kalshi and Polymarket US accounts belong to the user rather than one trading account, so every trading account of the user lists the same holdings there. A venue that could not be read is listed in `unavailable`. # Lower this key's limits Source: https://lean.mintlify.app/api-reference/account/lower-key-limits api-reference/openapi.json POST /account/limits A key may lower its own per order and rolling 24 hour limits. Raising them needs a signed in session in the dashboard; a raise is refused with `details.reason` `LIMIT_RAISE_NOT_ALLOWED`. # Pause order placement Source: https://lean.mintlify.app/api-reference/account/pause-trading api-reference/openapi.json POST /account/pause Stops new orders for this key or for every key of its trading account, and stops queued orders that have not reached a venue yet. Reads, cancels and resting orders are unaffected. Only the Lean dashboard can resume. # Get account configuration Source: https://lean.mintlify.app/api-reference/account/retrieve-account-config api-reference/openapi.json GET /account/config What this key may do, the spend limits an order placed with it is held to, where they come from, how much of the rolling 24 hour limit is left, the venues the account allows, its slippage cap, if it sets one, and whether trading is paused. # Create an API key Source: https://lean.mintlify.app/api-reference/api-keys/create-api-key api-reference/openapi.json POST /api-keys Creates a test or live key on one of your trading accounts with the scopes and limits you choose, up to the account’s own. The secret is returned once in this response; store it, because it cannot be shown again. # List API keys Source: https://lean.mintlify.app/api-reference/api-keys/list-api-keys api-reference/openapi.json GET /api-keys Every API key of the signed in user across their trading accounts, including revoked and expired keys. Secrets are never returned; each key shows only its prefix. # List trading pauses Source: https://lean.mintlify.app/api-reference/api-keys/list-trading-pauses api-reference/openapi.json GET /api-keys/suspensions Every pause that stops orders from your API keys: pauses on a key, pauses on a trading account, and a platform wide halt if one is in force. Each shows who set it, why and since when. # Pause API trading on a trading account Source: https://lean.mintlify.app/api-reference/api-keys/pause-account-api-trading api-reference/openapi.json PUT /api-keys/accounts/{tradingAccountId}/suspension Stops every API key of one trading account placing new orders until you resume it. Keys can still read and cancel, and resting orders stay on the venues. # Pause an API key Source: https://lean.mintlify.app/api-reference/api-keys/pause-api-key api-reference/openapi.json PUT /api-keys/{id}/suspension Stops one key placing new orders until you resume it. The key can still read and cancel, and its resting orders stay on the venues. Pausing a key that is already paused changes nothing. # Resume API trading on a trading account Source: https://lean.mintlify.app/api-reference/api-keys/resume-account-api-trading api-reference/openapi.json DELETE /api-keys/accounts/{tradingAccountId}/suspension Lifts a pause on a trading account so its keys can place orders again. A pause Lean set can only be lifted by Lean. # Resume an API key Source: https://lean.mintlify.app/api-reference/api-keys/resume-api-key api-reference/openapi.json DELETE /api-keys/{id}/suspension Lifts a pause you or the key set, so the key can place orders again. A pause Lean set can only be lifted by Lean. # Get a trading account's API limits Source: https://lean.mintlify.app/api-reference/api-keys/retrieve-account-limits api-reference/openapi.json GET /api-keys/accounts/{tradingAccountId}/limits The account's own API limits, allowed venues and slippage cap, and the limits every key on the account is held to. A limit the account has not set is reported as 100,000,000 USD, the most an account limit can be; each key still holds orders to its own limits. # Revoke an API key Source: https://lean.mintlify.app/api-reference/api-keys/revoke-api-key api-reference/openapi.json DELETE /api-keys/{id} Revokes a key at once, and requests with it are refused from then on. Revoking a key again returns it unchanged. # Set a trading account's API limits Source: https://lean.mintlify.app/api-reference/api-keys/update-account-limits api-reference/openapi.json PUT /api-keys/accounts/{tradingAccountId}/limits Replaces the account's own limits, allowed venues and slippage cap; a null slippage cap sets none. Each limit can be at most 100,000,000 USD; a null limit leaves that limit unset, so only each key's own limits apply. # Change an API key's limits Source: https://lean.mintlify.app/api-reference/api-keys/update-api-key-limits api-reference/openapi.json PATCH /api-keys/{id}/limits Raises or lowers an active key's limits, up to its trading account's own. # Create deposit addresses Source: https://lean.mintlify.app/api-reference/deposits/create-deposit-addresses api-reference/openapi.json POST /deposits/addresses Only needed if you haven’t already created a deposit address in the Lean app. Creates every deposit address the key’s trading account is missing on one venue and returns all of them. An address the provider cannot open right now is listed in missing while the others are still created and returned; call again later for it. Repeating it returns the same addresses and creates no others. It moves no money. Send only an asset GET /deposits/assets lists for the same venue, provider and address type. Hyperliquid addresses come only from Relay and credit Hyperliquid spot USDC. Do not use Hyperliquid’s own bridge: sending to Hyperliquid’s own bridge lands in perps, not in the spot balance these addresses fund. A test key gets placeholders that are not addresses on any chain. # Get deposit addresses Source: https://lean.mintlify.app/api-reference/deposits/list-deposit-addresses api-reference/openapi.json GET /deposits/addresses Addresses that fund the key’s trading account on one venue, as already created; this never creates one. An address created in the Lean app is returned here too. Each address not created yet is listed in `missing` with a `message` naming POST /deposits/addresses. Send only an asset GET /deposits/assets lists for the same venue, provider and address type. Hyperliquid addresses come only from Relay and credit Hyperliquid spot USDC. Do not use Hyperliquid’s own bridge: sending to Hyperliquid’s own bridge lands in perps, not in the spot balance these addresses fund. A test key gets placeholders that are not addresses on any chain. # List deposit assets Source: https://lean.mintlify.app/api-reference/deposits/list-deposit-assets api-reference/openapi.json GET /deposits/assets Chains and tokens each venue accepts as deposits, with the provider’s minimum. Hyperliquid deposits arrive through Relay as spot USDC; sending to Hyperliquid’s own bridge lands in perps. The first instant bridge order that funds a Hyperliquid account never used before pays Hyperliquid’s one time 1 USDC activation fee; an account already in use pays none. Arrival time depends on the source chain’s confirmations and the provider, and is not quoted here. # Cancel a limit chase Source: https://lean.mintlify.app/api-reference/limit-chases/cancel-limit-chase api-reference/openapi.json DELETE /limit-chases/{id} Stops a limit chase and cancels its resting order. Shares it already bought or sold stay with the account. Canceling works while trading is paused. A live limit chase answers with cancel_requested_at set and its status unchanged; it reads canceled a moment later, once Lean has applied the cancel. A test limit chase reads canceled at once. # Create a limit chase Source: https://lean.mintlify.app/api-reference/limit-chases/create-limit-chase api-reference/openapi.json POST /limit-chases Rests a limit order on the request’s venue a set distance behind the best price on its own side, and moves it as that price moves until the order fills, is canceled or expires. A buy follows the best bid and a sell the best ask. The order never crosses the spread, and never rests beyond price_limit when one is given. It is booked against the calling key’s limits at the most it can trade for: a buy as an order of this quantity at price_limit, or at the top price of $1 a share without one, and a sell at that same top price. A buy is held to the per-order cap, the account’s venue allow list and the rolling day; a sell only takes risk off, so it counts toward the rolling day and is held to the venue allow list, but no notional limit refuses it. On a test key the limit chase follows the live book and fills, in simulation, once the opposite best price reaches it. Every venue runs limit chases. # List limit chases Source: https://lean.mintlify.app/api-reference/limit-chases/list-limit-chases api-reference/openapi.json GET /limit-chases Limit chases of this key’s trading account in this key’s mode, newest first: every one still resting, and those that ended in the last hour. # Get a limit chase Source: https://lean.mintlify.app/api-reference/limit-chases/retrieve-limit-chase api-reference/openapi.json GET /limit-chases/{id} One limit chase of this key’s trading account by id. # Get price candles Source: https://lean.mintlify.app/api-reference/markets/get-market-candles api-reference/openapi.json GET /markets/{id}/candles Open, high, low and close prices and volume per interval for each venue leg of the market, oldest first. Prices are for the side the leg buys. A request covers at most 1000 intervals. Pass `venue` to read one venue only. # Get recent trades Source: https://lean.mintlify.app/api-reference/markets/list-market-trades api-reference/openapi.json GET /markets/{id}/trades The latest trades on each venue leg of the market, newest first. Pass `venue` to read one venue only; a venue symbol reads only the listing it names. Pass the `next_cursor` of a page as `cursor` to read older trades. # List markets Source: https://lean.mintlify.app/api-reference/markets/list-markets api-reference/openapi.json GET /markets Canonical sports markets, each with the Kalshi, Polymarket, Polymarket US and Hyperliquid legs that trade the same outcome. Filter by league, sport, status, start time or text, or look up the markets of one venue symbol. Pass `next_cursor` back as `cursor` for the next page. # Get prices Source: https://lean.mintlify.app/api-reference/markets/list-prices api-reference/openapi.json GET /prices Best bid and ask with the quantity resting at each, mid and last trade for up to 25 markets in one call, across venues and per venue. Ids that match no market are returned in `not_found`. # Quote a market Source: https://lean.mintlify.app/api-reference/markets/quote-market api-reference/openapi.json GET /markets/{id}/quote The best price to buy a quantity across venues right now, or to sell it from the shares the account holds, with the venue legs that would fill it. A venue symbol is quoted on the one listing it names, which is all an order naming it trades. Nothing is placed or reserved, and books can move before you order. # Get a market Source: https://lean.mintlify.app/api-reference/markets/retrieve-market api-reference/openapi.json GET /markets/{id} One market by its id, with each venue leg and how that venue resolves it. A market id keeps resolving after its fixture leaves the default list window. A venue symbol that names one market, such as a Polymarket token id or a Hyperliquid book coin, returns that market under its market id. # Get a market orderbook Source: https://lean.mintlify.app/api-reference/markets/retrieve-market-book api-reference/openapi.json GET /markets/{id}/book Resting bids and asks for the market on each venue, and the same levels merged across venues. Pass `venue` to read one venue only; a venue symbol reads only the listing it names. A venue whose book could not be read is listed in `unavailable`. # Amend an order Source: https://lean.mintlify.app/api-reference/orders/amend-order api-reference/openapi.json PATCH /orders/{id} Changes the limit price, the size or both of a resting good til canceled order on one venue. Lean cancels the order and, once the cancel is confirmed with its final fill, places a new good til canceled order on the same venue with the same post_only for the rest of the new size: the answer is the new order, its replaces_order_id names the old one, and the old order’s replaced_by_order_id names the new one. Each keeps its own fills. A Kalshi, Polymarket US or Hyperliquid cancel is confirmed within the request. A live Polymarket cancel is confirmed some time after it is requested, so the first amend usually answers 409 REPLACEMENT_PENDING; send the same amend again once the old order reads canceled and the replacement is placed for what did not fill. The new order is placed as the calling key places one. Every check the new order faces, from the venue’s price and size rules and a post_only price that would trade to the key’s caps, the rolling day and the account’s cash or shares, runs before the cancel with what the old order holds counted as free, and a refusal leaves the order resting. Only a change between that check and the placement, such as another order spending the cash, can refuse the new order after the cancel, and the old order then stays canceled. Split, routed and immediate or cancel orders cannot be amended. # Cancel every open order Source: https://lean.mintlify.app/api-reference/orders/cancel-all-orders api-reference/openapi.json POST /orders/cancel-all Cancels each open order of this key's trading account in this key's mode, optionally only on one venue or market, the same way canceling each order would. One failed cancel does not stop the rest; each result says what happened. Works while trading is paused. # Cancel an order Source: https://lean.mintlify.app/api-reference/orders/cancel-order api-reference/openapi.json POST /orders/{id}/cancel Cancels what is still resting of an open order on every venue it was placed on and returns the order once the venues answer. Shares already filled stay filled. # Cancel several orders Source: https://lean.mintlify.app/api-reference/orders/cancel-orders-batch api-reference/openapi.json POST /orders/cancel-batch Cancels each named order of this key's trading account in this key's mode, the same way canceling each order would. Name orders by id, by client_order_id or both, up to 50 in one call. One failed cancel does not stop the rest; each result says what happened, and an order that matches nothing fails with NOT_FOUND. Works while trading is paused. # Create an order Source: https://lean.mintlify.app/api-reference/orders/create-order api-reference/openapi.json POST /orders The default way to buy across venues, in one call. Lean places the order on the venues that can fill it. A buy the account cannot pay for on those venues is bought through a route across venues instead when routing is on and the key has the route scope: Lean moves the money from the funding venue and buys on the execution venue, and `route` names both. A live key also needs the account to have enabled trading in the Lean app, because Lean signs the payment with its delegated signer; a test key routes against the simulator and never signs. Without a route, a buy the account cannot pay for is refused. To sign route payments yourself, use POST /v1/routed-orders and POST /v1/routed-orders/{id}/execute instead. # Place a routed order Source: https://lean.mintlify.app/api-reference/orders/create-routed-order api-reference/openapi.json POST /routed-orders Advanced. Book a cross-venue buy whose payment you sign yourself. > [!NOTE] > > Most programs should use [Create an order](/api-reference/orders/create-order): it pays from the > other venue in the same call. This endpoint is the first of two calls for programs that sign each > payment themselves. See [Advanced: self-signed routed orders](/routed-orders). # Execute a routed order Source: https://lean.mintlify.app/api-reference/orders/execute-routed-order api-reference/openapi.json POST /routed-orders/{id}/execute Authorizes the payment of an order from POST /v1/routed-orders, with your signature over its `typed_data` or with Lean’s delegated signer, and starts the route. Call it before the payment expires. # List fills Source: https://lean.mintlify.app/api-reference/orders/list-fills api-reference/openapi.json GET /fills Executions on this key’s trading account, newest first, with price, quantity, fee and whether each fill made or took liquidity. Each fill names its `market_id`, `title` and `outcome`, or null when no market is listed for it. Filter by order, venue, market, time or text in the market title, and pass `next_cursor` back as `cursor` for the next page. A live key also sees fills of orders placed outside the API; a test key sees its simulated fills, including those of its limit chases. A limit chase’s fills have `order_id` `null`. Kalshi and Polymarket US fills belong to the user rather than one trading account, so every trading account of the user lists them. Reading a filled order with `GET /v1/orders/{id}` brings its fills into this list. A Polymarket fill whose trade Polygon has not confirmed yet, or a fill of an order you have not read, can be listed a few seconds after its order reads `filled`. # List orders Source: https://lean.mintlify.app/api-reference/orders/list-orders api-reference/openapi.json GET /orders Orders placed through the API on this key’s trading account, newest first. Each order names its `market_id`, `title` and `outcome`; the title and outcome are null for a market whose fixture started more than 7 days ago. Filter by status, venue, market, text in the market title or `client_order_id`, and pass `next_cursor` back as `cursor` for the next page. # Preview an order Source: https://lean.mintlify.app/api-reference/orders/preview-order api-reference/openapi.json POST /orders/preview Runs the same checks as POST /v1/orders on the same body and returns what it would do: the venue legs, the expected average price, the route a buy would take and whether the order would be refused before reaching a venue. Nothing is placed or reserved. # Preview several orders Source: https://lean.mintlify.app/api-reference/orders/preview-orders-batch api-reference/openapi.json POST /orders/preview-batch Previews up to 25 order bodies in one call, each exactly as POST /v1/orders/preview previews it, and runs them at once, so a batch takes about as long as its slowest preview. Each body is previewed on its own: the batch does not add the notional of one body to another's limit checks. One body that cannot be previewed does not stop the rest; its result carries the status and error the single preview answers with. Results are in the order the bodies were sent. Nothing is placed or reserved, and the call counts once against the key's rate limit. # Retrieve an order Source: https://lean.mintlify.app/api-reference/orders/retrieve-order api-reference/openapi.json GET /orders/{id} One API order by id, refreshed from its venues, with its market’s `title` and `outcome` and each leg’s status and the quantity filled so far. A canceled ioc order and its canceled legs carry `status_reason.code` `IOC_REMAINDER_CANCELED`: the venue canceled what did not fill at once, and `filled_quantity` is what filled. # Set a cancel timer Source: https://lean.mintlify.app/api-reference/orders/set-cancel-after api-reference/openapi.json POST /orders/cancel-after A safety timer: unless this is called again in time, every open order of this key's trading account in this key's mode is canceled once the timeout runs out. Each call restarts the timer; 0 disarms it. The timer fires once and then disarms. # Cancel a stop loss Source: https://lean.mintlify.app/api-reference/stop-losses/cancel-stop-loss api-reference/openapi.json DELETE /stop-losses/{id} Stops a stop loss or take profit from watching the market, and stops a sale it has started. Canceling works while trading is paused. A live stop loss answers with cancel_requested_at set and its status unchanged; it reads canceled a moment later, once Lean has applied the cancel. A test stop loss reads canceled at once. # Create a stop loss or take profit Source: https://lean.mintlify.app/api-reference/stop-losses/create-stop-loss api-reference/openapi.json POST /stop-losses Watches the best bid for shares this key’s trading account holds on the request’s venue and sells them once it reaches the trigger price. A stop_loss sells when the bid falls to trigger_price or below; a take_profit sells when it rises to trigger_price or above. The sale fills no lower than trigger_price minus slippage_limit: it sells what it can at once, then rests the rest at that price until it fills, is canceled or expires. The stop losses on the same shares together sell at most what the account holds. The sale is booked as an order at trigger_price would be: it counts toward the rolling day and is held to the account’s venue allow list, but as a sale it only takes risk off, so no notional limit refuses it. On a test key the stop loss is recorded, listed and booked but never sells. Every venue runs stop losses and take profits. # List stop losses Source: https://lean.mintlify.app/api-reference/stop-losses/list-stop-losses api-reference/openapi.json GET /stop-losses Stop losses and take profits of this key’s trading account in this key’s mode, newest first: every one still watching or selling, and those that ended in the last hour. # Get a stop loss Source: https://lean.mintlify.app/api-reference/stop-losses/retrieve-stop-loss api-reference/openapi.json GET /stop-losses/{id} One stop loss or take profit of this key’s trading account by id. # Create a stream ticket Source: https://lean.mintlify.app/api-reference/streaming/create-stream-ticket api-reference/openapi.json POST /ws/token Mints a short lived ticket for one connection to the /v1/ws WebSocket, so the API key itself never travels over the socket. Connect, then send `{"op":"auth","ticket":""}` as the first frame. Use the ticket to open the [WebSocket](/api-reference/streaming/websocket): it covers connecting, the `auth` frame, subscribing to channels and close codes. For reconnecting and rebuilding state, see the [Streaming guide](/streaming). # WebSocket Source: https://lean.mintlify.app/api-reference/streaming/websocket Connect, authenticate and subscribe to the orders, positions, balances and book channels. One WebSocket carries every channel you subscribe to, for one key, its trading account and its mode. For reconnecting and rebuilding state, see the [Streaming guide](/streaming). ## Connect | | | | - | - | | Path | `/v1/ws` at the WebSocket URL for your environment | | Frames | One JSON text object per frame, in both directions | | Frame size | Keep each frame you send under 16 KB; a larger frame ends the connection | | Channels | At most 32 on one connection | Frames you send must not carry fields other than the ones shown on this page. Channels always follow the ticket's account and mode; no frame can name another. ## Get a ticket Your API key never travels over the socket. Exchange it for a ticket with [Create a stream ticket](/api-reference/streaming/create-stream-ticket): ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/ws/token" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ```json theme={"dark"} { "success": true, "data": { "token": "", "expires_at": "2026-11-01T20:25:00.000Z", "livemode": false }, "meta": { "timestampMs": 1793564640000, "requestId": "" } } ``` A ticket opens one connection and is good for 60 seconds, or until the key expires if that is sooner. Request a new one for each connection, including every reconnect. ## Authenticate Within 10 seconds of opening the socket, send the ticket as the first frame: ```json theme={"dark"} { "op": "auth", "ticket": "" } ``` ```json theme={"dark"} { "type": "authenticated", "livemode": false, "key_id": "" } ``` Any other frame before `auth` closes the socket. A second `auth` frame on the same connection is answered with a `VALIDATION_ERROR` error frame. ## Subscribe and unsubscribe Name one or more channels: ```json theme={"dark"} { "op": "subscribe", "channels": [ { "channel": "orders" }, { "channel": "positions" }, { "channel": "balances" }, { "channel": "book", "market_id": "mkt_..." } ] } ``` The reply lists the channels you named: ```json theme={"dark"} { "type": "subscribed", "channels": [ { "channel": "orders" }, { "channel": "positions" }, { "channel": "balances" }, { "channel": "book", "market_id": "mkt_..." } ] } ``` To stop channels, send the same shape with `unsubscribe`. The reply is an `unsubscribed` frame listing the channels you named: ```json theme={"dark"} { "op": "unsubscribe", "channels": [{ "channel": "book", "market_id": "mkt_..." }] } ``` ```json theme={"dark"} { "type": "unsubscribed", "channels": [{ "channel": "book", "market_id": "mkt_..." }] } ``` Subscribing to a channel you already hold does not add it twice. These are answered with a `VALIDATION_ERROR` error frame and the connection stays open: | Message | When | | - | - | | `Name at least one channel` | `subscribe` named no channels. | | `Unrecognized market id` | A `book` channel's `market_id` is not shaped like a market id or venue symbol. | | `Too many channels on one connection` | The subscription would take the connection past 32 channels. | ## Channels | Channel | Frame type | Holds | | - | - | - | | `orders` | `order` | Each new state of an order, as [Retrieve an order](/api-reference/orders/retrieve-order) returns it. | | `positions` | `positions` | The whole [List positions](/api-reference/account/list-positions) result. | | `balances` | `balances` | The whole [List balances](/api-reference/account/list-balances) result. | | `book` | `book` | One market's book, as [Get a market orderbook](/api-reference/markets/retrieve-market-book) returns it. | ### orders Sends each state of the account's orders that happens after `subscribed`. Each order's states only move forward. Call `GET /v1/orders` once after `subscribed` to cover anything earlier. ```json theme={"dark"} { "type": "order", "order": { "id": "", "client_order_id": "my_order_0001", "market_id": "mkt_...", "venue": "hyperliquid", "ticker": "", "side": "yes", "action": "buy", "type": "limit", "time_in_force": "ioc", "expires_at": null, "quantity": "5", "filled_quantity": "5", "remaining_quantity": "0", "limit_price": "0.50", "avg_fill_price": "0.47", "notional_usd": "2.5", "filled_notional_usd": "2.35", "status": "filled", "venue_status": "filled", "venue_order_id": "", "status_reason": null, "legs": [ { "venue": "hyperliquid", "ticker": "", "side": "yes", "quantity": "5", "filled_quantity": "5", "limit_price": "0.50", "avg_fill_price": "0.47", "status": "filled", "venue_status": "filled", "venue_order_id": "", "cancel_requested_at": null, "status_reason": null } ], "post_only": false, "replaces_order_id": null, "replaced_by_order_id": null, "created_at": "2026-11-01T20:24:02.114Z", "updated_at": "2026-11-01T20:24:02.587Z", "livemode": false } } ``` ### positions Each frame is the whole state and replaces the one before it. The newest state arrives first, then each change. Frames follow every order change on the account and are refreshed about every ten seconds otherwise. ```json theme={"dark"} { "type": "positions", "positions": { "positions": [ { "venue": "hyperliquid", "ticker": "", "side": "yes", "quantity": "5", "average_price": "0.5", "mark_price": null, "unrealized_pnl_usd": null, "market_id": "mkt_...", "title": "", "outcome": "" } ], "unavailable": [], "livemode": false } } ``` ### balances Sent and refreshed the same way as positions. ```json theme={"dark"} { "type": "balances", "balances": { "balances": [ { "venue": "polymarket", "currency": "pUSD", "total_usd": "10000", "available_usd": "10000" }, { "venue": "hyperliquid", "currency": "USDC", "total_usd": "10000", "available_usd": "10000" } ], "unavailable": [], "livemode": false } } ``` ### book Takes a `market_id`: a market ID or a [venue symbol](/markets#venue-symbols). With a market ID, each frame holds the market's book across every venue that lists it; with a venue symbol, only that symbol's listing. `combined` merges the venues' levels by price, at a depth of 20 levels per side. The book updates about once a second, and each frame replaces the one before it. A `market_id` that names no market sends nothing. The frame's top-level `market_id` is the one you subscribed with, so a session following one market under two names can tell their frames apart. `book.market_id` is always the market ID. ```json theme={"dark"} { "type": "book", "market_id": "mkt_...", "book": { "market_id": "mkt_...", "venues": [ { "venue": "polymarket", "ticker": "", "side": "yes", "bids": [{ "price": "0.52", "quantity": "100" }], "asks": [{ "price": "0.55", "quantity": "40" }], "bid_quantity": "100", "ask_quantity": "40", "bid_notional_usd": "52", "ask_notional_usd": "22" } ], "combined": { "bids": [ { "price": "0.52", "quantity": "100", "venues": [{ "venue": "polymarket", "quantity": "100" }] } ], "asks": [ { "price": "0.55", "quantity": "40", "venues": [{ "venue": "polymarket", "quantity": "40" }] } ] }, "total_bid_quantity": "100", "total_ask_quantity": "40", "total_bid_notional_usd": "52", "total_ask_notional_usd": "22", "unavailable": [], "as_of": "2026-11-01T20:25:00.000Z", "livemode": false } } ``` A session that reads positions, balances or books too slowly skips ahead to the newest state. ## Keep the connection alive Send `{"op":"ping"}` every 10 seconds; the reply is `{"type":"pong"}`. If no frame of any kind, `pong` included, arrives for 25 seconds, close the socket and reconnect with a new ticket. ## Errors After authentication, a bad frame is answered with an error frame and the connection stays open: ```json theme={"dark"} { "type": "error", "code": "VALIDATION_ERROR", "message": "Unrecognized frame" } ``` ## Close codes Before authentication, or when the connection must end, Lean sends an error frame and then closes the socket: | Close code | `code` | When | | - | - | - | | `1008` | `UNAUTHORIZED` | The ticket is invalid, expired or already used; no `auth` frame arrived within 10 seconds; a frame came before `auth`; or the key was revoked or expired. | | `1008` | `VALIDATION_ERROR` | The first frame was not an `auth` frame. | | `1003` | `VALIDATION_ERROR` | A binary frame was sent. | | `1013` | `RATE_LIMITED` | The session read order states too slowly to keep up. | | `1013` | `UPSTREAM_ERROR` | Lean could not check whether the ticket was already used. | | `1013` | `UPSTREAM_ERROR` | Order updates were interrupted inside Lean, so some may not have reached the session. Only sessions subscribed to `orders`, or sending a `subscribe` that names it, close this way; that `subscribe` gets no `subscribed` reply. | | `1012` | none | Lean is restarting. | After a `1012` or `1013` close, reconnect with a new ticket, subscribe again and call `GET /v1/orders`. After a `1008` close, the ticket or key was refused: try once more with a new ticket and stop after three `1008` closes in a row. The [Streaming guide](/streaming#reconnecting) covers the full reconnect plan. # Reset test mode Source: https://lean.mintlify.app/api-reference/test-mode/reset-test-mode api-reference/openapi.json POST /test/reset Deletes every simulated order, withdrawal, transfer, stop loss and limit chase of the test key’s trading account, made by any test key on that account and not only the calling key, which returns the account’s test balances to the starting amount and clears its test positions. Live keys are refused. # Create a transfer Source: https://lean.mintlify.app/api-reference/transfers/create-transfer api-reference/openapi.json POST /transfers Creates a transfer of cash from one venue of this key’s trading account to the account’s own balance on the other venue. Transfers are simulated against test cash for test keys; live keys are refused with LIVE_TRANSFERS_UNAVAILABLE. Nothing moves until the transfer is executed with the owner’s signatures over `authorization.payloads` or the account’s delegated signer. The amount must be at least the route minimum, fit what the sending venue holds and fit the per order and rolling 24 hour limits of the key and the account. Sending the same client_transfer_id again returns the transfer already created. # Execute a transfer Source: https://lean.mintlify.app/api-reference/transfers/execute-transfer api-reference/openapi.json POST /transfers/{id}/execute Authorizes and submits a transfer waiting for authorization, once. Send the owner’s signatures over `authorization.payloads` in order, or `delegated` to have Lean sign them with the account’s delegated signer. A transfer is submitted at most once and never retried; sending the same authorization again returns the transfer as it stands. # List transfers Source: https://lean.mintlify.app/api-reference/transfers/list-transfers api-reference/openapi.json GET /transfers Transfers of this key’s trading account in this key’s mode, newest first. # Quote a transfer Source: https://lean.mintlify.app/api-reference/transfers/quote-transfer api-reference/openapi.json POST /transfers/quote What moving cash from one venue of this key’s trading account to the other would cost and deliver, the smallest amount the route accepts and what the sending venue holds. It needs only the read scope and creates nothing. # Get a transfer Source: https://lean.mintlify.app/api-reference/transfers/retrieve-transfer api-reference/openapi.json GET /transfers/{id} One transfer of this key’s trading account by id, with its current status. # Withdraw cash Source: https://lean.mintlify.app/api-reference/withdrawals/create-withdrawal api-reference/openapi.json POST /withdrawals Withdraws cash from one venue of this key’s trading account to the address the request names. The request names the source venue and the asset it holds, the destination chain, asset and address, and the amount of the source asset. Each venue pays out one asset as usdc, on any chain that destination.chain lists: pusd on Polymarket and usdc on Hyperliquid. Any other pair of assets is refused with a 400. The key needs the withdraw scope, and each withdrawal must fit the key’s optional per withdrawal limit, its optional limit across the last 24 hours and the venue’s available cash. The venue’s fee comes out of the amount: the response gives the fee and the net amount the destination is quoted to receive. A live withdrawal needs trading enabled for the account in the Lean app and is submitted once: it starts pending and becomes completed or failed as the venue settles it, with failure_reason saying why a failed one paid nothing. A Polymarket withdrawal is completed once the funds leave the account for Polymarket’s bridge, which then pays the USDC on the destination chain; a Hyperliquid withdrawal is completed once the USDC arrives on the destination chain. A test withdrawal moves nothing, charges no fee, completes at once and lowers the simulated cash on that venue until test mode is reset. Sending the same client_withdrawal_id again returns the withdrawal already made. # List withdrawals Source: https://lean.mintlify.app/api-reference/withdrawals/list-withdrawals api-reference/openapi.json GET /withdrawals Withdrawals this key’s trading account made in this key’s mode, newest first. # Get a withdrawal Source: https://lean.mintlify.app/api-reference/withdrawals/retrieve-withdrawal api-reference/openapi.json GET /withdrawals/{id} One withdrawal of this key’s trading account by id. # Authentication Source: https://lean.mintlify.app/authentication API keys, scopes, spending limits and rate limits. Every `/v1` call except the OpenAPI document needs an API key: ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets" -H "Authorization: Bearer $LEAN_API_KEY" ``` ## Create a key Each key belongs to one trading account and has its own limits. A key is either a test key (`lean_sk_test_…`) or a live key (`lean_sk_live_…`). Both use the same trading account. Test keys simulate orders and fills with no money; live keys trade real money, and trading can be paused platform wide. A key's mode is set when you create it and can't be changed. See [Test mode and live mode](/test-mode). 1. Sign in to Lean. 2. Open Settings (the gear) and choose **API**. 3. Under **API keys**, choose **Create API key**. Give the key a name, then choose its mode, access, per order limit, daily limit and expiry. The mode is **Test** and the access is **Read and trade** unless you change them. Choose **Create key**. 4. Under **Copy your key now**, choose **Copy**, then **Done**. You won't see the key again. > [!WARNING] > > Lean stores only a hash of the key and cannot recover a lost one. Keep it in a secret manager, > never in source control. | Setting | Meaning | | - | - | | Access | **Read only** allows every `GET`, `POST /v1/orders/preview`, `POST /v1/transfers/quote` and `POST /v1/ws/token` (a stream ticket): markets, quotes, previews, balances, positions, orders and streams. **Read and trade** also allows placing, amending and canceling orders, stop losses, limit chases and transfers, and paying for a buy with cash on the other venue, between Polymarket and Hyperliquid. In the API, **Read only** is the `read` scope and **Read and trade** is `read`, `trade` and `route`. A **Read and trade** key made before one-call routing shipped (see the [changelog](/changelog)) has only `read` and `trade`: create a new key to pay from the other venue. | | Per order limit | The largest single order, in USD. Lean refuses any order above it before it reaches a venue. | | Daily limit | The total notional, in USD, the key may place in any rolling 24 hours. Stop losses, limit chases and transfers count toward it too. A canceled, rejected or expired order counts only the part that filled. It must be at least the per order limit. | | Allow withdrawals | Off unless you turn it on. Lets the key withdraw through the API, with an optional per withdrawal limit and daily withdrawal limit, in USD. See [Withdrawals through the API](/funding#withdrawals-through-the-api). | | Expiry | From 1 to 90 days. The default is 90. | The **API keys** list shows each key's name with a **Test** or **Live** badge, its prefix (such as `lean_sk_test_xxxxxxxx…`), when it was created, last used and expires, and whether it is Active, Revoked or Expired. A user can hold up to 10 active keys; revoke one to create another. ### Manage keys with the API (advanced) If you manage keys from your own tooling, call `/api-keys` instead. These requests take the access token of your Lean session while you are signed in, sent as `Authorization: Bearer `, never an API key. The token expires after a short time. > [!WARNING] > > A session token acts as you, signed in. Use it only to create, list and revoke keys, never paste > it into a program, and don't share it. ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/api-keys" \ -H "Authorization: Bearer $LEAN_SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "my-bot", "mode": "test", "tradingAccountId": "", "scopes": ["read", "trade", "route"], "maxOrderNotionalMicros": 5000000, "dailyNotionalLimitMicros": 25000000, "expiresInDays": 7 }' ``` Send the body as JSON with `Content-Type: application/json`, or the request is refused with `400 VALIDATION_ERROR`. The secret is in `data.secret`. `mode` is `test` or `live` and defaults to `test`. `scopes` takes `read`, `trade` and `route`. `route` lets the key pay for a buy with cash on the other venue (see [Paying from the other venue](/orders#paying-from-the-other-venue)) and needs `trade`. Leave it out for a key that should only trade with the cash already on each venue. A key can also take `withdraw`, with optional withdrawal limits; see [Withdrawals through the API](/funding#withdrawals-through-the-api). Limits are in millionths of a dollar, so `5000000` is \$5. The API reference documents [Create an API key](/api-reference/api-keys/create-api-key), [List API keys](/api-reference/api-keys/list-api-keys) and [Revoke an API key](/api-reference/api-keys/revoke-api-key), with every field and error. ## Rotate and revoke To rotate a key, create a new one, move your client to it, then revoke the old one: in Settings, **API**, choose **Revoke** on its row, then **Revoke** again to confirm. Programs using the key stop working immediately, and this can't be undone. With the API: ```bash theme={"dark"} curl -sS -X DELETE "$LEAN_API_URL/api-keys/" \ -H "Authorization: Bearer $LEAN_SESSION_TOKEN" ``` Lean refuses revoked and expired keys immediately. ## Failures | HTTP | `code` | Cause | | - | - | - | | 401 | `UNAUTHORIZED` | No key, a malformed key, or an unknown, expired or revoked key. | | 403 | `FORBIDDEN` | The key lacks the scope, or its account has no API access. | | 429 | `RATE_LIMITED` | More than 5 requests a second per key, with bursts up to 20. Cancels have their own budget of 10 a second, with bursts up to 40. Wait for the `Retry-After` header. | | 503 | `INTERNAL_ERROR` | Lean could not check the key's rate limit, so it did not serve the request. Retry later. | # Build with AI Source: https://lean.mintlify.app/build-with-ai Give a coding assistant or an AI agent these docs, the OpenAPI spec and the Lean MCP server, then let it trade safely on a test key. These docs are available as plain Markdown, as one file for language models and through a hosted MCP server, and the OpenAPI spec describes every endpoint. Give them to a coding assistant or an agent so it works from the real API, then start it on a test key. ## Docs for language models | File | Address | Use it for | | - | - | - | | `llms.txt` | [lean.mintlify.site/llms.txt](https://lean.mintlify.site/llms.txt) | An index of every page with a one line summary. Point an agent here first. | | `llms-full.txt` | [lean.mintlify.site/llms-full.txt](https://lean.mintlify.site/llms-full.txt) | Every page in one Markdown file. Attach it when the model can't browse. | | A page as Markdown | Add `.md` to the page's address, for example [lean.mintlify.site/quickstart.md](https://lean.mintlify.site/quickstart.md) | One page without navigation or styling. | The menu at the top of each page copies the page as Markdown, opens it as Markdown, opens it in ChatGPT or Claude with the page as context, or copies the address of the docs MCP server. ## Connect the docs MCP server The docs have a hosted Model Context Protocol (MCP) server at `https://lean.mintlify.site/mcp`. An assistant connected to it can search these docs and read their pages while it works. It serves only the public docs: it can't call the Lean API or see your account, and it needs no key. ```bash Claude Code theme={"dark"} claude mcp add --transport http lean-api https://lean.mintlify.site/mcp ``` ```json Cursor (.cursor/mcp.json) theme={"dark"} { "mcpServers": { "lean-api": { "url": "https://lean.mintlify.site/mcp" } } } ``` ```json VS Code (.vscode/mcp.json) theme={"dark"} { "servers": { "lean-api": { "type": "http", "url": "https://lean.mintlify.site/mcp" } } } ``` Any other client that supports remote MCP servers over HTTP takes the same address. ## Run the Lean MCP server The Lean MCP server is different from the docs MCP server: it calls the Lean API with your API key, so an assistant connected to it can read markets, books, candles, orders, positions, profit and loss, risk, stop losses, deposits, withdrawals and transfers for your account. It runs on your machine over stdio with [Bun](https://bun.sh), and the key stays in its environment, so the key is never sent to the model. The server is the `sdks/mcp` package of the Lean SDKs, started with `bun sdks/mcp/src/index.ts`. | Setting | What it does | | - | - | | `LEAN_API_KEY` | Required. The key the server sends with every request. | | `LEAN_API_URL` | The API address. Defaults to `https://api.lean.xyz`. | | `LEAN_API_TIMEOUT_MS` | How long to wait for each request, in milliseconds. Defaults to 30000. | | `--enable-trading` | A command line flag that asks for the trading tools. | **It is read only by default.** These tools are always available: `list_markets`, `get_market`, `quote_market`, `get_market_book`, `get_market_trades`, `get_market_candles`, `get_prices`, `list_orders`, `get_order`, `list_fills`, `get_positions`, `get_balances`, `get_account_config`, `get_pnl`, `get_pnl_history`, `get_risk`, `list_stop_losses`, `get_stop_loss`, `list_limit_chases`, `get_limit_chase`, `get_deposit_addresses`, `get_deposit_assets`, `list_withdrawals`, `get_withdrawal`, `quote_transfer`, `list_transfers` and `get_transfer`. Any tool that takes a market ID also takes a venue's own ID for it, such as a Polymarket token ID, a Kalshi market ticker or a ticker with a `pm:`, `pmus:` or `hl:` prefix. The read and trading tools cover Kalshi, Polymarket, Polymarket US and Hyperliquid. Deposits, transfers and withdrawals cover Polymarket and Hyperliquid only. **Tools that change anything need two things:** the server starts with `--enable-trading`, and the key has the scope the API checks for that tool. Otherwise the assistant isn't offered them at all. With the flag and a **Read only** key, the server says so when it starts and stays read only. | Tools | Scope the key needs | | - | - | | `preview_order`, `create_order`, `amend_order`, `cancel_order`, `cancel_orders_batch`, `cancel_all_orders`, `set_cancel_after`, `close_positions`, `create_stop_loss`, `cancel_stop_loss`, `create_limit_chase`, `cancel_limit_chase`, `pause_trading`, `lower_limits` and `create_deposit_addresses` | `trade`, a **Read and trade** key (see [Authentication](/authentication#create-a-key)) | | `create_transfer` and `execute_transfer` | `trade` and `route`. A **Read and trade** key made in the Lean app has both. Only test keys can transfer for now. See [Transfers](/transfers). | | `create_withdrawal` | `withdraw`. See [Withdrawals through the API](/funding#withdrawals-through-the-api). | `create_order` and `preview_order` take every order type the API takes: limit or market, by quantity or by dollar amount, good till canceled, immediate or cancel, fill or kill, or good till a time, and post only. `pause_trading` and `lower_limits` let an assistant stop its own trading or tighten its own key. Neither can be undone through the API: only the Lean app resumes trading or raises a limit. Start with a test key, so orders are simulated and no money moves, and give the key tight limits. Every tool answers with the API response, including `livemode`, and an API error comes back with its code, message and request ID. A tool refuses any argument it does not define, so a misspelled filter is an error, not silently ignored. ```bash Claude Code theme={"dark"} claude mcp add lean \ --env LEAN_API_KEY=lean_sk_test_... \ --env LEAN_API_URL=https://api.lean.xyz \ -- bun /absolute/path/to/sdks/mcp/src/index.ts ``` ```json Cursor (.cursor/mcp.json) theme={"dark"} { "mcpServers": { "lean": { "command": "bun", "args": ["/absolute/path/to/sdks/mcp/src/index.ts"], "env": { "LEAN_API_KEY": "lean_sk_test_...", "LEAN_API_URL": "https://api.lean.xyz" } } } } ``` ```json Cursor with trading tools theme={"dark"} { "mcpServers": { "lean": { "command": "bun", "args": ["/absolute/path/to/sdks/mcp/src/index.ts", "--enable-trading"], "env": { "LEAN_API_KEY": "lean_sk_test_..." } } } } ``` The assistant should still preview every order and wait for your approval before it places one. The [system prompt](#a-system-prompt-for-a-trading-agent) and [safety checklist](#safety-checklist) below apply to it too. ## Use the OpenAPI spec The [OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json) (OpenAPI 3.0) lists every endpoint with its parameters, request and response schemas and error shapes. Its server is `{baseUrl}/v1`, and `baseUrl` defaults to `https://api.lean.xyz`, the same value as `LEAN_API_URL` in these guides. ```bash theme={"dark"} curl -sS -o lean-openapi.json https://lean.mintlify.site/api-reference/openapi.json ``` **Give it to an agent.** Many agent frameworks turn OpenAPI operations into tools. Load only the operations the agent needs. A research agent needs the market reads and [Preview an order](/api-reference/orders/preview-order). Leave out the `/api-keys` operations: they take the session token of a person signed in to Lean, not an API key. When the model writes requests itself, attach the spec, or the schemas for the calls it makes, so its bodies match. **Generate a client.** For TypeScript and Rust, the [TypeScript SDK](/typescript-sdk) and the [Rust SDK](/rust-sdk) are already generated from the spec. Any OpenAPI 3.0 generator works for other languages, for example: ```bash theme={"dark"} # Python client npx @openapitools/openapi-generator-cli generate -i lean-openapi.json -g python -o lean-client # TypeScript types npx openapi-typescript lean-openapi.json -o lean-api.d.ts ``` Send the key as `Authorization: Bearer `, the spec's `apiKey` scheme. The spec's `info.version` is the release named in the [changelog](/changelog). Download the spec again when the changelog lists a new release. See [Versioning](/versioning). ## A system prompt for a trading agent Start from this prompt for an agent that trades through `/v1` with a test key. Give the agent the key through its environment or a tool, never in the prompt text, so the key isn't sent to the model provider or kept in logs. ```text theme={"dark"} You trade sports prediction markets through the Lean API. Setup - Base URL: the LEAN_API_URL environment variable (https://api.lean.xyz). - Send the key from the LEAN_API_KEY environment variable as "Authorization: Bearer ". Never print, log or repeat the key. - The key is a test key (it starts with lean_sk_test_). Orders are simulated and no money moves. Every successful response has data.livemode. If it is ever true, stop and tell the user. - Docs index: https://lean.mintlify.site/llms.txt Spec: https://lean.mintlify.site/api-reference/openapi.json Follow the spec for every field name and type. Placing orders - Before placing an order, send the exact body to POST /v1/orders/preview. Place it only if would_submit is true and you can explain every entry in warnings. Show the user the preview and wait for approval before you place it. - Give every order a new client_order_id and write it down before you send POST /v1/orders. - On a timeout or network error, look the order up with GET /v1/orders?client_order_id=. Retry only with the same client_order_id and the same body. Never resend an order with a new client_order_id until you know the first one was not placed. - An order whose status is unconfirmed may be on the venue. Read it back by client_order_id. Do not resend it. Errors and limits - 422 means Lean placed nothing. Read error.details.reason and do not retry the same order. ORDER_NOTIONAL_LIMIT and DAILY_NOTIONAL_LIMIT are the key's limits: do not split an order to get under them. - 429: wait for the Retry-After header, then retry. Stay under 5 requests a second. - 503 FEATURE_DISABLED with details.reason TRADING_PAUSED: trading is paused. Stop placing orders and tell the user. Only a person can resume trading. - If you are unsure what an order will do, or something looks wrong, stop and pause the key: POST /v1/account/pause with {"scope": "api_key", "reason": ""}. ``` ## Safety checklist * **Start in test mode.** A test key simulates orders and fills with simulated balances, and responses carry `livemode: false`. Move to a live key only after the agent behaves well on a test key. See [Go live](/test-mode#go-live). * **Preview before placing.** [Preview an order](/api-reference/orders/preview-order) shows the legs, prices, cost and `would_submit` without placing anything. It is the natural approval step. See [Preview](/preview). * **Use idempotency keys.** A `client_order_id` saved before sending makes every retry safe. The same ID never places a second order. See [Idempotency](/orders#idempotency). * **Set tight key limits.** Give the agent's key a per order and daily limit no higher than it needs. Lean refuses any order above them before it reaches a venue. A research agent gets a **Read only** key, which can preview but not place orders. See [Authentication](/authentication#create-a-key) and [Lower key limits](/api-reference/account/lower-key-limits). * **Keep a way to stop it.** [Pause trading](/orders#pause-trading) stops new orders for a key or the whole trading account in one call, and only the Lean dashboard resumes. Run the pause from a monitor outside the agent too, and revoke a key from Lean at any time. > [card] [An AI agent that trades within a budget](/use-cases/ai-agent-trading) > > A research agent on a read only key proposes trades, and an execution key places them after > approval. > [card] [Quickstart](/quickstart) > > From a new key to a filled test order in one call. # Changelog Source: https://lean.mintlify.app/changelog Every Lean API release, newest first. Each entry names the release version from `info.version` in the [OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json). Breaking changes are marked, with the date they take effect. See [Versioning](/versioning) for what counts as breaking. **2026-11-13** 0.1.0: Kalshi and Polymarket US **Venues** * Markets, quotes, books, trades, prices, orders, fills, positions, balances, PnL, risk, stop losses and limit chases cover Kalshi and Polymarket US as well as Polymarket and Hyperliquid. `venue` takes `kalshi` and `polymarket_us` wherever it names a trading venue. * Kalshi and Polymarket US accounts belong to the user, so every trading account and key of the user shares their cash and shares. A live order there goes out under the user's API key for that venue, connected in the Lean app, and is refused with `403 FORBIDDEN` without one. See [Kalshi and Polymarket US](/orders#kalshi-and-polymarket-us). * A quote, preview or order that needs a Polymarket US book Lean has not loaded yet answers `503 UPSTREAM_ERROR` with `Retry-After`. Send it again after that time. * A test key starts with 10,000 USD of simulated cash on Kalshi and on Polymarket US. * Stop losses and limit chases run on every venue. They no longer refuse `hyperliquid`. * `post_only` orders go to Kalshi, Polymarket US and Hyperliquid. `gtd` orders go to Kalshi, Polymarket and Polymarket US. A `fok` order goes whole to one venue: Polymarket, else Kalshi, else Polymarket US. * Paying from the other venue, `best_price` routes, self-signed routed orders, deposits, withdrawals and transfers stay on Polymarket and Hyperliquid only. **2026-11-13** 0.1.0: fee terms and fixture filters on markets, sizes on prices, batch previews, test-mode marks **Markets** * Every market leg has `fees`: the formula (`price_curve` or `notional_on_exit`), `taker_rate`, `maker_rate` and, for `price_curve`, `exponent`. They are the terms the preview charges, so a client can set a fee-aware limit price before previewing. `fees` is `null` when the venue's fee rate isn't recorded. See [Fees](/markets#fees). * `GET /v1/markets` takes `fixture` (a fixture key) and `group` (a group key such as `moneyline:game`), so one event's market group loads in one request instead of a whole league. * Every market leg has `status`, the venue market's status (`unopened`, `open`, `closed`, `resolving` or `resolved`). An `unopened` or `resolving` leg has a live book on the Lean platform but stays `tradable: false`, because its venue refuses orders. See [Legs](/markets#legs). **Prices** * `GET /v1/prices` returns `best_bid_quantity` and `best_ask_quantity`, top level and per venue: the shares at the best price, so a client can see how much an edge is worth before previewing. * Prices match the Lean platform's orderbook. Best prices are snapped to the market's tick. `mid` is the venue's mid rounded down to the tick, and a book with only one side reads that side instead of `null`. One venue's crossed book reads a `spread` of `0`. * `last_trade_price` counts a Hyperliquid trade of the opposite outcome at 1 minus its price, as Polymarket's already did, so it is the latest trade on either outcome. **Candles** * `GET /v1/markets/{id}/candles` leaves out periods the Lean chart treats as unpriced (an open of 0 or a close below 0.001), as the chart does. **Orders and fills** * Orders and fills carry the market's `title` and `outcome`, as positions do. * A canceled `ioc` order and its canceled legs have `status_reason.code` `IOC_REMAINDER_CANCELED`; `filled_quantity` says how much filled first. * `POST /v1/orders/preview-batch` previews 1 to 25 orders in one request and returns each one's preview or error in order. It needs only the `read` scope. See [Preview orders (batch)](/api-reference/orders/preview-orders-batch). * Orders carry `remaining_quantity`: the shares still working on the venues, `0` once the order is final. `avg_fill_price` is documented as excluding fees. * An order or leg the venue rejected or canceled after part of it filled reads `canceled`, and one whose whole size filled reads `filled`, as the Lean app reports them. * A Polymarket `ioc` or `fok` sell may go below the market's minimum shares, down to `0.01`, so a position under the minimum can be closed. A sell that can rest keeps the minimum. * Closing positions skips a Hyperliquid remainder under one whole contract instead of sending a sell the venue refuses. **Test mode** * Test positions are marked as the Lean portfolio marks live ones: Polymarket at the last trade, Hyperliquid at the venue's mid. `GET /v1/pnl` totals their unrealized profit and loss exactly as it does for a live key, so a position on a resolved market counts none. `GET /v1/pnl/history` stays realized-only for test keys. See [Test mode](/test-mode). **Errors** * A `400 VALIDATION_ERROR` message names the first failing field and what is wrong with it, such as `market_ids: At most 25 market ids per request; split larger sets across requests`, and says how many more problems are in `details`. **Performance** * Responses report key authentication time in the `Server-Timing` header (`auth`), and a key's last-used time is written at most once a minute instead of on every request. **2026-11-13** 0.1.0: Rust SDK 0.1.0 **Rust SDK** * `lean-api-sdk` 0.1.0 is an async Rust client for the API. It is on crates.io once 0.1.0 is published; add it with Tokio. * Every endpoint is a method on `lean_api::Client` with typed requests and responses, generated from the 0.1.0 OpenAPI spec. A response that isn't a success returns `Error::Api` with the HTTP status, the error code and the request ID. * GET requests are retried on connection errors, 429 and 5xx responses. Order placement and other writes are never retried. * `Client::stream` keeps a WebSocket open for orders, positions, balances and books, and reconnects after a drop. * The API itself is unchanged. See [Rust SDK](/rust-sdk). **2026-11-13** 0.1.0: TypeScript SDK 0.1.0 on npm **TypeScript SDK** * [`@leanxyz/api-sdk`](https://www.npmjs.com/package/@leanxyz/api-sdk) 0.1.0 is on npm. Install it with `npm install @leanxyz/api-sdk`. It needs Node.js 22 or later. * Every endpoint is a method with typed requests and responses, generated from the 0.1.0 OpenAPI spec. A response that isn't a success throws `LeanApiError` with the HTTP `status`, the error `code` and the `requestId`. * `@leanxyz/api-sdk/stream` keeps a WebSocket open for orders, positions, balances and books, and reconnects after a drop. * The API itself is unchanged. See [TypeScript SDK](/typescript-sdk). **2026-11-13** 0.1.0: unknown query parameters refused **Requests** * Every endpoint that takes query parameters returns `400 VALIDATION_ERROR` for one it does not take, as `GET /v1/markets` already did, naming it in `details`. A misspelled filter such as `GET /v1/orders?stauts=open` used to be ignored and return every order. **Breaking:** takes effect on release; remove any parameter an endpoint does not list. **2026-11-12** 0.1.0: client_order_id lookups across keys, cursors tied to their list, clearer errors **Orders** * `GET /v1/orders?client_order_id=` lists the orders any key of the account placed with that ID, not only the calling key's, so an order placed before a key rotation can still be found. It combines with the other filters. * Quotes, previews and placement report a venue failure as `503 UPSTREAM_ERROR`. They never returned `502`; the reference listed it by mistake. **Paging** * A cursor is tied to the list that issued it. An orders cursor sent to `GET /v1/fills`, or any cursor sent to another list, returns `400 VALIDATION_ERROR`. **Breaking:** a cursor issued before this release is refused once with `400`; page that list again from the start. **Errors** * A path or method no endpoint serves returns the JSON `404 NOT_FOUND` envelope, not plain text. * A malformed key returns `401 UNAUTHORIZED` with "Invalid, expired or revoked API key", the same as an unknown key, instead of "Missing API key". **Funding** * When a venue already has some deposit addresses, the deposit address note names only the network still missing one, such as Solana, and says the returned addresses are ready to use. Hyperliquid's `min_deposit_usd` is `null`: it has no minimum. See [Funding](/funding). **2026-11-12** 0.1.0: steady search results, and closed markets refused on quote and preview **Markets** * `GET /v1/markets` with `search` looks only at the listings of games in the start window. The same search now returns the same markets every time; it used to drop nickname and typo matches, such as `philly`, when it ran slowly. One- and two-letter searches no longer return `503 UPSTREAM_ERROR`. * A search that cannot finish in time returns `503 UPSTREAM_ERROR` instead of a partial list. * `GET /v1/markets/{id}/quote` and `POST /v1/orders/preview` on a market Polymarket has stopped trading return `409 CONFLICT` with `details.reason: "MARKET_NOT_TRADABLE"`, as documented. They used to return `500`, or `500` and `409` at random for a market with both a YES and a NO Polymarket listing. The [OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json) now lists this `409` on both routes. * When Polymarket answers that check with a response Lean cannot read, quote and preview return `503 UPSTREAM_ERROR` instead of `500`. * `POST /v1/orders/preview` returns these errors, and `503 UPSTREAM_ERROR` when a venue book can't be read, as the quote does. It no longer answers `200` with a `ROUTE_UNAVAILABLE` warning for them; that warning now means routing is off or no route can take the order. * A leg whose venue market has closed now reads `tradable: false`. Closed markets used to show every leg as tradable. **2026-11-12** 0.1.0: profit and loss, risk and the Lean MCP server **Profit and loss** * New `GET /v1/pnl` returns realized, unrealized and total profit and loss for the account and for each venue. Pass `venue` or `market_id` to narrow it. * New `GET /v1/pnl/history` returns profit and loss over time at a `1h` or `1d` interval, for up to 365 days and 1000 points. See [Profit and loss](/orders#profit-and-loss). **Risk** * New `GET /v1/risk` returns cost basis, mark value, cash and open order notional for the account and for each venue, with the largest positions and the split by market and by category. See [Risk](/orders#risk). **Account** * `GET /v1/account/config` now returns `scopes`, what the key may do: `read`, `trade`, `route` and `withdraw`. **MCP server** * The Lean MCP server lets an AI assistant use your key to read markets, orders, fills, positions, profit and loss, risk, stop losses, limit chases, deposits, withdrawals and transfers. Every tool that takes a market id also takes a venue symbol. * It is read only unless it starts with `--enable-trading`. Then a key with the `trade` scope can place, preview, amend and cancel orders, close positions, create stop losses and limit chases, pause trading and lower its own limits. Transfers also need the `route` scope. Withdrawals need only the `withdraw` scope. Only the Lean app resumes trading or raises a limit. See [Run the Lean MCP server](/build-with-ai#run-the-lean-mcp-server). **2026-11-12** 0.1.0: withdrawals to more chains **Withdrawals** * `POST /v1/withdrawals` pays USDC out on every chain the Lean app withdraws to: `destination.chain` is one of `polygon`, `arbitrum`, `base`, `optimism`, `ethereum`, `bsc` or `solana`, from either venue. A Solana withdrawal takes a Solana address, and every other chain a `0x` address; an address the chain cannot take is refused with `400 VALIDATION_ERROR`. `GET /v1/withdrawals` and `GET /v1/withdrawals/{id}` return the chain each withdrawal paid out on. See [Withdrawals through the API](/funding#withdrawals-through-the-api). **2026-11-12** 0.1.0: market search matches the Lean app search **Markets** * `GET /v1/markets` with `search` now finds markets the way the search box in the Lean app does. Every word is matched against Polymarket and Hyperliquid listing titles, with common team nicknames and small typos tried when few listings match. See [Search by text](/markets#search-by-text). * Only markets with a matching listing are returned, not every market of the same game. Results keep their order by start time, and the other filters and `cursor` work as before. * `search` no longer matches a market by its league. A league name such as `nba` finds only the markets with a listing whose title contains it, such as some Hyperliquid listings. Use `league` to list a league. * A request with `search` can return `503 UPSTREAM_ERROR` while search is briefly unavailable. Retry it. **2026-11-11** 0.1.0: filter positions, and find positions, orders and fills by text **Positions** * `GET /v1/positions` takes `venue`, `market_id` and `search`. With `venue`, Lean reads only that venue, so only it can be listed in `unavailable`. See [Read positions](/orders#read-positions). **Orders and fills** * `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, and pages with `next_cursor` as usual. See [Find by text](/orders#find-by-text). * `search` must be 1 to 100 characters once spaces at either end are removed. Anything else returns `400 VALIDATION_ERROR`. **2026-11-11** 0.1.0: venue symbols wherever a market id goes **Markets** * Every path and field that takes a market id also takes a venue symbol that names one market: a Polymarket token id, a Hyperliquid book coin (`#…`, written `%23…` in a path), or a leg `ticker` that pays only one outcome. Responses, orders, fills and filters always use the market id. See [Venue symbols](/markets#venue-symbols). * An order named by a venue symbol trades only that listing, and a buy Lean routes for it can still be paid from the other venue. Quotes, books, trades, prices and the `book` stream channel named by a symbol read only that listing, so they price what the order would trade. * A `book` stream channel takes a venue symbol as well as a market id. Each `book` frame now carries a top level `market_id`: the id or symbol the channel was subscribed with. The book inside it still carries the market id. See [Book](/streaming#book). * A symbol that names more than one market, such as a Polymarket condition id, returns `400 VALIDATION_ERROR`. An unknown symbol returns `404 NOT_FOUND`, as an unknown market id does. **Breaking, effective 2026-11-12:** in a REST path, query or body, a value that is neither a market id nor a venue symbol now returns `400 VALIDATION_ERROR` instead of `404 NOT_FOUND`. A `mkt_…` id Lean did not issue still returns `404 NOT_FOUND`. **2026-11-11** 0.1.0: transfers between your venues **Transfers** * `POST /v1/transfers/quote` shows what moving USDC from one of your account's venues to the other costs: `fee_usd`, `receive_usd`, `minimum_usd`, `available_usd` and `expires_at`. * `POST /v1/transfers` creates a transfer to the account's own balance on the other venue and returns the message to sign. Sending the same `client_transfer_id` again returns the same transfer. `POST /v1/transfers/{id}/execute` takes your signature, or `"delegated"` to have Lean sign. * `GET /v1/transfers` and `GET /v1/transfers/{id}` show each transfer from `awaiting_authorization` to `completed`, `failed` or `expired`. * Transfers count against the key's limits and stop while the key or account is paused. A quote still answers while paused. They need the `trade` and `route` scopes. Transfers are test mode only for now: a live key gets `503 FEATURE_DISABLED` with `details.reason: "LIVE_TRANSFERS_UNAVAILABLE"`. See [Transfers](/transfers). **Test mode** * `POST /v1/test/reset` also deletes the account's test transfers and returns `deleted_transfers`. **2026-11-11** 0.1.0: limit chases **Limit chases** * `POST /v1/limit-chases` rests a post only limit order on Polymarket a set distance behind the best price on its own side, given in `offset_ticks` or `offset_price`, and moves it as the book moves until it fills, is canceled or reaches `expires_at`. `price_limit` caps how far it follows. Hyperliquid does not run them, and a request for it is refused with `400 VALIDATION_ERROR`. `GET /v1/limit-chases`, `GET /v1/limit-chases/{id}` and `DELETE /v1/limit-chases/{id}` read and cancel them. Each one counts against the key's order and daily limits at the most it can trade for. A test key's limit chases follow the public book and fill in simulation. What one has filled is listed in `GET /v1/fills` with `order_id` `null`, as a live limit chase's fills are. `POST /v1/test/reset` also deletes them and returns `deleted_limit_chases`. See [Limit chases](/limit-chases). **2026-11-10** 0.1.0: market names on positions, older trades, fill filters and price candles **Fills** * Each fill in `GET /v1/fills` now carries `market_id`, the market it filled on, or `null` when Lean cannot tie it to one. * `GET /v1/fills` takes `market_id`, `filled_after` and `filled_before` to narrow the list to one market or a time window. See [Read fills](/orders#read-fills). **Positions** * Each position in `GET /v1/positions` and the `positions` stream channel now carries `title` and `outcome` beside `market_id`. All three are `null` whenever `market_id` is. See [Reconcile](/orders#reconcile). **Markets** * Each market now carries `title`, the fixture, proposition and outcome in words. * `GET /v1/markets/{id}/trades` returns `next_cursor`. Pass it as `cursor`, with the same market and `venue`, to read older trades. See [Recent trades](/markets#recent-trades). * New `GET /v1/markets/{id}/candles` returns open, high, low, close and volume per venue listing, from one second to two hours per candle. See [Price candles](/markets#price-candles). **2026-11-10** 0.1.0: order management **Orders** * `POST /v1/orders/cancel-batch` cancels up to 50 orders in one call, named by id, `client_order_id` or both, with one result for each name. See [Track and cancel](/orders#track-and-cancel). * `post_only` on `POST /v1/orders` and `POST /v1/orders/preview` places an order that only rests on the book. It runs on Hyperliquid, and an order that would trade at once is refused with `details.reason` `POST_ONLY_WOULD_CROSS`. See [Post only orders](/orders#post-only-orders). * `PATCH /v1/orders/{id}` changes the price, the size or both of a resting order. Lean cancels it and places a new order for the rest once the cancel is confirmed, answering `409` `REPLACEMENT_PENDING` until then, and the two name each other in the new `replaces_order_id` and `replaced_by_order_id` fields. The new order is placed as the key that sends the amend places one. See [Amend an order](/orders#amend-an-order). * `type: "market"` on `POST /v1/orders` and `POST /v1/orders/preview` trades at once with `limit_price` as an optional cap. Without one, a buy is capped at `0.99` and a sell at `0.01`. It needs `time_in_force` `ioc` or `fok`. See [Market orders](/orders#market-orders). * `time_in_force` `fok` fills an order in full at once or cancels all of it, and `gtd` rests an order until the new `expires_at`. Both run on Polymarket, and a request for Hyperliquid is refused with `400 VALIDATION_ERROR`. A `fok` buy is sized with `notional`. See [Fill or kill and expiring orders](/orders#fill-or-kill-and-expiring-orders). * Orders and previews show the new `type` and `expires_at` fields. **Withdrawals** * `POST /v1/withdrawals` withdraws cash from a venue to the address the request names, within the key's single and daily withdrawal limits. `GET /v1/withdrawals` and `GET /v1/withdrawals/{id}` read them back. It needs the new `withdraw` scope, which a live key takes when you turn on withdrawals for it in the Lean app. Both limits are optional. A request names its `source` venue and asset, its `destination` chain, asset and address, and the `amount`; the response adds the venue's `fee` and the `net_amount` quoted to arrive. A live withdrawal pays USDC on Polygon from Polymarket's pUSD and USDC on Arbitrum from Hyperliquid's USDC; any other pair is refused with `400`. It starts `pending`, and becomes `completed` or `failed` with a `failure_reason` as the venue settles it. The account must have trading enabled. `POST /v1/test/reset` also deletes test withdrawals and returns `deleted_withdrawals`. See [Withdrawals through the API](/funding#withdrawals-through-the-api). **Stop losses and take profits** * `POST /v1/stop-losses` sells shares the account holds on Polymarket once the best bid falls to a trigger price (`stop_loss`) or rises to it (`take_profit`). Hyperliquid does not run them, and a request for it is refused with `400 VALIDATION_ERROR`. `GET /v1/stop-losses`, `GET /v1/stop-losses/{id}` and `DELETE /v1/stop-losses/{id}` read and cancel them, and a cancel shows in the new `cancel_requested_at` field. Each sale counts against the key's order and daily limits at its trigger price. A test key's stop losses are checked and listed but never sell. `POST /v1/test/reset` also deletes them and returns `deleted_stop_losses`. See [Stop losses and take profits](/stop-losses). **2026-11-10** 0.1.0: more fixes from agent testing **Orders** * **Breaking, effective 2026-11-12:** when no venue that lists the market is open to the trading account, for example because the venue is not available in your region, `POST /v1/orders/preview` now returns the same `403` error as `POST /v1/orders` and the quote. It used to return `200` with a `TRADING_UNAVAILABLE` warning. See [Preview](/preview). * Order docs now say where fees are: an order has no fee field, and its fees are the `fee_usd` of its fills. A live Hyperliquid buy fill shows `fee_usd` `0` because the buy pays its fee when the position closes or settles. See [Limitations](/orders#limitations). * **Breaking, effective 2026-11-12:** an order you canceled reads `cancel_requested` until its venue confirms the cancel, then `canceled`, or `filled` if a fill beat the cancel. It used to keep reading `open` or `partially_filled` meanwhile. `GET /v1/orders` takes `status=cancel_requested`. See [Statuses](/statuses). * Orders carry `filled_notional_usd`, what the filled shares traded for across every leg. `notional_usd` stays the order at its own limit. See [Orders](/orders). * A sell at `0.01`, as a close without `limit_price` places, now shows the lowest limit among its legs as its `limit_price`, the protection the venue orders carry. It used to show `0.01`. * An `ioc` buy can send `notional`, the dollars to spend, in place of `quantity`. Lean walks the books within your limit and slippage bound and never spends more than `notional` before fees. `limit_price` is optional with it. `POST /v1/orders/preview` and `GET /v1/markets/{id}/quote` take it too. See [Buying a dollar amount](/orders#buying-a-dollar-amount). * An `ioc` buy sized with `notional` can now fill on Polymarket. One sized with `quantity` is still refused there, and the error now says to send `notional`. * Reading a filled Hyperliquid or Polymarket order with `GET /v1/orders/{id}` now brings its fills into `GET /v1/fills`. Before, the order could read `filled` a few seconds before its fills were listed. 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 later. See [Limitations](/orders#limitations). **Closing positions** * Each placed sell in a close is read back before the response, so a sell the venue matched at once reads `filled` with its filled quantity and average price. It used to read as first placed. * A close scoped to one market no longer includes positions that can't be matched to a market the API trades. A close of every position still includes them. **Test mode** * A test buy paid from the other venue now fills at the asks that venue's public book shows. When those asks can't fill the whole size within the limit, the buy is refused with `422 VALIDATION_ERROR`, as a live one is. It used to fill at the limit. See [Test mode](/test-mode). * Test positions now carry `mark_price`, the best bid on the venue's public book, and `unrealized_pnl_usd`. Both used to be `null`. **Streaming** * The [Streaming](/streaming) page names the WebSocket URL, `wss://api.lean.xyz/v1/ws`. **2026-11-08** 0.1.0: fixes from agent testing **Markets** * `GET /v1/markets` takes `venue`, `polymarket` or `hyperliquid`, to list only markets with a leg on that venue. See [Query parameters](/markets#query-parameters). * A Polymarket leg the venue no longer trades now reads `tradable: false`, and a market with no tradable open leg reads `closed`. * **Breaking, effective 2026-11-12:** `GET /v1/markets` refuses a query parameter it does not know with `400 VALIDATION_ERROR`. It used to ignore it and return the whole list. * **Breaking, effective 2026-11-12:** a request that needs the book of a market Polymarket has stopped trading returns `409 CONFLICT` with `details.reason: "MARKET_NOT_TRADABLE"`. It used to return `503 UPSTREAM_ERROR`. See [Errors](/errors#codes). **Orders and account** * Each item of `GET /v1/positions` carries `market_id`, the Lean market the position belongs to. `market_id` is `null` when no listed market currently matches the holding, for example a fixture that settled more than 7 days ago. It 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. * `POST /v1/orders/preview` prices `route_plan` at the order's limit. A limit at the best ask no longer warns, and a buy limit below the book reports `limited_by: "depth"`, not `"funds"`. The `LIMIT_BELOW_ROUTE_PRICE` preview warning is gone: `ROUTE_LIMITED` covers a limit the books cannot fill. See [Preview](/preview). * `GET /v1/balances` answers within about 3 seconds. A venue that has not answered by then is listed in `unavailable`, and the other venues are still returned. **2026-11-02** 0.1.0: one-call orders across venues **Orders** * `POST /v1/orders` now buys with cash held on the other venue in the same call. Lean moves the cash and buys on the venue with the book. The response carries `route: { funding_venue, execution_venue }`, or `route: null` when nothing was moved. See [Paying from the other venue](/orders#paying-from-the-other-venue). * It needs the key's `route` scope, trading enabled in the Lean app for a live key, and routing available. If any is missing, the order is refused as before with `422 VALIDATION_ERROR` and `details.reason: "INSUFFICIENT_FUNDS"`. * **Read and trade** keys made in the Lean app now include the `route` scope, in test and live mode. Keys made earlier keep their scopes: create a new key, or one with `route` through `POST /api-keys`, to use one-call routing. See [Authentication](/authentication#create-a-key). * Test keys get the same one call against the simulator. No real funds move. * `POST /v1/routed-orders` and `POST /v1/routed-orders/{id}/execute` remain for programs that sign each payment themselves. See [Advanced: self-signed routed orders](/routed-orders). * `venues` on `POST /v1/orders` keeps an order on the venues it names. A single venue places the order only there, or refuses it. The list can only narrow the account's venues. See [Choosing venues](/orders#choosing-venues). * `POST /v1/orders/preview` honors `venues`, and shows the route a buy would take in `route`. * `best_price` on `POST /v1/orders` and `POST /v1/orders/preview` pays from the other venue whenever that costs less in all than buying where the account's cash is. It is `false` by default. See [Best price across venues](/orders#best-price-across-venues). Nothing breaking: an order that would have been refused with `INSUFFICIENT_FUNDS` can now fill. **0.1.0** Preview release The first public preview of the Lean API, served at `https://api.lean.xyz/v1`. **Markets** * `GET /v1/markets` lists canonical sports markets, without naming a venue. Each leg carries the venue's resolution terms, and each market says whether its venue listings were reviewed as the same proposition. See [Markets](/markets#legs). * `GET /v1/markets/{id}/quote` quotes a market across the venues that list it. **Orders** * `POST /v1/orders/preview` prices an order and shows the route Lean would take. * `POST /v1/orders` places an order on Hyperliquid, Polymarket or both. `client_order_id` makes retries safe. * `GET /v1/orders`, `GET /v1/orders/{id}` and `POST /v1/orders/{id}/cancel` reconcile and cancel orders. Each order has `legs`, one per venue order, each with its own `status` and `status_reason`, and an `avg_fill_price` for the whole order. * Venue outcomes are order statuses: an unfilled `ioc` order is `canceled`, a venue refusal is `rejected`, and a submit the venue did not confirm is `unconfirmed`. See [Order statuses](/statuses). **Account** * `GET /v1/balances` and `GET /v1/positions` read each venue, and report a venue that cannot be read as unavailable rather than as zero. * `POST /v1/account/pause` lets a key stop new orders for itself or its whole trading account. Only the Lean dashboard resumes. See [Pause trading](/orders#pause-trading). **Keys** * `POST /api-keys`, `GET /api-keys` and `DELETE /api-keys/{id}` manage keys, each with scopes and per order and daily limits. * Test keys simulate fills against simulated balances. See [Test mode](/test-mode). # Errors Source: https://lean.mintlify.app/errors Error codes, venue codes and what to do about each. Every error uses the same envelope: ```json theme={"dark"} { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "", "details": { "venue_code": "INSUFFICIENT_BALANCE", "order_id": "" } }, "meta": { "requestId": "" } } ``` | Field | Meaning | | - | - | | `error.code` | A stable `SCREAMING_SNAKE_CASE` code. Branch on this, not on `message`. | | `error.message` | A readable explanation. It may change. | | `error.details.venue_code` | When a venue refused the order: the specific reason, for example `INSUFFICIENT_BALANCE`. | | `error.details.order_id` | When the error concerns an order Lean recorded: its Lean ID. Read it back with `GET /v1/orders/{id}`. | | `error.details.reason` | On `422`: why Lean refused the order. On `403 FORBIDDEN` from `POST /v1/routed-orders/{id}/execute`: `ACCOUNT_NOT_DELEGATED`. On `503 FEATURE_DISABLED` at placement: `LIVE_TRADING_DISABLED` or `TRADING_PAUSED`. | | `error.details.scope` | With `TRADING_PAUSED`: what is paused, `api_key` or `trading_account`. | | `meta.requestId` | Also sent as the `X-Request-ID` header. Include it when you report a problem. | `details` can carry more fields specific to the venue. Ignore fields you do not recognize. `details` takes one of two shapes: * When the body, query or path failed validation, `details` is a list with one entry per problem: `path` names the field, with nested fields joined by `.` (such as `venues.0`), and `message` says what is wrong with it. `error.message` names the first problem as `path: message`, and adds how many more `details` lists. * Otherwise `details` is an object with the fields above, or it is left out. ```json theme={"dark"} { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "market_ids: At most 25 market ids per request; split larger sets across requests", "details": [ { "path": "market_ids", "message": "At most 25 market ids per request; split larger sets across requests" } ] }, "meta": { "requestId": "" } } ``` ## Codes | HTTP | `code` | When | What to do | | - | - | - | - | | 400 | `VALIDATION_ERROR` | Malformed body, a body sent without `Content-Type: application/json`, a query parameter the endpoint does not take, a price outside (0, 1), a size the venue cannot take, a bad cursor or one another list issued, a closed market, a value in a market ID field that is neither a market ID nor a venue symbol, or a venue symbol that names more than one market. `details` lists each invalid field when the body or query failed validation. | Fix the request. | | 401 | `UNAUTHORIZED` | Missing, malformed, unknown, expired or revoked key. | Check the key. | | 402 | `VALIDATION_ERROR` | The venue account cannot cover the order. `details.venue_code` is `INSUFFICIENT_BALANCE`. | Reduce the size or add funds. See [Funding](/funding). | | 403 | `FORBIDDEN` | The key lacks the scope, the account has no API access, or trading on the venue is not available to the account. | Use a key with `trade`, or check the account. | | 403 | `FORBIDDEN` | On a live Kalshi or Polymarket US order: the user has not connected an API key for that venue in the Lean app. | Connect the venue's API key in the Lean app, or leave the venue out with `venues`. See [Kalshi and Polymarket US](/orders#kalshi-and-polymarket-us). | | 403 | `FORBIDDEN` | On `POST /v1/routed-orders/{id}/execute` with `"authorization": "delegated"` and a live key: the account has not enabled trading in the Lean app. `details.reason` is `ACCOUNT_NOT_DELEGATED`. | Enable trading in the Lean app, or send a `payment_signature` instead. See [Advanced: self-signed routed orders](/routed-orders#letting-lean-sign). | | 400 | `VALIDATION_ERROR` | On `POST /v1/withdrawals`: the `source` and `destination` are not a pair the venue pays out on, or `destination.address` does not suit `destination.chain`. Polymarket pays `pusd` out as `usdc`, and Hyperliquid pays `usdc` out as `usdc`, on `polygon`, `arbitrum`, `base`, `optimism`, `ethereum`, `bsc` or `solana`. The message says what is supported. | Send a supported pair, with a `0x` address for every chain except `solana`. See [Withdrawals through the API](/funding#withdrawals-through-the-api). | | 403 | `FORBIDDEN` | On `POST /v1/withdrawals`: the key lacks the `withdraw` scope, or a live key's account has not enabled trading in the Lean app (`details.reason` is `ACCOUNT_NOT_DELEGATED`). | Use a key created with `withdraw`, or enable trading in the Lean app. See [Withdrawals through the API](/funding#withdrawals-through-the-api). | | 400 | `VALIDATION_ERROR` | On `POST /v1/stop-losses`: the trigger price, slippage limit, quantity or expiry does not fit the market, the best bid already meets the trigger (a `stop_loss` at or above the bid or on a market with no bid, a `take_profit` at or below the bid), or the quantity is more than the account holds beyond its other stop losses and resting sells. On `DELETE /v1/stop-losses/{id}`: the stop loss has already ended. | Fix the request, or read the stop loss back. See [Stop losses and take profits](/stop-losses). | | 400 | `VALIDATION_ERROR` | On `POST /v1/limit-chases`: the offset, price limit, quantity or expiry does not fit the market, a test key's buy costs more than its simulated cash on the venue, or a sell is more than the account holds beyond its resting sells and stop losses. On `DELETE /v1/limit-chases/{id}`: the limit chase has already ended. | Fix the request, or read the limit chase back. See [Limit chases](/limit-chases). | | 404 | `NOT_FOUND` | Unknown market ID, a quote for a market with no venue listing, an order not on this key's account, an order from the other mode (a live order read with a test key, or the other way round), or a path or method no endpoint serves. A request without a valid key gets `401` first. | Check the ID, the key and the path. | | 409 | `CONFLICT` | `client_transfer_id` reused with a different body. `details.transfer_id` is the original. | Read the transfer back. | | 409 | `CONFLICT` | `client_order_id` reused with a different body (`details.order_id` is the original), or a cancel of a finished order or one the venue has not acknowledged yet. Test orders are always finished. | Read the order back. | | 409 | `CONFLICT` | On `POST /v1/withdrawals`: `client_withdrawal_id` reused with a different venue, amount or destination (`details.withdrawal_id` is the original), the venue wallet is not set up, or another Hyperliquid withdrawal for the account is still settling (`details.reason` is `WITHDRAWAL_IN_PROGRESS`). | Read the withdrawal back, or wait for the other one to settle. | | 409 | `CONFLICT` | On `PATCH /v1/orders/{id}`: the order cannot be amended. `details.reason` is `ORDER_NOT_OPEN` (it finished), `ORDER_REPLACED` (`details.replaced_by_order_id` names the order that replaced it), `ORDER_NOT_AMENDABLE` (it is routed, split or `ioc`) or `REPLACEMENT_PENDING` (the order's cancel was requested and nothing was placed in its place yet; send the same amend again once it reads `canceled`). | Read the order back. See [Amend an order](/orders#amend-an-order). | | 409 | `CONFLICT` | A venue has stopped trading the market, so it has no book to read, quote or fill against. `details.reason` is `MARKET_NOT_TRADABLE`. | Use a leg whose `tradable` is `true`, or another market. | | 409 | `CONFLICT` | On placement: a venue the order needs is not ready for API orders on this account, for example its wallet changed or its signing is not delegated. | Fix the account's venue setup, then retry with the same `client_order_id`. | | 422 | `VALIDATION_ERROR` | Lean refused the order before it reached a venue. See `details.reason` below. | Change the order, or add funds. | | 429 | `RATE_LIMITED` | Over 5 requests a second per key (bursts of 20), or the venue throttled the request. Cancels have their own budget of 10 a second (bursts of 40). | Wait for `Retry-After` (seconds) when it is sent, then retry. | | 500 | `INTERNAL_ERROR` | An unexpected error inside Lean. | Retry reads. For an order, read it back by `client_order_id` first. Report `meta.requestId`. | | 503 | `UPSTREAM_ERROR` | On placement: a venue failed before anything was placed. On a quote or preview: the venue failed or answered with something Lean could not read. | Nothing was placed. Look the order up by `client_order_id` before you send it again. | | 503 | `UPSTREAM_ERROR` | On a quote, preview or order that needs a Polymarket US book: Lean has not loaded that market's book yet. `Retry-After` is sent. Nothing was placed. | Wait for `Retry-After`, then send the same request again. | | 503 | `UPSTREAM_ERROR` | On `GET /v1/orders/{id}`: a venue could not be read or reached, and the stored order is unchanged. On a cancel: a venue could not be reached, so its leg was not canceled, though legs on other venues may be. | Read the order again. Do not assume a cancel happened until the order reads `canceled`. | | 503 | `UPSTREAM_ERROR` | A venue or a Lean dependency timed out or dropped the connection, or the request lost a database conflict. `Retry-After` is sent. On placement the order may or may not have reached the venue. | Wait for `Retry-After`, then retry. For an order, look it up by `client_order_id` first and resend with the same `client_order_id`. | | 503 | `UPSTREAM_ERROR` | On `POST /v1/withdrawals`: the venue could not be read or could not prepare the withdrawal. Nothing was recorded or paid. | Retry with the same `client_withdrawal_id`. | | 503 | `UPSTREAM_ERROR` | On `POST /v1/stop-losses`: the market's book could not be read to check the trigger price against the best bid. Nothing was created. | Retry. See [Triggers the bid already meets](/stop-losses#triggers-the-bid-already-meets). | | 503 | `FEATURE_DISABLED` | On placement with a live key: Lean has paused live trading platform wide. `details.reason` is `LIVE_TRADING_DISABLED`. | Retry later, or keep building with a test key. Reads and cancels still work. See [Test mode](/test-mode#go-live). | | 503 | `FEATURE_DISABLED` | On placement: this key or its trading account is paused. `details.reason` is `TRADING_PAUSED` and `details.scope` is `api_key` or `trading_account`. | Resume from the Lean dashboard. Reads and cancels still work. See [Pause trading](/orders#pause-trading). | | 503 | `FEATURE_DISABLED` | On a quote: routing is not available. On an order: a venue's order placement is switched off. | Retry later. | | 503 | `FEATURE_DISABLED` | On a transfer with a live key: live transfers are not available yet. `details.reason` is `LIVE_TRANSFERS_UNAVAILABLE`. Nothing moved. | Use a test key, or pay from the other venue with `POST /v1/orders`. See [Transfers](/transfers). | | 503 | `INTERNAL_ERROR` | Lean or the venue is temporarily unavailable, for example Lean cannot check the key's rate limit. Lean does not serve a request it cannot rate limit. | Retry later with the same `client_order_id`. | Every code is one of `VALIDATION_ERROR`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`, `RATE_LIMITED`, `UPSTREAM_ERROR`, `INTERNAL_ERROR` and `FEATURE_DISABLED`. The error schema in the OpenAPI spec also lists `CONDITIONAL_SELL_REJECTED` and `CONDITIONAL_SELL_ACTIVE`. They belong to conditional sells in the Lean app, and no `/v1` endpoint returns them. New `details.reason` and `details.venue_code` values can appear without a new version; treat one you do not recognize by its HTTP status. See [Versioning](/versioning). ### `details.reason` on 422 | `details.reason` | Meaning | | - | - | | `ORDER_NOTIONAL_LIMIT` | A buy's `quantity × limit_price` is above the key's per order limit. A sell is never refused for it. | | `DAILY_NOTIONAL_LIMIT` | The buy, limit chase or transfer would push the key over its rolling 24 hour limit, which all of them share. Sells count toward the day but are never refused for it. | | `BELOW_VENUE_MINIMUM` | The order is below the minimum of every venue that could place it. `details.min_order_notional_micros` is the smallest notional accepted. On a transfer: `amount_usd` is below the route minimum, `details.minimum_usd`. | | `INSUFFICIENT_FUNDS` | The trading account cannot pay for the order on any venue that could place it, and Lean could not pay for it with cash from the other venue. On a transfer: `from_venue` can't send `amount_usd`; `details.available_usd` is what it can send. | | `NO_EXECUTABLE_VENUE` | No venue can place this market today. On `POST /v1/stop-losses` and `POST /v1/limit-chases`, the market cannot be traded on the `venue` you named. | | `VENUE_NOT_ALLOWED` | `venues` names a venue the trading account does not allow, or the account allows no venue that lists the market. `details.allowed_venues` lists the venues it allows. On `POST /v1/stop-losses` and `POST /v1/limit-chases`, the account does not allow the `venue` you named. | | `INSUFFICIENT_HOLDINGS` | A sell for more shares than the trading account holds. | | `INSUFFICIENT_DEPTH` | An `all_or_none` order the books can't fill in full within `limit_price` and the slippage bound. | | `ROUTE_NOT_EXECUTABLE`, `LIMIT_BELOW_ROUTE_PRICE` | On a [routed order](/routed-orders): no route can fill the whole quantity within the limit. | | `POST_ONLY_WOULD_CROSS` | A `post_only` order would trade at once against the books. `details.executable_quantity` is how much would fill. See [Post only orders](/orders#post-only-orders). | | `WITHDRAWAL_LIMIT_EXCEEDED` | A withdrawal is above the key's single withdrawal limit. `details.limit_usd` is the limit. | | `DAILY_WITHDRAWAL_LIMIT_EXCEEDED` | A withdrawal would push the key over its rolling 24 hour withdrawal limit. `details.limit_usd` is the limit and `details.used_usd` what the key has withdrawn in that time. | | `INSUFFICIENT_BALANCE` | A withdrawal is above the cash available on the venue. `details.available_usd` is what can be withdrawn. | > [!NOTE] > > Never resend an order with a new `client_order_id` after a timeout, an error, or an `unconfirmed` > status. Look it up by the original ID first. A venue outcome after placement is a `200` with the > order's `status`, not an error. See [What placement returns](/orders#what-placement-returns). # Funding Source: https://lean.mintlify.app/funding How money reaches each venue, and the one deposit route to avoid. Each venue keeps its own balance: USDC in Hyperliquid spot, pUSD on Polymarket, and USD on Kalshi and Polymarket US. `GET /v1/balances` shows them all. Lean routes an order to the venues that can pay for it, so fund the venues you want orders to reach. Deposits, withdrawals and transfers through Lean cover Polymarket and Hyperliquid only. Fund your Kalshi and Polymarket US accounts on those venues directly. A test key needs no funding. It trades against simulated balances. See [Test mode and live mode](/test-mode). ## Deposit through Lean's addresses only Send funds only to the deposit addresses Lean gives the trading account. Each address bridges into the right balance for you: | Venue | Route | Lands as | | - | - | - | | Hyperliquid | Relay | USDC in Hyperliquid spot | | Polymarket | Polymarket bridge | pUSD on Polygon | Supported assets include USDC, USDT, ETH and DAI on Polygon, Base, Arbitrum, Optimism, Ethereum, BSC and Solana. The Polymarket bridge sets a minimum deposit per asset, and a deposit below it may not be credited. Relay publishes no fixed minimum for Hyperliquid deposits, and neither does a pUSD transfer straight to the Polymarket wallet. > [!WARNING] > > Never send funds to Hyperliquid's own bridge. A deposit there lands in Hyperliquid perps, not in > spot where Lean's orders trade, so it is not available to the API. ## Network fees A deposit is an ordinary token transfer: the sender pays that network's usual fee. After that, you need no gas. Hyperliquid orders are signed actions with no gas, and Polymarket actions are paid for by Polymarket's relayer. ## Deposits through the API * [List deposit assets](/api-reference/deposits/list-deposit-assets) shows the chains and tokens each venue accepts. `min_deposit_usd` is the route's minimum, or `null` when the route publishes none. * [Get deposit addresses](/api-reference/deposits/list-deposit-addresses) returns your addresses, and [Create deposit addresses](/api-reference/deposits/create-deposit-addresses) creates any that are missing. Creating is idempotent. * [Get balances](/api-reference/account/list-balances) shows funds once they arrive. ## Withdrawals through the API A key can withdraw only when it was created for it. Create the key in the Lean app under Settings, API keys, or with [Create an API key](/api-reference/api-keys/create-api-key), and send: * `scopes` with `withdraw`. A key without it is refused with `403 FORBIDDEN`. The `withdraw` scope is separate from `trade`, so a key that trades cannot withdraw unless you add it. * `maxWithdrawalMicros`, the largest single withdrawal, and `dailyWithdrawalLimitMicros`, the total the key may withdraw in any rolling 24 hours. Both are optional and in millionths of a dollar. Leave one out for no limit of that kind. When you set both, the daily limit must be at least the single one. A withdrawal names where the money comes from, where it goes and how much moves: * `source` is the venue and the asset held there. * `destination` is the chain, the asset and the address paid. * `amount` is how much of the source asset leaves the venue. Each venue pays out USDC, on any of the chains the Lean app withdraws to: | `source` | `destination` asset | | - | - | | `polymarket`, `pusd` | `usdc` | | `hyperliquid`, `usdc` | `usdc` | `destination.chain` is one of `polygon`, `arbitrum`, `base`, `optimism`, `ethereum`, `bsc` or `solana`. The address must suit the chain: a `0x` address for every chain except `solana`, which takes a Solana address. Any other pair, or an address the chain cannot take, is refused with `400 VALIDATION_ERROR`, and the message says what is supported. A live withdrawal sends real funds: * The venue's fee comes out of the amount. The response gives `fee` and `net_amount`, the amount the destination is quoted to receive. Both come from the venue's quote when the withdrawal is made, so the amount that arrives can differ slightly. * The account must have trading enabled. Creating a live key that can trade or withdraw in the Lean app enables it for the whole account, so there is nothing else to switch on. If it isn't enabled, the withdrawal is refused with `403 FORBIDDEN` and `details.reason` `ACCOUNT_NOT_DELEGATED`. * Pausing trading for the key or its account also pauses its withdrawals. A paused key's withdrawal is refused with `503 FEATURE_DISABLED` and `details.reason` `TRADING_PAUSED`. * Each withdrawal is submitted to the venue once. It starts `pending` and becomes `completed` once the venue pays it, or `failed` when the venue refuses it. A failed withdrawal pays nothing, even though it still shows the quoted `fee` and `net_amount`, and `failure_reason` says why. Read it back with [Get a withdrawal](/api-reference/withdrawals/retrieve-withdrawal) to follow it. * A Polymarket withdrawal is `completed` once the pUSD has left the account for Polymarket's bridge. The bridge then pays the USDC on the chain you named, usually within a few minutes, so check the destination before relying on the funds. A Hyperliquid withdrawal is `completed` once the USDC has arrived on the chain you named. * Only one Hyperliquid withdrawal runs at a time for an account. Another one started before it settles is refused with `409 CONFLICT` and `details.reason` `WITHDRAWAL_IN_PROGRESS`. A test withdrawal takes simulated cash from a venue's test balance, moves no real funds, charges no fee and is `completed` at once. ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/withdrawals" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source": { "venue": "polymarket", "asset": "pusd" }, "destination": { "chain": "polygon", "asset": "usdc", "address": "" }, "amount": "25", "client_withdrawal_id": "payout-2026-11-10" }' ``` The response echoes `source`, `destination` and `amount`, and adds `fee`, `net_amount`, `status` and `failure_reason`. [Get a withdrawal](/api-reference/withdrawals/retrieve-withdrawal) and [List withdrawals](/api-reference/withdrawals/list-withdrawals) return the same fields. * `client_withdrawal_id` makes the call safe to repeat. Sending the same request again returns the first withdrawal and takes nothing more. Reusing the ID with a different venue, amount or destination is refused with `409 CONFLICT`, and `details.withdrawal_id` names the first one. * A withdrawal over the key's single limit, over its daily limit or over the venue's available cash is refused with `422 VALIDATION_ERROR`. See [Errors](/errors#details-reason-on-422). * [List withdrawals](/api-reference/withdrawals/list-withdrawals) shows the account's withdrawals in the key's mode, newest first, with `next_cursor` for the next page and an optional `venue` filter. [Get a withdrawal](/api-reference/withdrawals/retrieve-withdrawal) reads one by `id`. * [Reset test mode](/api-reference/test-mode/reset-test-mode) deletes the test withdrawals and gives their cash back. ## Using funds on either venue You don't need to move funds between venues. Lean routes each order to the best venue, and when the cash is on the other venue, `POST /v1/orders` moves it and buys in the same call. See [Paying from the other venue](/orders#paying-from-the-other-venue). To sign that payment yourself, see [Advanced: self-signed routed orders](/routed-orders). To move cash between your own venues without an order, use [Transfers](/transfers). They work with test keys today. Shares can't move between venues. A sell is placed on the venues that hold the shares. # Lean API v0.1 Source: https://lean.mintlify.app/index List canonical sports markets, quote them, place orders and reconcile, without naming a venue. **v0.1**Sports markets in preview Trade sports markets from code. One API for canonical sports markets, quotes and orders. Name the outcome you want; Lean finds the venue across Kalshi, Polymarket, Polymarket US and Hyperliquid, prices the route and places the order. [Start the quickstart](/quickstart) [Browse the API reference](/api-reference/markets/list-markets) **REST and WebSocket**One JSON envelope**Idempotent orders**Retry without doubling**OpenAPI 3**Generate any client ## One call to buy With a test key, nothing real moves: ```bash theme={"dark"} curl -sS -X POST "https://api.lean.xyz/v1/orders" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "client_order_id": "bot-2026-11-02-0001", "market_id": "mkt_...", "action": "buy", "quantity": "5", "limit_price": "0.42", "time_in_force": "ioc" }' ``` Polymarket takes `ioc` buys by dollar amount only. On a market only Polymarket lists, send `"notional": "25"` in place of `quantity`; see [Limitations](/orders#limitations). The response is the order. If the book was on Polymarket and the account's cash on Hyperliquid, or the other way round, Lean moved the cash and bought on the venue with the book, and `route` says so; otherwise `route` is `null`: ```json theme={"dark"} { "success": true, "data": { "id": "3f6c2a8e-91d4-4b7a-8c25-0e4d7b19a6f3", "client_order_id": "bot-2026-11-02-0001", "status": "filled", "filled_quantity": "5", "avg_fill_price": "0.42", "route": { "funding_venue": "hyperliquid", "execution_venue": "polymarket" }, "livemode": false }, "meta": { "requestId": "" } } ``` Read it back by `id`: ```bash theme={"dark"} curl -sS "https://api.lean.xyz/v1/orders/3f6c2a8e-91d4-4b7a-8c25-0e4d7b19a6f3" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` See [Orders and idempotency](/orders) for every field. ## From a new key to a reconciled trade in five calls Every step is a plain HTTPS request with a bearer key. The [TypeScript SDK](/typescript-sdk) and the [Rust SDK](/rust-sdk) make each one a typed method.
  1. 01 Create a key Start with a test key that simulates fills. Each key has its own per order and daily limit. [Authentication](/authentication)
  2. 02 Find a market List canonical sports markets. You name the outcome; Lean knows the venues. [GET`/v1/markets`](/markets)
  3. 03 Place the order One limit order with your own ID, on any venue and safe to retry on a dropped connection. [POST`/v1/orders`](/orders)
  4. 04 Read it back Read the order by its ID to see its status and fills. [GET`/v1/orders/{id}`](/orders#track-and-cancel)
  5. 05 Reconcile Read positions and balances back until the books agree. [GET`/v1/positions`](/orders#reconcile)
## Designed for programs that move money > [card] [Preview before you trade](/preview) > > `POST /v1/orders/preview` takes the exact order body and returns the venue, route plan and > refusals, with a read only key. > [card] [Retries are safe](/orders#idempotency) > > Every order carries your `client_order_id`. Sending it again returns the original order, never > a second order. > [card] [Limits live on the key](/authentication) > > Each key has its own per order and rolling daily notional limit, checked before anything > reaches a venue. > [card] [One shape everywhere](/errors) > > `{ success, data, meta }` on success and a stable error `code` on failure, with a request ID to > quote when you report a problem. ## Conventions * Every response uses one envelope: `{ "success": true, "data": …, "meta": … }` or `{ "success": false, "error": { "code", "message", "details" }, "meta": … }`. * `meta.requestId` (also sent as the `X-Request-ID` header) identifies the request. Include it when you report a problem. * Prices are decimal strings in dollars per share, strictly between `0` and `1`. * Quantities are shares, as decimal strings. Amounts are USD, as decimal strings. * Field names are `snake_case`. * `data.livemode` in every successful response is `false` for a test key and `true` for a live key. See [Test mode and live mode](/test-mode). ## What the API covers | Capability | Endpoint | | - | - | | Discover markets | `GET /v1/markets`, `GET /v1/markets/{id}` | | Prices, depth, trades and candles | `GET /v1/prices`, `GET /v1/markets/{id}/book`, `GET /v1/markets/{id}/trades`, `GET /v1/markets/{id}/candles` | | Quote across venues | `GET /v1/markets/{id}/quote` | | Preview orders without placing them | `POST /v1/orders/preview`, `POST /v1/orders/preview-batch` | | Place an order on any venue | `POST /v1/orders` | | Read, amend and cancel orders | `GET /v1/orders`, `GET /v1/orders/{id}`, `PATCH /v1/orders/{id}`, `POST /v1/orders/{id}/cancel`, `POST /v1/orders/cancel-batch`, `POST /v1/orders/cancel-all`, `POST /v1/orders/cancel-after` | | Stop losses and limit chases | `/v1/stop-losses`, `/v1/limit-chases` | | Fills | `GET /v1/fills` | | Balances, positions, PnL and risk | `GET /v1/balances`, `GET /v1/positions`, `POST /v1/positions/close`, `GET /v1/pnl`, `GET /v1/pnl/history`, `GET /v1/risk` | | Deposits, on Polymarket and Hyperliquid | `GET /v1/deposits/assets`, `GET /v1/deposits/addresses`, `POST /v1/deposits/addresses` | | Withdrawals, from Polymarket and Hyperliquid | `POST /v1/withdrawals`, `GET /v1/withdrawals`, `GET /v1/withdrawals/{id}` | | Transfers between Polymarket and Hyperliquid | `POST /v1/transfers/quote`, `POST /v1/transfers`, `POST /v1/transfers/{id}/execute`, `GET /v1/transfers` | | Live updates | `POST /v1/ws/token`, then the `/v1/ws` WebSocket | | Account controls | `GET /v1/account/config`, `POST /v1/account/limits`, `POST /v1/account/pause` | | Test mode | `POST /v1/test/reset` | | Self-signed routed orders, on Polymarket and Hyperliquid ([advanced](/routed-orders)) | `POST /v1/routed-orders`, `POST /v1/routed-orders/{id}/execute` | | Manage API keys, signed in | `POST /api-keys`, `GET /api-keys`, `DELETE /api-keys/{id}` | ### How it works * Markets cover the full game of a sports match only. Halves, quarters and periods are not listed. * Lean chooses the venues. A buy is split across eligible venues by best price; a sell takes the best bids across the venues that hold the shares. * Between Polymarket and Hyperliquid, a buy can pay with cash on the other venue: Lean moves it and buys on the venue with the book, in the same call. Kalshi and Polymarket US orders pay with the cash already on that venue. Shares can't move between venues. * Live orders route to Kalshi, Polymarket, Polymarket US and Hyperliquid. Test orders are simulated and never reach a venue. * Kalshi and Polymarket US are user wide accounts: every trading account of a user shares the same Kalshi and Polymarket US balances and positions, and live orders there use the venue API key the user connected in the Lean app. * Deposits, transfers, withdrawals and routed orders cover Polymarket and Hyperliquid only. * Quotes price buys, and sells of shares the account holds. * Hyperliquid does not cancel resting orders at kickoff. See [Orders](/orders#kickoff). # Limit chases Source: https://lean.mintlify.app/limit-chases Rest a limit order near the best price and let Lean move it as the book moves. A limit chase rests a post only limit order a set distance behind the best price on its own side of the book, and moves it whenever that price moves, until the order fills, you cancel it, or it expires. A buy follows the best bid and a sell follows the best ask. Lean moves the order for you, so your program does not need to stay connected. Limit chases run on every venue: Kalshi, Polymarket, Polymarket US and Hyperliquid. This example uses a test key, so nothing real moves: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/limit-chases" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "market_id": "'"$MARKET_ID"'", "venue": "polymarket", "action": "buy", "quantity": "25", "offset_ticks": 1, "price_limit": "0.45" }' ``` | Field | Meaning | | - | - | | `market_id` | A `mkt_…` ID from `GET /v1/markets`. | | `venue` | `kalshi`, `polymarket`, `polymarket_us` or `hyperliquid`: the venue the order rests on. | | `action` | `buy` or `sell`. | | `quantity` | Shares to buy or sell, as a decimal string. | | `offset_ticks` | Optional. How many price ticks behind the best price the order rests, from `0` to `10`. The default is `0`, resting at the best price. | | `offset_price` | Optional. The same distance in dollars, from `0` to `0.1`. Give `offset_ticks` or `offset_price`, not both. | | `price_limit` | Optional. The worst price the order rests at, in dollars: a buy never rests above it and a sell never below it. It must fit the market's price ticks. Leave it out to follow the book wherever it goes. | | `expires_at` | Optional. When the limit chase lapses if it has not filled, as an ISO 8601 time. Leave it out to keep it until you cancel it. | The key needs the `trade` scope. The answer is `200` with the limit chase, which reads `active` while it follows the book. `current_price` is the price the order rests at now, and is `null` while the chase waits for a book to follow. ## How the order moves Lean places the order at the best price on its own side less the offset for a buy, or plus the offset for a sell. It never rests at a price that would trade at once against the other side of the book, and never beyond `price_limit`. When the best price moves by a cent or more, Lean cancels the order and places it again at the new price. Each fill adds to `filled_quantity` and `avg_fill_price`, and the rest keeps following the book. | `status` | Final | Meaning | | - | - | - | | `active` | No | Resting on the book and following the best price. | | `filled` | Yes | Every share bought or sold. | | `canceled` | Yes | Canceled by you. Shares already bought or sold stay with the account. | | `expired` | Yes | `expires_at` passed before the order filled. | | `failed` | Yes | Lean could not keep the order on the book, for example because the venue kept refusing it. | ## Limits on what can be traded * A sell takes shares the account holds, and shares already offered by a resting sell order or covered by a stop loss count as taken. A sell above what is left is refused with `400 VALIDATION_ERROR`. * A test key's buy needs enough simulated cash on the venue for `quantity` shares at `price_limit`, or at \$1 a share without one, and is refused with `400 VALIDATION_ERROR` otherwise. A live key's buy is not checked against the account's cash when you create it, so check `GET /v1/balances` first: the venue refuses an order the account can't pay for. * An order must be at least the market's minimum number of shares. * The market must be open and must trade on the venue you name. A market that cannot be traded on that venue is refused with `422 VALIDATION_ERROR` and `details.reason: "NO_EXECUTABLE_VENUE"`, and a venue the trading account does not allow with `details.reason: "VENUE_NOT_ALLOWED"`. * A limit chase counts against the key's limits as an order of the most it can trade for, from when it is created: a buy as `quantity` shares at `price_limit`, or at the top price of \$1 a share without one, and a sell at that same top price. A buy above the key's per order limit is refused with `details.reason: "ORDER_NOTIONAL_LIMIT"`, and one past the key's or account's daily limit with `details.reason: "DAILY_NOTIONAL_LIMIT"`. A sell counts toward the day too, but only takes risk off, so neither limit refuses it. A test key's limit chases count against its own limits. * Creating a limit chase is refused with `503 FEATURE_DISABLED` while trading is paused, or while Lean has paused limit chases on the venue. See [Pause trading](/orders#pause-trading). ## Track and cancel `GET /v1/limit-chases` lists the limit chases of the key's trading account, newest first: every one still active, and those that ended in the last hour. A live key also sees the limit chases made in the Lean app on that account. `GET /v1/limit-chases/{id}` reads one. Cancel one with `DELETE /v1/limit-chases/{id}`: ```bash theme={"dark"} curl -sS -X DELETE "$LEAN_API_URL/v1/limit-chases/$LIMIT_CHASE_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` The answer is `200` with the limit chase and `cancel_requested_at` set. A live limit chase keeps its status for a moment while Lean cancels its resting order, then reads `canceled`. A test limit chase reads `canceled` at once. Canceling works while trading is paused, and a limit chase that has already ended is refused with `400 VALIDATION_ERROR`. Pausing trading does not stop a limit chase that is already on the book. Cancel it if you want it gone. ## Test keys A test key's limit chase is checked like a live one, against the market and the test account's simulated cash and shares. It follows the venue's public book and fills in simulation once the best price on the other side reaches its price. It is brought up to date with the book each time you list or read it, so its price and fills change between reads. It never reaches the venue, and its fills show in the test account's positions and balances. See [Test mode and live mode](/test-mode). ## Fills A limit chase is not an order you placed, so its fills are listed in `GET /v1/fills` with `order_id` set to `null`, and `GET /v1/fills?order_id=` never returns them. A live key sees each fill the venue reports for the chase's resting order. A test key sees one fill per limit chase for what it has filled so far, at `avg_fill_price`, with `liquidity` `maker` and `filled_at` the time the chase was created. It is listed once something fills and grows as more fills, keeping the same `id`. # Markets and IDs Source: https://lean.mintlify.app/markets Fixtures, propositions, outcomes, signed lines and market IDs. A market is one outcome of one proposition of one fixture. For example: "DEN" in "DEN -3.5" in "Denver Broncos at Los Angeles Chargers". ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets?league=nfl&limit=50" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ## Query parameters | Parameter | Meaning | | - | - | | `league` | Exactly as it appears in `fixture.league`, for example `nfl`. | | `sport` | As it appears in `fixture.sport`, in any case, for example `football` or `Football`. | | `fixture` | Exactly as it appears in `fixture.key`. Lists only that fixture's markets. | | `group` | Exactly as it appears in `group.key`, for example `moneyline:game`. Lists only markets of that proposition, in every fixture the other filters keep. | | `category` | `sports`. Every listed market is a sports market today. | | `status` | `open`: at least one venue leg is open for trading. `closed`: no leg is. | | `venue` | `kalshi`, `polymarket`, `polymarket_us` or `hyperliquid`. Lists only markets with a leg on that venue. | | `search` | Words to find, the way the search box in the Lean app finds them. See [Search by text](#search-by-text). | | `symbol` | A venue symbol: a leg `ticker` (`pm:…`, `pmus:…`, `hl:…` or a Kalshi market ticker), a Polymarket condition ID or token ID, or a Hyperliquid book coin (`#…`, sent as `%23…` in the query string). Lists the markets that symbol trades. Only `venue` applies with it; the start window, `cursor` and the other filters do not. | | `starts_after`, `starts_before` | ISO 8601 times. By default the list starts 12 hours ago and ends 30 days ahead. | | `limit` | From 1 to 200. The default is 50. | | `cursor` | The `next_cursor` of the previous page. `next_cursor` is `null` on the last page. | Season futures start later than 30 days ahead; pass `starts_before` to list them. Their market IDs resolve at any time. A parameter the endpoint does not take is refused with `400 VALIDATION_ERROR`, so a misspelled filter never returns the whole list. [List markets](/api-reference/markets/list-markets) lists every parameter. ## One proposition of one fixture Pass `fixture` and `group` together to list the outcomes of one proposition, such as every driver in one race's winner market, without paging through the whole league: ```bash theme={"dark"} curl -sS -G "$LEAN_API_URL/v1/markets" \ --data-urlencode "fixture=nfl:2026-10-11:DEN-LAC" \ --data-urlencode "group=moneyline:game" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` Take both keys from a market you already have. Both filters combine with the others, and the start window still applies: a fixture that starts outside it lists nothing, so pass `starts_after` or `starts_before` to reach it. ## Search by text ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets?search=celtics&limit=50" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` `search` finds markets the way the search box in the Lean app does. * Every word must appear, in any letter case, in the title of a Kalshi, Polymarket, Polymarket US or Hyperliquid listing of the market or of its game. The last word can be the start of a word, so `celt` finds `Celtics`. * When few listings match, Lean also tries common team nicknames and city short forms, such as `philly` for Philadelphia, and words one or two letters off, such as `celtcs`. * Only markets with a matching listing are returned, not every market of the same game. * Results keep the usual order by start time. `league`, `sport`, `status`, the start window, `limit` and `cursor` work the same as without `search`. Pass `next_cursor` back as `cursor` with the same `search` to read the next page. * A search looks only at the listings of games in the start window, and at no more than 10,000 matching ones, open listings first, then by start. Narrow broad words with `league`, `sport` or the start window. * The same search over the same listings returns the same markets every time. * League names are in only some listing titles, so `search=nba` finds only the markets with such a listing, not every NBA market. To list a league, use `league` rather than `search`. * Spaces at either end are ignored. The text must then be 1 to 100 characters, or the request returns `400 VALIDATION_ERROR`. * If search is briefly unavailable or cannot finish in time, the request returns `503 UPSTREAM_ERROR` rather than a partial list. Retry it, or narrow a long start window. ## A market ```json theme={"dark"} { "id": "mkt_bmZsOjIwMjYtMTAtMTE6REVOLUxBQwpzcHJlYWQ6Z2FtZTpERU46LTMuNQpERU4", "title": "Denver Broncos at Los Angeles Chargers: DEN -3.5, Denver Broncos -3.5", "outcome": "DEN", "line": "-3.5", "fixture": { "key": "nfl:2026-10-11:DEN-LAC", "sport": "football", "league": "nfl", "title": "Denver Broncos at Los Angeles Chargers", "starts_at": "2026-10-11T20:25:00.000Z", "scheduled_date": "2026-10-11", "participants": ["Denver Broncos", "Los Angeles Chargers"], "teams": [ { "key": "DEN", "name": "Denver Broncos", "role": "away" }, { "key": "LAC", "name": "Los Angeles Chargers", "role": "home" } ] }, "group": { "key": "spread:game:DEN:-3.5", "kind": "spread", "label": "DEN -3.5", "period": "game", "subject": "DEN", "stat": null, "line": "-3.5" }, "legs": [ { "venue": "hyperliquid", "ticker": "", "side": "yes", "status": "open", "tradable": true } ] } ``` `title` names the fixture, the proposition and the outcome in words, ready to show a person. ### Fixture | Field | Meaning | | - | - | | `fixture.key` | The canonical fixture key: `{league}:{scheduled date}:{participants}`. | | `fixture.scheduled_date` | The date part of the key, `YYYY-MM-DD`. | | `fixture.teams` | Each participant's `key`, `name` and `role` (`home`, `away` or `competitor`). | | `fixture.starts_at` | The scheduled start time. | ### Proposition (`group`) `group.kind` is `moneyline`, `spread`, `total`, `team_total` or `prop`. | `group.key` | Proposition | | - | - | | `moneyline:game` | Who wins the game. | | `spread:game:DEN:-3.5` | DEN wins by more than 3.5 points, or LAC covers +3.5. | | `total:game:44.5` | Combined points over or under 44.5. | * `group.period` is `game` for every v0.1 sports market. v0.1 lists markets on the full game only. * In a spread, `group.subject` is the team that holds the negative line, and `group.line` is that negative line. In `spread:game:DEN:-3.5`, DEN is the subject. ### Signed line per outcome `line` on each market is the line from that outcome's point of view: | Market | `outcome` | `line` | | - | - | - | | `spread:game:DEN:-3.5` | `DEN` | `-3.5` | | `spread:game:DEN:-3.5` | `LAC` | `3.5` | | `total:game:44.5` | `over` | `44.5` | | `total:game:44.5` | `under` | `44.5` | | `moneyline:game` | `DEN` or `LAC` | `null` | ### Legs `legs` lists the venue listings behind the market. `side` is the venue side that pays when this outcome happens. `status` is the venue market's status: `unopened`, `open`, `closed`, `resolving` or `resolved`, or `null` until Lean has recorded the venue market. The Lean platform shows a live book for every status but `closed` and `resolved`. `tradable: true` marks a leg the venue takes orders on now: a venue `POST /v1/orders` can place on, whose venue market is `open` and not marked untradable by the venue. An `unopened` or `resolving` leg has a live book but reads `tradable: false`, because its venue refuses orders. A market with no tradable leg is `closed`. Other legs are there for price discovery. * `legs[].resolution` is how that venue settles its market, and any field can be `null`: * `source`: how the venue resolved the market. It stays `null` until the market resolves. * `rules`: the venue's rules text, verbatim, with any secondary rules after a blank line. * `end_date`: the venue's end date, in ISO 8601. * `url`: the venue's page for the market, or `null` when Lean does not know it. * `legs[].fees` is what that venue charges a fill, with the same terms `POST /v1/orders/preview` prices its fees with. It is `null` on Kalshi and Polymarket US, and when Lean has not recorded the venue's fee for the market. See [Fees](#fees). * `equivalence` says how far the legs are known to match: `single_venue` (one venue lists it), `verified` (a reviewer confirmed each venue's market is the same proposition, which does not mean the rules text is identical, so read each leg's `rules`) or `unreviewed` (not yet checked). A venue listing a reviewer judged to be a different proposition is never listed as a leg. `GET /v1/markets/{id}` returns one market in the same shape, or `404 NOT_FOUND`. ## Fees Each leg's `fees` lets you price a fill's fee before you preview it: | Field | Meaning | | - | - | | `formula` | How the fee is charged: `price_curve` or `notional_on_exit`. | | `taker_rate` | The rate, as a fraction of 1, for a fill that takes liquidity. | | `maker_rate` | The rate, as a fraction of 1, for a resting order that fills. | | `exponent` | The exponent in `price_curve`. `null` for `notional_on_exit`. | | `formula` | Venue | Fee for `quantity` shares filled at `price` | | - | - | - | | `price_curve` | Polymarket | Buys and sells both pay `quantity × rate × (price × (1 − price))^exponent`. The fee is highest at 0.50 and falls toward 0 and 1. Each fill's fee is rounded to \$0.00001. | | `notional_on_exit` | Hyperliquid | A buy pays nothing. A sell pays `quantity × price × rate`. A winning share held to settlement pays `rate × $1`. Each fill's fee is rounded up to \$0.000001. | `rate` is `taker_rate` for a fill that takes liquidity and `maker_rate` for a resting order that fills. A Polymarket market with `maker_rate: "0"` charges only takers. Hyperliquid's `maker_rate` is its lowest-volume tier. For example, a Polymarket leg with `{ "formula": "price_curve", "taker_rate": "0.05", "maker_rate": "0", "exponent": 1 }`: * Buying 100 shares at 0.24 pays `100 × 0.05 × (0.24 × 0.76) = $0.912`, so each share costs 0.24912 with its fee. If the outcome is worth 0.255 to you, the edge is 0.255 − 0.24912 = 0.00588 a share, not 0.015. * Selling 100 shares at 0.76 pays the same \$0.912, because `price × (1 − price)` is the same. And a Hyperliquid leg with `{ "formula": "notional_on_exit", "taker_rate": "0.0007", "maker_rate": "0.0004", "exponent": null }`: * Buying 100 shares at 0.60 pays nothing. * Selling those 100 shares at 0.60 pays `100 × 0.60 × 0.0007 = $0.042`. * Holding them to a win instead pays `100 × $1 × 0.0007 = $0.07` at settlement. > [!NOTE] > > `POST /v1/orders/preview` and the [quote](#quotes-and-liquidity) price every fill at `taker_rate` > from these same terms, and their `expected_fee_usd` and `fee_usd` are authoritative. When a > Polymarket leg's `fees` is `null`, they show a fee of `0` for it, which may be less than > Polymarket charges. When a Hyperliquid leg's `fees` is `null`, they price its sells at the base > rate, 7 bps. A venue can change its fees, so preview an order before you place it. ## Market IDs A market ID (`mkt_…`) is stable and opaque. Store it and send it back unchanged. Do not build or edit IDs yourself. A `mkt_…` ID Lean did not issue, or one that names a team outside its fixture, returns `404 NOT_FOUND`. ### Venue symbols Every field and path that takes a market ID, including a `book` channel on the [stream](/streaming), also takes a venue symbol that names exactly one market: | Symbol | Example | Names | | - | - | - | | Polymarket token ID | `7132…` | The market whose outcome that token pays. | | Hyperliquid book coin | `#120` | The market whose outcome that coin pays. In a URL path, write `#` as `%23`. | | Leg `ticker` | `pm:0x…`, `pmus:…`, `hl:12`, `KXNBAGAME-…` | The market, when that listing pays only one outcome. | Kalshi and Polymarket US markets have no venue symbol here: name them by market ID. To find the market ID from a Kalshi or `pmus:` ticker, use `GET /v1/markets?symbol=`. Lean answers with the market under its market ID, so a market never appears under two IDs. Orders, fills and filters store and compare the market ID: listing orders by a token ID returns the same orders as listing them by the market ID. An order named by a venue symbol trades only that listing. If `venues` leaves out the symbol's venue, the order is refused with `422` and `details.reason: "NO_EXECUTABLE_VENUE"`. A buy Lean [routes](/routed-orders) for you still buys that listing, paid from the other venue, which happens only between Polymarket and Hyperliquid. Reads that price a market price what an order naming the same ID would trade. With a venue symbol, the quote, book, trades, prices and `book` stream channel read only the symbol's listing, under the market ID. With a market ID they read every listing. `GET /v1/markets/{id}` describes the whole market either way. A symbol that names more than one market returns `400 VALIDATION_ERROR`. The `ticker` or Polymarket condition ID of a listing that pays both outcomes names both of its markets; send the token ID, the book coin or the market ID instead. A symbol Lean does not list returns `404 NOT_FOUND`, and a value that is neither a market ID nor a venue symbol returns `400 VALIDATION_ERROR`. ## Prices ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/prices?market_ids=$MARKET_ID,$OTHER_MARKET_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` `GET /v1/prices` reads the top of the book for up to 25 markets, separated by commas. More than 25 returns `400 VALIDATION_ERROR` with `market_ids: At most 25 market ids per request`; split larger sets across requests. Ids that name no market are listed in `not_found`. | Field | Meaning | | - | - | | `best_bid`, `best_ask` | The best price across the venues read, snapped to the market's tick as the Lean platform shows it, or `null` when no venue has a level on that side. Hyperliquid prices are not snapped. | | `best_bid_quantity`, `best_ask_quantity` | The shares resting at `best_bid` and `best_ask`, summed over every venue at that price. `null` when the price is `null`. | | `mid` | The Lean platform's mid. When one venue holds both best prices, its mid rounded down to the market's tick (Hyperliquid's is not rounded); otherwise halfway between the best bid and best ask. A book with only one side reads that side's price. | | `spread` | `best_ask` minus `best_bid`, or `null` when either is `null`. One venue's crossed book reads `0`; `spread` is negative only when one venue bids above another's ask. | | `last_trade_price`, `last_trade_at` | The latest trade on any venue, in this market's outcome. A trade of the opposite outcome counts at 1 minus its price. | | `venues[]` | Per venue: `best_bid`, `best_bid_quantity`, `best_ask` and `best_ask_quantity` on that venue alone. | | `unavailable` | Venues whose book could not be read; never reported as empty. | A best price backed by a few shares fills only those shares there. Size an order against the quantity, or read the [book](/api-reference/markets/retrieve-market-book) for the depth behind it. Polymarket quantities include what the opposite outcome's book implies; Hyperliquid quantities are the venue's book as it stands. ## Quotes and liquidity ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets/$MARKET_ID/quote?quantity=5" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` A quote shows how a buy of `quantity` shares would fill across venues. Send `action=sell` to quote a sell of shares the trading account holds. For a buy, send `notional` instead of `quantity` to quote the shares a dollar amount buys, as a buy sized with `notional` would be placed. | Field | Meaning | | - | - | | `legs[]` | Per venue: `quantity`, `average_price`, `limit_price` (the limit that leg would be placed at), `fee_usd` and `executable`. | | `legs[].fee_usd` | The venue fee at the expected fills. A Hyperliquid buy pays its fee when the position closes or settles, so it shows `0` here; a Hyperliquid sell pays the market's taker rate, 7 bps times its fee scale. | | `expected_total_usd` | The expected cost of the whole quantity. | | `max_total_usd` | The cost in the worst case: every leg filled at its `limit_price`, with the fees at that price. | | `network_cost_usd` | The cost of moving cash between venues. A quote prices each venue with its own cash, so it is `0` here; a [preview](/preview) of an order that would take a route shows the route's costs. | | `limited_by` | Why the quote covers less than the whole quantity, or `null` when it covers all of it. See below. | | `expires_at` | Quote again after this time. A quote reserves nothing. | A quote prices a market order, within the account's slippage bound when it sets one (`max_slippage_bps` in `GET /v1/account/config`), on the venues orders can use. `limited_by` is one of: | `limited_by` | Meaning | | - | - | | `depth` | The books fill less than the quantity within the slippage bound, or no venue can place the market. | | `holdings` | A sell (`action=sell`) for more shares than the trading account holds. The quote covers the shares held. | | `funds` | The trading account can't pay for the buy on any venue that could place it. | | `venue_minimum` | The quantity is below the minimum of every venue that could place it. | | `increment` | No venue that could place the order takes the quantity in its size steps. | When nothing could be placed, `legs` is empty and `quantity` is `0`. New `limited_by` values can appear without a new version; treat one you do not recognize as covering only part of the quantity. If routing is not available, the quote returns `503 FEATURE_DISABLED`. Markets, previews and orders still work. ## Recent trades ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets/$MARKET_ID/trades?limit=100" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` `GET /v1/markets/{id}/trades` lists the trades on each venue listing of the market, newest first. To read further back, pass the page's `next_cursor` as `cursor`. Each page holds trades strictly older than the last trade of the page before. `next_cursor` is `null` when no older trade is recorded. A cursor works only for the market and `venue` it was issued for. A cursor Lean did not issue, or one passed with another market or `venue`, returns `400 VALIDATION_ERROR`. ## Price candles ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets/$MARKET_ID/candles?interval=1m&start=2026-11-10T12:00:00Z&end=2026-11-10T13:00:00Z" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` `GET /v1/markets/{id}/candles` returns open, high, low, close and volume for each venue listing of the market, oldest first. Pass `venue` to read one listing. | Parameter | Meaning | | - | - | | `interval` | `1s`, `1m`, `5m`, `15m`, `1h` or `2h`. Defaults to `1m`. | | `start` | The first candle opens at or after this time. Defaults to 100 intervals before `end`. | | `end` | Candles that open before this time. Defaults to now. | One call returns at most 1000 candles per listing. A range longer than that, a `start` that is not before `end`, or an unknown `interval` returns `400 VALIDATION_ERROR`. An unknown market returns `404 NOT_FOUND`. Prices are dollars per share of the side the market buys. A period with no trade has no candle, and the period still open may be missing or hold only the trades so far. A period the Lean chart treats as unpriced has no candle either: a recorded open of 0 or close below 0.001, read before a Polymarket NO market's prices are turned over. | Venue | Prices | `volume` | | - | - | - | | Kalshi, Polymarket, Polymarket US | A NO market reads the YES prices turned over: each price is 1 minus the YES price, so the YES high becomes the NO low. | Shares traded in the venue market in the period, so a YES and a NO market show the same volume. | | Hyperliquid | Each side has its own trades and its own candles. | Shares of that side traded in the period. | # Orders and idempotency Source: https://lean.mintlify.app/orders 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": "", "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": "", "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": "" } } ``` 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](/preview) 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](/preview) 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](/changelog)) doesn't: create a new one, or create one with `route` through [Create an API key](/api-reference/api-keys/create-api-key). See [Authentication](/authentication#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](/test-mode#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](/routed-orders). ## 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](/preview) 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](/preview) 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](/preview) 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](/preview) 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](/api-reference/account/close-positions) takes a `client_order_id` of up to 40 characters. Each sell it places gets `-close--`, 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](/test-mode#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](/test-mode#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](/test-mode)), 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. # Preview Source: https://lean.mintlify.app/preview Preview an order without placing it: where it would go, what it would cost, and whether it would be refused. `POST /v1/orders/preview` takes the exact body of `POST /v1/orders` and answers what that request would do. It reserves and places nothing, so a `read` key can call it. ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/orders/preview" \ -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.50", "time_in_force": "ioc" }' ``` ```json theme={"dark"} { "success": true, "data": { "market_id": "mkt_...", "action": "buy", "quantity": "5", "limit_price": "0.50", "time_in_force": "ioc", "execution": { "venue": "hyperliquid", "ticker": "", "side": "yes", "notional_usd": "2.5", "max_slippage_bps": 100, "executable_quantity": "5", "expected_average_price": "0.47", "legs": [ { "venue": "hyperliquid", "ticker": "", "side": "yes", "quantity": "5", "notional_usd": "2.5", "expected_fill_quantity": "5", "expected_average_price": "0.47", "expected_fee_usd": "0", "expected_resting_fee_usd": "0" } ] }, "would_submit": true, "route_plan": { "expected_total_usd": "2.35", "max_total_usd": "2.5", "legs": [] }, "route": null, "warnings": [], "livemode": true }, "meta": { "requestId": "" } } ``` | Field | Meaning | | - | - | | `execution` | Where the order would be placed. `null` when it would be refused before reaching a venue. | | `execution.venue`, `ticker`, `side` | The one venue order. `null` when the order would be split; read `legs` instead. | | `execution.legs` | One entry per venue order: `venue`, `ticker`, `side`, `quantity`, `notional_usd`, and the expected fill quantity, average price and fee. `expected_fee_usd` prices each expected fill at the taker rate in the market leg's [`fees`](/markets#fees), and is the authoritative fee for the order. `expected_resting_fee_usd` is the maker fee on the part a `gtc` or `gtd` leg would rest, as if it all filled at the leg's `limit_price`, and `0` when nothing rests. 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. | | `execution.notional_usd` | `quantity × limit_price` before fees, and the amount checked against your key's limits. For a buy sized with `notional`, `quantity` and `limit_price` are the shares and worst price that amount reaches on the books, so this is never more than `notional`. Fees come on top: `route_plan.max_total_usd` is the most the order can cost with them. For an order that would take a `route`, `route.notional_usd` is checked instead. | | `execution.max_slippage_bps` | The slippage bound the order would use: the body's `max_slippage_bps`, or the account's, or `null` when neither sets one. | | `execution.executable_quantity` | What the books would fill at once across every leg, as last read. | | `execution.expected_average_price` | The expected price per share across those fills. `null` when nothing would fill at once. | | `route` | The route `POST /v1/orders` would take: `funding_venue` pays for the buy with its cash and `execution_venue` buys it. `null` when the order would be paid for on the venue it buys on, or refused. With `best_price`, it is set when the route would cost less in all. It carries the route's `notional_usd` and itemized `costs`, as on the placed order. See [Paying from the other venue](/orders#paying-from-the-other-venue) and [Best price across venues](/orders#best-price-across-venues). | | `route_plan` | The quote for the same quantity at your limit: the expected (`expected_total_usd`) and worst (`max_total_usd`) cost. Its legs are the ones the order would place. When the order would take a `route`, it prices that route, with the route's costs in `network_cost_usd`. `null` when routing can't plan the order. | | `would_submit` | `false` when `POST /v1/orders` would refuse this body. | | `warnings` | Why it would be refused, or what might limit the fill. | When the trading account can't trade on any venue that lists the market, for example because that venue is not available in your region, the preview answers with the same `403` error that `POST /v1/orders` and the quote return. When a venue has stopped trading the market, the preview answers `409 CONFLICT` with `details.reason: "MARKET_NOT_TRADABLE"`, and when a venue can't be read, `503 UPSTREAM_ERROR`, as the quote does. A Polymarket US market whose book Lean has not loaded yet also answers `503 UPSTREAM_ERROR` with `Retry-After`; send the same preview again after that time. ## Warnings | `warnings[].code` | Blocks the order | Meaning | | - | - | - | | `ORDER_NOTIONAL_LIMIT` | Yes | Above the key's per order limit. | | `DAILY_NOTIONAL_LIMIT` | Yes | Would take the key or its account past the daily limit. | | `VENUE_NOT_ALLOWED` | Yes | The trading account does not allow orders on a venue the order names, or on any venue listing this market. | | `BELOW_VENUE_MINIMUM` | Yes | Below the minimum of every venue that could place it. | | `INSUFFICIENT_FUNDS` | Yes | The trading account cannot pay for the order on any venue that could place it, and Lean cannot [pay from the other venue](/orders#paying-from-the-other-venue). When it can, the preview shows that in `route` instead and `would_submit` is `true`. | | `INSUFFICIENT_HOLDINGS` | Yes | A sell for more shares than the trading account holds. | | `INSUFFICIENT_DEPTH` | Yes | An `all_or_none` order the books can't fill in full within the slippage bound. | | `POST_ONLY_WOULD_CROSS` | Yes | A `post_only` order would trade at once against the books. | | `NO_EXECUTABLE_VENUE` | Yes | No venue can place this market today. | | `CLIENT_ORDER_ID_USED` | Yes | The ID is taken. The order would be answered as a replay of the existing one. | | `TRADING_UNAVAILABLE` | Yes | The key or its account is paused, or the key is a live key and Lean has paused live trading platform wide. | | `ROUTE_LIMITED` | No | At this limit, the books or the trading account cover only part of the quantity. | | `ROUTE_UNAVAILABLE` | No | No route plan: routing is off or no route can take the order. | ## Preview several orders `POST /v1/orders/preview-batch` takes up to 25 bodies of `POST /v1/orders` in `orders` and previews them all at once, so the call takes about as long as the slowest preview. Like the single preview it places nothing, needs only a `read` key, and counts once against the key's rate limit. ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/orders/preview-batch" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "orders": [ { "client_order_id": "bot-2026-10-29-0001", "market_id": "'"$MARKET_ID"'", "action": "buy", "quantity": "5", "limit_price": "0.50", "time_in_force": "ioc" }, { "client_order_id": "bot-2026-10-29-0002", "market_id": "mkt_unknown", "action": "buy", "quantity": "5", "limit_price": "0.50", "time_in_force": "ioc" } ] }' ``` ```json theme={"dark"} { "success": true, "data": { "results": [ { "status": 200, "preview": { "market_id": "mkt_...", "would_submit": true, "warnings": [], "livemode": true }, "error": null }, { "status": 404, "preview": null, "error": { "code": "NOT_FOUND", "message": "Market not found" } } ], "livemode": true }, "meta": { "requestId": "" } } ``` `results` has one entry per body, in the order you sent them. `preview` is what `POST /v1/orders/preview` answers for that body, shortened here; it has every field described above. When the single preview would answer with an error, `preview` is `null` and `status` and `error` carry that error's HTTP status, `code`, `message` and `details`, so one body that can't be previewed does not fail the others. A body that fails validation, or more than 25 bodies, refuses the whole call with `400`. Each body is previewed on its own. The limits and holdings checks of one body do not count the others, so a set of orders that each pass can still go past a limit together. > [!NOTE] > > A preview is a snapshot. Prices and balances can change before you place the order. The daily > limit is read but not held, so an order placed in between can still take the room a preview saw. # Quickstart Source: https://lean.mintlify.app/quickstart From a new key to a filled test order in one call. These examples use two environment variables: ```bash theme={"dark"} export LEAN_API_URL="https://api.lean.xyz" export LEAN_API_KEY="lean_sk_test_..." ``` `LEAN_API_URL` is the Lean API. Test and live keys use the same URL; the key decides the mode. Start with a test key: orders and fills are simulated and no money moves. To create a key, sign in to Lean, open Settings (the gear) and choose **API**. [Authentication](/authentication#create-a-key) explains its limits, and [Test mode and live mode](/test-mode) shows how to switch to a live key when you're ready. **1. Find a market** ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets?league=nfl&limit=20" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` Pick a market whose `legs` include one with `tradable: true`, and keep its `id`: ```bash theme={"dark"} export MARKET_ID="mkt_..." ``` [Markets and IDs](/markets) explains each field. **2. Place the order** One call places the order. Lean picks the venues among Kalshi, Polymarket, Polymarket US and Hyperliquid. If the book is on Polymarket and the account's cash on Hyperliquid, or the other way round, it moves the cash and buys on the venue with the book: ```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" }' ``` Polymarket takes `ioc` buys by dollar amount only. On a market only Polymarket lists, send `"notional": "25"` in place of `quantity`; see [Limitations](/orders#limitations). The response is the order. A test order fills at once at the best price on the book, up to the size shown there and within your limit: ```json theme={"dark"} { "success": true, "data": { "id": "3f6c2a8e-91d4-4b7a-8c25-0e4d7b19a6f3", "client_order_id": "bot-2026-10-29-0001", "action": "buy", "quantity": "5", "filled_quantity": "5", "limit_price": "0.42", "avg_fill_price": "0.41", "status": "filled", "legs": [ … ], "route": null, "livemode": false }, "meta": { "requestId": "" } } ``` `route` is `null` when the order was paid for on the venue it bought on, which is always the case on Kalshi and Polymarket US. When Lean paid with cash from the other venue, its `funding_venue` names the venue the cash came from and its `execution_venue` the venue it bought on, with the route's `notional_usd` and `costs`. See [Paying from the other venue](/orders#paying-from-the-other-venue). > [!WARNING] > > An accepted response is not a fill. Read `status` and `filled_quantity`, and confirm them > with the steps below. **3. Read it back** ```bash theme={"dark"} export ORDER_ID="3f6c2a8e-91d4-4b7a-8c25-0e4d7b19a6f3" curl -sS "$LEAN_API_URL/v1/orders/$ORDER_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` Use the `id` from your own response. If the response never arrived, look the order up by `client_order_id` instead: `GET /v1/orders?client_order_id=bot-2026-10-29-0001`. **4. Reconcile** ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/positions" -H "Authorization: Bearer $LEAN_API_KEY" curl -sS "$LEAN_API_URL/v1/balances" -H "Authorization: Bearer $LEAN_API_KEY" ``` See [Orders and idempotency](/orders#reconcile). ## Quote and preview first Before you trade live, check what an order would do. Neither call places or reserves anything. ```bash theme={"dark"} # How a buy of 5 shares would fill: price per venue, expected_total_usd, max_total_usd and fees curl -sS "$LEAN_API_URL/v1/markets/$MARKET_ID/quote?quantity=5" \ -H "Authorization: Bearer $LEAN_API_KEY" # The exact order body: check would_submit and warnings curl -sS -X POST "$LEAN_API_URL/v1/orders/preview" \ -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" }' ``` Quote again after `expires_at`. See [Preview](/preview). A preview checks the order against the cash on the venues that could place it. When Lean would [pay from the other venue](/orders#paying-from-the-other-venue), `route` names both venues and `would_submit` is `true`. A blocking warning means the order would be refused. ## Try it in the API reference Every page under [API reference](/api-reference/markets/list-markets) has a **Try it** button that sends a real request with your key and shows the response. 1. In Lean, open Settings (the gear), choose **API**, and [create a test key](/authentication#create-a-key) with **Create API key**. Keep the **Test** mode and **Read and trade** access. 2. Open [List markets](/api-reference/markets/list-markets) and click **Try it**. 3. Under **Server**, set `baseUrl` to your `LEAN_API_URL`, without `/v1`. 4. Under **Authorization**, paste your test key. The playground adds `Bearer` for you. 5. Click **Send**, then copy a market `id` from the response. 6. Open [Create an order](/api-reference/orders/create-order) and send it. The body fields start filled with an example; replace `market_id` and set your own `client_order_id`. 7. Copy the order `id` from the response, and read it back with [Get an order](/api-reference/orders/retrieve-order). > [!WARNING] > > The key decides the mode. With a test key, **Send** on Create an order simulates the order. With > a live key, it places a real order against the key's trading account. Use a test key while you > experiment. Each page also shows the request as cURL, Python and JavaScript, with example responses for success and for each error status. ## Using TypeScript The [TypeScript SDK](/typescript-sdk) runs these same steps with typed methods: `npm install @leanxyz/api-sdk`, then `listMarkets`, `previewOrder`, `createOrder` and `getOrder` with the same `LEAN_API_URL` and `LEAN_API_KEY`. ## Using Rust The [Rust SDK](/rust-sdk) runs the same steps as async methods: add `lean-api-sdk` from crates.io with Tokio, then `list_markets`, `preview_order`, `create_order` and `get_order` with the same `LEAN_API_URL` and `LEAN_API_KEY`. ## Python ```python theme={"dark"} import os import uuid import requests BASE = os.environ["LEAN_API_URL"] HEADERS = {"Authorization": f"Bearer {os.environ['LEAN_API_KEY']}"} def call(method, path, **kwargs): response = requests.request(method, f"{BASE}{path}", headers=HEADERS, timeout=30, **kwargs) body = response.json() if not body["success"]: error = body["error"] raise RuntimeError(f"{response.status_code} {error['code']}: {error['message']}") return body["data"] market = call("GET", "/v1/markets", params={"league": "nfl", "limit": 1})["markets"][0] print(market["fixture"]["title"], market["group"]["label"], market["outcome"]) # Save client_order_id before sending, and reuse it on every retry of this order. order = call("POST", "/v1/orders", json={ "client_order_id": f"bot-{uuid.uuid4().hex[:16]}", "market_id": market["id"], "action": "buy", "quantity": "5", "limit_price": "0.42", "time_in_force": "ioc", }) print(order["id"], order["status"], order["filled_quantity"], order["route"]) print(call("GET", f"/v1/orders/{order['id']}")["status"]) ``` # Advanced: self-signed routed orders Source: https://lean.mintlify.app/routed-orders Sign the payment for a cross-venue buy yourself, in two calls. > [!NOTE] > > Most programs don't need this page. `POST /v1/orders` already buys with cash held on the other > venue, in one call. See [Paying from the other venue](/orders#paying-from-the-other-venue). Use > the flow below only if your program signs each payment with the account's wallet itself. A routed order buys on Polymarket or Hyperliquid with cash held on the other of the two. Kalshi and Polymarket US do not take routed orders. You name the venue whose cash pays (`funding_venue`), Lean buys on the other venue, and you sign the payment before anything moves. It takes two calls: 1. `POST /v1/routed-orders` quotes the route, books the order as `pending` and returns the payment to sign. 2. `POST /v1/routed-orders/{id}/execute` sends your signature. Lean then moves the cash and buys. Routed orders are buys only. The key needs the `trade` and `route` scopes. See [Authentication](/authentication#create-a-key). **1. Create the routed order** ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/routed-orders" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "client_order_id": "bot-2026-11-02-0001", "market_id": "'"$MARKET_ID"'", "quantity": "5", "limit_price": "0.42", "funding_venue": "hyperliquid" }' ``` | Field | Meaning | | - | - | | `client_order_id` | Required. Your ID for this order, as for `POST /v1/orders`. | | `market_id` | A `mkt_…` ID from `GET /v1/markets`. | | `quantity` | Shares, as a decimal string. | | `limit_price` | The worst price per share you accept on the venue Lean buys on. | | `funding_venue` | `hyperliquid` or `polymarket`: the venue whose cash pays. Lean buys on the other one. | The response is the order, `pending`, with `route` and `payment`: | Field | Meaning | | - | - | | `route` | The venues and costs, as on a [one-call order](/orders#paying-from-the-other-venue): `funding_venue`, `execution_venue`, `notional_usd` (the most the payment can cost) and `costs` (`rebalance_fee_usd`, `gas_usd`, `activation_fee_usd` and their sum, `network_cost_usd`). | | `payment.scheme` | What you sign: `hyperliquid_send_asset` or `polymarket_deposit_wallet_batch` for a live key, `lean_test_payment` for a test key. | | `payment.signer_address` | The wallet that must sign. | | `payment.typed_data` | The EIP-712 typed data to sign. A live payment is the venue transfer itself; a test payment is a Lean message naming this order. | | `payment.agent_approval` | Polymarket funding only: set when the buying wallet first needs a Lean agent approved. Sign it too. Otherwise `null`. | Only the response that created the order carries `payment`. A replay with the same `client_order_id` returns the order with `payment: null`. **2. Sign the payment** Sign `payment.typed_data` as EIP-712 typed data with the wallet at `payment.signer_address`. If `payment.agent_approval` is set, sign it as well. Sign and execute before the quote expires. **3. Execute it** ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/routed-orders/$ORDER_ID/execute" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "authorization": "signature", "payment_signature": "0x...", "agent_approval_signature": "0x..." }' ``` Leave out `agent_approval_signature` when the payment had no `agent_approval`. The response is the order with `payment: null`. A test order is `filled`. A live order stays `pending` while Lean moves the cash, then fills on the other venue. Sending the same authorization again returns the order as it stands. **4. Reconcile** Read the order back with `GET /v1/orders/{id}` until it is final, as for any order. See [Orders and idempotency](/orders#reconcile). ## Letting Lean sign Send `{ "authorization": "delegated" }` to the execute call instead of a signature, and Lean signs the payment with the account's delegated signer, as `POST /v1/orders` does. A live key needs the account to have trading enabled in the Lean app; otherwise the call returns `403 FORBIDDEN` with `details.reason: "ACCOUNT_NOT_DELEGATED"`. A routed order is authorized once. Sending a signature after a delegated authorization, or the other way round, returns `409 CONFLICT` with `details.reason: "PAYMENT_ALREADY_AUTHORIZED"`. ## Errors | HTTP | `code` | `details.reason` | When | | - | - | - | - | | 400 | `VALIDATION_ERROR` | `INVALID_SIGNATURE` | The signature is not a valid signature over the payment. | | 400 | `VALIDATION_ERROR` | `SIGNER_MISMATCH` | The payment was signed by another wallet than `payment.signer_address`. | | 403 | `FORBIDDEN` | | The key lacks the `route` scope. | | 403 | `FORBIDDEN` | `ACCOUNT_NOT_DELEGATED` | `delegated` authorization on a live key, and the account has not enabled trading in the Lean app. | | 404 | `NOT_FOUND` | | No routed order with this ID for this key, or, on create, no market with this ID. | | 409 | `CONFLICT` | `QUOTE_EXPIRED` | The quote expired before the payment was authorized. Create a new routed order. | | 409 | `CONFLICT` | `ROUTE_MOVED` | The route changed while it was quoted. Create a new routed order. | | 409 | `CONFLICT` | `ORDER_NOT_PENDING` | The order is no longer waiting for its payment. | | 409 | `CONFLICT` | `PAYMENT_ALREADY_AUTHORIZED` | The order was already authorized another way. | | 409 | `CONFLICT` | `PAYMENT_MISMATCH` | The payment does not match the order or its trading account. | | 409 | `CONFLICT` | `AGENT_APPROVAL_REQUIRED` | `delegated` authorization, and the buying wallet still needs its Lean agent approved. | | 422 | `VALIDATION_ERROR` | `ROUTE_NOT_EXECUTABLE`, `LIMIT_BELOW_ROUTE_PRICE` | On create: no route can fill the whole quantity within the limit. There is no fallback venue. | | 422 | `VALIDATION_ERROR` | `ORDER_NOTIONAL_LIMIT`, `DAILY_NOTIONAL_LIMIT` | A key or account limit. | | 503 | `FEATURE_DISABLED` | `ROUTING_DISABLED`, `LIVE_TRADING_DISABLED`, `TRADING_PAUSED` | Routing or live trading is switched off, or this key or its account is paused. | | 503 | `FEATURE_DISABLED` | `DELEGATED_ROUTE_SIGNING_DISABLED` | `delegated` authorization on a live key while Lean signing is switched off. Send a signature instead. | See [Errors](/errors) for the envelope and the other codes. # Rust SDK Source: https://lean.mintlify.app/rust-sdk Call the Lean API from Rust, with a typed async method for every endpoint. `lean-api-sdk` is the Lean API client for Rust. It is generated from the [OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json), so every endpoint in the [API reference](/api-reference/markets/list-markets) is an async method on `lean_api::Client` with typed requests and responses. The crate uses the 2024 edition, so it needs a recent stable Rust. It runs on Tokio, and TLS uses rustls, so there is no OpenSSL dependency. ## Install The crate is on crates.io once 0.1.0 is published. Add it with Tokio to run it, and `uuid` for order IDs: ```bash theme={"dark"} cargo add lean-api-sdk uuid --features uuid/v4 cargo add tokio --features macros,rt-multi-thread ``` Or in `Cargo.toml`: ```toml Cargo.toml theme={"dark"} [dependencies] lean-api-sdk = "0.1" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } uuid = { version = "1", features = ["v4"] } ``` The package is `lean-api-sdk` and the library is `lean_api`. ## Create a client The examples use the same two environment variables as the [quickstart](/quickstart): ```bash theme={"dark"} export LEAN_API_URL="https://api.lean.xyz" export LEAN_API_KEY="lean_sk_test_..." ``` ```rust theme={"dark"} use lean_api::Client; #[tokio::main] async fn main() -> Result<(), Box> { let lean = Client::from_env()?; Ok(()) } ``` `Client::from_env` reads `LEAN_API_KEY`, and `LEAN_API_URL` when it is set. The base URL defaults to `https://api.lean.xyz`. Keep the key in the environment and never log it; the client leaves it out of `Debug` output. [Authentication](/authentication#create-a-key) shows how to create a key. Each method returns a `Response`: the result is in `data` and the request ID in `meta.request_id`. ## Find a market ```rust theme={"dark"} use lean_api::{ListMarketsQuery, ListMarketsQueryStatus}; let markets = lean .list_markets(&ListMarketsQuery { league: Some("nfl".into()), status: Some(ListMarketsQueryStatus::Open), limit: Some(20), ..Default::default() }) .await? .data; let market = markets .markets .iter() .find(|item| item.legs.iter().any(|leg| leg.tradable)) .ok_or("No tradable market")?; println!("{} {} {} {}", market.id, market.fixture.title, market.group.label, market.outcome); ``` Pick a market whose `legs` include one with `tradable: true`. [Markets and IDs](/markets) explains each field. `lean.get_market(id)` reads one market. ## Quote and preview Check what an order would do before you place it. Neither call places or reserves anything. ```rust theme={"dark"} use lean_api::{Action, CreateOrderRequest, QuoteMarketQuery, TimeInForce}; let quote = lean .quote_market( &market.id, &QuoteMarketQuery { action: Some(Action::Buy), notional: Some("25".into()), ..Default::default() }, ) .await? .data; println!("{} {} {}", quote.executable_quantity, quote.expected_total_usd, quote.expires_at); // A new ID for each new order. Reuse it only to retry this same order. let client_order_id = format!("bot-{}", uuid::Uuid::new_v4().simple()); let order = CreateOrderRequest { notional: Some("25".into()), time_in_force: Some(TimeInForce::Ioc), ..CreateOrderRequest::new(client_order_id, &market.id, Action::Buy) }; let preview = lean.preview_order(&order).await?.data; println!("{} {:?}", preview.would_submit, preview.warnings); ``` `CreateOrderRequest::new` sets the required fields and leaves the rest unset. Quote again after `expires_at`. A blocking warning means the order would be refused. See [Preview](/preview). ## Place an order This buys 25 USD of the outcome at once and cancels whatever can't fill: ```rust theme={"dark"} if !preview.would_submit { return Err("The preview says this order would be refused".into()); } let placed = lean.create_order(&order).await?.data; println!("{} {} {} {}", placed.id, placed.status, placed.filled_quantity, placed.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, set `quantity` and `limit_price`. See [Buying a dollar amount](/orders#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. Prices, quantities and amounts are decimal strings exactly as the API sends them, so nothing is rounded through `f64`. Parse them with the decimal type your program already uses. ## Read an order ```rust theme={"dark"} let read = lean.get_order(&placed.id).await?.data; println!("{} {} {:?}", read.status, read.filled_quantity, read.avg_fill_price); ``` If the response to `create_order` never arrived, look the order up by its `client_order_id`: ```rust theme={"dark"} use lean_api::ListOrdersQuery; let found = lean .list_orders(&ListOrdersQuery { client_order_id: Some(order.client_order_id.clone()), ..Default::default() }) .await? .data; for item in &found.orders { println!("{} {}", item.id, item.status); } ``` Then reconcile with `lean.get_positions(&Default::default())` and `lean.get_balances()`. See [Orders and idempotency](/orders#reconcile). ## Errors, timeouts and retries A response that isn't a success returns `Error::Api`, and `error.api()` gives you its fields: the HTTP `status()`, the error `code()`, the `request_id()` to quote when you report a problem, and `details()` with structured details such as validation issues: ```rust theme={"dark"} let placed = match lean.create_order(&order).await { Ok(placed) => placed.data, Err(error) => { if let Some(api) = error.api() { eprintln!("{} {:?} {:?} {:?}", api.status(), api.code(), api.request_id(), api.details()); } return Err(error.into()); } }; ``` [Errors](/errors) lists every code. `Error::Transport` means the request did not complete: the connection failed or it timed out. A POST that fails this way may still have reached the API. Each request times out after 30 seconds. Build the client with `Client::builder()` to change it: ```rust theme={"dark"} use std::time::Duration; let lean = Client::builder() .api_key(std::env::var("LEAN_API_KEY")?) .timeout(Duration::from_secs(10)) .max_read_retries(2) .build()?; ``` GET requests are retried twice on connection errors, 429 and 5xx responses, with jittered backoff that follows `Retry-After`. Set `max_read_retries(0)` to turn that off. POST, PATCH and DELETE requests are never retried. After a timeout on `create_order`, look the order up with `list_orders` and its `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: ```rust theme={"dark"} let balances = lean.get_balances().await?.data; if balances.livemode { return Err("This program expects a test key".into()); } ``` To start over with a test key, `lean.reset_test_mode()` 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](/test-mode). ## Stream updates `Client::stream` keeps a WebSocket open. It reconnects with a new ticket after a drop and reads every page of orders again over REST after each reconnect: ```rust theme={"dark"} use lean_api::{StreamChannel, StreamEvent, StreamOptions, StreamStatus}; let (stream, mut events) = lean.stream(StreamOptions { channels: vec![StreamChannel::Orders, StreamChannel::Positions], ..Default::default() })?; stream.subscribe([StreamChannel::book(market.id.clone())]); while let Some(event) = events.recv().await { match event { StreamEvent::Order(order) => println!("{} {}", order.id, order.status), StreamEvent::OrdersResync(orders) => println!("{} orders after a reconnect", orders.len()), StreamEvent::Stale { channel, stale } => println!("{channel:?} stale: {stale}"), StreamEvent::Status(StreamStatus::Disconnected(reason)) => println!("stopped: {reason:?}"), _ => {} } } ``` `OrdersResync` replaces the order state you hold. A channel reports `Stale { stale: true }` from a drop until its first update on the next connection. A refused key stops the stream instead of retrying. Events queue up to `StreamOptions::event_buffer`, 1024 by default. Past that the stream stops reading the socket until you catch up. Call `stream.close()` when you are done; dropping every handle or the event receiver also stops it. See [Streaming](/streaming) for each channel. ## Types Every request and response type is exported from `lean_api` by name, such as `CreateOrderRequest`, `OrderPreview`, `Order` and `Market`. Enums such as `Action`, `TimeInForce` and `OrderStatus` print as the API's strings: ```rust theme={"dark"} use lean_api::{Order, OrderStatus}; fn is_resting(order: &Order) -> bool { matches!(order.status, OrderStatus::Open | OrderStatus::PartiallyFilled) } ``` ## Methods Method names follow the [API reference](/api-reference/markets/list-markets). The ones used most: | Method | Endpoint | | - | - | | `list_markets`, `get_market` | `GET /v1/markets`, `GET /v1/markets/{id}` | | `quote_market` | `GET /v1/markets/{id}/quote` | | `preview_order` | `POST /v1/orders/preview` | | `create_order` | `POST /v1/orders` | | `get_order`, `list_orders` | `GET /v1/orders/{id}`, `GET /v1/orders` | | `cancel_order` | `POST /v1/orders/{id}/cancel` | | `list_fills` | `GET /v1/fills` | | `get_positions`, `get_balances` | `GET /v1/positions`, `GET /v1/balances` | | `reset_test_mode` | `POST /v1/test/reset` | Changes to the crate are listed in the [changelog](/changelog). # Order statuses Source: https://lean.mintlify.app/statuses What each order status means and which ones are final. | `status` | Final | Meaning | | - | - | - | | `pending` | No | Lean accepted the order. The venue has not confirmed it yet. | | `open` | No | Resting on the venue's book. | | `partially_filled` | No | Some shares filled; the rest is still working. | | `cancel_requested` | No | You canceled the order and the venue has not confirmed the cancel yet. It ends `canceled`, or `filled` if a fill beat the cancel. `filled_quantity` shows any shares filled so far. | | `filled` | Yes | Every share filled. | | `canceled` | Yes | Canceled by you, or the unfilled part of an `ioc` order. `filled_quantity` shows any shares that filled first; an `ioc` order that matched nothing is `canceled` with `0`. A canceled `ioc` order has `status_reason.code` `IOC_REMAINDER_CANCELED`. | | `rejected` | Yes | Not placed. `status_reason.code` and `status_reason.message` say why. | | `expired` | Yes | The venue expired the order. | | `unconfirmed` | No | The venue did not confirm the order, so it may or may not be on the venue. Read it back by `client_order_id`; do not resend it. `status_reason.code` is `SUBMISSION_UNKNOWN`. | | `needs_attention` | No | A leg Lean cannot settle on its own. It stays live until Lean's operators resolve it. `status_reason.code` is `NEEDS_ATTENTION` or a more specific code. | `status_reason` is `{ code, message }` on `rejected`, `unconfirmed` and `needs_attention`, and on a canceled `ioc` order and its canceled legs. It is `null` otherwise. On `rejected`, `unconfirmed` and `needs_attention` the order copies it from the first leg in the order's status. | `status_reason.code` | Meaning | | - | - | | `VENUE_REJECTED` | The venue refused the order. A venue rejection can carry a more specific venue code instead. | | `SUBMISSION_UNKNOWN` | The venue did not confirm the submit. | | `VENUE_UNKNOWN` | An unconfirmed order the venue still had no record of ten minutes after placement. | | `NEEDS_ATTENTION` | Lean cannot settle the leg on its own. | | `ROUTE_PAYMENT_FAILED` | The routed order's payment did not go through. | | `IOC_REMAINDER_CANCELED` | An `ioc` order or leg ended `canceled`: the venue canceled whatever did not fill at once. `filled_quantity` is what filled, `0` if nothing matched. | New codes can appear without a new version; treat one you do not recognize by the order's `status`. `venue_status` carries the venue's own state, and `venue_order_id` its order ID, for your reconciliation. On a split order both are `null`. Each entry in `legs` has its own `status`, `status_reason`, `venue_status` and `venue_order_id`, and the order's `status` is worked out from all of them: * When every leg is final, the order is `filled` if every leg filled. Otherwise it is `canceled` if any leg filled or was canceled, then `expired`, then `rejected`. * While any leg is working, the first that applies wins: `needs_attention`, `unconfirmed`, `cancel_requested` (a leg waits on its venue to confirm a cancel), `partially_filled` (any shares filled), `open`, `pending`. ## Typical paths ```mermaid theme={"dark"} stateDiagram-v2 [*] --> pending pending --> open pending --> filled pending --> canceled pending --> rejected pending --> unconfirmed unconfirmed --> open unconfirmed --> filled unconfirmed --> rejected open --> partially_filled open --> filled open --> canceled open --> expired partially_filled --> filled partially_filled --> canceled open --> cancel_requested partially_filled --> cancel_requested cancel_requested --> canceled cancel_requested --> filled ``` `needs_attention` can follow any working status and is left out of the diagram. An `ioc` order never rests: it ends `filled`, or `canceled` with whatever filled first, `0` if nothing matched, and `status_reason.code` `IOC_REMAINDER_CANCELED`. # Stop losses and take profits Source: https://lean.mintlify.app/stop-losses Sell shares you hold once the market moves to a price you choose. A stop loss watches the best bid for shares your trading account holds and sells them when the bid reaches your trigger price. Lean watches the market for you, so your program does not need to stay connected. There are two types: * `stop_loss` sells once the best bid falls to `trigger_price` or below. * `take_profit` sells once the best bid rises to `trigger_price` or above. Both run on every venue: Kalshi, Polymarket, Polymarket US and Hyperliquid. This example uses a test key, so nothing real moves: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/stop-losses" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "market_id": "'"$MARKET_ID"'", "venue": "polymarket", "type": "stop_loss", "trigger_price": "0.4", "quantity": "25", "slippage_limit": "0.05" }' ``` | Field | Meaning | | - | - | | `market_id` | A `mkt_…` ID from `GET /v1/markets`. | | `venue` | `kalshi`, `polymarket`, `polymarket_us` or `hyperliquid`: the venue that holds the shares to sell. Shares stay on the venue that bought them, so a stop loss sells on that venue only. | | `type` | `stop_loss` or `take_profit`. | | `trigger_price` | The best bid, in dollars per share, that starts the sale. It must fit the market's price ticks and be one the bid has not reached yet: below the current best bid for a `stop_loss`, above it for a `take_profit`. See [Triggers the bid already meets](#triggers-the-bid-already-meets). | | `quantity` | Shares to sell, as a decimal string. | | `slippage_limit` | Optional. How far below `trigger_price` the sale may fill, in dollars above `0` and at most `0.2`, on the market's price tick and below `trigger_price`. The default is `0.05`. | | `expires_at` | Optional. When the stop loss lapses, as an ISO 8601 time. A sale still resting then is canceled. Leave it out to keep the stop loss until you cancel it. | The key needs the `trade` scope. The answer is `200` with the stop loss, which reads `active` while it watches the market. ## Triggers the bid already meets A trigger the best bid has already reached would start the sale on the next price check, so Lean refuses it with `400 VALIDATION_ERROR` on test and live keys alike. The message names the current best bid. * A `stop_loss` with `trigger_price` at or above the best bid is refused. To sell once the bid rises, send a `take_profit`. * A `stop_loss` on a market with no bid is refused too, since an empty bid side starts its sale. * A `take_profit` with `trigger_price` at or below the best bid is refused. A `take_profit` on a market with no bid is accepted and waits for one. The bid is read from the venue's book when the request arrives. If the book cannot be read, the request is refused with `503 UPSTREAM_ERROR` and nothing is created; send it again. ## How the sale works When the best bid reaches the trigger, Lean sells the shares on the venue at once, no lower than `trigger_price` minus `slippage_limit`. Whatever does not sell straight away rests on the book at that lowest price until it fills, you cancel it, or `expires_at` passes. Once the trigger is reached the sale keeps going even if the bid moves back. `triggered_at` and `triggered_price` record when it was reached and the best bid at that moment, and `filled_quantity` and `avg_fill_price` show what sold so far. | `status` | Final | Meaning | | - | - | - | | `active` | No | Watching the market. | | `triggered` | No | The bid reached the trigger and the sale is starting. | | `executing` | No | Selling right now. | | `partial` | No | Part of the quantity sold. The rest is resting on the book. | | `filled` | Yes | Every share sold. | | `canceled` | Yes | Canceled by you. | | `expired` | Yes | `expires_at` passed, or the shares were no longer held when the sale started. | | `failed` | Yes | Lean could not sell, for example because the venue kept refusing the sale. | ## Limits on what can be sold * The stop losses on the same shares together sell at most what the account holds. Shares already offered by a resting sell order count as taken. A stop loss above what is left is refused with `400 VALIDATION_ERROR`, and the message says how many shares are available. * A sale must be at least the market's minimum number of shares. * The market must be open and must trade on the venue you name. A market that cannot be traded on that venue is refused with `422 VALIDATION_ERROR` and `details.reason: "NO_EXECUTABLE_VENUE"`, and a venue the trading account does not allow with `details.reason: "VENUE_NOT_ALLOWED"`. * The sale counts toward the key's and account's rolling day as an order of `quantity` shares at `trigger_price` would, from when the stop loss is created. A sale only takes risk off, so neither the per order limit nor the daily limit refuses it. A test key's stop losses count toward its own day. * Creating a stop loss is refused with `503 FEATURE_DISABLED` while trading is paused, or while Lean has paused stop losses on the venue. See [Pause trading](/orders#pause-trading). ## Track and cancel `GET /v1/stop-losses` lists the stop losses of the key's trading account, newest first: every one still working, and those that ended in the last hour. A live key also sees the stop losses made in the Lean app on that account. `GET /v1/stop-losses/{id}` reads one. Cancel one with `DELETE /v1/stop-losses/{id}`: ```bash theme={"dark"} curl -sS -X DELETE "$LEAN_API_URL/v1/stop-losses/$STOP_LOSS_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` The answer is `200` with the stop loss and `cancel_requested_at` set. A live stop loss keeps its status for a moment while Lean stops it and cancels any sale it has resting, then reads `canceled`. A test stop loss reads `canceled` at once. Canceling works while trading is paused, and a stop loss that has already ended is refused with `400 VALIDATION_ERROR`. Pausing trading does not stop a stop loss that is already watching the market. Cancel it if you want it gone. ## Test keys A test key's stop loss is checked like a live one, against the market and the test account's simulated shares, and it can be listed and canceled. It never sells. See [Test mode and live mode](/test-mode). # Streaming Source: https://lean.mintlify.app/streaming Follow orders, positions, balances and market books over one WebSocket. The stream pushes the same objects the REST API returns, as they change. One WebSocket carries every channel you subscribe to, for one key, its trading account and its mode. ## Get a ticket Your API key never travels over the socket. Exchange it for a ticket first: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/ws/token" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ```json theme={"dark"} { "success": true, "data": { "token": "", "expires_at": "2026-11-01T20:25:00.000Z", "livemode": false }, "meta": { "requestId": "" } } ``` A ticket opens one connection and is good for 60 seconds, or until the key expires if that is sooner. Request a new one for each connection, including every reconnect. A `503` with `FEATURE_DISABLED` means streaming is not available right now. ## Connect and authenticate Open the WebSocket at `wss://api.lean.xyz/v1/ws`, the `/v1/ws` path on the same host as the REST API. Test and live keys use the same URL; the ticket sets the mode. Within 10 seconds, send the ticket as the first frame: ```json theme={"dark"} { "op": "auth", "ticket": "" } ``` ```json theme={"dark"} { "type": "authenticated", "livemode": false, "key_id": "" } ``` Every frame in both directions is one JSON text object. Frames you send must not carry fields other than the ones shown here. ## Subscribe ```json theme={"dark"} { "op": "subscribe", "channels": [ { "channel": "orders" }, { "channel": "positions" }, { "channel": "balances" }, { "channel": "book", "market_id": "mkt_..." } ] } ``` The reply lists the channels you named: ```json theme={"dark"} { "type": "subscribed", "channels": [{ "channel": "orders" }, { "channel": "positions" }] } ``` Send `{"op":"unsubscribe","channels":[...]}` to stop a channel; the reply is an `unsubscribed` frame. A connection holds at most 32 channels. Send `{"op":"ping"}` at any time; the reply is `{"type":"pong"}`. Channels always follow the ticket's account and mode; no frame can name another. ## Channels | Channel | Frame | Holds | | - | - | - | | `orders` | `{"type":"order","order":{...}}` | Each new state of an order, as `GET /v1/orders/{id}` returns it. | | `positions` | `{"type":"positions","positions":{...}}` | The whole `GET /v1/positions` result. | | `balances` | `{"type":"balances","balances":{...}}` | The whole `GET /v1/balances` result. | | `book` | `{"type":"book","market_id":"...","book":{...}}` | The combined order book of one market. | ### Orders Each order's states only move forward. The channel sends states that happen after you subscribe, so call `GET /v1/orders` once after `subscribed` to cover anything earlier. The channel never skips an order state while the connection stays open. If Lean cannot be sure every state reached you, it closes the connection with `1013` and `UPSTREAM_ERROR`, so reconnect and call `GET /v1/orders` again. ### Positions and balances Each frame is a whole state that replaces the one before it. The newest state arrives first, then each change. They are sent after every order change on the account and refreshed about every ten seconds otherwise. ### Book A book frame holds one market's book across every venue that lists it, at a depth of 20 levels per side. `market_id` takes a market ID or a [venue symbol](/markets#venue-symbols); a symbol's channel holds only the listing it names, under the market's ID. Each frame's top level `market_id` is the ID or symbol you subscribed with, so you can follow one market under several names and still tell their frames apart: ```json theme={"dark"} { "type": "book", "market_id": "", "book": { "market_id": "mkt_...", "venues": [ { "venue": "polymarket", "ticker": "", "side": "yes", "bids": [{ "price": "0.52", "quantity": "100" }], "asks": [{ "price": "0.55", "quantity": "40" }], "bid_quantity": "100", "ask_quantity": "40", "bid_notional_usd": "52", "ask_notional_usd": "22" } ], "combined": { "bids": [ { "price": "0.52", "quantity": "100", "venues": [{ "venue": "polymarket", "quantity": "100" }] } ], "asks": [ { "price": "0.55", "quantity": "40", "venues": [{ "venue": "polymarket", "quantity": "40" }] } ] }, "total_bid_quantity": "100", "total_ask_quantity": "40", "total_bid_notional_usd": "52", "total_ask_notional_usd": "22", "unavailable": [], "as_of": "2026-11-01T20:25:00.000Z", "livemode": false } } ``` * Bids are what a sell fills against and asks are what a buy fills against, for the market's outcome. Prices and quantities are decimal strings. * `combined` merges every venue's levels by price and shows each venue's share. * Quantity and notional totals cover every level read, not only the 20 listed. * A venue whose book could not be read appears in `unavailable` instead of as an empty book. * The book updates about once a second, from live venue data where Lean has it and from a venue poll otherwise. `as_of` is when the frame was built. * Each frame replaces the one before it. A book channel for a market that does not exist, or for a symbol that names more than one market, sends nothing. A session that reads positions, balances or books too slowly skips ahead to the newest state. ## Errors and closing After authentication, a bad frame is answered with an error frame and the connection stays open: ```json theme={"dark"} { "type": "error", "code": "VALIDATION_ERROR", "message": "Unrecognized frame" } ``` Before authentication, or when the connection must end, Lean sends the error frame and then closes the socket: | Close code | `code` | When | | - | - | - | | `1008` | `UNAUTHORIZED` | The ticket is invalid, expired or already used; no `auth` frame arrived within 10 seconds; a frame came before `auth`; or the key was revoked or expired. | | `1008` | `VALIDATION_ERROR` | The first frame was not an `auth` frame. | | `1003` | `VALIDATION_ERROR` | A binary frame was sent. | | `1013` | `RATE_LIMITED` | The session read order states too slowly to keep up. | | `1013` | `UPSTREAM_ERROR` | Lean could not check whether the ticket was already used. | | `1013` | `UPSTREAM_ERROR` | Order updates were interrupted inside Lean, so some may not have reached the session. Only sessions subscribed to `orders`, or sending a `subscribe` that names it, close this way; that `subscribe` gets no `subscribed` reply. | | `1012` | none | Lean is restarting. | Revoking a key closes its open streams with `1008` and `UNAUTHORIZED`. Pausing trading on an account does not close streams, since they only read. ## Reconnecting Connections end: Lean restarts and moves streams between servers, networks drop, and tickets expire. Plan for it. Frames that would have been sent while you were disconnected are not sent later, so a reconnect always rebuilds state from fresh data. ### Notice a lost connection A connection can stop delivering frames without closing. Send `{"op":"ping"}` every 10 seconds. If no frame of any kind, `pong` included, arrives for 25 seconds, close the socket and reconnect. Treat a socket that has not answered `auth` with `authenticated` within 15 seconds the same way. ### Wait before retrying Wait a random delay between zero and `min(30 seconds, 0.5 seconds × 2^attempt)` before each attempt, where `attempt` counts from zero. The random spread keeps many clients that lost their connections together from retrying together. Reset `attempt` to zero once a connection has stayed authenticated for 15 seconds. ### Reconnect 1. Get a new ticket from `POST /v1/ws/token`. A ticket works once, so never reuse one. 2. Open `/v1/ws` and send the `auth` frame. 3. After `authenticated`, send one `subscribe` frame naming every channel you want. Lean keeps nothing from the old connection. 4. Rebuild state from what arrives: * **Books:** mark each book stale when the connection drops. The first `book` frame for that market replaces it. * **Positions and balances:** the newest state arrives first after `subscribed` and replaces yours. * **Orders:** after `subscribed`, call `GET /v1/orders` and merge it with the order frames you receive. For each order keep the copy with the latest `updated_at`. ### Which closes to retry | What happened | What to do | | - | - | | Close `1012` | Lean is restarting. Reconnect with a new ticket after the delay. | | Close `1013` with `RATE_LIMITED` | Reconnect with a new ticket after the delay, and read frames faster. | | Close `1013` with `UPSTREAM_ERROR` | Lean could not check the ticket, or order updates were interrupted. Reconnect with a new ticket after the delay, subscribe again and call `GET /v1/orders`. | | Any other close, or no close at all | Reconnect with a new ticket after the delay. | | The upgrade answered HTTP `502`, `503` or `504`, or no connection could be made | Retry with a new ticket after the delay. | | `POST /v1/ws/token` answered `5xx` or did not answer | Retry it after the delay. No new connection can start until it succeeds. | | Close `1008` | The ticket or the key was refused. Try once more with a new ticket. Stop after three `1008` closes in a row. | | `POST /v1/ws/token` answered `401` or `403` | The key is revoked, expired or lacks access. Stop and fix the key. | ### What to expect * While you reconnect, no frames arrive. Most reconnects take a few seconds, longer during an outage. Show data as stale until its first frame after the reconnect. * Lean never replays missed frames. Books, positions and balances recover with their next frame; orders recover through `GET /v1/orders`. * Your client cannot tell which server it reached, and does not need to: tickets, channels and frames behave the same on every connection. # Test mode and live mode Source: https://lean.mintlify.app/test-mode Build against simulated orders with a test key, then switch to a live key to trade for real. Every API key is either a test key or a live key. The key you send decides the mode. The base URL, the endpoints and the request bodies are the same in both, and both kinds of key use the same trading account. A new key is a test key unless you create it as a live key. A test key never sees or spends the account's real balances. It sees simulated balances that start at 10,000 on each venue (USD on Kalshi and Polymarket US, pUSD on Polymarket, USDC on Hyperliquid), and test orders draw only on those. Markets and quotes are the same real market data in both modes. | | Test mode | Live mode | | - | - | - | | Key prefix | `lean_sk_test_` | `lean_sk_live_` | | Orders and fills | Simulated. Nothing is sent to a venue. | Placed on venues and filled for real. | | Money | None moves. | Real funds in the key's trading account. | | Balances | Simulated. Each venue starts at 10,000. | The account's real balances. | | Orders and positions | Test data, kept apart from live data. | Your live data. | | `livemode` in each successful response | `false` | `true` | ## Start with a test key Build and test your integration with a test key. You can place, cancel and reconcile as many orders as you like without risking money, and none of them appear in your live account. ```bash theme={"dark"} export LEAN_API_URL="https://api.lean.xyz" export LEAN_API_KEY="lean_sk_test_..." ``` [Authentication](/authentication#create-a-key) shows how to create a key. The [quickstart](/quickstart) and the **Try it** button in the [API reference](/api-reference/markets/list-markets) work with either kind of key. ## How test orders behave * A test order fills against the public order books as soon as you place it. A buy takes the best ask and a sell the best bid, up to the size shown at that price, when that price is within your limit and slippage bound. It fills at the book's price, which can be better than your limit. Its `legs` have no `venue_order_id`. * A buy sized with `notional` walks the whole public book instead, from the best ask, until the dollars are spent or your limit or slippage bound is reached. It never spends more than `notional`, as a live one does. * What doesn't fill at once follows `time_in_force`. With `ioc` the rest is canceled. With `fok` nothing fills unless all of it can, and the order reads `canceled`. With `gtc` or `gtd` the rest stays on the order, which reads `open` or `partially_filled`. Each time you read the order, the rest fills at its limit price, with no fee, from what the public book then shows at or better than that limit. A `gtd` order read after its `expires_at` reads `expired`. * Cancel a resting test order with `POST /v1/orders/{id}/cancel`. What filled stays filled. Canceling a test order that has finished returns `409 CONFLICT`. * The one call works the same way, between Polymarket and Hyperliquid. When a test buy can't be paid for from the simulated balance on the venues with a book, Lean pays from the other venue's simulated balance and fills on the venue with the book. The order fills at once at the asks that venue's public book shows, and `route` in the response names both venues, as it would for a live order. When those asks can't fill the whole size within your limit, the buy is refused with `422 VALIDATION_ERROR`, as a live one is. No real funds move. The key needs the `route` scope, which a **Read and trade** key made in the app has; without it the buy is refused with `422 VALIDATION_ERROR` and `details.reason: "INSUFFICIENT_FUNDS"`. See [Paying from the other venue](/orders#paying-from-the-other-venue). * A test sell needs enough simulated shares on one venue. Otherwise it is refused with `422 VALIDATION_ERROR` and `details.reason: "INSUFFICIENT_HOLDINGS"`. * Your key's per order and daily limits apply to test orders too. * Test and live data are kept apart. A test key can't read a live order, and a live key can't read a test order: either lookup returns `404 NOT_FOUND`. * A test-key preview's `route_plan` is priced over the public order books, as its orders are filled. See [Preview](/preview). * A test position's `mark_price` is read the way the Lean portfolio marks live positions: on Polymarket, the market's last trade, priced for the side held (1 minus the price for `no`); on Hyperliquid, the venue's mid for that side's book. `unrealized_pnl_usd` is the shares at that price less what they cost. Both are `null` when the market has no recent trade or the venue has no mid. * `GET /v1/pnl` with a test key totals unrealized profit and loss exactly as a live key does, over the test positions: a position on a resolved market counts none, and while any other position it counts has no mark, `unrealized_pnl_usd` and `total_pnl_usd` are `null`. Realized profit and loss is what the test fills realized. `GET /v1/pnl/history` has realized profit and loss only for a test key, because past marks of test positions aren't kept: each point's `unrealized_pnl_usd` and `total_pnl_usd` are `null`. * A test withdrawal takes simulated cash from the venue's test balance and moves no real funds. See [Withdrawals through the API](/funding#withdrawals-through-the-api). * A test stop loss or take profit is checked against the market and the test account's simulated shares, and can be listed and canceled, but it never sells. See [Stop losses and take profits](/stop-losses). * A test limit chase follows the venue's public book and fills in simulation once the best price on the other side reaches it. It is brought up to date each time you list or read it, and its fills show in the test account's positions and balances. See [Limit chases](/limit-chases). * A test [transfer](/transfers) moves simulated cash between the Polymarket and Hyperliquid test balances. It costs a flat 0.10 USD, its minimum is 2 USD, and it completes as soon as it is executed. * To start over, call [Reset test mode](/api-reference/test-mode/reset-test-mode). It clears the account's simulated orders, positions, withdrawals, transfers, stop losses and limit chases and returns test balances to the starting amount. ## Check the mode in code Every successful response has `livemode` in `data`. Error responses don't. Check it where your program would act on money, so a misconfigured key can't send test orders to production logic or the other way round. ```json theme={"dark"} { "success": true, "data": { "balances": [ … ], "unavailable": [], "livemode": false }, "meta": { "requestId": "" } } ``` ## Go live When your integration works in test mode: 1. Create a live key with only the access it needs. A test key can't be switched to live. Choose **Read only** for a program that only reads markets. 2. Set its per order and daily limits to what the program needs, and no more. Lean refuses any order above them before it reaches a venue. See [Authentication](/authentication#create-a-key). 3. Check that the key's trading account holds enough funds. Use `GET /v1/balances`. For Lean to pay for a buy with cash on the other venue, enable trading in the Lean app; otherwise such a buy is refused with `422 VALIDATION_ERROR` and `details.reason: "INSUFFICIENT_FUNDS"`. 4. To trade on Kalshi or Polymarket US, connect your API key for that venue in the Lean app. A live order there without one is refused with `403 FORBIDDEN`. Test orders don't need it. 5. Replace `LEAN_API_KEY` with the live key. Nothing else changes. 6. Preview before you place each order, and reconcile after it. See [Preview](/preview) and [Orders and idempotency](/orders#reconcile). > [!NOTE] > > Live keys trade real money. Lean can pause live trading platform wide, and while it is paused > live orders are refused and test keys keep working. While live trading is paused, a live key can still read markets, quotes, orders, balances and positions, and cancel orders. Placing an order with it returns `503 FEATURE_DISABLED` with `details.reason: "LIVE_TRADING_DISABLED"`: ```json theme={"dark"} { "success": false, "error": { "code": "FEATURE_DISABLED", "message": "Live order placement is switched off. Test keys can still place simulated orders.", "details": { "reason": "LIVE_TRADING_DISABLED" } }, "meta": { "requestId": "" } } ``` A preview with a live key still answers, with `would_submit: false` and a `TRADING_UNAVAILABLE` warning. > [!WARNING] > > A live key places real orders, including from the **Try it** button in the API reference. Keep > test and live keys in separate secrets, and never commit either to source control. # Transfers Source: https://lean.mintlify.app/transfers Move cash between your account's Polymarket and Hyperliquid balances. A transfer moves cash from one of your account's venues to the other: from Polymarket to Hyperliquid, or from Hyperliquid to Polymarket. The cash always lands in your own account's balance on the other venue. A transfer can't send funds to any other address or account. > [!NOTE] > > Transfers work with test keys today. A live key gets `503 FEATURE_DISABLED` with > `details.reason: "LIVE_TRANSFERS_UNAVAILABLE"`, and moves nothing. To use cash on the other venue > with a live key, place the order with `POST /v1/orders`: it pays from the other venue in the same > call. See [Paying from the other venue](/orders#paying-from-the-other-venue). A transfer takes three calls: 1. `POST /v1/transfers/quote` shows the fee, what arrives, the minimum and what you can send. 2. `POST /v1/transfers` creates the transfer and returns the message to sign. 3. `POST /v1/transfers/{id}/execute` sends your signature. Lean then moves the cash. Creating and executing need a key with the `trade` and `route` scopes. Quoting and reading need `read`. See [Authentication](/authentication#create-a-key). **1. Quote the transfer** ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/transfers/quote" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from_venue": "polymarket", "to_venue": "hyperliquid", "amount_usd": "25" }' ``` | Field | Meaning | | - | - | | `amount_usd` | What leaves `from_venue`. | | `fee_usd` | What the move costs. It comes out of `amount_usd`. | | `receive_usd` | What arrives on `to_venue`: `amount_usd` minus `fee_usd`. | | `minimum_usd` | The smallest `amount_usd` this route accepts. | | `available_usd` | What `from_venue` can send right now. | | `estimated_seconds` | How long the move usually takes once authorized. | | `expires_at` | Until when a transfer created now can be authorized. | | `warnings` | Why creating this transfer would be refused: `BELOW_VENUE_MINIMUM` under `minimum_usd`, `INSUFFICIENT_FUNDS` over `available_usd`. Empty means the amount fits the route; creating the transfer can still be refused under the key's notional limits, allowed venues or a placement block. | A quote never moves cash, and it answers even when the amount is below the minimum or above what is available, so you can show the numbers before you ask. Check `warnings` before you create the transfer. **2. Create the transfer** ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/transfers" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "client_transfer_id": "rebalance-2026-11-11-0001", "from_venue": "polymarket", "to_venue": "hyperliquid", "amount_usd": "25" }' ``` `client_transfer_id` is your ID for the transfer. Sending the same body again returns the same transfer, so a retry never moves cash twice. The same ID with a different body is `409 CONFLICT`, and `details.transfer_id` names the original. The transfer starts as `awaiting_authorization`, and `amount_usd` is held on `from_venue` at once: `available_usd` in `GET /v1/balances` drops by it. `authorization` says what to sign: | Field | Meaning | | - | - | | `authorization.signer_address` | The wallet that must sign: the account owner's. | | `authorization.expires_at` | Sign and execute before this time. | | `authorization.payloads` | The EIP-712 messages to sign, in order. Each has a `scheme` and `typed_data`. | **3. Sign and execute** Sign each `typed_data` exactly as returned, then send the signatures in the same order: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/transfers/$TRANSFER_ID/execute" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "authorization": "signature", "signatures": ["0x…"] }' ``` If the account has enabled trading in the Lean app, send `{ "authorization": "delegated" }` instead and Lean signs with the account's delegated signer. The transfer moves to `pending`, then `completed` once the cash arrives. Sending the same signatures again returns the transfer and moves nothing. ## Follow a transfer `GET /v1/transfers/{id}` returns one transfer. `GET /v1/transfers` lists the key's account's transfers, newest first. Pass `limit` (1 to 100) and the `next_cursor` from the previous page as `cursor` to read further back. | Status | Meaning | | - | - | | `awaiting_authorization` | Created. The amount is held on `from_venue` until you execute. | | `pending` | Authorized. The cash is on its way. | | `completed` | `receive_usd` arrived on `to_venue`. | | `failed` | The move did not happen. `failure_reason` says why, and the held amount is released. | | `expired` | Not executed before `authorization.expires_at`. The held amount is released. | ## Limits and refusals A transfer counts against the per order and daily limits of the key and its account like an order, and a paused key or trading account can't create or execute one. A quote still answers while paused. | Response | `details.reason` | When | | - | - | - | | `400 VALIDATION_ERROR` | | The venues are the same, a venue is not `polymarket` or `hyperliquid`, the amount is malformed, or the body has a field a transfer does not take. | | `422 VALIDATION_ERROR` | `BELOW_VENUE_MINIMUM` | `amount_usd` is below the route minimum. `details.minimum_usd` is the minimum. | | `422 VALIDATION_ERROR` | `INSUFFICIENT_FUNDS` | `from_venue` can't send `amount_usd`. `details.available_usd` is what it can send. | | `422 VALIDATION_ERROR` | `VENUE_NOT_ALLOWED` | The trading account does not allow one of the two venues. `details.allowed_venues` lists the ones it allows. | | `422 VALIDATION_ERROR` | `ORDER_NOTIONAL_LIMIT`, `DAILY_NOTIONAL_LIMIT` | The amount is over the key's or account's limits. | | `400 VALIDATION_ERROR` | `SIGNER_MISMATCH`, `INVALID_SIGNATURE` | A signature is not the owner's over the payload Lean returned. | | `403 FORBIDDEN` | `ACCOUNT_NOT_DELEGATED` | `delegated` was sent, but the account has not enabled trading in the Lean app. | | `409 CONFLICT` | `PAYMENT_ALREADY_AUTHORIZED` | The transfer was already authorized another way. | | `409 CONFLICT` | `QUOTE_EXPIRED` | The transfer expired before it was executed. Create a new one. | | `503 FEATURE_DISABLED` | `TRADING_PAUSED` | The key or its trading account is paused. | | `503 FEATURE_DISABLED` | `LIVE_TRANSFERS_UNAVAILABLE` | A live key. Transfers are test mode only for now. | ## In test mode A test transfer moves simulated cash between the test balances. It costs a flat 0.10 USD, its minimum is 2 USD, and it completes as soon as it is executed. [Reset test mode](/api-reference/test-mode/reset-test-mode) deletes the account's test transfers along with its test orders. # TypeScript SDK Source: https://lean.mintlify.app/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](/api-reference/markets/list-markets) 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](/quickstart): ```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](/authentication#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](/markets) 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](/preview). ## 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](/orders#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](/orders#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](/errors) 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](/test-mode). ## 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](/streaming) 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](/api-reference/markets/list-markets). 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](/changelog). # An AI agent that trades within a budget Source: https://lean.mintlify.app/use-cases/ai-agent-trading A research agent proposes trades on a read only key; an execution key places them after approval. **Who it's for:** teams putting LLM agents (Claude, GPT or your own models) into a trading or treasury workflow. **What you build:** an AI analyst that researches markets and proposes trades. A person, or a policy, approves each one, and the API executes it within limits you set. ## Call sequence **1. Research on a read only key** Give the research agent a key with only the `read` scope. It can call [List markets](/api-reference/markets/list-markets), [Quote a market](/api-reference/markets/quote-market), [Get a market orderbook](/api-reference/markets/retrieve-market-book) and [Get recent trades](/api-reference/markets/list-market-trades). An order attempt returns 403. **2. Propose with a preview** The agent writes a proposal and calls [Preview an order](/api-reference/orders/preview-order). The preview is the "here's exactly what would happen" for the approval step: legs, quantity, prices and whether it `would_submit`. **3. Execute on approval** An execution key with the `trade` scope and lowered limits calls [Place an order](/api-reference/orders/create-order) with the `client_order_id` from the proposal, so a double approval never trades twice. **4. Close the loop** The stream and [List fills](/api-reference/orders/list-fills) feed results back to the agent. [Pause order placement](/api-reference/account/pause-trading) lets the agent, or a monitor, stop everything. A person signed in to Lean can revoke either key at any time with [Revoke an API key](/api-reference/api-keys/revoke-api-key); a revoked key gets 401. ## Starter Create both keys in Lean under Settings → **API**: one with only `read`, one with `trade` and low limits. Then: ```bash theme={"dark"} # Research agent (read only key) curl -sS "$LEAN_API_URL/v1/markets?league=nfl&limit=20" \ -H "Authorization: Bearer $LEAN_READ_KEY" # Approval step: show the human this response curl -sS -X POST "$LEAN_API_URL/v1/orders/preview" \ -H "Authorization: Bearer $LEAN_READ_KEY" \ -H "Content-Type: application/json" \ -d '{"client_order_id":"proposal-42","market_id":"'"$MARKET_ID"'","action":"buy", "quantity":"5","limit_price":"0.42","time_in_force":"ioc"}' # Approved: the execution key sends the same body to /v1/orders ``` ## Guardrails * **Read only keys.** A `read` key can research and preview, and is refused with 403 if it tries to place an order. * **Spending caps.** Per order and rolling 24 hour limits live on the execution key, and the key can only lower them. * **Idempotency.** The proposal's `client_order_id` makes execution safe to retry. * **Kill switch and revocation.** Pause a key or the whole account in one call, and revoke a key from Lean at any time. # Best price execution across venues Source: https://lean.mintlify.app/use-cases/best-price-execution One order, filled at the best combined price across Polymarket and Hyperliquid. **Who it's for:** prop desks, funds and market makers who trade sports outcomes on more than one venue. **What you build:** an execution layer that gets one fill at the best combined price across Polymarket and Hyperliquid, without integrating either venue yourself. ## Call sequence **1. Find the market** [List markets](/api-reference/markets/list-markets) (filter by `league`, `sport` or `starts_after`), then [Get a market](/api-reference/markets/retrieve-market). **2. See the depth** [Quote a market](/api-reference/markets/quote-market) prices a size across venues. [Get a market orderbook](/api-reference/markets/retrieve-market-book) shows each venue's book. **3. Preview** [Preview an order](/api-reference/orders/preview-order) returns the plan: the legs per venue, the executable quantity and the slippage check. Nothing is sent. **4. Place it** [Place an order](/api-reference/orders/create-order) with the same body. Lean places the legs on the venues the plan chose. Set `client_order_id` so a retry returns the same order. If the cash is on one venue and the book on the other, the same call moves the cash and buys, and `route` in the response names both venues. See [Paying from the other venue](/orders#paying-from-the-other-venue). Set `best_price: true` to take that route whenever it costs less than buying where the cash is, even when the cash would cover the buy. See [Best price across venues](/orders#best-price-across-venues). **5. Follow and reconcile** [Create a stream ticket](/api-reference/streaming/create-stream-ticket) to follow order, position and balance updates over the WebSocket, then confirm with [Get an order](/api-reference/orders/retrieve-order) and [List fills](/api-reference/orders/list-fills). ## Starter ```bash theme={"dark"} # 1. Price 5 shares across venues curl -sS "$LEAN_API_URL/v1/markets/$MARKET_ID/quote?quantity=5" \ -H "Authorization: Bearer $LEAN_API_KEY" # 2. See the plan; nothing is sent curl -sS -X POST "$LEAN_API_URL/v1/orders/preview" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"client_order_id":"exec-0001","market_id":"'"$MARKET_ID"'","action":"buy", "quantity":"5","limit_price":"0.42","time_in_force":"ioc","max_slippage_bps":50}' # 3. Place it: send the same body to /v1/orders ``` ## Guardrails * **Price protection.** `limit_price` is the worst price per share you accept, and `max_slippage_bps` bounds how far each venue order may trade from that venue's own best price, so venues quoting different prices can each fill. `limit_price` caps every venue alike. * **Fill or nothing.** `all_or_none` with `time_in_force: ioc` places the order only if the books can fill the whole quantity. It is best effort: a book can move before the fill, so a partial fill is still possible. See [All or none](/orders#all-or-none). Polymarket takes `ioc` buys by dollar amount only, so a buy sized with `quantity` fills on Hyperliquid. * **Safe retries.** The same `client_order_id` always returns the same order. * **Spending caps.** Every order is checked against the key's per order and rolling 24 hour limits before it reaches a venue. * **Precise sizing.** Quantities are in steps of 0.01 shares. # Funding and treasury automation Source: https://lean.mintlify.app/use-cases/funding-automation Find deposit assets and addresses, then watch balances. **Who it's for:** treasury and operations teams automating how a trading account is funded. **What you build:** a funding job that knows which assets each venue accepts, keeps a deposit address ready for each, and confirms when balances arrive. ## Call sequence **1. What can be deposited** [List deposit assets](/api-reference/deposits/list-deposit-assets): chains and tokens each venue accepts, with the provider's minimum. **2. Where to send it** [Get deposit addresses](/api-reference/deposits/list-deposit-addresses) returns the addresses already created. [Create deposit addresses](/api-reference/deposits/create-deposit-addresses) creates any that are missing; repeating it returns the same addresses. Neither moves money. **3. Watch it land** [Get balances](/api-reference/account/list-balances). Building against a test key? [Reset test mode](/api-reference/test-mode/reset-test-mode) clears simulated orders and positions and returns test balances to the starting amount, so every run starts clean. ## Starter ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/deposits/assets" \ -H "Authorization: Bearer $LEAN_API_KEY" curl -sS "$LEAN_API_URL/v1/deposits/addresses?venue=hyperliquid" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ## Guardrails * **Safe to repeat.** Creating deposit addresses is idempotent: run it on every deploy and you get the same addresses back. * **Read before you write.** Getting addresses never creates one, and neither call moves money. * **Provider minimums up front.** Each deposit asset lists its minimum, so your job never sends an amount too small to credit. # Hedging sportsbook exposure Source: https://lean.mintlify.app/use-cases/hedging-exposure Buy the other side on prediction market liquidity when liability crosses a threshold. **Who it's for:** sportsbooks, B2B odds providers and fantasy operators carrying one sided liability on a match. **What you build:** an automatic hedger. When liability on an outcome crosses a threshold, it buys the other side on prediction market liquidity. ## Call sequence **1. Trigger** Your liability feed crosses a threshold. Find the market with [List markets](/api-reference/markets/list-markets). **2. Price and place the hedge** [Quote a market](/api-reference/markets/quote-market) → [Preview an order](/api-reference/orders/preview-order) → [Place an order](/api-reference/orders/create-order). If the cash is on the other venue, the same call moves it and buys. **3. Track and unwind** Confirm each hedge with [Get an order](/api-reference/orders/retrieve-order) and [List fills](/api-reference/orders/list-fills), and watch cash with [Get balances](/api-reference/account/list-balances). When liability falls, unwind with a sell through [Place an order](/api-reference/orders/create-order). ## Starter ```bash theme={"dark"} # Hedge: buy 50 shares of the other side, worst price 0.55, fill now or not at all curl -sS -X POST "$LEAN_API_URL/v1/orders" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"client_order_id":"hedge-match123-1","market_id":"'"$MARKET_ID"'","action":"buy", "quantity":"50","limit_price":"0.55","time_in_force":"ioc","all_or_none":true}' ``` ## Guardrails * **Price protection.** `limit_price` sets the worst price you pay for the hedge. * **Fill or nothing.** `time_in_force: ioc` with `all_or_none` places the hedge only if the books can fill the full size now. It is best effort: a book can move before the fill, so a partial hedge is still possible. See [All or none](/orders#all-or-none). Polymarket takes `ioc` buys by dollar amount only, so a hedge sized with `quantity` fills on Hyperliquid. * **One hedge per trigger.** Derive `client_order_id` from the match and trigger (for example `hedge-match123-1`). If your hedger fires twice, the second call returns the first order. * **Spending caps.** The key's per order and rolling 24 hour limits bound how much any hedger can spend. * **Kill switch.** [Pause order placement](/api-reference/account/pause-trading) stops the hedger in one call. # Use cases Source: https://lean.mintlify.app/use-cases/index What teams build with the Lean API, and the exact calls behind each one. Each use case covers who it's for, what you build, the call sequence, a starter you can run, and the guardrails that keep it safe. Every operation links to its page in the [API reference](/api-reference/markets/list-markets), where you can try it. > [card] [Best price execution across venues](/use-cases/best-price-execution) > > One order, filled at the best combined price across Polymarket and Hyperliquid, without > integrating either venue. > [card] [Model driven trading with hard limits](/use-cases/model-driven-trading) > > A bot that turns model edge into orders, with spending caps the API enforces. > [card] [An AI agent that trades within a budget](/use-cases/ai-agent-trading) > > A research agent on a read only key proposes trades; an execution key with tight limits > places them after approval. > [card] [Hedging sportsbook exposure](/use-cases/hedging-exposure) > > Buy the other side on prediction market liquidity when liability crosses a threshold. > [card] [Price monitoring and alerts](/use-cases/price-monitoring) > > Dashboards and alerts on a read only key, with no trading permission at all. > [card] [Funding and treasury automation](/use-cases/funding-automation) > > Find deposit assets and addresses, then watch balances arrive. ## Guardrails built into every key Every use case runs on the same controls: * **Spending caps on every key.** A per order limit and a rolling 24 hour limit, checked before anything reaches a venue. A key can lower its own limits, never raise them. * **Idempotent orders.** Your `client_order_id` makes every retry return the original order, never a second one. * **Read only keys.** A key with only the `read` scope can see markets, quotes and previews, and can never place an order. * **Kill switch.** One call pauses a key or its whole trading account. * **Preview first.** See the exact venue plan, cost and any refusal before you commit. ## Start with a test key All starters use the same two variables as the [Quickstart](/quickstart): ```bash theme={"dark"} export LEAN_API_URL="https://api.lean.xyz" export LEAN_API_KEY="lean_sk_test_..." ``` A test key lets you try everything without real money: orders and fills are simulated against test balances of 10,000 USD on each venue. Switch to a live key when you're ready. See [Test mode and live mode](/test-mode). # Model driven trading with hard limits Source: https://lean.mintlify.app/use-cases/model-driven-trading A bot that turns model edge into orders, with spending caps the API enforces. **Who it's for:** quant teams that have a pricing model and want it trading around the clock. **What you build:** a bot that turns model edge into orders. Its limits are enforced by the API, not only by the bot. ## Call sequence **1. Get data** [Get prices](/api-reference/markets/list-prices), [Get recent trades](/api-reference/markets/list-market-trades) and [Get a market orderbook](/api-reference/markets/retrieve-market-book), plus the WebSocket stream ([Create a stream ticket](/api-reference/streaming/create-stream-ticket)). **2. Trade on edge** [Preview an order](/api-reference/orders/preview-order), then [Place an order](/api-reference/orders/create-order) with a deterministic `client_order_id` (for example, model run plus signal id). A retry returns the same order, never a second one. **3. Set guardrails** [Get account configuration](/api-reference/account/retrieve-account-config) shows the per order and rolling 24 hour limits the key is held to. [Lower this key's limits](/api-reference/account/lower-key-limits) lets a bot key tighten its own limits; raising them needs a person signed in to Lean. [Pause order placement](/api-reference/account/pause-trading) is the kill switch: a key can stop itself or its whole trading account, and only the Lean dashboard can resume. **4. Reconcile** [List orders](/api-reference/orders/list-orders), [Get an order](/api-reference/orders/retrieve-order), [List fills](/api-reference/orders/list-fills) and [Get balances](/api-reference/account/list-balances). ## Starter ```bash theme={"dark"} # Tighten this key to $25 per order and $200 per rolling 24 hours curl -sS -X POST "$LEAN_API_URL/v1/account/limits" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"max_order_notional_usd":"25","daily_notional_limit_usd":"200"}' # Kill switch: stop new orders from this key 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":"model drift"}' ``` ## Guardrails * **Idempotency.** Replaying a `client_order_id` with the same body returns the original order; reusing it with a different body is refused with 409. * **Spending caps.** An order above the key's per order limit is refused with 422 `ORDER_NOTIONAL_LIMIT`, and the rolling 24 hour limit caps total activity. * **Kill switch.** One call to [Pause order placement](/api-reference/account/pause-trading) stops the key or the whole trading account. * **Slippage bounds.** `max_slippage_bps` caps every order when set. # Price monitoring and alerts Source: https://lean.mintlify.app/use-cases/price-monitoring Dashboards and alerts on a read only key, with no trading permission. **Who it's for:** media, odds comparison, analytics and research teams. It is also the first integration for most trading clients. **What you build:** a dashboard or an alert ("tell me when the best combined price for Team A moves more than 3c") with no trading permission at all. ## Call sequence **1. Use a read only key** Create a key with only the `read` scope. **2. Read markets and prices** [List markets](/api-reference/markets/list-markets), [Get prices](/api-reference/markets/list-prices), [Get a market orderbook](/api-reference/markets/retrieve-market-book) and [Get recent trades](/api-reference/markets/list-market-trades). **3. Go live** [Create a stream ticket](/api-reference/streaming/create-stream-ticket) and connect to the WebSocket for live books. ## Starter ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/prices?market_ids=$MARKET_ID" \ -H "Authorization: Bearer $LEAN_READ_KEY" curl -sS "$LEAN_API_URL/v1/markets/$MARKET_ID/book?depth=10" \ -H "Authorization: Bearer $LEAN_READ_KEY" ``` ## Guardrails * **Read only by design.** A key with only the `read` scope can't place, cancel or pause anything; an order attempt is refused with 403. * **Revocable.** Revoke a dashboard's key from Lean at any time; the next request gets 401. * **No money at risk.** Spending caps and trading permissions never come into play. # Venues Source: https://lean.mintlify.app/venues What the API supports on Kalshi, Polymarket, Polymarket US and Hyperliquid. Lean trades on four venues: Kalshi, Polymarket, Polymarket US and Hyperliquid. One market can list on several of them, and Lean reads every listing's book, prices the order across them and places it where it fills best. This page shows what each venue supports, so you know where an order can go before you send it. Wherever a request or response names a venue, `venue` is one of `kalshi`, `polymarket`, `polymarket_us` or `hyperliquid`. ## What each venue supports | Feature | Kalshi | Polymarket | Polymarket US | Hyperliquid | | - | - | - | - | - | | [Markets](/markets), quotes, books, trades, candles and prices | Yes | Yes | Yes | Yes | | [Orders](/orders), amends, cancels and fills | Yes | Yes | Yes | Yes | | Balances, positions and PnL | Yes | Yes | Yes | Yes | | [Stop losses](/stop-losses) and take profits | Yes | Yes | Yes | Yes | | [Limit chases](/limit-chases) | Yes | Yes | Yes | Yes | | `post_only` orders | Yes | No | Yes | Yes | | `gtd` orders | Yes | Yes | Yes | No | | `fok` orders | Yes | Yes | Yes | No | | Paying for a buy with cash on another venue, and `best_price` | No | Yes | No | Yes | | [Self signed routed orders](/routed-orders) | No | Yes | No | Yes | | [Deposits, withdrawals](/funding) and [transfers](/transfers) | No | Yes | No | Yes | | [Test mode](/test-mode) | Yes | Yes | Yes | Yes | ## Accounts and venue API keys Polymarket and Hyperliquid balances belong to a trading account. Each trading account has its own cash and shares there. Kalshi and Polymarket US accounts belong to the user. Every trading account and API key of the user shares the same Kalshi and Polymarket US cash and shares, so `GET /v1/balances` and `GET /v1/positions` show the same figures for those venues under each of them. A live order on Kalshi or Polymarket US goes out under the user's own API key for that venue. Connect it once in the Lean app: * Without it, a live order that needs that venue is refused with `403 FORBIDDEN`. Connect the key, or leave the venue out with `venues`. * Test keys never reach a venue, so test orders on Kalshi and Polymarket US need no venue key. ## Naming markets Each venue listing of a market is a leg with its own `ticker`: | Venue | Leg `ticker` | | - | - | | Kalshi | The Kalshi market ticker, such as `KXNBAGAME-…` | | Polymarket | Starts with `pm:`, such as `pm:0x…` | | Polymarket US | Starts with `pmus:` | | Hyperliquid | Starts with `hl:`, such as `hl:12` | `GET /v1/markets?symbol=` takes any of these tickers and lists the markets that trade it, so you can find the Lean market ID for a Kalshi or Polymarket US market. `GET /v1/markets?venue=` lists only markets with a leg on that venue. Store the market ID and use it everywhere else. See [Market IDs](/markets#market-ids). ## Cash on each venue | Venue | Cash | How to fund it | | - | - | - | | Kalshi | USD | On Kalshi directly | | Polymarket | pUSD | Lean [deposits](/funding) and [transfers](/transfers) | | Polymarket US | USD | On Polymarket US directly | | Hyperliquid | USDC in spot | Lean [deposits](/funding) and [transfers](/transfers) | Lean routes an order only to the venues that can pay for it. Between Polymarket and Hyperliquid, a buy can pay with cash on the other venue: Lean moves the cash and buys on the venue with the book, in the same call, and the order's `route` says so. A buy on Kalshi or Polymarket US pays with the cash already on that venue. Shares never move between venues, so a sell or a stop loss sells on the venue that holds the shares. A test key starts with 10,000 simulated on each venue: USD on Kalshi and Polymarket US, pUSD on Polymarket and USDC on Hyperliquid. ## Order terms on each venue Each venue takes prices only on its own 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 sit on the tick of every venue that could place the order. Lean never rounds it. Some order terms narrow the venues an order can reach: * A `post_only` order rests on Kalshi, Polymarket US or Hyperliquid. Polymarket can't rest a post only order. * A `gtd` order goes to Kalshi, Polymarket or Polymarket US. Hyperliquid has no order expiry. * A `fok` order goes whole to one venue: Polymarket, else Kalshi, else Polymarket US. Hyperliquid has no fill or kill. Polymarket takes a `fok` buy sized with `notional` only, so a `fok` buy sized with `quantity` goes to Kalshi or Polymarket US. When no venue that lists the market can take the order, it is refused with `400 VALIDATION_ERROR`. See [Orders](/orders) for every term. ## Polymarket US books Lean reads Polymarket US books from a live copy that starts on the first read of a market. Until that copy is ready, a quote, preview or order that needs the book answers `503 UPSTREAM_ERROR` with a `Retry-After` header, and nothing is placed. Send the same request again after that time. # Versioning Source: https://lean.mintlify.app/versioning What can change inside /v1, and how breaking changes are announced. The major version is in the path: every endpoint sits under `/v1`, apart from API key management. The release version, for example `0.1.0`, is `info.version` in the [OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json), and each release is listed in the [changelog](/changelog). ## Changes that ship inside /v1 These are additive. They can arrive in any release with no notice, so write clients that tolerate them: * New endpoints. * New optional request fields and query parameters. * New fields in responses, including inside `error.details`. * New values in open ended codes: `warnings[].code`, `details.reason`, `details.venue_code` and `status_reason.code`. * New venues in order and preview `legs`, `balances` and `positions`. Ignore fields you do not recognize. Treat an unknown code by its HTTP status, and an unknown venue like any other venue. ## Breaking changes A breaking change removes or renames a field, changes a field's type or meaning, makes an optional field required, or changes the HTTP status or `error.code` of an existing case. * **During the 0.x preview**, a breaking change can still ship inside `/v1`. Each one is listed in the changelog with the date it takes effect, and announced ahead of that date whenever possible. * **From 1.0**, breaking changes ship only in a new path version such as `/v2`. In every version, removing an endpoint or field follows [Deprecation](#deprecation). ## Deprecation Removing an endpoint or field starts with a deprecation notice. It is removed at least 90 days after the notice, never sooner. The notice is given in two places: * An entry in the [changelog](/changelog) naming what is deprecated, what replaces it, and the removal date. * `Deprecation` and `Sunset` headers on every response from the affected endpoint. `Sunset` is the removal date. Watch for both headers in your client logs. ## Generated clients The [TypeScript SDK](/typescript-sdk), the [Rust SDK](/rust-sdk), the Python SDK and the Postman collection are generated from the OpenAPI spec of each release, so they always match it. Regenerate your own clients from the same spec.