# OptAlgo for AI agents: Errors and what to do

> One section of the OptAlgo agent guide. Start at https://docs.optalgo.com/llm/index.md (the loop, the safety rules, every section). The whole guide in one file: https://docs.optalgo.com/optalgo-llm.md. Links to other sections point at their files.

## 6. Errors and what to do {#errors}

### The response shape

**Success.** `GET /v1/markets`, `GET /v1/prices` and `POST /v1/backtests/validate` answer `{data, next}`. The backtest endpoints that existed before (submit, get, list, limits, check, capabilities, chart) keep their fields at the top level and add `next` beside them. Rule: **the payload is `body.data` when present, else the body without `next`.** `next` is a list of `{action, method, path, why}`: the exact calls that move you forward.

**Refusal** (every `/v1/backtests*`, `/v1/markets` and `/v1/prices` error):

```json
{"error": "engine_refused", "message": "…", "detail": "…",
 "fix": "Use at most 3 symbols per run (this one has 5): split them over several runs.",
 "limit": "max_symbols", "value": 5, "allowed": 3,
 "docs": "https://docs.optalgo.com/ai-agents/optalgo-llm#max_symbols",
 "next": [{"action": "validate", "method": "POST", "path": "/v1/backtests/validate", "why": "see every problem and a version that fits"}]}
```

