# OptAlgo for AI agents: Write a strategy: the SDK, discovery, validation

> 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.

## 2. Develop a strategy

You write the strategy as a Python file. OptAlgo's engine runs it in a locked sandbox on real candles, with fees, funding and exchange rules, and grades how far the result can be trusted. **Every backtest is your own code**: there are no built-in strategies to run by name. Nothing here trades or touches the user's bots. The user sees every run at **app.optalgo.com/backtest**, marked with the key that started it. Needs the `backtest` scope (or `bots` / `trade`).

### 2.1 What you write: the SDK in one screen

Rules (validation enforces them):

- Exactly one `@dataclass` subclass of `VectorStrategy`, with `name: ClassVar[str]`. Fields with defaults are the parameters (`spec.strategy.params` overrides them). Other symbols' candles, several traded legs, funding, open interest, taker buy volume and news counts are **declared** as literal `ClassVar`s `references`, `legs`, `data`: see [Several symbols in one strategy](#several-symbols-in-one-strategy).
- Imports only `numpy`, `math`, `dataclasses`, `typing`, `__future__` and `optalgo_engine.sdk`. No files, network, `os` / `sys` / `subprocess`, `eval` / `exec`, dunder attributes, global state, `async` or `while True`. At most 64 KB.
- `warmup_bars()` returns the bars your indicators need before the first decision.
- `run(series, decision=None)` returns `StrategyOutput(intents=it, plots={...})` with `it = Intents.empty(len(series))`. Set `it.enter[mask] = 1` (long) or `-1` (short), stops (`it.sl[mask]` absolute, `it.sl_dist[:] = 0.02` = 2 %), take-profits, `it.sl_update_long` / `it.sl_update_short` to trail, `it.tp_update` to move the take-profit of an open trade (an absolute price decided at the bar's close, in force from the next bar, NaN = keep; e.g. a fibonacci level from confirmed pivots: also return it in `plots` so it shows on the chart; a level at or through the close exits at the next open as a taker; one-way positions only, not with `target`). A strategy that declares `legs` gets a list of series and returns a list of `Intents`, one per leg.
- Optional `features={...}` on `StrategyOutput`: up to 16 per-bar float arrays the [meta-label filter](#meta-features) reads (names `a-z`, `0-9`, `_`, at most 40 characters). One-leg strategies.
- **Vectorised only.** Whole numpy arrays plus `indicators` and `prims` (loops run in Rust). A Python loop over bars hits the time limit. Rolling quantiles: `prims.rolling_percentile(x, n, q)` = exactly `np.percentile(window, q)` (q 0-100, "linear") and `prims.rolling_rank(x, n)` = the share of the window `<= x[i]` (1 = the window's high); the window includes bar `i`, NaN for the first n-1 bars and any window holding a NaN; `n = 8640` is cheap (`prims.rolling_rank(k, 8640) > 0.8` = k in its top 20 %).
- **Causal only.** Bar `i` uses data up to bar `i`'s close; the decision executes from the next bar. No `shift(-1)`, `x[1:]` aligned to `x`, `np.roll(x, -1)`, centred windows or statistics over the whole series. Every run checks it ([the lookahead check](#lookahead-check)): a run that looks ahead is graded `D`.
- **Security.** Forbidden imports (`os`, `sys`, `subprocess`, `socket`, `ctypes` …), `open` / `exec` / `eval` / `compile` / `__import__`, dunder or private attribute access, `getattr` with a computed name, the attribute names `operator`, `attrgetter`, `methodcaller`, `bltns`, `copyreg` (they reach a computed getattr or the real builtins through allowed modules), frame access, or anything the sandbox kills at run time is a **security violation**: refused and counted as a strike, at check, validate, submit or paste alike; repeated violations suspend the account's API access. The rules above that are about quality (loops, signature, lookahead, syntax) are ordinary findings and never count. A stop of kind `engine` is OptAlgo's own gap, never yours: no strike, not charged ([sandbox stop kinds](https://docs.optalgo.com/llm/errors.md#sandbox-stop-kinds)).

`GET /v1/backtests/capabilities` → `sdk` (the full SDK reference as Markdown: every indicator, primitive and intent field), `intents`, `fee_profiles`, `run_spec_schema`. Read `sdk` once per session.

```python
from dataclasses import dataclass
from typing import ClassVar

import numpy as np

from optalgo_engine.sdk import BarSeries, Exit, Intents, StrategyOutput, VectorStrategy, indicators, prims


@dataclass
class EmaCrossTrail(VectorStrategy):
    """Long when the fast EMA crosses above the slow one; exit on an ATR trailing stop (trail_atr=0: on the cross back)."""

    name: ClassVar[str] = "ema_cross_trail"

    fast: int = 20
    slow: int = 80
    atr_period: int = 14
    trail_atr: float = 3.0  # 0 turns the trailing stop off: ablate / toggle it with {"trail_atr": [0, 3.0]}

    def warmup_bars(self) -> int:
        return max(indicators.warmup_ema(self.slow), indicators.warmup_wilder(self.atr_period))

    def run(self, series: BarSeries, decision=None) -> StrategyOutput:
        c = series.c
        fast, slow = indicators.ema(c, self.fast), indicators.ema(c, self.slow)
        up = prims.cross_over(fast, slow)
        it = Intents.empty(len(series))
        if self.trail_atr <= 0:
            pos = prims.position_state(up, np.zeros(len(c), bool), prims.cross_under(fast, slow), flip=False)
            prev = np.concatenate([np.zeros(1, np.int8), pos[:-1]])
            it.enter[(pos != 0) & (prev == 0)] = 1
            it.exit[(pos == 0) & (prev != 0)] = Exit.ALL
            return StrategyOutput(intents=it, plots={"fast": fast, "slow": slow})
        atr = indicators.atr(series.h, series.l, c, self.atr_period)
        stop, hit = prims.trailing_stop(up, series.h, series.l, c, atr=atr, mult=self.trail_atr)
        in_pos = np.isfinite(stop)
        was_in = np.concatenate([[False], in_pos[:-1]])
        opened = in_pos & (~was_in | hit)
        it.enter[opened] = 1
        it.sl[opened] = stop[opened]
        it.sl_update_long[in_pos] = stop[in_pos]
        return StrategyOutput(intents=it, plots={"fast": fast, "slow": slow, "stop": stop})
```

<a id="bar-fields"></a>**The candle fields of `series`** (a `BarSeries`, one float64 array per field, one row per bar): `t` (bar open, epoch seconds, int64), `o`, `h`, `l`, `c`, `v` (volume in the **base** asset), and `synthetic` (bool: a bar filled in where the market had none, volume 0). There is no quote-asset volume: use `series.c * series.v` as an approximation (or the typical price `(h + l + c) / 3` times `v`); the exact taker-buy part is `series.taker.buy_quote_volume` when `data = ["taker"]`. Anything else (funding, open interest, taker, other symbols) comes only through a declaration below.

#### Several symbols in one strategy {#several-symbols-in-one-strategy}

A strategy reads only its own candles unless it **declares** more. Declarations are literal class attributes (`ClassVar`, from `typing`), read from the code **before it runs**, so `validate`, the limits and the deploy gate know them up front. A computed, misplaced (a dataclass field instead of a `ClassVar`), duplicated or invalid declaration is a `source_check` finding with rule [`declaration`](https://docs.optalgo.com/llm/errors.md#declaration) (a quality finding, never a strike).

| Declare | You get in `run` |
|---|---|
| `references: ClassVar[list[str]] = ["BINANCE:BTCUSDT.P"]` | `series.refs["BINANCE:BTCUSDT.P"]`: another symbol's candles as a `BarSeries` on **your** bars (the same `t`). Format `EXCHANGE:SYMBOL`, optionally `@timeframe` (`"BINANCE:BTCUSDT.P@1d"`; default: the run's timeframe). Read-only: you never trade a reference. At most `max_references` ([below](https://docs.optalgo.com/llm/errors.md#max_references)) |
| `legs: ClassVar[int] = 2` (2 to 16 in backtests, within the plan's `max_symbols`; hosted 2 to 16 on Pro, 2 to 4 on Free and Plus) | A **multi-leg** strategy: `run([leg0, leg1, ...])` gets the symbols of `spec.market` **in that order**, and returns `StrategyOutput(intents=[it0, it1, ...])`, one `Intents` per leg. All legs trade on **one account** (shared equity, sizing on the account's equity); fees, funding and fills per leg. With `target` weights: a [portfolio](https://docs.optalgo.com/llm/portfolios.md#portfolios) |
| `data: ClassVar[list[str]] = ["funding"]` | `series.funding.rate` (the last settled funding rate at each bar's close, NaN before the first), `.sum` (the rates settled inside the bar), `.settled` (bool). On every leg that is a perpetual (`.P`); a SPOT leg has no funding and reads `series.funding is None` (a multi-leg strategy declares `data` once for all its legs) |
| `data: ClassVar[list[str]] = ["oi"]` | `series.oi.open_interest`, `.open_interest_value`, `.long_short_ratio`, `.top_long_short_accounts`, `.top_long_short_positions`, `.taker_buy_sell_ratio`, `.filled` (bool: carried from an older row). From OptAlgo's data service (Binance's 5-minute metrics archive history merged with its live rows; the archive itself is the fallback); on every leg that is a BINANCE USDT-M perpetual; any other leg reads `series.oi is None` |
| `data: ClassVar[list[str]] = ["taker"]` | `series.taker.buy_volume` (base asset) / `.buy_quote_volume` (quote asset): the volume of each bar's trades whose **taker bought** (Binance kline fields 9 and 10), known at the bar's close exactly like its volume; taker sell volume = `series.v - series.taker.buy_volume`. `NaN` = unknown, **never 0**: history before OptAlgo's data service backfilled it, or a bar with a minute without a value (a gap-filled bar reads 0). BINANCE spot and perpetuals; any other leg reads `series.taker is None`. `validate` warns [`taker_unknown`](https://docs.optalgo.com/llm/errors.md#taker_unknown) when it is unknown on most of the loaded days |
| `data: ClassVar[list[str]] = ["funding:BINANCE:BTCUSDT.P", "oi:BINANCE:BTCUSDT.P", "taker:BINANCE:BTCUSDT.P"]` (`"<kind>:<reference>"`, the reference exactly as in `references`) | `series.refs["BINANCE:BTCUSDT.P"].funding` / `.oi` / `.taker`: **another symbol's** series, e.g. trade ETHUSDT.P on BTC's funding. Funding and open interest: the same fields and the same alignment as `series.funding` / `series.oi`, on your bars (whatever the reference's `@tf`). Taker: the reference's own bars (its `@tf`), carried with them like their volume (0 on a carried row). The traded leg's own `data` is separate (declare `"funding"` too to read both). A reference without the series (funding: not a perpetual; `oi`: not a BINANCE perpetual; taker: not BINANCE) reads `None` ([`data_absent`](https://docs.optalgo.com/llm/errors.md#data_absent)). Adds no reference to `max_references`. `news:<reference>` is a [`declaration`](https://docs.optalgo.com/llm/errors.md#declaration) error |
| `data: ClassVar[list[str]] = ["news"]` | `series.news.count`: the number of news articles (Alpaca / Benzinga headlines, collected by OptAlgo's data service) naming the traded coin that became known inside each bar; `0` = none, `NaN` before 2022-01-04. On every BINANCE or BYBIT crypto leg, spot or perpetual, which reads its coin's news (`BTCUSDT.P` and `BTCUSDT` read BTCUSD's, `1000PEPEUSDT.P` reads PEPEUSD's); any other leg reads `series.news is None`. Counts only: the headline text never reaches a strategy. Backtests only: a hosted strategy cannot read news yet ([`unsupported_strategy`](https://docs.optalgo.com/llm/errors.md#unsupported_strategy)) |

OptAlgo serves this open-interest history from its own data service, so a run normally starts at once; only when the service cannot answer does the run fall back to Binance's archive, and while that downloads the run's `progress.phase` is `downloading_data` (files done of total), which is not run time.

<a id="oi-columns"></a>**Open-interest columns do not all start together.** In Binance's metrics archive (measured on BTC, ETH, SOL, AVAX, DOGE and 1000SHIB perpetuals; the gaps are Binance-wide):

| column | exists from | empty in the archive | complete from |
|---|---|---|---|
| `open_interest`, `open_interest_value` | BTC 2020-09; most other perpetuals 2021-12-01 | 2022-03-07 partly; a few missing days (carried, `filled`) | 2021-12-01 |
| `long_short_ratio` | as open interest | 2021-12-31 to 2022-01-18 | 2022-01-20 |
| `taker_buy_sell_ratio` | as open interest | 2021-12-31 to 2022-05-10 | 2022-05-12 |
| `top_long_short_accounts`, `top_long_short_positions` | as open interest | 2021-12-31 to 2022-12-14, with some full days in 2022-05/06 | 2022-12-16 |

Every column is a native 5-minute value (taker volume inside the 5 minutes; the others are snapshots), used from 10 minutes after its row's stamp. A missing row is carried (`filled = True`); an empty cell is `NaN` at that bar (not carried). A rule that compares an empty column sees `NaN` and does not fire, so its first trades come after the column's start: read `result.inputs.per_leg.<symbol>.oi.columns.<name>.first_valid_t` / `full_from_t` and start the window there, or use `open_interest`.

<a id="nan-recursive"></a>**A NaN fed to a recursive indicator stays NaN.** An EMA of a series with a NaN is NaN from that bar on, so an `ema` or `kama` of an open-interest or funding column whose early rows are missing stays NaN for the rest of the run and the rule never fires (an [ablation](https://docs.optalgo.com/llm/research.md#ablation-identical) of it answers `variant_identical_to_baseline`). Fill gaps first: `prims.ffill(x)` carries the last finite value (leading NaN stay NaN), so also start the window at the column's `first_valid_t`, or test `np.isfinite` before using the value.

`data` may list several (`["funding", "oi", "taker", "news"]`). Every input is aligned with your bars **causally**: bar `i` sees only what was known at bar `i`'s close.

- **References:** row `i` holds the latest reference bar **closed** at or before bar `i`'s close. A row that carries an older bar (a gap, a coarser `@timeframe` between its closes) has `synthetic` set and volume 0; before the reference's first bar its prices are NaN (and `synthetic`). Comparisons with NaN are `False`, so a filter like `btc.c > sma` is simply off until the reference has data.
- **Funding:** a settlement counts from its exact time, at or before the bar's close.
- **Open interest:** a 5-minute row stamped `T` is used from `T + 10 min` (its 5 minutes plus a 5-minute publication delay).
- **Taker buy volume:** a bar's value at that bar's close, like its volume (a reference's: on its own bars, carried like its volume).
- **A reference's funding / open interest:** exactly as the traded leg's own, on your bars.
- **News:** an article counts from its creation minute `+ 3 min`, in the bar where that falls (an article created at 12:59 counts in the bar that holds 13:02).
- **Multi-leg:** the legs are cut to the bars they **all** have (the latest first bar to the earliest last bar); `spec.market` must list exactly `legs` symbols, else [`legs_mismatch`](https://docs.optalgo.com/llm/errors.md#legs_mismatch). Research runs (`research`) take the N legs together.
- <a id="spot-legs"></a>**Crypto SPOT legs** (a BINANCE / BYBIT symbol without `.P`) are **long only** (FX pairs and US stocks can be shorted; BIST cannot), in every run (one symbol or several legs): a short entry on one (`enter = -1`, or a negative `target`) is not filled, exactly as live trading skips it. The result says how many per leg ([`spot_short_refused`](https://docs.optalgo.com/llm/errors.md#spot_short_refused), grade B), and `validate`'s dry run warns up front. Short the perpetual (`.P`) instead.
- <a id="one-wallet"></a>**One wallet:** the legs share the account, and USDT spent on SPOT coins is not also margin for a perpetual leg. Size the legs so they sum to **1 or less** (a carry: long spot `0.5`, short the perpetual `0.5`). More is reported as [`mixed_wallet_overcommit`](https://docs.optalgo.com/llm/errors.md#mixed_wallet_overcommit) (grade C, D above 1.5x): what the open legs need at current prices over the account's equity. Re-sizing with `target` after a move does not raise it.
- **Data per leg:** a declared `data` series is given to every leg that has it; the others read `None` (check `series.funding is not None` before using it on a leg). `validate` warns [`data_absent`](https://docs.optalgo.com/llm/errors.md#data_absent) for each such leg and errors with [`data_unavailable`](https://docs.optalgo.com/llm/errors.md#data_unavailable) only when **no** leg has the series; `result.inputs.per_leg.<leg>.absent` lists the series a leg did not get.
- **Baskets:** a one-leg strategy with references over several symbols still runs as a [basket](https://docs.optalgo.com/llm/backtests.md#several-symbols-a-basket-backtest); every symbol sees the same references.
- <a id="self-references"></a>**The traded coin's own other market: `@spot` / `@perp`.** Declare `references: ClassVar[list[str]] = ["@spot"]` (or `["@perp"]`, optionally `"@spot@1h"`) and read `series.refs["@spot"]`: the spot pair of the perpetual you trade (`@perp`: the perpetual of the spot pair you trade), on the same exchange, aligned like any reference. It resolves per traded symbol, so ONE basket job gives every coin its own: `BTCUSDT.P` reads `BTCUSDT`, `ETHUSDT.P` reads `ETHUSDT`. Perpetuals quoted per 1000 coins read the other market in their own units: `1000PEPEUSDT.P`'s `@spot` is PEPEUSDT with prices × 1000 and volume ÷ 1000 (and `PEPEUSDT`'s `@perp` is `1000PEPEUSDT.P` ÷ 1000), so a basis or a ratio means the same on every coin. Each token counts as one reference (at most 3). `@spot` on a spot pair, `@perp` on a perpetual, or a coin whose other market has no data is the finding `self_reference_unavailable`, naming the symbol: remove that coin or trade its other market. `validate` lists one `inputs.references_detail` row per coin (`for_symbol`, the resolved `symbol`, `price_scale`, `data_start`); a result's `inputs.per_leg.<symbol>.references["@spot"]` shows `symbol`, `price_scale`, `bars`, `carried_bars` and `missing_bars`. The other market is only read: you still trade one market, so a one-leg `@spot` strategy on perpetuals deploys hosted as an all-futures strategy, and each deployed coin follows its own spot feed. A strategy that declares `references` or `data` gets `result.inputs` with one `per_leg.<symbol>` block per symbol.
- <a id="context-series"></a>**Context series (daily, read-only):** `FRED:SP500`, `FRED:NASDAQ100`, `FRED:DJIA`, `FRED:VIXCLS` (indices), `FRED:DGS10` / `FRED:DGS2` (10y / 2y Treasury yield, percent), `FRED:DCOILWTICO` (WTI oil, USD per barrel), `FRED:DTWEXBGS` (broad US dollar index), once OptAlgo's data service serves them. Read only as references at their minimum timeframe or coarser (`["FRED:DGS10@1d"]`); traded, they are refused (`context_symbol_not_tradable`), below the minimum `timeframe_below_min`. Close-only (open = high = low = close, volume 0): read `close`. A daily bar is readable from its UTC day's close **plus its series' publication lag**, the same in backtests and hosted: SP500 / NASDAQ100 / DJIA 1 day, VIXCLS 2 days, DGS10 / DGS2 5 days, DCOILWTICO / DTWEXBGS 9 days (FRED's worst-case release plus the data refresh, rounded up); validate's `inputs.references_detail[]` shows it as `publish_lag_s`. A day without a value (holidays) carries the previous close (`synthetic`), a value ≤ 0 is left out, and the rows before a lagged value is readable stay `synthetic`, so `prims.on_closed` counts each value once.
- **Cost:** reference, funding, open-interest, taker and news rows count in the estimate's `loaded_rows`, memory and run time (so in the units); `max_bars` stays per leg.
- **Not yet:** `execution.early_decision_s` with any declaration ([`early_decision_unsupported`](https://docs.optalgo.com/llm/errors.md#early_decision_unsupported)).
- **Hosted (section 3):** everything above runs hosted exactly as in its backtest (up to 16 legs on Pro, 4 on Free and Plus; [target-weight portfolios](https://docs.optalgo.com/llm/portfolios.md#portfolios-hosted) on paper): several legs on one account, `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)). Not `news`: it is backtests only for now. A multi-leg strategy deploys on exactly its legs, in the backtest's `market` order, and sizes on the bot's whole allocation (the backtest's shared account).

`validate` checks every declared input against the market data and says from when it exists: [`unknown_reference`](https://docs.optalgo.com/llm/errors.md#unknown_reference), [`reference_source`](https://docs.optalgo.com/llm/errors.md#reference_source), [`reference_starts_late`](https://docs.optalgo.com/llm/errors.md#reference_starts_late), [`data_unavailable`](https://docs.optalgo.com/llm/errors.md#data_unavailable), [`data_absent`](https://docs.optalgo.com/llm/errors.md#data_absent), [`data_starts_late`](https://docs.optalgo.com/llm/errors.md#data_starts_late), [`taker_unknown`](https://docs.optalgo.com/llm/errors.md#taker_unknown), [`max_references`](https://docs.optalgo.com/llm/errors.md#max_references). Its answer also carries an `inputs` block when the code declares anything: `legs`, `references`, `data`, `references_detail[]` (`name`, `exchange`, `symbol`, `tf_s`, `source`, `data_start`), `data_detail[]` (one row per series and leg or reference: `series`, `leg`, `reference`, `symbol`, `available`, `source`, `data_start`; taker adds `unknown_days` / `days`) and `hosted` (`supported`, `reasons[]`: whether it can be deployed hosted as written). `POST /v1/backtests/check` returns the declared `legs`, `references` and `data` beside its findings. The dry run gives a declaring strategy synthetic legs, references, funding and open interest, so it checks them for lookahead too. A done run's `result.inputs` repeats the declarations and counts, per leg inside the window (each symbol of a basket too, under `per_leg.<symbol>`): each reference's `bars`, `carried_bars` and `missing_bars`; funding `settlements`, `missing_bars` and `first_valid_t`; news under `per_leg.<symbol>.news`; taker `missing_bars` and `first_valid_t` under `per_leg.<symbol>.taker`; open interest `bars`, `filled_bars` and `missing_bars`, and per column (`oi.columns.open_interest`, `.open_interest_value`, `.long_short_ratio`, `.top_long_short_accounts`, `.top_long_short_positions`, `.taker_buy_sell_ratio`) `filled_bars` (carried from an older row), `missing_bars` (empty), `first_valid_t` and `full_from_t` (epoch s of the bar open; real on every bar from there on); a multi-leg run's `common_span` (`first`, `last`, `dropped_bars`). See [open-interest columns](#oi-columns) for when each column exists. Many carried or missing bars mean the strategy decided on stale or absent inputs: say so with the grade.

**A reference as a filter** (trend entries on any symbol, only while BTC trends up). Spec: `"market": [{"exchange": "BINANCE", "symbol": "SOLUSDT.P"}]`, `"timeframe": "60"`. Deployable as a hosted strategy (a reference on another timeframe, `"BINANCE:BTCUSDT.P@1d"`, deploys too).

```python
from dataclasses import dataclass
from typing import ClassVar

import numpy as np

from optalgo_engine.sdk import BarSeries, Exit, Intents, StrategyOutput, VectorStrategy, prims


@dataclass
class BtcRegimeFilter(VectorStrategy):
    """Fast/slow SMA cross on the traded symbol, longs only while BTC closes above its own long SMA."""

    name: ClassVar[str] = "btc_regime_filter"
    references: ClassVar[list[str]] = ["BINANCE:BTCUSDT.P"]  # a literal: read before the code runs

    fast: int = 20
    slow: int = 80
    regime: int = 200
    stop: float = 0.03

    def warmup_bars(self) -> int:
        return max(self.slow, self.regime) + 1

    def run(self, series: BarSeries, decision: BarSeries | None = None) -> StrategyOutput:
        btc = series.refs["BINANCE:BTCUSDT.P"]
        with np.errstate(invalid="ignore"):
            risk_on = btc.c > prims.rolling_mean(btc.c, self.regime)  # NaN (no BTC yet) -> False
        fast = prims.rolling_mean(series.c, self.fast)
        slow = prims.rolling_mean(series.c, self.slow)
        it = Intents.empty(len(series))
        it.enter[prims.cross_over(fast, slow) & risk_on] = 1
        it.exit[prims.cross_under(fast, slow) | ~risk_on] = Exit.LONGS
        it.sl_dist[:] = self.stop
        return StrategyOutput(intents=it, plots={"fast": fast, "slow": slow})
```

**Two legs: the ETH / BTC ratio z-score** (mean reversion of the log price ratio, one leg long and the other short). Spec: `"market": [{"exchange": "BINANCE", "symbol": "ETHUSDT.P"}, {"exchange": "BINANCE", "symbol": "BTCUSDT.P"}]` (leg 0, then leg 1), `"timeframe": "60"`. Both legs are **perpetuals**, because it shorts either leg: on a SPOT leg (`ETHUSDT`) those shorts would [not be filled](#spot-legs) and the trade would no longer be dollar-neutral. Deployable as a hosted strategy on exactly these two legs, in this order; `leg_size = 0.5` puts half of the bot's allocation in each leg ([sizing](https://docs.optalgo.com/llm/hosted.md#hosted-inputs)).

```python
from dataclasses import dataclass
from typing import ClassVar

import numpy as np

from optalgo_engine.sdk import BarSeries, Exit, Intents, StrategyOutput, VectorStrategy, prims


@dataclass
class RatioZScore(VectorStrategy):
    """Mean reversion of the log price ratio of two legs (e.g. ETH / BTC), dollar-neutral."""

    name: ClassVar[str] = "ratio_zscore_legs"
    legs: ClassVar[int] = 2  # spec.market = [leg 0, leg 1]: ETHUSDT.P then BTCUSDT.P (it shorts both: perpetuals)

    lookback: int = 96
    entry_z: float = 2.0
    exit_z: float = 0.5
    stop_z: float = 4.0
    leg_size: float = 0.5  # fraction of equity per leg

    def warmup_bars(self) -> int:
        return self.lookback + 1

    def run(self, series: list[BarSeries], decision: list[BarSeries] | None = None) -> StrategyOutput:
        a, b = series
        ratio = np.log(a.c) - np.log(b.c)
        z = prims.zscore(ratio, self.lookback)
        az = np.abs(np.nan_to_num(z))
        ok = np.isfinite(z) & (az <= self.stop_z)
        cheap = ok & (z < -self.entry_z)  # leg 0 cheap against leg 1: long the ratio
        rich = ok & (z > self.entry_z)
        leave = np.isfinite(z) & ((az < self.exit_z) | (az > self.stop_z))
        pos = prims.position_state(cheap, rich, leave, flip=False, reenter=False)
        prev = np.concatenate([np.zeros(1, np.int8), pos[:-1]])
        opened, closed = (pos != 0) & (prev == 0), (pos == 0) & (prev != 0)
        ia, ib = Intents.empty(len(a)), Intents.empty(len(b))
        ia.enter[opened] = pos[opened]
        ib.enter[opened] = -pos[opened]
        ia.size[:] = ib.size[:] = self.leg_size
        ia.exit[closed] = ib.exit[closed] = Exit.ALL
        return StrategyOutput(intents=[ia, ib], plots={"ratio": ratio, "z": z})
```

**Cash and carry: long SPOT, short the perpetual, reading the perpetual's funding.** Spec: `"market": [{"exchange": "BINANCE", "symbol": "BTCUSDT"}, {"exchange": "BINANCE", "symbol": "BTCUSDT.P"}]` (spot leg 0, perpetual leg 1), `"timeframe": "60"`. `data = ["funding"]` reaches the perpetual leg; the spot leg reads `series.funding is None`. Each leg is `0.5`: one wallet holds both ([one wallet](#one-wallet)).

```python
from dataclasses import dataclass
from typing import ClassVar

import numpy as np

from optalgo_engine.sdk import BarSeries, Exit, Intents, StrategyOutput, VectorStrategy, prims


@dataclass
class CashAndCarry(VectorStrategy):
    """Hold spot and short the perpetual while its funding (paid to shorts) stays positive."""

    name: ClassVar[str] = "cash_and_carry"
    legs: ClassVar[int] = 2  # leg 0 BTCUSDT (SPOT, long only), leg 1 BTCUSDT.P
    data: ClassVar[list[str]] = ["funding"]  # only the perpetual leg has it

    enter_rate: float = 0.0001  # per settlement
    exit_rate: float = 0.0
    smooth: int = 24
    leg_size: float = 0.5  # the two legs sum to 1: one wallet

    def warmup_bars(self) -> int:
        return self.smooth + 1

    def run(self, series: list[BarSeries], decision: list[BarSeries] | None = None) -> StrategyOutput:
        spot, perp = series  # spot.funding is None: only perp.funding is read
        rate = prims.rolling_mean(np.nan_to_num(perp.funding.rate), self.smooth)
        pos = prims.position_state(rate > self.enter_rate, np.zeros(len(rate), bool), rate < self.exit_rate,
                                   flip=False, reenter=False)
        prev = np.concatenate([np.zeros(1, np.int8), pos[:-1]])
        opened, closed = (pos != 0) & (prev == 0), (pos == 0) & (prev != 0)
        ia, ib = Intents.empty(len(spot)), Intents.empty(len(perp))
        ia.enter[opened] = 1  # buy spot
        ib.enter[opened] = -1  # short the perpetual
        ia.size[:] = ib.size[:] = self.leg_size
        ia.exit[closed] = ib.exit[closed] = Exit.ALL
        return StrategyOutput(intents=[ia, ib], plots={"funding": rate})
```

**Funding and open interest as a crowding filter** (breakout longs that stand aside while funding is high or open interest just jumped). Spec: `"market": [{"exchange": "BINANCE", "symbol": "ETHUSDT.P"}]`, `"timeframe": "60"`. Deployable as a hosted strategy (it reads OptAlgo's live funding and open-interest feed with the same timing rules).

```python
from dataclasses import dataclass
from typing import ClassVar

import numpy as np

from optalgo_engine.sdk import BarSeries, Exit, Intents, StrategyOutput, VectorStrategy, indicators


@dataclass
class CrowdingFilter(VectorStrategy):
    """Donchian breakout long, skipped while funding is high or open interest jumped."""

    name: ClassVar[str] = "crowding_filter"
    data: ClassVar[list[str]] = ["funding", "oi"]

    lookback: int = 48
    funding_cap: float = 0.0003  # 0.03 % per settlement
    oi_lookback: int = 24
    oi_jump: float = 0.10  # +10 % open interest over oi_lookback bars
    stop: float = 0.03
    hold: int = 48

    def warmup_bars(self) -> int:
        return max(self.lookback, self.oi_lookback) + 1

    def run(self, series: BarSeries, decision: BarSeries | None = None) -> StrategyOutput:
        hi = indicators.shift(indicators.highest(series.h, self.lookback))
        oi = series.oi.open_interest
        with np.errstate(invalid="ignore", divide="ignore"):
            growth = oi / indicators.shift(oi, self.oi_lookback) - 1.0
            crowded = (series.funding.rate > self.funding_cap) | (growth > self.oi_jump)
            breakout = series.c > hi
        it = Intents.empty(len(series))
        it.enter[breakout & ~crowded] = 1
        it.exit[crowded] = Exit.LONGS
        it.sl_dist[:] = self.stop
        it.max_bars[:] = self.hold
        return StrategyOutput(intents=it, plots={"channel": hi, "oi_growth": growth})
```

The SDK reference (`sdk` in `GET /v1/backtests/capabilities`) has the same section, "Several symbols in one strategy".

#### Several timeframes {#several-timeframes}

A higher (or lower) timeframe of the **same** symbol is a reference too: declare `references: ClassVar[list[str]] = ["BINANCE:BTCUSDT.P@4h"]` on a 1m or 15m strategy and read `series.refs["BINANCE:BTCUSDT.P@4h"]`. It never repaints:

- **Closed bars only.** Row `i` holds the latest 4h bar that **closed** at or before bar `i`'s close (a bar closes at its open + 4h; on a session venue a half day closes early). The 4h bar that closes at 04:00 is first seen by the traded bar that closes at 04:00, never earlier. Between closes the row carries that bar (`synthetic` set, volume 0).
- **Finer references work too:** a 1m reference on a 15m strategy gives, at each 15m bar, the 1m bar that closes with it.
- **Indicators on the higher timeframe: `prims.on_closed(ref, fn, ...)`.** An indicator computed on the carried rows counts each 4h bar many times (an EMA(200) of those rows is not a 4h EMA(200)). `prims.on_closed(h4, lambda b: indicators.ema(b.c, 200))` is a 4h EMA(200) on your bars. The exact contract:
  - `fn` is called **once**, as `fn(bars, *args, **kw)`, with **one** positional argument: `bars`, a `BarSeries` of the m **closed** reference bars only (`bars.t` their open times, `bars.o / h / l / c / v`, each a float64 array of shape `(m,)`, oldest first). Not five arrays: a method takes `(self, bars)` and is passed as `self.f`; a lambda takes `b`.
  - `fn` returns m values, one per closed bar (shape `(m,)`; a scalar or another length is a `ValueError` naming both shapes). NaN is allowed (its warm-up).
  - The result has shape `(n,)` (your bars): row `i` = `fn`'s value for the latest reference bar closed by bar `i`'s close, carried until the next one closes; NaN before the first closed bar.
  - Research templates' `self.htf(series, minutes, fn)` helper is **not** the SDK: it builds the traded coin's own periods and calls `fn(o, h, l, c, v)` with five arrays (`def f(self, o, h, l, c, v)`), one value per period back.
- **Plot and stop from it:** `plots` and every stop field are per-bar arrays, so a 4h line is drawn and a 4h ATR sets the stop (`sl_off` = an offset from the entry price).
- **Warm-up:** `warmup_bars()` counts **your** bars. A 4h EMA(200) on 1m needs 200 × 240 = 48,000 traded bars of warm-up in a backtest. Hosted, the warm-up is counted **per series**: 5,000 traded bars, and each **coarser** reference in its own bars, at most 5,000 each ([`warmup_too_long`](https://docs.optalgo.com/llm/errors.md#unsupported_strategy)), so that same strategy deploys with 200 4h bars (one-leg strategies only; see [Warm-up per series](https://docs.optalgo.com/llm/hosted.md#hosted-warmup)).

```python
from dataclasses import dataclass
from typing import ClassVar

import numpy as np

from optalgo_engine.sdk import BarSeries, Exit, Intents, StrategyOutput, VectorStrategy, indicators, prims


@dataclass
class TrendPullback4h(VectorStrategy):
    """15m entries in the direction of the 4h trend; the stop is 2 x the 4h ATR."""

    name: ClassVar[str] = "trend_pullback_4h"
    references: ClassVar[list[str]] = ["BINANCE:BTCUSDT.P@4h"]

    trend: int = 50
    fast: int = 20
    atr_mult: float = 2.0

    def warmup_bars(self) -> int:
        return 16 * (self.trend + 20)          # 16 bars of 15m per 4h bar, a margin for the 4h EMA

    def run(self, series: BarSeries, decision=None) -> StrategyOutput:
        h4 = series.refs["BINANCE:BTCUSDT.P@4h"]
        h4_ema = prims.on_closed(h4, lambda b: indicators.ema(b.c, self.trend))   # on closed 4h bars only
        h4_atr = prims.on_closed(h4, lambda b: indicators.atr(b.h, b.l, b.c, 14))
        fast = indicators.ema(series.c, self.fast)
        with np.errstate(invalid="ignore"):
            up = h4.c > h4_ema
            entry = up & prims.cross_over(series.c, fast)
        it = Intents.empty(len(series))
        it.enter[entry] = 1
        it.sl_off[entry] = self.atr_mult * h4_atr[entry]                   # a 4h ATR stop under the entry
        it.exit[~up] = Exit.LONGS
        return StrategyOutput(intents=it, plots={"h4_ema": h4_ema, "fast": fast})
```

#### Sizing {#sizing}

One convention, enforced:

- **`size` is a fraction 0 to 1 of equity**, set on the entry bar (`it.size[entry] = 0.5` = half the equity; NaN = 1, the whole equity). The notional is `size × equity × leverage`.
- **Leverage only through the spec:** `execution.leverage` (default 1). Never fold it into `size`: a `size` or `|target|` above `max(1, leverage)` is refused with [`size_scale`](https://docs.optalgo.com/llm/errors.md#size_scale) (a percent-looking value gets the hint "size is a fraction 0-1: 50% = 0.5"); a negative `size` is [`size_negative`](https://docs.optalgo.com/llm/errors.md#size_negative).
- **Risk sizing** (lose a fixed fraction of equity at the stop), one of two ways, **never both**:
  - in the code: `it.size[entry] = prims.risk_size(entry_px, stop_px, risk=0.01, cap=1.0)`, the fraction `min(cap, risk / (|entry − stop| / entry))`, sized at the price you pass (the decision close). It is NaN where there is no stop, and a NaN `size` means 1 (the whole equity), so set it on entry bars that have a stop only. It travels with the code, so it runs hosted as written;
  - in the spec: `execution.overrides.risk_per_trade` (`0.01` = 1 %), sized by the engine at the **fill price** from the stop distance (× `size`, × leverage); an entry without a stop is skipped (`risk_skipped`), and `risk_skip_above_full: true` skips an entry whose fraction would exceed 1 instead of capping it. On a [multi-leg strategy](https://docs.optalgo.com/llm/hosted.md#on_leg_failure) a skipped leg's entry takes the other legs' entries of that bar with it, as a hosted strategy with `on_leg_failure: unwind` does: a leg before it in leg order opens and closes at once (trade `exit_reason` `leg_unwound`, a round trip of fees), a leg after it is not entered; `counters.legs_unwound_risk` counts them. Hosted strategies accept both overrides too, sized at the decision close instead of the fill ([Risk sizing hosted](https://docs.optalgo.com/llm/hosted.md#hosted-risk)).
- **The strategy cannot read equity.** `run()` is one vectorised pass over the bars, before any fill. The engine compounds: each entry's notional is `size` × the equity at that bar (mark-to-market; `execution.overrides.size_on_realized` uses the realised balance instead, `size_at_fill` sizes at the fill price instead of the decision close).

```python
    def run(self, series: BarSeries, decision=None) -> StrategyOutput:
        c = series.c
        atr = indicators.atr(series.h, series.l, c, 14)
        entry = prims.cross_over(c, indicators.ema(c, 50))
        stop = c - 2.0 * atr                                         # where the stop will sit
        it = Intents.empty(len(series))
        it.enter[entry] = 1
        it.sl[entry] = stop[entry]
        it.size[entry] = prims.risk_size(c, stop, risk=0.01)[entry]  # lose ~1 % of equity at the stop
        return StrategyOutput(intents=it)
```

Or keep `size` out of the code and send `"execution": {"overrides": {"risk_per_trade": 0.01}}` with the same stops. Either way the result's `sizing` says what was used: `{entries, min, median, max, risk_skipped}` (a basket also per symbol, `per_symbol.<symbol>.sizing`).

#### The lookahead check {#lookahead-check}

Every run of your code proves, before its numbers count, that it decides the same with the future removed (`sandbox.causal` in the run's result):

- **Window cuts:** on the last 3,000 bars (or twice the warm-up plus 200, if more), the strategy runs again on data **cut** at 6 evenly spaced and 6 random bars (seeded from the code and params, so a replay is byte-identical). Every leg and every reference, funding and open-interest input is cut with the bars.
- **Decision bars:** after the first full run of a params set (the first 3 params sets of a run; research: its first trials), up to 24 bars where that run **entered, exited or set a target**, across every traded symbol and the whole history, are decided again on data that **ends at that bar**. A one-bar shift on a rare signal (`np.roll(c, -1)`, `np.concatenate([c[1:], c[-1:]])`) only differs at its own signal bar: this pass finds it.
- **Determinism:** the same params on the same bars must give the same intents twice.
- **Alignment:** references, funding, open interest and news reach your code already aligned causally (above); the engine refuses an alignment that would hand a bar a later value.

Before any of that, the static check reads the code for the usual look-ahead shapes (`shift(x, -k)` / `.shift(-k)`, `np.roll(x, -k)`, `x[k:]` aligned to `x`, `x[i + 1]`, centred windows, a whole-series `mean()` / `std()` / `max()` used in a comparison) and warns [`lookahead_suspect`](https://docs.optalgo.com/llm/errors.md#lookahead_suspect) with the line, the snippet and a fix. It is a warning, not a refusal: the run's checks decide.

Any difference up to a cut is lookahead. A backtest still **finishes**, graded **`D`** with the honesty finding `lookahead` (`params`: the intent `field`, the `bar`, its `time`, the `symbol`) and `sandbox.causal: "lookahead"`; a `D` run never deploys. Research runs and the hosted deploy check refuse it outright. `validate` already runs your code once on **synthetic bars** (free: no market data, no units) through the same checks and reports [`lookahead`](https://docs.optalgo.com/llm/errors.md#lookahead), [`nondeterministic`](https://docs.optalgo.com/llm/errors.md#nondeterministic), runtime errors and sandbox stops before you pay for a run.

What it does **not** prove:

- It samples cuts; it does not re-run every bar. Lookahead that changes nothing at any checked cut bar can pass: for example one that only moves a stop (`sl_update_*`) on bars no cut lands on, or a rare signal in a params set after the first three.
- It compares intents and `features`. `plots` are not checked: a plot may look ahead without a finding, so never trust a plot as a signal.
- The decision-bar pass covers the first params sets of a run only, and reads a bounded number of bars (at least 60,000 or half the run's bars, at most 400,000).
- On `validate`'s synthetic bars, a strategy that never decides anything is not proven ([`dry_run_no_decisions`](https://docs.optalgo.com/llm/errors.md#dry_run_no_decisions)); the run checks it again on real data.
- It is not an overfitting check: parameters tuned on the same window look good without any lookahead. That is the [search verdict](https://docs.optalgo.com/llm/research.md#avoid-overfitting).

#### Meta-label features {#meta-features}

**Use the `meta` tool for meta-labelling and ML sizing; do not train a model inside `run()`.** A user asking for "meta-labelling", "an ML filter" or "size positions by confidence" means: write the primary strategy, return its setup as `features`, backtest it, then `meta` research (`mode: size` sizes entries by the model's confidence rank, below `floor` skipped). A model fitted inside the strategy has none of the research's controls (purged walk-forward, several seeds, shuffled-label placebos, a shifted-mask null), cannot be judged for overfitting, and leaks easily: refitting, in-sample prediction quantiles or labels that read future bars change past decisions when bars are removed, and the run is graded **`D`** for lookahead.

How many inputs: **up to 16 strategy features**, plus the market catalogue below (11 columns; funding columns for Binance perpetuals only). Each fold keeps **at most 12** of them. A request for "20+ features" is met by returning your 16 most telling setup measurements; the catalogue adds the rest. Do not merge or hand-pick features to fit the limit: the research selects per fold, and more correlated columns add nothing.

The meta-label filter (`meta`: research on a backtest, then attach to a hosted paper strategy) learns which of your entries to skip or size down: the trades that only pay fees. It reads two kinds of inputs:

- **Market context** chosen by OptAlgo's feature lab: funding rate and its 30-day z-score, BTC's 1-day momentum and 7-day trend, the coin's strength against BTC, short-term overextension, distance to the 30-day low, volatility. Each was confirmed out of sample across 18 coins. Funding inputs exist for Binance perpetuals only.
- **Your strategy's own view of each setup**: return it as `features`. The model cannot see what your strategy saw unless you hand it over: how far the breakout cleared its level in ATR, the distance to your stop, your indicator readings at the entry, bars since the last signal.

```python
        level = indicators.shift(prims.rolling_max(series.h, 20), 1)   # the previous 20-bar high
        atr = indicators.atr(series.h, series.l, series.c, 14)
        return StrategyOutput(intents=it, plots={"fast": fast, "slow": slow},
                              features={"gap": (fast - slow) / slow, "breakout_atr": (series.c - level) / atr})
```

Each fold of the research keeps only the inputs that separated winning from losing trades on that fold's training trades (at most 12, one per group of near-copies). The result lists what the model could read (`features.catalogue`, `features.strategy`) and what the final model uses (`features.selected`).

Rules:

- **Entries as `enter` intents.** The model skips or sizes the strategy's `enter` intents; it never touches `target`. A strategy that sets its position through `it.target` (e.g. `prims.target_steps`) has nothing to filter: research on it fails with `meta_no_entries`. Write the entries as `it.enter[...] = 1 / -1` and the exits as `it.exit[...]` (or a stop / target / time barrier), backtest that, then research. A verdict `ineffective` means every seed and placebo came out identical to the primary: the model changed no trade, so the run says nothing about the features.
- **Causal**, like intents: the lookahead check compares every feature (`f.<name>`).
- **The same however much history came before.** The live runner computes your strategy on a shorter window (warm-up plus the bars since its anchor) than a backtest does. After `warmup_bars` a feature must not depend on where history starts: an `ema` of a long length seeded too close to the decision fails. The run records `sandbox.features_window: "unstable"` (with the feature and bar) and meta research refuses it. Raise `warmup_bars` to cover the indicator, or use windowed ones (`rolling_*`, `zscore`, `atr`).
- **Same code live.** A model reads the features of the exact source it was trained on: attaching it to a strategy deployed from other code is refused (`meta_source`); run the research on a backtest of the deployed code. Live, a missing or non-finite feature on an entry skips that entry (`meta_unavailable`), never sends it unfiltered.

### 2.2 Discover before you spend quota

| Call | Answers |
|---|---|
| `GET /v1/backtests/limits` | Your plan's per-run `limits` and your `quota` |
| `GET /v1/markets?exchange=BINANCE&type=FUTURES` | The supported universe (below) |
| `GET /v1/backtests/capabilities` | The SDK reference (`sdk`), intents, the RunSpec JSON schema |

**The supported universe is exactly what `GET /v1/markets` lists, at the moment you call it.** Symbols and timeframes are added over time, so never plan from a list in this document (or from memory): read `GET /v1/markets` first. Backtest only symbols with `"backtest": true`, and only on a timeframe in `data.timeframes` (each symbol's own `timeframes` say from when it has history). A symbol, timeframe or window it does not cover is a validate finding. It answers `{data, next}` (the values below are an example, not the current list):

```json
{"data": {"exchanges": [{"exchange": "BINANCE", "types": ["FUTURES", "SPOT"], "symbols": 20, "backtest_symbols": 20}],
          "timeframes": ["1", "5", "15", "30", "60", "240", "1440"],
          "symbols": [{"exchange": "BINANCE", "symbol": "BTCUSDT.P", "type": "FUTURES", "short_allowed": true,
                       "timeframes": [{"timeframe": "1", "data_start": "2019-09-08"}, {"timeframe": "60", "data_start": "2019-09-08"}],
                       "data_start": "2019-09-08", "tick_size": 0.1, "step_size": 0.001, "min_qty": 0.001, "min_notional": 100,
                       "backtest": true}],
          "updated_at": "2026-10-09T12:00:00+00:00"},
 "next": [{"action": "validate", "method": "POST", "path": "/v1/backtests/validate", "why": "check a spec on these symbols for free"}]}
```

A symbol with `"backtest": false` carries a `reason`. Every Binance symbol OptAlgo keeps market data for, perpetual (`.P`) and spot, can be backtested: trading rules (tick size, lot size, minimum order) are refreshed from Binance in the background, so a newly added symbol becomes backtestable within minutes of its data. A symbol Binance has delisted entirely cannot (its rules are no longer published). BYBIT symbols are listed for live data but not backtestable yet: backtests model Binance's rules, fees and funding; use the BINANCE listing of the coin.

### 2.3 Validate: the free dry run

`POST /v1/backtests/validate` with the same body you will submit:

```json
{"source": "<the whole strategy.py>",
 "spec": {"market": [{"exchange": "BINANCE", "symbol": "BTCUSDT.P"}], "timeframe": "60",
          "window": {"start": "2024-01-01", "end": "2025-01-01"}, "strategy": {"params": {"fast": 20, "slow": 80}}}}
```

It queues nothing, loads no market data and costs no units. Code that passes the static check runs **once** in its sandbox on synthetic bars (the spec's timeframe and params), through the [lookahead check](#lookahead-check): lookahead, nondeterminism, runtime errors and sandbox stops are findings before you pay for a run. It reports **every problem at once** (code, spec, symbols, timeframe, data for the window, limits, quota), each finding with its own `fix`: apply them all in one edit, validate again, and submit only when `ok` is `true`.

```json
{"data": {"ok": false,
          "findings": [{"code": "source_check", "severity": "error", "field": "source", "line": 14, "col": 8, "rule": "loop_over_bars",
                        "kind": "quality", "message": "a Python loop over bars", "fix": "use prims.cross_over(fast, slow) instead"},
                       {"code": "window_before_data", "severity": "error", "field": "window.start", "symbol": "ETHUSDT.P",
                        "data_start": "2023-01-01", "message": "no 1m history before 2023-01-01", "fix": "start on or after 2023-01-01"}],
          "estimate": {"run_s": 14.2, "symbols": 1, "bars_per_leg": 527040, "finest_tf_s": 60, "loaded_rows": 527040,
                       "trials": 0, "mem_mb": 410, "warmup_days": 4, "fetch_s": 0},
          "cost": {"units": 2, "run_s": 14.2, "seconds_per_unit": 10},
          "quota": {"period": "month", "units": 50, "used": 12, "remaining": 38, "resets_at": "…", "seconds_per_unit": 10},
          "limits": {"wall_s": 60, "max_symbols": 3, "max_bars": 300000, "…": "…"}},
 "next": [{"action": "validate", "method": "POST", "path": "/v1/backtests/validate", "why": "apply every fix in findings, then validate again"}]}
```

Findings with `"severity": "warning"` or `"info"` do not block (`ok` can still be `true`); only `"error"` blocks. The finding codes:

| Area | `code` | Extra fields |
|---|---|---|
| Code | `source_check` | `line`, `col`, `rule`, `kind` (`security` or `quality`), `snippet`. A `security` finding is refused with [`security_violation`](https://docs.optalgo.com/llm/errors.md#security_violation). Rule [`declaration`](https://docs.optalgo.com/llm/errors.md#declaration): a `legs` / `references` / `data` declaration that is not a literal `ClassVar` with an allowed value |
| Code, dry run | [`lookahead`](https://docs.optalgo.com/llm/errors.md#lookahead), [`nondeterministic`](https://docs.optalgo.com/llm/errors.md#nondeterministic), [`strategy_error`](https://docs.optalgo.com/llm/errors.md#strategy_error), [`size_scale`](https://docs.optalgo.com/llm/errors.md#size_scale), [`size_negative`](https://docs.optalgo.com/llm/errors.md#size_negative), `sandbox` (a stop at run time: `rule`, `kind`, see [stop kinds](https://docs.optalgo.com/llm/errors.md#sandbox-stop-kinds)); warnings [`lookahead_suspect`](https://docs.optalgo.com/llm/errors.md#lookahead_suspect) (static), [`dry_run_limit`](https://docs.optalgo.com/llm/errors.md#dry_run_limit), [`dry_run_no_decisions`](https://docs.optalgo.com/llm/errors.md#dry_run_no_decisions) | `rule`, `kind`, `line`, `snippet`, `value` (the bar) |
| Code | `strategy_source_required` | Send `source` |
| Spec | `spec_invalid` | `field`, `allowed`, `example` |
| Execution ([what the run refuses](https://docs.optalgo.com/llm/errors.md#execution-config)) | [`magnifier_timeframe`](https://docs.optalgo.com/llm/errors.md#magnifier_timeframe), `override_unknown`, `override_invalid`, `venue_option`, `early_decision_magnifiers`, `early_decision_lead`, `research_unsupported`, `size_multiplier_invalid`, `inputs_need_crypto`, [`slippage_*`](https://docs.optalgo.com/llm/errors.md#slippage-map) (a [slippage map](https://docs.optalgo.com/llm/backtests.md#slippage-per-symbol)), `execution_invalid` | `field`, `value`, `allowed`, `suggestion` |
| Strategy vs symbols | warning `basket`: your one-instrument strategy has several symbols in `market`, so it runs as a [basket](https://docs.optalgo.com/llm/backtests.md#several-symbols-a-basket-backtest); `legs_mismatch`: a robustness check on several symbols ("check one symbol per run"), or a strategy that trades a fixed number of legs (a strategy declaring `legs = N`: [`legs_mismatch`](https://docs.optalgo.com/llm/errors.md#legs_mismatch), "needs exactly N legs"); `duplicate_symbol` | `value` (symbols sent), `allowed`, `suggestion` (`{"basket": true, "symbols": N, "initial_equity_per_symbol": …}`) |
| Data | `data_source_unavailable` | Market data could not be read; retry later |
| Declared inputs ([several symbols](#several-symbols-in-one-strategy)) | [`unknown_reference`](https://docs.optalgo.com/llm/errors.md#unknown_reference), [`reference_source`](https://docs.optalgo.com/llm/errors.md#reference_source), [`data_unavailable`](https://docs.optalgo.com/llm/errors.md#data_unavailable), [`early_decision_unsupported`](https://docs.optalgo.com/llm/errors.md#early_decision_unsupported), `unsupported_timeframe` (a reference's `@timeframe`); warnings [`reference_starts_late`](https://docs.optalgo.com/llm/errors.md#reference_starts_late), [`data_starts_late`](https://docs.optalgo.com/llm/errors.md#data_starts_late), [`data_absent`](https://docs.optalgo.com/llm/errors.md#data_absent), [`spot_short_refused`](https://docs.optalgo.com/llm/errors.md#spot_short_refused) (dry run: shorts on a SPOT leg), [`hosted_unsupported`](https://docs.optalgo.com/llm/errors.md#hosted_unsupported), `coverage_unknown` (an input could not be checked right now: validate again in a minute) | `value` (the reference or symbol), `symbol`, `data_start` |
| Data | warning [`data_download`](https://docs.optalgo.com/llm/errors.md#data_download): the first run on this data downloads it from the Binance archive first, which takes a while (`estimate.fetch_s`); not charged | `value` (seconds) |
| Symbols | `unknown_symbol` | `suggestion`, `allowed` |
| Symbols | `unsupported_exchange`, `no_instrument_rules` | Pick from `GET /v1/markets` |
| Timeframe | `unsupported_timeframe` | `nearest` |
| Window | `window_invalid`, `window_before_data` (`data_start`); warnings `window_in_future`, `warmup_before_data`, `coverage_unknown` | |
| Limits | `max_symbols`, `max_bars`, `max_trials`, `mem_mb` (the estimate is above the plan's memory: such a run would be stopped at the cap and charged, so it is an error), [`wall_s`](https://docs.optalgo.com/llm/errors.md#wall_s) (the estimate is above the plan's wall time: the same, an error), [`max_references`](https://docs.optalgo.com/llm/errors.md#max_references), `user_code`, `limits`; warning `max_concurrent` (the run will queue) | `value`, `allowed`, `suggestion` (a window start, magnifiers or symbols that fit) |
| Quota | `daily_quota`, `monthly_quota` | `used`, `remaining`, `resets_at` |
| Request | `invalid_request` | `field` |

`estimate.fetch_s` is the time to download market data that is not cached yet (Binance archive) before the run starts: it is **not charged** and not part of `run_s` / `cost`. While it downloads, the job is `running` with the reason [`downloading_data`](https://docs.optalgo.com/llm/errors.md#downloading_data).

`POST /v1/backtests/check {"source": "…"}` is the older code-only check (`{ok, findings: [{line, col, rule, message, kind}], legs, references, data, next}`: what the code [declares](#several-symbols-in-one-strategy)); prefer `validate`.

---

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