Building a trading bot
Place one limit order and cancel it. The examples are curl. Signing happens on your side, with the account’s trading key. The key never goes on the wire.
Base URL in the examples: https://api.loafmarkets.com. Market: TERA.
What you will do
| Step | Call |
|---|---|
| 1 | Create an account and copy the trading key |
| 2 | Sign a login token |
| 3 | GET /api/trade/TERA and subscribe to orderbook:TERA |
| 4 | GET /api/l2/keys, then POST /api/l2/order-indices |
| 5 | POST /api/orders with a signed body |
| 6 | POST /api/orders/cancel |
Signing
Your trading key, api key 0, signs every login token, order, stop, take and withdrawal, and every perps allocate, exit and set-mode request. The signature is a Schnorr signature, sent as l2SigS and l2SigE. curl cannot make it. Key registration, deposits and offering purchases are signed by your wallet instead. An offering purchase paid from the trading balance also carries a withdrawal signed by your trading key.
Loaf’s Python SDK and bot template signs login tokens, orders, stops and takes, withdrawals, and perps allocations and exits. It signs on your machine, with your trading key. Use it as your client, or port its signer to your language and check the port against the known answers in its tests. Install it from its repository, at version 0.7.0 or later. Earlier versions do not work with this API.
1. Account and trading key
Sign up at beta.loafmarkets.com . Deposit, then enable trading on the Trade page. Then show the trading key on the app’s API page. It looks like:
loaf_tk_<l2ChainId>_<l2AccountIndex>_<secret>Store it like a private key. Anyone who has it can trade for the account. The app shows the same key each time you ask, with one wallet signature. It changes only when you reset it. A reset cancels your open orders and take-profit and stop-loss orders. After a reset, login tokens and orders signed with the old key are refused. The secret is api key 0. You use it to sign login tokens and orders. You do not send it.
The account needs an L2 key registered and a deposit before GET /api/l2/keys returns an accountIndex. Registration and deposits take a Privy JWT, not a login token. See L2.
2. Login token
Sign a token that lives about 10 minutes:
loaf_lt_<l2ChainId>_<l2AccountIndex>_<l2ExpiryMs>_<l2SigS><l2SigE>l2SigS and l2SigE are 80 lowercase hex characters each, the Schnorr signature of api key 0 over the login message. See Signing. Loaf refuses a token that is already expired or that expires more than 15 minutes ahead.
Send it as Authorization: Bearer loaf_lt_… on cancels, history, the portfolio summary and component, saved leverage, GET /api/l2/keys, order indexes, withdrawals, and perps allocate, exit, and set mode. See Authentication. POST /api/orders ignores the header. The signature on the body is the credential.
Mint a new token once less than half of its life remains. A session on the WebSocket ends with close code 4001 at expiry. Send a fresh auth frame before that.
3. Read the market
curl 'https://api.loafmarkets.com/api/trade/TERA'Use market.marketIndex, market.l2.l2ChainId, market.l2.baseAssetId, market.l2.quoteAssetId, priceDecimals, and quantityDecimals from this response. The book is orderBook. Prices and quantities in the order body use those decimals. The minimum order value is 10 USD.
Then connect to wss://api.loafmarkets.com/ws and subscribe. Public channels need no auth. See WebSocket.
{ "type": "subscribe", "channels": ["orderbook:TERA", "trades:TERA", "markprice:TERA"], "timestamp": 1764000000 }orderbook_update is { ticker, bids, asks }. Levels are { price, quantity }. There is no propertyId and no orderId on a level. mark_price carries price as a decimal string.
orderbook and trades send the current values to a new subscriber. Seed candles from GET /api/trade/TERA/candles before listening to chart:TERA. Seed your account from GET /api/portfolio/summary and /component before listening to portfolio.
Headlines are a different host, https://news.loafmarkets.com, and need no trading key. See News.
4. Reserve an order index
curl 'https://api.loafmarkets.com/api/l2/keys' \
-H "authorization: Bearer $LOAF_LOGIN_TOKEN"{ "accountIndex": 4, "epoch": 3, "journaledKey": "…", "pending": false, "withdrawalNonce": 7 }A 401 with code UNAUTHENTICATED means the login token was refused. The error text says why.
curl -X POST 'https://api.loafmarkets.com/api/l2/order-indices' \
-H "authorization: Bearer $LOAF_LOGIN_TOKEN" \
-H 'content-type: application/json' \
-d '{"count":64}'{ "accountIndex": 4, "firstIndex": 100, "count": 64, "reservedAtMs": 1764000000000 }Sign l2OrderIndex from firstIndex upward, each value once. Sign l2ExpiryMs at least 72 hours ahead, plus however long the order should rest. It cannot be more than about 49 days ahead, or later than reservedAtMs + 4261412864.
5. Place a limit buy
Build the body in Orders. Sign it with api key 0 (see Signing). For a tutorial buy, set price under the best ask so the order rests.
l2MarketIndex is market.marketIndex from step 3. l2Epoch is epoch from step 4. l2ChainId is market.l2.l2ChainId. A spot order sends l2BaseAssetId and l2QuoteAssetId and does not send l2Pool.
curl -X POST 'https://api.loafmarkets.com/api/orders' \
-H 'content-type: application/json' \
-d @order.json{
"success": true,
"orderId": 9001,
"status": "OPEN",
"quantityLeft": 1,
"cancelReason": null,
"duplicate": false,
"attachedLegIds": []
}status: OPEN means the order is resting. It does not mean it filled. Fills arrive as trade_new on portfolio after you send { "type": "auth", "token": "<login token>" } and subscribe to portfolio.
If this call times out, send the same body again. The same (l2AccountIndex, l2OrderIndex) returns duplicate: true and the original order. A different body on that index is ORDER_INDEX_USED. 503 with code NOT_PROCESSED means nothing was placed. Send the same body again. 503 with UNCONFIRMED means the order may still land. Look up the index before you send a new order. 503 with TRADING_PAUSED carries Retry-After. A halt is MARKET_HALTED or TRADING_HALTED.
A competition round does not block orders. Scoring runs on ordinary trading. See Competition.
Attached take-profit and stop-loss are tp and sl on this body, each with its own index and signature. See Stop & take orders.
6. 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}'POST /api/orders/cancel-all with {} cancels every resting order. POST /api/orders/cancel-after with { "timeoutMs": 15000 } cancels them if your process stops refreshing the timer. Use that on a quoter.
Confirm with one GET /api/history/orders/active, or with order_status on portfolio. Do not poll active orders for the live book.
Quoting
- Subscribe to
orderbook:TERA. Seed the mark fromGET /api/trade/TERA, then followmarkprice:TERA. - Quote inside the spread, at the market’s decimal scales, at least 10 USD.
- Keep the
orderIdandl2OrderIndexyou used. Replace a quote withreplacesOrderIdon the new order, or cancel then place. - On a lost place call, resend the same signed body.
- Set
cancel-afterso a dead process does not leave quotes up.
Perp quotes use ticker TERA-PERP, l2Pool, and l2ReduceOnly. A perp order pays the account’s perps rates in applicableFees on GET /api/portfolio/component, not its spot rates. It never pays more than that market’s l2.takerFee and l2.makerFee. l2FeeRateCap is per million, so 100 is 1 bp. It has to cover the maker and taker rates the order pays, or it is refused FEE_RATE_CAP_TOO_LOW. A cap of the larger of l2.takerFee and l2.makerFee always covers them.