Skip to Content
API ReferenceOrders API

Orders

Place, cancel, and replace. Every order is signed by the account’s trading key (api key 0). POST /api/orders and POST /api/orders/conditional ignore Authorization. Cancels take a login token or the web app’s Privy JWT.

There is no approve route. The trading key is registered once with POST /api/l2/keys, and each order spends an index from POST /api/l2/order-indices.

l2SigS and l2SigE are 80 lowercase hex characters, the Schnorr signature of api key 0. To sign, see Signing. A bad signature comes back as INVALID_SIGNATURE.

Endpoints

MethodPathAuthDescription
POST/api/ordersSignaturePlace an order. Attached tp / sl are allowed.
POST/api/orders/conditionalSignaturePlace a standalone stop or take. See Stop & take orders.
POST/api/orders/cancelLogin token or Privy JWTCancel one resting order
POST/api/orders/conditional/cancelLogin token or Privy JWTCancel a stop or take, standalone or attached
POST/api/orders/cancel-allLogin token or Privy JWTCancel every open order, or one market, or one tag
POST/api/orders/cancel-afterLogin token or Privy JWTDead man’s switch
POST/api/orders/cancel-by-indexLogin token or Privy JWTCancel by l2OrderIndex before the order id is known

Place an order

POST /api/orders

Read GET /api/l2/keys for accountIndex and epoch, and GET /api/trade/:ticker for market.marketIndex, l2.l2ChainId, and the asset ids. Reserve indexes, then sign.

A spot order names l2BaseAssetId and l2QuoteAssetId. It must not send l2Pool or l2ReduceOnly.

A perp order (l2MarketIndex 0 to 254) names l2Pool (0 to 7; 0 is the cross pool) and l2ReduceOnly. It must not send l2BaseAssetId. l2QuoteAssetId is 3.

