List Markets
Returns markets sorted by end_date, newest first by default. Every item has type: "market".
Filters that take a list accept comma-separated values: a market matches if it has any of them. Different filters combine with AND. Names are case-insensitive.
Query Parameters
| Param | Type | Description |
|---|---|---|
address | string | Market address, or several comma-separated. |
state | string | open · upcoming · pending · settled · voided |
instrument | string | Underlying asset: BTC |
market_type | string | UpDown |
period | string | Expiry period as returned in period: 5m · 15m · 30m · 1h · 4h · Daily |
category | string | e.g. Crypto |
end_from | integer | end_date from, unix seconds, inclusive |
end_to | integer | end_date until, unix seconds, exclusive |
order | string | By end_date: desc (default) or asc |
limit | integer | Max items, 1–1000. Default 100. |
offset | integer | Items to skip, for paging. Default 0, max 10000. |
curl 'https://api.testnet.lucyd.trade/markets?market_type=UpDown&period=15m&state=open,upcoming&order=asc&limit=10'
[
{
"type": "market",
"address": "0xC345e876Fde6d007AA54b6Dc374B1fB6de110b3b",
"instrument": "BTC",
"market_type": "UpDown",
"period": "Daily",
"title": "Will BTC go up or down today?",
"category": "Crypto",
"outcomes": [
"up",
"down"
],
"state": "open",
"start_date": "2026-09-28T00:00:00Z",
"end_date": "2026-09-29T00:00:00Z",
"resolved_at": null,
"winner": null,
"volume_traded": 284.5,
"strike": 6250000000000,
"rules": "Resolves Up if the Pyth BTC/USD price at expiry is strictly greater than the strike recorded at open, Down otherwise.",
"resolved_value": null,
"resolver_address": "0xe051D7D72DEb54F934F5DFa0846779232e7265dD",
"oracle": {
"provider": "pyth",
"feeds": [
{
"id": "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",
"name": "BTC/USD",
"url": "https://pyth.network/price-feeds/crypto-btc-usd"
}
]
}
}
]offset increased by limit until fewer than limit items come back. offset stops at 10000: to go further back, page by end_from / end_to windows.Get Market
Returns a single market by its contract address.
Path Parameters
| Param | Type | Description |
|---|---|---|
addressrequired | string | EVM contract address of the market |
curl https://api.testnet.lucyd.trade/markets/0xC345e876Fde6d007AA54b6Dc374B1fB6de110b3b
{
"type": "market",
"address": "0xC345e876Fde6d007AA54b6Dc374B1fB6de110b3b",
"instrument": "BTC",
"market_type": "UpDown",
"period": "Daily",
"title": "Will BTC go up or down today?",
"category": "Crypto",
"outcomes": [
"up",
"down"
],
"state": "settled",
"start_date": "2026-09-27T00:00:00Z",
"end_date": "2026-09-28T00:00:00Z",
"resolved_at": "2026-09-28T00:05:12Z",
"winner": "up",
"volume_traded": 284.5,
"strike": 6250000000000,
"rules": "Resolves Up if the Pyth BTC/USD price at expiry is strictly greater than the strike recorded at open, Down otherwise.",
"resolved_value": 6301234500000,
"resolver_address": "0xe051D7D72DEb54F934F5DFa0846779232e7265dD",
"oracle": {
"provider": "pyth",
"feeds": [
{
"id": "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",
"name": "BTC/USD",
"url": "https://pyth.network/price-feeds/crypto-btc-usd"
}
]
}
}404 if the address is not found or is not an UpDown market.Market Object
All market endpoints return markets with type: "market". The only market type is UpDown on the Pyth BTC/USD price, with periods 5m, 15m, 30m, 1h, 4h and Daily.
| Param | Type | Description |
|---|---|---|
type | "market" | Discriminator field |
address | string | EVM contract address |
instrument | string | null | Underlying asset: "BTC" |
market_type | string | UpDown |
period | string | Expiry period: 5m · 15m · 30m · 1h · 4h · Daily |
title | string | Generated server-side: "Will BTC go up or down over the next {period}?", Daily: "Will BTC go up or down today?" |
category | string | e.g. "Crypto" |
outcomes | string[] | Possible outcomes: ["up","down"] |
state | string | open · upcoming · pending · settled · voided |
start_date | string (ISO 8601) | Market open time |
end_date | string (ISO 8601) | Market expiry time |
resolved_at | string (ISO 8601) | null | Settlement timestamp |
winner | string | null | Winning outcome label |
volume_traded | number | Total traded notional, USD (taker price × quantity over all fills) |
strike | integer | null | Strike (BTC/USD at open) |
rules | string | null | Resolution rules text |
resolved_value | integer | null | Final oracle value at settlement |
resolver_address | string | On-chain resolver contract address |
oracle | Oracle | Price feeds the market resolves on (see Oracle below). |
Market states
| Param | Type | Description |
|---|---|---|
open | Trading active | |
upcoming | Not yet started | |
pending | end_date passed, oracle result not yet published | |
settled | Resolved with a winner | |
voided | Cancelled — all positions refunded |
resolved_value use 8-decimal fixed point. Divide by 1e8 to get the display value (e.g. 6250000000000 → 62500.00).List Trades
Returns executed trades (fills), newest first. Every trade is read from the Exchange contract on chain, so it appears once its transaction is included in a block.
Each row describes the trade from the taker's side: the order that crossed the book. A taker order that matches several resting orders produces one row per matched order, each with its own price. With trader, rows describe that wallet's side instead (taker or maker).
Query Parameters
| Param | Type | Description |
|---|---|---|
market | string | Market address, or several comma-separated. Omit for all markets. |
from | integer | Unix seconds, inclusive |
to | integer | Unix seconds, exclusive |
trader | string | Wallet, or several comma-separated. Fills where this wallet was the taker or the maker; side, outcome, price are that wallet's side of the fill. |
side | string | Taker side: buy · sell |
outcome_index | integer | 0 = up, 1 = down |
match_type | string | direct · mint · merge, comma-separated |
min_amount_usd | number | Only trades with amount_usd at least this, inclusive |
order | string | By block: desc (default for JSON) or asc (default for CSV) |
limit | integer | Max rows, 1–1000. Default 100. |
offset | integer | Rows to skip, for paging. Default 0, max 10000. |
format | string | json (default) or csv. See Download CSV. |
curl 'https://api.testnet.lucyd.trade/trades?market=0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d&limit=2'
[
{
"trade_id": "0x5f1c...e2a9:0x8d04...71bc",
"tx_hash": "0x9a3e...4f10",
"log_index": 7,
"block_number": 11809412,
"block_time": "2026-09-29T20:01:24Z",
"market_id": "0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d",
"match_type": "direct",
"trader": "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be",
"side": "buy",
"outcome_id": "0x8756c597fb7af9d1a06e4b5dad8686b45a189eb5a3fea39c58052a20d05d7e44",
"outcome_index": 0,
"outcome": "up",
"price": 0.66,
"quantity": 378787878,
"amount_usd": 250
},
{
"trade_id": "0x77a0...c3d1:0x1b9e...0f42",
"tx_hash": "0x2c6b...a8e7",
"log_index": 3,
"block_number": 11809407,
"block_time": "2026-09-29T20:00:12Z",
"market_id": "0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d",
"match_type": "mint",
"trader": "0x71c7656ec7ab88b098defb751b7401b5f6d8976f",
"side": "buy",
"outcome_id": "0x5e5fbb0202ce2fe377f6cbe704e21d3767fc8838a4b270e59b9093b355c852a9",
"outcome_index": 1,
"outcome": "down",
"price": 0.34,
"quantity": 147058823,
"amount_usd": 50
}
]market and dedupe rows by trade_id. New trades arrive once per block (about 12 s).Download CSV
Same data as GET /trades, returned as a CSV file for backtesting and analysis. Rows are sorted oldest first. Use from / to to pick a time range.
Query Parameters
| Param | Type | Description |
|---|---|---|
formatrequired | "csv" | Return CSV instead of JSON |
market | string | Market address, or several comma-separated |
from | integer | Unix seconds, inclusive |
to | integer | Unix seconds, exclusive |
limit | integer | Max rows, 1–20000. Default 20000. |
… | All other filters of GET /trades work too (trader, side, outcome_index, match_type, min_amount_usd, order, offset). |
curl -o trades.csv \ 'https://api.testnet.lucyd.trade/trades?format=csv&market=0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d&from=1790640000&to=1790726400'
trade_id,tx_hash,log_index,block_number,block_time,market_id,match_type,trader,side,outcome_id,outcome,price,quantity,amount_usd 0x77a0...c3d1:0x1b9e...0f42,0x2c6b...a8e7,3,11809407,2026-09-29T20:00:12+00:00,0xbb62...644d,mint,0x71c7...976f,buy,0x5e5f...52a9,down,0.34,147058823,50 0x5f1c...e2a9:0x8d04...71bc,0x9a3e...4f10,7,11809412,2026-09-29T20:01:24+00:00,0xbb62...644d,direct,0x3f5c...f0be,buy,0x8756...7e44,up,0.66,378787878,250
from / to windows.Positions
Returns positions, sorted by value plus payout descending. A position is the amount of outcome tokens a wallet bought minus sold through the exchange, minus what it redeemed after resolution. A fully redeemed position is still returned, with shares 0, so its result stays visible.
Filter by market, trader, outcome_index in any combination; at least one of market or trader is required. market alone gives the top holders of a market, trader alone gives a wallet's portfolio.
It is valued at the last traded price of that outcome; once the market is resolved, at its payout (1 USD per winning share, 0 per losing one, 0.5 on void). avg_price is the average price paid over all buys of that outcome. redeemed_usd is what was already paid out, automatically or by the holder.
Query Parameters
| Param | Type | Description |
|---|---|---|
market | string | Market address, or several comma-separated |
trader | string | Wallet, or several comma-separated |
outcome_index | integer | 0 = first outcome, 1 = second |
state | string | Market state, or several comma-separated: open, pending, settled, voided |
limit | integer | Max rows, 1–100. Default 20. |
offset | integer | Rows to skip, for paging. Default 0, max 10000. |
curl 'https://api.testnet.lucyd.trade/positions?market=0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d&limit=2'
[
{
"market_id": "0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d",
"trader": "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be",
"outcome_index": 0,
"outcome": "up",
"shares": 3303030303,
"value_usd": 2180,
"avg_price": 0.52,
"cost_usd": 1717.58,
"redeemed_shares": 0,
"redeemed_usd": 0,
"market_state": "open"
},
{
"market_id": "0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d",
"trader": "0x71c7656ec7ab88b098defb751b7401b5f6d8976f",
"outcome_index": 1,
"outcome": "down",
"shares": 1088235294,
"value_usd": 370
}
]Position Object
| Param | Type | Description |
|---|---|---|
market_id | string | Market address |
trader | string | Wallet address, lowercase |
trader_nickname | string | null | Public name the owner set in the Lucyd app (set once, never changes); null if none |
outcome_index | integer | 0 = first outcome, 1 = second |
outcome | string | null | Outcome label from the market, e.g. "up" |
shares | integer | Outcome tokens still held (bought − sold − redeemed), raw units (6 decimals) |
value_usd | number | shares × last traded price of the outcome, in USD; after resolution shares × payout (1 or 0, 0.5 on void) |
avg_price | number | null | Average price paid over all buys of this outcome, USD per share |
cost_usd | number | null | (shares + redeemed_shares) × avg_price, in USD |
redeemed_shares | integer | Tokens redeemed after resolution, raw units (6 decimals) |
redeemed_usd | number | USDC paid out for the redeemed tokens, after fee |
market_state | string | null | open, pending, settled or voided |
Trade Object
One trade is one fill: a taker order matched against one resting (maker) order. All fields describe the taker's side.
| Param | Type | Description |
|---|---|---|
trade_id | string | takerOrderId:makerOrderId. Unique per fill. |
tx_hash | string | Settlement transaction hash |
log_index | integer | Position of the fill event within the block |
block_number | integer | Block that included the trade |
block_time | string (ISO 8601) | Block timestamp |
market_id | string | Market address, same as address in GET /markets |
match_type | MatchType | direct · mint · merge (see below) |
trader | string | Taker wallet address, lowercase (with the trader filter: the filtered wallet) |
trader_nickname | string | null | Public name the owner set in the Lucyd app (set once, never changes); null if none |
side | string | buy · sell |
outcome_id | string | Outcome token id (ERC-1155) |
outcome_index | integer | null | 0 = up, 1 = down |
outcome | string | null | Outcome label from the market's outcomes array |
price | number | USDC per outcome token, 0–1 |
quantity | integer | Outcome tokens traded, raw units (6 decimals) |
amount_usd | number | price × quantity, in USD |
Match types
| Param | Type | Description |
|---|---|---|
direct | Buyer and seller of the same outcome swap tokens for USDC | |
mint | Two buyers of opposite outcomes; their USDC mints a new pair of tokens. Prices sum to 1. | |
merge | Two sellers of opposite outcomes; their tokens are merged back into USDC. Prices sum to 1. |
quantity and shares by 1e6 to get whole tokens (e.g. 250000000 → 250).Order Book History
Full L2 order book history of every market, one Parquet file per market, free to download without a key. A file appears a few minutes after the market is closed and removed from the order book. Markets that never had an order have no file. Browse every available file with its size at https://data.testnet.lucyd.trade/.
| Param | Type | Description |
|---|---|---|
market_typerequired | string | market_type from GET /markets, lowercase: updown |
periodrequired | string | period from GET /markets, lowercase: 5m, 15m, 30m, 1h, 4h or daily |
instrumentrequired | string | instrument from GET /markets, lowercase, e.g. btc |
daterequired | string | Market start date in UTC, YYYY-MM-DD (start_date in GET /markets) |
marketrequired | string | Market address (address in GET /markets), lowercase |
curl -O 'https://data.testnet.lucyd.trade/books/updown/15m/btc/2026-10-07/0xbb62c701d023d601073455e9a6439815437c56fc768bbc5cc528d147cfe7644d.parquet'
Columns
| Column | Type | Description |
|---|---|---|
| timestamp | timestamp (ms, UTC) | When the book reached this state |
| state_sequence | uint64 | Order book publication counter, increases over time |
| kind | string | `snapshot` or `delta` |
| asset_id | string | Outcome token, the same `asset_id` as on the order book stream; null in an empty snapshot |
| side | string | `bid` or `ask`; null in an empty snapshot |
| price | double | 0.0025 to 0.9975 in steps of 0.0025 |
| size | uint64 | Total size at this price in base units (6 decimals); 0 in a `delta` = the level is gone |
Rebuilding the book
Rows with the same timestamp and kind snapshot are the complete book of both outcomes at that moment; an empty book is a single row with null level fields. A delta row sets one level to a new size. To get the book at time T, take the last snapshot at or before T and apply the deltas after it up to T. A snapshot is written when the book first gets an order, about once a minute while it keeps changing, and after any gap in recording.
import pandas as pd
df = pd.read_parquet("0xbb62….parquet")
t = pd.Timestamp("2026-10-07T12:07:30Z")
df = df[df.timestamp <= t]
last = df[df.kind == "snapshot"].timestamp.max()
book = {}
for r in df[df.timestamp >= last].itertuples():
if r.kind == "snapshot" and r.timestamp == last:
if r.side is not None:
book[(r.asset_id, r.side, r.price)] = r.size
elif r.kind == "delta":
book[(r.asset_id, r.side, r.price)] = r.size
book = {k: v for k, v in book.items() if v > 0}GET /trades and the CSV download have block time.Fills History
Every fill of a market at the moment the order book matched it, with millisecond time, one Parquet file per market, free to download without a key. Same path and names as Order Book History, under fills/. GET /trades has the time of the settlement block (up to 12 s later); use these files to line trades up with the book. A file appears once the market is removed from the order book and its fills are settled (at most an hour later). Markets without trades have no file. Browse every available file with its size at https://data.testnet.lucyd.trade/.
| Param | Type | Description |
|---|---|---|
market_typerequired | string | market_type from GET /markets, lowercase: updown |
periodrequired | string | period from GET /markets, lowercase: 5m, 15m, 30m, 1h, 4h or daily |
instrumentrequired | string | instrument from GET /markets, lowercase, e.g. btc |
daterequired | string | Market start date in UTC, YYYY-MM-DD (start_date in GET /markets) |
marketrequired | string | Market address (address in GET /markets), lowercase |
curl -O 'https://data.testnet.lucyd.trade/fills/updown/15m/btc/2026-10-27/0x….parquet'
Columns
| Column | Type | Description |
|---|---|---|
| timestamp | timestamp (ms, UTC) | When the order book matched the fill; rows are sorted by it, then by `journal_id` |
| journal_id | int64 | Order event id, increases in match order |
| trade_id | string | `takerOrderId:makerOrderId`, the same `trade_id` as in `GET /trades` |
| price | double | Price of the taker's outcome |
| size | uint64 | Outcome tokens in base units (6 decimals), the unit of `size` in book files |
| taker | string | Taker wallet |
| taker_side | string | `buy` or `sell` |
| taker_asset_id | string | Taker's outcome token, the same id as `asset_id` in book files |
| maker | string | Maker wallet |
| maker_side | string | `buy` or `sell` |
| maker_asset_id | string | Maker's outcome token, the same id as `asset_id` in book files |
| match_type | string | `direct` (same outcome changes hands), `mint` (both buy opposite outcomes), `merge` (both sell) |
| settlement | string | `confirmed`, `failed`, or `pending` if not settled an hour after the market was removed |
| tx_hash | string | Settlement transaction; null while pending |
| block_number | int64 | Block of `tx_hash` |
timestamp comes from clocks on the same machine, but means different moments: here it is when the order book matched the fill, in book files when the book snapshot arrived, up to ~100 ms after the change. So a fill shows up in the book shortly after its timestamp. A taker order that fills against several makers gives several rows with the same timestamp.Price History
Pyth price history of every feed markets settle on, one Parquet file per feed and UTC day, free to download without a key. About one update per second, as streamed by Pyth Hermes. A day's file appears a few minutes after midnight UTC; the current day is not published. Browse every available file with its size at https://data.testnet.lucyd.trade/.
| Param | Type | Description |
|---|---|---|
feedrequired | string | Pyth feed name, lowercase with a dash, e.g. btc-usd |
daterequired | string | UTC day of publish_time, YYYY-MM-DD |
curl -O 'https://data.testnet.lucyd.trade/prices/pyth/btc-usd/2026-10-27.parquet'
Columns
| Column | Type | Description |
|---|---|---|
| publish_time | timestamp (ms, UTC) | Price time set by Pyth, whole seconds; rows are sorted by it |
| receive_time | timestamp (ms, UTC) | When the update reached our recorder |
| price | double | Pyth aggregate price, exponent applied (e.g. `114073.5`) |
| conf | double | Pyth confidence interval, exponent applied |
| slot | uint64 | Pythnet slot of the update; null if Hermes did not send it |
publish_time here is the column to match against end_date in GET /markets.Live Trades
Public stream of trades over WebSocket, no authentication. A trade arrives as soon as the order book matches it (status: "matched", usually well under a second), and again once its settlement transaction is confirmed on chain ("confirmed", about a minute later, with tx_hash). If settlement reverts, it comes a third time as "failed": the trade did not happen. Every message carries the whole trade; join them by trade_id, the same id as in GET /trades.
Subscribe
All messages are JSON text frames. A subscription is any combination of markets, traders and series; every given field must match, and none given means all trades. A connection may hold up to 20 subscriptions and gets a trade once even if several of them match.
{"type":"subscribe","requestId":"all"}
{"type":"subscribe","requestId":"w","traders":["0x71c7…976f"]}
{"type":"subscribe","requestId":"m","markets":["0x…market address"],"backfill":50}
{"type":"subscribe","requestId":"s","series":{"instrument":"BTC","market_type":"UpDown","period":"15m"}}| Param | Type | Description |
|---|---|---|
markets | string[] | Market addresses (address in GET /markets), up to 100 |
traders | string[] | Wallets, up to 100. Matches trades where the wallet is the taker or the maker |
series | object | instrument, market_type and period as in GET /markets: every market of the series, including ones opened later |
backfill | integer | Also send the last N matching messages, up to 500 |
since | integer | Also send every kept matching message with seq greater than this, to resume after a reconnect |
requestId | string | number | Echoed in the answer |
The answer comes before any backfill. seq is the newest message position at that moment; gap: true means some messages after your since are no longer kept: fetch that period from GET /trades.
{"type":"subscribed","requestId":"m","subscriptionId":3,"backfill":50,"gap":false,"seq":918245}Trade message
Taker fields are the same as in the Trade Object; maker fields describe the resting order on the other side.
{"type":"trade","seq":918246,"status":"matched","trade_id":"0x77a0…c3d1:0x1b9e…0f42","market_id":"0xbb62…644d","instrument":"BTC","market_type":"UpDown","period":"15m","match_type":"mint","trader":"0x71c7…976f","side":"buy","outcome_index":1,"outcome":"down","price":0.34,"quantity":50000000,"amount_usd":17.0,"maker":"0x3f5c…f0be","maker_side":"buy","maker_outcome_index":0,"maker_outcome":"up","maker_price":0.66,"time":"2026-10-07T12:00:01.204Z","tx_hash":null,"block_number":null,"reason_code":null}| Param | Type | Description |
|---|---|---|
type | "trade" | |
seq | integer | Stream position, grows with every message. Use it with since |
status | string | matched: by the order book · confirmed: settlement confirmed on chain · failed: settlement reverted, the trade did not happen |
trade_id | string | takerOrderId:makerOrderId, same as in GET /trades |
market_id | string | Market address |
instrument | string | null | BTC |
market_type | string | null | UpDown |
period | string | null | 5m · 15m · 30m · 1h · 4h · Daily |
match_type | string | null | direct · mint · merge |
trader | string | Taker wallet, lowercase |
side | string | Taker side |
outcome_index | integer | null | Taker outcome: 0 = up, 1 = down |
outcome | string | null | Taker outcome label |
price | number | Taker price, USDC per outcome token |
quantity | integer | Outcome tokens traded, raw units (6 decimals) |
amount_usd | number | price × quantity, in USD |
maker | string | null | Maker wallet, lowercase |
maker_side | string | null | buy · sell |
maker_outcome_index | integer | null | Maker outcome: 0 = up, 1 = down |
maker_outcome | string | null | Maker outcome label |
maker_price | number | null | Maker price in its own outcome |
time | string (ISO 8601) | When the order book matched it, or when settlement was confirmed / failed |
tx_hash | string | null | Settlement transaction, from confirmed / failed on |
block_number | integer | null | Block of the settlement transaction (confirmed) |
reason_code | integer | null | 10 on failed |
Other commands
{"type":"unsubscribe","requestId":"u","subscriptionId":3}
{"type":"unsubscribe","requestId":"u"}
{"type":"ping","requestId":"p"}unsubscribe without subscriptionId removes all subscriptions; ping is answered with pong. A bad command gets {"type":"error","requestId":…,"error":"…"} and the connection stays open.
Reconnecting
Keep the largest seq you received and resubscribe with since after a reconnect. The server closes with code 1012 when it restarts and 1008 when a client reads too slowly. A trade may repeat when a backfill overlaps another subscription of the same connection: skip a seq you already have.
| Limit | Value |
|---|---|
| Subscriptions per connection | 20 |
| Markets or wallets per subscription | 100 |
| Backfill | 500 messages; `since` reaches back over the last 5000 messages |
| Message size | 16 KiB |
confirmed a trade is not final: a failed one never happened on chain. Count only confirmed trades to match GET /trades.List Traders
Returns every wallet that has traded, with its stats, sorted by total P&L descending. Use it for leaderboards and to find the most profitable or active wallets.
The list is recomputed at most every 30 seconds; GET /traders/{address} is always current.
Query Parameters
| Param | Type | Description |
|---|---|---|
sort | string | pnl (default), realized_pnl, volume, trades, markets, win_rate, first_trade, last_trade, registered |
order | string | desc (default) or asc. Wallets without a value for the sort field (no win rate, not registered) are always last. |
min_pnl | number | Total P&L at least, USD |
max_pnl | number | Total P&L at most, USD |
min_volume | number | Volume at least, USD |
min_markets | integer | Markets traded at least |
active_from | integer | Unix seconds: last trade at or after |
registered | boolean | true: only wallets registered in the Lucyd app; false: only external wallets |
registered_from | integer | Unix seconds, inclusive, on registered_at |
registered_to | integer | Unix seconds, exclusive, on registered_at |
limit | integer | Max rows, 1–1000. Default 100. |
offset | integer | Rows to skip, for paging. Default 0, max 10000. |
curl 'https://api.testnet.lucyd.trade/traders?sort=win_rate&min_markets=20&limit=10'
[
{
"trader": "0x2c2b35ff4055522a7bf228efb07540d6c8f73744",
"total_pnl": 115.84,
"realized_pnl": 114.63,
"unrealized_pnl": 1.21,
"volume_usd": 2697.48,
"trades_count": 2069,
"markets_traded": 128,
"open_positions": 4,
"markets_won": 50,
"markets_lost": 29,
"win_rate": 0.6329,
"best_market_pnl": 13.69,
"worst_market_pnl": -11.71,
"first_trade_at": "2026-09-30T10:57:36Z",
"last_trade_at": "2026-10-01T11:48:48Z",
"registered_at": "2026-09-28T14:02:11Z"
}
]Trader Object
| Param | Type | Description |
|---|---|---|
trader | string | Wallet address, lowercase |
total_pnl | number | realized_pnl + unrealized_pnl, USD |
realized_pnl | number | P&L of closed markets (resolved, or fully exited), USD |
unrealized_pnl | number | P&L of markets still held and not resolved, at the last traded price, USD |
volume_usd | number | USDC paid and received in fills |
trades_count | integer | Fills, as taker or maker |
markets_traded | integer | Markets with at least one fill |
open_positions | integer | Outcomes still held in markets that are not resolved |
markets_won | integer | Closed markets with P&L above 0, voided ones excluded |
markets_lost | integer | Closed markets with P&L below 0, voided ones excluded |
win_rate | number | null | markets_won / (markets_won + markets_lost), 0–1. Null until a market is won or lost. |
best_market_pnl | number | null | Best P&L in one closed market, USD |
worst_market_pnl | number | null | Worst P&L in one closed market, USD |
first_trade_at | string (ISO 8601) | First fill |
last_trade_at | string (ISO 8601) | Latest fill |
registered_at | string (ISO 8601) | null | Sign-up in the Lucyd app; null for wallets trading directly on the contract |
nickname | string | null | Public name the owner set in the Lucyd app (set once, never changes); null if none |
Get Trader
Stats of one wallet, computed on request.
Path Parameters
| Param | Type | Description |
|---|---|---|
addressrequired | string | Wallet address |
curl 'https://api.testnet.lucyd.trade/traders/0x2c2b35ff4055522a7bf228efb07540d6c8f73744'
{
"trader": "0x2c2b35ff4055522a7bf228efb07540d6c8f73744",
"total_pnl": 115.84,
"realized_pnl": 114.63,
"unrealized_pnl": 1.21,
"volume_usd": 2697.48,
"trades_count": 2069,
"markets_traded": 128,
"open_positions": 4,
"markets_won": 50,
"markets_lost": 29,
"win_rate": 0.6329,
"best_market_pnl": 13.69,
"worst_market_pnl": -11.71,
"first_trade_at": "2026-09-30T10:57:36Z",
"last_trade_at": "2026-10-01T11:48:48Z",
"registered_at": "2026-09-28T14:02:11Z"
}Trader Object
| Param | Type | Description |
|---|---|---|
trader | string | Wallet address, lowercase |
total_pnl | number | realized_pnl + unrealized_pnl, USD |
realized_pnl | number | P&L of closed markets (resolved, or fully exited), USD |
unrealized_pnl | number | P&L of markets still held and not resolved, at the last traded price, USD |
volume_usd | number | USDC paid and received in fills |
trades_count | integer | Fills, as taker or maker |
markets_traded | integer | Markets with at least one fill |
open_positions | integer | Outcomes still held in markets that are not resolved |
markets_won | integer | Closed markets with P&L above 0, voided ones excluded |
markets_lost | integer | Closed markets with P&L below 0, voided ones excluded |
win_rate | number | null | markets_won / (markets_won + markets_lost), 0–1. Null until a market is won or lost. |
best_market_pnl | number | null | Best P&L in one closed market, USD |
worst_market_pnl | number | null | Worst P&L in one closed market, USD |
first_trade_at | string (ISO 8601) | First fill |
last_trade_at | string (ISO 8601) | Latest fill |
registered_at | string (ISO 8601) | null | Sign-up in the Lucyd app; null for wallets trading directly on the contract |
nickname | string | null | Public name the owner set in the Lucyd app (set once, never changes); null if none |
P&L History
P&L of a wallet over time, for an equity curve. Each point is the P&L the wallet had at that moment: its USDC flow up to then plus the tokens it held, valued at the last price traded by then (the payout if the market was already resolved). Deposits and withdrawals don't move it.
Points are evenly spaced: 30 min for 1d, 2 h for 1w, 8 h for 1m; all starts at the first trade and has about 120 points (at least 1 h apart). The last point is the current time and equals total_pnl of GET /traders/{address}. A wallet without trades gives an empty array.
Path Parameters
| Param | Type | Description |
|---|---|---|
addressrequired | string | Wallet address |
Query Parameters
| Param | Type | Description |
|---|---|---|
range | string | 1d, 1w, 1m or all (default) |
curl 'https://api.testnet.lucyd.trade/traders/0x2c2b35ff4055522a7bf228efb07540d6c8f73744/pnl-history?range=1w'
[
{
"time": "2026-10-01T07:48:59Z",
"pnl": 92.4
},
{
"time": "2026-10-01T09:48:59Z",
"pnl": 104.1
},
{
"time": "2026-10-01T11:48:59Z",
"pnl": 115.84
}
]Trader Object
Trading stats of one wallet, built from its exchange fills and redemptions. Market P&L is the net USDC flow in that market (sells and payouts minus buys) plus the tokens still held, valued at the last traded price, or at the payout once the market is resolved.
A market is closed for the wallet once it is resolved or the wallet holds none of its tokens, so exiting early by selling counts. Closed markets give realized_pnl and the win rate; the rest give unrealized_pnl.
| Param | Type | Description |
|---|---|---|
trader | string | Wallet address, lowercase |
total_pnl | number | realized_pnl + unrealized_pnl, USD |
realized_pnl | number | P&L of closed markets (resolved, or fully exited), USD |
unrealized_pnl | number | P&L of markets still held and not resolved, at the last traded price, USD |
volume_usd | number | USDC paid and received in fills |
trades_count | integer | Fills, as taker or maker |
markets_traded | integer | Markets with at least one fill |
open_positions | integer | Outcomes still held in markets that are not resolved |
markets_won | integer | Closed markets with P&L above 0, voided ones excluded |
markets_lost | integer | Closed markets with P&L below 0, voided ones excluded |
win_rate | number | null | markets_won / (markets_won + markets_lost), 0–1. Null until a market is won or lost. |
best_market_pnl | number | null | Best P&L in one closed market, USD |
worst_market_pnl | number | null | Worst P&L in one closed market, USD |
first_trade_at | string (ISO 8601) | First fill |
last_trade_at | string (ISO 8601) | Latest fill |
registered_at | string (ISO 8601) | null | Sign-up in the Lucyd app; null for wallets trading directly on the contract |
nickname | string | null | Public name the owner set in the Lucyd app (set once, never changes); null if none |
GET /positions.API Health
The API is up and reaches its database. Polled by the status page.
curl 'https://api.testnet.lucyd.trade/health'
{
"status": "ok"
}Settlement Health
No market is left unresolved more than 15 minutes past its end. Polled by the status page.
curl 'https://api.testnet.lucyd.trade/health/settlement'
{
"status": "ok",
"overdue": 0
}Live Trades Health
The live trade stream reads the order journal (last read within 30 seconds). Polled by the status page.
curl 'https://api.testnet.lucyd.trade/health/trades-live'
{
"status": "ok",
"seq": 918246,
"clients": 12,
"read_age_secs": 0,
"error": null
}Trading Overview
Orders are placed and matched on the central limit order book (CLOB) at clob.testnet.lucyd.trade. Trading is non-custodial: there are no deposits, funds stay in your wallet and the Exchange contract pulls them with transferFrom when an order is filled. Settlement gas is paid by the exchange. There are no trading fees.
| Endpoint | Purpose |
|---|---|
| wss://clob.testnet.lucyd.trade/v1/ws | Trading: authenticate, submit and cancel orders, receive fills |
| wss://clob.testnet.lucyd.trade/v1/ws/book | Public order book stream |
| https://clob.testnet.lucyd.trade/v1/… | Order book snapshots, your open orders and your order history over HTTP |
Network and contracts
| Name | Value |
|---|---|
| Chain | Ethereum Sepolia, chainId 11155111 |
| Exchange (verifying contract) | 0x6588c789c6b6df8f8b6b92e6433f813cc2d1d4d0 |
| USDC (6 decimals) | 0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238 |
| ConditionalTokens (outcome tokens, ERC-1155) | 0xB62eFc43C16b4E2Bf1aAAD33002368e55708538D |
| AutoRedeemer (pays out winnings) | 0x42Bf669f0A3DCc95510001Ddbc43D56FdE67268F |
Before the first trade
Once per wallet: approve(Exchange, amount) on USDC to buy, and setApprovalForAll(Exchange, true) on ConditionalTokens to sell outcome tokens. Each order is signed by your wallet key (EIP-712), so a standard Ethereum library is all you need: ethers or viem in JavaScript, eth-account in Python.
Optional, for automatic payouts: setApprovalForAll(AutoRedeemer, true) on ConditionalTokens. After a market resolves, winning tokens are redeemed for you and the USDC goes to your wallet. The AutoRedeemer contract has no admin and can only send the payout to the token holder. Without it, claim winnings yourself with redeemPositions(marketId, side, amount) on ConditionalTokens (side 0 = up, 1 = down). To turn it off, call setApprovalForAll(AutoRedeemer, false).
Markets and outcomes
marketId is the market address from GET /markets. Each market has two outcome tokens: up (the YES side) and down (the NO side). Their ids are keccak256(abi.encodePacked(marketId, uint8(0))) for up and uint8(1) for down; the same number is the ERC-1155 token id. One book serves both outcomes: buying down at p is selling up at 1 − p.
Units
| Value | Unit |
|---|---|
| USDC and token amounts | Integers in base units, 6 decimals: 1000000 = 1 USDC or 1 token |
| Price | 0.0025 to 0.9975 in steps of 0.0025 (tick = 0.0025). A winning token pays 1 USDC |
| Order size | Whole tokens only, at least 1 USDC notional |
| Order expiration | Unix seconds |
| Auth and cancel expirations | Unix milliseconds |
| ts field of server messages | Unix microseconds |
Limits
| Limit | Value |
|---|---|
| Message size | 16 KiB |
| Orders per submit_order | 16 |
| Order ids per cancel | 64 |
| Orders per connection | 4096, then reconnect |
| Session length | 15 minutes, then reconnect and authenticate again |
| Markets per book stream | 64 |
Authentication
Right after connecting, the server sends a challenge. Sign it with EIP-712 and reply with authenticate within 30 seconds. All messages are JSON text frames.
{"type":"auth_challenge","protocolVersion":1,"challenge":"0x5f3a…c9","issuedAt":1791300000000,"challengeExpiration":1791300030000,"sessionExpiration":1791300900000,"chainId":11155111,"verifyingContract":"0x6588c789c6b6df8f8b6b92e6433f813cc2d1d4d0","ts":1791300000000123}Signed data
Domain {name: "Exchange WebSocket", version: "1", chainId, verifyingContract}, type below, filled with the exact values of the challenge.
WebSocketAuthV1(uint16 protocolVersion,address account,address signer,bytes32 challenge,uint64 issuedAt,uint64 challengeExpiration,uint64 sessionExpiration)
| Param | Type | Description |
|---|---|---|
protocolVersion | uint16 | 1 |
account | address | Wallet that owns the funds and the orders |
signer | address | Key that signs. Same as account, or a key the account approved with setSigner(signer, true) on the Exchange contract |
challenge | bytes32 | From the challenge message |
issuedAt | uint64 | From the challenge message |
challengeExpiration | uint64 | From the challenge message |
sessionExpiration | uint64 | From the challenge message |
Request
{"type":"authenticate","requestId":"auth-1","account":"0xYourWallet","signer":"0xYourWallet","signature":"0x…65 bytes"}Response
{"type":"authenticated","requestId":"auth-1","account":"0x…","signer":"0x…","sessionExpiration":1791300900000,"ts":1791300000150000}
{"orders":[],"positions":[],"ts":1791300000150100}The second frame lists your open orders (same objects as GET /v1/orders) and positions. A wrong signature returns {"type":"auth_error","code":"invalid_auth"} and a new challenge; after 3 failures the socket closes.
sessionExpiration the server closes the socket with code 1008. Reconnect and authenticate again. requestId is any string of 1–128 bytes and is echoed in the response.Place Orders
An order is signed by your key and sent over the authenticated socket. order is one object or an array of up to 16; each gets its own response, and a batch is not atomic.
{"type":"submit_order","requestId":"r-1","order":{
"protocolVersion":1,
"clOrdId":1,
"settlementOrder":{
"maker":{"kind":"evm","value":"0xYourWallet"},
"signer":{"kind":"evm","value":"0xYourWallet"},
"taker":null,
"outcomeId":"0x…up outcome id",
"side":"buy",
"makerAmount":5500000,
"takerAmount":10000000,
"nonceEpoch":0,
"salt":"0x…32 random bytes"
},
"marketId":"0x…market address",
"timeInForce":"gtc",
"minFillAmount":0,
"expiration":0,
"signature":"0x…65 bytes"
}}This buys 10 up tokens at 0.55: pay 5.5 USDC, receive 10 tokens.
Fields
| Param | Type | Description |
|---|---|---|
clOrdIdrequired | integer | Your own tag, ≥ 1, echoed in events. Not signed |
makerrequired | object | The authenticated account |
signerrequired | object | The authenticated signer |
takerrequired | null | Always null |
outcomeIdrequired | bytes32 | Outcome to buy or sell (see Trading Overview) |
siderequired | string | buy or sell |
makerAmountrequired | integer | What you give: USDC for buy, tokens for sell (base units) |
takerAmountrequired | integer | What you get: tokens for buy, USDC for sell (base units) |
nonceEpochrequired | integer | Your current epoch, 0 unless you advanced it (see Cancel Orders) |
saltrequired | bytes32 | Random, makes every order unique |
marketIdrequired | bytes32 | Market address |
timeInForcerequired | string | gtc rests until filled or canceled; gtd rests until expiration; fak fills what it can now and cancels the rest; fok fills fully now or not at all |
minFillAmountrequired | integer | Always 0 |
expirationrequired | integer | Unix seconds. 0 for gtc, required for gtd, fak and fok |
Price is USDC / tokens and must land exactly on a 0.0025 step. Tokens must be whole (a multiple of 1000000) and USDC at least 1000000. A market order is fak or fok with a limit price you accept and a short expiration.
Order signature
Domain {name: "Exchange", version: "1", chainId: 11155111, verifyingContract: Exchange}. Sign with the wallet key (EOA). Numeric codes: side buy = 0, sell = 1; timeInForce gtc = 0, gtd = 1, fak = 2, fok = 3; taker is the zero address.
SettlementOrderV1(uint16 protocolVersion,address maker,address signer,address taker,bytes32 outcomeId,bytes32 marketId,uint8 side,uint8 timeInForce,uint64 makerAmount,uint64 takerAmount,uint64 minFillAmount,uint64 expiration,uint64 nonceEpoch,bytes32 salt)
The EIP-712 hash of the order is its orderId.
Response
{"type":"accepted","requestId":"r-1","orderId":"0x…","status":"queued","ts":1791300001000000}
{"type":"error","requestId":"r-1","error":"insufficient collateral balance","ts":1791300001000000}accepted means the order is queued for matching; the outcome comes as events (see Order Events). error means it was not queued, except for errors saying the outcome is unknown: then the order may still have been queued.
sell (gtc / gtd) needs tokens bought on this exchange. Tokens from elsewhere can be sold with fak / fok.Cancel Orders
Cancels resting orders by id, up to 64 per request. The request is signed with domain {name: "Exchange WebSocket", version: "1", chainId, verifyingContract}.
{"type":"cancel","requestId":"c-1","orderIds":["0x…"],"account":"0xYourWallet","signer":"0xYourWallet","nonce":1,"expiration":1791300025000,"signature":"0x…"}CancelOrdersV1(uint16 protocolVersion,address account,address signer,bytes32 orderIdsHash,uint64 nonce,uint64 expiration)
| Param | Type | Description |
|---|---|---|
orderIdsHash | bytes32 | keccak256 of the order ids concatenated as 32-byte values, in request order |
nonce | integer | Must grow with every signed request on this connection; start anywhere |
expiration | integer | Unix milliseconds, at most 30 seconds ahead |
Response
{"type":"cancel_result","requestId":"c-1","canceled":["0x…"],"not_canceled":{"0x…":"order_not_resting"},"ts":1791300002000000}Cancel everything
Advancing your nonce epoch cancels all your orders at once. Orders signed with the old epoch are no longer accepted, so sign new ones with nonceEpoch = newEpoch.
{"type":"advance_nonce_epoch","requestId":"e-1","account":"0xYourWallet","signer":"0xYourWallet","newEpoch":1,"nonce":2,"expiration":1791300025000,"signature":"0x…"}AdvanceNonceEpochV1(uint16 protocolVersion,address account,address signer,uint64 newEpoch,uint64 nonce,uint64 expiration)
Response: {"type":"nonce_epoch_advanced","requestId":"e-1","newEpoch":1,"canceledOrders":12}. It shares the nonce counter with cancel.
setNonceEpoch), and a fill settles only when the two match. If you advance it, call setNonceEpoch with the same value on chain.Order Events
After accepted, the server pushes events about your orders over the same socket.
| type | Meaning |
|---|---|
| placed | The order is resting in the book. `quantity` is the resting size |
| trade | A fill. Sent again for each settlement status: MATCHED → MINED → CONFIRMED, or FAILED |
| rejected | The order was refused, see `reasonCode` |
| canceled | A resting order was removed by the exchange (e.g. balance or approval gone) or by your other connection |
| resync_required | Events were lost; the socket closes. Reconnect and reload your orders |
{"type":"trade","sequence":981,"orderId":"0xaaa…","peerOrderId":"0xbbb…","maker":"0x…","taker":"0x…","marketId":"0x…","outcomeId":"0x…up","clOrdId":1,"priceTicks":220,"price":"0.5500","quantity":10000000,"status":"MATCHED","tradeId":"0xaaa…:0xbbb…","ts":1791300003000000}| Param | Type | Description |
|---|---|---|
orderId | bytes32 | Your order |
peerOrderId | bytes32 | The order on the other side |
price | string | priceTicks × 0.0025 |
quantity | integer | Filled tokens, base units |
status | string | MATCHED (matched in the book), MINED (settlement transaction in a block), CONFIRMED (final), FAILED (settlement reverted, the fill is void) |
tradeId | string | Same for all status updates of one fill |
trade events outcomeId and price are always for the up outcome, also when your order was on down. Your down price is 1 − price.placed and rejected go only to the connection that sent the order; trade goes to every connection of the maker and the taker. Events are not replayed after a reconnect: reload open orders with GET /v1/orders and what happened meanwhile with GET /v1/orders/history (see Order History).
Reject codes
| Code | Reason |
|---|---|
| 1 | malformed_message |
| 2 | invalid_order (also expired) |
| 3 | invalid_price |
| 4 | unknown_instrument (market not open) |
| 5 | unknown_outcome |
| 6 | duplicate_order |
| 7 | fok_insufficient_liquidity |
| 8 | sequence_exhausted |
| 9 | internal_error |
| 10 | settlement_failed |
| 11 | insufficient_collateral_balance |
| 12 | insufficient_collateral_allowance |
| 13 | insufficient_outcome_balance |
| 14 | outcome_not_approved |
| 15 | settlement_simulation_reverted |
| 16 | non_current_nonce_epoch |
| 17 | nonce_epoch_order_limit |
| 18 | order_notional_below_minimum |
| 19 | quantity_not_whole_tokens |
Order History
Your orders, newest first, with what happened to each: filled, canceled, expired, rejected with a reason, or a fill whose settlement failed. Signed with the same headers as GET /v1/orders (see Order Book (HTTP)); targetHash covers the exact path and query string, e.g. keccak256("GET\n/v1/orders/history?status=filled&limit=50"). Send the query exactly as signed.
Query parameters
| Param | Type | Description |
|---|---|---|
market | string | Market ids, comma-separated, up to 50 |
outcome | string | Outcome ids, comma-separated, up to 50 |
side | string | buy or sell |
status | string | Current statuses, comma-separated (table below); all when omitted |
from | integer | Placed at or after, Unix seconds |
to | integer | Placed before, Unix seconds |
limit | integer | 1–500, default 100 |
cursor | string | nextCursor of the previous page |
events | boolean | true adds each order's events; default false |
{"orders":[{"orderId":"0x…","clOrdId":1,"marketId":"0x…","outcomeId":"0x…","side":"BUY","timeInForce":"GTC","makerAmount":5500000,"takerAmount":10000000,"expiration":0,"filledQuantity":10000000,"status":"settled","statusReasonCode":null,"statusReason":null,"receivedAt":1791300001000,"updatedAt":1791300009000}],"nextCursor":"1791300001000000_8812"}Keep passing nextCursor as cursor until it is null. filledQuantity is the filled tokens (base units) minus fills whose settlement failed. Times are Unix milliseconds.
Order status
| status | Meaning |
|---|---|
| received | Accepted, not processed by the book yet |
| resting | In the book, possibly partly filled (also listed by `GET /v1/orders`) |
| filled | Fully filled in the book, settlement on chain in progress |
| settled | Fully filled and every fill confirmed on chain |
| cancelled | Canceled: by you, the unfilled rest of `fak` / `fok`, an epoch advance, or the market closed. Part may have filled, see `filledQuantity` |
| expired | `gtd` order reached its expiration |
| rejected | Refused; `statusReason` says why (reject codes in Order Events) |
| settlement_failed | A fill was voided because its settlement transaction failed |
Events
With events=true every order has events, oldest first. One order with all its events: GET /v1/orders/{orderId} (404 if it is not yours).
{"id":8812,"type":"matched","time":1791300003000,"reasonCode":null,"reason":null,"tradeId":"0xaaa…:0xbbb…","peerOrderId":"0xbbb…","role":"taker","amount":10000000,"remaining":0,"priceTicks":220,"txHash":null,"blockNumber":null}| type | Meaning |
|---|---|
| received | The order was accepted; `remaining` is its full size |
| resting | Placed in the book; `remaining` is the resting size |
| matched | One fill: `amount`, `remaining` after it, `priceTicks`, `role` (taker or maker), `tradeId` |
| settlement_confirmed | The fill settled on chain: `txHash`, `blockNumber` |
| settlement_failed | The fill was voided, its tokens and USDC did not move |
| cancelled | `amount` canceled, `reason` why |
| expired | `amount` that expired |
| rejected | `reasonCode` and `reason` |
priceTicks × 0.0025 is the price, for the up outcome as in Order Events.
Order Book (HTTP)
Public, no authentication. asset_id is an outcome id (0x hex or the decimal ERC-1155 token id). Errors are {"error": "…"}.
| Endpoint | Returns |
|---|---|
| GET /v1/book?asset_id= | Bids (best first) and asks, sizes in base units, plus tick_size |
| GET /v1/prices?asset_id= | best_bid, best_ask, mid (null when a side is empty) |
| GET /v1/spread?asset_id= | best_ask − best_bid |
| GET /v1/tick-size?asset_id= | Price step, "0.0025" |
| GET /v1/bookL3?asset_id= | Every resting order: order_id, price, size, original_size |
curl 'https://clob.testnet.lucyd.trade/v1/book?asset_id=0x…up outcome id'
{"market":"0x…","asset_id":"0x…","bids":[{"price":"0.5400","size":"8000000"}],"asks":[{"price":"0.5600","size":"12000000"}],"tick_size":"0.0025"}Your open orders
Signed with headers, no query parameters. Domain {name: "Exchange HTTP", version: "1", chainId, verifyingContract}.
HttpGetRequestV1(uint16 protocolVersion,address account,address signer,bytes32 targetHash,uint64 nonce,uint64 expiration)
| Param | Type | Description |
|---|---|---|
X-Exchange-Account | header | Your wallet |
X-Exchange-Signer | header | Signing key |
X-Exchange-Nonce | header | Any integer |
X-Exchange-Expiration | header | Unix milliseconds, at most 30 seconds ahead |
X-Exchange-Signature | header | Signature; targetHash = keccak256("GET\n/v1/orders"), protocolVersion 1 |
[{"orderId":"0x…","clOrdId":1,"marketId":"0x…","outcomeId":"0x…","side":"BUY","timeInForce":"GTC","makerAmount":5500000,"takerAmount":10000000,"remainingQuantity":10000000,"minFillAmount":0,"expiration":0,"nonceEpoch":0}]Order Book Stream
Public L2 book over WebSocket, no authentication. Subscribe by market id (up to 64 per connection).
{"type":"subscribe","requestId":"s-1","marketIds":["0x…market address"]}The server answers subscribed, then sends a book snapshot for each outcome (up and down):
{"type":"book","market":"0x…","asset_id":"0x…up","bids":[{"price":"0.5500","size":"10000000"}],"asks":[],"tick_size":"0.0025","ts":1791300004000000}On every change it sends both snapshots again, followed by price_change with the changed levels. size is the new total at that price; "0" means the level is gone.
{"type":"price_change","market":"0x…","price_changes":[{"asset_id":"0x…up","side":"BID","price":"0.5500","size":"6000000"},{"asset_id":"0x…down","side":"ASK","price":"0.4500","size":"6000000"}],"ts":1791300004100000}Stop with {"type":"unsubscribe","requestId":"u-1","marketIds":[…]}. When a market closes it stops trading; take open markets from GET /markets?state=open.
Series
Instead of looking up each new round, subscribe to a series. The server sends the open market of the series right away (or subscribed_series if there is none yet), then open_markets again each time the next round opens, and expired when a round ends. It does not send books by itself: subscribe to each new market by marketIds as above.
{"type":"subscribe_series","requestId":"s-5m","market_type":"UpDown","period":"5m","instrument":"BTC"}{"type":"open_markets","requestId":"s-5m","markets":[{"marketId":"0x…","leftOutcomeId":"0x…up","leftOutcomeName":"up","rightOutcomeId":"0x…down","rightOutcomeName":"down"}],"ts":1791300000000000}
{"type":"expired","marketIds":["0x…"],"ts":1791300300000000}| Param | Type | Description |
|---|---|---|
market_type | string | UpDown |
period | string | 5m, 15m, 30m, 1h or 4h. Daily rounds are not in the series feed: take them from GET /markets?state=open&period=Daily |
instrument | string | BTC |
marketId is address in GET /markets; the strike and end time come from there. Stop with unsubscribe_series and the same fields; the server answers unsubscribed_series.
Example (Python)
Connects, authenticates, buys 10 up tokens at 0.55 on the current 5m market and cancels the order. Needs pip install websockets eth-account requests and USDC approved to the Exchange contract.
import asyncio, json, os, secrets, time
import requests, websockets
from eth_account import Account
from eth_utils import keccak
KEY = os.environ["PRIVATE_KEY"]
ME = Account.from_key(KEY).address
CHAIN_ID = 11155111
EXCHANGE = "0x6588c789c6b6df8f8b6b92e6433f813cc2d1d4d0"
def fields(spec):
return [{"name": n, "type": t} for t, n in (f.split() for f in spec.split(","))]
AUTH = fields("uint16 protocolVersion,address account,address signer,bytes32 challenge,"
"uint64 issuedAt,uint64 challengeExpiration,uint64 sessionExpiration")
ORDER = fields("uint16 protocolVersion,address maker,address signer,address taker,bytes32 outcomeId,"
"bytes32 marketId,uint8 side,uint8 timeInForce,uint64 makerAmount,uint64 takerAmount,"
"uint64 minFillAmount,uint64 expiration,uint64 nonceEpoch,bytes32 salt")
CANCEL = fields("uint16 protocolVersion,address account,address signer,bytes32 orderIdsHash,"
"uint64 nonce,uint64 expiration")
def sign(domain, type_name, types, message):
signed = Account.sign_typed_data(
KEY,
domain_data={"name": domain, "version": "1", "chainId": CHAIN_ID, "verifyingContract": EXCHANGE},
message_types={type_name: types},
message_data=message,
)
return "0x" + bytes(signed.signature).hex()
async def wait_for(ws, *types):
while True:
msg = json.loads(await ws.recv())
print(msg)
if msg.get("type") in types:
return msg
async def main():
market = requests.get("https://api.testnet.lucyd.trade/markets",
params={"state": "open", "period": "5m", "limit": 1}).json()[0]["address"]
up = "0x" + keccak(bytes.fromhex(market[2:]) + b"\x00").hex()
async with websockets.connect("wss://clob.testnet.lucyd.trade/v1/ws") as ws:
# 1. authenticate
ch = await wait_for(ws, "auth_challenge")
sig = sign("Exchange WebSocket", "WebSocketAuthV1", AUTH, {
"protocolVersion": 1, "account": ME, "signer": ME, "challenge": ch["challenge"],
"issuedAt": ch["issuedAt"], "challengeExpiration": ch["challengeExpiration"],
"sessionExpiration": ch["sessionExpiration"]})
await ws.send(json.dumps({"type": "authenticate", "requestId": "auth-1",
"account": ME, "signer": ME, "signature": sig}))
await wait_for(ws, "authenticated", "auth_error")
# 2. buy 10 up tokens at 0.55 (pay 5.5 USDC)
order = {"protocolVersion": 1, "maker": ME, "signer": ME,
"taker": "0x0000000000000000000000000000000000000000",
"outcomeId": up, "marketId": market, "side": 0, "timeInForce": 0,
"makerAmount": 5_500_000, "takerAmount": 10_000_000, "minFillAmount": 0,
"expiration": 0, "nonceEpoch": 0, "salt": "0x" + secrets.token_hex(32)}
await ws.send(json.dumps({"type": "submit_order", "requestId": "r-1", "order": {
"protocolVersion": 1, "clOrdId": 1,
"settlementOrder": {
"maker": {"kind": "evm", "value": ME}, "signer": {"kind": "evm", "value": ME},
"taker": None, "outcomeId": up, "side": "buy",
"makerAmount": order["makerAmount"], "takerAmount": order["takerAmount"],
"nonceEpoch": 0, "salt": order["salt"]},
"marketId": market, "timeInForce": "gtc", "minFillAmount": 0, "expiration": 0,
"signature": sign("Exchange", "SettlementOrderV1", ORDER, order)}}))
accepted = await wait_for(ws, "accepted", "error")
if accepted["type"] == "error":
return
await wait_for(ws, "placed", "trade", "rejected")
# 3. cancel it
order_id = accepted["orderId"]
expiration = int(time.time() * 1000) + 20_000
sig = sign("Exchange WebSocket", "CancelOrdersV1", CANCEL, {
"protocolVersion": 1, "account": ME, "signer": ME,
"orderIdsHash": "0x" + keccak(bytes.fromhex(order_id[2:])).hex(),
"nonce": 1, "expiration": expiration})
await ws.send(json.dumps({"type": "cancel", "requestId": "c-1", "orderIds": [order_id],
"account": ME, "signer": ME, "nonce": 1,
"expiration": expiration, "signature": sig}))
await wait_for(ws, "cancel_result", "error")
asyncio.run(main())