- **`error`** is a stable code: branch on it. **`message`** (= `detail`) says what happened; quote it. **`fix`** is one concrete instruction: do it. **`field`**, when present, names the part of your request. **`docs`** links the code's entry below. **`next`** lists the calls to make next. Each code adds its own fields (`limit`, `value`, `allowed`, `findings`, `resets_at` …).
- Bot, signal, trade and account endpoints answer the object itself, and errors as `{"error", "detail", …}`.
- Headers: `X-RateLimit-Remaining` on every response; `X-Quota-Remaining` and `X-Quota-Resets-At` on limits, validate, submit, list and get; `Retry-After` on every `429`; **`X-Request-Id`** (`req_…`) on every `/v1` response.
- **A `5xx` on any `/v1` path** (also an unexpected crash: `500 internal_error`, always JSON) carries `request_id` and, last in `next`, a `report_issue` step with a ready ticket in `body`: `{"action": "report_issue", "method": "POST", "path": "/v1/tickets", "why": "…", "body": {"items": [{"kind": "bug", "title": "502 engine_unreachable on GET /v1/backtests/{backtest_id}", "body": "Expected: … Got: …", "context": {"backtest_id": "…", "request_id": "req_…"}}]}}`. Retry first as `fix` says; when it repeats, send that body (add the call you made) - see [Report problems automatically](https://docs.optalgo.com/llm/tickets.md#report-problems-automatically). OptAlgo also logs every `5xx` on its own.

### Access and plan

#### `invalid_api_key` (401) {#invalid_api_key}
The key is missing, revoked or its account closed. Delete the credentials file and run the agent login (section 0, `POST /v1/agent/login`). Never ask for a pasted key.

#### `plan_required` (403) {#plan_required}
The plan does not include this (on Free: the `trade` scope, full autonomy, live trading). The body carries `required_scope` and `upgrade_url`. Tell the user they can upgrade at app.optalgo.com/subscription; Free keys can still read, run backtests (50 units a month) and trade bots on paper. Do not retry.

#### `scope_required` (403) {#scope_required}
The key lacks `required_scope`. Give the user `fix_url`: they turn the scope on for this same key (no new key), then retry with the same `Idempotency-Key`.

#### `rate_limited` (429) {#rate_limited}
Wait `Retry-After` seconds, then retry.

#### `not_in_plan` (403) {#not_in_plan}
A plan limit, not a bug: the account gets none of this daily allowance (filter screens, meta-labelling research). `plan` + `upgrade_url` name the plan that has it; without them it is turned off for this account or open on no plan yet. Tell the user what `message` says; do not retry and do not file a ticket.

#### `backtests_disabled` (403) {#backtests_disabled}
Backtests are switched off for the account. Tell the user to contact support (or file a ticket, `POST /v1/tickets`); stop.

#### `account_suspended` (403) {#account_suspended}
API access is suspended after repeated security violations: every key, key creation, agent login, claim, connected chat (connector) and code submission of the account stops. Tell the user to contact support@optalgo.com. There is no `next`: do not log in again or try another key.

### Connectors (chat apps)

These come only to a chat app connected through the OptAlgo connector (`https://mcp.optalgo.com/mcp`), never to an API key. Setup and tools: https://docs.optalgo.com/ai-agents/connectors

#### `connector_paper_only` (403) {#connector_paper_only}
The call would touch real money (a live signal or close, a live bot, paper-to-live, a higher live allocation, pausing / resuming / editing / deleting a live hosted strategy). [Compare with backtest](https://docs.optalgo.com/llm/hosted.md#compare-with-backtest) is allowed on a live hosted strategy: it places no order. Connectors are paper only on every plan: do not retry, and never ask for an API key to get around it. Tell the user live trading is done in the app; keep working on paper.

#### `connector_research_only` (403), `research_only` {#connector_research_only}
<a id="research_only"></a>The user approved this chat as **Research only** (`read` + `backtest`) and the call needs `bots` (any write to a bot or a hosted strategy; body `required_scope`, `access: "research"`). The connector answers `research_only` itself for its bot tools, which it does not list for such a chat. Reads and backtests keep working. The choice is fixed for the connection: for bots the user disconnects OptAlgo in the chat app and connects again with **Full access** ([choose the access](https://docs.optalgo.com/ai-agents/connectors#access)). Do not retry.

#### `connector_not_allowed` (403) {#connector_not_allowed}
The connector does not offer this call. Use the connector's tools only; anything else (API keys, exchange connections, payments) is done by the user in the app.

#### `invalid_token` (401) {#invalid_token}
The connector's token expired or was revoked, or the user disconnected the chat. Tell the user to reconnect the connector in the chat app (Claude: the connector's **Connect**; Claude Code: `/mcp`). Never ask for a pasted key instead.

[`account_suspended`](#account_suspended) stops connectors too.

### Quota

#### `daily_quota` (429) {#daily_quota}
Plus / Pro: today's units are used, or this run's estimate (`cost`) is more than `remaining`. Stop submitting; tell the user `used`, `remaining` and `resets_at` (00:00 UTC). `validate` and reads stay free meanwhile; only a cheaper run that fits `remaining` may go.

#### `limit` (429) {#limit}
A plan limit, not a bug: today's filter screens or meta-labelling research runs are used (`screens_per_day` / `meta_research_per_day`). Stop submitting them until `resets_at` (00:00 UTC); backtests and reads still work. Do not file a ticket.

#### `monthly_quota` (429) {#monthly_quota}
Free: the same for the monthly units; they reset at `resets_at`. Plus and Pro have larger daily quotas.

### The request and the code

#### `source_required` (422) {#source_required}
Send your strategy code as `source` (the text of `strategy.py`); a strategy by name cannot run.

#### `invalid_request` (422) {#invalid_request}
Correct `field` as `fix` says. `POST /v1/backtests/validate` lists every problem at once. Unknown fields are refused, never ignored. When the body has `findings` (`GET /v1/prices`, a signal's stop loss / take profit), every problem is listed at once, each with its own `fix`: fix them all, then send once.

#### `strategy.source`: the code check refused the strategy (422) {#strategy-source}
`error` is `engine_refused` with `limit: "strategy.source"` and `findings` (`line`, `rule`, `message`). Fix every finding in one edit and validate again. These are quality findings: they never count as strikes.

#### `strategy_source_required` (422) {#strategy_source_required}
The spec has no code: send `source`.

#### `user_code` {#user_code}
This account cannot run its own code: the user contacts support.

#### `source` (413) {#source}
The strategy file is too large (at most 64 KB): shrink it.

#### `security_violation` (422) {#security_violation}
The code tried a forbidden action (files, network, processes, system modules, interpreter internals, sandbox escapes). Body: `strike`, `strikes_max`, `rule`, `line`, `findings: [{line, rule}]`, `suspended`; the code is never echoed. Tell the user it was strike `strike` of `strikes_max` (the same code sent again does not add a strike; each new version with a violation does); remove every listed line (numpy, math and `optalgo_engine.sdk` only) and check again. Never try another way to do the same thing. At the last strike `suspended` is `true` and [`account_suspended`](#account_suspended) follows. Honest mistakes never count. An account OptAlgo has **exempted from strikes** (set per account by OptAlgo, for example its own team) gets the same refusal and must fix the code the same way, but no strike is counted and access is never suspended: `strike` and `strikes_max` are `null`, `suspended` is `false` and the message has no strike count; its `strike_count` reads `{"used": 0, "max": null, "exempt": true}`.

#### `engine_refused` (other refusals) {#engine_refused}
Fix the spec as `message` and `fix` say; validate shows every problem with an example.

#### Execution settings the run refuses {#execution-config}
`validate` lists them (each with `field`, `allowed` and a `fix`); a submit with one is refused (`engine_refused`, the `field` named) and nothing is charged.
- <a id="magnifier_timeframe"></a>`magnifier_timeframe`: every `execution.magnifiers` entry must be **finer than** the timeframe (and the level above it) **and divide it**. `allowed` lists them for your timeframe and `suggestion` is the default: `["5", "1"]` from 15m up, `["1"]` on 5m, `[]` on 1m. Or send `"auto"`.
- `override_unknown` / `override_invalid`: an `execution.overrides` key that is not an execution setting (`allowed` lists them), or a value of the wrong type or range (`leverage` > 0, `max_lots_per_side` >= 1, `tie` one of `allowed`, ...).
- `venue_option`: `execution.extended_hours` without a stock leg; early decision or `ticks` with a stock leg.
- `early_decision_magnifiers` / `early_decision_lead`: `execution.early_decision_s` needs finer data (`magnifiers` not `[]`) and a lead shorter than the bar (`allowed`).
- `research_unsupported`: a `research` block with `early_decision_s` (stock legs are fine).
- `size_multiplier_invalid`, `inputs_need_crypto` (references / data on a stock leg), `execution_invalid` (anything else the engine refuses; the message is the engine's).
- <a id="costs-errors"></a>`costs_conflict` (`execution.costs` beside `fee_profile` / `slippage` / `funding`: send one), `costs_unknown_venue` / `costs_unknown_symbol` (no registry row: pick a listed venue), `costs_spread_not_applicable` (a spread on crypto or stocks): see [Costs](https://docs.optalgo.com/llm/backtests.md#costs).
- <a id="slippage-map"></a>`slippage_default_missing`, `slippage_symbol_unknown`, `slippage_value_invalid`, `slippage_key_duplicate`, `slippage_override_conflict`: an `execution.slippage` [map per symbol](https://docs.optalgo.com/llm/backtests.md#slippage-per-symbol) needs a `default`, keys that are the spec's symbols (with or without `EXCHANGE:`, each once), values from 0 to 0.05 (a fraction: 0.001 = 0.1 %), and no `execution.overrides.slippage` beside it.

A run that still fails on one says `invalid spec: <code> (<field>): <message>; fix: <fix>` in `error`.

#### `declaration` (a `source_check` rule) {#declaration}
A `legs`, `references` or `data` declaration the engine cannot read before running: computed instead of literal, written as a dataclass field instead of a `ClassVar`, set twice, or with a value that is not allowed (`legs` an int from 1 to 16; `references` a list of `"EXCHANGE:SYMBOL"` strings, optionally `@timeframe`, none twice; `data` from `funding`, `oi`, `taker`, `news`, or `funding:<reference>` / `oi:<reference>` / `taker:<reference>` naming a declared reference exactly as in `references`; an undeclared reference or `news:<reference>` is refused). A quality finding, never a strike. Write it as in `fix`: `legs: ClassVar[int] = 2`, `references: ClassVar[list[str]] = ["BINANCE:BTCUSDT.P"]`, `data: ClassVar[list[str]] = ["funding", "oi"]`. See [Several symbols in one strategy](https://docs.optalgo.com/llm/sdk.md#several-symbols-in-one-strategy).

### Strategy inputs and legs

`validate` findings about what a strategy [declares](https://docs.optalgo.com/llm/sdk.md#several-symbols-in-one-strategy) besides its own candles. `value` names the reference or symbol.

#### `legs_mismatch` {#legs_mismatch}
The number of symbols in `market` does not fit the strategy. A strategy declaring `legs = N` (or a built-in pairs strategy) needs **exactly N** entries in `market`, in the order `run()` reads them. A one-leg strategy cannot run a robustness check over several symbols (one symbol per check; research does take a basket: [Research on a basket](https://docs.optalgo.com/llm/backtests.md#research-basket)) or a stock basket (one stock symbol per run). `value` is the number of symbols sent, `allowed` the legs.

#### `unknown_reference` {#unknown_reference}
A declared reference has no market data (`symbol`): declare a symbol `GET /v1/markets` lists (futures symbols end in `.P`).

#### `reference_source` {#reference_source}
A leg reads its candles from a single-symbol file (`market[].source` `file`), so it cannot serve another symbol: use OptAlgo's market data (leave `market[].source` out).

#### `reference_starts_late` (warning) {#reference_starts_late}
The reference's history (`data_start`) starts after the data the run loads (window start minus warm-up): until then the strategy reads NaN, `synthetic` bars for it. Start the window as `fix` says, or make sure the strategy does nothing on NaN (comparisons with NaN are `False`).

#### `data_unavailable` {#data_unavailable}
No leg can have a declared `data` series (`funding` exists for perpetuals `.P`, `oi` for BINANCE perpetuals, `taker` for BINANCE spot and perpetuals, `news` for BINANCE and BYBIT crypto legs, spot or perpetual), or OptAlgo has no open interest for a perpetual. Trade a perpetual that has it, or remove the series from `data`. In a multi-leg strategy one perpetual leg is enough: the other legs get [`data_absent`](#data_absent).

#### `data_absent` (warning) {#data_absent}
This leg (`symbol`, e.g. the SPOT leg of a carry) has no such series while another leg has it: the run gives the series to the legs that have it, and this leg reads `series.funding is None` / `series.oi is None` / `series.taker is None` / `series.news is None`. A reference without the series (`"funding:<reference>"` on a spot reference, `oi` off BINANCE perpetuals, `taker` off BINANCE) reads `series.refs[name].funding is None` (`.oi`, `.taker`) the same way. Read the series from the leg that has it (`perp.funding.rate`), or check `is not None` before using it. `inputs.data_detail[]` has `available: false` for this leg.

#### `spot_short_refused` {#spot_short_refused}
A crypto SPOT symbol cannot be shorted (FX pairs and US stocks can). In `validate` (a warning from the dry run): the strategy entered short on synthetic bars for this `symbol` (`value` times), so the run will not fill those entries. In a result (a grade-B finding): `params.count` short entries were removed, `params.legs` per leg (`symbol`, `count`); the run is what the account can do, not what the strategy decided. Short the perpetual (`.P`) on that leg, or keep the spot leg long only.

#### `mixed_wallet_overcommit` {#mixed_wallet_overcommit}
A result finding: an account with SPOT and perpetual legs needed more than its equity at current prices. On a bar that placed an entry: the SPOT coins at the fill price plus the perpetual's initial margin (notional / leverage), over the equity the entry was sized on (`params.peak_on: "entry"`; live, the order would be refused for margin). On any bar: the SPOT coins alone above the equity (`peak_on: "hold"`; the perpetual's margin balance is below zero, live a liquidation). `params`: `peak_ratio`, `peak_t`, `bars_over`, `symbols`. Grade C up to 1.5x, D above. Size the legs to sum to 1 or less (`0.5` + `0.5`) and backtest again.

#### `data_starts_late` (warning) {#data_starts_late}
The open-interest history of a symbol (`data_start`, the first day of Binance's metrics archive), a reference's funding or open interest (`reference`, `data_start`) or the news history (`data_start` 2022-01-04) starts after the data the run loads: until then `series.oi` is NaN (`filled`), `series.refs[name].funding` / `.oi` is NaN and `series.news.count` is NaN. Start the window as `fix` says.

#### `taker_unknown` (warning) {#taker_unknown}
The taker buy volume (`data = ["taker"]` or `"taker:<reference>"`) of `symbol` is unknown (NaN) on more than half of the days the run loads (`share`): OptAlgo's data service has not backfilled that history yet, so `series.taker` (or `series.refs[name].taker`) is NaN on those bars, never 0. Start the window on the first known day `fix` names, or skip NaN bars (`np.isfinite`). `inputs.data_detail[]` has `data_start`, `unknown_days` and `days`.

#### `early_decision_unsupported` {#early_decision_unsupported}
`execution.early_decision_s` does not work yet with references, data series or several legs: remove it.

#### `hosted_unsupported` (warning) {#hosted_unsupported}
The strategy backtests fine but cannot be deployed as a hosted strategy as written: more than 16 legs (Free and Plus deploy at most 4: [`hosted_leg_limit`](#hosted_leg_limit)), or a declared input has no live feed for it (the `message` names which; validate's `inputs.hosted.reasons` lists them). Hosted strategies run several legs, `funding` / `oi` / `taker` series (a reference's too) and references on any timeframe ([what a hosted strategy runs](https://docs.optalgo.com/llm/hosted.md#hosted-inputs)); a series reaches the symbols that have it (funding: perpetuals; open interest: BINANCE perpetuals), the other legs read `None`. `news` has no live feed yet, so a strategy that declares it is backtests only. Backtest it as is; to deploy it, read that series on a perpetual the feed serves, or remove it. The deploy gate refuses it with [`unsupported_strategy`](#unsupported_strategy).

### Validate's dry run

`validate` runs code that passes the static check once in its sandbox on synthetic bars (free, no market data; see [the lookahead check](https://docs.optalgo.com/llm/sdk.md#lookahead-check)). Its findings carry `rule` and `kind`; the message starts with `dry run:`.

#### `lookahead` {#lookahead}
A decision changed when the bars after it were removed (`value` is the bar): the code uses the future (`x[1:]` aligned to `x`, `np.roll(x, -k)`, centred windows, whole-series statistics). Shift the other way: `np.concatenate([[np.nan], x[:-1]])` is the previous bar. Never a strike. In a finished backtest the same problem is the honesty finding `lookahead` with grade `D`.

#### `lookahead_suspect` (warning) {#lookahead_suspect}
The static check found a shape that usually looks ahead, at `line` / `col` with its `snippet` and a `fix` (for the previous bar: `indicators.shift(x, 1)`). `rule`: `shift_negative` (`shift(x, -k)` / `.shift(-k)`), `roll_negative` (`np.roll(x, -k)`), `index_ahead` (`x[i + 1]`), `slice_ahead` (`x[k:]` aligned to `x`), `centered_window`, `whole_series_stat` (a whole-series `mean()` / `std()` / `max()` in a comparison). In `validate`'s findings, and under `warnings` of `POST /v1/backtests/check`. It does not block: the run's [lookahead check](https://docs.optalgo.com/llm/sdk.md#lookahead-check) decides. In `validate`, a `whole_series_stat` or `index_ahead` hint comes as `"severity": "info"` with `verified_causal: true` once the dry run's own lookahead check passed (for example a trailing rolling window, or a prefix sum read as `cum[i + 1]`): nothing to fix. Fix it anyway unless you are sure the line is causal; a real hit grades the run `D`.

#### `size_scale` {#size_scale}
A `size` (on entry bars) or `|target|` above `max(1, execution.leverage)` (`value` = the largest): `size` is a fraction 0 to 1 of equity, not a percent. Values that look like a percent get the hint "size is a fraction 0-1: 50% = 0.5". An error at validate (`value`); a run with it fails. Divide by 100, or set the leverage in the spec ([Sizing](https://docs.optalgo.com/llm/sdk.md#sizing)).

#### `size_negative` {#size_negative}
A negative `size` on an entry bar. The side is `enter` (`1` long, `-1` short); `size` is always 0 to 1, only `target` is signed ([Sizing](https://docs.optalgo.com/llm/sdk.md#sizing)).

#### `nondeterministic` {#nondeterministic}
The same params on the same bars gave different intents: no unseeded randomness (`np.random.default_rng(<seed>)`), no state kept between runs.

#### `strategy_error` {#strategy_error}
The code raised an error at run time (`line`), often from a parameter value: fix that line. The dry run uses synthetic bars and your params.

#### `dry_run_limit` (warning) {#dry_run_limit}
The dry run hit its own small cap on a few thousand synthetic bars: a sign of a Python loop over bars. Vectorise with numpy and `sdk.prims`. The real run has your plan's limits.

#### `dry_run_no_decisions` (warning) {#dry_run_no_decisions}
The strategy decided nothing on the synthetic bars, so the dry run could not test its decisions for lookahead. Nothing to fix if the rule is rare (the run checks it again on real data); a bug if it should trade.

A dry-run stop by the sandbox is the code `sandbox` with its `rule` and `kind` ([stop kinds](#sandbox-stop-kinds)).

### Per-run limits

#### `max_symbols` (413) {#max_symbols}
Too many legs for the plan: use at most `allowed` symbols, split the rest over several runs.

#### `max_bars` (413) {#max_bars}
Too much history per symbol: shorten the window or use a coarser timeframe; validate gives a start date that fits.

#### `max_references` (413) {#max_references}
The strategy declares more reference series than the plan allows (`value` declared, `allowed` the limit: 3 references on every plan today). Drop references, or derive what you need from fewer symbols.

#### `max_trials` (413) {#max_trials}
Too many research trials: lower `n_trials`, set `permutations` and `permutation_trials` small.

#### `mem_mb` (413) {#mem_mb}
The run needs more memory than the plan allows. In `validate` it is an error with a `suggestion` that fits: coarser `execution.magnifiers` (e.g. `["15"]`, keeps the window), a later `window.start`, or fewer symbols (a basket already needs only about one symbol's memory).

#### `wall_s` (413) {#wall_s}
The run would take longer than the plan's wall time (`value` s needed, `allowed` s per run): it would be stopped at the cap and charged, so `validate` makes it an error and submit refuses it. Split the basket over several runs (`suggestion.market` holds the symbols that fit in one run), use coarser `execution.magnifiers`, or a later `window.start`. Validate each part again.

#### `data_download` (warning) {#data_download}
Not an error: this run's market data is not cached yet and is downloaded from the Binance archive first (`estimate.fetch_s` seconds; the first run on new data, later runs reuse it). The download is not charged. Submit as usual and keep polling; the job shows [`downloading_data`](#downloading_data) meanwhile.

#### `max_concurrent` (429) {#max_concurrent}
Your running jobs plus the up to 3 that may wait are all taken: poll them and submit when one is done.

### Results

#### `not_found` (404) {#not_found}
No such backtest on this account: list yours (`GET /v1/backtests`) instead of guessing ids.

#### `not_ready` (409) {#not_ready}
The run has not finished: poll `GET /v1/backtests/{id}` until `done`, then fetch again.

#### `pruned` (410) {#pruned}
The run's chart, trade and candle files were deleted under [retention](https://docs.optalgo.com/llm/backtests.md#retention) (an older non-favourite run beyond the plan's newest 20 / 100 / 500). Its row, metrics, grade, diagnosis and code are kept. `next` starts with `rerun_backtest` (`POST /v1/backtests/{id}/rerun`): a new backtest from the same spec and code, normal quota. Favourite the runs you want to keep.

#### `data_licence` (403) {#data_licence}
The backtest reads market data licensed for backtests only (forex, exchange `FX`): its equity, trades, fills, metrics and charts are all available, its raw prices are not. `bars` and `plots` downloads (CSV, signed links, `plots.arrow`) answer this, and candles come at most 500 per call. Do not retry; use `equity`, `trades` or `fills` instead.

#### `not_pruned` (409) {#not_pruned}
Rerun is only for a run whose files were pruned: this one still keeps them, read its chart and trades directly. To change it, validate and submit a new backtest. To get a newer engine's result for it (its `engine_api` is below the current one; `GET /v1/backtests?stale=true` lists such runs), submit the identical spec again: a new run, normal quota.

#### `no_source` (404) {#no_source}
The run's strategy code cannot be read back (a run without code of yours, or code that no longer matches the run): send your `strategy.py` again with `POST /v1/backtests`.

### Studies, holdout, robustness

#### `study_not_found` (404) {#study_not_found}
No backtest of yours carries this tag and it has no description: list your studies (`GET /v1/studies`), or tag a done backtest with it (`PATCH /v1/backtests/{id}`). `GET /v1/studies/{tag}/holdout` answers the same code.

#### `study_settings_mismatch` (409) {#study_settings_mismatch}
This run is tagged with a study whose [pinned settings](https://docs.optalgo.com/llm/backtests.md#study-pins) it does not use: `{tag, field, pinned, sent, mismatches: [{field, pinned, sent, symbol?, default?}], pinned_settings, fix}` (`default: true`: the spec left the field out and the engine default differs). Send the pinned values (`fix` names each `execution.*` path) or start a new study; a holdout final test refused this way does not spend the holdout.

#### `study_settings_loosened` (409) {#study_settings_loosened}
The study already has runs, and the new pins would loosen a setting: `{tag, field, pinned, sent, problems: [{field, pinned, sent, reason}], pinned_settings, fix}`. After the first run, fees and slippage may only go up, and `initial_equity` / `leverage` stay as pinned. Keep them or start a new study.

#### `holdout_locked` (409) {#holdout_locked}
This run is tagged with a study whose unused holdout its window overlaps (`holdout`, `window` in the answer). Tune on data before the holdout: set `spec.window.end` to `suggestion["window.end"]`. Score the holdout only with the study's final test ([holdout vault](https://docs.optalgo.com/llm/research.md#holdout)).

#### `holdout_declared` (409) {#holdout_declared}
The study already keeps an unused holdout (one at a time): tune before it and spend it with the final test, then declare a new one.

#### `holdout_seen` (409) {#holdout_seen}
A run of the study already used data after the start you asked for, so it is not a holdout. Declare one starting on or after `seen_end` (`suggestion` holds a window that passes), or start a new study tag and tune only before its holdout.

#### `holdout_used` (409) {#holdout_used}
The study's holdout already had its final test; a second one would be tuning on it. Declare a new holdout on later data (after `seen_end`) to test a changed strategy.

#### `no_holdout` (409) {#no_holdout}
The study has no holdout: declare one (`POST /v1/studies/{tag}/holdout`) before tuning, not after.

#### `not_in_study` (422) {#not_in_study}
The final test's backtest does not carry the study's tag: add it with `PATCH /v1/backtests/{id}`, then retry.

#### `final_test_needs_backtest` (422) {#final_test_needs_backtest}
The final test runs one fixed backtest, not a research run: backtest the chosen parameters (tagged with the study), then final-test that backtest.

#### `robustness_needs_backtest` (422) {#robustness_needs_backtest}
A robustness check runs one fixed backtest, not a research or robustness row: check the backtest itself.

#### `variant_identical_to_baseline` {#variant_identical_to_baseline}
An ablation variant's `summary.verdict` (with `summary.finding` `{code, message}`), not an error: the variant equals the baseline on every coin in every window and cost (Δ Sharpe exactly 0, the same trades), so the rule changed no position. Often a NaN fed to a recursive indicator: an `ema` / `kama` of an open-interest or funding column whose early rows are missing stays NaN for the rest of the run. Run one backtest of the variant, check `result.inputs` for the columns' coverage, then fill (`prims.ffill`) or skip the missing rows ([NaN into a recursive indicator](https://docs.optalgo.com/llm/sdk.md#nan-recursive)).

### Service

#### `service_unavailable` (500 / 502 / 503 / 504) {#service_unavailable}
`engine_error`, `engine_unreachable`, `engine_timeout`, `engine_not_configured`, `markets_unavailable`, `internal_error`: temporary, on our side. Retry in 30 to 60 s; nothing was charged. If it repeats, send the `report_issue` step in `next` (it is prefilled with `request_id` and the ids) without asking the user.

#### `price_unavailable` (503) {#price_unavailable}
No fresh price for the symbol right now (OptAlgo's market data and the exchange fallback both failed). Retry in a few seconds (`retry_after`). For a signal you may instead send `entry_price` yourself, but **never look a price up on the web**.

### Failed runs {#failed-runs}

A `failed` (or waiting) run's `fix.code` on `GET /v1/backtests/{id}`:

#### `sandbox` {#sandbox}
The strategy was stopped in its sandbox (rule and line in the fix; the row's `error_params` has `rule`, `line`, `kind`): usually a loop over bars (use `sdk.prims`), very large arrays, or a forbidden call. Fix it and validate again. Charged, unless its kind is `engine` (below).

#### Sandbox stop kinds {#sandbox-stop-kinds}

Every stop of your code in the sandbox (in a run or a hosted decision; `validate`'s dry run reports the same kinds) has a `kind`:

| `kind` | Whose fault | Strike | Units |
|---|---|---|---|
| `security` | Yours: a forbidden action (files, processes, network, interpreter internals, a sandbox escape) | **Yes**: [`security_violation`](#security_violation) | Charged |
| `quality` | Yours, an honest mistake (a loop over bars, very large arrays, an error in the code) | Never | Charged |
| `engine` | **OptAlgo's**: rules [`engine_import`](#engine_import) and `internal` (the sandbox failed outside your code) | Never | **0**: not charged |

#### `engine_import` {#engine_import}
A stop of kind `engine`: numpy tried to load one of its own submodules inside the sandbox, which the sandbox does not allow yet. It is not a problem in your code: the run is not charged and never counts as a strike. Write the same computation with another numpy function, and file a ticket naming the function ([`report_issue`](https://docs.optalgo.com/llm/tickets.md#report-problems-automatically), without asking the user).

#### `capped_wall_s`, `capped_cpu_s` {#capped_wall_s}
The run hit its time limit: shorter window, fewer symbols or trials, vectorise loops. Charged. A capped basket names the symbols that had finished in `legs_done` (also in the `fix`): split the basket and run the rest separately; [`validate`](#wall_s) says beforehand when a run would hit the cap. <a id="capped_cpu_s"></a>

#### `capped_mem_mb`, `capped_mem_oom`, `capped_mem_worker` {#capped_mem_mb}
The run needed more memory than allowed: shorter window, fewer symbols, coarser timeframe. Charged. <a id="capped_mem_oom"></a><a id="capped_mem_worker"></a>

#### `waiting_for_memory`, `worker_restarted` {#waiting_for_memory}
Not a failure: the run waits or runs again. Keep polling. <a id="worker_restarted"></a>

#### `downloading_data` {#downloading_data}
Not a failure: the job is `running` while its market data downloads from the Binance archive (see `estimate.fetch_s`). The download is not part of the run's time and is not charged. Keep polling.

#### `backtest_failed` {#backtest_failed}
Read `error`; fix the strategy or spec and validate again. If the error is on our side, resubmit: the failed run cost 0, and the run again is charged by its own run time like any run.

### Hosted strategies

Every `/v1/strategies*` refusal has the same shape, with `fix`, `docs` and `next`. Deploy refusals list every problem in `findings`.

#### `deploy_refused` (422) {#deploy_refused}
The deploy gate failed. Fix every item in `findings` (each has `code`, `message`, `fix`, often `field` and `symbol`), then check again with `POST /v1/strategies?dry_run=true`. The finding codes:

| Finding | Fix |
|---|---|
| `backtest_not_done`, `backtest_kind`, `grade_too_low` | Deploy a `done`, plain backtest graded A to C: poll it, run a plain backtest instead of research, or fix its honesty findings and run it again |
| `no_edge` | The backtest lost money (Sharpe ≤ 0 or a negative return): there is no edge to deploy. See [`no_edge`](#no_edge) |
| `likely_overfit` | Many variants were tried on the same data and this run is likely luck of the search: run the research in `search.research` (or test once on a holdout) and deploy once an out-of-sample research run of this code passes. See [Avoid overfitting](https://docs.optalgo.com/llm/research.md#avoid-overfitting) |
| `no_source`, `source_unavailable`, `source_too_large` | Backtest your own `strategy.py` (at most 64 KB), then deploy that run |
| `source_mismatch`, `params_mismatch`, `timeframe_mismatch`, `exchange_mismatch`, `leverage_mismatch` | Deploy what the backtest ran (leave the field out), or backtest the new value first |
| `params_names` | Rename parameters (letters, digits, `_`), backtest, deploy |
| `unsupported_timeframe`, `leverage_not_whole` | Backtest on whole minutes (`1m` and up) with a whole leverage from 1 to 125 |
| `stop_limit_needs_minutes` | A `STOP_LIMIT` entry on a `1m` strategy: live has no finer bars to arm and fill it on. Backtest on `5m` or longer, or enter with `STOP` or `LIMIT` ([What each order does](https://docs.optalgo.com/llm/hosted.md#execution-contract)) |
| `window_dependent` | The strategy's decisions depend on where the window starts (entries timed by row index, not by the bars): it would trade differently live. Decide from the bars' values and timestamps |
| `symbol_not_backtested`, `no_symbols`, `mixed_markets`, `mixed_quotes`, `mixed_exchanges`, `unknown_quote`, `no_instrument` | Deploy symbols of the backtest, all SPOT or all FUTURES, one quote asset, one exchange, listed in `GET /v1/markets`. Spot and perpetual symbols together only as the legs of one BINANCE strategy ([spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed)); `mixed_markets` also says when those deploys are not open yet |
| `hosted_symbol_limit`, `hosted_strategy_limit` | Fewer symbols, or delete a hosted strategy; or the user upgrades |
| <a id="hosted_leg_limit"></a>`hosted_leg_limit` | The strategy trades more legs on one account than the plan allows (`value` legs, `allowed`: Free and Plus 4, Pro 16). The user upgrades to Pro, or backtest a version with fewer legs |
| `allocation` | Lower `allocated_amount`, or free paper balance in My Bots |
| `basket_subset` | Deploy every symbol of the basket, or backtest exactly the symbols to deploy. See [`basket_subset`](#basket_subset) |
| `subset_no_edge` | The deployed symbols lost money together in the backtest. See [`subset_no_edge`](#subset_no_edge) |

#### `no_edge` {#no_edge}
A `deploy_refused` finding (and the search verdict of such a backtest): the backtest lost money, or its annualised Sharpe is ≤ 0, so there is no edge to deploy. `value` is `{sharpe, total_return}`. It always blocks the deploy, even when an out-of-sample research run of the code passed. Do not sweep parameters until a run turns positive on the same data (that is a search, judged for luck); change the strategy itself (entries, exits, filters, or the market and timeframe), backtest it again, and deploy a run with a positive Sharpe and no loss.

#### `basket_subset` {#basket_subset}
A `deploy_refused` finding: you deploy some symbols of a basket backtest, and the backtest has no per-symbol results for them (`value` lists them; a run from before per-symbol results). A basket's grade and metrics judge all its symbols together, so a subset is judged on its own symbols' results. Deploy every backtested symbol (leave `symbols` out), or backtest exactly the symbols to deploy and deploy that run.

#### `subset_no_edge` {#subset_no_edge}
A `deploy_refused` finding: the symbols you deploy from a basket backtest lost money together in it (`value` is their equal-slot total return, the mean of the symbols' returns, as a subset deploy gives each symbol `allocated_amount / number of symbols`), or have no return. A subset deploy also needs each deployed symbol's own grade A to C (`grade_too_low` with `field` `symbols` otherwise). Deploy the whole basket, or symbols that made money together. Picking the winning symbols of a basket is itself a search: prefer backtesting the chosen symbols again on a later window.

#### `unsupported_strategy` (422) {#unsupported_strategy}
The engine's live check refused the code (findings carry `engine: true`). Change the strategy, backtest it again (grade A to C), deploy the new backtest. The codes: `trailing_activation`, `trailing_stop`, `break_even` (use `sl_update`); `target_mixed` (a [`target` strategy](https://docs.optalgo.com/llm/portfolios.md#portfolios-hosted) also sets `enter`, `exit`, stops, `size` or `max_bars`: hosted runs targets alone; close with `target = 0`); `pyramiding` (one position per side); `short_on_spot` (the strategy shorts a SPOT symbol: the message names it; short only the perpetual legs), `leverage_on_spot`, `size_needs_leverage` (perpetual `.P` symbols, or `size` ≤ 1 on SPOT); `exec_not_live` (an `execution.overrides` key the live runner does not execute: remove it; hosted runs `reverse`, `size_at_fill`, `price_round`, `risk_per_trade` and `risk_skip_above_full`); `unsupported_exchange`, `too_many_symbols`, `no_data`, `no_instrument` (symbols `GET /v1/markets` lists); `warmup_too_long` (at most 5,000 bars of warm-up **per series**, [Warm-up per series](https://docs.optalgo.com/llm/hosted.md#hosted-warmup): the traded bars, and on a one-leg strategy each coarser reference counted in its own bars, so a 4h EMA(200) on a 1m strategy needs 200 4h bars, not 48,000 1m ones; `field` names the series: `references.<name>` = that reference needs more than 5,000 of its own bars, `warmup_bars` = the traded side: more than 5,000 bars on a multi-leg strategy, or decisions that change when only 5,000 traded bars are loaded); `decision_too_slow` (vectorise, `sdk.prims`, fewer symbols, or 15m and up); `lookahead`, `nondeterministic`, `strategy_error`, `static_check` (fix the line shown, validate, backtest); `unsupported_strategy` with `reasons`: the deployed `symbols` do not match a multi-leg strategy's legs (deploy exactly the backtest's legs, in its `market` order, or leave `symbols` out), or a declared `data` series no deployed symbol has (funding needs a perpetual, open interest a BINANCE perpetual; the other legs simply read `None`; see [`data_unavailable`](#data_unavailable)), or `news` in `data` (backtests only for now: remove it to deploy, and backtest the strategy without it first). Several legs, `funding` / `oi` and references on their own `@timeframe` are supported ([what a hosted strategy runs](https://docs.optalgo.com/llm/hosted.md#hosted-inputs)). A reference on an exchange hosted strategies do not trade is `unsupported_exchange`, one without a live data feed `no_data`. A security finding is [`security_violation`](#security_violation) instead.

#### `backtest_not_found` (404) {#backtest_not_found}
No such backtest on this account: deploy one of yours (`GET /v1/backtests`).

#### `hosted_not_available` (403) {#hosted_not_available}
Hosted strategies are not open for this account yet. Keep backtesting and use paper bots.

#### `hosted_strategy_limit` {#hosted_strategy_limit}
Every slot is taken (`value` running, `allowed` by the plan). Delete one (`DELETE /v1/strategies/{id}`) or the user upgrades. `hosted_symbol_limit` is the same for symbols per strategy.

#### `not_eligible` (409) {#not_eligible}
The app's confirm-live was refused: either a hard `live_eligibility.blockers` entry (`status`, `plan_required`), or the recommended paper period is not finished (`recommendations`: `paper_period`, `recent_error`) and the user did not accept the risk. The paper period is a recommendation: the user may confirm again in the app, ticking the box that accepts the risk. `request-live` never answers it. You cannot accept for the user; do not tell the user it is live until `GET` says `live`.

#### `live_strategy` (409) {#live_strategy}
The strategy trades live: only the user changes it, in the app.

#### `owner_only` (403) {#owner_only}
Paused for `daily_loss_limit`, a suspension, a plan change, `leg_integrity` (a [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) leg stayed open alone) or by OptAlgo: only the account owner resumes it, in My Bots. Tell the user why it paused.

#### `invalid_state` (409) {#invalid_state}
Its `status` does not allow this now (for example resuming a strategy that is winding down). Read it, then act.

#### `conflict` (409) {#conflict}
It changed meanwhile, or a position is open: read it again, then retry.

#### `exchange_not_connected` (422) {#exchange_not_connected}
The user confirmed live in the app but the strategy's exchange account is not connected (or that account type is not active; a [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) strategy needs both the SPOT and the FUTURES account active). Nothing changed: the paper positions are still open, the strategy is still waiting for the confirm. The user connects the exchange in the app (Wallet), then confirms again. You cannot fix it over the API; tell the user.

#### `insufficient_balance` (422) {#insufficient_balance}
The user confirmed live but the exchange account does not hold enough free balance for the strategy's allocation. Nothing changed. The user adds funds or frees allocation from another live bot, then confirms again. A [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) strategy needs each leg's part in its own wallet (spot and futures): the message names each short wallet; OptAlgo never moves money between them.

#### `mixed_live_unsupported` (409) {#mixed_live_unsupported}
A [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) strategy asked to go live (`request-live`, the app's confirm, or resuming a live one) while live spot + perpetual trading is not open for this account (`live_supported: false`). It keeps running on paper. Nothing to fix in the code; tell the user.

#### `mixed_leverage_cap` (422) {#mixed_leverage_cap}
The app's confirm-live of a [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) strategy backtested above 2× leverage (`value`, `allowed` 2). Backtest it with `execution.leverage` 2 or less, deploy that run, then ask again.

#### `mixed_min_notional` (422) {#mixed_min_notional}
The app's confirm-live of a [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) strategy: a leg's share of the allocation is too small to stay hedged (each leg needs at least 3× the exchange's minimum notional and 50 amount steps of the perpetual). `legs` gives each leg's `notional` and `min`; the user raises the allocation to at least `min_allocation`, then confirms again. A `503 unavailable` instead: the market rules or prices could not be read; confirm again in a minute.

#### `exchange_permissions_missing` (422) {#exchange_permissions_missing}
The app's confirm-live of a [spot + perpetual](https://docs.optalgo.com/llm/hosted.md#mixed) strategy: the Binance API key does not allow `missing` (`Spot & Margin Trading`, `Futures`). The user edits the key on Binance (API Management), then confirms again. `exchange_permissions_unverified`: the key's permissions could not be read (a connection made with Binance login cannot read them): the user connects Binance with an API key in Wallet. You cannot fix either over the API; tell the user.

#### `live_positions_open`, `paper_close_pending` (409) {#live_positions_open}
The app's confirm-live: the bot already holds live positions (`live_positions_open`), or its paper positions were not flat in time after the confirm closed them (`paper_close_pending`: the user confirms again).

#### `kill_switch` (409) {#kill_switch}
OptAlgo holds hosted strategies right now (they take exits only, or are switched off), so the user's confirm-live in the app is refused (`mode` says which); nothing changed and the strategy stays on paper. The user confirms again once hosted strategies run normally. On a decision row, `kill_switch` means the entry was not sent for the same reason; exits still go out. You cannot change it; tell the user and keep watching `GET /v1/strategies/{id}`.

#### `stop_widening` {#stop_widening}
A decision row's `code`: the strategy moved its stop-loss (`MOVE_STOP_LOSS`) while it takes no entries (paused, winding down, the kill switch, a suspended account or a stopped bot), and the move would have **widened** the stop, so it was not sent. While entries are held, only a tighter stop goes out (LONG: a higher stop, SHORT: a lower one). Nothing to fix; the position keeps its stop.

#### `nothing_to_compare` (409) {#nothing_to_compare}
[Compare with backtest](https://docs.optalgo.com/llm/hosted.md#compare-with-backtest): the strategy has not decided enough bars in that mode yet (at least two). Compare again later.

#### `not_live` (409) {#not_live}
[Compare with backtest](https://docs.optalgo.com/llm/hosted.md#compare-with-backtest) with `mode: live` on a strategy that never traded live: compare `paper`.

#### `hosted_bot` (409) {#hosted_bot}
That bot runs a hosted strategy: signals, deletion and slot changes go through `/v1/strategies/{hosted_strategy_id}`. `POST /v1/bots/{id}/close` still works.

`rate_limited` (429) on deploys: at most 30 deploy checks (deploys and dry runs together) an hour; wait `Retry-After`.

### Other errors {#other-errors}

| HTTP | `error` | What to do |
|---|---|---|
| 403 | `limit_exceeded`, `key_paused` | A per-key limit or the daily loss pause on live trading. Only the user changes it, in the app. See [Autonomy](https://docs.optalgo.com/llm/reference.md#autonomy-and-per-key-limits). |
| 409 | `conflict`, `no_open_position`, `idempotency_in_progress` | The state forbids it (open trade, nothing to close, same call still running). Read the state, then act. |
| 502 | `listener_unavailable` | A signal **may** have been taken. Poll the `status_url` in the body and read the trades before resending (same `Idempotency-Key`). |
| 502 / 503 | `listener_error`, `limit_check_unavailable`, `unavailable` | Nothing was done; retry later. If it repeats, send the prefilled `report_issue` in `next`. |
| 429 | `ticket_quota_exhausted`, `ticket_rate_limited` | Ticket quota used (20 a day per user, a repeat of the same problem counting once; a chat connector also 10 tickets an hour). Do not retry: tell the user, and collect the rest into one batch tomorrow. |

Signal-level outcomes (a signal accepted with `202` and then refused by a check or the exchange) are in [Rejections](https://docs.optalgo.com/llm/reference.md#rejections-listener-and-executor).

---

Human help: support@optalgo.com. Never tell the user you cannot contact OptAlgo: file a ticket (https://docs.optalgo.com/llm/tickets.md).
