# Lean API > This file is very large and may be truncated. For an index of this content, please refer to https://docs.lean.xyz/llms.txt instead. # Close positions Source: https://docs.lean.xyz/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. # Convert to pUSD Source: https://docs.lean.xyz/api-reference/account/convert-to-pusd api-reference/openapi.json POST /conversions Turns the whole balance of source_asset in the account’s Polymarket wallet into the same amount of pUSD, the cash Polymarket trades with. GET /conversions shows what can be converted. usdc_e is converted in one transaction: settled once it confirms, submitted while it is on its way. usdc is sent through Polymarket’s bridge, so it is submitted and its pUSD arrives a few minutes later; a balance under the bridge’s minimum is refused with details.reason BELOW_MINIMUM. One conversion runs at a time per account; another while one is settling is refused with details.reason CONVERSION_IN_PROGRESS. A live conversion needs trading enabled for the account in the Lean app and is submitted once. A test key holds nothing to convert, so it is refused with details.reason NOTHING_TO_CONVERT and nothing changes. # Get convertible balances Source: https://docs.lean.xyz/api-reference/account/get-convertible-balances api-reference/openapi.json GET /conversions The USDC and USDC.e in the account’s Polymarket wallet. Polymarket trades only with pUSD, so these do not count toward the account’s cash until POST /conversions turns them into pUSD. They usually come from a transfer sent straight to the wallet instead of through a deposit address. A test key answers zero for both, because test cash is always pUSD. # Get profit and loss Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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 Kalshi subaccounts Source: https://docs.lean.xyz/api-reference/account/list-kalshi-subaccounts api-reference/openapi.json GET /kalshi/subaccounts Requires read scope. The Kalshi connection belongs to the key’s user and is shared across their trading accounts. Lists the primary and numbered subaccounts, including hidden ones. Basic-tier accounts return eligible=false and an empty list. Test keys return an empty list with no active subaccount. # List positions Source: https://docs.lean.xyz/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://docs.lean.xyz/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`. # Merge positions Source: https://docs.lean.xyz/api-reference/account/merge-positions api-reference/openapi.json POST /positions/merge Turns every pair of one YES share and one NO share the account holds on market_id at venue back into 1 of cash per pair, without trading. Only Polymarket and Hyperliquid merge. An account without both sides is refused with details.reason NOTHING_TO_MERGE. A live merge needs trading enabled for the account in the Lean app and is submitted once: it is settled once the venue confirms it, submitted while it is on its way, or failed with failure_reason when the venue refused it. A test merge leaves shares held for a resting sell alone, moves nothing, settles at once, removes the pairs from the simulated positions and adds their proceeds to the simulated cash until test mode is reset. # Pause order placement Source: https://docs.lean.xyz/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. It also stops withdrawals, transfers, conversions, merges and redeems. Reads, cancels and resting orders are unaffected, and transfer quotes still answer. Only the Lean dashboard can resume. # Redeem positions Source: https://docs.lean.xyz/api-reference/account/redeem-positions api-reference/openapi.json POST /positions/redeem Pays out every holding GET /positions marks redeemable, or only those on market_id, as cash on the venue. A Polymarket holding of a resolved market stays a token until it is redeemed; Kalshi, Polymarket US and Hyperliquid pay resolved holdings out on their own and never need this. The response lists each holding redeemed with its payout, and is empty when nothing was redeemable. A live redeem needs trading enabled for the account in the Lean app and is submitted once, in one transaction for every holding: it is settled once the venue confirms it, submitted while it is on its way, or failed with failure_reason when the venue refused it. A test redeem moves nothing, settles at once, removes the holdings from the simulated positions and adds their payout to the simulated cash until test mode is reset. # Get account configuration Source: https://docs.lean.xyz/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. `venues` gives each venue’s connection status: `ready`, `not_configured` or `unavailable`. It covers Kalshi, Polymarket, Polymarket US, Hyperliquid and Lighter. # Create an API key Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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. # Cancel a conditional sell Source: https://docs.lean.xyz/api-reference/conditional-sells/cancel-conditional-sell api-reference/openapi.json DELETE /conditional-sells/{id} Stops a conditional sell: Lean cancels its resting leader sell and any follower sells still working. Shares already sold stay sold. Canceling works while trading is paused. The answer reads canceled. # Create a conditional sell Source: https://docs.lean.xyz/api-reference/conditional-sells/create-conditional-sell api-reference/openapi.json POST /conditional-sells Sells a leader position and, as it fills, sells the same number of shares of each follower position, never below the follower’s floor price. A limit leader rests a sell at limit_price at once; a stop leader waits until its best bid falls to trigger_price, then sells down to trigger_price minus slippage_limit. With a limit leader, the conditional sell pauses while a follower’s book holds too little at or above its floor, and resumes by itself once that depth has held for 5 seconds; a live key’s create can answer paused for that reason. Every leg is a different position this key’s trading account holds, on a venue its allow list includes, and each must hold the quantity beyond the account’s other resting sells, stop losses and conditional sells. The sale is booked as orders at the leader’s lowest price and each follower’s floor would be: it counts toward the rolling day and is held to the venue allow list, but as a sale it only takes risk off, so no notional limit refuses it. On a test key the conditional sell is checked, recorded, listed and booked but never sells. Kalshi, Polymarket, Polymarket US and Hyperliquid run conditional sells. # List conditional sells Source: https://docs.lean.xyz/api-reference/conditional-sells/list-conditional-sells api-reference/openapi.json GET /conditional-sells Conditional sells of this key’s trading account in this key’s mode, newest first: every one still selling, waiting or paused, and those that ended in the last day. # Get a conditional sell Source: https://docs.lean.xyz/api-reference/conditional-sells/retrieve-conditional-sell api-reference/openapi.json GET /conditional-sells/{id} One conditional sell of this key’s trading account by id. # Create deposit addresses Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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. # List deposits Source: https://docs.lean.xyz/api-reference/deposits/list-deposits api-reference/openapi.json GET /deposits Recent deposits into the key’s trading account on one venue, newest first, at most 50, each with its status. Only deposits sent to the addresses from GET /deposits/addresses through a provider are listed: Relay for Hyperliquid and the Polymarket bridge for Polymarket. Sending pUSD straight to the Polymarket wallet credits it at once and is not listed. A test key gets an empty list. # Cancel a limit chase Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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. # Update a limit chase Source: https://docs.lean.xyz/api-reference/limit-chases/update-limit-chase api-reference/openapi.json PATCH /limit-chases/{id} Changes the quantity, offset or price limit of a limit chase that is still resting, keeping its id. Fields left out keep their values, and giving one offset replaces the current one. quantity is the new total, counting what has already filled. The new values pass the same checks as at creation, with one difference: shares that can still fill on either the current or the edited values, or on the chase’s resting order at the size it still rests at, up to the new quantity, are counted at the highest of the old price limit, the new price limit and the price that order is resting at, because that order can fill before Lean moves or resizes it. Shares that have filled count at what they cost. A buy is checked as a whole on that basis against the per-order cap, and whatever the edit adds to the most the chase can trade for counts toward the rolling day: a larger size, a higher or removed price limit on a buy, or any edit while the order still rests above a lowered price limit. On Kalshi, the order is amended in place rather than canceled and placed again, so a smaller size at the same price keeps its place in the queue. A limit chase that has ended or has a cancel pending cannot be changed. A live limit chase answers with the edited values and edit_pending true; Lean moves the resting order a moment later. Read it by id to confirm: edit_pending turns false once Lean applies the edit, and another edit is refused until then. If Lean refuses it, for example because fills overtook a smaller size, the earlier values stay and last_error says why. Every venue supports it. # Get price candles Source: https://docs.lean.xyz/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 weather for a station Source: https://docs.lean.xyz/api-reference/markets/get-weather-station api-reference/openapi.json GET /weather/{stationCode} Stored observations from the last 24 hours, forecast models, accuracy and release estimates for a four-character station code. Observations and six_hour_extremes report six_hour_high_c and six_hour_low_c in Celsius. six_hour_extremes and CLI/DSM daily_reports each include up to 60 entries, newest first. Timestamps are Unix seconds. Observation, forecast and daily report temperatures use station.temperature_unit. dew_point_c is Celsius. Public weather data is available to live and test keys. Requires read scope. # Get recent trades Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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 50 markets in one call, across venues and per venue. Ids that match no market are returned in `not_found`. # List recently resolved markets Source: https://docs.lean.xyz/api-reference/markets/list-resolved-markets api-reference/openapi.json GET /resolution/markets Kalshi and Polymarket resolutions from the resolution read model, newest first, grouped once per event. market_tickers lists all markets in that event. limit defaults to 100 and is capped at 200. source optionally filters one exact resolution source. Pass both next_cursor fields as before_changed_at and before_id to fetch older events, preserving source. A null next_cursor ends pagination. Public resolution data is available to live and test keys. Requires read scope. # Quote a market Source: https://docs.lean.xyz/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://docs.lean.xyz/api-reference/markets/retrieve-market api-reference/openapi.json GET /markets/{id} One market by its id, with each venue leg (including `lean_url`, resolution rules, and fees) plus automatic `series_context` (whether the market is recurring, Brier score & sharpness calibration of prior settled markets in the series, sibling strikes in the same event, cross-venue equivalents, and active liquidity rewards). # Get a market orderbook Source: https://docs.lean.xyz/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://docs.lean.xyz/api-reference/orders/amend-order api-reference/openapi.json PATCH /orders/{id} Changes the limit price, total size, or both of a resting single-venue good til canceled order. Quantity includes prior fills. On live Kalshi and Polymarket US orders, the original API key can reduce size at the same price in place, retaining the Lean order and client IDs. Kalshi keeps queue priority and Polymarket US preserves post_only. Price changes, size increases, cross-key amends, test orders, and orders on other eligible venues use linked cancel-and-replace for the remaining size. Each order keeps its own fills. Lean checks the new terms, available funds or shares, and trading limits before dispatch. A concurrent fill or change in funds may affect replacement after cancellation. If cancellation is pending, send the same amend again once the old order reads canceled. Routed orders and orders split across venues cannot be amended. # Cancel every open order Source: https://docs.lean.xyz/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. Orders placed in the Lean app, which GET /v1/orders lists with `source` app, are left resting. # Cancel an order Source: https://docs.lean.xyz/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://docs.lean.xyz/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. An order id that matches no order of the account in this key's mode, or a client_order_id that matches no order this key placed, fails with NOT_FOUND. Works while trading is paused. # Create an order Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/api-reference/orders/list-orders api-reference/openapi.json GET /orders Orders on this key’s trading account, newest first: every order placed through the API, and, for a live key, each order placed in the Lean app that is still open on its venue. `source` says which; an app order has `client_order_id` `null`, an empty `legs` list, and `market_id`, `title` and `outcome` `null` when no market is listed for it. 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. App orders are read from the venues on each call, so a venue that could not be read is listed in `unavailable` and its app orders are left out. They cannot be read by id, amended or canceled through the API; manage them in the Lean app. Orders a limit chase, stop loss or conditional sell placed are not listed; read those through their own routes. Filter by status, venue, market, text in the market title or `client_order_id` (which matches API orders only), and pass `next_cursor` back as `cursor` for the next page. # Preview an order Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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. It cancels the orders POST /v1/orders/cancel-all would, so orders placed in the Lean app are left resting. # Get reward earnings today Source: https://docs.lean.xyz/api-reference/rewards/get-reward-earnings api-reference/openapi.json GET /rewards/earnings Read today’s earnings across connected venues, or filter by venue. Polymarket reports live pool shares and a projected total for its UTC day. Polymarket US reports paid and pending rewards for its America/New_York day, with pmus: tickers, zero share and pace, and estimated earnings equal to earned USD. Each venue reports its own status. Requires read scope. Test keys return zero earnings. # List reward programs Source: https://docs.lean.xyz/api-reference/rewards/list-reward-programs api-reference/openapi.json GET /rewards/programs Lists active rewards in ticker order across Kalshi, Polymarket US and Polymarket. Requires read scope. Filter by venue, literal ticker_prefix and min_daily_reward in USD per day across a ticker’s active programs. Each page defaults to 100 tickers with a maximum of 200. Pass next_cursor as cursor with the same filters until next_cursor is null. Each ticker includes all its active programs. Kalshi lists open markets and includes event_ticker, series_ticker, title, market_status, price_level_structure, price_ranges and tick_rule, and each Kalshi program carries the stored period_reward_centicents, exact target_size_fp, last_rest_update, created_at and updated_at. last_rest_update and updated_at move only when a Kalshi refresh inserts or changes the program, not on every refresh. Polymarket US includes event_start_time, category, reward_pool, max_spread and pool_market_count. Polymarket end_date is null because its feed has no end date. Test keys read the same programs with livemode false. # Accept a combo RFQ quote Source: https://docs.lean.xyz/api-reference/rfqs/accept-combo-rfq api-reference/openapi.json POST /rfqs/{id}/accept Accept a specific maker quote on an open combo RFQ by quote_id and exact price_usd. Places a real combo order on a live key. # Cancel a combo RFQ Source: https://docs.lean.xyz/api-reference/rfqs/cancel-combo-rfq api-reference/openapi.json DELETE /rfqs/{id} Cancel/delete an open combo RFQ on Kalshi or Polymarket US. # Create a combo RFQ Source: https://docs.lean.xyz/api-reference/rfqs/create-combo-rfq api-reference/openapi.json POST /rfqs Create a multi-leg combo on Kalshi or Polymarket US and request maker quotes for any 2 to 10 legs (elections, macro, sports, or cross-category). Waits up to `wait_seconds` for initial quotes. Set `quote_only: true` to automatically delete/cancel the RFQ on the venue after capturing quotes. # Retrieve a combo RFQ Source: https://docs.lean.xyz/api-reference/rfqs/retrieve-combo-rfq api-reference/openapi.json GET /rfqs/{id} Read fresh maker quotes or acceptance status for an existing combo RFQ. # Cancel a stop loss Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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. Kalshi and Polymarket US stop losses belong to the user rather than to a trading account, so a live key lists all of the user’s on those venues. A live key also lists the sales that conditional sells run for their followers and stop leaders; those cannot be changed or canceled here. # Get a stop loss Source: https://docs.lean.xyz/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. # Update a stop loss Source: https://docs.lean.xyz/api-reference/stop-losses/update-stop-loss api-reference/openapi.json PATCH /stop-losses/{id} Changes the trigger price, quantity or slippage limit of a stop loss or take profit that is still watching the market, keeping its id. Fields left out keep their values. The new values pass the same checks as at creation, and a larger sale books the added amount toward the rolling day, which never refuses a sale. A stop loss that has started selling, ended or has a cancel pending cannot be changed. A live stop loss answers with the edit applied; Lean moves the strategy to it a moment later. Every venue supports it. # Create a stream ticket Source: https://docs.lean.xyz/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://docs.lean.xyz/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 | | | | - | - | | URL | `wss://api.lean.xyz/v1/ws`, on the same host as the REST API | | 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 1000 on one connection; split a long list across several `subscribe` frames | 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; see [Before authentication](#before-authentication). A second `auth` frame on the same connection is answered with a `VALIDATION_ERROR` error frame and the connection stays open. ## 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, each once: ```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, each once: ```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`, or a `trades` or `market_lifecycle` channel's `ticker`, is not printable ASCII without spaces of at most 512 characters. | | `Too many channels on one connection` | The subscription would take the connection past 1000 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`, then `book_delta`, then `book_ended` if it ends | One market's book, as [Get a market orderbook](/api-reference/markets/retrieve-market-book) returns it, then what changes in it. | | `trades` | `trades` | Trades on one venue listing, named by `ticker`, as they happen. | | `market_lifecycle` | `market_lifecycle` | Status and tick size changes of one venue listing, named by `ticker`. | ### 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_...", "title": "Denver Broncos at Los Angeles Chargers: Moneyline, Denver Broncos", "outcome": "DEN", "source": "api", "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", "cost_basis_usd": "2.5", "mark_price": null, "unrealized_pnl_usd": null, "redeemable": false, "payout_usd": null, "market_id": "mkt_...", "title": "", "outcome": "", "settled": false } ], "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 channel opens with a `book` frame holding the whole book, then sends `book_delta` frames holding only what changed since the book Lean last published. A busy book can get several deltas within a few milliseconds or one delta covering many changes. A book with no change gets a delta with no levels about once a second. Every `book` and `book_delta` frame has a `sequence`. A delta also has `prev_sequence`: apply it only when that equals the `sequence` of the book you hold, then hold its `sequence`. When a delta cannot follow the frame before it, because your session read too slowly or the market's venues changed, Lean sends a whole `book` frame instead, which replaces the book you hold. If you still see a delta whose `prev_sequence` is not yours, drop the book, send `unsubscribe` for the channel, then `subscribe` again: the new subscription opens with a whole `book` frame. The official SDKs do all of this and hand you the whole book after each frame. 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. `book.as_of` is when Lean built the book. The first frame after you subscribe has `snapshot` set to `true`: it is the newest book Lean already holds, so on a quiet book its `as_of` can be up to about a second before you subscribed. Every later `book` frame has `snapshot` set to `false`, and `book_delta` frames carry no `snapshot` field; both are built as they are sent. To measure delay, skip the snapshot frame. Subscribing again to a channel you already have changes nothing, so it sends no new snapshot; unsubscribe first to get one. ```json theme={"dark"} { "type": "book", "market_id": "mkt_...", "snapshot": true, "sequence": 1841, "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 `book_delta` frame lists only the levels that changed: * Each level replaces the level at its price on its side. A `quantity` of `"0"` removes the level. * A level that falls out of the 20 shown is removed, and one that comes into them is added, so the book you build always matches the next whole `book`. * A `combined` level carries its whole `venues` split, not only the venue that changed. * A venue book is matched by `venue`, `ticker` and `side`. It lists only its changed levels, with its new quantity and notional totals. * The four book totals and `as_of` are always the new book's. * Keep bids highest price first and asks lowest price first. Quantities keep the venue's precision, as `GET /v1/markets/:id/book` returns them, so a level holding a fraction of a share is listed and can be the best price. Every listed level holds more than `0`, so `"0"` only ever means a removal. ```json theme={"dark"} { "type": "book_delta", "market_id": "mkt_...", "sequence": 1842, "prev_sequence": 1841, "delta": { "venues": [ { "venue": "polymarket", "ticker": "", "side": "yes", "bids": [{ "price": "0.52", "quantity": "0" }, { "price": "0.51", "quantity": "75" }], "asks": [], "bid_quantity": "75", "ask_quantity": "40", "bid_notional_usd": "38.25", "ask_notional_usd": "22" } ], "combined": { "bids": [ { "price": "0.52", "quantity": "0", "venues": [] }, { "price": "0.51", "quantity": "75", "venues": [{ "venue": "polymarket", "quantity": "75" }] } ], "asks": [] }, "total_bid_quantity": "75", "total_ask_quantity": "40", "total_bid_notional_usd": "38.25", "total_ask_notional_usd": "22", "as_of": "2026-11-01T20:25:00.050Z" } } ``` When a book channel will send no more books, it sends one `book_ended` frame and the session stops following it. `reason` is `unknown_market` when the `market_id` names no market, or is a [venue symbol that names more than one market](/markets#venue-symbols), such as the ticker of a listing that pays both outcomes. The REST endpoints refuse that symbol with `400`; the channel ends instead. `reason` is `market_closed` once every venue listing of the market is closed or resolved. `unknown_market` arrives within a few seconds. `market_closed` arrives after Lean records the close, which can be a few minutes after the venue closes the market. A market whose listings are unopened or resolving still streams its book. ```json theme={"dark"} { "type": "book_ended", "market_id": "mkt_...", "reason": "unknown_market" } ``` A market listed after you subscribed, such as an upcoming crypto window, can end with `unknown_market`. Subscribe again once [List markets](/api-reference/markets/list-markets) returns it. ### trades Name a venue listing by its leg `ticker`, as a market's `legs[].ticker` shows it: ```json theme={"dark"} { "op": "subscribe", "channels": [{ "channel": "trades", "ticker": "" }] } ``` Each frame holds the trades the venue reported since the last frame, oldest first. Only trades that happen after `subscribed` are sent; read [List recent market trades](/api-reference/markets/list-market-trades) for earlier ones. Live and test keys get the same trades. ```json theme={"dark"} { "type": "trades", "ticker": "", "timestamp": 1764620700120, "trades": [ { "venue": "polymarket", "ticker": "", "trade_id": "", "side": "yes", "price": "0.42", "quantity": "120", "taker_side": "yes", "maker_side": "no", "timestamp": 1764620700050, "received_at_ms": 1764620700080, "maker": "0x...", "taker": "0x...", "maker_username": null, "taker_username": null, "maker_builder": null, "taker_builder": null, "additional_makers": [], "notional_cents": 5040 } ] } ``` | Field | Meaning | | - | - | | `side`, `price` | The side and price of the trade as the venue reports them, the price in dollars. | | `quantity` | Shares traded, as a decimal string. | | `taker_side`, `maker_side` | The side each party took. `maker_side` is `null` when the venue does not say. | | `timestamp` | When the venue executed the trade, in Unix milliseconds. The frame's own `timestamp` is when Lean published it. | | `received_at_ms` | When Lean received the trade, in Unix milliseconds, or `null`. | | `maker`, `taker` | The parties' venue addresses where the venue publishes them, else `null`. `*_username` and `*_builder` name them when known. | | `additional_makers[]` | Further makers filled by the same trade, each with `address`, `quantity`, `maker_side`, `username` and `builder`. | | `notional_cents` | What the trade was worth, in cents. | ### market_lifecycle Name a venue listing the same way: ```json theme={"dark"} { "op": "subscribe", "channels": [{ "channel": "market_lifecycle", "ticker": "" }] } ``` A `status_change` frame arrives when the listing's status changes. `status` is `unopened`, `open`, `closed`, `resolving` or `resolved`, and `result` names the outcome once the venue reports one, else `null`: ```json theme={"dark"} { "type": "market_lifecycle", "event": "status_change", "venue": "kalshi", "ticker": "", "status": "resolved", "result": "yes", "timestamp": 1764620700000 } ``` A `tick_size_change` frame arrives when the listing's price step changes. `tick_rule` is `cent`, `half_cent`, `tenth`, `hundredth` or `tapered`, and `tick_size` is the exact step in dollars when the venue gives one, else `null`: ```json theme={"dark"} { "type": "market_lifecycle", "event": "tick_size_change", "venue": "polymarket", "ticker": "", "tick_rule": "tenth", "tick_size": "0.001", "timestamp": 1764620700000 } ``` The first frame after `subscribed` can repeat the listing's current state. New `event` values can appear without a new version; skip one you do not recognize. Only a `ticker`'s shape is checked: one no venue lists is accepted and sends nothing. Unlike a `book` channel's `market_id`, a Polymarket condition ID, token ID or Hyperliquid coin is not resolved to a ticker. A session that reads positions, balances or books too slowly skips ahead to the newest state. A session that reads trades or lifecycle events too slowly is closed with `1013` and `RATE_LIMITED`, with the message `Stream fell behind; reconnect and refetch 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 Every error is an `error` frame with a `code` and a `message`. Whether the connection stays open depends on whether it has authenticated. ### Before authentication Until `authenticated` arrives, Lean accepts only an `auth` frame. Anything else gets one error frame, then the socket closes: | You send | Close code | `code` | `message` | | - | - | - | - | | `ping`, `subscribe` or `unsubscribe` | `1008` | `UNAUTHORIZED` | `Authenticate before any other frame` | | Text that is not JSON, or JSON that is not a frame shown on this page | `1008` | `VALIDATION_ERROR` | `Expected an auth frame` | | A binary frame | `1003` | `VALIDATION_ERROR` | `Frames must be JSON text` | | No `auth` frame within 10 seconds | `1008` | `UNAUTHORIZED` | `Authentication timed out` | An `auth` frame whose ticket or key is refused also closes with `1008` and `UNAUTHORIZED`: the ticket is invalid, expired or already used, or the key is expired or revoked. The closes that can follow an `auth` frame for other reasons are in [Close codes](#close-codes). ### 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" } ``` `Unrecognized frame` answers text that is not JSON or not a frame shown on this page. A second `auth` frame gets `This connection is already authenticated`, and a bad `subscribe` gets one of the [subscribe errors](#subscribe-and-unsubscribe). A binary frame still closes the socket with `1003`. ## Close codes When the connection must end, Lean sends an error frame and then closes the socket: | Close code | `code` | When | | - | - | - | | `1008` | `UNAUTHORIZED` | Before authentication, as [listed above](#before-authentication). After it, the key was revoked or expired. | | `1003` | `VALIDATION_ERROR` | A binary frame was sent, before or after authentication. | | `1013` | `RATE_LIMITED` | In reply to `auth`: the key already has 500 open streams. | | `1013` | `RATE_LIMITED` | The session read order states, trades or lifecycle events too slowly to keep up. | | `1013` | `UPSTREAM_ERROR` | In reply to `auth`: 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. | | `1001` | none | Nothing arrived from the client for 45 seconds, not even a pong to Lean's pings. The close reason is `no frames from client`. | Lean sends a WebSocket ping every 15 seconds, and any frame from the client counts, a pong included. Most WebSocket libraries answer pings on their own; sending `{"op":"ping"}` every 10 seconds also keeps the connection open. After a `1001`, `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://docs.lean.xyz/api-reference/test-mode/reset-test-mode api-reference/openapi.json POST /test/reset Deletes every simulated order, withdrawal, transfer, stop loss, limit chase, conditional sell, redeem and merge of the test key’s trading account, made by any test key on that account and not only the calling key. It returns the account’s test balances to the starting amount, clears its test positions and resets the test daily limit usage. Live keys are refused. # Create a transfer Source: https://docs.lean.xyz/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 another venue. Test keys simulate transfers against test cash. Live keys move real cash through Relay: the route is prepared now, so fee_usd is the fee it pays, and an account sends one live transfer at a time. Nothing moves until the transfer is executed, with the owner’s signatures over `authorization.payloads` for a test key or with 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://docs.lean.xyz/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 live transfer has nothing to sign, so it takes `delegated` only, and it answers pending until its venues settle it. A transfer that cannot be sent fails with failure_reason and nothing moved. 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://docs.lean.xyz/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://docs.lean.xyz/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 another would cost and deliver, the smallest amount the route accepts and what the sending venue holds. Live keys move cash between polymarket, hyperliquid and lighter through Relay, and the fee is Relay’s live quote. Test keys simulate polymarket and hyperliquid. It needs only the read scope and creates nothing. # Get a transfer Source: https://docs.lean.xyz/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. A live transfer on its way is read from its venues on each request. # Withdraw cash Source: https://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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/orders/preview-batch`, `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, or **Never expires**. The dashboard fills in 90. A key that never expires works until you revoke it. | 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. `expiresInDays` is required and must be from 1 to 90, or `null` for a key that never expires; the API has no default. A key's limits can't be above its trading account's limits, or the request is refused with `422`. An account limit is at most 100,000,000 USD. 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), [Revoke an API key](/api-reference/api-keys/revoke-api-key), [Update API key limits](/api-reference/api-keys/update-api-key-limits), [Get account limits](/api-reference/api-keys/retrieve-account-limits), [Update account limits](/api-reference/api-keys/update-account-limits), [Pause an API key](/api-reference/api-keys/pause-api-key), [Resume an API key](/api-reference/api-keys/resume-api-key), [List trading pauses](/api-reference/api-keys/list-trading-pauses), [Pause account API trading](/api-reference/api-keys/pause-account-api-trading) and [Resume account API trading](/api-reference/api-keys/resume-account-api-trading), 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://docs.lean.xyz/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. ## Connect Lean to your assistant The Lean MCP server calls the Lean API for your account, so an assistant connected to it can read markets, books, candles, orders, positions, profit and loss, risk, stop losses, deposits, withdrawals and transfers, and trade if you let it. Lean hosts it at `https://api.lean.xyz/mcp`. Add that address to your assistant and it sends you to Lean to log in. There you choose what it gets, exactly as when you [create a key](/authentication#create-a-key): the trading account, **Read only** or **Read and trade**, test or live, spending limits and when the access expires. Nothing is copied or pasted, and the assistant never sees a key. ```text Claude and ChatGPT theme={"dark"} Add a custom connector with the address https://api.lean.xyz/mcp ``` ```bash Claude Code theme={"dark"} claude mcp add --transport http lean https://api.lean.xyz/mcp ``` ```json Cursor (.cursor/mcp.json) theme={"dark"} { "mcpServers": { "lean": { "url": "https://api.lean.xyz/mcp" } } } ``` ```json VS Code (.vscode/mcp.json) theme={"dark"} { "servers": { "lean": { "type": "http", "url": "https://api.lean.xyz/mcp" } } } ``` Claude, Claude Code, ChatGPT, Codex, Cursor and VS Code are verified clients. Any other standard MCP OAuth client using HTTPS or a local loopback callback is also supported and shown with an unverified app warning naming its callback host; approve it only if you just started the login yourself. The access is an API key with the assistant's name on it. It appears under **Settings › API** with your other keys, the same limits, pauses and kill switch apply to it, and revoking it there disconnects the assistant at once. Connecting the same assistant to the same trading account again replaces its previous access. The hosted server offers the tools described below. The trading tools appear when you choose **Read and trade**, so there is no `--enable-trading` to pass. ## Docs for language models | File | Address | Use it for | | - | - | - | | `llms.txt` | [docs.lean.xyz/llms.txt](https://docs.lean.xyz/llms.txt) | An index of every page with a one line summary. Point an agent here first. | | `llms-full.txt` | [docs.lean.xyz/llms-full.txt](https://docs.lean.xyz/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 [docs.lean.xyz/quickstart.md](https://docs.lean.xyz/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 separate, read-only hosted Model Context Protocol (MCP) server at `https://docs.lean.xyz/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://docs.lean.xyz/mcp ``` ```json Cursor (.cursor/mcp.json) theme={"dark"} { "mcpServers": { "lean-api": { "url": "https://docs.lean.xyz/mcp" } } } ``` ```json VS Code (.vscode/mcp.json) theme={"dark"} { "servers": { "lean-api": { "type": "http", "url": "https://docs.lean.xyz/mcp" } } } ``` Any other client that supports remote MCP servers over HTTP takes the same address. ## Run the Lean MCP server The same server also runs on your machine over stdio, for clients that start local servers. It calls the Lean API with an API key you create, and the key stays in its environment, so the key is never sent to the model. The server is the `@leanxyz/mcp` package on npm. It needs [Node.js](https://nodejs.org) 22 or later (22.4 or later for `watch_stream`), and your MCP client starts it with `npx -y @leanxyz/mcp`. | 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`, `preview_order`, `preview_orders_batch`, `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`, `list_conditional_sells`, `get_conditional_sell`, `get_deposit_addresses`, `get_deposit_assets`, `list_deposits`, `get_convertible_balances`, `list_withdrawals`, `get_withdrawal`, `quote_transfer`, `list_transfers`, `get_transfer` and `watch_stream`. 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, and the market, book, trade, candle and order tools also cover Lighter's crypto markets. Deposits and withdrawals cover Polymarket and Hyperliquid only. Live transfers also reach Lighter. `preview_order` and `preview_orders_batch` place nothing, so they work with a **Read only** key. `quote_market` prices sports and event markets; to price a crypto price window, use `preview_order`. `watch_stream` opens the [stream](/streaming) for one call of up to 25 seconds and returns what arrived: order updates, best price changes of up to 10 books, and the latest positions and balances. An assistant uses it to wait for a fill or a price move instead of polling, and nothing stays subscribed after it returns. If the connection drops while it watches orders, the result says so, and the assistant checks the order with `get_order` before acting. **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 | | - | - | | `create_order`, `amend_order`, `cancel_order`, `cancel_orders_batch`, `cancel_all_orders`, `set_cancel_after`, `close_positions`, `redeem_positions`, `merge_positions`, `convert_to_pusd`, `create_stop_loss`, `update_stop_loss`, `cancel_stop_loss`, `create_limit_chase`, `update_limit_chase`, `cancel_limit_chase`, `create_conditional_sell`, `cancel_conditional_sell`, `pause_trading`, `lower_limits` and `create_deposit_addresses` | `trade`, a **Read and trade** key (see [Authentication](/authentication#create-a-key)) | | `reset_test_mode`, offered only with a test key | `trade`. It starts the test account over, as [Reset test mode](/api-reference/test-mode/reset-test-mode) does. | | `create_transfer`, `execute_transfer`, `create_routed_order` and `execute_routed_order` | `trade` and `route`. A **Read and trade** key made in the Lean app has both. A live transfer also needs trading enabled in the Lean app. See [Transfers](/transfers) and [Routed orders](/routed-orders). | | `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 as compact JSON, including `livemode`. An API error comes back with its status, code, message, request ID and details. A rate limit refusal also carries `retry_after_seconds`, and where the next step is clear the error adds a `hint`, such as reading an order back by its client ID before sending a write again after a timeout. A tool refuses any argument it does not define, so a misspelled filter is an error, not silently ignored. ```json Claude Desktop (claude_desktop_config.json) theme={"dark"} { "mcpServers": { "lean": { "command": "npx", "args": ["-y", "@leanxyz/mcp"], "env": { "LEAN_API_KEY": "lean_sk_test_..." } } } } ``` ```bash Claude Code theme={"dark"} claude mcp add lean --env LEAN_API_KEY=lean_sk_test_... -- npx -y @leanxyz/mcp ``` ```json Cursor (.cursor/mcp.json) theme={"dark"} { "mcpServers": { "lean": { "command": "npx", "args": ["-y", "@leanxyz/mcp"], "env": { "LEAN_API_KEY": "lean_sk_test_..." } } } } ``` ```json Cursor with trading tools theme={"dark"} { "mcpServers": { "lean": { "command": "npx", "args": ["-y", "@leanxyz/mcp", "--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://docs.lean.xyz/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://docs.lean.xyz/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.** Any OpenAPI 3.0 generator works with the spec, 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 prediction markets, sports and events, 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://docs.lean.xyz/llms.txt Spec: https://docs.lean.xyz/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://docs.lean.xyz/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-12-04** 0.1.0: combo RFQ quotes arrive sooner and replaced quotes are rejected **RFQs** * On Kalshi and Polymarket US, [`POST /v1/rfqs`](/api-reference/rfqs/create-combo-rfq) and [`POST /v1/rfqs/{id}/accept`](/api-reference/rfqs/accept-combo-rfq) now follow the venue's private stream while they wait, so initial quotes and accept results return sooner. If the stream is unavailable, Lean reads the venue as before. [`GET /v1/rfqs/{id}`](/api-reference/rfqs/retrieve-combo-rfq) still reads the latest quotes from the venue when you call it. * A Kalshi accept that would previously end as `acceptance_unconfirmed` because the maker replaced the quote now returns `rejected`, with the venue's reason when it gives one. If you receive `rejected`, read the RFQ again before choosing another quote. * The [RFQs reference](/api-reference/rfqs/create-combo-rfq) now lists create, retrieve, accept and cancel. **2026-12-03** 0.1.0: discovery volume is dollars traded **Markets** * **Breaking, effective 2026-12-03:** `volume_24h_usd` in [`POST /v1/discover`](/api-reference/markets/discover-markets), its batch and taxonomy responses is now dollars traded over the last 24 hours. It was previously the number of contracts traded. Volume computed from trades counts each fill at its YES price times its contracts; a Hyperliquid or Lighter market can instead carry the venue's own reported 24h dollar notional, which on Hyperliquid adds YES- and NO-token notional. `min_volume_24h`, `max_volume_24h` and the `volume` sort use the same dollars, so a threshold you send now selects by dollars rather than contracts. **2026-12-03** 0.1.0: reward programs carry exact Kalshi program fields **Rewards** * Each Kalshi program in [`GET /v1/rewards/programs`](/api-reference/rewards/list-reward-programs) also carries `period_reward_centicents`, the exact `target_size_fp` decimal string, `last_rest_update`, `created_at` and `updated_at`. `last_rest_update` and `updated_at` record when a Kalshi refresh last inserted or changed the program; an unchanged refresh leaves them as they were. **2026-12-02** 0.1.0: limit chase lists show pending edits **Limit chases** * `GET /v1/limit-chases` shows an edit Lean has accepted but not yet applied as reading the limit chase by id does: the edited values with `edit_pending: true`. A list read just after an edit can still trail it. See [Change a limit chase](/limit-chases#change-a-limit-chase). **2026-12-02** 0.1.0: order previews say whether a resting order earns liquidity rewards **Orders** * Each `execution.legs[]` entry of an [order preview](/preview#liquidity-rewards) carries `reward`: for a leg on a Polymarket, Kalshi or Polymarket US market with an active reward program, whether the part a `gtc` or `gtd` order would rest would score at its price and size, with `reasons` when it would not. `null` for a market without one. **2026-12-02** 0.1.0: amend in place, Polymarket US balance details **Orders** * [Amending](/orders#amend-in-place) a resting Kalshi or Polymarket US order to a smaller size at the same price, with the key that placed it, now changes the venue order in place. The order keeps its Lean ID, `client_order_id` and fills, and a Kalshi order keeps its place in the queue. Every other amend still cancels and replaces. * An amend in place whose venue order changed meanwhile returns `409 CONFLICT`. Read the order back and try again. * A Polymarket US amend keeps `post_only`. **Account** * Each Polymarket US balance from `GET /v1/balances` can carry `polymarket_us_details`, with `buying_power_usd`, `asset_available_usd`, `open_orders_usd` and `unsettled_funds_usd`. **2026-12-02** 0.1.0: trades and market lifecycle streams, closed event markets, reward programs, Kalshi subaccounts, weather, resolutions **Streams** * The [WebSocket](/api-reference/streaming/websocket#trades) stream has `trades` and `market_lifecycle` channels, each naming a venue listing by its `ticker`. `trades` sends trades as they happen, with maker and taker details. `market_lifecycle` sends status changes, with the result once known, and tick size changes. Live and test keys get the same frames. A session that falls behind on either is closed with `1013` and `RATE_LIMITED`. **Markets** * An event listing takes `include_closed=true` to list [closed event markets](/markets#closed-event-markets) from the last 30 days, alone or with `status=closed`. * [`GET /v1/resolution/markets`](/api-reference/markets/list-resolved-markets) lists recent Kalshi and Polymarket resolutions, newest first and once per event, 100 per page by default and 200 at most. * [`GET /v1/weather/{stationCode}`](/api-reference/markets/get-weather-station) returns a weather station's last 24 hours of readings, its forecasts and when the next reading is expected. **Account and rewards** * [`GET /v1/kalshi/subaccounts`](/api-reference/account/list-kalshi-subaccounts) lists your Kalshi subaccounts and their balances. Test keys get an empty list. * [`GET /v1/rewards/programs`](/api-reference/rewards/list-reward-programs) lists active reward programs on Kalshi, Polymarket US and Polymarket, filtered by `venue`, `ticker_prefix` and `min_daily_reward`, 200 per page by default and 1000 at most. **SDKs** * The TypeScript and Rust SDKs cover the new endpoints and stream channels. **2026-12-02** 0.1.0: reward earnings **Rewards** * [`GET /v1/rewards/earnings`](/api-reference/rewards/get-reward-earnings) returns what the key's account earned in Polymarket rewards today, an estimate for the whole day and its share of each market's pool. Test keys get zeros. **2026-12-02** 0.1.0: book channels stream deltas **Streams** (breaking) * A [WebSocket](/api-reference/streaming/websocket#book) `book` channel now sends the whole book once, then `book_delta` frames holding only the levels that changed since the book Lean last published. A quantity of `"0"` removes a level. A book with no change gets an empty delta about once a second. * `book` and `book_delta` frames carry a `sequence`, and a delta carries the `prev_sequence` it follows. A session that reads too slowly, or a market whose venues change, gets a whole `book` frame again. The TypeScript and Rust SDKs apply deltas and still hand you the whole book. * Stream book quantities keep the venue's precision, as `GET /v1/markets/:id/book` returns them, so a level holding a fraction of a share is listed. * A session can hold up to 1000 channels. * A key can hold up to 500 open streams at once, up from 50. One more is closed with `1013` and `RATE_LIMITED`. **2026-12-02** 0.1.0: test cost basis with fees, MCP argument errors, expired transfer times **Account** * A test position's cost basis now includes the fees its buys paid, as a live position's does. A settled test position's `unrealized_pnl_usd` now matches what `GET /v1/pnl` realized for it. * A transfer that expired before anything was written for it shows when it expired in `updated_at`. **SDKs and MCP server** * `requestId` in the TypeScript SDK and `request_id` in the Python SDK return nothing, rather than throwing, when an error body has no `meta`. * An MCP tool called with arguments its schema refuses now returns a tool error in the same shape as an API error, with code `INVALID_INPUT` and each refused field in `details.issues`, so the assistant can correct the call. **2026-11-25** 0.1.0: event listings reach back 48 hours, titles name the event, faster search and category listings **Markets** * An event listing's `ends_after` now defaults to 48 hours ago, so a market the venue keeps trading after its scheduled close, such as a daily weather market waiting for the day's reading, stays listed. Pass `ends_after` to list only markets that have not reached their scheduled close. * An event market's `title` starts with its event title when the venue names the market only by its range or outcome, so a daily temperature market reads `Highest temperature in Miami on Nov 24, 2026? 77° to 78°: Yes` instead of `77° to 78°: Yes`. * `search` on an event listing now matches whole words of the venue market title, its event title and its outcome names, the last word as a prefix, so `rain` finds `Rain` and `Rainfall` but no longer `Ukraine`. It answers faster on broad words. An event listing cursor issued with `search` before this change is refused; start that listing again from its first page. * `search` on a sports listing answers faster on broad words that used to time out. * An event listing with a `category` that has few open markets, such as `transportation` or `society`, answers in about a second instead of timing out. * A read that runs out of time, such as a broad market listing, now returns `503 UPSTREAM_ERROR` with `Retry-After` instead of `500 INTERNAL_ERROR`. A busy `search` sends `Retry-After` too. **Orders** * `POST /v1/orders/preview-batch` refuses a body with a field other than `orders` with `400 VALIDATION_ERROR`, as the other order endpoints do. **2026-11-25** 0.1.0: faster previews, decimal quantities **Orders** * Previews and quotes now price on books at most about 2 seconds old and read funds from a read at most 30 seconds old, so they answer faster. [`POST /v1/orders`](/preview#how-fresh-a-preview-is) still reads everything fresh. * When Kalshi throttles a balance read, a preview answers from the last balance read instead of failing. * A venue route that cannot reach Lean's cache returns `503 UPSTREAM_ERROR` instead of `500 INTERNAL_ERROR`. * Quantities are summed as decimals, so a total reads `66.9` rather than `66.89999999999999`, and fractional quantities are kept. **2026-11-24** 0.1.0: hosted MCP server with log in with Lean **MCP server** * Lean hosts the MCP server at `https://api.lean.xyz/mcp`. Add the address to Claude, ChatGPT, Claude Code, Codex, Cursor or VS Code, log in with Lean, and choose what the assistant gets, as when you create a key. See [Connect Lean to your assistant](/build-with-ai#connect-lean-to-your-assistant). * `watch_stream` watches for up to 25 seconds per call, down from 50, so a hosted call always answers before the connection times out. Call it again to keep watching. * **API keys**: a key granted to an assistant this way carries `oauthClient`, the assistant it was granted to. It is `null` for a key made in settings. **2026-11-24** 0.1.0: faster positions, PnL and risk **Account** * `GET /v1/positions`, `GET /v1/pnl` and `GET /v1/risk` answer faster on accounts with many holdings. Position marks no longer wait for the Polymarket US or Lighter book of a market no one read in the last few seconds: that holding keeps its source's `mark_price` for the read, and a read a few seconds later marks it from the book. **2026-11-24** 0.1.0: event listing cursors keep their filters, rules read once **Markets** * An event listing's `next_cursor` now works only with the `category`, `venue`, `search`, `ends_after` and `ends_before` that listed it, and is refused with `400 VALIDATION_ERROR` otherwise. Event listing cursors issued before this change are refused too; start the listing again from its first page. * `legs[].resolution.rules` reads a Polymarket US market's rules once. The venue stores the same text as its main and secondary rules, and both used to be shown. * The docs now say that `search` on an event listing matches text anywhere in a title, even inside a longer word, and that a market a venue stopped trading is refused with `409` on quotes, previews and orders while its book still reads. **Streams** * The [WebSocket](/api-reference/streaming/websocket#errors) docs list every error a frame sent before `auth` gets, and say that a `book` channel naming a venue symbol for more than one market ends with `book_ended` and `unknown_market`. **2026-11-24** 0.1.0: MCP server streams, previews on a read only key, test mode reset **MCP server** * `watch_stream` watches order updates, best price changes of up to 10 books, positions and balances for up to 50 seconds and returns what arrived, so an assistant can wait for a fill without polling. It needs Node.js 22.4 or later. * `preview_order` and `preview_orders_batch` are read tools, offered with a **Read only** key as the API allows. * With a test key and trading on, `reset_test_mode` starts the test account over. * A rate limit error carries `retry_after_seconds`, errors add a `hint` where the next step is clear, and responses are compact JSON. * The tool schemas carry the API's own caps, so a value the API would refuse is caught first: book depth, trades per page, market IDs per price read, limit chase offset ticks and conditional sell followers. A stop loss or limit chase `expires_at` must be in UTC ending in `Z`. **2026-11-24** 0.1.0: Polymarket US and Lighter books on the first read **Markets** * `GET /v1/markets/{id}/book` and `GET /v1/prices` wait up to a second for the Polymarket US or Lighter book of a market no one read in the last few seconds, as quotes and orders do, instead of listing the venue in `unavailable`. A stop loss or take profit trigger check waits the same way instead of refusing with `503 UPSTREAM_ERROR`, and position marks wait within their read deadline. **2026-11-24** 0.1.0: Lighter closes, expired gtd orders, stricter queries **Orders** * A Kalshi `fok` order that Kalshi cannot fill in full reads `canceled` with `filled_quantity` `"0"`, as an `ioc` order that finds no match does. * A Polymarket `gtd` order that reaches `expires_at` reads `expired`. It used to read `canceled`. * An order or preview on a market every venue has stopped trading returns `409 CONFLICT` with `details.reason: "MARKET_NOT_TRADABLE"` before any venue's own order rules, so a Polymarket `ioc` buy sized with `quantity` on such a market gets the `409`, not a `400`. A Lighter window that has ended answers the same way. * Orders and fills on a Lighter window name it by `title` and `outcome`, as its position does. They used to read `null`. * A `canceled` row of `POST /v1/orders/cancel-batch` means every leg's cancel was accepted. Its `order` can still read `cancel_requested` until each venue confirms, as the docs now say. * `POST /v1/positions/close` sells Lighter positions with the rest, and `venue: "lighter"` scopes it to them. Its limit sells on Lighter are `ioc`. It used to answer `nothing_to_close` for them. `legs[].venue` and `unavailable_venues` can name `lighter`. **Account** * `GET /v1/account/config` lists `lighter` in `venues`, ready when a Lighter account is connected to the key's trading account. * `GET /v1/pnl/history` reads an `end` after now as now, and the response's `end` shows the time it used. **Requests** * **Breaking, effective 2026-11-24:** `GET /v1/balances`, `GET /v1/account/config`, `GET /v1/risk`, `GET /v1/conversions`, the list and read of stop losses, limit chases and conditional sells, and `GET /v1/transfers/{id}` refuse a query parameter with `400 VALIDATION_ERROR`, since they take none. They used to ignore it. * **Breaking, effective 2026-11-24:** a query parameter sent more than once returns `400 VALIDATION_ERROR` naming it, instead of a type error such as `received nan`. **2026-11-24** 0.1.0: fill or kill on Polymarket US, fully filled Polymarket buys **Orders** * **Breaking, effective 2026-11-24:** a `fok` order no longer goes to Polymarket US, which can fill part of a fill or kill order and expire the rest. A `fok` order goes whole to Polymarket, else Kalshi. On a market listed only on Polymarket US it is refused with `400 VALIDATION_ERROR`; send `ioc` instead. A `fok` buy sized with `quantity` goes to Kalshi only. * An `ioc` or `fok` buy on Polymarket that bought every share its dollars could buy reads `filled`. It used to read `canceled` when Polymarket's rounding of the spend to whole cents left it a fraction of a share short of `quantity`. **2026-11-21** 0.1.0: Kalshi and Polymarket US event markets **Markets** * `GET /v1/markets` lists event markets on all four prediction venues: Polymarket, Polymarket US, Hyperliquid and Kalshi. `venue=polymarket_us` and `venue=kalshi` take event listings. Kalshi multivariate (parlay) markets are not listed. * A Kalshi event Lean has not categorized takes the category Kalshi files it under, such as `politics` for Kalshi's Elections, else `uncategorized`. * A `pmus:` ticker or Kalshi market ticker of a market outside sports names its event market, in `symbol=` and wherever a market ID is taken, when that listing pays one outcome. **Orders** * Event markets on every venue trade single-venue through the normal order API, in live and test mode. Sports markets keep smart order routing; a routed order on an event market is refused with `ROUTE_NOT_EXECUTABLE`. * Orders, fills and positions on Kalshi and Polymarket US event markets name the event market by its `mkt_…` ID, title and outcome, as on Polymarket and Hyperliquid. `POST /v1/positions/merge` stays Polymarket and Hyperliquid only. **Streams** * Subscribe to an event market's book on `/v1/ws` with a `book` channel naming its `mkt_…` ID. The stream has no trades, quotes or fills channel; each `orders` frame carries the order's fills. * `orders` frames name an event market by its `mkt_…` ID, title and outcome. **2026-11-21** 0.1.0: API keys that never expire, book snapshot flag, book stream ends **API keys** * `POST /api-keys` takes `expiresInDays: null` for a key that never expires, and the dashboard adds a **Never expires** switch. See [Authentication](/authentication). **Streams** * Each `book` frame has a `snapshot` field. It is `true` on the first frame after you subscribe, which is the newest book Lean already holds and can have an `as_of` up to about a second old, and `false` on every later frame. See [Streaming](/streaming). * A `book` channel whose `market_id` names no market, or whose market closed, sends one `book_ended` frame and stops, instead of staying silent. See [WebSocket](/api-reference/streaming/websocket#book). * `subscribed` and `unsubscribed` frames list each channel once, even when the request named it twice. **2026-11-20** 0.1.0: event markets **Markets** * `GET /v1/markets` lists Polymarket and Hyperliquid markets outside sports, such as elections, central bank decisions and coin prices on a date. Pass a `category` other than `sports` or `crypto` (`politics`, `economy`, `business` and more), or `kind=event`. Each venue market is two markets, its `yes` and `no` sides, with `kind: "event"`, an `event` instead of `fixture` and `group`, one leg and `equivalence: "single_venue"`. See [Event markets](/markets#event-markets). * `GET /v1/markets` takes `kind`, and `ends_after` and `ends_before` to list event markets by scheduled close. With no `category` or `kind` it still lists sports markets, and `category=crypto` still lists Lighter crypto windows; `kind=event&category=crypto` lists event coin-price markets. * A Polymarket token ID, `pm:` or `hl:` ticker, or Hyperliquid book coin of a market outside sports now names its event market, in `symbol=` and wherever a market ID is taken. * Books, prices, quotes, trades, candles and the `book` stream channel take event markets. **Orders** * Previews, orders, amends, cancels, stop losses, limit chases and conditional sells take event markets, with the same order types as sports markets, in live and test mode. `game_start` is refused on them. * Routed orders stay sports only: a routed order on an event market is refused with `ROUTE_NOT_EXECUTABLE`, since it lists on a single venue. **Risk** * `GET /v1/risk` groups event market holdings under their `category` in `by_category`, with `sport: null`. **2026-11-19** 0.1.0: positions read deadline, book stream on change, OR orders **Positions** * `GET /v1/positions` answers within about 3 seconds. A venue that has not answered by then is listed in `unavailable`, and the other venues are still returned. **Streams** * The `book` stream channel sends a frame as soon as a venue book changes, and at least once a second otherwise. **Conditional sells** * Conditional orders made in the Lean app that rest on several markets at once are not conditional sells, so `/v1/conditional-sells` does not list them. **2026-11-19** 0.1.0: conditional sells, change stop losses and limit chases, more chase offsets **Conditional sells** * `POST /v1/conditional-sells` sells one position and, as it fills, sells the same number of shares of up to five others, each never below its floor price. `GET /v1/conditional-sells`, `GET /v1/conditional-sells/{id}` and `DELETE /v1/conditional-sells/{id}` list, read and cancel them. They run on Kalshi, Polymarket, Polymarket US and Hyperliquid. See [Conditional sells](/conditional-sells). * A test key's conditional sell is checked, listed, read and canceled like a live one but never sells. Reset test mode clears them and counts them in `deleted_conditional_sells`. * The MCP server adds `list_conditional_sells` and `get_conditional_sell`, and with the `trade` scope `create_conditional_sell` and `cancel_conditional_sell`. **Stop losses and limit chases** * `PATCH /v1/stop-losses/{id}` changes the trigger price, quantity or slippage limit of a stop loss or take profit that is still watching the market, keeping its id. See [Change a stop loss](/stop-losses#change-a-stop-loss). * `PATCH /v1/limit-chases/{id}` changes the quantity, offset or price limit of an active limit chase, keeping its id. Where the venue amends in place, a smaller size keeps its place in the queue. A limit chase reads back `edit_pending` while Lean applies the edit, and `last_error` when Lean refuses it. See [Change a limit chase](/limit-chases#change-a-limit-chase). * A limit chase takes `offset_shares`, the most shares it lets rest ahead of it, and `offset_beat_best`, to rest one tick better than the best price. Every limit chase reads back `offset_beat_best`, and `offset_midpoint` for one made in the Lean app that rests within a set distance of the midpoint. * The MCP server has `update_stop_loss` and `update_limit_chase`. **2026-11-19** 0.1.0: gtd orders on Hyperliquid **Orders** * `gtd` orders, `expires_at` `game_start` included, now reach Hyperliquid. Hyperliquid has no order expiry, so Lean places the order as `gtc` and cancels what is left at `expires_at`. It then reads `expired`, like a `gtd` order on any other venue, and keeps any shares that filled. See [Fill or kill and expiring orders](/orders#fill-or-kill-and-expiring-orders). **2026-11-19** 0.1.0: convert USDC and USDC.e to pUSD **Funding** * `GET /v1/conversions` shows the USDC and USDC.e in the account's Polymarket wallet. Polymarket trades only with pUSD, so these are not cash until they are converted. * `POST /v1/conversions` converts the whole balance of one `source_asset`, `usdc` or `usdc_e`, into pUSD. A USDC.e conversion is `settled` once it confirms. A USDC conversion is `submitted`, and its pUSD arrives a few minutes later. * It needs the trade scope and follows the trading pause and venue limits. A test key holds nothing to convert, so it is refused with `details.reason` `NOTHING_TO_CONVERT`. * When Lean cannot reach Polymarket's relayer, a conversion is refused with `503 FEATURE_DISABLED` and nothing is submitted. * The MCP server has `get_convertible_balances` and `convert_to_pusd`. * See [Convert USDC to pUSD](/funding#convert-usdc-to-pusd). **2026-11-19** 0.1.0: deposit history, leg results, venue connections, game start expiry **Deposits** * `GET /v1/deposits?venue=` lists the latest deposits to your Polymarket or Hyperliquid addresses, newest first, each with its `status` (`detected`, `processing`, `completed`, `failed` or `refunded`), the amount credited and its transactions. Deposits through Relay or the Polymarket bridge are listed; pUSD sent straight to the Polymarket wallet is not. A test key reads an empty list. See [Deposits through the API](/funding#deposits-through-the-api). **Markets** * `legs[].resolution.result` reads `won`, `lost` or `void` once a leg is `resolved`, and `null` before. See [Legs](/markets#legs). **Account** * `GET /v1/account/config` returns `venues`: each venue with `status` `ready`, `not_configured` or `unavailable`, so a client can see which venues it can order on before it orders. `ready` matches what `POST /v1/orders` allows for the key. Keys are still connected in the Lean app only. A test key reads every venue `ready`. **Orders** * A `gtd` order takes `expires_at` `game_start` to expire when its market's game starts. It is refused once the game has started, and like any expiry it must be three minutes to thirty days away. See [Fill or kill and expiring orders](/orders#fill-or-kill-and-expiring-orders). **MCP server** * New tools: `list_deposits`, `preview_orders_batch`, `create_routed_order` and `execute_routed_order`. The routed order tools need the `route` scope, like the transfer tools. See [Build with AI](/build-with-ai). **2026-11-19** 0.1.0: live transfers through Relay **Transfers** * Live keys can now transfer. A live transfer moves real cash through Relay between Polymarket, Hyperliquid and Lighter, in any direction. Live keys no longer get `503 FEATURE_DISABLED` with `details.reason: "LIVE_TRANSFERS_UNAVAILABLE"`. * `from_venue` and `to_venue` also take `lighter`. Test keys still move simulated cash between Polymarket and Hyperliquid only, and a test key that names `lighter` gets `400 VALIDATION_ERROR`. * A live quote's `fee_usd` is Relay's price at that moment plus any fee the sending venue charges. The live minimum is 2 USD. * A live transfer has nothing to sign: its `authorization` is `null` and it executes with `"delegated"` only, so the account must have enabled trading in the Lean app. An account moves one transfer at a time. * See [Live transfers](/transfers#live-transfers). **2026-11-19** 0.1.0: Lighter crypto markets **Markets** * `GET /v1/markets` lists Lighter's BTC and ETH 15 minute up or down windows with `category=crypto` or `venue=lighter`. Each market has `kind: "time_window"` and a `window` instead of `fixture` and `group`. Sports markets now carry `kind: "sports"`. See [Crypto windows](/markets#crypto-windows). * Books, prices, trades, candles and the `book` stream channel cover Lighter markets, and `venue` takes `lighter` on those reads. A Lighter `lt:` ticker lists both markets of its window with `symbol=`. * Quotes on Lighter markets are refused with `400 VALIDATION_ERROR`. **Orders** * `POST /v1/orders/preview`, `POST /v1/orders` and cancels take Lighter markets, in live and test mode. Orders take `gtd` or `ioc`, expire with their window, are sized in shares and cannot be amended. See [Lighter](/venues#lighter). * An order's `venue` and legs, and `GET /v1/orders?venue=`, can name `lighter`. **2026-11-17** 0.1.0: redeem and merge positions **Positions** * Every position has `redeemable` and `payout_usd`. A Polymarket holding of a resolved market that pays out is `redeemable` until it is redeemed; other venues pay resolved holdings out on their own. `payout_usd` is what the holding pays once its market resolves, and `null` while it is open. * `POST /v1/positions/redeem` pays out every redeemable holding, or only those on one `market_id`, and lists each one with its payout. * `POST /v1/positions/merge` turns pairs of YES and NO shares on one market back into cash on Polymarket or Hyperliquid. * A venue symbol as `market_id` settles only that listing of a market listed more than once. * Both need the trade scope and follow the trading pause and venue limits. A test key redeems and merges in simulation. Reset test mode undoes them and returns `deleted_settlements`. * The MCP server has `redeem_positions` and `merge_positions`. * See [Redeem and merge](/orders#redeem-and-merge). **2026-11-17** 0.1.0: the Lean MCP server on npm **Build with AI** * The Lean MCP server is the `@leanxyz/mcp` package on npm. It needs Node.js 22 or later, and an MCP client starts it with `npx -y @leanxyz/mcp`, so you no longer need a copy of the source. See [Run the Lean MCP server](/build-with-ai#run-the-lean-mcp-server) for Claude Desktop, Claude Code and Cursor settings. **2026-11-17** 0.1.0: settled positions, and names for futures and older holdings **Positions** * Each position in `GET /v1/positions` and the `positions` stream channel carries `settled`: `true` once its market has resolved. Its `unrealized_pnl_usd` stays its settlement payout minus cost, but `GET /v1/pnl` leaves it out of the account's unrealized PnL. See [Read positions](/orders#read-positions). * A holding on a fixture that started more than 7 days ago keeps its `market_id`, `title` and `outcome`. * A holding on a market the API does not list, such as a season futures market, takes its `title` and `outcome` from the venue market; its `market_id` stays `null`. `search` matches it. **Profit and loss** * `GET /v1/pnl` reports `meta.source` `upstream` for every read, the account included, since its unrealized amount marks open positions live. Each venue's `updated_at` is now the read time, the same as `as_of`, instead of when the stored record last changed. **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: 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). # Conditional sells Source: https://docs.lean.xyz/conditional-sells Sell one position and have Lean sell related positions by the same count as it fills. A conditional sell sells one position, the leader, and as each leader share sells, Lean sells one share of every other position you name, the followers. Each follower has a floor price it never sells below. Use it to unwind positions that only make sense together, such as both sides of a hedge on two venues, without one side being left open. Conditional sells run on Kalshi, Polymarket, Polymarket US and Hyperliquid, and the legs may be on different venues. A leg naming `lighter` is refused with `422` and reason `NO_EXECUTABLE_VENUE`. This example uses a test key, so nothing real moves: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/conditional-sells" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "leader": { "market_id": "'"$LEADER_MARKET_ID"'", "venue": "kalshi", "type": "limit", "limit_price": "0.62" }, "quantity": "25", "followers": [ { "market_id": "'"$FOLLOWER_MARKET_ID"'", "venue": "polymarket", "floor_price": "0.55" } ] }' ``` | Field | Meaning | | - | - | | `leader.market_id` | A `mkt_…` ID from `GET /v1/markets` for the position the leader sells. | | `leader.venue` | `kalshi`, `polymarket`, `polymarket_us` or `hyperliquid`: the venue holding the leader's shares. | | `leader.type` | `limit` rests a sell at `limit_price` at once. `stop` sells nothing until the best bid falls to `trigger_price`, then sells down to `trigger_price` minus `slippage_limit`. | | `leader.limit_price` | For a `limit` leader only. The price the sell rests at, in dollars between `0.0001` and `0.9999` on the market's price ticks. | | `leader.trigger_price` | For a `stop` leader only. The best bid that starts the sale. It must be below the current best bid, or the sale would start at once. | | `leader.slippage_limit` | Optional, for a `stop` leader only. How far below `trigger_price` the sale may fill, in dollars above `0` and at most `0.2`. The default is `0.05`. | | `quantity` | Shares the leader sells, as a decimal string. | | `followers` | From one to five positions to sell as the leader fills. | | `followers[].market_id` | A `mkt_…` ID for the follower's position. | | `followers[].venue` | The venue holding the follower's shares. | | `followers[].floor_price` | The lowest price the follower sells at, in dollars on the market's price ticks, at or below its current best bid. | The key needs the `trade` scope. The answer is `200` with the conditional sell, which reads `active` while the leader sells or waits, or `paused` with `pause_reason` `floor` when a follower cannot sell at its floor yet. ## How it sells The leader sells first. Each time leader shares fill, Lean sells the same number of shares of every follower at the best bids down to that follower's floor, and leaves any shares that do not sell at once resting at the floor. Each leg's `filled_quantity` and `avg_fill_price` grow as it sells, and `unhedged_quantity` is the number of leader shares a follower has not matched yet. For a conditional sell led by a `limit` leader, Lean pauses it with `pause_reason` `floor` while a follower's book does not hold enough shares at or above its floor to match the leader, or while a follower's book cannot be read for 30 seconds before the leader is placed. A leader already resting on its venue stays live while a follower's book cannot be read. It carries on by itself once every follower's book has held enough at its floor for 5 seconds. | `status` | Final | Meaning | | - | - | - | | `active` | No | The leader is selling or waiting for its trigger. | | `paused` | No | Selling stopped. `pause_reason` says why. | | `hedging` | No | The leader has sold every share and followers are still selling. | | `filled` | Yes | Every leg has sold every share. | | `canceled` | Yes | Canceled by you, or the venue refused the first leader order, which `reject_reason` explains. Shares already sold stay sold. | A follower's `state` is `idle` before it has anything to sell, `selling` while a sell works, `retrying` after a sell failed and another is on its way, `below_minimum` while the shares it owes are under the venue's minimum order, `failed` once it runs out of retries, and `done` once it has sold every share it owes. A `failed` follower stays unsold until you retry it in the Lean app or sell it yourself. `pause_reason` is `floor` for a follower floor, `user` when the sell was paused in the Lean app, or one of `leader_unconfirmed`, `leader_ended`, `leader_account_changed` and `leader_rejected` when the venue did not confirm, ended or refused the leader order. A conditional sell paused for a reason that starts with `leader_` waits for you: resume it in the Lean app, or cancel it. ## Limits on what can be sold * Every leg, the leader included, is a different position the trading account holds. Each must hold `quantity` shares beyond what the account's resting sells, stop losses and other conditional sells already cover, or the request is refused with `400 VALIDATION_ERROR`. * With a live key, a follower whose market has no bid, or whose floor is above its best bid, does not refuse the request. A conditional sell led by a `limit` leader starts `paused` with `pause_reason` `floor`, and one led by a `stop` leader starts `active`. A test key refuses such a follower with `400 VALIDATION_ERROR`. * A `stop` leader whose trigger is at or above its best bid, or whose market has no bid, is refused with `400 VALIDATION_ERROR`. * Every leg's market must be open, or the request is refused with `400 VALIDATION_ERROR`, and it must trade on the venue you name. A leg that cannot be traded on its 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 conditional sell counts toward the key's rolling day as orders at the leader's lowest price and each follower's floor would. It only takes risk off, so neither the per order nor the daily limit refuses it. * With a live key, a request is refused with `403 FORBIDDEN` when the account can't trade on a leg's venue: for example, on Kalshi and Polymarket US no API key is connected in the Lean app, or on Polymarket the wallet isn't set up or its approvals need refreshing in the Lean app. * Creating one is refused with `503 FEATURE_DISABLED` while trading is paused or, for a live key, while Lean has paused these orders on a leg's venue, and with `503 UPSTREAM_ERROR` when a leg's book could not be read. See [Pause trading](/orders#pause-trading). ## Track and cancel `GET /v1/conditional-sells` lists the conditional sells of the key's trading account, newest first: every one still active, paused or hedging, and those that ended in the last day. A live key also sees the conditional sells made in the Lean app on that account, as long as every leg is on a venue the API trades. `GET /v1/conditional-sells/{id}` reads one. Conditional buys and OR orders made in the Lean app are not part of the API: they are not listed, cannot be read and cannot be canceled here. An ended conditional sell can stay in the list past the day until Lean has finished settling it. A conditional sell's sales are not orders you placed, so they send no `order` frame on the stream, and their fills are listed in `GET /v1/fills` with `order_id` set to `null`. Each leg's `filled_quantity` and `avg_fill_price` show what it has sold. Cancel one with `DELETE /v1/conditional-sells/{id}`: ```bash theme={"dark"} curl -sS -X DELETE "$LEAN_API_URL/v1/conditional-sells/$CONDITIONAL_SELL_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` The answer is `200` with the conditional sell reading `canceled`. Lean cancels the leader's resting sell and any follower sells still working, and shares already sold stay sold. Canceling works while trading is paused. A conditional sell that has already ended is refused with `409 CONFLICT`. Pausing trading does not stop a conditional sell that is already working. Cancel it if you want it gone. ## Test keys A test key's conditional sell is checked like a live one, against each leg's market and the test account's simulated shares, and it can be listed, read and canceled. It never sells, so it stays `active` until you cancel it, and its shares count as covered until then. See [Test mode and live mode](/test-mode). # Errors Source: https://docs.lean.xyz/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": { "orderErrorCode": "INSUFFICIENT_BALANCE", "retryable": false, "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.orderErrorCode` | When a venue error stopped the request: the specific reason, for example `INSUFFICIENT_BALANCE`, with `retryable` saying whether the same request can succeed later. A venue that refuses an order you placed does not cause an error: the order comes back `rejected` with the reason in `status_reason.code`. | | `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 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 a payment Lean had to make for the order, such as a buy paid from the other venue. `details.orderErrorCode` 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"`: 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/transfers` or its execute with 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. See [Live transfers](/transfers#live-transfers). | | 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). | | 400 | `VALIDATION_ERROR` | On `POST /v1/conditional-sells`: a price or the quantity does not fit a leg's market, two legs are the same position, a follower's floor is above its best bid or its market has no bid, a `stop` leader's trigger is at or above its best bid, or a leg holds less than the quantity beyond the account's resting sells, stop losses and other conditional sells. | Fix the request. See [Conditional sells](/conditional-sells). | | 409 | `CONFLICT` | On `DELETE /v1/conditional-sells/{id}`: the conditional sell has already ended. On `POST /v1/conditional-sells`: another conditional sell is being created for the same positions. | Read the conditional sells back. | | 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` | On `POST /v1/transfers` with a live key: another live transfer on the account is still open. Nothing was created. | Wait until the open transfer finishes, then create the new one. | | 409 | `CONFLICT` | `client_order_id` reused with a different body (`details.order_id` is the original). Or a cancel of an order that has finished, one the venue has not acknowledged yet, or a routed order whose payment is already signed and under way. A resting `gtc` or `gtd` test order can be canceled like a live one. | 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 across venues, or not `gtc`) 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` | On a quote, preview or order: a venue has stopped trading the market, so there is nothing to quote or fill against. `details.reason` is `MARKET_NOT_TRADABLE`. Reads still work: `GET /v1/markets/{id}/book` answers `200` for the market, with empty levels or with the venue listed in `unavailable`. | 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, dropped the connection or is briefly unavailable, such as text search on `GET /v1/markets`, a read ran out of time, or the request lost a database conflict. `Retry-After` is sent when Lean knows how long to wait. On placement the order may or may not have reached the venue. | Wait for `Retry-After` when it is sent. Otherwise retry shortly, waiting longer between each try. 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`. Nothing was placed. | 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`. Nothing was placed. | 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. Nothing was placed. | Retry later. | | 503 | `UPSTREAM_ERROR` | On a transfer quote or create with a live key: Relay or a venue could not price or prepare the route. Nothing was sent. | Retry with the same `client_transfer_id`. See [Transfers](/transfers#live-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.orderErrorCode` 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 one of those venues accepts at the order's limit price, counting its share minimum: 5 shares on most Polymarket books, whole shares on Hyperliquid. 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`, `POST /v1/limit-chases` and `POST /v1/conditional-sells`, the market cannot be traded on the `venue` you named, or the venue is `lighter`, which runs none of them. | | `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://docs.lean.xyz/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 and withdrawals through Lean cover Polymarket and Hyperliquid only. Live [transfers](/transfers) move cash between Polymarket, Hyperliquid and Lighter. Fund your Kalshi and Polymarket US accounts on those venues directly. `GET /v1/balances` and `GET /v1/positions` cover Kalshi, Polymarket, Polymarket US and Hyperliquid. Cash moved to Lighter and Lighter positions don't appear there; check them in the Lean app. 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 | The accepted tokens differ by chain and venue. [List deposit assets](/api-reference/deposits/list-deposit-assets) returns every chain and token each venue accepts right now, with the minimum for each. 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. * [List deposits](/api-reference/deposits/list-deposits) shows the latest deposits to your addresses on a venue, newest first, with each one's `status`: `detected` once the funds reach the address, `processing` while they move, then `completed` when the venue is credited, `failed`, or `refunded` to the sender. It lists deposits that go through Relay or the Polymarket bridge. pUSD sent straight to your Polymarket wallet is credited at once and is not listed. A test key reads an empty list. * [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. * A Hyperliquid withdrawal waits for any other transfer on the account to finish. That includes another withdrawal, a live transfer and a transfer started in the Lean app. While one is in progress, a new withdrawal 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. While trading is paused, a repeat is refused with `503 FEATURE_DISABLED` like a new withdrawal. Read the first one with [Get a withdrawal](/api-reference/withdrawals/retrieve-withdrawal) or [List withdrawals](/api-reference/withdrawals/list-withdrawals) instead. * 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. ## Convert USDC to pUSD Polymarket trades only with pUSD. USDC or USDC.e sent straight to the account's Polymarket wallet, instead of through a deposit address, sits there without counting as cash until it is converted. * [Get convertible balances](/api-reference/account/get-convertible-balances) shows the `usdc` and `usdc_e` waiting in the wallet. * [Convert to pUSD](/api-reference/account/convert-to-pusd) converts the whole balance of one `source_asset`, `usdc` or `usdc_e`, into the same amount of pUSD. It needs the trade scope. ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/conversions" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source_asset": "usdc_e" }' ``` The response has `venue`, `source_asset`, `amount_usd`, `status`, `transaction_id`, `failure_reason` and `livemode`. * USDC.e converts in one transaction: `settled` once it confirms, `submitted` while it is on its way. USDC goes through Polymarket's bridge, so it is always `submitted` and its pUSD shows in [Get balances](/api-reference/account/list-balances) a few minutes later. * `failed` converted nothing, and `failure_reason` says why. * The bridge has a minimum for USDC. A smaller balance is refused with `422 VALIDATION_ERROR` and `details.reason` `BELOW_MINIMUM`, and the message names the minimum. * An empty balance is refused with `422 VALIDATION_ERROR` and `details.reason` `NOTHING_TO_CONVERT`. One conversion runs at a time per account; another sent while one is settling is refused with `409 CONFLICT` and `details.reason` `CONVERSION_IN_PROGRESS`. * A live conversion needs trading enabled for the account in the Lean app, and is refused with `403 FORBIDDEN` and `details.reason` `ACCOUNT_NOT_DELEGATED` otherwise. It follows the trading pause and the key's allowed venues. * When Lean cannot reach Polymarket's relayer, a conversion is refused with `503 FEATURE_DISABLED` and no `details.reason`, and nothing is submitted. Try again later. * A test key's cash is always pUSD, so it reads zero for both and a conversion is refused with `NOTHING_TO_CONVERT`. ## 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 and live keys. Shares can't move between venues. A sell is placed on the venues that hold the shares. # Historical data Source: https://docs.lean.xyz/historical-data Multi-venue historical prediction market data across Kalshi, Polymarket, Polymarket US and Hyperliquid: L2 orderbooks (full depth on Kalshi/Polymarket, up to 20 levels/side on HIP-4), trades, bars and feed-health telemetry. Lean archives normalized, institutional-grade historical market data across the major prediction-market venues in one canonical schema. > [!NOTE] > > Historical data access is currently in **early access**. Email [s@lean.xyz](mailto:s@lean.xyz?subject=Lean%20Historical%20Data%20Access) to request sample files, custom date ranges or API access. ## Venues covered | Venue | L2 book depth | Tick trades | OHLCV & mid-price bars | Feed-health telemetry | | :- | :-: | :-: | :-: | :-: | | **Kalshi** | Full depth | Yes | Yes | Yes | | **Polymarket** | Full depth | Yes | Yes | Yes | | **Polymarket US** | Full depth | Yes | Yes | Yes | | **Hyperliquid (HIP-4)** | Up to 20 levels/side | Yes | Yes | Yes | ## Datasets ### L2 orderbooks Continuous orderbook snapshots and deltas captured directly from each venue's live stream (full depth on Kalshi, Polymarket and Polymarket US; up to 20 levels per side on Hyperliquid HIP-4), normalized across venues so you can reconstruct book depth, spreads and slippage for timestamps with a baseline snapshot and confirmed feed coverage (see [Feed health & gap provenance](#feed-health--gap-provenance) below). ### Tick trades & bars 3.6B+ normalized trade prints alongside pre-aggregated OHLCV and mid-price bars across venues, mapped to Lean's canonical market IDs. ### Canonical market metadata Cross-venue market and outcome mappings, venue leg identifiers, and resolution metadata so historical series join cleanly across Kalshi, Polymarket, Polymarket US and Hyperliquid. ### Feed health & gap provenance Explicit venue-side connection and data-quality telemetry (`connection` vs. `data-quality` streams) so backtests can distinguish quiet markets from venue outages or dropped feeds. ## Delivery formats * **Bulk Parquet flat files**: Partitioned by venue and date for direct querying in DuckDB, Polars, ClickHouse or Spark—no REST pagination or rate limits. * **REST snapshots & bars** *(early access)*: On-demand historical bars, trades and point-in-time snapshots over HTTPS. ## Contact us Interested in historical L2 orderbooks, trade archives or custom datasets? Reach out and let us know the **venues**, **date range** and **granularity** (L2 book replay, tick trades, or bars) you need. > [card] [Request historical data access](mailto:s@lean.xyz?subject=Lean%20Historical%20Data%20Access) > > Email **[s@lean.xyz](mailto:s@lean.xyz)** for sample Parquet files, schema docs and early access pricing. # Lean API v0.1 Source: https://docs.lean.xyz/index List canonical sports and event markets, quote them, place orders and reconcile, without naming a venue. **v0.1**Sports and event markets in preview Trade prediction markets from code. One API for canonical sports and event 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.
  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 and event 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. * The number of decimal places can differ between endpoints and venues for the same field, so `"4"`, `"4.00"` and `"4.000000"` are the same quantity. Parse decimal strings as numbers before you compare them. * Times are ISO 8601 strings, at up to microsecond precision, so parse them rather than compare the text. * 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, limit chases and conditional sells | `/v1/stop-losses`, `/v1/limit-chases`, `/v1/conditional-sells` | | Fills | `GET /v1/fills` | | Balances, positions, PnL and risk | `GET /v1/balances`, `GET /v1/positions`, `POST /v1/positions/close`, `POST /v1/positions/redeem`, `POST /v1/positions/merge`, `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`, `GET /v1/deposits` | | Convert USDC and USDC.e to pUSD, on Polymarket | `GET /v1/conversions`, `POST /v1/conversions` | | Withdrawals, from Polymarket and Hyperliquid | `POST /v1/withdrawals`, `GET /v1/withdrawals`, `GET /v1/withdrawals/{id}` | | Transfers between Polymarket, Hyperliquid and Lighter | `POST /v1/transfers/quote`, `POST /v1/transfers`, `POST /v1/transfers/{id}/execute`, `GET /v1/transfers`, `GET /v1/transfers/{id}` | | 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}` | | Key and account limits, and trading pauses, signed in | `/api-keys/{id}/limits`, `/api-keys/accounts/{tradingAccountId}/limits`, `/api-keys/suspensions`, `/api-keys/{id}/suspension`, `/api-keys/accounts/{tradingAccountId}/suspension` | ### How it works * Each sports market names the part of the game it covers in `group.period`. `game` is the full game, overtime included. * 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. * [Event markets](/markets#event-markets), such as elections and central bank decisions, list on one venue, Polymarket or Hyperliquid, and trade through the same order API on that venue. Smart order routing across venues is for sports markets. * 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. Orders on Lighter crypto markets also run live. 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, withdrawals and routed orders cover Polymarket and Hyperliquid only. Live transfers also reach Lighter. * Quotes price buys, and sells of shares the account holds. * Hyperliquid does not cancel resting orders at kickoff. Send `gtd` with `expires_at` `game_start` and Lean cancels them for you. See [Orders](/orders#kickoff). # Limit chases Source: https://docs.lean.xyz/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 at a set position relative to 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 Kalshi, Polymarket, Polymarket US and Hyperliquid. One naming `lighter` is refused with `422` and reason `NO_EXECUTABLE_VENUE`. 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`. With no offset, the order rests at the best price. | | `offset_price` | Optional. The same distance in dollars, from `0` to `0.1`. | | `offset_shares` | Optional. The most shares the order lets rest ahead of it in the queue, in steps of `0.01` up to `10000000`. The order rests one tick inside the first price level that would put more shares ahead of it. | | `offset_beat_best` | Optional. Only `true` is accepted: send it to rest one tick better than the best price, first in the queue. It stops one tick short of the other side, so it never trades at once, and when the spread is a single tick it joins the best price instead. | | `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 in UTC ending in `Z`, in the future and at most 30 days ahead. On Polymarket, and on any venue with a test key, it must be at least 2 minutes ahead. Leave it out to keep it until you cancel it. | Give at most one of `offset_ticks`, `offset_price`, `offset_shares` and `offset_beat_best`. The limit chase reads back the one it uses and `null` for the others, with `offset_beat_best` `false` unless it beats the best price. A limit chase made in the Lean app can instead rest as far back as it can within a set distance of the midpoint. It reads back that distance in dollars as `offset_midpoint`, which is `null` for every other limit chase. A request cannot set `offset_midpoint`, but an edit can keep it by leaving the offset out or replace it with one of the offsets above. On Polymarket the midpoint is the one Polymarket uses for liquidity rewards, which leaves out small orders at the top of the book. 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 where its offset puts it relative to the best price on its own side: behind it by `offset_ticks` or `offset_price`, inside the queue depth `offset_shares` allows, or one tick better with `offset_beat_best`. On Polymarket and Hyperliquid a buy rests higher when needed to stay worth at least 1 USD. It never rests at a price that would trade at once against the other side of the book, and never beyond `price_limit`. When its target price moves by a price tick or more, Lean moves the order there, waiting 2 seconds after the last move unless the order would otherwise trade at once or sit beyond `price_limit`. With `offset_shares`, it moves by the queue ahead of it rather than by each price change. On Kalshi the order is changed in place; on other venues Lean cancels it and places it again. 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, or the market closed or resolved first. Shares already bought or sold stay with the account. | | `expired` | Yes | `expires_at` passed before the order filled. | | `failed` | Yes | The venue refused the order 5 times in a row with nothing filled in between, Lean could not place it for about 10 minutes, or the order is too small to place at any price within `price_limit`. If part had filled, that last case ends `filled`. | ## 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. On Hyperliquid it must also fit the venue's size step. On Polymarket and Hyperliquid, a buy with a `price_limit` must be worth at least 1 USD at that price. * 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. * With a live key, a limit chase is refused with `403 FORBIDDEN` when the account can't trade on the venue: for example, on Kalshi and Polymarket US no API key is connected in the Lean app, or on Polymarket the wallet isn't set up or its approvals need refreshing in the Lean app. * Creating a limit chase is refused with `503 FEATURE_DISABLED` while trading is paused, or, for a live key, 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. Kalshi and Polymarket US limit chases belong to you rather than to a trading account, so a live key sees all of yours on those venues. `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. ## Change a limit chase Change the size, offset or price limit of a limit chase with `PATCH /v1/limit-chases/{id}`. It keeps its id, and fields you leave out keep their values: ```bash theme={"dark"} curl -sS -X PATCH "$LEAN_API_URL/v1/limit-chases/$LIMIT_CHASE_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "quantity": "40", "offset_beat_best": true }' ``` | Field | Meaning | | - | - | | `quantity` | Optional. The new total shares, counting what has already filled. It can't be less than `filled_quantity`. | | `offset_ticks`, `offset_price`, `offset_shares`, `offset_beat_best` | Optional. One new offset, which replaces the current one. | | `price_limit` | Optional. The new worst price the order rests at. Send `null` to remove it. | The new values are checked as they are when you create one. A buy is checked as a whole against your per order limit, and whatever the edit adds to the most it can trade for, from a larger size or a higher or removed `price_limit`, counts toward your day. The answer is `200` with the limit chase as edited. A live one answers with `edit_pending: true` and moves its resting order a moment later. Read it by id to confirm: once Lean applies the edit, `edit_pending` turns `false`. If Lean refuses the edit, for example because fills overtook a smaller size, the limit chase keeps its earlier values and `last_error` says why. A list shows a pending edit the same way, though it can trail an edit accepted a moment earlier. On Kalshi, Lean changes the resting order in place rather than canceling and placing it again, so a smaller size at the same price keeps its place in the queue. Only an `active` limit chase can change: one that has ended is refused with `400 VALIDATION_ERROR`, and one with a cancel pending with `409 CONFLICT`. A limit chase that changed while you edited it also answers `409 CONFLICT` on test and live keys alike, and so does a live one whose earlier edit is still pending; send the edit again. ## 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://docs.lean.xyz/markets Sports, crypto window and event markets: fixtures, propositions, outcomes, signed lines and market IDs. Every market has a `kind`: * `sports`: one outcome of one proposition of one fixture. For example: "DEN" in "DEN -3.5" in "Denver Broncos at Los Angeles Chargers". Listed by default. * `time_window`: one outcome of a coin's price over a fixed window. See [Crypto windows](#crypto-windows). * `event`: one side, `yes` or `no`, of a single Polymarket, Polymarket US, Hyperliquid or Kalshi market about anything else, such as an election, a central bank decision or a coin price. See [Event markets](#event-markets). ```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. | | `kind` | `sports`, `time_window` or `event`. The default follows `category`: `time_window` for `crypto` or with `venue=lighter`, `event` for any category but `sports` and `crypto`, else `sports`. | | `category` | `sports`, `crypto`, `politics`, `economy`, `business`, `entertainment`, `science`, `society`, `climate`, `commodities`, `transportation`, `gaming`, `health`, `law` or `uncategorized`. The default is `sports`, or `crypto` with `venue=lighter`. `crypto` lists [crypto windows](#crypto-windows) unless you pass `kind=event`; every other category but `sports` lists [event markets](#event-markets). | | `status` | `open`: at least one venue leg is open for trading. `closed`: no leg is. An event listing takes `status=closed` only with `include_closed=true`. | | `include_closed` | `true` to list event markets that are closed or not tradable as well as open ones. With `status=closed`, lists only those that are not tradable. Event listings only. See [Closed event markets](#closed-event-markets). | | `venue` | `kalshi`, `polymarket`, `polymarket_us`, `hyperliquid` or `lighter`. 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:…`, `lt:…` 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. Sports and crypto window listings only. | | `ends_after`, `ends_before` | ISO 8601 times, matched against an event market's scheduled close. `ends_after` defaults to 48 hours ago; `ends_before` has no default, or 30 days after `ends_after` with `include_closed=true`. Event listings only. | | `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" ``` On a sports listing, `search` finds markets the way the search box in the Lean app does. An [event listing](#event-markets) searches more simply; see [Search in event listings](#search-in-event-listings). * 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`. * A short word is close to many others, so near spellings make it match widely: `ain` finds `Saint` and `Mountain`. Search for whole words. * If search is busy or cannot finish in time, the request returns `503 UPSTREAM_ERROR` with a `Retry-After` header rather than a partial list. Wait that many seconds and try again, or narrow a long start window. ### Search in event listings * Every word must match a whole word, in any letter case, in the venue market's title, its event's title or its outcome names. The last word can be the start of a word, so `rain` finds `Rain` and `Rainfall` but not `Ukraine`. Add more words to narrow the list. * No team nicknames, short forms or near spellings are tried. * Results keep the event listing order, soonest close first. Pass `next_cursor` back as `cursor` with the same `search` and other filters to read the next page. * The text must be 1 to 100 characters once spaces at either end are removed, or the request returns `400 VALIDATION_ERROR`. * An event listing that cannot finish in time, with or without `search`, returns `503 UPSTREAM_ERROR` with a `Retry-After` header. Wait that many seconds and try again, or narrow it with `category`, `venue` or `ends_before`. ## A market ```json theme={"dark"} { "kind": "sports", "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, "resolution": { "source": null, "rules": "", "end_date": null, "url": null, "result": null }, "fees": { "formula": "notional_on_exit", "taker_rate": "0.0007", "maker_rate": "0.0004", "exponent": null } } ], "equivalence": "single_venue" } ``` `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 the part of the game the proposition covers. `game` is the full game, overtime included. * 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. * `result`: once the leg is `resolved`, `won` when the venue paid this outcome, `lost` when it did not, or `void` when the venue voided the market. It is `null` on any other leg. * `rules`: the venue's rules text, verbatim, with any secondary rules after a blank line. When the venue repeats its main rules as the secondary rules, the text appears once. * `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, Polymarket US and Lighter, 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`. ## Crypto windows A crypto market is one outcome of a coin's price over a fixed window. Lean lists Lighter's BTC and ETH windows, each 15 minutes long. Every window has two markets: `up` pays when the price at the window end is at or above the price at its start, as the venue's rules define them, and `down` pays when it is below. ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets?category=crypto&limit=50" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ```json theme={"dark"} { "kind": "time_window", "id": "mkt_…", "title": "BTC up or down, 01:00 to 01:15 UTC: Up", "outcome": "up", "line": null, "window": { "key": "btc:15m:20261117-0100", "category": "crypto", "underlying": "BTC", "duration_minutes": 15, "proposition": "up_down", "starts_at": "2026-11-17T01:00:00.000Z", "ends_at": "2026-11-17T01:15:00.000Z", "title": "BTC up or down, 01:00 to 01:15 UTC" }, "legs": [ { "venue": "lighter", "ticker": "lt:123", "side": "yes", "status": "open", "tradable": true } ] } ``` * `kind` is `time_window` for a crypto window. Check it before you read `fixture` and `group`, which only sports markets have. * `window.key` names the coin, the window length and its start in UTC. Both markets of a window share it. * The Up and Down markets of a window share one Lighter leg `ticker`: Up is its `yes` side and Down its `no` side. * A crypto listing takes `starts_after`, `starts_before`, `status`, `venue`, `limit` and `cursor`. `sport`, `league`, `fixture`, `group` and `search` are refused with `400 VALIDATION_ERROR`. * Books, prices, trades, candles and the `book` stream channel work on crypto markets as on sports markets. * [Previews](/preview) and [orders](/orders) take a crypto market's ID. Its orders expire with the window, so they take `gtd` or `ioc` only and cannot be amended. See [Lighter](/venues#lighter) for the full rules. Quotes, routed orders, stop losses and limit chases do not take crypto windows. ## Event markets An event market is one side of a single Polymarket, Polymarket US, Hyperliquid or Kalshi market that no sports fixture lists: an election, a central bank decision, a coin's price on a date, and so on. Each venue market is two event markets, its `yes` side and its `no` side. Lean lists the ones that are open and take orders, soonest scheduled close first. A venue can keep a market trading after its scheduled close, such as a daily weather market that waits for the day's reading, so a listing reaches back 48 hours unless you pass `ends_after`. Kalshi multivariate (parlay) markets, whose tickers start with `KXMVE`, are not listed. ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets?category=politics&limit=50" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ```json theme={"dark"} { "kind": "event", "id": "mkt_…", "title": "Will the Fed cut rates in December? Yes", "outcome": "yes", "line": null, "event": { "key": "", "title": "Fed decision in December", "category": "economy", "ends_at": "2026-12-10T19:00:00.000Z" }, "legs": [ { "venue": "polymarket", "ticker": "pm:0x…", "side": "yes", "status": "open", "tradable": true, "resolution": { "source": null, "rules": "", "end_date": "2026-12-10T19:00:00.000Z", "url": "https://polymarket.com/event/…", "result": null }, "fees": { "formula": "price_curve", "taker_rate": "0.04", "maker_rate": "0", "exponent": 1 } } ], "equivalence": "single_venue" } ``` * An event market has exactly one leg, on the venue that lists it, so `equivalence` is always `single_venue`. It has no `fixture` or `group`, and `line` is `null`. * `outcome` is the venue side the market pays on, `yes` or `no`. `title` reads the venue's question and that side's label. When the venue names one outcome of a larger event only by its range or name, such as a Kalshi or Polymarket US daily temperature market, `title` starts with the event title, so it reads `Highest temperature in Miami on Nov 24, 2026? 77° to 78°: Yes`. * `event.key` and `event.title` name the venue event the market belongs to; the markets of one venue event share them. `event.category` is `crypto` for an event about a coin's price: one Polymarket or Polymarket US tags `crypto-prices`, or both `crypto` and `hit-price`, and a Hyperliquid price outcome on a coin Hyperliquid lists itself (not a HIP-3 asset such as `xyz:GOLD`). Any other event takes Lean's category for it; an event Lean has not categorized takes its Kalshi category: the one Kalshi files a Kalshi event under, else the Kalshi category Lean tags an event of another venue with. It is `uncategorized` when neither names one of the listed categories. `event.ends_at` is the venue market's scheduled close, which is in the past for a market the venue still trades after it. * Pass a `category` other than `sports` or `crypto`, or `kind=event`, to list event markets. Event coin-price markets are `category=crypto`, so list them with `kind=event&category=crypto`; `category=crypto` alone lists [crypto windows](#crypto-windows), which only Lighter has, so `category=crypto` with any other `venue` returns an empty page unless you pass `kind=event`. * An event listing takes `category`, `venue` (`polymarket`, `polymarket_us`, `hyperliquid` or `kalshi`), `search`, `ends_after`, `ends_before`, `include_closed`, `limit` and `cursor`. `sport`, `league`, `fixture`, `group`, `starts_after` and `starts_before` are refused with `400 VALIDATION_ERROR`, and so is `status=closed` without `include_closed=true`. [`search`](#search-in-event-listings) matches whole words of titles and outcome names. * An event listing's `next_cursor` works only with the `category`, `venue`, `search`, `ends_after`, `ends_before` and `include_closed` that listed it. Sent with other values, it is refused with `400 VALIDATION_ERROR`. * `GET /v1/markets/{id}`, books, prices, quotes, trades and candles work on event markets as on sports markets. An event market's ID resolves after it closes, so its orders, fills and positions keep naming it. * On the [stream](/streaming), subscribe to an event market's book with a `book` channel naming its `mkt_…` ID, and to its trades and status changes with `trades` and `market_lifecycle` channels naming its leg `ticker`. The stream has no quotes or fills channel; each `orders` frame carries the order's fills. * Event markets trade through the normal order API, on the one venue that lists them: [previews](/preview), [orders](/orders), amends, cancels, stop losses and limit chases all take an event market's ID, with the same order types as a sports market. `game_start` is refused, because an event market has no start. * Sports markets keep smart order routing. An event market lists on one venue, so a routed order on it is refused with `422 VALIDATION_ERROR`, reason `ROUTE_NOT_EXECUTABLE`; send a venue order instead. * Both sides of a Polymarket or Hyperliquid event market merge with `POST /v1/positions/merge`. Kalshi and Polymarket US have no merge, so `venue` there takes only `polymarket` or `hyperliquid`. ### Closed event markets An event listing holds only open, tradable markets unless you pass `include_closed=true`. With it, the listing also holds markets that closed, are resolving or resolved, or are not tradable yet. Add `status=closed` to list only the markets that are not tradable. ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/markets?category=climate&include_closed=true&status=closed&ends_after=2026-11-20T00:00:00Z" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` * The window of scheduled closes must start no more than 30 days ago and span at most 30 days. `ends_after` defaults to 48 hours ago and `ends_before` to 30 days after `ends_after`. A wider or older window is refused with `400 VALIDATION_ERROR`. * `status=open` with `include_closed=true` is refused, and so is `include_closed` on a sports or crypto window listing, or with `symbol`. To follow resolutions as they happen, [List recently resolved markets](/api-reference/markets/list-resolved-markets) lists Kalshi and Polymarket events newest first. ## 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 the nearest \$0.00001. | | `notional_on_exit` | Hyperliquid | A buy pays nothing. A sell pays `quantity × price × rate`. A winning share held to settlement pays `rate` times its 1 USD payout. Each fill's fee is rounded to the nearest \$0.00001. | `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. | A Kalshi or `pmus:` ticker works only when that listing pays a single outcome. Most Kalshi and Polymarket US game listings pay both teams, so name those markets by market ID. To find the market ID from a 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, and so does a Lighter `lt:` ticker; send the token ID, the book coin or the market ID instead. Most event market tickers name both the `yes` and the `no` market, so look them up with `GET /v1/markets?symbol=`, which lists every market a symbol names. 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. | | `quoted_at` | When the quote was priced. | | `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. `limit` sets how many trades a page holds: 50 by default, at most 100. 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`. So does a range that starts before 1970 or runs past early 2106, with `start and end are outside the supported time range`. 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, Lighter | 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://docs.lean.xyz/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`, or a venue symbol for the market. | | `action` | `buy` or `sell`. | | `quantity` | Shares, as a decimal string in steps of 0.01. Hyperliquid takes whole shares only. A sell of your whole position is rounded down to the step rather than refused. See [Quantity steps](#quantity-steps). Send exactly one of `quantity` or `notional`. | | `notional` | Dollars to spend, in place of `quantity`, with at most two decimals. Only for an `ioc` or `fok` buy. See [Buying a dollar amount](#buying-a-dollar-amount). | | `type` | `limit` or `market`. The default is `limit`. See [Market orders](#market-orders). | | `limit_price` | The worst price per share you accept. Required with `quantity` on a `limit` order. With `notional` or on a `market` order it is optional: a buy defaults to `0.99` and a sell to `0.01`. A `market` order is placed 1 cent past the worst price its quantity reaches. | | `time_in_force` | `gtc` rests until filled or canceled. `ioc` fills what it can at once and cancels the rest. `fok` fills in full at once or not at all. `gtd` rests until `expires_at`. The default is `gtc`. A crypto market takes `gtd` or `ioc` only, so send one of them there. See [Lighter](/venues#lighter). Polymarket takes `ioc` and `fok` buys by dollar amount only, so send `notional` for an immediate buy that should fill there. | | `expires_at` | Required with `gtd` and refused without it. When the order expires, as an ISO 8601 time, or `game_start` to expire it when the market's game starts. A crypto market takes an ISO 8601 time only. See [Fill or kill and expiring orders](#fill-or-kill-and-expiring-orders). | | `venues` | Optional. Only these venues may fill or pay for the order, such as `["polymarket"]`. Leave it out to use every venue the account allows. See [Choosing venues](#choosing-venues). | | `best_price` | Optional, `false` by default. With `true`, a buy pays from the other venue whenever that costs less in all than buying where the account's cash is. See [Best price across venues](#best-price-across-venues). | | `max_slippage_bps` | Optional. How far each venue order may trade from that venue's best price, in basis points, from `0` to `10000`. Leave it out to use the account's `max_slippage_bps`, if it sets one. See [Slippage](#slippage). | | `all_or_none` | Optional, `false` by default. With `true`, the order is placed only if the books can fill the whole quantity. Only with `time_in_force` `ioc` or `fok`. See [All or none](#all-or-none). | | `post_only` | Optional, `false` by default. With `true`, the order only rests on the book and never takes. See [Post only orders](#post-only-orders). | Send the body as JSON with `Content-Type: application/json`, here and for `POST /v1/orders/preview`. A body sent without that header is refused with `400 VALIDATION_ERROR`. The response is the order, plus `route`. Here the account had no cash on Polymarket, so Lean paid with its cash on Hyperliquid and bought on Polymarket: ```json theme={"dark"} { "success": true, "data": { "id": "3f6c2a8e-91d4-4b7a-8c25-0e4d7b19a6f3", "client_order_id": "bot-2026-10-29-0001", "market_id": "mkt_...", "title": "Denver Broncos at Los Angeles Chargers: Moneyline, Denver Broncos", "outcome": "DEN", "venue": "polymarket", "ticker": "", "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, Hyperliquid and Lighter. An order on a market with a time window, such as a short crypto price market, goes whole to Lighter and is never split. Test orders are simulated and never reach a venue. `title` and `outcome` name the order's market as `GET /v1/markets` does. They are `null` for a market whose fixture started more than 7 days ago, and for a moment after an API restart. `legs` has one entry per venue order, with its `venue`, `ticker`, `side`, `quantity`, `filled_quantity`, `avg_fill_price`, `status` and `status_reason`. When the order went to one venue, the order's own `venue`, `ticker` and `side` name it. When it was split, they are `null`; read `legs` instead. `status`, `filled_quantity` and `avg_fill_price` on the order always cover every leg: `avg_fill_price` is the price weighted by size across the legs that filled, before fees, and `null` until every filled leg has a price. Kalshi, Polymarket and Hyperliquid report a leg's price with its fill. Polymarket US and Lighter report none, so Lean prices those legs from their fills once it has recorded every one of them. `remaining_quantity` is the shares still working on the venues, the unfilled size of each live leg, and `0` once the order is final. `notional_usd` is the order at its own limit, the amount checked against your key's limits. A sell counts at the limits of its `legs`, the least it sells for, and toward the rolling day, but only takes risk off, so no notional limit refuses it: a close works however much the day has traded. `filled_notional_usd` is what the filled shares traded for across every leg, `0` before any fill, and `null` until every filled leg has a price, as with `avg_fill_price`. A sell at `0.01`, as a close without a `limit_price` places, sells into the bids, down to the slippage bound below the best bid when one is set. Its `limit_price` shows the lowest limit among its `legs`, the price the venue orders are protected by, rather than `0.01`. [Preview](/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`. `venues` in [Get account config](/api-reference/account/retrieve-account-config) reads each venue `ready` when an order can be placed there, `not_configured` until its key is connected, or `unavailable` when the connected key can't trade right now. Keys are connected in the Lean app only. * Polymarket US reads its book from a live copy that starts on the first read of a market, and that read waits up to a second for it. If it is still not ready, a quote, preview or order that needs that book is refused with `503 UPSTREAM_ERROR`, and a book or price read lists `polymarket_us` in `unavailable`. It is safe to retry after a moment. * Cash can't move to or from these venues through Lean. A buy there is paid with the cash already on that venue. ## Post only orders Set `post_only: true` to make sure an order adds liquidity and never trades against a resting order when it arrives. A post only order: * needs `time_in_force` `gtc` and cannot use `best_price`. Any other combination is refused with `400 VALIDATION_ERROR`. On a crypto market it needs `gtd` instead, and rests on Lighter. * is placed on Kalshi, Polymarket US and Hyperliquid, since Polymarket cannot rest a post only order. On a market with none of those listings, or with `venues` that leave all three out, it is refused with `400 VALIDATION_ERROR`. * is refused with `422 VALIDATION_ERROR` and `details.reason: "POST_ONLY_WOULD_CROSS"` when the books, as Lean last read them, would fill any of it at once. The `client_order_id` is not used up, so you can send it again at a price further from the other side of the book. The books can move between Lean's read and the order reaching the venue. If the order would trade by then, the venue refuses it instead of filling it, and the order ends `rejected` with no fills. [Preview](/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 what is left expires and the order reads `expired`. Any shares that filled before then stay filled. Kalshi, Polymarket, Polymarket US and Lighter expire the order on the venue. Hyperliquid has no order expiry, so Lean places the order there as `gtc` and cancels what is left at `expires_at`, usually within a few seconds. `expires_at` must be at least three minutes and at most thirty days away. On a crypto market it must be at least 6 minutes away and at or before the window end, and the order rests on Lighter. See [Lighter](/venues#lighter). To expire an order when its game starts, send `expires_at` `game_start` in place of a time. Lean sets the expiry to the market's `fixture.starts_at`, and the order and its preview show that time. Once the game has started, or when it starts less than three minutes or more than thirty days away, `game_start` is refused with `400 VALIDATION_ERROR`. Hyperliquid has no fill or kill, and Polymarket US can fill part of a fill or kill order and expire the rest. So: * a `fok` order is placed whole on one venue: Polymarket, else Kalshi. Fill or kill holds only within one venue's book. * on a market with neither listing, or with `venues` that leave both out, a `fok` order is refused with `400 VALIDATION_ERROR`. On a market listed only on Polymarket US, send `ioc` instead. * Polymarket takes a `fok` buy by `notional` only, so a `fok` buy sized with `quantity` goes to Kalshi. Without a Kalshi listing, it is refused with `400 VALIDATION_ERROR`. * `expires_at` without `gtd`, `gtd` without `expires_at`, or an expiry outside the window is refused with `400 VALIDATION_ERROR`. The order and its preview show `expires_at`, and `null` for any order without one. ## Choosing venues By default an order may use every venue the trading account allows. To keep it on some of them, list them in `venues`: * With one venue, the order is placed only there. If that venue can't fill or pay for it, the order is refused; Lean does not send it elsewhere. * `venues` can only narrow the account's venues. Naming a venue the account doesn't allow refuses the order with `422 VALIDATION_ERROR` and `details.reason: "VENUE_NOT_ALLOWED"`, even beside one it allows. `details.allowed_venues` lists the venues the account allows. * Paying from the other venue also stays inside `venues`. With `["polymarket"]`, Lean never uses cash on Hyperliquid for the order. * List each venue once. An empty list is refused with `400 VALIDATION_ERROR`. * A retry with the same `client_order_id` must name the same venues, in any order. Other venues make it a different body, which returns `409 CONFLICT`. ## Paying from the other venue Each venue keeps its own cash. When a buy can't be paid for on the venues with a book for it, but the account holds cash on the other venue, Lean moves that cash and buys on the venue with the book, in the same call. This works between Polymarket and Hyperliquid only; a buy on Kalshi or Polymarket US is paid with the cash already there. The response names both venues in `route`: | Field | Meaning | | - | - | | `route.funding_venue` | The venue whose cash paid for the order. | | `route.execution_venue` | The venue the order was bought on. | | `route.notional_usd` | The most the route's payment can cost: the buy at its limit, its fees and `route.costs`. It is the order's `notional_usd`, and the amount checked against your key's limits. | | `route.costs.rebalance_fee_usd` | The 20 bps fee on the cash Lean moves between venues. | | `route.costs.gas_usd` | The network gas the route pays. | | `route.costs.activation_fee_usd` | The \$1 Hyperliquid charges the first time funds reach an account it has not activated, when the route pays into one. Otherwise `0`. | | `route.costs.network_cost_usd` | The sum of the three costs above. | Lean pays from the other venue only when all of these hold: * The key has the `route` scope as well as `trade`. A **Read and trade** key made in the Lean app has both, in test and live mode. A key made before one-call routing shipped (see the [changelog](/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. * The market is listed on both venues: the one whose cash pays as well as the one Lean buys on. The `legs` of `GET /v1/markets/{id}` name the venues that list it. If any of them is missing, the order is refused as before: `422 VALIDATION_ERROR` with `details.reason: "INSUFFICIENT_FUNDS"`. * A live routed order can read `pending` while Lean moves the cash. Read it back with `GET /v1/orders/{id}` until it is final. * With a test key, the same call routes between the simulated balances. No real funds move. See [Test mode](/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. ## Quantity steps `quantity` moves in steps of `0.01`, and Hyperliquid takes whole shares only. A quantity that no venue which could place the order can take is refused with `400 VALIDATION_ERROR`: "No venue can accept this quantity". A buy of `5.155` is refused this way, and so is a buy of `30.5` that only Hyperliquid could place. A sell of your whole position is the one exception. When `quantity` is more than the venues can sell on their steps, but no more than you hold, or your holding rounded to `0.01`, Lean sells the holding rounded down to the step instead of refusing the order. On Hyperliquid that is whole shares. The order's `quantity` then reads the shares it sells, not the quantity you sent, and the part below the step stays on the venue. For example, with `5.155173` shares held on Polymarket, a sell of `5.1551` is placed for `5.15`, the order reads `"quantity": "5.15"`, and `0.005173` shares stay held. That remainder is smaller than one step, so no order can sell it. ## Idempotency `client_order_id` makes placement safe to retry: * The same ID with the same body returns the original order. Nothing new is placed. * The same ID with a different body returns `409 CONFLICT`. * An ID is used once, even if that order was rejected. * [Close positions](/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` | | A `fok` order that could not fill in full | `canceled`, with `filled_quantity` `0` | `null` | | The venue refused the order | `rejected` | `VENUE_REJECTED` or the venue's own code | | The venue did not confirm the order | `unconfirmed` | `SUBMISSION_UNKNOWN` | An error status means Lean placed nothing, with these exceptions: * `422 VALIDATION_ERROR`: a key limit or a check before any venue refused the order. * `503 UPSTREAM_ERROR`: a venue failed before anything was placed. When the response carries `Retry-After`, a venue timed out or dropped the connection, so the order may or may not have reached it. Look it up by `client_order_id` before you send it again. * Any error with `details.order_id`: Lean recorded the order before the failure, for example a buy that pays from the other venue whose payment was refused. Read it back with `GET /v1/orders/{id}` before you send it again. ### When the venue does not confirm An `unconfirmed` order or leg reads: "The venue did not confirm this order. Read it back by client_order_id; do not resend it." It may or may not be on the venue. Read it with `GET /v1/orders?client_order_id=...` or `GET /v1/orders/{id}`: * If the venue has it working, it reads `open` (or filled) and `status_reason` clears. * If the venue still has no record of it ten minutes after placement, it reads `rejected` with `status_reason.code` `VENUE_UNKNOWN`. Only then is it safe to place it again, with a new `client_order_id`. ## Track and cancel ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/orders/$ORDER_ID" -H "Authorization: Bearer $LEAN_API_KEY" curl -sS "$LEAN_API_URL/v1/orders?limit=50" -H "Authorization: Bearer $LEAN_API_KEY" curl -sS -X POST "$LEAN_API_URL/v1/orders/$ORDER_ID/cancel" -H "Authorization: Bearer $LEAN_API_KEY" ``` * `GET /v1/orders/{id}` refreshes the order from its venue. A test order is never sent to a venue; reading it fills what rests against the public books. See [Test mode](/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). * `status` takes one status, so `status=open` leaves out orders that are `pending`, `partially_filled` or `cancel_requested`. To list every working order, ask once for each of those statuses, or list without `status` and keep the ones that have not finished. * `created_after` and `created_before` narrow the list to orders Lean recorded at or after, and before, a time. Send UTC ISO 8601 times ending in `Z`, such as `2026-11-10T12:00:00Z`. A time with an offset such as `+00:00`, or a date alone, returns `400 VALIDATION_ERROR`. * `client_order_id` matches the orders any key of the account placed with that ID, and combines with the other filters like any of them. * The list also shows orders placed in the Lean app that are still open, for a live key. They have no `client_order_id`, an empty `legs` list, and their market fields can be `null`. You can see them but not read, cancel or amend them through the API: those calls return `404 NOT_FOUND` with `details.reason` `APP_ORDER_NOT_ADDRESSABLE`. Orders placed by stop losses, limit chases and conditional sells are not listed here. * Canceling a finished order, one the venue never confirmed, or a routed order whose payment is already under way returns `409 CONFLICT`. * A cancel stops every leg that is still working. Most stop at once. A leg that can't be stopped at once reads `cancel_requested`, with a `cancel_requested_at` time, until its venue confirms it, and the order reads `cancel_requested` too. Read the order back until it is `canceled`, or `filled` if a fill beat the cancel. To cancel several orders in one call, name them by `order_ids`, `client_order_ids` or both, up to 50 in all: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/orders/cancel-batch" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"order_ids": ["'"$ORDER_ID"'"], "client_order_ids": ["bot-0002"]}' ``` * Each order is canceled the same way a single cancel would cancel it, and one failure never stops the rest. The call answers `200` with one row in `results` for each name you sent, in the order you sent them: `order_ids` first, then `client_order_ids`. * A row's `status` is `canceled`, `finished` for an order that had already finished (its `order` shows how), or `failed` with an `error`. A `canceled` row means every leg's cancel was accepted. Its `order` can still read `cancel_requested` until each venue confirms, as with a single cancel. An order ID that matches no order of the account in this key's mode, or a client order ID that matches no order this key placed, fails with `NOT_FOUND`. A row that failed for another reason carries the order as it stands, so you can see which legs are still open. * An order named twice, by its id and by its `client_order_id`, is canceled once, and both rows show that one result. The same id listed twice in `order_ids`, or in `client_order_ids`, returns `400 VALIDATION_ERROR` and cancels nothing. * Batch cancels draw on the same rate limit as other cancels and work while trading is paused. `POST /v1/orders/cancel-after` sets a safety timer. Unless you call it again in time, every open order of the trading account in the key's mode is canceled once `timeout_seconds` runs out. `timeout_seconds` is `0`, which disarms the timer, or from `5` to `86400`; any other value returns `400 VALIDATION_ERROR`. Each call restarts the timer, and it fires once. See [Set a cancel timer](/api-reference/orders/set-cancel-after). ## Amend an order Change the price, the size or both of a resting order with `PATCH /v1/orders/{id}`: ```bash theme={"dark"} curl -sS -X PATCH "$LEAN_API_URL/v1/orders/$ORDER_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"limit_price": "0.41", "quantity": "30"}' ``` | Field | Meaning | | - | - | | `limit_price` | Optional. The new worst price per share, in dollars. Omit it to keep the current price. | | `quantity` | Optional. The new total size in shares, counting what already filled. Omit it to keep the current size. | | `client_order_id` | Optional. The `client_order_id` of the new order that replaces this one. Omit it and Lean picks one. An [amend in place](#amend-in-place) keeps the order's own. | Send at least one of `limit_price` and `quantity`. Only an `open` or `partially_filled` order with `time_in_force` `gtc` that rests on one venue can be amended. A routed order, an order split across venues, or an `ioc`, `fok` or `gtd` order is refused with `409 CONFLICT` and `details.reason: "ORDER_NOT_AMENDABLE"`. A finished order is refused with `ORDER_NOT_OPEN`. The new size must be more than what already filled. Amends are refused while trading is paused. ### Amend in place A live order on Kalshi or Polymarket US whose size you only lower, at the same price, with the key that placed it, is changed at the venue in place. The answer is `200` with the same order: its ID, `client_order_id` and fills stay, and its `quantity` is the new size. On Kalshi it keeps its place in the queue. The order keeps its own `client_order_id`, so leave it out of such an amend; one this key already used is still refused with `409 CONFLICT`. If the venue order changed while Lean planned the amend, the amend is refused with `409 CONFLICT`; read the order back and try again. ### Cancel and replace Any other amend cancels the order and places a new `gtc` order on the same venue, with the same `post_only`, for the rest of the new size at the new price: a new price, a larger size, an amend from another key, a test order, or an order on Polymarket or Hyperliquid. The answer is `200` with the new order, whose `replaces_order_id` names the old one. The old order reads `canceled`, with `replaced_by_order_id` naming the new one. Each order keeps the fills of its own venue order. The new order is placed as the key that sends the amend places one. Before the old order is canceled, Lean checks the new order as though the old one were already gone: the new price and size against the venue, a `post_only` price that would trade at once (`POST_ONLY_WOULD_CROSS`), the key's limits, the account's allowed venues, the rolling day and the account's cash or shares, with what the old order holds counted as free. Any refusal leaves the order as it was. The replacement waits for the cancel: * The old order can fill until its cancel lands, so Lean places the new order only once the cancel is confirmed with the old order's final fill, and sizes it from what had filled by then. Hyperliquid confirms the cancel within the request. A live cancel on another venue, such as Polymarket, can be confirmed a moment after it is requested, so the first amend can answer `409 CONFLICT` with `details.reason: "REPLACEMENT_PENDING"` and nothing placed. Send the same amend again once the old order reads `canceled`; that amend places the new order. * If the old order filled to the new size or more, nothing is placed and the amend is refused with `ORDER_NOT_OPEN`. * If something changes between that check and the new order, for example another order spends the cash, the new order can still be refused once the old one is canceled. The old order then stays canceled and nothing rests in its place. * An order that was already replaced is refused with `ORDER_REPLACED`, and `details.replaced_by_order_id` names the order to amend instead. After any error, read the order back before you send the amend again. ## Pause trading If your program misbehaves, a key with `trade` can stop new orders at once: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/account/pause" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"scope": "api_key", "reason": "Strategy halted"}' ``` * `scope` is `api_key` to pause this key, or `trading_account` to pause every key of its trading account. `reason` is optional, up to 200 characters. * The pause also stops queued orders that have not reached a venue yet. Reads, cancels and resting orders are unaffected, so cancel resting orders yourself if you want them gone. * The response lists what now pauses this key in `paused.key`, `paused.account` and `paused.global`, each `null` or `{ reason, source, since }`. * A key cannot resume trading. Resume from the Lean dashboard. A pause with `source` `operator` was set by Lean, and only Lean can lift it. While paused, placing an order returns `503 FEATURE_DISABLED` with `details.reason` `TRADING_PAUSED` and `details.scope` `api_key` or `trading_account`. A preview answers with `would_submit: false` and a `TRADING_UNAVAILABLE` warning. ## Reconcile An accepted response is not proof of a fill. To reconcile an order: 1. Read the order with `GET /v1/orders/{id}`. Check `status`, `filled_quantity` and `avg_fill_price`, then each entry in `legs`: its `status`, `filled_quantity`, `avg_fill_price` and `venue_order_id`. 2. Read `GET /v1/positions` and check the position for each leg's `venue`, `ticker` and `side`. Match on those three fields. Each position also names its `market_id`, `title` and `outcome`, so you can match it to the market you ordered. `market_id` is `null` when the API lists no market for the holding, such as a season futures market. Its `title` and `outcome` then come from the venue market, and are `null` only when Lean has no title for it. Closing still works because the close path resolves the market from the ticker. 3. Read `GET /v1/balances` and compare the change on each venue with that leg's `filled_quantity × avg_fill_price` plus the `fee_usd` of its fills in `GET /v1/fills`. For an order with a `route`, the funding venue's change also includes `route.costs.network_cost_usd`. A venue that cannot be read right now is listed in `unavailable`. It is never reported as an empty position or a zero balance. Do not reconcile against a venue listed in `unavailable`. ## Read positions `GET /v1/positions` lists what you hold on each venue. Narrow the list with any of these query parameters: | Parameter | Effect | | - | - | | `venue` | Only holdings on this venue. Lean reads only that venue, so only it can be listed in `unavailable`. | | `market_id` | Only holdings on this market. A market Lean does not know returns an empty list. | | `search` | Only holdings on a market whose title or outcome contains this text. See [Find by text](#find-by-text). | A `venue` the API does not support returns `400 VALIDATION_ERROR`. ```bash theme={"dark"} curl -sS "$LEAN_API_URL/v1/positions?venue=polymarket&search=lakers" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` Each position has `payout_usd`, what the whole holding pays once its market resolves, and `redeemable`. Kalshi, Polymarket US, Hyperliquid and Lighter pay resolved holdings into your balance on their own. A Polymarket holding of a resolved market that pays out stays a token until it is redeemed, and is marked `redeemable: true` until then. A losing holding pays nothing and is never redeemable. `settled` is `true` once the holding's market has resolved. That row's `unrealized_pnl_usd` is its settlement payout minus cost, as the Lean portfolio row shows it, but the account's unrealized PnL in `GET /v1/pnl` leaves it out, as the Lean portfolio totals do. Add up only rows with `settled: false` to match it. [Close positions](/api-reference/account/close-positions) leaves a settled holding out, since it pays out rather than sells. ## Redeem and merge [Redeem positions](/api-reference/account/redeem-positions) pays out every holding marked `redeemable`, or only those on one `market_id`. Shares on the winning side pay 1 each and a void market pays 0.5 a share; shares on the losing side pay nothing and are left as they are. The response lists each holding redeemed with its `payout_usd`, and is empty when nothing was redeemable. A market can be listed more than once on Polymarket. A Polymarket token id or condition id as `market_id` redeems only that listing, and a Lean market id redeems every Polymarket listing of the market. A condition id redeems both sides of its listing, even when its YES and NO belong to two markets. ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/positions/redeem" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"market_id": "'"$MARKET_ID"'"}' ``` [Merge positions](/api-reference/account/merge-positions) turns every pair of one YES share and one NO share you hold on a market back into cash, 1 per pair, without trading. Send the `market_id` and the `venue`, `polymarket` or `hyperliquid`. Kalshi and Polymarket US have no merge. Holding only one side is refused with `422 VALIDATION_ERROR` and `details.reason` `NOTHING_TO_MERGE`. A Polymarket token id or a Hyperliquid book coin as `market_id` merges that one listing. A Lean market id works when the market has one listing on the venue; when it has more, the merge is refused with `400` and you send the token id or book coin of the listing instead. A `market_id` naming a listing on another venue is refused with `400` too. Both need the trade scope, follow the key's trading pause and venue limits, and on a live key need trading enabled for the account in the Lean app. A live redeem or merge is sent to the venue once and reads: | `status` | Meaning | | - | - | | `settled` | The venue paid out. | | `submitted` | The payout is on its way and may still fail. Read positions and balances again shortly. | | `failed` | The venue refused it and paid nothing. `failure_reason` says why. | After a timeout or a `5xx`, read `GET /v1/positions` before you try again: a holding no longer marked `redeemable`, or a pair no longer held, was already paid out or is on its way. ## Read fills `GET /v1/fills` lists your fills, newest first. Each fill names its `order_id` and its `market_id`, with the market's `title` and `outcome`. Either ID is `null` when Lean cannot tie the fill to one, for example a fill from an order placed outside the API on a market the API does not list; `title` and `outcome` are then `null` too. A test order's fill names its order's market, and its `title` and `outcome` are `null` once the market's fixture started more than 7 days ago. Narrow the list with any of these query parameters: | Parameter | Effect | | - | - | | `order_id` | Only fills of this order. | | `market_id` | Only fills on this market. A market Lean does not know returns an empty list. | | `venue` | Only fills on this venue. | | `filled_after` | Only fills at or after this time, as an ISO 8601 timestamp. | | `filled_before` | Only fills before this time, as an ISO 8601 timestamp. | | `search` | Only fills on a market whose title or outcome contains this text. See [Find by text](#find-by-text). | Send times in UTC ending in `Z`, such as `2026-11-10T12:00:00Z`. A time with an offset such as `+00:00`, a date alone, or anything else returns `400 VALIDATION_ERROR`. To read every fill in a window, page with `next_cursor` and keep the same parameters. ## Find by text `GET /v1/positions`, `GET /v1/orders` and `GET /v1/fills` take `search`. It keeps the records on a market whose `title` or `outcome` contains the text, in any letter case. A record on a market the API does not list never matches. * Spaces at either end are ignored. The text must then be 1 to 100 characters, or the request returns `400 VALIDATION_ERROR`. * `search` combines with the other parameters. Each record must match all of them. * Orders and fills page as usual. Pass `next_cursor` back as `cursor` with the same `search` to read the next page. ## Profit and loss `GET /v1/pnl` returns your realized, unrealized and total profit and loss in USD, for the whole account and for each venue. Realized counts what closed and reduced positions made after fees. Unrealized values your open positions at their current price. Pass `venue` or `market_id` to read one venue or one market. A venue that cannot be read right now is listed in `unavailable`, and its unrealized and total are `null`. Its realized amount still counts. A market Lean does not know returns `404 NOT_FOUND`. `GET /v1/pnl/history` returns the same amounts as points over time, each one cumulative as of its `ts`. Choose the spacing with `interval`, `1h` or `1d` (the default), and the range with `start` and `end` as ISO 8601 timestamps. Without them you get the last 30 days. An `end` after now is read as now, and the response's `end` shows the time used, so no point is reported for a time still to come. A range longer than 365 days, or with more than 1000 points at the chosen interval, returns `400 VALIDATION_ERROR`, as does a `start` that is not before the `end` used. A test key replays its simulated fills for realized, with what each holding on a resolved market paid less what it cost, and values its simulated positions at the midpoint of their venue's public book for unrealized. Unrealized and total are `null` while one of those positions has no mark. Its history has realized only, because past marks of test positions aren't kept. See [Test mode](/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. To take an order off the book at kickoff, send it as `gtd` with `expires_at` `game_start`. This works on every venue, Hyperliquid included, where Lean cancels what is left when the game starts. See [Fill or kill and expiring orders](#fill-or-kill-and-expiring-orders). ## Buying a dollar amount An `ioc` or `fok` buy can name the dollars to spend instead of the shares to buy. Send `notional` in place of `quantity`: ```bash theme={"dark"} curl -sS -X POST "$LEAN_API_URL/v1/orders" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "client_order_id": "bot-2026-11-10-0001", "market_id": "'"$MARKET_ID"'", "action": "buy", "notional": "25", "time_in_force": "ioc" }' ``` * Lean walks the venue books from the best ask until the dollars are spent, within your `limit_price` and slippage bound, if set. The order's `limit_price` is the worst price that walk reaches, and its `quantity` is the shares the dollars buy at that price, rounded down to what the venues take. Hyperliquid takes whole shares only. * The order never spends more than `notional` before fees. A better price than the limit spends less, and on Polymarket it can buy a few more shares than `quantity` for the same dollars. * Polymarket spends a buy in whole cents, rounded down. The shares that rounding leaves out are worth less than a cent, so a Polymarket leg that falls short of `quantity` by that little reads `filled`, and `filled_quantity` shows the shares it bought. * `notional_usd`, and the amount checked against your key's limits, is the order's `quantity` at its `limit_price`. It is never more than `notional`. * `limit_price` is optional with `notional`. Without it the walk stops at `0.99`, or at the slippage bound when one is set. * A sell and a `gtc` or `gtd` order are sized with `quantity`. Sending `notional` on one, or sending both `quantity` and `notional`, or neither, is refused with `422 VALIDATION_ERROR`. * A buy sized with `notional` is paid with the cash on the venues it buys on. It doesn't take a [route](#paying-from-the-other-venue). * `POST /v1/orders/preview` and `GET /v1/markets/{id}/quote` take `notional` the same way. ## Limitations * Shares stay on the venue that bought them. A sell is placed only on venues that hold the shares. * `filled_quantity` comes from the venue's answer at placement and from later reads. A resting order that later fills completely reads `filled`. * An `ioc` buy sized with `quantity` is not placed directly on Polymarket. It goes only to the other venues it can use. When Polymarket is the only one, the order and its preview are refused with `400 VALIDATION_ERROR`; send `notional` instead, or send it as `gtc`. A buy [paid from the other venue](#paying-from-the-other-venue) can still fill on Polymarket, and never for more than `quantity`. * Reading a filled order with `GET /v1/orders/{id}` brings its fills into `GET /v1/fills?order_id=`, so read the order first when you need its fills right away. A Polymarket fill whose trade Polygon has not confirmed yet, or a fill of an order you have not read, can still be listed a few seconds after the order reads `filled`. If the list is empty, read it again shortly. * An order has no fee field. Its fees are the `fee_usd` of its fills in `GET /v1/fills`. * A live Hyperliquid buy fill shows `fee_usd` `0`, because a Hyperliquid buy pays its fee when the position closes or settles; a sell pays the market's taker rate. `fee_usd` is `null` when the fee was charged in a token Lean cannot value in dollars. * If the venue still has no record of an unconfirmed order ten minutes after placement, the order is marked `rejected` with `status_reason.code` `VENUE_UNKNOWN`. * An order in `needs_attention` has a leg Lean cannot settle on its own. It stays live until Lean's operators resolve it. Do not place it again; read it back later. # Preview Source: https://docs.lean.xyz/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", "type": "limit", "time_in_force": "ioc", "expires_at": null, "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", "limit_price": "0.50", "notional_usd": "2.5", "expected_fill_quantity": "5", "expected_average_price": "0.47", "expected_fee_usd": "0", "expected_resting_fee_usd": "0", "reward": null } ] }, "would_submit": true, "route_plan": { "expected_total_usd": "2.35", "max_total_usd": "2.5", "legs": [ { "venue": "hyperliquid", "ticker": "", "side": "yes", "quantity": "5", "average_price": "0.47", "limit_price": "0.50", "fee_usd": "0", "executable": true } ] }, "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`, `limit_price`, `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.legs[].reward` | Whether what the leg rests would earn the venue's liquidity rewards. `null` when the venue market has no active reward program. See [Liquidity rewards](#liquidity-rewards). | | `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. | ## Liquidity rewards Polymarket, Kalshi and Polymarket US pay makers whose orders rest near the top of a rewarded market's book. [`GET /v1/rewards/programs`](/api-reference/rewards/list-reward-programs) lists the markets that pay and their rules. For a leg on one of them, `reward` says whether the part a `gtc` or `gtd` order would rest would score, judged against the book as just read with that part added. The book moves, so an order that scores when placed can stop scoring, and the venue decides what it pays. Earnings show in [`GET /v1/rewards/earnings`](/api-reference/rewards/get-reward-earnings). ```json theme={"dark"} "reward": { "eligible": false, "daily_reward_usd": "50", "reasons": [ { "code": "OUTSIDE_MAX_SPREAD", "message": "4.5¢ from the 52.5¢ midpoint; rewards need within 3¢" } ] } ``` | Field | Meaning | | - | - | | `eligible` | `true` when the resting part would score at this price and size. `null` when the book could not be read. | | `daily_reward_usd` | What the market's active programs pay all makers per day. | | `reasons` | Why it would not score; empty when it would. | | `reasons[].code` | Meaning | | - | - | | `NOT_RESTING` | Nothing rests: a `market`, `ioc` or `fok` order, or a limit order expected to fill in full at once. | | `BELOW_MIN_SIZE` | Polymarket: the resting size is below the market's `min_size`. | | `OUTSIDE_MAX_SPREAD` | Polymarket: the price is further from the midpoint than the market's `max_spread`. | | `NO_MIDPOINT` | Polymarket: the book has no bid or no ask to take a midpoint from. | | `NO_LIQUIDITY_PROGRAM` | Kalshi, Polymarket US: the market's programs pay for volume, not resting orders. | | `BOOK_BELOW_TARGET` | Kalshi, Polymarket US: the book does not reach any program's `target_size` (Kalshi needs both sides to). | | `OUTSIDE_TARGET_DEPTH` | Kalshi, Polymarket US: orders at better prices already fill the `target_size`. | | `BOOK_UNAVAILABLE` | The book could not be read. | Polymarket also requires orders on both sides of a market whose midpoint is below 10¢; the preview does not check your other orders. ## 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. ### How fresh a preview is To answer fast, a preview, a preview batch and a [quote](/markets#quotes-and-liquidity) price on books Lean already holds, at most about 2 seconds old, and read the account's funds and sellable shares from a recent read, at most 30 seconds old. An order you place or cancel through Lean clears that read for its venue account at once, but a change made elsewhere, such as an order placed in the venue's own app, can take up to 30 seconds to show. If Kalshi throttles the balance read, a preview answers from the last balance Lean read. `POST /v1/orders` reads every book, balance and holding fresh before it places the order, so it can still refuse an order its preview accepted. # Quickstart Source: https://docs.lean.xyz/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. ## 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://docs.lean.xyz/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`, or the symbol of the market on the venue Lean buys on. | | `quantity` | Shares, as a decimal string in steps of 0.01. | | `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` | Only on the `polymarket_deposit_wallet_batch` scheme: set when the buying wallet first needs a Lean agent approved, so sign it too, and `null` otherwise. Other schemes do not have this field. | 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. The account must have trading enabled in the Lean app, for a test key as for a live one; 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`. | | 400 | `VALIDATION_ERROR` | | `limit_price` is not between 0 and 1 or has more decimals than any venue's price tick, or `quantity` is not in steps of 0.01. | | 403 | `FORBIDDEN` | | The key lacks the `route` scope. | | 403 | `FORBIDDEN` | `ACCOUNT_NOT_DELEGATED` | `delegated` authorization, 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` | On execute: the route changed while it was quoted. Create a new routed order. On create the same case returns `409` with no `details.reason`; send the create again. | | 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, or the market is not listed on both the funding venue and the venue Lean buys on. There is no fallback venue. | | 422 | `VALIDATION_ERROR` | `VENUE_NOT_ALLOWED` | The account does not allow orders on the funding or the buying venue. `details.allowed_venues` lists the ones it allows. | | 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. # Order statuses Source: https://docs.lean.xyz/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://docs.lean.xyz/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 Kalshi, Polymarket, Polymarket US and Hyperliquid. One naming `lighter` is refused with `422` and reason `NO_EXECUTABLE_VENUE`. 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 in UTC ending in `Z`, in the future and at most 30 days ahead. It applies whether or not the sale has started, and 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. `triggered_price` is `null` when the sale started because the market had no bid. | `status` | Final | Meaning | | - | - | - | | `active` | No | Watching the market. | | `triggered` | No | The bid reached the trigger. The sale is starting, or rests on the book with nothing sold yet. | | `executing` | No | Selling into the bids 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, or the market closed or resolved first. | | `expired` | Yes | `expires_at` passed, or the shares were no longer held when the sale started. If they go after part of the sale filled, it ends `filled` instead. | | `failed` | Yes | The venue refused the sale 5 times in a row with nothing sold in between, or Lean could not place it for about 10 minutes. | ## 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. On Hyperliquid it must also fit the venue's size step and be worth at least 1 USD at `trigger_price` minus `slippage_limit`, unless it sells the whole position. * 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. * With a live key, a stop loss is refused with `403 FORBIDDEN` when the account can't trade on the venue: for example, on Kalshi and Polymarket US no API key is connected in the Lean app, or on Polymarket the wallet isn't set up or its approvals need refreshing in the Lean app. * Creating a stop loss is refused with `503 FEATURE_DISABLED` while trading is paused, or, for a live key, 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. Kalshi and Polymarket US stop losses belong to you rather than to a trading account, so a live key sees all of yours on those venues. A live key's list also shows the sales that conditional sells run for their followers and `stop` leaders. They can't be changed or canceled here, which is refused with `409 CONFLICT`: cancel the conditional sell instead. `GET /v1/stop-losses/{id}` reads one. A stop loss's sale is not an order you placed, so it sends no `order` frame on the stream, and its fills are listed in `GET /v1/fills` with `order_id` set to `null`. Its `filled_quantity` and `avg_fill_price` show what it has sold. 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. ## Change a stop loss Change the trigger, size or slippage limit of a stop loss with `PATCH /v1/stop-losses/{id}`. It keeps its id, and fields you leave out keep their values: ```bash theme={"dark"} curl -sS -X PATCH "$LEAN_API_URL/v1/stop-losses/$STOP_LOSS_ID" \ -H "Authorization: Bearer $LEAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "trigger_price": "0.38", "quantity": "30" }' ``` | Field | Meaning | | - | - | | `trigger_price` | Optional. The new best bid that starts the sale. A stop loss must stay below the current best bid and a take profit above it. | | `quantity` | Optional. The new number of shares to sell. With the account's other stop losses on these shares, it is at most what the account holds. | | `slippage_limit` | Optional. How far below `trigger_price` the sale may fill, as at creation. | The new values are checked as they are when you create one. The answer is `200` with the stop loss as edited. A live stop loss moves to the new values a moment later. Only a stop loss still watching the market can change: one that has started selling or ended is refused with `400 VALIDATION_ERROR`, and one with a cancel pending with `409 CONFLICT`. A stop loss that changed while you edited it also answers `409 CONFLICT` on test and live keys alike; send the edit again. A larger sale counts the added amount toward your rolling day, which never refuses a sale. ## 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://docs.lean.xyz/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" }, { "channel": "balances" }, { "channel": "book", "market_id": "mkt_..." } ] } ``` Send `{"op":"unsubscribe","channels":[...]}` to stop a channel; the reply is an `unsubscribed` frame. A connection holds at most 1000 channels; a frame must stay under 16 KB, so following hundreds of books takes several `subscribe` frames. 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. The `trades` and `market_lifecycle` channels carry venue data, the same for live and test keys. ## 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":"...","snapshot":true,"sequence":1,"book":{...}}`, then `{"type":"book_delta","market_id":"...","sequence":2,"prev_sequence":1,"delta":{...}}` | The combined order book of one market, then what changes in it. | | `trades` | `{"type":"trades","ticker":"...","trades":[...],"timestamp":...}` | Trades on one venue listing as they happen. | | `market_lifecycle` | `{"type":"market_lifecycle","event":"status_change",...}` | Status and tick size changes of one venue listing. | ### 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 drops a frame while the connection stays open. If Lean cannot be sure every frame reached you, it closes the connection with `1013` and `UPSTREAM_ERROR`, so reconnect and call `GET /v1/orders` again. A frame carries the order as it is when Lean sends it, so an order that fills as it is placed, such as an `ioc` order, can arrive first as `filled` with no `pending` frame before it. Only orders placed with `POST /v1/orders` send `order` frames. The sales that stop losses, limit chases and conditional sells make are not API orders: follow them by reading that object, and through the `positions` and `balances` frames. Their fills are listed in `GET /v1/fills` with `order_id` set to `null`. ### 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": "", "snapshot": true, "sequence": 1841, "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 was read but holds no orders appears in `venues` with no levels. A venue whose book could not be read appears in `unavailable` instead, once per venue. * After the whole book, the channel sends `book_delta` frames with only the levels that changed. Each delta holds the changes since the book Lean last published, so a busy book can get several deltas within a few milliseconds or one delta covering many changes. A book with no change gets a delta with no levels about once a second. Where Lean has no live venue data it polls the venue about once a second. * In a delta, each level replaces the level at its price on its side, and a `quantity` of `"0"` removes it. A level that falls out of the 20 shown is removed and one that comes into them is added. Venue books are matched by `venue`, `ticker` and `side`, and the totals and `as_of` are always the new book's. Keep bids highest price first and asks lowest price first. * Apply a delta only when its `prev_sequence` equals the `sequence` of the book you hold, then hold its `sequence`. When a delta cannot follow, because your session read too slowly or the market's venues changed, Lean sends a whole `book` frame instead. If a delta still does not follow, drop the book, send `unsubscribe` for the channel, then `subscribe` again: the new subscription opens with a whole `book` frame. The official SDKs apply deltas for you and always hand you the whole book. See [WebSocket](/api-reference/streaming/websocket#book). * `as_of` is when Lean built the book, not when you received it. * The first frame after you subscribe has `snapshot` set to `true`. It is the newest book Lean already holds, so on a quiet book its `as_of` can be up to about a second before you subscribed. The book is still current: Lean replaces it as soon as a venue book changes. Every later `book` frame has `snapshot` set to `false`; `book_delta` frames carry no `snapshot` field. Both are built as they are sent. To measure delay, skip the snapshot frame. Subscribing again to a channel you already have changes nothing, so it sends no new snapshot; unsubscribe first to get one. * Each `book` frame replaces the book you hold. * When a book channel will send no more books, it sends one `book_ended` frame and the session stops following it. `reason` is `unknown_market` for a market that does not exist or a symbol that names more than one market, and `market_closed` once every venue listing of the market is closed or resolved. See [WebSocket](/api-reference/streaming/websocket#book). The book channel and [`GET /v1/markets/{id}/book`](/api-reference/markets/retrieve-market-book) agree on which venues make up a market, how levels are merged and what counts as empty or unavailable. They read venue books differently, so these differences are expected: * The channel builds every venue's book from the venue data Lean ingests. The REST endpoint reads that data for `polymarket_us` and `lighter`, but reads `polymarket`, `kalshi` and `hyperliquid` books from the venue when called. For those three, the two can differ for the moment a venue book change takes to reach Lean. * The first frame waits up to 3 seconds for every venue's book. A venue whose book has not arrived by then appears in `unavailable` and fills in on a later frame. A Polymarket market Lean has just started following takes a few seconds longer. * A Polymarket market that is not open and tradable in Lean's catalog is not ingested, so the channel lists Polymarket in `unavailable` even where the REST endpoint can still read its book. A session that reads positions, balances or books too slowly skips ahead to the newest state. ### Trades and market lifecycle These channels follow one venue listing, named by its leg `ticker` as a market's `legs[].ticker` shows it, such as a Kalshi market ticker or a `pm:…` ticker: ```json theme={"dark"} { "op": "subscribe", "channels": [ { "channel": "trades", "ticker": "" }, { "channel": "market_lifecycle", "ticker": "" } ] } ``` * `trades` sends the trades that happen after you subscribe, a batch per frame, with the venue's price, side, maker and taker details. It sends no history; read [recent trades](/markets#recent-trades) for that. * `market_lifecycle` sends a `status_change` frame when the listing's status changes, with `result` once it resolves, and a `tick_size_change` frame when its price step changes. The first frame can repeat the current state. * Only the ticker's shape is checked. A ticker no venue lists is accepted and sends nothing, and a Polymarket condition ID, token ID or Hyperliquid coin is not resolved to a ticker as a `book` channel resolves it. * These channels never skip a frame. A session that reads them too slowly is closed with `1013` and `RATE_LIMITED`; reconnect, subscribe again and read the current state over REST. See [WebSocket](/api-reference/streaming/websocket#trades) for every field. ## 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, Lean accepts only an `auth` frame. Any other frame gets one error frame and then the socket closes. A `ping`, `subscribe` or `unsubscribe` sent first gets `UNAUTHORIZED` with `Authenticate before any other frame`. Text that is not JSON, or not a frame shown here, gets `VALIDATION_ERROR` with `Expected an auth frame`. Both close with `1008`. See [WebSocket errors](/api-reference/streaming/websocket#errors) for every message. 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 `ping`, `subscribe` or `unsubscribe` came before `auth`; or the key was revoked or expired. | | `1008` | `VALIDATION_ERROR` | Before authentication, a frame was not JSON or not a frame shown here. | | `1003` | `VALIDATION_ERROR` | A binary frame was sent, before or after authentication. | | `1013` | `RATE_LIMITED` | In reply to `auth`: the key already has 500 open streams. | | `1013` | `RATE_LIMITED` | The session read order states, trades or lifecycle events too slowly to keep up. | | `1013` | `UPSTREAM_ERROR` | In reply to `auth`: 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. | | `1001` | none | Nothing arrived from the client for 45 seconds, not even a pong to Lean's pings. The close reason is `no frames from client`. | Lean sends a WebSocket ping every 15 seconds, and any frame from the client counts, a pong included. Most WebSocket libraries answer pings on their own; sending `{"op":"ping"}` every 10 seconds, as [Notice a lost connection](#notice-a-lost-connection) suggests, also keeps the connection open. 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 `subscribe` frames naming every channel you want, splitting the list so each frame stays under 16 KB. 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, and its deltas follow from there. * **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 `1001` | Nothing came from your client for 45 seconds. Reconnect with a new ticket after the delay, and answer pings or send `{"op":"ping"}`. | | Close `1013` with `RATE_LIMITED` | Reconnect with a new ticket after the delay, and read frames faster. If it came in reply to `auth`, close another stream on the key first. | | 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://docs.lean.xyz/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 Lighter), and test orders draw only on those. `GET /v1/balances` does not list Lighter. 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, paying the market's maker fee, from what the public book then shows at or better than that limit. A `gtd` order read after its `expires_at` reads `expired`. * In `GET /v1/fills`, what a test order filled when you placed it is one `taker` fill per venue, at the order's creation time. Each later fill of a resting remainder is its own `maker` fill, at the time it filled, with the maker fee it paid. `filled_after` and `filled_before` apply to each fill's own time. * 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. What a test position cost includes the fees its buys paid, as a live position's does, so those fees count as realized profit and loss only once the shares are sold or settle. * `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, plus what each test holding on a resolved market paid less what it cost. * A test holding settles when its market resolves, as a live one does. On every venue but Polymarket, what it pays is added to the test cash and the holding leaves the test positions. A Polymarket holding stays until you redeem or merge it. Either way, its payout less its cost counts as realized profit and loss from the resolution, by outcome, whatever a later merge pays. A merge before its market resolves realizes what it paid when you merged, and the resolution never changes that afterwards. * `POST /v1/positions/close` leaves out every position on a resolved market, test or live, since it settles rather than sells. A close with nothing else to sell reads `nothing_to_close`. `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, changed 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. Changing one moves it to the new price at once, keeping its place in the queue while its price moves by less than a cent. See [Limit chases](/limit-chases). * A test conditional sell is checked against each leg's market and the test account's simulated shares, and can be listed, read and canceled, but it never sells, so it stays `active` until you cancel it. See [Conditional sells](/conditional-sells). * 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. * A test [redeem or merge](/orders#redeem-and-merge) moves nothing on the venue. It settles at once, removes the holdings from the test positions and adds what they pay to the test cash. A test merge leaves shares held for a resting sell alone. * A test key holds no USDC or USDC.e. [Get convertible balances](/funding#convert-usdc-to-pusd) reads zero for both, and a conversion is refused with `details.reason` `NOTHING_TO_CONVERT`. * 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, limit chases, conditional sells, redeems and merges, returns test balances to the starting amount and resets the daily limit usage for test orders. ## 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://docs.lean.xyz/transfers Move cash between your account's Polymarket, Hyperliquid and Lighter balances. A transfer moves cash from one of your account's venues to another. A live key moves it between Polymarket, Hyperliquid and Lighter, in any direction. A test key moves simulated cash between Polymarket and Hyperliquid. 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. 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. 3. `POST /v1/transfers/{id}/execute` authorizes it. 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`. A test transfer returns what to sign in `authorization`: | 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`. | A live transfer has nothing for you to sign, so its `authorization` is `null`. See [Live transfers](#live-transfers). **3. Execute the transfer** For a test transfer, 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. A live transfer takes `delegated` only. The transfer moves to `pending`, then `completed` once the cash arrives. Sending the same request again returns the transfer and moves nothing. ## Live transfers A live transfer moves real cash through [Relay](https://relay.link). Lean signs every step with the account's delegated signer, so the account must have enabled trading in the Lean app. * `fee_usd` on the quote is Relay's price at that moment, plus any fee the sending venue charges. Creating the transfer prices the route again, and the transfer keeps that fee. * The minimum is 2 USD. Relay may ask for more on some routes, and the quote then warns `BELOW_VENUE_MINIMUM`. * An account moves one transfer at a time. While another live transfer is open, or a Hyperliquid withdrawal or a transfer started in the Lean app is in progress, creating a live transfer is refused with `409 CONFLICT`. A transfer you created and have not executed counts as open until it is executed or expires. Test keys can hold several open transfers at once, so a client that opens transfers in parallel in test mode should still expect this `409` live. * A live transfer does not hold `amount_usd` on `from_venue`. If the venue no longer has it when you execute, the transfer fails and nothing moves. * Each read of a `pending` transfer checks Relay and the venues, and the status follows the cash. If a step fails after the cash left, Relay refunds it to `from_venue` and `failure_reason` says so. If the cash has left `from_venue` but has neither arrived nor been refunded, the transfer stays `pending` and `failure_reason` says so. * `GET /v1/balances` and `GET /v1/positions` cover Kalshi, Polymarket, Polymarket US and Hyperliquid. Cash moved to Lighter and Lighter positions don't appear there; check them in the Lean app. ## 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 and not yet executed. A test transfer holds the amount on `from_venue` until then. | | `pending` | Authorized. The cash is on its way. | | `completed` | The cash arrived on `to_venue`. | | `failed` | The move did not happen, or Relay refunded it. `failure_reason` says why. | | `expired` | Not executed in time. Nothing moved. | ## 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. Executing checks the limits and allowed venues again, so a limit lowered or a venue removed after the transfer was created is refused with 422 and nothing moves. Only the key that created a transfer can execute it; any other key gets 404. | Response | `details.reason` | When | | - | - | - | | `400 VALIDATION_ERROR` | | The venues are the same, a venue is unknown, a test key names `lighter`, a venue is not connected, 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, or a live transfer was sent signatures. | | `403 FORBIDDEN` | `ACCOUNT_NOT_DELEGATED` | A live key, or `delegated` was sent, and the account has not enabled trading in the Lean app. | | `409 CONFLICT` | | Another transfer on the account is open or in progress, from the API or the Lean app, including a Hyperliquid withdrawal. | | `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`, `LIVE_TRADING_DISABLED` | The key or its trading account is paused, or Lean has halted live trading. | | `503 UPSTREAM_ERROR` | | Relay or a venue could not price or prepare the route. Nothing was sent. | ## 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. Executing answers `pending`, and the next read or list shows it `completed`. [Reset test mode](/api-reference/test-mode/reset-test-mode) deletes the account's test transfers along with its test orders. # An AI agent that trades within a budget Source: https://docs.lean.xyz/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://docs.lean.xyz/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. A buy sized with `quantity` skips Polymarket and fills on the other venues, so size it with `notional` to include Polymarket. * **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://docs.lean.xyz/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. Creating needs a key with the `trade` scope. Reading needs only `read`. **3. Watch it land** [List deposits](/api-reference/deposits/list-deposits) follows each deposit by `id` until it reads `completed`, `failed` or `refunded`, and [Get balances](/api-reference/account/list-balances) shows the cash once it is credited. pUSD sent straight to the Polymarket wallet skips the list and shows up in the balance at once. 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" curl -sS "$LEAN_API_URL/v1/deposits?venue=hyperliquid" \ -H "Authorization: Bearer $LEAN_API_KEY" ``` ## Guardrails * **Safe to repeat.** Creating deposit addresses returns the same addresses every time, so a job with a `trade` key can run it on every deploy. * **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://docs.lean.xyz/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, between Polymarket and Hyperliquid, the same call moves it and buys. This needs a key with the `route` scope. **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. A buy sized with `quantity` skips Polymarket and fills on the other venues, so size it with `notional` to include Polymarket. * **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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/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://docs.lean.xyz/venues What the API supports on Kalshi, Polymarket, Polymarket US, Hyperliquid and Lighter. Lean trades on five venues: Kalshi, Polymarket, Polymarket US, Hyperliquid and Lighter. One sports 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. Lighter lists crypto markets, which trade on Lighter alone. 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`. Markets, books, prices, trades, candles, the stream, orders, fills, positions, PnL, canceling every open order, closing positions, the account config's `venues`, transfers and a trading account's allowed venues can also name `lighter`. A stop loss, limit chase or conditional sell naming `lighter` is refused with `422` and reason `NO_EXECUTABLE_VENUE`. ## What each venue supports | Feature | Kalshi | Polymarket | Polymarket US | Hyperliquid | Lighter | | - | - | - | - | - | - | | [Markets](/markets), books, trades, candles and prices | Yes | Yes | Yes | Yes | Yes | | [Previews](/preview) | Yes | Yes | Yes | Yes | Yes | | [Quotes](/markets#quotes-and-liquidity) | Yes | Yes | Yes | Yes | No | | [Orders](/orders) and cancels | Yes | Yes | Yes | Yes | Yes | | Amends | Yes | Yes | Yes | Yes | No | | Fills, positions and PnL | Yes | Yes | Yes | Yes | Yes | | Balances | Yes | Yes | Yes | Yes | No | | [Stop losses](/stop-losses) and take profits | Yes | Yes | Yes | Yes | No | | [Limit chases](/limit-chases) | Yes | Yes | Yes | Yes | No | | [Conditional sells](/conditional-sells) | Yes | Yes | Yes | Yes | No | | `gtc` orders | Yes | Yes | Yes | Yes | No | | `post_only` orders | Yes | No | Yes | Yes | Yes | | `gtd` orders | Yes | Yes | Yes | Yes | Yes | | `fok` orders | Yes | Yes | No | No | No | | Paying for a buy with cash on another venue, and `best_price` | No | Yes | No | Yes | No | | [Self signed routed orders](/routed-orders) | No | Yes | No | Yes | No | | [Deposits and withdrawals](/funding) | No | Yes | No | Yes | No | | [Transfers](/transfers) | No | Yes | No | Yes | Live keys only | | [Test mode](/test-mode) | Yes | Yes | Yes | Yes | Yes | ## Lighter Lighter lists crypto price markets on BTC and ETH. Each one asks whether the price ends a 15 minute window up or down. A window is two markets, Up and Down, with `kind` `time_window` and `category` `crypto`. List them with `GET /v1/markets?category=crypto` or `GET /v1/markets?venue=lighter`. See [Crypto windows](/markets#crypto-windows). Preview, place and cancel orders on them with the usual order routes. Every window closes when it ends, so its orders follow the window: * `time_in_force` is `gtd` or `ioc`. `gtc` and `fok` are refused, and nothing rests past the window end. * A `gtd` order's `expires_at` is at or before the window end and at least 6 minutes away. Closer to the end, use `ioc`. * Orders are sized in shares, at least 5, at a whole cent from `0.01` to `0.99`. * An order trades on Lighter alone, paid from the Lighter account's own cash. `venues`, `best_price` and `all_or_none` are refused. * `post_only` orders must use `gtd`. * Orders cannot be amended. Cancel and place a new one. * `POST /v1/positions/close` sells Lighter positions with the rest. Its limit sells on Lighter are `ioc`, whatever `time_in_force` asks, and each sell is at least 5 shares. * A window that has ended no longer trades, so an order or preview on it returns `409 MARKET_NOT_TRADABLE`. A live order needs a Lighter account connected to the key's trading account in the Lean app. If a trading account limits its venues, include `lighter` in its allowed venues to trade Lighter markets. Otherwise orders on Lighter are refused with `VENUE_NOT_ALLOWED`. Move USDC to and from Lighter with [transfers](/transfers). Test keys cannot name `lighter` in a transfer. ## 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` | | Lighter | Starts with `lt:`, such as `lt:120` | `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. A Lighter `lt:` ticker lists both the Up and the Down market of its window. `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) | | Lighter | USDC | Lean [transfers](/transfers) from another venue | 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. `quantity` moves in steps of `0.01` on Kalshi, Polymarket and Polymarket US, and in whole shares on Hyperliquid. Lean refuses a quantity off those steps with `400 VALIDATION_ERROR`, except on a sell of your whole position, which it rounds down to the step and leaves the rest held. See [Quantity steps](/orders#quantity-steps). 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 can go to any venue. Hyperliquid has no order expiry, so Lean cancels what is left there at `expires_at`. * A `fok` order goes whole to one venue: Polymarket, else Kalshi. Hyperliquid has no fill or kill, and Polymarket US can fill part of a fill or kill order and expire the rest. Polymarket takes a `fok` buy sized with `notional` only, so a `fok` buy sized with `quantity` goes to Kalshi. 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 and Lighter books Lean reads Polymarket US and Lighter books from a live copy that starts on the first read of a market and stops a few seconds after the last one. A read of a market no one read lately waits up to a second for the copy. If it is still not 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. * [`GET /v1/markets/{id}/book`](/api-reference/markets/retrieve-market-book) and [`GET /v1/prices`](/markets#prices) answer `200` and list the venue in `unavailable`, with the other venues' levels when the market has any. Read again after a moment. # Versioning Source: https://docs.lean.xyz/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.orderErrorCode` 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 Each release publishes its OpenAPI spec. Generate your clients from the spec of the release you use, and regenerate them when you move to a new one.