Introduction
The Backtest API runs your own bot, in any language, against recorded Open Trade history. A backtest session serves the same WebSocket channels and REST paths as the live API, against a simulated clock and a simulated account, so the code that trades live is the code you test.
channelArgs and data classes are the live ones, described on the Market Data API, Private Data API and REST API pages. This page covers what a session adds and where it differs.
How a backtest runs
- Create a session with
POST /sessions: the window, pairs and venues, and the balances you start with. - Open the session's WebSocket and subscribe, exactly as on live.
- Call
start. The clock sits at the start of the window. - Read a step, act on it, send
STEP. Repeat until the session reportsFINISHED. - Read the report with
GET /sessions/{id}/result. The run stays in your Runs list.
Differences from Live
| Topic | Live | Backtest session |
|---|---|---|
| Addresses | …/hermes-ws-gateway | The session base, …/hermes-backtest/s/{sessionId} |
| Token | scopes=API_ACCESS | scopes=BACKTEST_ACCESS; a live token is refused, and so is a backtest token on live |
| Time | Wall clock | A simulated clock framed by BACKTEST_CLOCK; your bot advances it with STEP |
| Order book | Several levels a side, re-sent in full | One level a side, sent at the end of each step in which the top changed, labelled source: BOOKS_TOP or LAST_PRINT |
| Balances | Your account | The per-venue balances you give at create |
| Orders | Sent to the venue | Arrive after the session's latency and fill against the recorded trades of each venue |
| Stops | BUY_STOP, SELL_STOP, STOP_LOSS, TAKE_PROFIT | BUY_STOP and SELL_STOP trigger at price, as on live; the order has no separate trigger field. A buy stop triggers on the first recorded print above price, a sell stop on the first print below it, and then trades as a market order. STOP_LOSS and TAKE_PROFIT are rejected UNSUPPORTED_ORDER_TYPE |
| SMART orders | Split across venues by price and balance | The same split over the session's venues, by the one-level book and your free balance at each venue |
| Rejections | Free text in message | The reason code first, then the text: PRICE_OFF_TICK: … |
| Order ids | clientOrderId optional; a CANCEL without one cancels every order on the pair | Every CREATE must carry a clientOrderId, used once per session, and UPDATE and CANCEL name one order by it. An order without one is refused with ERROR; there is no cancel by pair or by exchangeOrderId |
| Money moves | Deposits, transfers, withdrawals, Yield | Not served; the channels answer ERROR |
| Extra REST | — | public/instrument-specs, sessions only. public/candles is also served live, where exchange defaults to OPENTRADE; in a session it is required and names a venue |
Base URLs
Control API
Session addresses
Each session has its own base, returned by POST /sessions as baseUrl, restBase and wsUrl. The session base replaces the live …/hermes-ws-gateway.
| What | Address |
|---|---|
| Session base | https://gateway-public.opentrade.exchange/hermes-backtest/s/{sessionId} |
| Live REST in the session | {session base}/api/rest/… (live: …/hermes-ws-gateway/api/rest/…) |
| WebSocket | wss://gateway-public.opentrade.exchange/hermes-backtest/s/{sessionId}/ws |
404, never 403. The sessionId is also the id of the run the session produces. Every address is served by the public gateway under /hermes-backtest/**.
Authentication
A backtest uses the same API key and the same two-step login as live, and asks for a backtest token.
Before You Start: Give the Key Backtesting Access
Under Account → API Keys, tick Backtesting when you create the key. One key may carry both Live API and Backtesting access, and a key with Backtesting alone is allowed; it cannot trade live. Backtesting moves no money, so no key needs the Trade permission to backtest.
Step 1: Login with the API Username and Password
POST https://auth.opentrade.exchange/login
// Form Data (lowercase keys)
username: {api-username}
password: {password}
Step 2: Obtain a Backtest Token
Ask for the BACKTEST_ACCESS scope. The client secret travels as a header, and the body is empty.
POST https://auth.opentrade.exchange/auth/jwt/clients/{api-username}/token?scopes=BACKTEST_ACCESS
// Headers
Cookie: SESSION={session_cookie_from_step_1}
clientSecret: {secret}
// Body: empty
curl -s --cookie-jar cookies.txt -X POST \
"https://auth.opentrade.exchange/login" \
-d "username=[API_USERNAME]&password=[PASSWORD]" \
-o /dev/null -w "login redirected to %{redirect_url}\n" \
--next -s -b cookies.txt -X POST \
"https://auth.opentrade.exchange/auth/jwt/clients/[API_USERNAME]/token?scopes=BACKTEST_ACCESS" \
-H "clientSecret: [SECRET]" \
-d ""
The response body is the token, already prefixed Bearer eyJ.... Send it as the Authorization header on every control and session REST call and on the WebSocket upgrade, and as signature on private WebSocket messages, as on live. Read jwt-expire-at and mint a new token before it passes; the Python SDK refreshes at 80% of the token's life.
| Token | Backtest API | Live API |
|---|---|---|
scopes=BACKTEST_ACCESS | Accepted | Refused: REST 401, the live socket refuses the upgrade |
scopes=API_ACCESS | Refused with 403, on REST and on the socket upgrade. The public gateway refuses it before the service, so the response carries no code; a live token that reaches the service answers 403 WRONG_AUDIENCE on REST and 401 on the upgrade | Accepted |
| Both scopes in one request | — | 400 SCOPES_NOT_COMBINABLE: a token is always either live or backtest |
Authorization on a WebSocket, and the session accepts no token in the query string, which would leak into logs. Run bots from Node, Python or any language whose WebSocket client sets headers.
Limits
These limits apply to every account.
| Limit | Value |
|---|---|
| Gateway rate limit | 600 requests a minute per account on /hermes-backtest/**, bursts of 50. Over it: 429 with Retry-After and no code |
| Window | At most 366 days, else 400 WINDOW_TOO_LONG |
| Pairs and venues per session | At most 10 pairs and 7 venues, SPOT only |
| Sockets per session | 2. A third upgrade is refused with 429 |
| Start deadline | 15 minutes after create (startBy), or the session ends CANCELLED with failureReason: NOT_STARTED |
| Abandoned | 10 minutes with no socket open and no step, stop, order call or status request ends a running session CANCELLED with failureReason: ABANDONED |
| Wall time | 24 hours after start the session is stopped and ends FINISHED with failureReason: WALL_TIME_LIMIT; its report is kept |
| Idle advance | 5 seconds of wall time by default (clock.idleAdvanceMs); see Clock Modes |
| Service load | The service runs at most 8 sessions at once. Over that, create answers 503 ENGINE_BUSY with Retry-After: 30 |
Errors
Every refusal from the control API and the session REST has the same body:
{
"code": "INVALID_PARAMETER",
"message": "a session's window has to end after it starts",
"field": "window"
}
Every refusal from the service has code and message; the other fields depend on the code. message is free text for people; branch on code. A request refused before the service reads it, such as malformed JSON, a value of the wrong type or a missing required query parameter, answers 400 with a standard error body and no code, and refusals by the gateway carry none either.
| HTTP | code | When |
|---|---|---|
| 400 | INVALID_PARAMETER (+field), UNKNOWN_PAIR, WINDOW_TOO_LONG, NO_DATA (+missing: [{venue, pair, dataset, days}]) | Validation, or recorded history the window needs is missing |
| 401 | — | No token, or a bad one |
| 403 | WRONG_AUDIENCE, or no body | A live token. Mint one with scopes=BACKTEST_ACCESS. The public gateway refuses a live token itself, with a bare 403; a live token that reaches the service answers WRONG_AUDIENCE on REST and 401 on the socket upgrade |
| 403 | NOT_PERMITTED | The key has no Backtesting access |
| 404 | SESSION_NOT_FOUND, RUN_NOT_FOUND | Unknown, or another account's |
| 404 | NOT_IN_BACKTEST | A live REST path a session does not serve |
| 409 | SESSION_NOT_CREATED | start or cancel on a session that is not CREATED, such as a second start |
| 409 | SESSION_NOT_RUNNING | step or stop on a session that is not RUNNING; session REST and the socket upgrade once the session has ended |
| 409 | RESULT_NOT_READY | result on a session that is not FINISHED. For a CANCELLED or FAILED session this never changes; read the run with GET /runs/{id} |
| 409 | CLOCK_NOT_STEP_LOCKED | step on a FAST session |
| 409 | FEE_BRACKET_UNDECIDED | clientFee.basis: ACCOUNT while your fee bracket for the month is still being decided |
| 429 | (no code; Retry-After) | Gateway rate limit |
| 503 | ENGINE_BUSY (+Retry-After: 30) | The service already runs its 8 sessions |
| 503 | SESSION_BUSY | The session has more commands waiting than it holds; send the call again shortly |
| 503 | UNAVAILABLE | The results store, the recorded history, your fee profile or the access rules cannot be read just now |
Validates the request, checks the recorded history, resolves limits and fees, and builds the session without starting its clock. Returns 201.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
Request Body
| Field | Type | Required | Rule |
|---|---|---|---|
| window.from | string | Yes | UTC ISO-8601 instant |
| window.to | string | Yes | After from, and at most 366 days after it (else WINDOW_TOO_LONG). The length must also fit what is left of SIMULATED_DAYS_MONTH |
| pairs | array | Yes | {pair, venues[]}. SPOT only, at most 10 pairs and 7 venues; the same pair twice at one venue is refused. A pair with no recorded history at a venue answers UNKNOWN_PAIR |
| balances | array | Yes | {venue, asset, amount}, amounts > 0 as decimal strings. Every venue in pairs needs a row, every row's venue must trade one of the pairs, and an asset appears once per venue |
| name | string | Optional | Shown in the Runs list |
| fillModel | object | Optional | model: TRADE_THROUGH (default; needs raw trades on every day, else 400 NO_DATA) or CANDLE_THROUGH (needs one-minute bars). participation default 0.01, slippageBps default 0, both decimal strings |
| clientFee | object | Optional | basis: ACCOUNT (default; your own fee bracket, billed as your own trading), VENUE_ONLY (no client fee), TIER + tierCd, or CUSTOM_BPS + bps from 0 to 1000 |
| latency | object | Optional | orderMs (80), reportMs (20), jitterMs (0); each 0–5000 |
| clock | object | Optional | mode: STEP_LOCKED (default) or FAST; stepMs (1000), from 1 ms to one day; idleAdvanceMs (5000), 0 or more, where 0 never steps for you |
| book.source | string | Optional | AUTO (default: the recorded top of book where fresh, else the last print on each side) or LAST_PRINT. A generated market always uses LAST_PRINT |
| instrumentLimits | array | Optional | Your own tick size, amount step and minimum per venue and pair. Otherwise the venue's limits on the window's first day (for a generated market, the day before it), else the newest recorded, else inferred from the recorded trades |
| seed | integer | Optional | Feeds the latency jitter and, with a generated market, the generated path; everything else is deterministic. Default 0. Run the same settings with several seeds, under one pathSet, to see a strategy across several generated markets |
| market | object | Optional | source: RECORDED (default: the market as it was recorded) or GENERATED (a market drawn from the Shestakov market model, fitted on the 90 days recorded before window.from). With GENERATED: generator is STUDENT_T (default, fat-tailed shocks), GAUSSIAN (normal shocks) or BOOTSTRAP (past shocks resampled); drift is NONE (default) or HISTORICAL. A generated market takes one pair at one venue, starts on a whole minute no later than now, and lasts at least a minute; trade sizes, limits and fees come from the day before window.from |
| pathSet | string | Optional | Groups this session with others that differ only by seed: 1 to 64 letters, digits, - or _. A session whose other settings or market differ from the set's runs is refused with 400 INVALID_PARAMETER, field: pathSet, naming the settings that differ. GET /runs shows a set once, with the spread of its outcomes |
{
"name": "grid BTC 3m",
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-09-15T00:00:00Z"
},
"pairs": [
{
"pair": "BTC/USDT",
"venues": [
"HUOBI",
"OKEX",
"BITGET"
]
}
],
"balances": [
{
"venue": "HUOBI",
"asset": "USDT",
"amount": "20000"
},
{
"venue": "OKEX",
"asset": "USDT",
"amount": "20000"
},
{
"venue": "BITGET",
"asset": "USDT",
"amount": "20000"
}
],
"fillModel": {
"model": "TRADE_THROUGH",
"participation": "0.01",
"slippageBps": "0"
},
"clientFee": {
"basis": "ACCOUNT"
},
"latency": {
"orderMs": 80,
"reportMs": 20,
"jitterMs": 0
},
"clock": {
"mode": "STEP_LOCKED",
"stepMs": 1000,
"idleAdvanceMs": 5000
},
"book": {
"source": "AUTO"
},
"instrumentLimits": [],
"seed": 7
}
{
"sessionId": 812,
"status": "CREATED",
"baseUrl": "https://gateway-public.opentrade.exchange/hermes-backtest/s/812",
"restBase": "https://gateway-public.opentrade.exchange/hermes-backtest/s/812/api/rest",
"wsUrl": "wss://gateway-public.opentrade.exchange/hermes-backtest/s/812/ws",
"startBy": "2026-09-25T10:15:00Z",
"parameters": {
"window-from": "2026-06-15T00:00:00Z",
"window-to": "2026-09-15T00:00:00Z",
"pairs": "BTC/USDT@HUOBI,OKEX,BITGET",
"balances": "HUOBI:USDT=20000;OKEX:USDT=20000;BITGET:USDT=20000",
"fill-model": "TRADE_THROUGH",
"participation": "0.01",
"slippage-bps": "0",
"client-fee": "ACCOUNT",
"latency-order-ms": "80",
"latency-report-ms": "20",
"latency-jitter-ms": "0",
"clock-mode": "STEP_LOCKED",
"step-ms": "1000",
"idle-advance-ms": "5000",
"book-source": "AUTO",
"instrument-limits": "",
"seed": "7"
},
"parametersHash": "9f1c07d2b85e4a3c6f01d7e29a4b8c35e6f7a0b1c2d3e4f5061728394a5b6c7d",
"datasetVersion": "a41e33b07c5d2f98e1b6a3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708",
"engineVersion": "2.0.412",
"instruments": [
{
"venue": "OKEX",
"pair": "BTC/USDT",
"tickSize": "0.1",
"amountStep": "0.00000001",
"minAmount": "0.00001",
"source": "VENUE_SNAPSHOT",
"appliedFrom": "2026-06-15"
}
],
"fees": {
"venues": [
{
"venue": "OKEX",
"maker": "-0.0008",
"taker": "-0.001"
}
],
"client": {
"basis": "ACCOUNT",
"rate": "-0.0005",
"source": "FEE_PROFILE"
}
},
"warnings": [
{
"code": "NO_BOOKS",
"venue": "OKEX",
"pair": "BTC/USDT",
"detail": "books_top not recorded in the window; the book is the last print on each side"
}
]
}
| Field | Description |
|---|---|
| parameters | Every setting the session runs with, defaults filled in, as a flat map of strings. parametersHash is its hash; two runs with the same hash, datasetVersion and engineVersion were given the same inputs |
| instruments | Tick size, amount step and minimum per venue and pair, as Instrument Specs serves them |
| fees | The venue maker and taker rates and the client fee rate the session charges, with where the client rate came from: FEE_PROFILE, FEE_TIER or RUN_CONFIG |
| warnings | {code, venue, pair, detail}: NO_BOOKS, PARTIAL_BOOKS, LIMITS_INFERRED or MODEL_FIT_POOR (the generated market missed the recorded one on a graded measure; see market.grade in the result) |
| startBy | Start before this, or the session ends CANCELLED with failureReason: NOT_STARTED |
fees, on every fill and in the report. Client fees are charged in the asset the fill delivers.
Moves the session from CREATED to RUNNING. The clock sits at window.from and the server sends one BACKTEST_CLOCK END with seq 0, which your first STEP answers. Subscriptions made before start are kept, so subscribe first.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
{
"sessionId": 812,
"status": "RUNNING",
"name": "grid BTC 3m",
"clock": {
"mode": "STEP_LOCKED",
"simTime": "2026-06-15T00:00:00.000Z",
"simTimeMs": 1781481600000,
"seq": 0,
"idleAdvances": 0
},
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-09-15T00:00:00Z"
},
"progress": 0.0,
"eventsReplayed": 0,
"orders": 0,
"fills": 0,
"nav": "60000",
"navAsset": "USDT",
"connectedSockets": 1,
"warnings": [],
"reportReady": false,
"failureReason": null
}
The session's state, simulated clock and progress.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
{
"sessionId": 812,
"status": "RUNNING",
"name": "grid BTC 3m",
"clock": {
"mode": "STEP_LOCKED",
"simTime": "2026-07-02T11:00:05.000Z",
"simTimeMs": 1782990005000,
"seq": 1552001,
"idleAdvances": 0
},
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-09-15T00:00:00Z"
},
"progress": 0.1897651217793881,
"eventsReplayed": 8812003,
"orders": 4210,
"fills": 3977,
"nav": "60812.55",
"navAsset": "USDT",
"connectedSockets": 1,
"warnings": [],
"reportReady": false,
"failureReason": null
}
| State | Meaning |
|---|---|
CREATED | Built, not started |
RUNNING | The clock is running |
FINISHED | Replayed to window.to, stopped, or stopped by a limit. The report is ready |
CANCELLED | Ended before it could finish. What it replayed is kept as a run under /runs/{id}; result answers 409 RESULT_NOT_READY |
FAILED | The replay, or the service running it, failed. As for CANCELLED, read the run under /runs/{id} |
failureReason is free text, null when the session replayed to window.to or you stopped it. These values are fixed words you can match on:
| failureReason | State | Meaning |
|---|---|---|
NOT_STARTED | CANCELLED | Not started within 15 minutes of create |
ABANDONED | CANCELLED | 10 minutes with no socket open and no step, stop, order call or status request |
WALL_TIME_LIMIT | FINISHED | Stopped after 24 hours of wall time |
NOT_KEPT | CANCELLED | The run could not be recorded when the session started; start answers 404 SESSION_NOT_FOUND |
SERVICE_RESTARTED | FAILED | The service restarted while the session was open |
DELETED | FINISHED or CANCELLED | The run was deleted while the session was open |
CANCELLED_BY_CLIENT | CANCELLED | You cancelled the session before it started, with POST /sessions/{id}/cancel |
Any other value is an error message, for example on a FAILED replay: the replay failed: …. Once a session has ended, its status is read from the stored run: clock.seq and connectedSockets are then 0.
The REST form of the WebSocket STEP, for bots that do not hold a socket. Step-locked sessions only. The response carries the step's closing clock and every frame the step produced except the clock frames; sockets on the session receive the same step as usual.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
| until | string | Optional | ISO-8601 instant to step to |
| advanceMs | integer | Optional | Milliseconds to step, 1 or more, when until is absent. With neither, one stepMs |
| wakeOnPrivate | boolean | Optional | End the step early at the first private report. Default true |
{
"advanceMs": 5000,
"wakeOnPrivate": true
}
The clock ended the last step at 2026-06-15T00:00:01Z, so advanceMs: 5000 runs to 00:00:06. A step always moves the clock on by at least 1 ms and never past window.to; the step that reaches window.to finishes the session.
{
"clock": {
"phase": "END",
"seq": 2,
"simTime": "2026-06-15T00:00:06.000Z",
"simTimeMs": 1781481606000,
"stepTo": "2026-06-15T00:00:06.000Z",
"mode": "STEP_LOCKED"
},
"events": [
{
"event": "UPDATE",
"channel": "TRADE_PUBLIC",
"data": [
{
"class": "PublicTrade",
"exchange": "HUOBI",
"symbol": "BTC/USDT",
"price": 104212.3,
"quantity": 0.004,
"tradeSide": "BUY",
"eventTime": 1781481603412
}
]
}
]
}
Ends the run at the current simulated time and writes the report, orders and fills. Answers the status, now FINISHED. A bot that raises an error should call it, as the Python SDK does.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
{
"sessionId": 812,
"status": "FINISHED",
"name": "grid BTC 3m",
"clock": {
"mode": "STEP_LOCKED",
"simTime": "2026-07-02T11:00:05.000Z",
"simTimeMs": 1782990005000,
"seq": 1552001,
"idleAdvances": 0
},
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-09-15T00:00:00Z"
},
"progress": 0.1897651217793881,
"eventsReplayed": 8812003,
"orders": 4210,
"fills": 3977,
"nav": "60812.55",
"navAsset": "USDT",
"connectedSockets": 1,
"warnings": [],
"reportReady": true,
"failureReason": null
}
Cancels a session that has not been started and frees its concurrent-session slot at once. Answers the status, now CANCELLED with failureReason CANCELLED_BY_CLIENT. Any other session is refused with 409 SESSION_NOT_CREATED and left as it is, so a bot can call it safely when its socket could not be opened, or when stop is refused because the session never started. A socket still open on the session receives the CANCELLED status and is closed.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
The report, once the session is FINISHED; before that, 409 RESULT_NOT_READY. Money is in decimal strings and fees are signed.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
{
"sessionId": 812,
"runId": 812,
"status": "FINISHED",
"name": "grid BTC 3m",
"reproducible": true,
"reproducibleReason": null,
"parametersHash": "9f1c07d2b85e4a3c6f01d7e29a4b8c35e6f7a0b1c2d3e4f5061728394a5b6c7d",
"datasetVersion": "a41e33b07c5d2f98e1b6a3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708",
"engineVersion": "2.0.412",
"seed": 7,
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-09-15T00:00:00Z"
},
"simulatedTo": "2026-09-15T00:00:00Z",
"navAsset": "USDT",
"metrics": [
{
"scope": "OVERALL",
"scopeKey": "ALL",
"metric": "PNL",
"value": "812.55",
"assetCd": null
},
{
"scope": "BENCHMARK",
"scopeKey": "ALL",
"metric": "PNL",
"value": "406.1",
"assetCd": null
},
{
"scope": "VENUE",
"scopeKey": "OKEX",
"metric": "FEE",
"value": "-0.000008",
"assetCd": "BTC"
},
{
"scope": "VENUE",
"scopeKey": "OKEX",
"metric": "CLIENT_FEE",
"value": "-0.000005",
"assetCd": "BTC"
}
],
"nav": [
{
"time": "2026-06-15T00:01:00Z",
"nav": "60000",
"hold": "60000"
}
],
"orders": [
{
"orderId": 1,
"clientOrderId": "1781481601001",
"parentOrderId": null,
"requestType": "SMART",
"venue": null,
"pair": "BTC/USDT",
"orderType": "LIMIT",
"timeInForce": "GTC",
"side": "BUY",
"price": "104150",
"triggerPrice": null,
"quantity": "0.01",
"filledQuantity": "0.01",
"avgFillPrice": "104150",
"status": "FILLED",
"rejectReason": null,
"sentAt": "2026-06-15T00:00:01Z",
"arrivedAt": "2026-06-15T00:00:01.080Z",
"closedAt": "2026-06-15T00:00:09Z"
}
],
"fills": [
{
"orderId": 2,
"clientOrderId": "1781481601001",
"venue": "OKEX",
"pair": "BTC/USDT",
"time": "2026-06-15T00:00:09Z",
"side": "BUY",
"price": "104150",
"quantity": "0.01",
"liquidity": "MAKER",
"venueFee": "-0.000008",
"venueFeeAsset": "BTC",
"clientFee": "-0.000005",
"clientFeeAsset": "BTC"
}
],
"books": [
{
"venue": "OKEX",
"pair": "BTC/USDT",
"booksTopSeconds": 0,
"lastPrintSeconds": 7948800
}
],
"dataQuality": [],
"market": {
"source": "RECORDED",
"generator": null,
"drift": null,
"fitFrom": null,
"grade": null
}
}
| Field | Description |
|---|---|
| reproducible | true when the same inputs give the same fills. Otherwise reproducibleReason says why: FAST_CLOCK or IDLE_ADVANCES |
| metrics | {scope, scopeKey, metric, value, assetCd}. OVERALL (scopeKey: ALL) holds the run's performance and counts, such as START_VALUE, END_VALUE, PNL, RETURN_RATIO, MAX_DRAWDOWN, SHARPE, FILLS and ORDERS_PLACED, in navAsset. BENCHMARK is the same performance for holding the starting balances. VENUE (scopeKey the venue) holds HOLDING, FEE and CLIENT_FEE per asset |
| navAsset | The quote asset of the session's pairs; null when they have more than one |
| nav | Net asset value and the value of holding the starting balances, sampled evenly over the run: at most about 1,000 points, plus the last |
| orders | Every order, SMART parents and their per-venue children (parentOrderId set), with simulated sent, arrival and close times. status is ACTIVE, PARTIALLY_FILLED, FILLED, CANCELLED, EXPIRED, REJECTED or FAILED. On a BUY_STOP or SELL_STOP row, price is null and triggerPrice is the price the stop was sent with; on every other row triggerPrice is null |
| fills | Every fill with its liquidity, venue fee and client fee, signed |
| books | Seconds of recorded top of book and of last-print book per venue and pair |
| dataQuality | The warnings the session was created with |
| market | source RECORDED or GENERATED. For a generated market: generator, drift, fitFrom (start of the history the model was fitted on) and grade: {generator, rows[], passed}, each row {measure, real, simulated, tolerance, comparison, passed} comparing the recorded market with a generated one on fat tails, skew, volatility memory, variance ratios and the gap between the busiest and quietest hour |
The price a session has replayed so far, its fills and every order it sent, for drawing a run while it is in progress or after it has ended. It reads the session without stepping it, takes none of its two sockets and does not count as the bot being present. Nothing later than the simulated time is ever answered.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
| pair | query | string | Optional | A pair of the session. Default: its first pair |
| venue | query | string | Optional | The venue whose bars are drawn. Default: the first venue of the pair |
| since | query | integer | Optional | Epoch milliseconds. Only the bars from the one holding this moment and the fills at or after it are answered: replace what you hold from there. Pass the simulatedTo of your last read, as epoch milliseconds, to poll a long run cheaply |
{
"sessionId": 812,
"status": "RUNNING",
"venue": "OKEX",
"pair": "BTC/USDT",
"period": "ONE_HOUR",
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-07-15T00:00:00Z"
},
"simulatedTo": "2026-06-15T02:10:00Z",
"bars": [
[1781481600000, 104480.1, 104560.0, 104410.5, 104500.0, 182.44],
[1781485200000, 104500.0, 104590.2, 104470.0, 104537.5, 141.09]
],
"fills": [
{
"time": "2026-06-15T01:12:04.123Z",
"venue": "OKEX",
"side": "BUY",
"price": "104490",
"quantity": "0.01"
}
],
"orders": [
{
"clientOrderId": "1781485924123",
"venue": "OKEX",
"side": "SELL",
"type": "LIMIT",
"price": "104900",
"quantity": "0.01",
"filledQuantity": "0",
"sentAt": "2026-06-15T01:12:04.123Z",
"status": "ACTIVE",
"closedAt": null,
"parentClientOrderId": null
}
]
}
| Field | Description |
|---|---|
| period | The finest of ONE_MIN, FIVE_MIN, FIFTEEN_MIN, ONE_HOUR, FOUR_HOURS and ONE_DAY that covers the window in 1,000 bars or fewer |
| bars | [openMs, open, high, low, close, volume], oldest first, closed bars only. Bars that cannot be read are left out rather than failing the call, so the list can be short or empty; it is also empty for an ended session on a generated market, whose path is not kept |
| fills | The fills of the pair at any venue, oldest first. side is BUY or SELL; amounts are decimal strings |
| orders | Every order the session sent for the pair, at any venue, resting or not, while it runs and after it has ended. A SMART order is shown as its per-venue children once it is routed, each naming it in parentClientOrderId; drop a held order that a later one names as its parent. price is the limit price, or the trigger of a stop; an order with neither is left out. status is ACTIVE or PARTIALLY_FILLED while the order rests, and closedAt is when it stopped resting, null until then. With since, the orders still resting come back together with those sent or closed from a minute before it, so an order held from an earlier answer is replaced by its clientOrderId |
Your sessions, newest first.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| state | query | string | Optional | active (default: CREATED and RUNNING) or all |
| page | query | integer | Optional | From 0 |
| size | query | integer | Optional | 1 to 100, default 100 |
| Authorization | header | string | Yes | Backtest token |
{
"sessions": [
{
"sessionId": 812,
"status": "RUNNING",
"name": "grid BTC 3m",
"clock": {
"mode": "STEP_LOCKED",
"simTime": "2026-07-02T11:00:05.000Z",
"simTimeMs": 1782990005000,
"seq": 1552001,
"idleAdvances": 0
},
"window": {
"from": "2026-06-15T00:00:00Z",
"to": "2026-09-15T00:00:00Z"
},
"progress": 0.1897651217793881,
"eventsReplayed": 8812003,
"orders": 4210,
"fills": 3977,
"nav": "60812.55",
"navAsset": "USDT",
"connectedSockets": 1,
"warnings": [],
"reportReady": false,
"failureReason": null
}
],
"page": 0,
"size": 100,
"total": 1
}
Clock Modes
| Mode | Behaviour | Reproducible |
|---|---|---|
STEP_LOCKED (default) | The clock waits for your STEP. Your bot's speed and language make no difference. If nothing reaches the session from your bot for idleAdvanceMs of wall time after END (5 s by default). Any socket frame and any REST step, stop or order call counts; status requests and session REST reads such as candles or balances do not, the engine takes one stepMs step itself and counts it in idleAdvances. With idleAdvanceMs: 0 the clock waits for you indefinitely | Yes, while idleAdvances is 0 |
FAST | Steps follow one another without waiting. A command is stamped with the simulated time at which the engine reads it, so fills depend on your bot's speed | No |
Subscribed automatically on every socket: SUBSCRIBE and UNSUBSCRIBE only answer ACK, and the frames keep coming. Every step is framed by BEGIN and END; between them come the step's events in replay order, with your private reports at their simulated times. start sends one END with seq 0 at window.from. GET on the channel returns the current clock. A socket that connects to a running session receives the current clock as a SNAPSHOT; before start it receives no clock frame.
| Field | Type | Description |
|---|---|---|
| phase | string | BEGIN, SAMPLE or END. SAMPLE comes only in a step asked with sampleEveryMs: it marks a grid point the step passed, after the books that moved there, and hands no control back |
| seq | integer | The step number. 0 is the END sent at start |
| simTime | string | Simulated time, ISO-8601 with milliseconds. On BEGIN the time the step starts from; on END the time it stopped at, which is before stepTo when wakeOnPrivate ended it early at a private report, or a wake price ended it at a grid point |
| simTimeMs | integer | The same in epoch milliseconds; use it wherever your bot reads the time |
| stepTo | string | Where the step runs to, never past window.to |
| mode | string | STEP_LOCKED or FAST |
← {"event":"UPDATE","channel":"BACKTEST_CLOCK","data":[{"class":"BacktestClock","phase":"END","seq":0,
"simTime":"2026-06-15T00:00:00.000Z","simTimeMs":1781481600000,"stepTo":"2026-06-15T00:00:00.000Z","mode":"STEP_LOCKED"}]}
→ {"requestId":"s-1","command":"STEP","channel":"BACKTEST_CLOCK","channelArgs":[{"name":"advanceMs","value":"1000"}]}
← {"requestId":"s-1","command":"STEP","event":"ACK","channel":"BACKTEST_CLOCK","channelArgs":[{"name":"advanceMs","value":"1000"}]}
← {"event":"UPDATE","channel":"BACKTEST_CLOCK","data":[{"class":"BacktestClock","phase":"BEGIN","seq":1,
"simTime":"2026-06-15T00:00:00.000Z","simTimeMs":1781481600000,"stepTo":"2026-06-15T00:00:01.000Z","mode":"STEP_LOCKED"}]}
← {"command":"SUBSCRIBE","event":"UPDATE","channel":"ORDER_BOOK_PUBLIC","data":[{"class":"OrderBook","exchange":"OKEX",
"symbol":"BTC/USDT","bids":[[104210.1,0.52]],"asks":[[104210.2,0.31]],"eventTime":1781481601000,"source":"LAST_PRINT"}]}
← {"event":"UPDATE","channel":"BACKTEST_CLOCK","data":[{"class":"BacktestClock","phase":"END","seq":1,
"simTime":"2026-06-15T00:00:01.000Z","simTimeMs":1781481601000,"stepTo":"2026-06-15T00:00:01.000Z","mode":"STEP_LOCKED"}]}
→ {"requestId":"o-2","command":"CREATE","channel":"TRADE_PRIVATE","signature":"Bearer …",
"data":[{"class":"Order","globalInstrumentCd":"BTC/USDT","direction":"BUY","orderType":"LIMIT",
"timeInForce":"GTC","price":104150.0,"amount":0.01,"clientOrderId":"1781481601001"}]}
← {"requestId":"o-2","command":"CREATE","event":"ACK","channel":"TRADE_PRIVATE"}
← {"command":"CREATE","channel":"TRADE_PRIVATE","data":[{"class":"Order","clientOrderId":"1781481601001","orderStatus":"SUBMITTED", …}]}
→ {"requestId":"s-3","command":"STEP","channel":"BACKTEST_CLOCK","channelArgs":[{"name":"until","value":"2026-06-15T00:00:06Z"},
{"name":"wakeOnPrivate","value":"true"}]}
Advances the clock. Send exactly one STEP for each END, from any socket of the session. The STEP answers ACK; then the step runs, releasing every event after the current time up to the target between its BEGIN and END. A STEP while a step is running answers ERROR "Step already running"; a STEP on a FAST session, or on a session that is not RUNNING, answers ERROR with the reason. A STEP that is refused answers ERROR alone, never ACK first.
| Argument | Value | Description |
|---|---|---|
| until | string | ISO-8601 instant to step to |
| advanceMs | string | Milliseconds to step, 1 or more, when until is absent. With neither, one stepMs |
| wakeOnPrivate | string | "true" (the default when absent) ends a long step at the first private report, so a bot can ask for 60 s and still react to its fills at once. "false" always runs to the target |
| sampleEveryMs | string | Optional. Stops the replay at every grid point now + k × sampleEveryMs before the target, adds the books that moved there exactly as an END would, and sends a SAMPLE clock frame. A bot that samples the price every 60 s can then ask for a long step and see every minute, with one round trip. A private report still ends the step, so wakeOnPrivate cannot be "false"; a step holds at most 1,000 grid points |
| wakeInstrument | string | Optional, with sampleEveryMs: the one pair whose price the wake prices are, e.g. [BTC/USDT]; a pair the session does not trade is refused |
| wakeVenues | string | Optional, with wakeInstrument: the venues that price is taken from, e.g. [OKEX,HUOBI], each one the session trades the pair on; every venue when absent. The price is the midpoint of the best bid and the best ask across them, or the one side there is |
| wakeBelow / wakeAbove | string | Optional, with wakeInstrument, either or both: the step ends at the first grid point whose price is at or below wakeBelow, or at or above wakeAbove, instead of sending its SAMPLE. The test is on the level, not the crossing: a price already beyond a wake price when the step starts ends it at its first grid point. With both, wakeBelow must be under wakeAbove |
{
"requestId": "s-3",
"command": "STEP",
"channel": "BACKTEST_CLOCK",
"channelArgs": [
{
"name": "until",
"value": "2026-06-15T00:00:06Z"
},
{
"name": "wakeOnPrivate",
"value": "true"
}
]
}
{
"requestId": "s-3",
"command": "STEP",
"event": "ACK",
"channel": "BACKTEST_CLOCK",
"channelArgs": [
{
"name": "until",
"value": "2026-06-15T00:00:06Z"
},
{
"name": "wakeOnPrivate",
"value": "true"
}
]
}
Subscribed automatically, like BACKTEST_CLOCK; GET returns it at once. Sent at start, every 1,000 steps, and when the session ends. The last one carries the final state, failureReason and the runId, and 60 seconds later the session's sockets close with code 1000.
{
"event": "UPDATE",
"channel": "BACKTEST_STATUS",
"data": [
{
"class": "BacktestStatus",
"sessionId": 812,
"status": "FINISHED",
"progress": 1.0,
"simTime": "2026-09-15T00:00:00.000Z",
"eventsReplayed": 45120331,
"fills": 3977,
"reproducible": true,
"failureReason": null,
"runId": 812,
"reportReady": true
}
]
}
Ordering Guarantees
A session orders its frames more strictly than live:
- Within a step the frames run
BEGIN; the public trades and your private reports in replay order; the order books whose top moved;BALANCEandCLIENT_PORTFOLIOupdates, if they changed;END. Every 1,000th step is followed byBACKTEST_STATUS. - Replies follow the order of your commands.
SUBSCRIBEanswersACKfirst.ORDER_BOOK_PUBLIC,BALANCEandCLIENT_PORTFOLIOthen send aSNAPSHOT;TRADE_PRIVATEsends aGETwith the active orders of the pairs named;TRADE_PUBLICsends nothing more until the next print. Nothing is lost in between.- The
TRADE_PRIVATEactive-order reply comes before any update for those orders. - An order you send arrives at its send time plus
latency.orderMsand jitter, ahead of any recorded event at the same instant. Cancels and updates travel the same way, so a fill can beat a cancel; the cancel is then answered with anOrderUpdatecarrying the order's state,COMPLETEDonce it has filled. - Reports reach you
latency.reportMsafter the event that caused them.
Determinism
A STEP_LOCKED session with idleAdvances = 0 reproduces its fills exactly, given the same datasetVersion, engineVersion, parameters, seed and the same commands in each step. Your commands are stamped with the simulated time of the END they answer, never with wall time.
- Read the time from
BACKTEST_CLOCK, not from the machine's clock. - Generate
clientOrderIds from the simulated time. - Answer every
ENDwithinidleAdvanceMs.
Live Channels in a Session
Same names, commands, channelArgs and data classes as live. Private channels need signature, and its account must be the session's; a missing one answers ERROR "Signature was not provided in the request", a wrong one ERROR "Invalid signature". PING works as live; a socket silent for 120 seconds is dropped. Subscriptions belong to the socket that made them.
| Channel | Served as |
|---|---|
PING | Live: PONG |
ACTIVE_SUBSCRIPTIONS, ASSET_LIST | GET, as live; the assets are those of the session's pairs and balances |
INSTRUMENT_LIST | GET: the session's pairs only |
ORDER_BOOK_PUBLIC | SUBSCRIBE with instrument: ACK, SNAPSHOT, then one OrderBook per venue and pair at the end of each step in which its top changed, one level a side, plus source |
TRADE_PUBLIC | SUBSCRIBE with instrument: ACK, then one PublicTrade per recorded print, at its time |
CANDLES | Sessions only. SUBSCRIBE with instrument, exchange, period (ONE_MIN when left out) and limit (100 when left out, 1000 at most): ACK, a SNAPSHOT of the bars of the last limit periods that have closed, then just before END an UPDATE with the bars that closed in that step, and in a step asked with sampleEveryMs also just before each SAMPLE the bars that closed by that grid point. Each Candles item carries exchange, symbol, period and bars, the rows of public/candles oldest first; more than 300 bars come in several frames, each but the last with more: true. A bar is sent once and a period with no print has none, so a bot that subscribes needs no candle request while it steps |
BALANCE | SUBSCRIBE with currency: ACK, SNAPSHOT, then UPDATE just before END when it changed. GET returns every asset. balance, available, locked are summed across venues |
TRADE_PRIVATE | SUBSCRIBE with instrument; CREATE, UPDATE and CANCEL for pairs this socket has subscribed (others answer ERROR "Invalid (not subscribed to) instrument code"); GET with category ACTIVE_ORDERS (default), ORDERS_HISTORY or TRADES_HISTORY, optionally instrument and status, on simulated dates. A command answers ACK, then one Order per order with orderStatus: SUBMITTED; an order it could not take is listed in an ERROR instead. Then come OrderUpdate (ACCEPTED; ACTIVE when a stop triggers; CANCELLED; REJECTED) and ExecutionReport (ACTIVE while part of the order is open, COMPLETED on the fill that completes it) |
CLIENT_PORTFOLIO | SUBSCRIBE: ACK, SNAPSHOT, then UPDATE just before END when it changed, valued at the mid of the session's books |
CLIENT_BALANCE_DISTRIBUTION | GET: holdings per venue |
UNSUBSCRIBE
UNSUBSCRIBE with the channel's argument, such as instrument or currency, drops only the pairs or assets it names, and the channel once none are left. Without arguments it drops the channel. Arguments that do not include the channel's own answer ERROR "<argument>: list must be provided" and change nothing; otherwise UNSUBSCRIBE answers ACK. Dropping TRADE_PRIVATE for a pair also stops that socket's reports for it and its orders on it. BACKTEST_CLOCK and BACKTEST_STATUS cannot be dropped.
Updating an Order
UPDATE is a cancel and replace, as on live. The replacement is sent as a new order whose clientOrderId is the original followed by ~r and a revision number: 1781481601001~r1, then ~r2, and so on. The reply's message is Replaced by 1781481601001~r1, with the same id in exchangeOrderId, and later reports carry the replacement's id. A later UPDATE or CANCEL may keep naming the original id; it acts on the latest revision. A clientOrderId you send may not contain ~r, and each id may be used once per session.
SMART Orders
An order with no exchange, or with OPENTRADE, is SMART, as on live. A SMART order is a LIMIT, a MARKET or a stop order. It is split across the session's venues by best price and by your free balance on each. Each child is a DIRECT order {parent}#{venue}, with #2, #3 added for later children at the same venue; reports carry the parent's clientOrderId, requestType: SMART, the child's id in exchangeOrderId and, on an ExecutionReport, the child's venue in exchange. An unfilled part of a GTC or GTX limit is re-allocated on later steps; the unfilled part of any other order is dropped.
{
"event": "UPDATE",
"channel": "TRADE_PRIVATE",
"data": [
{
"class": "OrderUpdate",
"requestType": "DIRECT",
"tradeSide": "BUY",
"instrumentCd": "BTC/USDT",
"clientOrderId": "1781481601002",
"orderRequestStatus": "REJECTED",
"message": "PRICE_OFF_TICK: OKEX quotes BTC/USDT in steps of 0.1, so 104150.05 is not a price it can hold"
}
]
}
Channels Not Served
These live channels answer ERROR "Not available in a backtest session: <channel>":
CLIENT_PORTFOLIO_HISTORYDEPOSIT_WORKFLOW,DEPOSIT_WALLETTRANSFER_WORKFLOW,TRANSFER_FEE_QUOTE,WITHDRAWAL_WALLETYIELD_PRODUCT,YIELD_CONTRACTPERP_POSITION,PERP_RISK,PERP_ORDER_BOOK_PUBLIC,PERP_TRADE_PUBLIC
A session trades spot only. An order CREATE, UPDATE or CANCEL whose instrumentType is anything but SPOT is answered FAILED with "Only spot orders are available in a backtest session".
{
"requestId": "g-4",
"command": "SUBSCRIBE",
"event": "ERROR",
"channel": "YIELD_CONTRACT",
"data": [
{
"class": "Error",
"desc": "Not available in a backtest session: YIELD_CONTRACT"
}
]
}
Live REST in a Session
Under {session base}/api/rest, with the same bodies and replies as the REST API. X-API-Version is accepted and ignored. Any other path answers 404 NOT_IN_BACKTEST. The paths answer while the session is CREATED or RUNNING; once it has ended they answer 409 SESSION_NOT_RUNNING.
| Method | Path | Notes |
|---|---|---|
| GET | public/asset-list, public/instrument-list, public/order-book-public?instruments= | The session's pairs and book |
| GET | balance, client-portfolio, client-balance-distribution | The simulated account |
| GET | trade-private/active-orders, trade-private/orders-history (instruments and statuses required), trade-private/trades-history | fromDtm and toDtm are simulated times |
| POST, PUT, DELETE | trade-private/orders | Subject to the session's latency; returns List<Order> as live. PUT replaces as UPDATE does, with a ~r revision id |
GET /hermes-backtest/s/812/api/rest/trade-private/active-orders HTTP/1.1
Host: gateway-public.opentrade.exchange
Authorization: Bearer eyJraWQiOi...
Tick size, amount step and minimum amount for each venue and pair of the session, and where they came from. Sessions only; live has no equivalent.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| Authorization | header | string | Yes | Bearer token minted with scopes=BACKTEST_ACCESS |
[
{
"exchange": "OKEX",
"symbol": "BTC/USDT",
"tickSize": "0.1",
"amountStep": "0.00000001",
"minAmount": "0.00001",
"source": "VENUE_SNAPSHOT",
"appliedFrom": "2026-06-15"
}
]
| source | Meaning |
|---|---|
RUN_CONFIG | Your instrumentLimits |
VENUE_SNAPSHOT | The venue's recorded limits as of appliedFrom |
INFERRED_FROM_TAPE | No recorded limits; inferred from the recorded trades |
Bars that closed at or before the current simulated time, including warm-up history before window.from. Rows are [ts, open, high, low, close, volume], newest first. In a generated market, bars before window.from are recorded and bars after it are the generated market you trade. Sessions only.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| instrument | query | string | Yes | Pair, e.g. BTC/USDT |
| exchange | query | string | Yes | Venue, e.g. OKEX |
| period | query | string | Optional | ONE_MIN (default), FIVE_MIN, FIFTEEN_MIN, ONE_HOUR, FOUR_HOURS, ONE_DAY |
| to | query | integer | Optional | Latest bar time in epoch milliseconds; a later time is read as the simulated now |
| limit | query | integer | Optional | 1 to 1000, default 100 |
| Authorization | header | string | Yes | Backtest token |
[
[
1781481540000,
104200.0,
104260.1,
104190.0,
104210.1,
3.2044
],
[
1781481480000,
104188.4,
104214.0,
104170.2,
104200.0,
2.7719
]
]
Runs
Every session becomes a run, kept for the account until it is deleted. Runs are served under the control API.
| Method | Path | Does |
|---|---|---|
| GET | /runs?page&size&pathSet | Your runs, newest first; size 1 to 100, default 50. Each run names its market and pathSet. A path set is listed once, at its newest run, with outcomes: {runs, finished, profitAndLoss, returnRatio, maxDrawdownRatio}, each figure {p5, p25, p50, p75, p95} over the finished runs. With pathSet, the runs of that set |
| GET | /runs/{id} | One run: settings, metrics and report |
| GET | /runs/{id}/orders?page | Its orders, 100 a page: {orders, page, size, total} |
| GET | /runs/{id}/fills?page | Its fills, 100 a page: {fills, page, size, total} |
| GET | /runs/compare?id=…&id=… | 2 to 4 runs side by side, differing settings flagged |
| PUT | /runs/{id} | Rename or pin: {"name": "…", "pinned": true}; at least one of the two |
| DELETE | /runs/{id} | Delete. The run leaves your lists at once; its simulated days count until the month ends. A session still open is ended first, with failureReason: DELETED. 204 |
Which days of recorded history exist, per dataset, venue and pair. Each day is PRESENT, EMPTY (recorded, with no rows) or MISSING.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| dataset | query | string | Yes | trades, candles, index, instruments, fees, books_top |
| from | query | date | Yes | First day, YYYY-MM-DD |
| to | query | date | Yes | Last day |
| venue | query | string | Optional | e.g. HUOBI |
| pair | query | string | Optional | e.g. BTC/USDT |
| period | query | string | Optional | Bar length, for candles |
| instrumentType | query | string | Optional | e.g. SPOT |
{
"dataset": "trades",
"period": null,
"from": "2026-06-15",
"to": "2026-06-16",
"venue": "HUOBI",
"pair": "BTC/USDT",
"instrumentType": null,
"datasetVersion": "a41e33b07c5d2f98e1b6a3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708",
"days": [
{
"date": "2026-06-15",
"state": "PRESENT",
"rows": 184223,
"firstMs": 1781481600112,
"lastMs": 1781567999871,
"bytes": 5210331
},
{
"date": "2026-06-16",
"state": "MISSING",
"rows": 0,
"firstMs": null,
"lastMs": null,
"bytes": 0
}
]
}
Streams a slice of recorded history as Parquet or CSV, as an attachment. The response carries X-Dataset-Version.
| Name | In | Type | Required | Description |
|---|---|---|---|---|
| dataset | path | string | Yes | As for coverage |
| from | query | date | Yes | First day |
| to | query | date | Yes | Last day. At most 31 days of trades or books_top, 366 of the others |
| venue | query | string | Optional | Venue |
| pair | query | string | Optional | Pair |
| period | query | string | Optional | Bar length, for candles |
| instrumentType | query | string | Optional | e.g. SPOT |
| format | query | string | Optional | parquet (default) or csv |
curl -H "Authorization: $TOKEN" -o trades.parquet \
"https://gateway-public.opentrade.exchange/hermes-backtest/api/backtest/data/trades?venue=HUOBI&pair=BTC/USDT&from=2026-06-15&to=2026-06-30"
Example: Python SDK
The opentrade-backtest package (Python 3.10 or later) logs in, mints and refreshes the backtest token, runs the step loop and turns the report into pandas frames. ws.clock.now() reads like time.time(), and ws.clock.sleep(s) steps until simulated time has moved by s seconds. If the loop body raises, the SDK stops the session. If connect() is refused with a 4xx other than 401, 409 or 429, or is interrupted with Ctrl-C, on a session the SDK created and no other socket of it is open or opening, the SDK calls cancel so the slot is freed at once. Any other failure leaves the session for you to retry. When the loop body raises before start, the stop is refused and the SDK cancels instead.
pip install "opentrade-backtest[pandas]"
import os
from decimal import Decimal
from opentrade_backtest import BacktestClient, Balance, Credentials, SessionSpec
PAIR = "BTC/USDT"
VENUES = ["HUOBI", "OKEX", "BITGET"]
REST_FOR_MS = 60_000
FINISHED = {("ExecutionReport", "COMPLETED"), ("OrderUpdate", "REJECTED"), ("OrderUpdate", "CANCELLED")}
creds = Credentials(os.environ["OT_API_USERNAME"], os.environ["OT_PASSWORD"],
os.environ["OT_API_USERNAME"], os.environ["OT_SECRET"])
bt = BacktestClient.production(creds)
session = bt.create_session(SessionSpec(
name="bid under the book",
window=("2026-06-15", "2026-09-15"),
pairs={PAIR: VENUES},
balances=[Balance(venue, "USDT", "20000") for venue in VENUES],
seed=7,
))
print("session", session.session_id, session.ws_url)
bids = {}
resting = None
with session.connect() as ws:
ws.subscribe_book(PAIR)
ws.subscribe_private(PAIR)
session.start()
for batch in ws.steps(until_ms=5000):
for report in batch.private:
if resting and report.get("clientOrderId") == resting["id"] and \
(report.get("class"), report.get("orderRequestStatus")) in FINISHED:
resting = None
for book in batch.books:
if book["bids"]:
bids[book["exchange"]] = Decimal(str(book["bids"][0][0]))
now = ws.clock.now_ms()
if resting and not resting["cancelling"] and now - resting["placed"] > REST_FOR_MS:
ws.cancel_order(PAIR, client_order_id=resting["id"], exchange=resting["venue"])
resting["cancelling"] = True
if resting is None and bids:
venue, best = max(bids.items(), key=lambda item: item[1])
price = (best * Decimal("0.998")).quantize(Decimal("0.1"))
order_id = ws.create_order(PAIR, "BUY", "0.01", price=price, exchange=venue)
resting = {"id": order_id, "venue": venue, "placed": now, "cancelling": False}
report = session.result()
frames = report.frames()
print("run", report.run_id, "reproducible", report.reproducible)
print(frames["metrics"])
print(frames["fills"].tail())
| Module | What it gives you |
|---|---|
BacktestClient | .production(creds); create_session, run_paths(spec, seeds, bot), session(id), sessions(), runs(), run(id), run_orders(id), run_fills(id), compare(ids), update_run(id), delete_run(id), coverage(…), download(…) |
Session | start(), stop(), cancel(), status(), step(…), result(), connect(), instrument_specs(), candles(…), base_url, rest_base, ws_url |
SessionSocket | subscribe_book, subscribe_trades, subscribe_candles, subscribe_private, subscribe_balance, create_order, cancel_order, get, step(), steps(), run(on_step), clock, and events() for FAST sessions |
GeneratedMarket | Pass market=GeneratedMarket("STUDENT_T", "NONE") to SessionSpec to trade a market drawn from the Shestakov market model instead of the recorded one; change seed for another market. result().market names the generator and its grade |
run_paths | bt.run_paths(spec, seeds=range(20), bot=run_my_bot, path_set="ma-grid") creates one session per seed in turn, each named after spec.name and its seed, calls bot(session) to run each to its end, and returns a PathSet of the set's name and every report. If a path fails, its session is stopped and PathSetInterrupted is raised, carrying the seed and a PathSet of the reports finished so far. bt.runs(path_set="ma-grid") lists its runs |
live | order_body and cancel_body in the live wire shape; live_endpoints(env) and session_endpoints(session) return (rest_base, ws_url), so one bot switches between live and backtest by configuration |
| Errors | All ApiError: AuthError, InvalidRequest, Unauthorized, WrongAudience, NotPermitted, NotFound, SessionConflict, RateLimited and Unavailable (with retry_after), SessionEnded |
Example: JavaScript (Node)
Node 20 with the ws package, which sets the Authorization header on the upgrade. Browsers cannot, and no token is accepted in the query string. Run it with node step-loop.mjs.
npm install ws
import WebSocket from "ws";
const AUTH = "https://auth.opentrade.exchange";
const CONTROL = "https://gateway-public.opentrade.exchange/hermes-backtest/api/backtest";
const PAIR = "BTC/USDT";
const { OT_API_USERNAME: username, OT_PASSWORD: password, OT_SECRET: secret } = process.env;
async function backtestToken() {
const login = await fetch(`${AUTH}/login`, {
method: "POST",
redirect: "manual",
body: new URLSearchParams({ username, password }),
});
if ((login.headers.get("location") ?? "").includes("/login")) throw new Error("login refused");
const cookie = login.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
const minted = await fetch(`${AUTH}/auth/jwt/clients/${username}/token?scopes=BACKTEST_ACCESS`, {
method: "POST",
headers: { Cookie: cookie, clientSecret: secret },
});
if (!minted.ok) throw new Error(`token refused: HTTP ${minted.status}`);
return (await minted.text()).trim();
}
const token = await backtestToken();
async function call(method, path, body) {
const response = await fetch(CONTROL + path, {
method,
headers: { Authorization: token, "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const json = response.status === 204 ? null : await response.json();
if (!response.ok) throw new Error(`${response.status} ${json?.code}: ${json?.message}`);
return json;
}
const session = await call("POST", "/sessions", {
name: "bid under the book",
window: { from: "2026-06-15T00:00:00Z", to: "2026-09-15T00:00:00Z" },
pairs: [{ pair: PAIR, venues: ["HUOBI", "OKEX", "BITGET"] }],
balances: ["HUOBI", "OKEX", "BITGET"].map((venue) => ({ venue, asset: "USDT", amount: "20000" })),
seed: 7,
});
const REST_FOR_MS = 60000;
const FINISHED = new Set(["ExecutionReport:COMPLETED", "OrderUpdate:REJECTED", "OrderUpdate:CANCELLED"]);
const ws = new WebSocket(session.wsUrl, { headers: { Authorization: token } });
const send = (frame) => ws.send(JSON.stringify(frame));
let requests = 0;
let answered = -1;
let resting = null;
let ended = false;
const bids = new Map();
function onStep(clock) {
if (resting && !resting.cancelling && clock.simTimeMs - resting.placed > REST_FOR_MS) {
send({ requestId: `c-${++requests}`, command: "CANCEL", channel: "TRADE_PRIVATE", signature: token,
data: [{ class: "Order", action: "Cancel", globalInstrumentCd: PAIR, clientOrderId: resting.id,
exchange: resting.venue, requestType: "DIRECT" }] });
resting.cancelling = true;
}
if (resting === null && bids.size > 0) {
const [venue, bestBid] = [...bids.entries()].reduce((a, b) => (b[1] > a[1] ? b : a));
resting = { id: String(clock.simTimeMs), venue, placed: clock.simTimeMs, cancelling: false };
send({
requestId: `o-${++requests}`, command: "CREATE", channel: "TRADE_PRIVATE", signature: token,
data: [{ class: "Order", globalInstrumentCd: PAIR, direction: "BUY", orderType: "LIMIT", timeInForce: "GTC",
price: Math.floor(bestBid * 0.998 * 10) / 10, amount: 0.01, clientOrderId: resting.id,
exchange: venue, requestType: "DIRECT" }],
});
}
}
async function stopSession(reason) {
if (ended) return;
ended = true;
clearInterval(ping);
ws.close();
console.error("stopping the session:", reason);
await call("POST", `/sessions/${session.sessionId}/stop`)
.catch((error) => error.message.startsWith("409 ")
? call("POST", `/sessions/${session.sessionId}/cancel`) : null)
.catch(() => {});
process.exitCode = 1;
}
const ping = setInterval(() => send({ command: "PING", channel: "PING" }), 30000);
ws.on("open", async () => {
send({ requestId: "sub-1", command: "SUBSCRIBE", channel: "ORDER_BOOK_PUBLIC",
channelArgs: [{ name: "instrument", value: `[${PAIR}]` }] });
send({ requestId: "sub-2", command: "SUBSCRIBE", channel: "TRADE_PRIVATE", signature: token,
channelArgs: [{ name: "instrument", value: `[${PAIR}]` }] });
await call("POST", `/sessions/${session.sessionId}/start`);
});
ws.on("message", async (raw) => {
const frame = JSON.parse(raw);
const item = frame.data?.[0];
if (frame.channel === "ORDER_BOOK_PUBLIC") {
for (const book of frame.data ?? []) {
if (book.bids?.length) bids.set(book.exchange, book.bids[0][0]);
}
}
if (resting && item?.clientOrderId === resting.id && FINISHED.has(`${item.class}:${item.orderRequestStatus}`)) {
resting = null;
}
if (frame.channel === "BACKTEST_CLOCK" && item?.phase === "END" && item.seq > answered) {
answered = item.seq;
onStep(item);
send({ requestId: `s-${++requests}`, command: "STEP", channel: "BACKTEST_CLOCK",
channelArgs: [{ name: "until", value: new Date(item.simTimeMs + 5000).toISOString() },
{ name: "wakeOnPrivate", value: "true" }] });
}
if (frame.channel === "BACKTEST_STATUS" && ["FINISHED", "CANCELLED", "FAILED"].includes(item?.status)) {
ended = true;
clearInterval(ping);
ws.close();
if (item.status === "FINISHED") {
const report = await call("GET", `/sessions/${session.sessionId}/result`);
console.log("run", report.runId, "reproducible", report.reproducible, report.metrics);
} else {
console.log("session ended", item.status, item.failureReason);
}
}
});
ws.on("close", () => stopSession("the socket closed before the session ended"));
ws.on("error", (error) => stopSession(error.message));
process.on("uncaughtException", (error) => stopSession(error.stack));
Example: Raw WebSocket
websocat is enough to drive a session by hand. Create and start the session with the control API, connect, and type frames. The session is created with idleAdvanceMs: 0, so its clock waits for you however slowly you type. Run it with sh session.sh; it reads OT_API_USERNAME, OT_PASSWORD and OT_SECRET from the environment.
set -eu
AUTH=https://auth.opentrade.exchange
CONTROL=https://gateway-public.opentrade.exchange/hermes-backtest/api/backtest
TOKEN=$(curl -sf --cookie-jar cookies.txt -X POST "$AUTH/login" \
--data-urlencode "username=$OT_API_USERNAME" --data-urlencode "password=$OT_PASSWORD" -o /dev/null \
--next -sf -b cookies.txt -X POST \
"$AUTH/auth/jwt/clients/$OT_API_USERNAME/token?scopes=BACKTEST_ACCESS" \
-H "clientSecret: $OT_SECRET" -d "")
T=${TOKEN#Bearer }
SESSION=$(curl -sf -X POST "$CONTROL/sessions" \
-H "Authorization: Bearer $T" -H "Content-Type: application/json" \
-d '{"window":{"from":"2026-06-15T00:00:00Z","to":"2026-06-16T00:00:00Z"},
"pairs":[{"pair":"BTC/USDT","venues":["HUOBI","OKEX","BITGET"]}],
"balances":[{"venue":"HUOBI","asset":"USDT","amount":"20000"},
{"venue":"OKEX","asset":"USDT","amount":"20000"},
{"venue":"BITGET","asset":"USDT","amount":"20000"}],
"clock":{"idleAdvanceMs":0}}')
ID=$(printf '%s' "$SESSION" | sed -n 's/.*"sessionId": *\([0-9]*\).*/\1/p')
[ -n "$ID" ] || { echo "no session created: $SESSION" >&2; exit 1; }
(sleep 2 && curl -sf -X POST "$CONTROL/sessions/$ID/start" -H "Authorization: Bearer $T" > /dev/null) &
websocat -H "Authorization: Bearer $T" "wss://gateway-public.opentrade.exchange/hermes-backtest/s/$ID/ws"
{"requestId":"sub-1","command":"SUBSCRIBE","channel":"ORDER_BOOK_PUBLIC","channelArgs":[{"name":"instrument","value":"[BTC/USDT]"}]}
{"requestId":"s-1","command":"STEP","channel":"BACKTEST_CLOCK","channelArgs":[{"name":"advanceMs","value":"5000"},{"name":"wakeOnPrivate","value":"true"}]}
{"command":"PING","channel":"PING"}
AsyncAPI
The session's WebSocket is described in AsyncAPI 3.0: the envelope, BACKTEST_CLOCK, STEP, BACKTEST_STATUS, and the message schemas of every live channel a session serves. Generate a client in your language from it.