{ "l2ChainId": 1, "l2AccountIndex": 4, "l2MarketIndex": 2048, "l2OrderIndex": 100, "l2Epoch": 3, "l2FeeRateCap": 7000, "l2ExpiryMs": 1765000000000, "l2BaseAssetId": 7, "l2QuoteAssetId": 3, "l2SigS": "…80 hex…", "l2SigE": "…80 hex…", "price": 167.5, "quantity": 2.5, "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "selfTradePrevention": "CANCEL_MAKER" }
FieldRule
price, quantityHuman numbers at the market’s priceDecimals and quantityDecimals. Minimum value is 10 USD, except a full close.
sideBUY or SELL. A perp SELL can open a short.
typeLIMIT or MARKET.
timeInForceGTC, IOC, FOK, or POST_ONLY. POST_ONLY requires LIMIT.
selfTradePreventionCANCEL_MAKER (default), CANCEL_TAKER, or CANCEL_BOTH.
maxOrderValueOptional USD cap, at least 10, at most 6 decimal places.
l2FeeRateCapThe highest fee rate the order will pay, per million: 100 is 1 bp. Sign at least the higher of the account’s maker and taker rates for the order, or it is refused FEE_RATE_CAP_TOO_LOW. Read the rates from applicableFees on GET /api/portfolio/component: spot for a spot order, perps for a perp. A perp’s rates are never above the market’s makerFee and takerFee in market.l2, so a cap of the larger of those two always covers them. A spot buy holds funds for its fee at the cap. On a perp, the margin check counts the fee at the cap.
l2ExpiryMsUnix ms. The engine fills an order only until 72 hours before its signed expiry, and then cancels it. Sign l2ExpiryMs at least 72 hours ahead, plus however long the order should rest. An expiry inside that 72-hour buffer is refused, and so is one past the maximum order life, about 49 days ahead. The expiry cannot be later than reservedAtMs + 4261412864 for the reserved index. A later expiry is refused INVALID_REQUEST, even one past the maximum order life. If the expiry is within the maximum order life, reserve a new range. Otherwise sign an earlier expiry.
l2Epochepoch from GET /api/l2/keys. A stale epoch is SETTLE_EPOCH_MISMATCH. While epoch is null, the trading key has not taken effect. An order is then refused INVALID_REQUEST.
orderTagOptional, 1 to 4294967295. Cancel-all and cancel-after can select this tag. Not signed.
sendByMsOptional unix ms. If the order is decided after this time, nothing is placed and the index is not spent (SEND_BY_PASSED).
replacesOrderIdOptional id of your resting order on the same market. The engine cancels it first, then decides the new order. The two never rest together, and the new order can use the funds the old one held. If it is not resting, the new order is refused REPLACE_TARGET_GONE and the old order stays. If the cancel lands and the new order is then refused, the old order stays cancelled (replacedOrderCancelled: true).
quoteOrderQtyOptional USD, 6 decimal places. Only a spot MARKET BUY with timeInForce GTC or IOC and no attached legs. The signed quantity is an upper bound. The engine buys as many tokens as this money pays for, fees included.
l2BatchCount, l2BatchPosition, l2BatchSiblings, l2BatchTreeRootAll four, or none. One signature over a root of up to 256 of this account’s orders. l2BatchSiblings is the path from the leaf, leaf end first, each sibling 64 lowercase hex characters. A conditional and an attached leg are signed alone.
tp, slOptional attached legs. See Stop & take orders.
curl -X POST 'https://api.loafmarkets.com/api/orders' \ -H 'content-type: application/json' \ -d @order.json
{ "success": true, "orderId": 9001, "status": "OPEN", "quantityLeft": 2.5, "cancelReason": null, "duplicate": false, "attachedLegIds": [] }
FieldMeaning
statusThe order’s status when the engine answered: OPEN, PARTIALLY_FILLED, FILLED, or CANCELLED
quantityLeftThe unfilled remainder
cancelReasonWhy the engine cancelled the remainder when status is CANCELLED, or null
duplicatetrue when this (l2AccountIndex, l2OrderIndex) was already admitted. The body is the original order
attachedLegIdsEmpty on a duplicate

The answer waits for the engine’s result. If the engine does not confirm the order, the route answers 503 UNCONFIRMED: the order may still land. Look up the index before sending a new one.

Cancel one

POST /api/orders/cancel

curl -X POST 'https://api.loafmarkets.com/api/orders/cancel' \ -H "authorization: Bearer $LOAF_LOGIN_TOKEN" \ -H 'content-type: application/json' \ -d '{"orderId":9001}'
{ "success": true, "orderId": 9001 }

POST /api/orders/conditional/cancel takes the same body and cancels a stop or take by its conditional id, standalone or attached.

Cancel all

POST /api/orders/cancel-all

An empty body cancels every open order. marketIndex limits it to one market (0 to 4095). orderTag limits it to one tag.

{ "marketIndex": 2048, "orderTag": 7 }
{ "requestedCount": 2, "cancelledOrderIds": [9001], "failedOrders": [{ "orderId": 9002, "errorMessage": "…" }] }

Dead man’s switch

POST /api/orders/cancel-after

Cancels the scoped resting orders if your client stops refreshing the timer. timeoutMs is 0 (off) or 10000 to 120000. Optional marketIndex and orderTag use the same scope as cancel-all.

curl -X POST 'https://api.loafmarkets.com/api/orders/cancel-after' \ -H "authorization: Bearer $LOAF_LOGIN_TOKEN" \ -H 'content-type: application/json' \ -d '{"timeoutMs":15000}'
{ "deadlineMs": 1764000015000 }

Send a new timeoutMs before deadlineMs to keep the orders up. This route has its own per-account limit on top of the normal one.

Cancel by index

POST /api/orders/cancel-by-index

Use this when you have signed an index and do not yet have orderId, or the place call never answered.

{ "l2AccountIndex": 4, "l2OrderIndex": 100 }
{ "outcome": "CANCELLED", "orderId": 9001, "status": "CANCELLED" }

outcome is CANCELLED or ENDED with an orderId and status, or VOIDED with both null when no order was booked on that index. A voided index is spent. An order on it is refused ORDER_INDEX_USED, even one still in flight.

Errors

Trading refusals are a JSON object with error (a string), optional code, and optional details (an array of strings). error is readable text and can change. Match on code. replacedOrderCancelled is true when a replace cancelled the old order and then refused the new one.

codeStatusWhen
UNAUTHENTICATED401A cancel route with no login token or Privy JWT, or with one that is refused
INVALID_SIGNATURE400, 401The signature or the batch leaf does not verify, or l2AccountIndex has no trading account, or epoch is set but the trading key is missing or disabled. error says which. 400 on an offering purchase whose permit is not the wallet’s signature
INSUFFICIENT_BALANCE400, 422Available balance cannot reserve the order. On a perp, the pool’s margin cannot cover it. 422 on a withdrawal above the available balance, fee included
WITHDRAW_FEE_ABOVE_MAX422A withdrawal’s fee is above maxWithdrawFee, or above 0 when it is absent. Nothing was withdrawn and the nonce is not spent. Read withdrawFee on GET /api/portfolio/summary and send again
BELOW_MIN_ORDER_VALUE400, 422Notional under 10 USD. 422 on a withdrawal below the asset’s minimum withdrawal
ABOVE_MAX_ORDER_VALUE400Notional above the order’s own maxOrderValue
PRICE_BAND400Price outside the market’s band
POST_ONLY_WOULD_TAKE400POST_ONLY would match immediately
NOT_FILLED400An IOC or MARKET order filled nothing
FOK_NOT_FILLED400A FOK order could not fill in full
SELF_TRADE400Self-trade prevention cancelled it
OPEN_ORDER_LIMIT400Too many open orders, in total or on this market. Resting orders and PENDING or ARMED stops and takes all count
TRIGGER_THROUGH400A trigger the last trade price (on a perp, the mark) has already reached
NOTHING_TO_REDUCE400Reduce-only order with nothing to reduce
FEE_RATE_CAP_TOO_LOW400l2FeeRateCap is below the account’s maker or taker rate for the order. Sign a higher cap
ORDER_INDEX_USED400, 409, 422That index was already used by another order or a stop or take, or voided by cancel-by-index. 409 on an offering purchase whose signed withdrawal already funds another purchase. 422 on a withdrawal or a perps allocate, exit, or set-mode whose l2Nonce is not withdrawalNonce
ORDER_INDEX_NOT_RESERVED400Cancel by index: the index is not in a range reserved to this account. An order placed on such an index is refused INVALID_REQUEST
ORDER_EXPIRY_INVALID400, 422Expiry inside the buffer, or past the maximum life but not later than reservedAtMs + 4261412864. 422 when a perps exit’s expiry is past the maximum life, or a withdrawal’s expiry reaches the buffer before it is decided
SETTLE_EPOCH_MISMATCH400l2Epoch is not the account’s current epoch (epoch from GET /api/l2/keys)
SEND_BY_PASSED400Decided after sendByMs. Index not spent
REPLACE_TARGET_GONE409replacesOrderId is not resting
MARKET_NOT_FOUND404No such market
MARKET_NOT_LIVE400, 403The market is not live, or its trading has not started
MARKET_UNAVAILABLE503Trading on this market is unavailable for now. Nothing was placed. Retry the same body
MARKET_HALTED403Trading is halted on this market
TRADING_HALTED403Platform-wide trading halt
TRADING_PAUSED503Trading is paused. Retry after the Retry-After seconds
MARKET_CLOSED403The market is outside its trading hours
REDUCE_ONLY403The market takes only orders that reduce a position
PRICE_STALE403The perp is reduce-only while its price is stale
PRICE_HELD403The perp is reduce-only while its latest price is held for review
OPEN_INTEREST_CAP403Perp open interest is full
ORDER_NOT_FOUND404No such order to cancel. On POST /api/orders/conditional/cancel, also a stop or take of another user
ORDER_NOT_OWNED403On POST /api/orders/cancel, the order belongs to another user. On cancel by index, the account or the index does
ORDER_NOT_CANCELLABLE400, 409The order is no longer open. On POST /api/orders/cancel, 409 when the cancel lost a race to a fill or another cancel. On POST /api/orders/conditional/cancel, 409 while the stop or take still reads PENDING or ARMED
NOT_PROCESSED503Nothing was placed or changed. Retry the same body
UNCONFIRMED503The engine did not confirm the order. It may still land. Look up the index before sending a new one
RATE_LIMITED422, 429Too many requests. Retry after the Retry-After seconds. The general per-IP limit answers 429 with no code. 422 on a withdrawal while too many withdrawals are not yet settled on chain. Send the same body again later
INVALID_REQUEST400, 422Body failed validation, and error names the field (when error is Validation failed, details names the fields). Also an index outside your reserved ranges, an expiry later than reservedAtMs + 4261412864, or a trading key that has not taken effect yet (epoch is null on GET /api/l2/keys). 422 on a withdrawal of an asset that is not listed, or on a perps allocate between the spot balance and pool 0 of a UNIFIED account
UNKNOWN_REASON400, 403, 422Refused for a reason with no code of its own. error says why. 422 on a withdrawal or a perps allocate, exit, or set-mode. 403 while withdrawals are closed
SERVICE_UNAVAILABLE503The service could not answer. Retry the same body
INTERNAL_ERROR500The service could not answer. Retry the same body

A 400 validation error names the field in error, for example l2 pool: only a perps order (l2_market_index at most 254) has a pool or quote_order_qty: only a spot MARKET BUY executing as IOC, with no attached legs, may carry it.

Last updated on