{
"method": "subscribe",
"subscription": {
"type": "capitalAccount",
"capital_account_id": "00000000-0000-4000-8000-000000000001"
}
}
Connect from a server-side client to wss://trading-api.legend.trade/v1/ws. Set the HTTP handshake header Authorization: Bearer lg_trade_… with a key that has trading:read. Get your Capital account ID from GET /v1/capital/accounts. Use the API key guide to register a key.
Add ?capital_account_id=<uuid> to select an account in the handshake, or send this message after you receive connected.
{
"method": "subscribe",
"subscription": {
"type": "capitalAccount",
"capital_account_id": "00000000-0000-4000-8000-000000000001"
}
}
Each connection streams one Capital account at a time. A successful subscription replaces the current account and sends subscribed. Send {"method":"unsubscribe"} to stop the current subscription. Use {"method":"ping"} to request a JSON pong.
The type field identifies the event. seq increases by one for each message on the connection and starts again at one when you reconnect. Account events include capital_account_id. When snapshot is true, the event contains initial state.
| Event | Data |
|---|---|
account.updated | A balance update with equity, withdrawable funds, and perpetual margin by DEX, or an update with spot balances. Merge these fields into your account state. |
positions.snapshot | The current positions. Each position has a market, signed size, entry price, unrealized PnL, and margin data. |
position.opened, position.updated, position.closed, position.liquidated | A position change. Close events give the market. Liquidation events give the market and fill ID. |
orders.snapshot | The current open orders. |
order.created, order.updated, order.triggered, order.partially_filled, order.filled, order.canceled, order.rejected | An update with the exchange order ID, market, side, price, size, remaining size, and status. |
fill.created | A live fill with an ID, exchange order ID, market, side, price, size, fee, closed PnL, and execution time. |
The server sends a WebSocket ping every 20 seconds. Use a client library that replies with a WebSocket pong. The limit is five connections per user across keys and 30 client messages per second per connection. The server closes a connection if its output buffer exceeds 1 MiB.
The stream has no replay cursor. After a disconnect, reconnect with backoff and use REST account, order, position, and fill reads to catch up. Deduplicate fills by ID. The server checks the key and account access again while the connection is open. An invalid or expired key returns HTTP 401 at the handshake. A key without permission returns 403, an unavailable account returns 404, and the connection limit returns 429.
Use each orders.snapshot and positions.snapshot to replace your local order and position state. fill.created includes live fills only. Use GET /v1/fills with capital_account_id for fill history. On close codes 1012 or 1013, reconnect with backoff. On 4401 or 4403, check the API key and Capital account access before reconnecting. On 4408, check your heartbeat and message rate.
Install ws and use it in a Node.js process. Set LEGEND_TRADING_API_KEY and LEGEND_CAPITAL_ACCOUNT_ID in that process.
import WebSocket from 'ws'
const url = new URL('wss://trading-api.legend.trade/v1/ws')
url.searchParams.set('capital_account_id', process.env.LEGEND_CAPITAL_ACCOUNT_ID!)
const socket = new WebSocket(url, {
headers: { Authorization: `Bearer ${process.env.LEGEND_TRADING_API_KEY}` },
})
socket.on('message', (message) => console.log(JSON.parse(message.toString())))
socket.on('close', (code) => console.log(code))
socket.on('error', (error) => console.error(error))
Install websockets and set the same two environment variables.
import asyncio
import json
import os
from urllib.parse import urlencode
from websockets.asyncio.client import connect
async def main():
query = urlencode({"capital_account_id": os.environ["LEGEND_CAPITAL_ACCOUNT_ID"]})
url = f"wss://trading-api.legend.trade/v1/ws?{query}"
headers = {"Authorization": f"Bearer {os.environ['LEGEND_TRADING_API_KEY']}"}
async with connect(url, additional_headers=headers) as socket:
async for message in socket:
print(json.loads(message))
asyncio.run(main())