# The Metrand API

Strategies, checks and backtests from your own code, scripts and AI agents: keys, limits, every endpoint and every error.

Write a strategy, check it, backtest it on years of exchange history and read every trade: from code, a script or an AI
agent. Everything here is also in the [OpenAPI document](https://metrand.com/api/v1/openapi.json), which code generators
and AI assistants read directly, and this page is plain Markdown at
[metrand.com/docs/api.md](https://metrand.com/docs/api.md).

Base URL: `https://metrand.com/api/v1`

## Keys

Make a key in the app under **Account → API keys**. It is shown once: keep it like a password. Send it with every
request:

```
Authorization: Bearer mtr_AbCdEfGhIjKl_…
```

A key acts as you, in your workspace, narrowed by its scopes:

| Scope | Allows |
| --- | --- |
| `read` | strategies, versions, backtests, trades, the op catalog, templates and market rules |
| `research` | checking graphs and running backtests, which spend the workspace’s daily backtests |
| `strategies:write` | creating strategies and saving versions |

A key can be limited to some IP addresses and given an expiry date. Revoking it stops it at once; resetting your
password revokes all of yours.

## Limits

Every key of a workspace draws on the same limits, set by its plan:

| Plan | Requests a minute | Backtests running at once | Backtests waiting | Backtests a day | Bars per backtest |
| --- | --- | --- | --- | --- | --- |
| Free | 60 | 1 | 10 | 20 | 5,000 |
| Pro | 300 | 2 | 50 | 200 | 20,000 |
| Expert | 1,200 | 4 | 200 | 2,000 | 50,000 |

The daily backtests and the longest window are the plan’s, shared with the app; an Enterprise plan with larger limits
is arranged with us. Every answer says how much of the minute is left (`RateLimit-Limit`, `RateLimit-Remaining`,
`RateLimit-Reset`); a refusal says when to come back (`Retry-After`). `GET /me` shows the limits and today’s use.

## Conventions

- JSON in and out, request bodies up to 1 MB.
- Times are RFC 3339 in UTC (`2025-01-31T00:00:00Z`); inputs also take epoch milliseconds.
- Money, prices and quantities are decimal strings, so nothing is rounded on the way.
- Every object says what it is in `object`.
- A list is `{"object": "list", "data": [...], "next_cursor": ...}`. Pass `next_cursor` back as `cursor` for the next
  page of the same list; `null` means the last page. `limit` is 1 to 100, 25 when left out; trades take up to 1,000.
  The lists of reference data (`/markets`, `/templates`) come whole, with `next_cursor` always `null`.
- Every answer has `X-Request-Id`; quote it when something looks wrong.
- Version 1 only grows. New fields, endpoints and values may appear; nothing is renamed or removed. Ignore fields you
  do not know.

## Quick start

With curl:

```bash
KEY=mtr_…
API=https://metrand.com/api/v1

# 1. Start a strategy from a template (GET /templates lists them, with their graphs).
curl -s -X POST $API/strategies -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"name": "Momentum test", "template": "momentum"}'
# → {"object":"strategy","id":"…","version":{"hash":"9f2c…"},…}

# 2. Backtest it on two years of hourly BTCUSDT, waiting up to 20 s for the result.
curl -s -X POST $API/backtests -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -H 'Prefer: wait=20' -H 'Idempotency-Key: momentum-btc-2y' \
  -d '{"strategy": {"id": "…", "version": "9f2c…"},
       "market": {"exchange": "binance", "symbol": "BTCUSDT", "interval": "1h"},
       "window": {"start": "2023-10-01T00:00:00Z", "end": "2025-10-01T00:00:00Z"},
       "costs": {"taker_bps": 5, "slippage_bps": 2}}'
# → 201 with "status":"succeeded" and the result, or 202 with "status":"queued": read it again

# 3. Read the backtest, its trades and its equity curve.
curl -s $API/backtests/<id> -H "Authorization: Bearer $KEY"
curl -s "$API/backtests/<id>/trades?limit=500" -H "Authorization: Bearer $KEY"
curl -s "$API/backtests/<id>/equity?points=300" -H "Authorization: Bearer $KEY"
```

The same in Python, waiting out a limit when told to:

```python
import time, uuid, requests

API = "https://metrand.com/api/v1"
s = requests.Session()
s.headers["Authorization"] = "Bearer mtr_…"

def call(method, path, **kw):
    r = s.request(method, API + path, timeout=90, **kw)
    if r.status_code == 429:                       # a limit: wait as told, then try again
        time.sleep(int(r.headers.get("Retry-After", "5")))
        return call(method, path, **kw)
    if r.status_code >= 400:
        raise RuntimeError(r.json())               # problem details: code, detail, errors
    return r.json()

strategy = call("POST", "/strategies", json={"name": "Momentum test", "template": "momentum"},
                headers={"Idempotency-Key": str(uuid.uuid4())})
bt = call("POST", "/backtests", headers={"Prefer": "wait=20"}, json={
    "strategy": {"id": strategy["id"], "version": strategy["version"]["hash"]},
    "market": {"symbol": "BTCUSDT", "interval": "4h"},
    "window": {"bars": 3000},
})
while bt["status"] in ("queued", "running"):
    time.sleep(2)
    bt = call("GET", f"/backtests/{bt['id']}")

print(bt["status"], bt["result"]["report"]["net_pnl"] if bt["result"] else bt["error"])
```

## Endpoints

| Endpoint | Scope | Does |
| --- | --- | --- |
| `GET /me` | any key | The key, its user and workspace, the plan’s limits and today’s use. |
| `GET /catalog` | `read` | Every op a strategy graph may hold: kind, parameters, ports. |
| `GET /templates` | `read` | The templates a strategy can start from, with their graphs and latest measurement. |
| `GET /markets` | `read` | Every USDT perpetual the exchange lists (`?exchange=binance` or `bybit`). |
| `GET /markets/{exchange}/{symbol}` | `read` | One market’s timeframes, lot rules, leverage tiers and standard fees. |
| `GET /strategies` | `read` | The workspace’s strategies (`?archived=true` for the archived ones). |
| `POST /strategies` | `strategies:write` | A new strategy from a template or a graph. |
| `GET /strategies/{id}` | `read` | One strategy and its latest version. |
| `GET /strategies/{id}/versions` | `read` | A strategy’s versions, newest first. |
| `POST /strategies/{id}/versions` | `strategies:write` | Save a graph as a version; the same graph returns the version it already is. |
| `GET /strategies/{id}/versions/{hash}` | `read` | One version with its graph. |
| `POST /strategies/validate` | `research` | Whether the engine compiles a graph, without saving it. |
| `GET /backtests` | `read` | The backtests run here and in the app (`?strategy=`, `?version=`, `?status=`). |
| `POST /backtests` | `research` | Ask for a backtest. |
| `GET /backtests/{id}` | `read` | One backtest, finished or not. |
| `POST /backtests/{id}/cancel` | `research` | Cancel a queued backtest; its charge comes back. |
| `GET /backtests/{id}/trades` | `read` | A finished backtest’s trades, in the order they closed. |
| `GET /backtests/{id}/equity` | `read` | A finished backtest’s equity curve. |
| `GET /openapi.json` | none | The OpenAPI 3.1 document of all of this. |

The fields of every request and answer are in the [OpenAPI document](https://metrand.com/api/v1/openapi.json). Paths
are relative to the base URL: `GET /me` is `https://metrand.com/api/v1/me`.

## Strategies

A strategy is a name and a list of immutable versions. A version is a graph, named by its content hash: saving the
same graph again returns the version it already is (`200`), so it is safe to save before every backtest.

- `POST /strategies` takes a `name` and either a `template` (a key from `GET /templates`) or a graph as `dsl`.
- `POST /strategies/{id}/versions` and `POST /strategies/validate` take the graph as `dsl`.

The op catalog (`GET /catalog`) lists every node a graph may hold. The format is explained in the guide
[Strategy graphs](https://metrand.com/guides/strategy-graphs), and all of it is in one file,
[the strategy format pack](https://metrand.com/api/guides/strategy-format.md), to hand to an AI assistant. Graphs
beyond what the app’s Builder makes need a plan with the Graph editor (`plan_required`).

## Backtests

A backtest is a job. `POST /backtests` checks the request, charges one backtest and answers at once.

| Field | Means |
| --- | --- |
| `strategy` | `id` and `version` (the hash, or a unique prefix of at least 6 characters) |
| `market` | `exchange` (`binance` or `bybit`, binance when left out), `symbol` (one that `GET /markets` lists; any other is refused before the charge), `interval` (`1h` when left out) |
| `window` | either `bars`, the last bars closed by now, or `start` and `end`; up to the plan’s bars per backtest |
| `costs` | `taker_bps`, `maker_bps`, `slippage_bps`, `start_equity`, `leverage`; each is the exchange’s standard when left out |

| Answer | Means |
| --- | --- |
| `202` | waiting or running: read it again, or ask with `Prefer: wait=N` (up to 20 seconds) |
| `201` | accepted and ended within the wait; look at `status`: succeeded or failed |
| `200` + `Backtest-Reused: true` | an identical backtest already had this result; no charge |
| `202` + `Backtest-Reused: true` | an identical backtest is under way; no charge, the same id |

`Prefer: wait=N` holds the answer up to N seconds, 20 at most, and says so with `Preference-Applied: wait=N`. A
waiting request holds a server worker, so a workspace has at most two waiting at once: a third, or one that comes while
the server already holds many, is answered at once, `202` without `Preference-Applied`, and the backtest is read again
like any other.

Identical means the same strategy and version, market, resolved window, costs and engine release. A window ends at
the last bar closed by `end` (now, when left out), so “the last 500 bars” is computed again once a new bar closes.

The states are `queued` → `running` → `succeeded`, `failed` or `canceled`. A queued backtest can be canceled and its
charge comes back. A backtest that fails for a reason that is not the request’s, the exchange’s history or the engine
unreachable, is tried again, and if it still fails its charge comes back too (`error.code`: `market_data_unavailable`,
`service_unavailable`). One the engine refuses (`backtest_failed`: the graph cannot trade as written) keeps its charge:
the engine did the work.

The result carries the engine’s report, the bars it was measured on (`result.measured_on`), the costs and its
provenance (`provenance.fingerprint`, `provenance.release`).

- `/trades`: the trades in the order they closed, net of fees and funding, up to 1,000 a page.
- `/equity`: the equity curve thinned to `points` points, 10 to 5,000 (500 when left out). Each stretch keeps its
  lowest and highest point, so drawdowns survive; `total_points` says how many there were.

How the engine fills orders inside a bar, and what it does not model, is in the guide
[How a backtest is computed](https://metrand.com/guides/how-backtests-work).

## Errors

Failures are problem details (`application/problem+json`) with a stable `code` to branch on:

```json
{
  "type": "https://metrand.com/docs/api#quota_exceeded",
  "title": "Quota exceeded",
  "status": 429,
  "code": "quota_exceeded",
  "detail": "Daily backtest limit reached (200) — upgrade for more.",
  "request_id": "6f0c2c1e-…"
}
```

`type` links to the code below. A refused field is named in `errors`, by its path in the request. Nothing is charged
for a `503`. Retry `429` after `Retry-After`, and `5xx` with backoff.

### `unauthenticated` · 401

No key was sent. Send it as `Authorization: Bearer mtr_…`.

### `invalid_api_key` · 401

The key is unknown, revoked or expired. Make a new one.

### `forbidden` · 403

The key’s user may not do this, for example a viewer of the workspace writing to it.

### `insufficient_scope` · 403

The key lacks the scope this needs; `detail` names it. Make a key with that scope.

### `plan_required` · 403

The workspace’s plan does not include this, for example an op of the Graph editor.

### `ip_not_allowed` · 403

The key is limited to other IP addresses.

### `not_found` · 404

Nothing with that id in this workspace, or a path the API does not have.

### `method_not_allowed` · 405

The path does not take that method.

### `conflict` · 409

The resource is in a state that does not allow this, for example canceling a backtest already running.

### `idempotency_in_progress` · 409

The first request with this `Idempotency-Key` is still being answered. Retry in a moment.

### `payload_too_large` · 413

The body is over 1 MB.

### `unsupported_media_type` · 415

Send JSON, with `Content-Type: application/json`.

### `validation_failed` · 422

A field is refused: `errors` names each one by its path (`market.symbol`, `window.start`). Fix the request; retrying it
unchanged fails again.

### `idempotency_key_reused` · 422

This `Idempotency-Key` was used with a different request. Use a new key for a new request.

### `rate_limited` · 429

Too many requests this minute. Wait for `Retry-After` seconds.

### `quota_exceeded` · 429

The workspace has used today’s backtests. They renew at 00:00 UTC.

### `too_many_jobs` · 429

The workspace has as many backtests waiting as its plan allows. Wait for some to finish.

### `internal_error` · 500

Something failed on our side. Quote `request_id` when you write to us.

### `market_data_unavailable` · 503

The exchange’s history could not be read just now; nothing was charged. Retry after `Retry-After`.

### `service_unavailable` · 503

A service this needs is down; nothing was charged. Retry with backoff.

## Retrying safely

Send an `Idempotency-Key` (any string up to 255 characters, unique per action) with a `POST` that creates or changes
something: a strategy, a version, a backtest, a cancel. If the answer is lost, send the same request with the same key:
within 24 hours you get the first answer again (`Idempotent-Replayed: true`), and nothing is created or charged twice.
The same key with a different body is refused (`idempotency_key_reused`). Only successes and refusals of the request
as written are kept; after any other answer (a limit, a conflict, an outage) the retry runs again.

## For AI agents

An agent that runs every day should **watch daily and change rarely**: a daily or 4-hour strategy gains one to six
bars a day, and tuning on them every day fits noise. Read the market and the results daily; propose a new version on a
fixed, slower schedule, and keep it only if it wins on data it was not tuned on. Keep every version: they are cheap,
immutable, and their backtests show what was tried. Use `Idempotency-Key` on every `POST`, and `Prefer: wait` instead
of polling.

## Not in version 1 yet

Webhooks when a backtest ends; comparisons, periods, baskets and parameter sweeps as jobs; paper runs; live trading; an
MCP server for AI assistants. Raw candles are not served: they are the exchanges’ data.
