OptAlgo for AI agents
This file is for AI coding agents (Claude Code, Codex and others) that work for an OptAlgo user through the OptAlgo API. With one API key you get:
- a backtest engine: you write a strategy in Python, OptAlgo runs it on real candles and grades how far the result can be trusted;
- paper trading in the user's My Bots: real market data, fills in milliseconds, no exchange and no money;
- live trading on the user's own exchange account, when the user decides in the app.
Read this file once, completely, before you call anything. It is the canonical reference: if another page disagrees with it, this file wins. The plain-text copy is https://docs.optalgo.com/optalgo-llm.md.
The path: follow it in this order
| Step | You do | The user sees |
|---|---|---|
| 0. Connect | Device login; the key goes straight into a file, never into the chat | An approval page in the app |
| 1. Paper demo | Open 1 to 3 paper positions in a My Bots bot, show them, close them | The bot and its trades at app.optalgo.com/my-bots |
| 2. Develop a strategy | Write strategy.py, validate, backtest, read the grade, iterate | Every run at app.optalgo.com/backtest |
| 3. Run it on OptAlgo | Deploy a backtested strategy (grade A to C), dry run first | The bot, marked Runs on OptAlgo, in My Bots, on paper |
| 4. Watch it | Read its status, decisions and logs | Every decision on the bot's page |
| 5. Go live | Ask (the paper period is recommended, not required); never flip it yourself | A Your agent asked to go live card: Confirm or Decline |
| Live | Never your decision. The user switches to live in the app | The switch, in My Bots |
Start with OptAlgo itself. Do not open with TradingView, webhooks or alert messages: they are optional (section 9) and only for a user who already has TradingView alerts and asks to connect them.
Conventions: "bot" means one of the user's own My Bots strategies. "Signal" is a JSON message that tells a bot what to do (open, close, move a stop). Exact strings OptAlgo returns are in code font: match on them, do not paraphrase them. Timestamps are epoch seconds (UTC) unless a field is ISO 8601 (as_of, expires_at, resets_at).
The loop in one screen
Every result carries next: it names the call to make after it. With an API key you call the endpoint; in a chat app with the OptAlgo connector you call the tool.
| # | Step | API | Connector tool |
|---|---|---|---|
| 0 | Context: what needs attention, quota, hosted strategies, open paper positions, studies. First call of a session (context) | GET /v1/context | context |
| 1 | Markets and limits: which symbols and timeframes exist and from when; plan limits and quota left | GET /v1/markets, GET /v1/backtests/limits | markets, capabilities(section="limits") |
| 2 | SDK: how to write strategy.py, the intents and the run spec. Read it once per session | GET /v1/backtests/capabilities → sdk | capabilities(section="sdk"); capabilities(example=...) = a strategy + spec that validate |
| 3 | Validate: free dry run that lists every problem at once. Fix them all, validate again until ok | POST /v1/backtests/validate | validate_strategy |
| 4 | Run: costs quota units (1 unit = up to 10 s of run time). At most 3 runs at once | POST /v1/backtests | run_backtest; up to 3 at once: run_backtests |
| 5 | Status: poll until done, respecting poll_after_s | GET /v1/backtests/{id} | none: run_backtest waits and answers the result; still running, backtest_result(id, wait_s=25) |
| 6 | Result: after every finished backtest, ALWAYS show the equity chart first: strategy vs buy-and-hold, both compounded from the same initial equity (the image run_backtest / backtest_result attach; without image support, draw their series as a line chart; Charts and data). Then the honesty grade (A best to D), the search verdict (ok / caution / likely_overfit / no_edge), the diagnosis (why it wins or loses: in-sample hints, act on one suggestion, then validate; Diagnostics), then the numbers, net of fees. One backtest is in-sample | GET /v1/backtests/{id}, /diagnostics, /chart, /chart.png, /download-links | backtest_result, backtest_diagnostics, backtest_chart (with the image), download_data; compare_backtests ranks up to 6 |
| 7 | Paper: a paper bot in My Bots, or deploy the backtested strategy to run on OptAlgo on paper (dry run first) | POST /v1/bots, /signal; POST /v1/strategies?dry_run=true, then without it | create_paper_bot, paper_signal; deploy_strategy (dry_run) |
| 8 | Watch: status, every decision, logs | GET /v1/strategies/{id}, /decisions, /logs | strategies(id, view) |
| 9 | Compare: its real trades against a backtest of the same code over the same period | POST /v1/strategies/{id}/compare | compare_with_backtest |
| 10 | Organise: the best runs first, a note (purpose, hypothesis) and tags when a line of research starts, a favourite on every run worth keeping. Files of old non-favourite runs are pruned (the row, metrics, grade and code stay); rerun rebuilds them (Organise and retention) | GET /v1/backtests?sort=sharpe, PATCH /v1/backtests/{id}, POST /v1/backtests/{id}/rerun | backtests (sort, filters), annotate_backtest, rerun_backtest |
| 11 | Study, holdout, robustness: tag one idea's runs study:<name> (studies); declare the study's holdout before tuning, score the chosen run on it once at the end (holdout); check robustness before deploying (robustness) | GET /v1/studies/{tag}, POST /v1/studies/{tag}/holdout, /final-test, POST /v1/backtests/{id}/robustness | run_backtest(tags=["study:<name>"]), research(source, spec, space) = one walk-forward, studies(tag, holdout_months / final_test), robustness(backtest_id) |
Something wrong, missing or confusing on OptAlgo's side at any step: file a ticket without asking (POST /v1/tickets, tool report_issue). A human: [email protected].
Safety rules (always)
- Never ask for, print or store the key anywhere but its file. Connect with the device login (section 0). If the user pastes a key (
oa_live_…), do not use it: tell them to revoke it under AI agents and run the login. - Paper first. Every new bot is created on paper. Every demo and every new strategy runs on paper.
- Live is the user's decision, made in the app. Suggest it; never start it on your own. The user switches a bot to live in My Bots. Only if the user explicitly asks you to do it, and your key has
trade, may you switch it (PATCH /v1/bots/{bot_id}with{"is_paper": false}), asking once more right before underconfirm_live. A hosted strategy (section 3) goes live only when the user confirms it in the app: you may only request it (section 5). - Never claim live until a GET says live. Say "live" only after
GET /v1/bots/{bot_id}answers"mode": "live". Say "filled" only afterGET /v1/signals/{transaction_id}isexecutedandGET /v1/tradesshows the trade. A202is "accepted", nothing more. - Follow
fixandnext. Every backtest and market refusal tells you what to change (fix), what to call next (next) and where it is explained (docs). Do that before anything else; do not retry the same request unchanged. - Stop on quota.
daily_quota,monthly_quotaorlimit: stop submitting, tell the user when it resets. Plan limits (not_in_plan,limit, the quotas,plan_required) are never bugs: do not file a ticket for them. - Respect limits and scopes. A
403(plan_required,scope_required,limit_exceeded,key_paused) is the user's or the plan's decision. Never work around it with another bot, key or exchange. - Grade before numbers. Report a backtest's honesty grade and findings before any return figure, together with its search verdict (
search.verdict, section 2.5), and call a single backtest in-sample. Judge it net of fees: fees kill short timeframes (section 2.5). Don't sweep parameters with many single runs (section 2.4). - Never send code that tries forbidden actions. Strategy code may only use
numpy,mathandoptalgo_engine.sdk. Code that tries files, network, processes, system modules or sandbox escapes is refused withsecurity_violationand counts as a strike (the answer says strike N ofstrikes_max, 3 by default; checking, validating and submitting the same code counts once); repeated security violations suspend the account's API access (account_suspended) until [email protected] restores it. Honest mistakes (a loop over bars, a wrong signature, lookahead, a syntax error) never count, and neither does a stop OptAlgo's own sandbox caused (kindengine, e.g.engine_import: not charged either). On a strike, tell the user, remove the forbidden part, and do not try another way around it. - Never fetch prices or market data from the web. Use
GET /v1/pricesandGET /v1/markets. A signal needs no price: leaveentry_priceout and OptAlgo fills it from its live price. Don't ask the user for values OptAlgo can default; ask only for intent (symbol, direction, size) when it is missing. - Report problems automatically. File a ticket (
POST /v1/tickets; connector toolreport_issue) without asking the user, not only on errors: when OptAlgo gets something wrong (validate and a run disagree, an estimate far off, a5xxorinternal_errorthat repeats), when the user wants something OptAlgo cannot do (kindfeature), when the docs and a tool or answer disagree, when a result looks wrong, and when the user is confused by a response (kindquestion). Anextstepreport_issuealready carries the ticket: send it. One ticket per distinct problem per session; tell the user in one line with the ticket id. Never say you cannot contact OptAlgo; a person is at [email protected]. Details: Report problems automatically.
0. Connect
Chat apps (Claude.ai, the Claude app on desktop or mobile, ChatGPT) use the OptAlgo connector URL https://mcp.optalgo.com/mcp instead of a key: the user adds it in the chat app and approves it once in OptAlgo, and the chat gets backtests and paper bots (never live trading), or only reads and backtests when the user approves it as Research only (then the bot tools are missing and bot calls answer connector_research_only). Never paste a key into a chat. Setup: https://docs.optalgo.com/ai-agents/connectors
Coding agents (Claude Code, Codex and others with a shell) use an OptAlgo API key. The key must never pass through the chat. OptAlgo gives it to you through a device login: you start a login, the user approves it in the OptAlgo app, and the API writes the key straight into a file on this machine. You never see it, the user never copies it.
Already in a chat with the connector? Then you call tools, not endpoints: the same steps, one tool each (the last column of the loop), and no key. Answers are brief by default (the decision first, short keys, rounded numbers, next as {tool, args}); pass detail: "normal" or "full" only when you need more. run_backtest, run_backtests, research, backtest_result and compare_backtests wait for runs on OptAlgo's side (wait_s, at most 25 s) and answer the finished result; a run still going answers its status, then call backtest_result(id, wait_s=25). This guide is the guide(topic) tool and the resources optalgo://guide/<topic>. A tool named here that the chat does not have means the chat still holds the old tool list: the user removes the connector and adds it again (version 2, October 2026: what changed).
The key lives in ~/.config/optalgo/credentials.env (readable only by the user):
OPTALGO_API_KEY=oa_live_...
OPTALGO_API_BASE=https://api.optalgo.com/v1
Every plan can connect, Free included.
| Plan | Scopes a key can have | Money |
|---|---|---|
| Free | read, backtest, bots | Paper only. trade answers 403 plan_required |
| Plus, Pro | read, backtest, bots, trade | Paper, and live with trade |
read is always on. backtest runs backtests of code you write, nothing else. bots creates and runs the user's bots and trades them on paper. trade is real money: live signals and closes, paper-to-live, live bots. Request ["read", "backtest", "bots"] (the default below); add trade only when a Plus or Pro user wants live trading.
After you connect, your first suggestion is the 2-minute paper demo (section 1), unless the user already asked for something specific.
Hard rules for the key
-
Never ask the user to paste a key, and never offer it as an option.
-
Never print the key. Do not
cat,head,lessorgrepthe credentials file; do notecho $OPTALGO_API_KEYor runenv,printenvorsetwhile it is loaded; nocurl -v,--traceorset -x; never copy the key into another file, a script, a commit, a ticket or a URL. -
Load it only inside the command that uses it, with the base URL from the same file. Every example below assumes this prefix:
set -a; . ~/.config/optalgo/credentials.env; set +a; curl -sS "$OPTALGO_API_BASE/me" -H "X-API-Key: $OPTALGO_API_KEY" -
One key per machine. Reuse the file while it works. Log in again only when there is no file or the key answers
401 invalid_api_key. A missing scope (403 scope_required) is not a reason to log in again (see "Changing what a key may do"). An account has at most 5 active keys. -
Without a shell and a file system (a chat-only assistant) you cannot hold a key safely: do not ask for one. Tell the user to add the OptAlgo connector to the chat app (https://docs.optalgo.com/ai-agents/connectors: backtests and paper bots, approved in the app, no key), or to use a coding agent such as Claude Code or Codex, or the OptAlgo app.
Step 1: is this machine already connected?
CRED="$HOME/.config/optalgo/credentials.env"
if [ -f "$CRED" ]; then
( set -a; . "$CRED"; set +a
curl -sS --max-time 30 -w '\nHTTP %{http_code}\n' "${OPTALGO_API_BASE:-https://api.optalgo.com/v1}/me" -H "X-API-Key: $OPTALGO_API_KEY" )
else
echo "not connected"
fi
HTTP 200: connected. The answer names the account,plan.tier, the key'sprefix,scopes,autonomyandlimits(never the key itself). Go on.HTTP 401(invalid_api_key): revoked or account closed.rm ~/.config/optalgo/credentials.envand run step 2.HTTP 403(plan_required): the plan does not allow this key's use any more. Do not log in again; tell the user.not connected: run step 2.
Step 2: device login
Tell the user in one sentence what the approval page will ask: the scopes (default read + backtest + bots: backtests and paper trading, no real money) and the autonomy (confirm_live, the default: you ask before anything that could touch real money). The approval page pre-ticks what you request; the user decides.
Run each snippet as one shell command of its own (it uses set -eu and exit), or save it and run sh <file>. Needs only sh, curl, sed, grep, mktemp.
2a. Start the login. Prints only the approval link and the code. Set client_name to something the user recognises (at most 60 characters), for example "Claude Code on Ayse's MacBook". More than 10 logins a minute from one IP answers 429 rate_limited with retry_after.
# OptAlgo agent login, step 2a: start. Prints only the approval link and the code.
set -eu
umask 077
API="${OPTALGO_API_BASE:-https://api.optalgo.com/v1}"
DIR="$HOME/.config/optalgo"
mkdir -p "$DIR"
field() { sed -n "s/.*\"$1\": *\"\{0,1\}\([^\",}]*\).*/\1/p"; }
TMP=$(mktemp "$DIR/.login.XXXXXX"); trap 'rm -f "$TMP"' EXIT
STATUS=$(curl -sS --max-time 30 -o "$TMP" -w '%{http_code}' -X POST "$API/agent/login" \
-H 'Content-Type: application/json' -d '{"client_name": "Claude Code", "scopes": ["read", "backtest", "bots"]}') || STATUS=000
if [ "$STATUS" != 200 ]; then
echo "Login could not start (HTTP $STATUS): $(field error < "$TMP")" >&2; exit 1
fi
DEVICE_CODE=$(field device_code < "$TMP")
USER_CODE=$(field user_code < "$TMP")
LINK=$(field verification_uri_complete < "$TMP")
INTERVAL=$(field interval < "$TMP"); EXPIRES_IN=$(field expires_in < "$TMP")
case "$DEVICE_CODE" in ''|*[!A-Za-z0-9_-]*) echo "Unexpected login answer." >&2; exit 1;; esac
case "$INTERVAL" in ''|*[!0-9]*) INTERVAL=5;; esac
case "$EXPIRES_IN" in ''|*[!0-9]*) EXPIRES_IN=600;; esac
printf 'DEVICE_CODE=%s\nINTERVAL=%s\nEXPIRES_AT=%s\n' \
"$DEVICE_CODE" "$INTERVAL" "$(( $(date +%s) + EXPIRES_IN ))" > "$DIR/login.pending"
echo "Open this link and approve: $LINK"
echo "The page must show the code $USER_CODE. It expires in $(( EXPIRES_IN / 60 )) minutes."
Show the user the link and the code exactly as printed. They open the link (logging in if needed), check the code, and click Approve. Without a clickable link: https://app.optalgo.com/connect-agent and type the code.
2b. Wait for the approval and save the key. Run it right after showing the link. It polls every interval seconds, writes the key into the credentials file and never prints it. It waits at most 90 seconds per run (OPTALGO_LOGIN_WAIT changes that); on "Still waiting", run it again.
# OptAlgo agent login, step 2b: wait for approval, save the key. Never prints the key.
set -eu
umask 077
API="${OPTALGO_API_BASE:-https://api.optalgo.com/v1}"
DIR="$HOME/.config/optalgo"
STATE="$DIR/login.pending"
field() { sed -n "s/.*\"$1\": *\"\{0,1\}\([^\",}]*\).*/\1/p"; }
[ -f "$STATE" ] || { echo "No login in progress: run step 2a." >&2; exit 1; }
. "$STATE"
TMP=$(mktemp "$DIR/.token.XXXXXX"); trap 'rm -f "$TMP"' EXIT
STOP_AT=$(( $(date +%s) + ${OPTALGO_LOGIN_WAIT:-90} ))
while :; do
NOW=$(date +%s)
if [ "$NOW" -ge "$EXPIRES_AT" ]; then
rm -f "$STATE"; echo "The login expired before it was approved. Run step 2a again." >&2; exit 1
fi
if [ "$NOW" -ge "$STOP_AT" ]; then echo "Still waiting for the user's approval. Run step 2b again."; exit 75; fi
sleep "$INTERVAL"
STATUS=$(printf '{"device_code": "%s"}' "$DEVICE_CODE" | curl -sS --max-time 15 -o "$TMP" -w '%{http_code}' \
-X POST "$API/agent/token?format=env" -H 'Content-Type: application/json' -d @-) || STATUS=000
case "$STATUS" in
200)
if ! grep -q '^OPTALGO_API_KEY=oa_' "$TMP"; then echo "Unexpected token answer; not saved." >&2; exit 1; fi
chmod 600 "$TMP"; mv "$TMP" "$DIR/credentials.env"; rm -f "$STATE"
echo "Connected. The key is saved in $DIR/credentials.env (not shown)."
break ;;
428) ;; # authorization_pending: the user has not approved yet
429) INTERVAL=$(( INTERVAL + 5 )) ;; # slow_down: poll less often
403|409|410) # access_denied / plan_required, key_limit_reached, expired_token
rm -f "$STATE"; echo "Login ended (HTTP $STATUS): $(field error < "$TMP")" >&2; exit 1 ;;
*) echo "HTTP $STATUS from the token call; trying again." >&2 ;;
esac
done
( set -a; . "$DIR/credentials.env"; set +a
curl -sS --max-time 30 -w '\nHTTP %{http_code}\n' "$OPTALGO_API_BASE/me" -H "X-API-Key: $OPTALGO_API_KEY" )
| Ending | Meaning | What you do |
|---|---|---|
Connected. and HTTP 200 | The key is saved and works | Read plan.tier, api_key.scopes and api_key.autonomy, then offer the paper demo (section 1). |
Still waiting … (exit 75) | Not approved yet | Run 2b again; remind the user of the link. |
HTTP 403: access_denied | The user clicked Deny | Stop. Ask whether to try again. |
HTTP 403: plan_required | A requested scope needs a higher plan (trade on Free) | Start again without trade. |
HTTP 409: key_limit_reached | 5 active keys already | The user revokes one under AI agents; run 2a again. |
HTTP 410: expired_token / The login expired | Not approved within 10 minutes, or used | Run 2a again. |
HTTP 503 … trying again | Temporary server error | Nothing: the script keeps polling. |
The key is created at the first successful token call and returned once. If the file write failed, the key is lost: the user revokes it in AI agents and you log in again. The user gets a Telegram notice naming the new key and your client_name.
The same login in Python (standard library only), for a program of the user's:
import json, os, time, urllib.error, urllib.request
from pathlib import Path
API = os.environ.get("OPTALGO_API_BASE", "https://api.optalgo.com/v1")
CRED = Path.home() / ".config" / "optalgo" / "credentials.env"
def _post(path, body):
req = urllib.request.Request(API + path, data=json.dumps(body).encode(), method="POST",
headers={"Content-Type": "application/json", "User-Agent": "my-optalgo-script/1.0"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def login(client_name="my OptAlgo script", scopes=("read", "backtest", "bots")): # "trade" only for live (Plus/Pro)
status, raw = _post("/agent/login", {"client_name": client_name, "scopes": list(scopes)})
if status != 200:
raise SystemExit(f"login could not start: HTTP {status} {raw[:200]!r}")
start = json.loads(raw)
print(f"Open {start['verification_uri_complete']} and approve the code {start['user_code']}", flush=True)
interval, deadline = start["interval"], time.time() + start["expires_in"]
while time.time() < deadline:
time.sleep(interval)
status, raw = _post("/agent/token?format=env", {"device_code": start["device_code"]})
if status == 200: # the key: write it, never print it
CRED.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
tmp = CRED.with_name(".credentials.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(raw)
os.replace(tmp, CRED)
return
if status == 429:
interval += 5 # slow_down
elif status != 428: # 428 = not approved yet
raise SystemExit(f"login ended: HTTP {status}")
raise SystemExit("login expired; run it again")
Fallback: a claim code
Where the user cannot open a link from this machine (a server, a container), they create a one-time claim code in the app under AI agents (OPTC-…, valid 10 minutes, works once) and give it to you. Exchange it straight into the file:
# OptAlgo claim code: exchange a one-time OPTC-... code for a key, saved without printing it.
set -eu
umask 077
API="${OPTALGO_API_BASE:-https://api.optalgo.com/v1}"
DIR="$HOME/.config/optalgo"; mkdir -p "$DIR"
CODE='OPTC-XXXX-XXXX-XXXX-XXXX' # the code the user gave you
CODE=$(printf '%s' "$CODE" | tr -d ' ' | tr '[:lower:]' '[:upper:]')
case "$CODE" in ''|*[!A-Z0-9-]*) echo "That does not look like a claim code." >&2; exit 1;; esac
TMP=$(mktemp "$DIR/.claim.XXXXXX"); trap 'rm -f "$TMP"' EXIT
STATUS=$(printf '{"claim_code": "%s"}' "$CODE" | curl -sS --max-time 30 -o "$TMP" -w '%{http_code}' \
-X POST "$API/agent/claim?format=env" -H 'Content-Type: application/json' -d @-) || STATUS=000
if [ "$STATUS" = 200 ] && grep -q '^OPTALGO_API_KEY=oa_' "$TMP"; then
chmod 600 "$TMP"; mv "$TMP" "$DIR/credentials.env"
echo "Connected. The key is saved in $DIR/credentials.env (not shown)."
else
echo "Claim failed (HTTP $STATUS): $(sed -n 's/.*"error": *"\([^"]*\)".*/\1/p' "$TMP")" >&2; exit 1
fi
410 expired_token: used, expired or mistyped; ask for a new code. 403 plan_required and 409 key_limit_reached mean the same as in the login. More than 10 claims a minute or 5 wrong codes in 10 minutes from one IP: 429 rate_limited, wait retry_after. Then run step 1.
Changing what a key may do (no new login)
The user turns backtest, bots and trade on or off for the same key in the app (AI agents). It applies on the next call. Every 403 scope_required carries the link:
{"error": "scope_required", "detail": "Live trading needs the 'trade' scope: this bot is live. Paper bots can be traded with the 'bots' scope.",
"required_scope": "trade", "fix_url": "https://app.optalgo.com/ai-agents?section=keys&key=<key_id>&grant=trade"}
- Tell the user in one line what the scope allows and give them
fix_url: "Open this and confirm, then I'll retry." - When they say it is done, retry the same request with the same
Idempotency-Key. - Never log in again for a scope. On Free,
tradeis not available: say live trading needs Plus or Pro, and continue on paper.
Every session: start with the context
GET /v1/context (scope read; tool context) is the first call of every session: one small answer (at most about 1,500 characters of JSON, free, cached 30 s per user) that picks up where an earlier chat left off, decisions first. After a change you just made, read that endpoint itself, not the cached context.
{"data": {"as_of": "2026-10-11T09:00:00Z",
"attention": [{"code": "live_requested", "id": "<hosted id>", "do": "owner confirms live in the app"}],
"plan": {"tier": "Plus", "backtests": true, "quota": {"left": 22, "of": 30, "per": "day"}, "strikes": "0/3"},
"hosted": [{"id": "…", "name": "ema cross BTC", "status": "paper", "decided": "12m", "open": 1, "alerts": ["recent_error"]}],
"paper_open": [{"bot_id": "…", "name": "demo", "open": 2, "symbols": ["BTCUSDT.P", "ETHUSDT.P"]}],
"studies": [{"tag": "study:rsi-4h", "runs_14d": 9, "last": "3h", "best": ["B", 1.21]}],
"notes": {"cols": ["id", "age", "grade", "sharpe", "tags", "note"], "rows": [["…", "3h", "B", 1.21, ["study:rsi-4h"], "hypothesis: …"]]},
"favorites": {"cols": ["id", "name", "grade", "sharpe"], "rows": [["…", "rsi 4h v3", "B", 1.21]]},
"tickets": {"open": 1, "replied": 1, "titles": ["…"]}},
"next": [{"action": "read_study", "method": "GET", "path": "/v1/studies/study:rsi-4h", "why": "…"}]}
| Field | Meaning |
|---|---|
attention | At most 4 items {code, id?, do}, most urgent first: what only the user can unblock (key_paused, live_requested, owner_resume), then what stops you (backtests_off, quota_spent with the reset time, strikes: one more code strike suspends API access), then what you can fix (hosted_error: read its logs, fix, redeploy). Act on it first, or tell the user in one line what only they can do |
plan | tier, backtests (enabled), quota {left, of, per} (resets_at added when nothing is left), strikes as "used/max" ("0/exempt" for an account exempt from strikes) |
hosted | Hosted strategies not stopped or deleted (at most 20): decided = age of the last decision (45s, 12m, 5h, 3d), open positions, mode only when it differs from what status implies, alerts: error:<reason>, paused:<reason>, cpu_budget_spent, recent_error (last 24 h), position_mismatch, no_recent_decision (none for 3 bars, at least 5 minutes) |
paper_open | Other bots with open paper positions: open count and up to 3 symbols |
studies | Up to 3 studies with runs in the last 14 days, newest first: runs_14d, last (age), best = [best grade, best Sharpe] |
notes, favorites | Column tables: the newest annotated runs (up to 10) and favourites (up to 5) |
tickets | Your open agent tickets, how many have a team reply, up to 2 titles; answered (only when above 0): tickets resolved with a team reply in the last 14 days. Read the replies with GET /v1/tickets (connector: account(section="tickets")); next points there when there is one |
more, partial | more {section: n} counts what was left out to stay small (the full lists: GET /v1/backtests?favorites=true, /v1/studies, /v1/strategies, /v1/summary); partial names sections that could not be read this time (the rest still answers) |
next (at most 2): the strategy that needs attention, else the newest study, else markets and the SDK on an account with nothing yet.
1. Paper demo in My Bots
Two minutes, no exchange, no money. It proves the key works, a bot takes signals, OptAlgo sizes and fills them, and the trades appear in the API and in the user's app. Paper bots trade on OptAlgo's paper exchange: fills at live prices, 10,000 USDT of paper balance per account type.
Offer it right after connecting, in one sentence: "Want a 2-minute paper demo? I'll open three small paper trades in your My Bots (BTC, ETH, SOL) and close them again. No real money." Run it after they agree. Needs read + bots.
Send every write with its own Idempotency-Key (one UUID per action).
-
Read the plan.
GET /v1/me→plan.tier,plan.strategy_limit,multi_symbol.enabled,multi_symbol.max_positions_cap. On Free,GET /v1/summary→monthly_trade_quota.paper_remainingmust be at least 1. -
Find or create one paper bot.
GET /v1/botsfirst: if a paper bot namedPaper demoexists with no open position, reuse it. Otherwise create it withPOST /v1/bots:-
Multi-symbol (
multi_symbol.enabledtrue andmax_positions_cap≥ 3, Plus or Pro):{"type": "multi", "name": "Paper demo", "max_positions": 3, "allocated_amount": 300, "account_type": "FUTURES"} -
Single bot (Free, or multi-symbol not available): the
exchange_idofBINANCEcomes fromGET /v1/exchanges:{"type": "single", "name": "Paper demo", "exchange_id": "<BINANCE exchange_id>", "account_type": "FUTURES",
"symbol": "BTCUSDT.P", "allocated_amount": 100, "is_paper": true} -
Refused with
Strategy limit reached: your … plan allows N active strategies(Free has a small limit): do not stop anything. Reuse an existing paper bot fromGET /v1/botsthat hashas_open_position: false(a single bot trades only its ownsymbol; use that). If none qualifies, tell the user the plan's active-bot limit is reached and ask which bot to use. Never stop or delete a bot for the demo.
-
-
Open positions with
POST /v1/bots/{bot_id}/signal. Multi-symbol bot: three entries, one call each (the first one configures the bot, so each carriesexchangeandticker):{"position_side": "LONG", "exchange": "BINANCE", "ticker": "BTCUSDT.P", "leverage": 1}then the same with
ETHUSDT.PandSOLUSDT.P. Single bot: one entry,{"position_side": "LONG", "leverage": 1}(the API fills in the bot's exchange and ticker). Each answer is202with atransaction_id. -
Poll
GET /v1/signals/{transaction_id}every 2–5 s until the status is final.executedis what you want; anything else, quotelistener.reasonorworker.reasonand map it with Rejections. -
Show it.
GET /v1/trades?bot_id={bot_id}(open trades: side, size, entry price) as a small table, and tell the user: "Open https://app.optalgo.com/my-bots — the bot "Paper demo" shows these positions, their PnL and the log of every step." -
Close them (right away if they only wanted a look):
POST /v1/bots/{bot_id}/closewith no body closes every open position (one signal per ticker;{"ticker": "ETHUSDT.P"}closes one). Poll eachsignals[i].status_urluntil final, thenGET /v1/trades?bot_id={bot_id}&status=closedand show the realizedpnlof each (net of fees; small either way). -
Offer the next step: develop a strategy (section 2). "Next I can turn an idea of yours into a strategy and backtest it on OptAlgo's engine. What would you like to test?" Do not suggest TradingView.
Paper has no simulated stop-loss or take-profit: a paper trade closes only on a close signal. The demo proves nothing about the user's exchange account (connection, balance, order rules).
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
@dataclasssubclass ofVectorStrategy, withname: ClassVar[str]. Fields with defaults are the parameters (spec.strategy.paramsoverrides them). Other symbols' candles, several traded legs, funding, open interest, taker buy volume and news counts are declared as literalClassVarsreferences,legs,data: see Several symbols in one strategy. - Imports only
numpy,math,dataclasses,typing,__future__andoptalgo_engine.sdk. No files, network,os/sys/subprocess,eval/exec, dunder attributes, global state,asyncorwhile True. At most 64 KB. warmup_bars()returns the bars your indicators need before the first decision.run(series, decision=None)returnsStrategyOutput(intents=it, plots={...})withit = Intents.empty(len(series)). Setit.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_shortto trail,it.tp_updateto 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 inplotsso 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 withtarget). A strategy that declareslegsgets a list of series and returns a list ofIntents, one per leg.- Optional
features={...}onStrategyOutput: up to 16 per-bar float arrays the meta-label filter reads (namesa-z,0-9,_, at most 40 characters). One-leg strategies. - Vectorised only. Whole numpy arrays plus
indicatorsandprims(loops run in Rust). A Python loop over bars hits the time limit. Rolling quantiles:prims.rolling_percentile(x, n, q)= exactlynp.percentile(window, q)(q 0-100, "linear") andprims.rolling_rank(x, n)= the share of the window<= x[i](1 = the window's high); the window includes bari, NaN for the first n-1 bars and any window holding a NaN;n = 8640is cheap (prims.rolling_rank(k, 8640) > 0.8= k in its top 20 %). - Causal only. Bar
iuses data up to bari's close; the decision executes from the next bar. Noshift(-1),x[1:]aligned tox,np.roll(x, -1), centred windows or statistics over the whole series. Every run checks it (the lookahead check): a run that looks ahead is gradedD. - Security. Forbidden imports (
os,sys,subprocess,socket,ctypes…),open/exec/eval/compile/__import__, dunder or private attribute access,getattrwith a computed name, the attribute namesoperator,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 kindengineis OptAlgo's own gap, never yours: no strike, not charged (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.
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})
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
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 (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) |
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 |
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 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). Adds no reference to max_references. news:<reference> is a 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) |
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.
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 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 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
iholds the latest reference bar closed at or before bari's close. A row that carries an older bar (a gap, a coarser@timeframebetween its closes) hassyntheticset and volume 0; before the reference's first bar its prices are NaN (andsynthetic). Comparisons with NaN areFalse, so a filter likebtc.c > smais 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
Tis used fromT + 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.marketmust list exactlylegssymbols, elselegs_mismatch. Research runs (research) take the N legs together. - 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 negativetarget) is not filled, exactly as live trading skips it. The result says how many per leg (spot_short_refused, grade B), andvalidate's dry run warns up front. Short the perpetual (.P) instead. - 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 perpetual0.5). More is reported asmixed_wallet_overcommit(grade C, D above 1.5x): what the open legs need at current prices over the account's equity. Re-sizing withtargetafter a move does not raise it. - Data per leg: a declared
dataseries is given to every leg that has it; the others readNone(checkseries.funding is not Nonebefore using it on a leg).validatewarnsdata_absentfor each such leg and errors withdata_unavailableonly when no leg has the series;result.inputs.per_leg.<leg>.absentlists the series a leg did not get. - Baskets: a one-leg strategy with references over several symbols still runs as a basket; every symbol sees the same references.
- The traded coin's own other market:
@spot/@perp. Declarereferences: ClassVar[list[str]] = ["@spot"](or["@perp"], optionally"@spot@1h") and readseries.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.PreadsBTCUSDT,ETHUSDT.PreadsETHUSDT. Perpetuals quoted per 1000 coins read the other market in their own units:1000PEPEUSDT.P's@spotis PEPEUSDT with prices × 1000 and volume ÷ 1000 (andPEPEUSDT's@perpis1000PEPEUSDT.P÷ 1000), so a basis or a ratio means the same on every coin. Each token counts as one reference (at most 3).@spoton a spot pair,@perpon a perpetual, or a coin whose other market has no data is the findingself_reference_unavailable, naming the symbol: remove that coin or trade its other market.validatelists oneinputs.references_detailrow per coin (for_symbol, the resolvedsymbol,price_scale,data_start); a result'sinputs.per_leg.<symbol>.references["@spot"]showssymbol,price_scale,bars,carried_barsandmissing_bars. The other market is only read: you still trade one market, so a one-leg@spotstrategy on perpetuals deploys hosted as an all-futures strategy, and each deployed coin follows its own spot feed. A strategy that declaresreferencesordatagetsresult.inputswith oneper_leg.<symbol>block per symbol. - 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 minimumtimeframe_below_min. Close-only (open = high = low = close, volume 0): readclose. 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'sinputs.references_detail[]shows it aspublish_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 staysynthetic, soprims.on_closedcounts 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_barsstays per leg. - Not yet:
execution.early_decision_swith any declaration (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 on paper): several legs on one account,
funding/oi/takerseries (a reference's too) and references on any timeframe (what a hosted strategy runs). Notnews: it is backtests only for now. A multi-leg strategy deploys on exactly its legs, in the backtest'smarketorder, 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, reference_source, reference_starts_late, data_unavailable, data_absent, data_starts_late, taker_unknown, 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 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).
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 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).
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).
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).
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
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
iholds the latest 4h bar that closed at or before bari'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 (syntheticset, 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:fnis called once, asfn(bars, *args, **kw), with one positional argument:bars, aBarSeriesof the m closed reference bars only (bars.ttheir 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 asself.f; a lambda takesb.fnreturns m values, one per closed bar (shape(m,); a scalar or another length is aValueErrornaming both shapes). NaN is allowed (its warm-up).- The result has shape
(n,)(your bars): rowi=fn's value for the latest reference bar closed by bari'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 callsfn(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:
plotsand 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), so that same strategy deploys with 200 4h bars (one-leg strategies only; see Warm-up per series).
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
One convention, enforced:
sizeis 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 issize × equity × leverage.- Leverage only through the spec:
execution.leverage(default 1). Never fold it intosize: asizeor|target|abovemax(1, leverage)is refused withsize_scale(a percent-looking value gets the hint "size is a fraction 0-1: 50% = 0.5"); a negativesizeissize_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 fractionmin(cap, risk / (|entry − stop| / entry)), sized at the price you pass (the decision close). It is NaN where there is no stop, and a NaNsizemeans 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), andrisk_skip_above_full: trueskips an entry whose fraction would exceed 1 instead of capping it. On a multi-leg strategy a skipped leg's entry takes the other legs' entries of that bar with it, as a hosted strategy withon_leg_failure: unwinddoes: a leg before it in leg order opens and closes at once (tradeexit_reasonleg_unwound, a round trip of fees), a leg after it is not entered;counters.legs_unwound_riskcounts them. Hosted strategies accept both overrides too, sized at the decision close instead of the fill (Risk sizing hosted).
- in the code:
- The strategy cannot read equity.
run()is one vectorised pass over the bars, before any fill. The engine compounds: each entry's notional issize× the equity at that bar (mark-to-market;execution.overrides.size_on_realizeduses the realised balance instead,size_at_fillsizes at the fill price instead of the decision close).
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).
Portfolios and target weights
A target-weight portfolio holds a set of weights across many symbols and rebalances to them, instead of entering and exiting trades. Declare legs = N (up to 16 in backtests, within the plan's max_symbols: Pro 16, Free and Plus 3) and set each leg's target intent to the weight it should hold: a signed fraction of equity used as margin, × leverage like size (0.25 = a long worth 25 % of equity × leverage, -0.25 the same short, 0 = flat, NaN = hold, no change). The engine trades the difference from the next bar, on one shared account. A target is never combined with enter on the same bar of a leg; on a SPOT leg a negative target is not filled. Backtests only for now: see Hosted below.
Three execution options shape how targets trade (all off by default; a run without them gives exactly the results it always did):
| Option | Exact meaning |
|---|---|
rebalance_band | Absolute, in target units (0.01 = 1 % of equity). At each decision the position is expressed in target units (held qty × close / (equity × leverage)); a target on the same side within the band of it is not traded (counted band_skipped; orders already waiting stay). Outside the band the position trades all the way to the target, not to the band's edge. A target of 0, a sign change and an entry from flat always trade. 0 (default) = every target trades. |
gross_cap | Whole account (the first leg's value counts). Each bar, before the decisions: a leg's effective target is this bar's target, else its last one (0 before the first). When sum(|effective target| × leverage) over the legs exceeds the cap, every target is scaled by cap / sum (pro rata); a leg whose target is NaN that bar trades its scaled last target. Counted gross_capped (bars). The cap is on the targets: between rebalances prices (and the band) can carry the realised exposure above it; that is reported, not prevented. Default: no cap. 1.5 = gross notional at most 1.5× equity. |
target_position | lots (default): each increase opens its own lot with its own stops; a decrease closes the oldest lots first. merged: one position per leg and side, as an exchange holds it: an increase joins it at the volume-weighted average entry (fees and funding accumulate), its sl / tp re-set the whole position's (absolute, or measured from the new average entry); trailing, break-even and max_bars of the increase are not used. Counted target_merges. Equity is the same in both modes when the stops are position-wide (none, or execution.overrides.bracket_reference: "position_avg"). Use merged when you will compare with an exchange position. |
What to use them for: rebalance_band cuts turnover and fees (and orders below the exchange minimum) from tiny resizes; gross_cap is the risk budget: weights that sum to more than the cap are shrunk together, never one leg alone; merged makes the backtest's positions look like the exchange's.
Example: cross-sectional momentum over 12 perpetuals, rebalanced daily. Every 6 bars of 4h (anchored to 00:00 UTC), rank the 12 legs by their 7-day return; the 3 strongest get +gross / 6 each, the 3 weakest -gross / 6, the rest 0; NaN between rebalances (hold).
from __future__ import annotations
from dataclasses import dataclass
from typing import ClassVar
import numpy as np
from optalgo_engine.sdk import BarSeries, Intents, StrategyOutput, VectorStrategy
@dataclass
class TargetWeights12(VectorStrategy):
"""Long the strongest, short the weakest of 12 symbols, equal weights, scheduled rebalance."""
name: ClassVar[str] = "target_weights_12"
legs: ClassVar[int] = 12
lookback: int = 42 # bars of return the ranking reads (42 x 4h = 7 days)
rebalance_every: int = 6 # bars between rebalances (6 x 4h = daily)
n_long: int = 3
n_short: int = 3
gross: float = 1.0 # sum of |weights|
def warmup_bars(self) -> int:
return self.lookback + 1
def run(self, series: list[BarSeries], decision: list[BarSeries] | None = None) -> StrategyOutput:
n = len(series[0])
closes = np.vstack([s.c for s in series]) # legs x bars
ret = np.full_like(closes, np.nan)
k = self.lookback
if n > k:
ret[:, k:] = closes[:, k:] / closes[:, :-k] - 1.0 # causal: bar i reads closes up to i
weights = np.full_like(closes, np.nan)
w = self.gross / max(self.n_long + self.n_short, 1)
# rebalance bars anchored to the clock, not to where the data starts
period = max(self.rebalance_every, 1) * series[0].key.tf_s
t = series[0].t
at = np.flatnonzero((t % period == 0) & (np.arange(n) >= k))
r = ret[:, at]
ok = np.isfinite(r).all(axis=0)
rank = np.argsort(np.argsort(np.where(np.isfinite(r), r, 0.0), axis=0, kind="stable"), axis=0)
legs = len(series)
row = np.where(rank < self.n_short, -w, np.where(rank >= legs - self.n_long, w, 0.0))
weights[:, at[ok]] = row[:, ok]
out = []
for j in range(len(series)):
it = Intents.empty(n)
it.target[:] = weights[j]
out.append(it)
return StrategyOutput(intents=out, plots={"leg0_weight": weights[0]})
The spec (Pro: 12 symbols; every one has 4h data from before 2021):
{"name": "target weights 12",
"strategy": {"params": {"lookback": 42, "rebalance_every": 6, "n_long": 3, "n_short": 3, "gross": 1.0}},
"market": [{"exchange": "BINANCE", "symbol": "BTCUSDT.P"}, {"exchange": "BINANCE", "symbol": "ETHUSDT.P"},
{"exchange": "BINANCE", "symbol": "SOLUSDT.P"}, {"exchange": "BINANCE", "symbol": "BNBUSDT.P"},
{"exchange": "BINANCE", "symbol": "XRPUSDT.P"}, {"exchange": "BINANCE", "symbol": "DOGEUSDT.P"},
{"exchange": "BINANCE", "symbol": "ADAUSDT.P"}, {"exchange": "BINANCE", "symbol": "AVAXUSDT.P"},
{"exchange": "BINANCE", "symbol": "LINKUSDT.P"}, {"exchange": "BINANCE", "symbol": "NEARUSDT.P"},
{"exchange": "BINANCE", "symbol": "UNIUSDT.P"}, {"exchange": "BINANCE", "symbol": "BCHUSDT.P"}],
"timeframe": "240",
"window": {"start": "2023-01-01", "end": "2026-01-01"},
"execution": {"leverage": 2, "rebalance_band": 0.01, "gross_cap": 1.5, "target_position": "merged"}}
Weights summing to 1.0 at leverage 2 ask for a gross of 2.0, so the cap scales every target by 0.75 on every rebalance (gross_cap_scaled); at the default 1000 equity some BTC resizes fall below Binance's minimum order (below_minimum_orders): raise execution.initial_equity or the weights. On a Free or Plus plan (3 symbols), use 3 legs and n_long = n_short = 1.
The result gains a portfolio block (any run with several legs or a target):
"portfolio": {
"legs": [{"symbol": "BINANCE/BTCUSDT.P/240", "target": true, "net_pnl": 293.56, "gross_pnl": 346.3, "fees": 45.99,
"funding": -6.74, "turnover": 91972.6, "turnover_x": 91.97, "trades": 155, "target_trades": 303,
"band_skipped": 1675, "below_minimum": 198, "max_notional": 507.31}, "…"],
"exposure": {"gross_max": 1.7156, "gross_mean": 1.4853, "net_max": 0.1203, "net_min": -0.1039, "net_mean": 0.0029,
"unit": "notional / account equity at each bar close", "series": {"t": ["…"], "every_bars": 17, "gross": ["…"], "net": ["…"]}},
"account": {"max_drawdown": -0.468, "margin_use_max": 0.8578, "margin_use_mean": 0.7426,
"margin_use": "sum(|notional| / leverage) / equity"},
"liquidation": {"checked": true, "hit": false, "bars": 0, "first_t": null, "min_margin_ratio": 106.1,
"min_margin_ratio_t": 1730865600, "mmr": {"BINANCE/BTCUSDT.P/240": 0.005, "…": "…"},
"approximate": ["BINANCE/BTCUSDT.P/240", "…"], "method": "cross margin: …"},
"options": {"rebalance_band": 0.01, "gross_cap": 1.5, "target_position": "merged"},
"gross_cap": {"cap": 1.5, "bars": 6577, "share": 1.0, "max_requested": 2.0, "min_scale": 0.75,
"drift_bars": 102, "realised_gross_max": 1.7156},
"band": {"band": 0.01, "skipped": 35057, "turnover": 1360872.49, "turnover_band0": 1415497.26,
"turnover_saved": 0.0386, "final_equity": 1833.16, "final_equity_band0": 1778.56}}
legs[]: per leg net and gross PnL, fees, funding (+ = received),turnover(notional traded) andturnover_x(× initial equity), trades,target_trades(decisions that placed an order),band_skipped,below_minimum(target orders under the exchange minimum, not placed),max_notional.exposure: gross (sum |notional|) and net (sum notional) over equity at every bar close: max, mean, and a sampledseriesto plot.account: the account'smax_drawdown;margin_use=sum(|notional| / leverage) / equity(max, mean). Near 1 means little room left.liquidation: a whole-account (cross margin) check: every perpetual leg marked at its worst price of the bar together (a long at the low, a short at the high) against the maintenance marginsum(|qty| × price × mmr).mmris the instrument's first-tier maintenance rate; when unknown it is 0.5 % and the leg is listed inapproximate.min_margin_ratio= the lowest equity / maintenance margin (below 1 = liquidated). Approximate on purpose (no tiers, no fees inside the bar): ahitis a grade D finding, the run does not apply a liquidation.gross_cap(with a cap): bars scaled, theirshare, the largest gross asked for and the smallest scale applied, anddrift_barswhere the realised gross ran above the cap × 1.05.band(with a band): decisions skipped and the turnover and final equity against the same run at band 0 (the engine runs it again to tell you what the band saved).
Honesty findings it adds (the grade moves to the worst one):
| Code | Grade | Means | Do |
|---|---|---|---|
liquidation_risk | D | On bars bars the legs' worst prices together took equity below the maintenance margin (first at first_t); a real cross-margin account would have been liquidated | Lower leverage or set / lower gross_cap; never quote the numbers |
gross_drift_above_cap | B | The realised gross exposure ran above gross_cap × 1.05 on bars bars (max) | Rebalance more often, a smaller band, or a lower cap if the drift matters |
below_minimum_orders | B | total target orders were below the exchange minimum (min qty / notional) and not placed (per_leg): those legs stayed away from their target | Raise initial_equity or the weights, or drop the smallest legs |
gross_cap_scaled | A | The targets asked for more than the cap on bars bars and were scaled down (min_scale) | Information: the cap did its job; size the weights to the cap if you want them as written |
band_turnover | A | What the band saved: decisions skipped, turnover and final equity against band 0 | Information: a wider band trades less but tracks the targets more loosely |
Hosted: on paper. A portfolio deploys like any hosted strategy (section 3) and runs on paper only: up to 16 legs on the Pro plan (Free and Plus: 4, hosted_leg_limit). How it trades:
- Targets only. A hosted
targetstrategy usestargetand nothing else: noenter/exit, nosl/tp, nosize, nomax_bars, nosl_update/tp_update(refused astarget_mixed). Close a leg withtarget = 0.|target|is capped at 1 (the whole allocation as margin; × the deployed leverage = the notional). - Every bar OptAlgo runs the backtest's row: each leg's target (its last one when it says nothing),
gross_capscaling every leg when the row asks for more (then every leg trades its scaled target, every bar the row stays above the cap, as in the backtest). Each leg that trades sends aTARGETdecision. - OptAlgo trades the bot's real position to the target, not a replayed one: from flat it opens at the target; a smaller target closes the difference (a partial close); 0 closes; a sign change closes, then opens the other side; a larger target closes and re-opens at the new size (no add-to-position yet: two fees and a flat instant; decision code
target_reopen).rebalance_bandis decided on the real position (band_skipped). A difference below one amount step or the exchange's minimum is not traded (at_target,below_minimum). - Sizing is the bot's allocation (a multi-leg portfolio: the whole allocation, as in several legs), not compounded.
- Live: not yet.
request-liveand the app's confirm answertarget_paper_only. To trade money today, anenter/exitversion withsizedeploys and goes live as usual.
Without a rebalance_band the dry run warns target_band_zero: every small change trades, and every increase pays the re-open. Backtest with a band (0.01 to 0.05) before you deploy. Compare with backtest matches a portfolio by rebalance bars per leg (report.target).
The 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 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, 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.plotsare 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); 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.
Meta-label 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.
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
enterintents. The model skips or sizes the strategy'senterintents; it never touchestarget. A strategy that sets its position throughit.target(e.g.prims.target_steps) has nothing to filter: research on it fails withmeta_no_entries. Write the entries asit.enter[...] = 1 / -1and the exits asit.exit[...](or a stop / target / time barrier), backtest that, then research. A verdictineffectivemeans 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_barsa feature must not depend on where history starts: anemaof a long length seeded too close to the decision fails. The run recordssandbox.features_window: "unstable"(with the feature and bar) and meta research refuses it. Raisewarmup_barsto 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):
{"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:
{"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, 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.
{"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. Rule declaration: a legs / references / data declaration that is not a literal ClassVar with an allowed value |
| Code, dry run | lookahead, nondeterministic, strategy_error, size_scale, size_negative, sandbox (a stop at run time: rule, kind, see stop kinds); warnings lookahead_suspect (static), dry_run_limit, 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) | magnifier_timeframe, override_unknown, override_invalid, venue_option, early_decision_magnifiers, early_decision_lead, research_unsupported, size_multiplier_invalid, inputs_need_crypto, slippage_* (a slippage map), 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; 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, "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) | unknown_reference, reference_source, data_unavailable, early_decision_unsupported, unsupported_timeframe (a reference's @timeframe); warnings reference_starts_late, data_starts_late, data_absent, spot_short_refused (dry run: shorts on a SPOT leg), 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: 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 (the estimate is above the plan's wall time: the same, an error), 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.
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); prefer validate.
2.4 The backtest loop
Repeat until the user is satisfied:
- Limits and quota:
GET /v1/backtests/limits. Ifquota.remainingis below the run's cost, stop and tell the user when it resets. - Validate (2.3) until
ok. Itscost.unitsis the estimate that will be reserved. - Submit:
POST /v1/backtestswith the same{spec, source}→202 {"id", "status": "queued", "units", "units_estimated", "position", "eta_s", "poll", "next"}. The estimate is reserved from the quota now. - Wait and poll. When busy, runs queue instead of being refused: plans in order Pro, Plus, Free, then in turn per user; besides your
max_concurrentrunning jobs, up to 3 more may wait. Whilestatusisqueued, tell the user once where it stands ("3rd in the queue, starts in about 40 s"). Poll thepollpath, waitingpoll_after_sseconds between calls (5 s when absent); each answer updatespositionandeta_s. Stop atdoneorfailed. While a run is active,progresssays where it is:phasequeued|waiting_for_memory|downloading_data(Binance archive data such as open interest: can take minutes, not run time) |running, pluselapsed_s,estimate_sandover_estimate_s.eta_sisnullwhen unknown (downloading, or past the estimate): never invent one, followpoll_after_s. - Read the result, summary first (2.5). Tell the user in 3 to 5 lines: what ran (symbols, timeframe, window, params), grade and main findings, the search verdict, return, max drawdown, trades, units charged, and what you try next.
- Change one thing (code or params) and go back to 2. Changing the strategy is fine; tuning its parameters by hand is not (below).
Avoid overfitting
Every run you make on the same data is a try. Run 35 variants of one idea on one window and the best of them looks good partly by luck, even if each one alone grades B: the grade judges one run's mechanics, not the search around it. So:
- Don't sweep parameters with many single runs. Use one research run that optimises and validates out-of-sample: the same spec plus
research(walk_forward, with the parameters you would have swept asspace). Itsverdictis judged on test folds the optimiser never saw. Whensearchadvises it,search.researchis a ready-made block: validate it first (it costs quota by run time). - Or keep a holdout window you never tuned on. Tune with
window.endbefore the last months (search.holdout.tune_window), then run the chosen parameters once on the rest (search.holdout.test_window) and report that run. A run on data none of your variants saw starts a fresh count. In a study, declare it in the holdout vault before tuning: OptAlgo then refuses tagged runs over it and keeps the one final test honest. - Group one idea's runs into a study (tag
study:<name>): its verdict counts every variant you tried, on any window. Before deploying, check robustness. - Report the search verdict with the grade: "grade B, 35 variants tried on this window, likely overfit".
- Send at most 3 runs at once and wait for their results before the next batch.
A run that lost money (annualised Sharpe ≤ 0, or a negative total_return) is not luck of a search: it has no edge. Its search verdict is no_edge however many variants you ran, and the fix is a different idea (entries, exits, filters, market or timeframe), not a research run over the same losing one.
The deploy gate (section 3) refuses a backtest whose search verdict is likely_overfit unless an out-of-sample research run of the same code passed (search.validated_by), and always refuses a losing backtest (no_edge), even when such a research run passed.
The spec:
| Field | Required | Meaning |
|---|---|---|
market | yes | 1 to max_symbols legs {"exchange": "BINANCE", "symbol": "BTCUSDT.P"}. .P = USDT-M perpetual (funding modelled); no suffix = spot. Stocks: {"exchange": "BIST", "symbol": "THYAO"} or {"exchange": "ALPACA", "symbol": "AAPL"} (stocks). Forex: {"exchange": "FX", "symbol": "EURUSD"} (forex). Two or more symbols run as a basket, unless the strategy declares legs = N: then exactly N symbols, in the order run() reads them, on one account (several symbols in one strategy). |
timeframe | yes | Bar size in minutes, as a string ("15", "60", "240"): any value in data.timeframes of GET /v1/markets. |
window | yes | {"start": "2024-01-01", "end": "2025-01-01"} (UTC). Warm-up history before start is loaded for you. |
strategy.params | no | Parameter overrides, e.g. {"fast": 10}. Leave strategy.name out (422 source_required). |
name | no | Your label, shown in the app. |
execution | no | Backtest assumptions, all with defaults: initial_equity (1000), leverage (1), magnifiers ("auto"), and costs: commission, spread, slippage and funding, each Auto by default (the venue's own numbers, see Costs). Leave costs out unless the user asks for other costs. The older fee_profile / slippage / funding fields still work (slippage as a map per symbol too), but not beside costs (costs_conflict). For target weights: rebalance_band, gross_cap, target_position (rows below). |
execution.rebalance_band | no | Portfolios: a same-side target within this distance of the position (target units, 0.01 = 1 % of equity) is not traded; outside it the position trades all the way to the target; 0, flips and entries from flat always trade. Default 0. |
execution.gross_cap | no | Portfolios: when sum(|target| × leverage) over the legs exceeds it, every target is scaled down pro rata (1.5 = gross at most 1.5× equity). Default: none. |
execution.target_position | no | Portfolios: lots (default: each increase its own lot) or merged (one position per leg at the average entry, like an exchange). |
research | no | A validation job instead of one backtest (one symbol; a multi-leg strategy: its N legs together; a one-instrument strategy on several symbols: the whole basket, see Research on a basket): {"protocol": "walk_forward", "plan": {"plan": "rolling", "train_days": 180, "test_days": 30, "step_days": 30}, "space": {"fast": {"low": 5, "high": 50, "step": 5}}, "n_trials": 40, "objective": "sharpe"}. Protocols: optimize, walk_forward, nested_walk_forward, multi_config, purged_cv, cpcv, masters4, monte_carlo. See Research runs. |
Costs: commission, spread, slippage, funding
Every backtest pays four costs. Each is Auto unless the run says otherwise: Auto is the venue's own numbers from OptAlgo's venue cost registry (one row per venue, market and symbol, kept up to date by OptAlgo; a new exchange is a new row, not new code). Read what Auto is before you run: GET /v1/costs/auto?venue=BINANCE&market=usdm&symbols=BTCUSDT (public, no key; market spot | usdm | fx | stock) → {venue, market, symbols: {SYM: {commission, spread, slippage, funding, contract, source}}, registry_version}.
"execution": {"costs": {"commission": "auto", "spread": "auto", "slippage": "auto", "funding": "auto"}}
| Field | Auto | Your value |
|---|---|---|
commission | the venue's maker / taker rate (Binance USD-M 0.02 % / 0.05 %, spot 0.1 %; Exness forex 0) | {"maker": 0.0002, "taker": 0.0005} (fractions of notional per fill) or {"per_lot": 3.5} (forex: quote currency per lot per fill) |
spread | forex / gold only: the bar's own spread where the data has one (Exness 1-minute bars), else the registry's typical spread for the pair | {"pips": 0.8} or "none"; refused on crypto and stocks (costs_spread_not_applicable) |
slippage | the registry's (0 on every venue today) | a fraction on every taker fill (0.0005 = 0.05 %), or a map per symbol |
funding | perpetual funding on .P; overnight swap where the registry has it | "off" |
- Default Auto. Do not set slippage or any cost unless the user asks for it. Auto is what the venue charges; a guess added "to be safe" makes the backtest disagree with the account (a deployed forex backtest once carried an agent's slippage on every fill and paid about four times the spread the account really paid).
- Forex fills on the bid and the ask. The bars are BID. A buy fills on the ask (bid + spread), a sell on the bid, so a round trip pays one spread, inside the price: no separate spread fee. A short's stop-loss and take-profit, and a buy limit, trigger on the ask. On the chart a buy marker sits a spread above the BID candle; that is the ask, not an error.
- What the run used: a finished row carries
costs{model: "v2", requested, registry_version, legs: [{venue, market, symbol, commission, spread_pips, spread_px, slippage, funding, source, auto}]}(sourceper field:registry:<venue>/<market>/<symbol>@<version>oruser;auto= what Auto would have charged) andcost_model(v2). Runs from before the registry saycost_model: "v1"(the old model: a forex run paid half a spread as a fee per fill; a crypto or stock run is unchanged by v2) and keep their results; run them again on Auto as a cost variant to compare. - Grade: costs set below Auto in total (cheaper commission, spread or slippage than the venue's) drop the honesty grade one step (
costs_below_auto: the run looks better than the venue would trade it). A value more than 2× above or below Auto is a note (costs_far_from_auto): check it is what the user meant. Costs above Auto never lower the grade. - Unknown venue: a venue or symbol with no registry row is refused (
costs_unknown_venue,costs_unknown_symbol), never guessed.
Cost variants: the same run at other costs. POST /v1/backtests/{id}/variants {"costs": {...}} (tool rerun_backtest(id, costs); scope backtest) runs a finished backtest again with other costs as a new backtest: 202 with the submit answer plus cost_variant_of = the original, which is never changed. It is charged like any run and works on a pruned run too. GET /v1/backtests/{id}/variants lists them, newest first. The same costs as the original answer 409 variant_same_costs; costs that match another run you already have 409 variant_already_ran (existing_id); an unfinished original 409 not_ready. A variant is not tagged into the original's study and does not count in its search, so the study's pinned settings do not bind it ("rerun on Auto" works for a run in a pinned study). Show the variant beside the original (return, drawdown, fees) when the user asks "what if fees were higher?".
Stocks: BIST and US
Backtests, research (walk-forward and the other protocols), robustness checks and ablations take stock symbols as well as crypto. Name the exchange: {"exchange": "BIST", "symbol": "THYAO"} (Borsa Istanbul, prices in TRY) or {"exchange": "ALPACA", "symbol": "AAPL"} (US stocks and the SPY / QQQ / DIA ETFs, USD). markets lists the symbols, their timeframes and where their data starts. The engine applies the venue's rules on its own:
- Sessions: no fills while the market is closed. From 1h up, bars are cut at the session: BIST 1h = 10:00..17:00 Istanbul, 4h = 10:00-14:00 and 14:00-18:00; US 4h = 09:30-13:30 and 13:30-16:00 New York. BIST has
60,240and1440only. - Costs and lots: the venue's own fees (BIST 0.15 % a side; US commission-free plus SEC/TAF fees), whole shares.
- Shorts: BIST is long-only: short entries are removed before the run and counted (
shorts_refused). US stocks can be shorted (borrow costs not modelled). FX pairs can be shorted (enter = -1), though they are listed asSPOT. - Prices are split-adjusted (
equities.legs[].adjusted: true). - History: BIST hourly bars start 2024-01-02; US bars 2016.
- Count lookbacks in session bars. Closed hours are not bars: a BIST
60day has 8 bars (10:00..17:00), a week 40, a year about 2,000 (252 days);240has 2 a day. Solookback = 168on BIST 1h is about 4 weeks, not one.validate'sestimate.bars_per_legcounts the same session bars.
Several stocks run as a basket (each on its own slice of the capital) or as the legs of one strategy (legs = N, e.g. a target-weight portfolio ranking N stocks), as crypto symbols do; every stock keeps its sessions, fees and shorting rule.
Not available for stocks: references and data series (references, data), execution.early_decision_s, execution.ticks, a crypto and a stock symbol in one run, and paper or live trading.
Forex: FX venues
Forex has no exchange: every source is its own venue with its own prices and symbols. Backtests, research, robustness checks and ablations take 10 pairs (EURUSD, USDJPY, GBPUSD, AUDUSD, USDCAD, USDCHF, NZDUSD, EURJPY, GBPJPY, EURGBP) on:
| Venue | Prices | History | Paper / live |
|---|---|---|---|
FX-EXNESS | the Exness broker (what an Exness MT5 account fills at) | 1-minute from 2014-01-14 to now | hosted later, MT5-enabled accounts |
FX-HISTDATA | a bank feed (research data) | 1-minute 2015 to 2026-10 | never: backtest only |
{"exchange": "FX-EXNESS", "symbol": "EURUSD"}. FX is the old name of FX-HISTDATA (old runs keep it). Compare venues by running the same code and spec on each (one study tag). Every timeframe from 1 to 1440. The engine applies forex rules on its own:
- Week: trades Monday-Friday, UTC days; closed 25 Dec and 1 Jan. The Sunday-evening reopen (~21:00 UTC) is not traded: the weekend gap shows at Monday 00:00 UTC.
- Prices are BID; fills are bid / ask. A buy fills on the ask (bid + spread), a sell on the bid: one spread a round trip, in the price, no spread fee. Auto spread is each bar's own where the data has it (
FX-EXNESS1-minute bars), else the registry's typical spread for the pair; the leg'scostssays which. Commission Auto is 0 (an Exness Standard account); setexecution.costs(spread,commission.per_lot) only when the user's account differs. See Costs. - Units and account: sizes in units of the base currency; profit, fees and the account are in the pair's quote currency (EURUSD in USD, USDJPY in JPY:
initial_equity10000 there means 10,000 JPY). Pairs with different quote currencies cannot share a run (mixed_currencies), and forex never runs beside crypto or stocks (fx_mixed_markets). - Shorts and leverage are allowed (
execution.leverage). - Not modelled, and said in the honesty report: overnight swap (
swap_not_modelled, C, when a position is held through 17:00 New York; Wednesday counts three days), the wider spread around that rollover (fx_rollover_fills, B). Forex has no volume: the volume column is 0 (no_volume). - Backtests only: results, trades, equity and charts are available; raw prices are not (
bars/plotsdownloads answerdata_licence, candles come at most 500 per call). No paper or live forex yet. - Count lookbacks in trading bars: a
60week has 120 bars, a year about 6,240 (260 days).
Several symbols: a basket backtest
A strategy.py that does not declare legs trades one instrument (it may still read other symbols as references). Put several symbols in market and the backtest runs as a basket, automatically (no extra field): one independent backtest per symbol, each with initial_equity / N of the capital (1000 over 3 symbols = 333.33333333 each), the same execution, fees and funding. That is exactly how a hosted strategy (section 3) trades several symbols: one slot per symbol, allocated_amount / N each (a multi-leg strategy is different: its legs share one account, sized on the whole allocation). validate says so with a basket warning (it does not block).
The result tells you it is a basket and adds, per symbol, what a single run has:
{"basket": true,
"allocation": {"rule": "initial_equity / symbols (…)", "symbols": 3, "initial_equity": 1000.0, "per_symbol": 333.33333333},
"metrics": {"initial_equity": 999.99999999, "final_equity": 1084.2, "total_return": 0.0842, "max_drawdown": -0.071, "trades": 165, "…": "…"},
"per_symbol": {"BINANCE/BTCUSDT.P/60": {"initial_equity": 333.33333333, "grade": "B", "metrics": {"total_return": 0.12, "…": "…"}, "counters": {"…": 0}},
"BINANCE/ETHUSDT.P/60": {"…": "…"}, "BINANCE/SOLUSDT.P/60": {"…": "…"}},
"honesty": {"grade": "C", "per_symbol": {"BINANCE/BTCUSDT.P/60": "B", "…": "…"},
"findings": [{"grade": "C", "code": "warmup_short", "symbol": "BINANCE/SOLUSDT.P/60", "…": "…"}]}}
metricsare on the combined equity (the symbols' equities summed) and all trades;per_symbolholds each symbol's own numbers. Report both: a basket that wins on one coin and loses on two is not an edge.- The grade is the worst symbol's; every finding carries its
symbol. Fix the weakest symbol or drop it. - Trades (
trades.arrow, the chart'strades) carry theirsymbol; the chart's equity is the combined curve, withbasket: trueand aper_symbolsummary. - Cost: run time is the sum of the symbols' runs (about N times one symbol), charged as usual.
max_symbolsstill applies. Memory is about one symbol's: the symbols run one after another, so a basket fits the plan's memory when one symbol does (validate'sestimate.mem_mbalready counts it this way). - Research (
researchblock) on a basket runs every trial as the basket: the same parameters on every symbol, the objective on the summed equity, folds split time for all symbols together (Research on a basket). One job = one try for the search counter. A research basket keeps every symbol loaded, so its memory estimate is all symbols together. - To deploy on several symbols (section 3), backtest exactly those symbols as a basket first; you may then deploy any subset of them. A multi-leg strategy (
legs = N) is never a basket: it deploys on exactly its N legs, no subset.
Slippage per symbol
One execution.slippage number charges every symbol the same. In a basket of liquid majors plus one thin coin, that either charges BTC the thin coin's slippage or lets the thin coin trade like BTC. Send a map instead: default for every symbol not named, plus the symbols that differ. It works the same in a single run, a basket, a multi-leg strategy and a research run.
{"market": [{"exchange": "BINANCE", "symbol": "BTCUSDT.P"}, {"exchange": "BINANCE", "symbol": "ETHUSDT.P"},
{"exchange": "BINANCE", "symbol": "SOLUSDT.P"}, {"exchange": "BINANCE", "symbol": "BRETTUSDT.P"}],
"timeframe": "60", "window": {"start": "2025-01-01", "end": "2025-07-01"},
"execution": {"slippage": {"default": 0.0005, "BRETTUSDT.P": 0.0015}}}
- Keys: the spec's symbols, with or without the exchange (
"BRETTUSDT.P"or"BINANCE:BRETTUSDT.P"; the exchange-prefixed key wins when both are sent).defaultis required. Each value is a fraction from0to0.05(5 %):0.0015= 0.15 % per taker fill, not0.15. - Validate names every problem with a fix:
slippage_default_missing,slippage_symbol_unknown(a key that is not inmarket;allowedlists them),slippage_value_invalid(negative, above 0.05, or not a number; a value above 0.05 getssuggestion= value / 100),slippage_key_duplicate(one symbol named twice),slippage_override_conflict(execution.overrides.slippagebeside a map: remove it). - The result says what each symbol paid:
diagnostics.costs.slippage_basisis"map"andcosts.slippage_by_symbolholds{"BINANCE/BRETTUSDT.P/60": {"slippage": 0.0015, "taker_notional": 8120.4, "slippage_cost": 12.16}, …}(slippage_estimateis their sum); a basket'sper_symbolentries and a multi-leg run'sby_legrows carryslippageandslippage_cost;honesty.assumptions.slippagelists the map you sent andhonesty.modelledone slippage line per symbol. - Stress it: run the same spec once more with every value ×2 (
{"default": 0.001, "BRETTUSDT.P": 0.003}). A strategy whose edge disappears at twice the slippage has no margin for live fills. - A plain number gives exactly the results it always did. Hosted strategies do not use it: live and paper fills are real; compare them with Compare with backtest.
- The same map goes in
execution.costs.slippage(Costs). Auto slippage is 0: set one only when the user asks. This is an assumption you choose per coin, not an order-book model; forex spread is modelled separately (bid / ask fills).
Research runs
plan(days):{"plan": "rolling" | "anchored", "train_days", "test_days", "step_days"}(step_daysdefaults totest_days);purged_cvtakes{"plan": "purged_kfold", "k", "purge_days", "embargo_days"},cpcvtakes{"plan": "cpcv", "n_groups", "k_test", "purge_days", "embargo_days"}. The kindplan.planmay be left out: it is the protocol's, elserolling.nested_walk_forwardalso needsinner(a rolling plan inside each training span);multi_configneedscandidates(a list of fixed parameter sets) instead ofspace. Default plan: rolling 180 / 60.space: per parameter{"low", "high"}(+"step","log") or{"choices": [...]}."sampler": "grid"tries every configuration of a finite space once (every parameter needssteporchoices); the defaulttpesamplesn_trialsof them.- Any shape problem in
researchis aspec_invalidfinding on its field invalidate; fix it before you submit. - Trials count against
max_trials:n_trials(withsampler: grid, at most the number of configurations inspace;multi_config: the number ofcandidates). Onlymasters4also runs permutation tests, and then max(n_trials,permutations×permutation_trials,wf_permutations) counts; fields you leave out take the engine defaults (n_trials50,permutations100,permutation_trials20,wf_permutations50), so for masters4 always setpermutationsandpermutation_trialssmall yourself. More configurations and more folds mean more run time, so more units. - Combine backtests into one portfolio:
POST /v1/backtests/combine {ids, weights?, rebalance?, points?}(connector:compare_backtests(ids, combine=true, weights?, rebalance?, detail?)). Combines 2 to 8 of your finished backtests from their stored equity: nothing re-runs, it is free (0 units) and nothing is stored. They are aligned on the UTC days they share (window).weights: one number per id (scaled to sum to 1),"equal"(default) or"risk"(inverse volatility, in-sample).rebalance:daily(default),monthlyornone(buy and hold; a basket split overmax_symbolsinto two runs, combined withnoneand weights = each half's share of the coins, is the whole basket). Answer:metrics(return, CAGR, Sharpe, Sortino, max drawdown, volatility, worst month),members(weight, grade, search verdict, return, Sharpe, drawdown, contribution, risk share),correlation(daily, monthly),diversification_ratio, dailyequity, andhonesty: the grade is never better than the weakest member,searchcarries the worst member verdict,findingsstate what is assumed (separate capital per member, free rebalancing, daily-close drawdown, in-sample). Report the grade and search verdict first. Errors: 404 for an id that is not yours, 409 until every run is done, 410pruned(rerun that member), 422invalid_request. - A research run's result (
GET /v1/backtests/{id}):summary{verdict,protocol,oos_return,oos_sharpe(annualised like a backtest's),oos_sharpe_bar(per bar),folds,folds_positive,n_trials,evaluations,failed,warnings} andresult= the report; each fold haschosen,train/test(the objective),trades, andtrain_window/test_window(epoch s). A research run keepsresearch.jsonandspec.json(also served asfiles/result.json): no trades or candles (charts answerno_chart_for_report). Its stitched out-of-sample curve isresult.oos_equity{t,equity,bars,fold_starts} (1.0 at the first test bar, thinned to 1500 points; the connector shows it withdetail="normal"). A basket fold addsper_symbol{symbol: {return,trades}} (each symbol's profit over the basket's capital; they add up to the fold'stest_return). - Reading a walk-forward:
summary.oos_returnis the chained out-of-sample return;folds[i].trainandfolds[i].testare the objective on that fold (per-bar Sharpe for"objective": "sharpe"), not returns;folds[i].chosenis what the fold picked.summary.n_trialsis the number of distinct configurations evaluated (what the deflated Sharpe inoverfit.checks.dsrcorrects for);summary.evaluationsis configurations × folds. - An ablation variant that changed nothing (
ablate,research.protocol: "ablation"): each variant'ssummary.verdictisrobust_win,harmful,no_effectormixed; a variant equal to the baseline on every coin in every window and cost (every Δ Sharpe exactly 0, the same trades) getsvariant_identical_to_baselineinstead, withsummary.finding{code, message}: the rule changed no position. The usual cause is a NaN fed to a recursive indicator (fill or skip it). Run one backtest of the variant and read itsresult.inputs(the columns' coverage) before calling the rule useless.
Validate fixed parameters out of sample (no search): either a walk-forward with ONE configuration ("space" with one choice per parameter, "sampler": "grid", "n_trials": 1): every fold tests the same parameters on data after its training span, it counts as 1 trial, and the verdict judges the out-of-sample folds; or a holdout: run the parameters once, as a plain backtest, on a window you never tuned on (search.holdout.test_window), and report that run.
{"protocol": "walk_forward", "plan": {"plan": "rolling", "train_days": 365, "test_days": 90, "step_days": 90},
"space": {"lb1": {"choices": [42]}, "lb4": {"choices": [336]}}, "sampler": "grid", "n_trials": 1, "objective": "sharpe"}
Research on a basket
Put several symbols in market with a one-instrument strategy and a research block (walk_forward, purged_cv, cpcv, masters4, ...). Every trial runs the basket exactly as a basket backtest does: initial_equity / N per symbol, the same parameters on every symbol, all trading from the latest first bar (result.basket.common_start when a symbol was listed later). The objective (sharpe, return, calmar, profit_factor) is computed on the summed basket equity; legacy_score is refused for several symbols. Folds split time for all symbols together, and a fold's chosen applies to every symbol; folds[i].per_symbol shows which coins carried or hurt it. result.basket = {symbols, allocation, objective_on, common_start?}. The verdict and overfit.checks read as for one symbol.
Cost: about N single-symbol research runs of run time, quoted by validate's estimate.run_s (10 symbols, 1h, 5 years, 30 trials, 8 folds: about 65 s, ~7 units). Every symbol is held in memory at once: with the 1m magnifier, 10 or more symbols over 5 years exceed a 4 GB job, and validate suggests execution.magnifiers: ["5"]. Over the time cap, validate suggests fewer research.n_trials or a longer step_days, never a split. Robustness checks still take one symbol at a time.
Studies: the runs of one idea
A study is every backtest of yours that carries one tag, by convention study:<name> (study:rsi-4h; any tag works). Nothing to create: send "tags": ["study:rsi-4h"] with POST /v1/backtests or POST /v1/backtests/validate (at most 5 tags), or add the tag later with PATCH /v1/backtests/{id}. A robustness run inherits its backtest's tags. Why: a run's search counts variants on overlapping windows of the last 30 days; a study's verdict counts every variant you put in it, whatever the window or date. Tagging runs into one study says they are one search.
| Call | Scope | Answers |
|---|---|---|
GET /v1/studies | read | {studies: [{tag, description, runs, backtests, first_run, last_run, best_grade, best_sharpe, holdout_used}], total, truncated}, the most recently run first (at most 100). holdout_used: null without a holdout, else whether its final test ran |
GET /v1/studies/{tag} | read | {tag, description, runs, truncated, variants_tried, verdict, best_run, spread, research, table, holdout}; study_not_found (404) for a tag none of your runs carries |
POST /v1/studies/{tag} | backtest (or bots / trade) | {"description": "…", "pinned": {…}}, both optional: the idea or hypothesis under test, at most 280 characters of plain text ("" / null clears; a body with neither field clears it), and the study's pinned settings. Answers the study's list row (with pinned) |
verdict{variants_tried, sharpes_known, best_sharpe, expected_max_sharpe_by_luck, deflated_sharpe_prob, verdict, fix, assumptions}: the deflated Sharpe of the study's best run against every distinct variant among its done plain backtests (the same spec twice is one variant; the holdout's final test is not a variant). The same scale assearch:no_edge(the best run lost money),ok(one variant, or a probability of at least 0.95),caution(below 0.95),likely_overfit(below 0.5);nulluntil a backtest of the study is done. Report it with the best run's grade, and do whatfixsays.best_run{id, created_at, grade, total_return, max_drawdown, sharpe, trades, params, symbols, timeframe, window, note}: the highest annualised Sharpe.spread: Sharpe and return{min, median, max}, drawdown{worst, median}, runs per grade (a best run far above the median is the luck the verdict discounts).research: up to 10 research runs of the study with their out-of-sampleverdict.table: the newest 50 runs ascolumnsid, created_at, kind, status, grade, total_return, max_drawdown, sharpe, note+rows, withtotal/shown.holdout:null, or the holdout vault block. A study reads at most 500 runs (truncated).nextfollows the verdict:caution/likely_overfit→ one research run instead of more sweeps;no_edge→ change the idea, not its parameters.
Pinned study settings
Variants of one idea are only comparable at the same costs and account. A study pins execution.costs too ("costs": {...}, the Costs block); a run that sends execution.costs is checked against old slippage / fee_profile pins through it. A cost variant is not part of the study and is not checked. Pin them once and OptAlgo holds every run of the study to them: POST /v1/studies/{tag} {"pinned": {"fee_profile": "binance-vip0", "slippage": {"default": 0.0005, "BRETTUSDT.P": 0.0015}, "initial_equity": 1000, "leverage": 2}}. Only the fields sent change; a field sent as null unpins it, "pinned": null clears them all. GET /v1/studies and GET /v1/studies/{tag} show pinned (null when nothing is pinned).
| Pinned field | RunSpec path | Values | Default when a spec leaves it out |
|---|---|---|---|
fee_profile (or fees, not both) | execution.fee_profile | binance-vip0, binance-vip0-bnb, optalgo-account, brain-compat, legacy | binance-vip0 |
slippage | execution.slippage | a number 0 to 0.05, or a map with default (at most 64 keys, each 0 to 0.05) | 0 |
initial_equity | execution.initial_equity | above 0, at most 1e9 | 1000 |
leverage | execution.leverage | above 0, at most 125 | 1 |
- Every run tagged with the study (backtest, research, robustness, the holdout's final test, a rerun, the tag added later with
PATCH) whose settings differ is refusedstudy_settings_mismatch(409), naming each field, the pinned value and what the run would have used;validatereports the same as a finding (ok: false). A spec that setsexecution.overridesfor a pinned field also differs. Slippage is compared per symbol: a number and a map that give every leg the same rate agree. Untagged runs are never checked. - After the study's first run pins may only tighten: higher fees (every rate of the new profile at least the old one's) or higher slippage (for no symbol lower). Anything else, including a changed
initial_equityorleverageor removing a pin, isstudy_settings_loosened(409): keep them, or start a new study. Before the first run they change freely; a field not pinned yet can always be added. - A bad value is
422 invalid_requestwithfield: "pinned.<name>".
The holdout vault
search discounts luck; a holdout removes it: data you declare before tuning and score once, at the end. OptAlgo enforces it per study.
- Declare it before tuning:
POST /v1/studies/{tag}/holdout(scopebacktest) with{"last_months": 6}(the last 1 to 60 months up toend, default today 00:00 UTC) or{"start": "2025-10-01", "end": "2026-10-01"}. At least 7 days, ending at most 366 days ahead. It must start on or after the latest data any run of the study already used. - Tune before it. While the holdout is unused, every run tagged with the study whose window overlaps it (backtest, research, robustness, or the tag added later with
PATCH) is refusedholdout_locked(409) withsuggestion: {"window.end": "<holdout start>"};validatereports it as a finding. Untagged runs are not refused. - One final test:
POST /v1/studies/{tag}/final-test{"backtest_id": "<the chosen done backtest of the study>"}→202 {data: {tag, final_test: {backtest_id, source_backtest_id, status, …}, holdout, units, findings}, next}: that backtest's exact spec and code run once on the holdout window, as a new backtest charged by run time. Pollfinal_test.backtest_id. - Read it:
GET /v1/studies/{tag}/holdout(scoperead; also theholdoutofGET /v1/studies/{tag}).
The block: {tag, holdout: {window, locked_at, status, final_test}, in_sample_vs_holdout, history, data_seen: {latest_end, runs, code_versions}, findings, rule}. status goes locked (declared, unused) → testing (the final test runs) → done; rule says what is allowed now. in_sample_vs_holdout {in_sample, holdout, sharpe_kept, verdict, message} puts the chosen backtest next to its holdout run; verdict:
verdict | Meaning |
|---|---|
holds | The holdout makes money and keeps at least half of the in-sample Sharpe (sharpe_kept ≥ 0.5). The study records passed |
degraded | It makes money, with less than half the in-sample Sharpe. Recorded failed |
failed | It lost money on data it never saw: the in-sample result does not hold. Recorded failed |
pending, error, not_run | Still running; the final test failed (read that backtest); no final test yet |
Report it as the strategy's out-of-sample result, next to the grade. findings never block: holdout_seen_elsewhere (warning: the same code already ran on that window outside the study, under another tag or untagged, so treat the final test as in-sample) and holdout_window_used_by_other_code (info: other code of yours on the same symbols covered it).
Next: once done, the holdout is spent and counts as data seen. To test a changed strategy again, declare a new holdout on later data (on or after data_seen.latest_end; the old one moves to history), or start a new study. A second final test on the same holdout is holdout_used: that would be tuning on it. Other refusals: holdout_declared, holdout_seen, no_holdout, not_in_study, final_test_needs_backtest, not_ready.
Robustness check
Does a good backtest survive small changes? POST /v1/backtests/{id}/robustness (tool robustness; scope backtest, or bots / trade) runs the done backtest's own code and spec under four pressures and answers one verdict. Do it before deploying.
- Estimate first, free: body
{"dry_run": true}→200 {data: {ok, estimate: {evaluations, run_s, …}, cost: {units, run_s, seconds_per_unit}, quota, within_wall, wall_s}}.okisfalsewhen it would exceed the plan's time per run or the quota left.{"seed": n}fixes the bootstrap and the jitter (the same seed gives the same result). - Run: without
dry_run→202with a new row of kindrobustness(robustness_of= the backtest, which then showsrobustness_id), charged by run time like any run: up to about 22 evaluations of the strategy (base, fees, slippage, 2 per jittered parameter, 4 joint variants, 3 later starts). It inherits the backtest's tags, so it belongs to its study (and is refused over a locked holdout). Poll itsid.
| Check | What it does | pass, warn, else fail |
|---|---|---|
bootstrap | The run's trades resampled 1,000 times: p_loss, p_ruin, return_p05 / return_p50, max_drawdown_p05 | pass: p_loss ≤ 0.10; warn: ≤ 0.35. Fewer than 10 trades: inconclusive |
costs | Fees ×2, then taker slippage ×2 (at least 0.0005; the rate used is reported) | pass: both keep ≥ 50 % of the base return; warn: less; fail: either loses money |
params | Each numeric parameter (up to 6) moved ±10 % (integers by at least 1), plus 4 joint moves of all of them | pass: ≥ 90 % of the variants make money and their median keeps ≥ 60 % of the base Sharpe; warn: ≥ 2/3 make money. A variant the strategy refuses is listed invalid |
start_shift | The window started 5, 10 and 15 % later, same end | pass: all make money and keep ≥ 50 % of the base Sharpe; warn: ≥ 2/3 make money. A window too short to shift: skipped |
Verdict: broken when the base run does not make money, the bootstrap loses in more than 50 % of paths, or two checks fail; fragile when one check fails or two warn (or are inconclusive); robust otherwise. reasons gives the deciding sentence first, then every check that did not pass, each with its why.
Read it: GET /v1/backtests/{robustness id}: summary {verdict, reasons, checks: {bootstrap: "pass", …}, robustness_of, units_charged, run_seconds}, then result, the full report {verdict, reasons, base, checks, evaluations, seed, window, note}. Its numbers come from the research harness (flat at the start, closed at the end): compare the variants with base, not with the backtest's own result. Say the verdict and its first reason. robust is still in-sample: score the run once on its study's holdout before trusting it (next names the final test of the run's own study, its study: tag first; a run in no study gets a tag_study step instead). fragile: read the failing check's why and the diagnostics; change the idea, do not tune until it passes. broken: do not deploy.
Refused: not_ready (409) until the backtest is done; robustness_needs_backtest (422) for a research or robustness row; engine_refused (422, before anything is queued) for a basket (several symbols without legs: backtest the one symbol you care about, then check that run), and execution.early_decision_s. Never put robustness in a spec yourself: POST /v1/backtests refuses it (invalid_request, field spec.robustness).
2.5 Reading the result
Show the equity chart first (strategy vs buy-and-hold, compounded; Charts and data): in a chat, the image run_backtest / backtest_result attach, or their series drawn as a line chart; with a shell, download_data and the snippet. Then read and say the rest in this order.
GET /v1/backtests/{id} adds units_estimated, units_charged, run_seconds, position, eta_s, poll and poll_after_s to the row. When the run is done, summary comes first: {grade, total_return, max_drawdown, trades, verdict, units_charged, run_seconds, findings, search, diagnosis} (the top honesty findings, grouped across a basket's symbols; the compact search block; the diagnosis without its evidence). Read it before the full result. verdict is a research job's out-of-sample verdict (robust, inconclusive, likely_overfit); a plain backtest has none (null): its search verdict is search.verdict.
-
The grade (
Abest toD) and its findings.A: every fill resolved on real data with fees, funding and exchange rules.B: a few assumption-dependent fills.C: decisions depend on where the data starts (warmup_short,warmup_unstable: raisewarmup_bars()), many pessimistic ties, or missing coverage.D: not realistic. Two findings about SPOT legs:spot_short_refused(B: short entries on a SPOT symbol were not filled;params.legscounts them per leg) andmixed_wallet_overcommit(C, D above 1.5x: at current prices one wallet could not hold the SPOT coins and the perpetual's margin). A multi-leg ortargetrun addsresult.portfolio(per-leg PnL, exposure, margin use, a cross-margin liquidation check) and its findings,liquidation_risk(D) first (Portfolios). Say the grade and its findings before any number. -
The search (a done plain backtest): how many variants of this strategy you ran on overlapping data in the last 30 days, and whether this run's Sharpe survives the luck of that many tries. Say its
verdictwith the grade; whenfixis set, do what it says (Avoid overfitting)."search": {"variants_tried": 35, "window_reused": true, "variants_on_this_window": 33,
"sharpe": 1.21, "best_sharpe": 1.34, "expected_max_sharpe_by_luck": 1.12,
"deflated_sharpe_prob": 0.71, "verdict": "caution",
"fix": "You tried 35 variants of this strategy on the same data window (…). Either run ONE research job … or hold out the last 16 months …",
"research": {"protocol": "walk_forward", "space": {"rsi_len": {"low": 14, "high": 2000}, "band": {"low": 0.0, "high": 2.0}},
"n_trials": 30, "objective": "sharpe", "plan": {"plan": "rolling", "train_days": 365, "test_days": 180}},
"holdout": {"months": 16, "tune_window": {"start": "2020-01-01", "end": "2025-06-08"},
"test_window": {"start": "2025-06-08", "end": "2026-10-08"}},
"validated_by": null,
"family": {"source_sha256": ["28a60db74e87", "…"], "linked": ["…"], "rule": "…", "lookback_days": 30},
"observations": 2472, "sharpes_known": 35, "assumptions": "normal returns assumed …"}- Family: counted per account (every key and the app together), over the last 30 days, on windows overlapping this run's: runs of the same code (
source_sha256; the same code with other params is the same strategy), plus edited code that shares a parameter name, plus the same code with other numbers written into it (source_shape: the code with numbers, comments and blank lines taken out; a sweep's best parameters hard-coded are still that sweep), always on a shared symbol and the same timeframe. A different idea (different code) is not counted, however close in time. Runs from before 2026-10-12 have no shape and are matched by working session instead (earlier runs less than 1 h apart, within 4 h).family.counted= {same_code,shared_params,same_shape,session} says why each variant is in the count. The same spec twice counts once; a run on a window none of the variants touched starts fresh. - Sharpes are annualised (
result.metrics.sharpe_daily_annualised).expected_max_sharpe_by_luckis what the best ofvariants_triedworthless variants would reach (Bailey & López de Prado), from how much the variants' Sharpes differ;deflated_sharpe_probis the probability that this run's true Sharpe beats that luck. verdict:no_edge(this run lost money: annualised Sharpe ≤ 0 ortotal_returnbelow 0, whatever the number of variants; checked first),ok(one run, or the deflated Sharpe probability is at least 0.95),caution(below 0.95),likely_overfit(below 0.5).fix,researchandholdoutare set when the verdict iscautionorlikely_overfit, or when 10 or more variants ran on this exact window. Forno_edgeonlyfixis set: change the strategy itself, then backtest again.validated_by:{id, protocol, verdict, symbols, runs}when out-of-sample research validates this run, elsenull. It counts only research runs that aredoneand: of this exact code (the samesource_sha256, not the family), with a protocol that tests on unseen data (walk_forward,nested_walk_forward,multi_config,purged_cv,cpcv,masters4), with verdictrobust(inconclusiveis not a pass), on a window overlapping this run's; and together they must cover every symbol of this run (one research run on the whole basket covers all its symbols; single-symbol research runs add up too). It lifts alikely_overfitdeploy block, never ano_edgeone.- When
researchis set,nextstarts withvalidate_research(POST /v1/backtests/validatewith the same spec plusresearch). Never forno_edge.
- Family: counted per account (every key and the app together), over the last 30 days, on windows overlapping this run's: runs of the same code (
-
The diagnosis (
summary.diagnosis,result.diagnostics): why the run wins or loses, rules that fired on its own numbers with evidence and asuggestion,highfirst. In-sample hints, not proof: act on one suggestion, validate, confirm out of sample (Diagnostics). -
result.metrics:total_returnandmax_drawdownare fractions (0.25 = +25 %), pluscagr,sharpe_daily_annualised,sortino_daily_annualised,win_rate,profit_factor,trades,fees_total,funding_total,exposure,return_by_year,top5_share_of_profit(above 1: the other trades lost money, fragile).Judge it net of fees.
total_returnalready pays fees and funding; sayfees_totalnext to it. Fees kill short timeframes: a"15"(15m) strategy that trades several times a day pays the fee on every entry and exit, and an edge that is gone oncefees_totalis paid is no edge. Fewer, larger moves (a longer timeframe, stricter entries) usually beat more trades. -
A single backtest is in-sample. Say so. Before calling an edge real, run a
walk_forwardresearch job and show its out-of-sample folds (resultis then the research report with averdict). Tell the user its estimated cost first. -
Charts and files: show the user a chart (Charts and data: views, a PNG drawn by OptAlgo, full-resolution CSV files and download links).
GET /v1/backtests/{id}/chart?points=1500(equity, drawdown, trades), orGET /v1/backtests/{id}/files/{name}withnamefrom the row'sfiles(equity.arrow,trades.arrow,fills.arrow,result.json,spec.json). Before the run is done:not_ready. Your own code back:GET /v1/backtests/{id}/source(read) answers the run'sstrategy.pyas a file named<name>-<sha8>.py, its sha256 inX-Source-SHA256(404 no_sourcewhen the run had no code of yours). -
A
failedrun carrieserrorand afix: {code, fix, docs}(codes in Failed runs). -
validate_gap{kind, class[, run_s, estimate_s]}: you validated this exact spec and code (ok) in the last 24 hours, yet the run failed on something validation should have caught (kind: "run_failed",classe.g.KeyError,spec_invalid,instrument,data_coverage) or was stopped at a cap far above its estimate (kind: "estimate", more than 3× and over 60 s). That is OptAlgo's bug, not yours:nextstarts with a prefilledreport_issue; send it (add the spec, never the code) and tell the user the ticket id. OptAlgo files its own report too.
Compare runs with GET /v1/backtests?limit=50&skip=0&status=done (newest first; each row has id, kind, status, created_at, name, strategy, params, symbols, timeframe, window, grade, total_return, max_drawdown, trades, sharpe, verdict, units_estimated, units_charged, run_seconds, via, favorite, note, tags, files_state, files_pruned_at, rerun_of, rerun_id). Comparing many runs of one idea is exactly the search that search accounts for: pick with a research run, not by eye.
Organise: the best runs, notes, tags, favourites
The best first. GET /v1/backtests?sort= (tool backtests(sort=...)): recent (default, newest first) | sharpe | return | grade (A first) | drawdown (least deep first) | trades. A metric sort lists only the rows that have that metric (finished runs). Filters, combinable: status, kind (backtest | research | robustness), via (app | api_key), favorites=true (or favorite=true), grade_min (A..D: that grade or better), symbol (a symbol the run traded, BTCUSDT.P; an EXCHANGE: prefix is ignored), tag, q (text in the name or the note, at most 64 characters), stale=true (runs an older engine made: see Rerun). total counts what the filters match. A bad value is invalid_request naming the field. Example, the three best-graded runs with a Sharpe: GET /v1/backtests?sort=sharpe&grade_min=B&limit=3. The best of many single runs still looks good by luck: read its search verdict.
Annotate. PATCH /v1/backtests/{id} (tool annotate_backtest; key scope backtest, or bots / trade; your own backtest only, anyone else's is not_found) with any of:
| field | rule |
|---|---|
note | at most 280 characters, plain text on one line (control characters dropped, whitespace collapsed, infrastructure details scrubbed); "" or null clears it |
tags | at most 5 (lower-cased, duplicates dropped), each a word of 1 to 24 characters of a-z, 0-9, _, - with one optional namespace: study:momentum (^[a-z0-9_-]{1,24}(:[a-z0-9_-]{1,24})?$). study:<name> puts the run in a study. Replaces the list; [] or null clears it |
favorite | true / false: the same star as in the app (one flag for the app, keys and chats) |
Only the fields sent change; the answer is the row.
Groups. A group is a tag: put the runs of one line of work in it (PATCH the runs' tags; connector: annotate_backtest), and the user sees them as one folder in the app's backtest list. GET /v1/backtests/groups (connector: backtests(groups=true)) lists the groups, newest activity first: tag, runs, last_at, best (the done backtest with the highest Sharpe: id, name, grade, sharpe), plus untagged. Read one group with GET /v1/backtests?tag=<tag> (runs in no group: ?untagged=true); a study:<name> group also has its search verdict at GET /v1/studies/{tag}. Before starting something new, list the groups to see what was already tried. A run can be in up to 5 groups.
Tags on a spec you already ran. Submitting the exact spec and code of a run you already have (made by the current engine) is free and answers that run. Its tags are added to the run's own; when together they are more than 5, the run keeps the tags it has and takes only the new ones that fit, and the answer says what was left out: tags (the run's list now), tags_dropped (the list) and warning {code: "tags_dropped", message, fix}. The connector's run_backtest passes both through. Tell the user, then PATCH the run's tags to the ones you want, or change the spec to start a new run.
When you start a line of research, write its purpose or hypothesis as the note ("hypothesis: RSI 30/70 mean reversion on BTC 1h") and tag its runs; favourite every run worth keeping (the one you deploy, the baseline you compare against). backtests(tag=..., favorites=true) finds them again.
Retention: what is kept
OptAlgo keeps every backtest row, but not every run's files. Each account keeps the result files (charts, trades, fills, candles, CSV exports) of its newest finished backtests: 20 on Free, 100 on Plus, 500 on Pro (limits.max_kept_backtests). Older runs lose those files when they are all of: not a favourite, older than 7 days, not used by a hosted strategy (deployed from it or a compare of it), and a finished plain backtest (research runs keep theirs). Favourites count toward that number but are never pruned.
What a pruned run keeps: its row, metrics, grade, honesty findings, the search verdict, the diagnosis (GET .../diagnostics), its code (GET .../source) and spec, note, tags and favourite. Its row says files_state: "pruned" (tool backtests: files: pruned) and files_pruned_at; a kept run says kept; a run not finished, null. Charts, chart.png, candles, trades.csv, CSV exports, download links and the arrow files of a pruned run answer pruned (410) with next = rerun.
Rerun. POST /v1/backtests/{id}/rerun (tool rerun_backtest; scope backtest) submits the run's own spec and code again as a new backtest: the same checks and quota units as POST /v1/backtests, the same 202 answer plus rerun_of (the old row then shows rerun_id). Poll the new id; its charts work once it is done. A run that still keeps its files answers not_pruned (409): read it directly.
A run's identity is its spec, its code and the engine version. Every row carries engine_api (null: made before versions were recorded, counted as 0). An engine fix that changes results raises it, and the identical spec submitted again (POST /v1/backtests) then runs on the new engine as a new run, charged normally; the old run keeps its result. GET /v1/backtests?stale=true lists the runs an older engine made. Rerun stays for pruned runs.
2.6 Plans, limits and quota
| Free | Plus | Pro | |
|---|---|---|---|
| Backtest units (1 unit = up to 10 s of run time) | 50 per month | 30 per day | 200 per day |
| Resets | at quota.resets_at | 00:00 UTC | 00:00 UTC |
| Symbols per run (legs of one strategy, too) | 3 | 3 | 16 |
| History per run (1-minute bars per symbol) | 300,000 (about 7 months) | 550,000 (about 1 year) | 3,200,000 (about 6 years) |
| Trials per optimisation | 40 | 100 | 500 |
| Runs at once | 1 | 1 | 2 |
| Time per run | 60 s | 90 s | 300 s |
| Memory per run | 1.5 GB | 2 GB | 4 GB |
| Backtests whose result files are kept (retention) | 20 | 100 | 500 |
Units are run time. A run costs max(1, ceil(run_seconds / 10)) units: up to 10 s is 1 unit, a 1-minute run is 6; an optimisation is charged the same way on its total run time. At submit the engine's estimate is reserved (the submit is refused when it is more than you have left); when the run ends it is settled to the measured run_seconds (units_charged). A run that hits its plan's time or memory cap, or is stopped by the sandbox, is your run and is charged. A run that fails on our side costs 0. Resubmitting a spec whose run failed runs it again: that new run is charged by its own run time like any run (the earlier failure's 0 does not carry over). A result that already existed (the same run, already computed) costs 1. A refused request costs nothing; validate, check, limits, markets and reads are free.
Make runs cheaper (fewer seconds, fewer units): fewer symbols; a shorter window; a coarser timeframe ("60" instead of "15"); indicators and prims from the SDK instead of Python loops; fewer research trials. validate shows the new estimate before you spend anything.
GET /v1/backtests/limits (an endpoint from before the envelope: its fields stay at the top level, next is added beside them):
{"plan": "Free", "enabled": true, "active_jobs": 0,
"limits": {"cpu_s": 60, "wall_s": 60, "mem_mb": 1536, "max_symbols": 3, "max_bars": 300000,
"max_trials": 40, "max_concurrent": 1, "user_code": true},
"quota": {"period": "month", "units": 50, "used": 12, "remaining": 38, "resets_at": "…", "seconds_per_unit": 10},
"strike_count": {"used": 0, "max": 3},
"next": [{"action": "list_markets", "method": "GET", "path": "/v1/markets", "why": "…"}]}
strike_count is how many security strikes the account has (used) of how many suspend its API access (max); GET /v1/me has it too. An account exempted from strikes reads {"used": 0, "max": null, "exempt": true}.
period is month (Free) or day (Plus, Pro); a daily quota also keeps the older keys units_per_day, used_today, remaining_today. When a monthly quota resets: read quota.resets_at. Headers X-Quota-Remaining and X-Quota-Resets-At come with limits, validate, submit, list and get.
Over the quota, POST /v1/backtests answers 429 daily_quota (Plus, Pro) or monthly_quota (Free), with Retry-After:
{"error": "monthly_quota", "message": "Monthly backtest quota reached: 48 of 50 units used this month, this run needs about 3 …",
"detail": "…", "fix": "Monthly quota used (48 of 50 units; this run costs 3). It resets at …. Until then validate for free and read results; …",
"limit": "max_units_per_month", "value": 51, "allowed": 50, "used": 48, "remaining": 2, "cost": 3, "period": "month",
"resets_at": "…", "docs": "https://docs.optalgo.com/ai-agents/optalgo-llm#monthly_quota",
"next": [{"action": "read_limits", "method": "GET", "path": "/v1/backtests/limits", "why": "quota left and when it resets"}, {"action": "validate", "…": "…"}]}
cost is this run's estimate. Stop submitting. No retry, no loop. Tell the user used, remaining and resets_at; suggest a cheaper run if remaining allows it, or the next plan. validate and reads still work.
2.7 Ready-made helpers
Reading any answer: the payload is body.data when the body has data, otherwise the body without next.
curl (with jq, strategy.py in the current directory, the credentials loaded as in section 0):
H="X-API-Key: $OPTALGO_API_KEY"; B="$OPTALGO_API_BASE/backtests"
d() { jq 'if has("data") then .data else del(.next) end'; } # the payload, envelope or not
curl -sS "$B/limits" -H "$H" | d | jq '{plan, limits, quota}'
curl -sS "$OPTALGO_API_BASE/markets?exchange=BINANCE&type=FUTURES" -H "$H" | d | jq '[.symbols[] | {symbol, data_start, backtest}]'
SPEC='{market: [{exchange: "BINANCE", symbol: "BTCUSDT.P"}], timeframe: "60",
window: {start: "2024-01-01", end: "2025-01-01"}, strategy: {params: {fast: 20, slow: 80}}}'
jq -Rs "{source: ., spec: $SPEC}" strategy.py | curl -sS -X POST "$B/validate" -H "$H" -H 'Content-Type: application/json' -d @- | d | jq '{ok, findings, cost}'
jq -Rs "{source: ., spec: $SPEC}" strategy.py | curl -sS -X POST "$B" -H "$H" -H 'Content-Type: application/json' -d @- | d # {id, status, position, eta_s, ...}
curl -sS "$B/<id>" -H "$H" | d | jq '{status, position, eta_s, summary}'
Python (standard library only). Save as optalgo_bt.py; run python3 optalgo_bt.py strategy.py BTCUSDT.P 60 2024-01-01 2025-01-01 fast=20 slow=80. It validates, submits, polls (telling you the queue position) and prints the summary and metrics; it exits non-zero with the fix on any refusal, and stops on a quota.
"""Backtest strategy.py on OptAlgo: validate -> submit -> poll -> print. Never prints the key."""
import json, os, sys, time, urllib.error, urllib.request
from pathlib import Path
def creds(path=Path.home() / ".config" / "optalgo" / "credentials.env"):
vals = dict(l.split("=", 1) for l in path.read_text().splitlines() if "=" in l) if path.exists() else {}
key = os.environ.get("OPTALGO_API_KEY") or vals.get("OPTALGO_API_KEY", "").strip()
base = os.environ.get("OPTALGO_API_BASE") or vals.get("OPTALGO_API_BASE", "https://api.optalgo.com/v1").strip()
return key or sys.exit("Not connected: run the OptAlgo agent login (section 0)."), base.rstrip("/")
KEY, BASE = creds()
def payload(body):
"""body.data when present, else the body without next."""
if isinstance(body, dict):
return body["data"] if "data" in body else {k: v for k, v in body.items() if k != "next"}
return body
def call(method, path, body=None):
req = urllib.request.Request(BASE + path, method=method, data=None if body is None else json.dumps(body).encode(),
headers={"X-API-Key": KEY, "Content-Type": "application/json", "User-Agent": "optalgo-bt/1.0"})
while True:
try:
with urllib.request.urlopen(req, timeout=60) as r:
return payload(json.load(r))
except urllib.error.HTTPError as e:
err = json.loads(e.read() or b"{}")
if err.get("error") == "rate_limited":
time.sleep(int(e.headers.get("Retry-After") or 5)); continue
if err.get("error") in ("daily_quota", "monthly_quota"): # stop: never retry before resets_at
sys.exit(f"Backtest quota reached: {err.get('used')} used, {err.get('remaining')} left, "
f"this run needs {err.get('cost')}. Resets at {err.get('resets_at')}.")
sys.exit(f"{e.code} {err.get('error')}: {err.get('message') or err.get('detail')}\nfix: {err.get('fix') or '-'}\ndocs: {err.get('docs') or '-'}")
def main(path, symbol, timeframe, start, end, *params):
source = open(path).read()
spec = {"market": [{"exchange": "BINANCE", "symbol": symbol}], "timeframe": timeframe,
"window": {"start": start, "end": end},
"strategy": {"params": {k: json.loads(v) for k, v in (p.split("=", 1) for p in params)}}}
checked = call("POST", "/backtests/validate", {"spec": spec, "source": source})
for f in checked.get("findings") or []:
where = f"{path}:{f['line']}" if f.get("line") else f.get("field") or "spec"
print(f"[{f.get('severity')}] {where}: {f.get('code')} {f.get('rule') or ''}: {f.get('message')} fix: {f.get('fix', '-')}")
if not checked.get("ok"):
sys.exit(1)
print("estimated units", (checked.get("cost") or {}).get("units"))
run = call("POST", "/backtests", {"spec": spec, "source": source})
while (row := call("GET", f"/backtests/{run['id']}"))["status"] in ("queued", "running"):
if row["status"] == "queued" and row.get("position"):
print(f"queued: #{row['position']}, starts in about {row.get('eta_s', '?')} s", flush=True)
time.sleep(row.get("poll_after_s") or 5)
if row["status"] != "done":
fix = row.get("fix") or {}
sys.exit(f"failed ({fix.get('code')}): {row.get('error')}\nfix: {fix.get('fix')}")
summary, metrics = row.get("summary") or {}, (row.get("result") or {}).get("metrics") or {}
print("grade", summary.get("grade"), "units charged", summary.get("units_charged"), "run seconds", summary.get("run_seconds"))
for f in summary.get("findings") or []:
print(f" {f.get('code')}: {f.get('message')}")
for k in ("total_return", "max_drawdown", "cagr", "sharpe_daily_annualised", "win_rate", "profit_factor",
"trades", "fees_total", "top5_share_of_profit"):
print(f"{k:24} {metrics.get(k)}")
if __name__ == "__main__":
main(*sys.argv[1:])
2.8 Charts and data: views, images, CSV files
Show the user the result, don't only describe it. The user only sees what you show. After every finished backtest, ALWAYS show the equity chart first: the strategy against buy-and-hold of its symbols (equal weight for a basket or several legs), both compounded from the same initial equity, with the drawdown under it. Then the grade and the numbers.
- The connector does it by default:
run_backtest(once done) andbacktest_resultattach the PNG (about 800 × 450) and a miniseries:{"columns": ["t", "equity", "buy_hold"], "rows": [...]}, about 24 points (detail="normal": 60,"full": 200; peaks and troughs kept), about 1 KB.image=falseleaves the PNG out. - A chat that cannot show images: draw
seriesas a line chart (an artifact, or the chat's own chart), two lines: strategy and buy & hold. For more points:backtest_chart(id, detail="normal"). - An agent with a shell:
download_data(id)and the snippet below (it plots the equity file'sbuy_holdcolumn).
By what you can run:
| You are | Use | You get |
|---|---|---|
| A chat with the OptAlgo connector (Claude.ai, ChatGPT: no shell) | backtest_chart(id, view), candles(id, image=true) | A PNG drawn by OptAlgo (show it as is) plus compact JSON with a plot hint, to build an interactive chart from when the user asks |
| A chat without network access (claude.ai) | GET /v1/backtests/{id}/daily (connector: backtests(id, file="equity_daily")); backtests(id, file="trades.csv", skip, limit) | The run by UTC day inline {cols, rows}: date, equity (the day's last bar), return, drawdown, pnl:<symbol> (realised net PnL of trades closed that day); every trade in pages of at most 60k characters, follow next_skip |
| An agent with a shell (Claude Code, Codex) | download_data(id, files) (connector) or POST /v1/backtests/{id}/download-links | Full-resolution CSV files behind 10-minute links that need no header, to plot locally |
| Any API client | GET /v1/backtests/{id}/chart, /chart.png, /files/{name}.csv | The same data with your key |
Shared shape. Every table is columnar, {"columns": [...], "rows": [[...], ...]}. Times are epoch seconds (int). Numbers are rounded: prices and money 6 significant digits, equity 2 decimals, ratios (returns, drawdown, exposure) 4 decimals (the CSV files are exact). Every answer carries plot, a hint for drawing it right the first time. Every list that is cut says so: <name>_total, <name>_shown and a note.
"plot": {"type": "line", "x": "t", "y": ["equity"], "y2": ["drawdown"], "y2_format": "percent", "log_y": false,
"markers": "trades", "title": "ema cross · BTCUSDT.P · 2024-01-01..2025-01-01"}
title starts with the backtest's name (the run's id when it has none), then its symbols and window. type is line, area, bar, candlestick, histogram or heatmap. x / y name columns of the table; y2 goes on a second axis (drawdown under the equity, in percent); markers: "trades" = mark each trade's entry and exit from the trades table; a heatmap has z (the value) and z_format; a histogram has stack (wins, losses).
Chart views GET /v1/backtests/{id}/chart (read), all parameters optional; without any it answers what it always did (view=equity, 1500 points):
| Parameter | Meaning |
|---|---|
view | equity (default) | trades | monthly | pnl_hist | exposure |
points | equity / exposure: at most this many points (16 to 5000, default 1500). Downsampled per bucket with the peaks, troughs and the deepest drawdown kept, the first and last point exact |
from, to | Epoch seconds: a window inside the run's window |
symbol | A basket's symbol: that symbol's own curve or trades |
per_symbol | true on a basket's equity view: also per_symbol_curves, each symbol's equity on the same timestamps (null + per_symbol_curves_note when the run kept none; never estimated) |
max_trades, offset | trades view: rows per page (at most 2000) and the first row; next_offset and next give the next page |
| View | Table(s) | Plot |
|---|---|---|
equity | equity as column lists {t: [...], equity: [...], drawdown: [...], buy_hold: [...]} (buy_hold: the equal-weight buy-and-hold of the run's symbols, or of symbol, compounded from the same initial equity: bought at the first close of the window, no fee, so its last point / initial_equity − 1 is the diagnostics benchmark total_return; absent when the run's bars are not kept), the most recent trades in exit-time order as objects {symbol, side, entry_time, exit_time, entry_px, exit_px, qty, net_pnl, fees, funding, reason} with trades_total, summary (bars, final_equity, max_drawdown, max_drawdown_at) | line (y: equity, buy_hold), drawdown on y2 |
trades | trades: symbol, side, entry_time, exit_time, entry_px, exit_px, qty, net_pnl, return, fees, bars_held, reason, by exit time, paged; summary of every matching trade (count, win rate, average win / loss) | bar |
monthly | monthly [year, month, return] and yearly [year, return]; summary (best and worst month) | heatmap |
pnl_hist | bins [bin_start, bin_end, count, wins, losses] of the trades' return (Freedman-Diaconis, 10 to 60 bins), stats | histogram |
exposure | exposure [t, positions, gross, net]: open positions and their gross / net entry notional as a fraction of equity at each bar | area |
return = net_pnl / (entry_px * qty): net of fees and funding, on the entry notional (leverage does not change it). side is 1 long, -1 short.
{"view": "equity", "symbols": ["BINANCE/BTCUSDT.P"], "window": {"start": 1704067200, "end": 1735689600},
"plot": {"type": "line", "x": "t", "y": ["equity", "buy_hold"], "y2": ["drawdown"], "y2_format": "percent", "…": "…"},
"summary": {"bars": 8784, "final_equity": 11873.4, "max_drawdown": -0.0912, "max_drawdown_at": 1717200000},
"equity": {"t": [1704067200, 1704085200, "…"], "equity": [10000.0, 10012.5, "…"], "drawdown": [0.0, 0.0, "…"],
"buy_hold": [10000.0, 10031.2, "…"]},
"trades": [{"symbol": "BINANCE/BTCUSDT.P", "side": 1, "entry_time": 1704200400, "exit_time": 1704470400,
"entry_px": 44210.1, "exit_px": 45102.5, "qty": 0.0226, "net_pnl": 19.42, "fees": 0.81, "reason": "signal"}, "…"],
"trades_total": 64, "trades_shown": 64,
"next": [{"action": "read_chart_image", "method": "GET", "path": "/v1/backtests/<id>/chart.png?view=equity", "why": "…"}, "…"]}
The image GET /v1/backtests/{id}/chart.png (read): the chart drawn by OptAlgo, image/png, about 1200 x 700 px (size=full, the default) or about 800 x 450 (size=small: enough for a chat, less to send), at most 200 KB, one light theme, titled with the backtest's name (the run's id when it has none), its symbols and window; equity draws the strategy against buy-and-hold (both from the same initial equity, the buy-and-hold return in the subtitle) with the drawdown under it. view is equity (default), monthly, pnl_hist or candles (one symbol's price with the trades marked: symbol, from, to), with the same parameters as the JSON. Cached 5 minutes. There is no image of the trades or exposure view: draw those from the JSON.
Candles GET /v1/backtests/{id}/candles?symbol=&from=&to=&max_points= ("why did it enter here"): the bars in a window, the strategy's plot series on the same bars with plots_meta ({"ema": {"pane": "price"}, "rsi": {"pane": "separate"}}: draw price series over the candles, separate ones in their own pane), the fills (t, side, px, qty, purpose, reason, net_pnl (on exits), with fills_total / fills_shown) and the trades in range (id, side, entry_time, entry_px, exit_time, exit_px, qty, net_pnl, gross_pnl, fees, funding, reason, with trades_in_range / trades_shown), both columnar. A cut list says so in note: zoom in with from / to.
CSV files GET /v1/backtests/{id}/files/{name}.csv (read): the full-resolution data with a header row, streamed as an attachment. Times are epoch seconds, numbers exact, an empty cell is no value. 404 when the run kept no such data (a run with outputs.verbosity: summary has no equity curve).
name | Columns |
|---|---|
equity | t, equity, drawdown, buy_hold (every bar of the window; ?symbol=: a basket symbol's own curve; buy_hold as in the chart view, absent when the run's bars are not kept) |
trades | symbol, side, entry_time, exit_time, entry_px, exit_px, qty, net_pnl, return, fees, bars_held, reason, by exit time |
fills | t, symbol, side, purpose, px, qty, fee, maker, reason, lot_id |
plots | t + one column per plot series of one symbol (?symbol=, default the first) |
bars | t, o, h, l, c, v: the run's own bars of one symbol (?symbol=) |
Download links for tools that cannot send a header (pandas, a notebook, curl -o): POST /v1/backtests/{id}/download-links with {"files": ["equity", "trades"], "symbol": "BTCUSDT.P"} (symbol optional) answers {data: {links: [{file, url, expires_at}], expires_in_s}, next}. Each url (https://api.optalgo.com/v1/dl/<token>) serves exactly that file of that backtest, to anyone holding it, for 10 minutes: download it now, never paste it anywhere else, and ask again when it expired. A bad, tampered or expired link answers 404; links are rate limited.
Plot locally (Claude Code, Codex: pip install pandas matplotlib):
import pandas as pd, matplotlib.pyplot as plt
EQ, TR = "<equity url>", "<trades url>" # from download-links (or download_data in a chat)
eq = pd.read_csv(EQ); eq["time"] = pd.to_datetime(eq["t"], unit="s")
tr = pd.read_csv(TR); x = pd.to_datetime(tr["exit_time"], unit="s")
fig, (a1, a2) = plt.subplots(2, 1, sharex=True, figsize=(12, 7), height_ratios=[3, 1])
a1.plot(eq["time"], eq["equity"], label="strategy"); a1.set_ylabel("equity"); a1.set_title("Backtest")
if "buy_hold" in eq: a1.plot(eq["time"], eq["buy_hold"], color="gray", label="buy & hold")
a1.legend()
a1.scatter(x, eq.set_index("time")["equity"].asof(x), s=14, zorder=3,
c=["tab:green" if p > 0 else "tab:red" for p in tr["net_pnl"]])
a2.fill_between(eq["time"], eq["drawdown"] * 100, 0, color="tab:red", alpha=0.4); a2.set_ylabel("drawdown %")
fig.tight_layout(); fig.savefig("backtest.png", dpi=120)
With a key instead of links: curl -sS -H "X-API-Key: $OPTALGO_API_KEY" -o equity.csv "$OPTALGO_API_BASE/backtests/<id>/files/equity.csv".
In a chat (the connector): backtest_chart(id, view="equity", points=200, start, end, symbol, per_symbol, image=true, offset) answers the same data, every table columnar (the equity curve as {"columns": ["t", "equity", "drawdown", "buy_hold"], "rows": [...]}, the trades with their prices and PnL), at most about 30 KB (a longer table is thinned and the note says so), and the PNG as an image: show the image first, then offer the other views or an interactive chart built from plot + the tables. view="trades" pages with offset (100 rows a page). candles(id, start, end, image=true) adds the candlestick image. download_data(id, files, symbol) gives the links above with a ready snippet; it is for agents with a shell, a chat app cannot open them.
2.9 Why a backtest wins or loses (diagnostics)
A grade and a Sharpe say how much a run made and how far to trust it, never why. Every finished backtest also carries diagnostics: rules that fire on the run's own numbers ("four trades made all the profit", "the shorts lost in four of six years", "funding cost four times the fees"), each with its evidence and what to try next, plus the breakdowns behind them. OptAlgo computes it once, when the run finishes (a run from before diagnostics existed, or diagnosed by an older version of the rules, gets it on its first read); reading it costs nothing.
Where it is. result.diagnostics in GET /v1/backtests/{id} (about 7 KB), and alone at GET /v1/backtests/{id}/diagnostics (read; {data, next}; ?section= one of diagnosis, breakdowns, trades, costs, drawdowns, benchmark, stability, stops, rules, hedged). The row's summary.diagnosis lists {code, severity, message, suggestion} without the evidence. When the diagnosis has a high item, next starts with read_diagnostics. 404 not_found for a run that kept no trades or equity (outputs.verbosity: "summary"), not_ready before it is done. Connector: backtest_result shows the diagnosis (the 2-3 key evidence numbers each) and four breakdown lines right after the grade and search; backtest_diagnostics(id, section) the whole block.
How to use it (in this order):
- Grade → search → diagnosis. The grade says whether the numbers are real, the search whether you tuned them on luck; only then ask why the run wins or loses.
- Tell the user the
highitems in one line each, with their evidence. They are in-sample hints, not proof: they describe this backtest on this window. - Act on one
suggestionper change (long only, a regime filter, a higher timeframe, a wider stop). Changing several things at once hides which one helped. - Validate the change and confirm it where you did not tune it: a research run (
spec.research) or a holdout window you never looked at. Each rerun counts as a variant insearch. Never hand-pick symbols or years from the breakdowns: that is fitting the past; filter on what the losers share (volatility, trend, liquidity) instead. no_red_flagsis not a pass: no rule fired on this one in-sample run.
diagnosis: at most 8 entries {code, severity, message, evidence, suggestion}, high first, then medium, then info. A rule fires only on the numbers it puts in evidence; a rule that could not be evaluated (no market bars, a window too short, one symbol) is listed in rules.skipped with the reason, never guessed.
{"code": "few_trades_dominate", "severity": "high",
"message": "The top 4 trade(s) (1%) make 101.7% of the net profit and the top 10 make 208.7%; without the top 1% the net is -12.49.",
"evidence": {"top1pct_share": 1.0168, "top1pct_trades": 4, "top10_share": 2.0871, "top5pct_share": 3.0275,
"largest_share": 0.3216, "net_without_top1pct": -12.49, "trades": 327},
"suggestion": "check those trades are not one event (one coin, one week); a robust edge survives removing its best trades"}
Every rule and when it fires:
code | Fires when | Severity |
|---|---|---|
no_trades | the strategy never traded in the window | high |
no_gross_edge | it loses before any fee, slippage or funding paid (funding received counts as income): costs.pre_cost_pnl ≤ 0 (the entries have no edge: change the idea, not the exits) | high |
costs_eat_edge | fees + slippage + funding paid take ≥ 50 % of the pre-cost profit | high when the net is ≤ 0, else medium |
worse_than_holding | both the return and the Sharpe are below an equal-weight buy-and-hold of the same symbols; a hedged run: it lost money (holding cash did better) | high when holding gained, else medium (hedged: medium) |
too_few_trades | under 30 trades; or a positive mean trade return with t-statistic under 2 (trades_for_t2 = about how many trades a t of 2 needs); a hedged run: the same on its daily returns (basis: daily_returns, days) | high (under 30) / medium |
few_trades_dominate | a winning run where the top 1 % of trades make ≥ 50 % of the net profit, or the top 10 make ≥ 80 % (with ≥ 50 trades), or the single largest ≥ 25 %; a hedged run: on its combined positions, skipped under 30 of them | high when the net without the top 1 % is ≤ 0, else medium |
edge_decays | the second half's Sharpe is under 0.5× the first half's (first half Sharpe ≥ 0.5), or the first half gained and the second lost; each half ≥ 60 days | high when the second half lost, else medium |
side_loses | one side (≥ 10 trades) loses while the other wins; years_lost of years says how consistently; skipped (hedged) on a hedged run | high when the loss is ≥ 50 % of the other side's profit, else medium |
one_symbol_carries | ≥ 3 symbols and one makes ≥ 70 % of the net profit; skipped (hedged) on a hedged run | high when the others together make ≤ 0, else medium |
symbol_drag | symbols (≥ 5 trades each) that lose ≥ 10 % of the net profit of a winning run, or any loser beside a winner in a losing run; skipped (hedged) on a hedged run | medium |
regime_dependent | ≥ 6 months, makes money in the market's up months and loses in its down months with correlation ≥ 0.5; or beta ≥ 0.7 with correlation ≥ 0.7; a hedged run also needs beta ≥ 0.1 (the hedge leaks market exposure) | medium |
overexposed | in the market ≥ 90 % of the time with beta ≥ 0.7: close to just holding | medium |
long_drawdown | the longest stretch without a new equity high is ≥ 40 % of the window (and ≥ 30 days) | high at ≥ 70 %, else medium |
exit_reason_problem | stop-loss exits are ≥ 20 and ≥ 20 % of exits, and ≥ 50 % of them saw a close back at the entry price within H bars (H = the median holding time, clamped to 5-100): the stops look too tight. Needs the market bars | medium |
no_red_flags | nothing above fired | info |
A market month is up above +5 %, down below −5 % (the benchmark's monthly return), sideways between.
Hedged runs (a cash-and-carry: spot long + perpetual short of the same coin, or any multi-leg strategy whose legs offset each other). When the open legs' net notional is at most 20 % of their gross notional over time, the run is diagnosed as one position: its legs' price PnL cancelling is the design and its edge is what the hedge earns (funding received). The block then has hedged: {net_to_gross, legs, positions}; trades counts combined positions (basis: hedged_positions, leg_trades); side_loses, one_symbol_carries and symbol_drag are skipped with reason hedged (the per-leg rows stay in breakdowns as information); benchmark is holding cash (kind: cash, return 0) with the buy-and-hold of its symbols kept as benchmark.market. Do not tell the user a carry "loses on one side" or "trails buy-and-hold": that is how it works.
The other blocks (every number rounded, lists capped):
breakdowns:by_symbol,by_side,by_year(exit year, UTC),by_exit_reason(signal,stop_loss,take_profit,time_barrier,end_of_data...),by_leg(multi-leg strategies). Rows{key, trades, net_pnl, share_of_net_pnl, win_rate, profit_factor, avg_return, avg_bars_held};share_of_net_pnl= the row's net / |total net| (negative = the row lost money; the shares sum to +1 for a winning run, −1 for a losing one);avg_return= mean net PnL / entry notional. At most 12 rows (the best and worst 6;omittedcounts the rest).trades:count,win_rate,avg_win,avg_loss(and as returns),payoff_ratio,expectancy(money andexpectancy_bpsof notional),median_bars_held,p90_bars_held,max_consecutive_losses,t_statof the mean trade return,significant(|t| ≥ 2),enough_trades(≥ 30),trades_for_t2,concentration(top1pct_share,top1pct_trades,top5pct_share,top10_share,largest_share,net_without_top1pct); a hedged run addsbasis: hedged_positionsandleg_trades.costs:gross_pnl(after slippage, as simulated),fees,funding(net, + = received, − = paid) split intofunding_received(income) andfunding_paid(a cost),slippage_estimatewithslippage_basis(fills,trades_upper_bound,not_modelledwhen slippage is 0,mapwith a slippage map: thenslippage_by_symbol{label: {slippage, taker_notional, slippage_cost}}),pre_cost_pnl= gross + slippage + funding received,total_costs= fees + slippage + funding paid (never negative),costs_share_of_pre_cost_pnl,edge_bps_per_tradevscost_bps_per_trade(of notional),turnover_per_year(notional traded / average equity).drawdowns: the 3 deepesttopepisodes{start (the peak), trough, end (recovery or null), recovered, depth, length_bars, recovery_bars, length_days},time_under_water(share of bars below a high),longest_without_new_high_bars/_days.benchmark: an equal-weight buy-and-hold of the run's symbols over the window (each 1/N slot buys at its first close and holds, no fees), on the strategy's daily closes:total_return,max_drawdown,sharpe; the strategy'sstrategy_return,strategy_sharpe,correlationandbetato it,excess_return;months.up/down/sideways{months, strategy_avg, benchmark_avg, strategy_positive}.kindsays which:equal_weight_buy_and_hold, orcashfor a hedged run (return 0; the buy-and-hold block ismarket).stability:positive_years,positive_months(shares),halves{split, first_return, second_return, first_sharpe, second_sharpe},rolling182-day returns{windows, mean, std, min, max, positive}.stops:stop_exits,share_of_exits,horizon_bars,recovered_to_entry,stop_net_pnl(null when it could not be computed).rules.skipped:{code: reason}for the rules that could not be evaluated.
Grouped honesty findings. A basket repeats each honesty finding once per symbol in result.honesty.findings (unchanged). result.honesty_findings_grouped folds them: one entry per grade + code with symbols and count; when only the numbers differ per symbol, message is the first symbol's (message_of) and per_symbol holds each symbol's params. The row's summary.findings uses the grouped form (symbols = how many symbols it concerns); a run from before the grouping existed is grouped the same way when it is read.
3. Run your strategy on OptAlgo
A hosted strategy is the user's own strategy.py, run by OptAlgo at every bar close in its sandbox and traded in a bot in the user's My Bots (marked Runs on OptAlgo). It starts on paper. You deploy it from a finished backtest of the same code; you never send orders for it yourself. The user can also do it without you in the app: Run on OptAlgo on a backtest (the same gate, paper first), Go live on the bot in My Bots (the paper period is recommended; before it ends the user accepts the risk in the app), and Download code on both. The backtest must show an edge (a positive Sharpe and no loss: else no_edge) and a search verdict that is not likely_overfit, unless an out-of-sample research run of the same code passed (see Avoid overfitting).
| Endpoint | Scope | Does |
|---|---|---|
GET /v1/strategies/limits | read | Slots used and left, symbols per strategy, daily CPU budget, paper trades left this month (Free), the live rule |
POST /v1/strategies?dry_run=true | bots | The whole deploy gate, nothing created. Free; at most 30 checks an hour |
POST /v1/strategies | bots | Deploys on paper. 201 with the strategy |
PATCH /v1/strategies/{id} | bots | name, allocated_amount, on_leg_failure, on paper only |
POST /v1/strategies/{id}/pause, /resume | bots | Stop or restart deciding; positions keep their stops |
DELETE /v1/strategies/{id}[?close=true] | bots | Flat: gone now. Open positions: winding_down (only exits until flat), or close=true to close them now |
GET /v1/strategies/{id}/source | read | The strategy.py it runs, as a file <name>-<sha8>.py (sha256 in X-Source-SHA256, the same as code.source_sha256) |
POST /v1/strategies/{id}/compare[?dry_run=true] | backtest | Compare with backtest: a backtest of the same code over the period it ran, matched trade by trade against its real (paper or live) trades. Costs backtest units |
What a hosted strategy runs
A hosted strategy runs everything its backtest ran: every declaration a backtest supports runs hosted the same way:
- One leg (no
legsdeclared): one symbol per decision. Deployed on several symbols, each symbol is traded on its own (a basket) withallocated_amount / N. - Several legs (
legs = 2to 16: pairs, ratio trades,targetportfolios on paper; more than 4 legs needs the Pro plan): deployed on exactly the backtest's symbols, in itsmarketorder (leavesymbolsout, or send them in that order; no subset). The bot in My Bots is a multi-symbol bot with one child per leg. Sizing is the backtest's shared account: each leg's notional is the intent's size × leverage × the bot's wholeallocated_amount, notallocated_amount / Nas in a basket (size = 0.5on two legs puts half of the allocation in each). There is one decision per bar, made once every leg's bar has closed; its actions are per leg and are delivered together in one record, each action naming itslegandsymbol. - Funding and open interest (
data = ["funding", "oi"]): on every leg that has the series (funding: perpetuals; open interest: BINANCE perpetuals; a SPOT leg readsNone, as in the backtest, and is never waited for), read from OptAlgo's live funding / open-interest feed with the backtest's causal rules: a funding settlement counts from its settlement time (rate,sum,settled), an open-interest row stampedTis used fromT + 10 min(filledwhen carried from an older row). - A reference's funding / open interest (
"funding:<reference>","oi:<reference>"): from the same live feed, keyed by the reference's symbol, aligned like the leg's own; a missing row is adata_gapnamingfunding:ref:<name>/oi:ref:<name>. - Taker buy volume (
data = ["taker"],"taker:<reference>"): the same values as the backtest, read from OptAlgo's data service after each bar closes; a bar whose value has not arrived by the deadline is adata_gapnamingtaker:<symbol>/taker:ref:<name>. The deploy gate refuses it (no_data) when none of the latest 60 bars has a value. - Context series (
FRED:*references): read after their publication lag, as in the backtest; a day without a value (weekend, holiday) is carried, not waited for. - News (
data = ["news"]): backtests only for now. There is no live news feed for hosted strategies, so the deploy gate refuses a strategy that declares it; removenews, backtest again, and deploy that run. - References, also on their own timeframe (
"BINANCE:BTCUSDT.P@1h"): row by row the latest reference bar closed by the traded bar's close, exactly as in a backtest. - Every declared input is waited for: each leg's bar, each reference's bar, funding, open interest, taker buy volume. When one is not there by the decision deadline (15 s after the bar's close on
1m, 30 s on longer timeframes), the whole decision is skipped asdata_gap, for every leg, and the bar's row says what wasmissing. The strategy never decides on half of its inputs. - Per leg: reconciliation, drift, staleness and the live confirm checks work leg by leg; the churn guard counts per leg; the CPU budget is unchanged (one decision runs all legs in one sandbox run). Live eligibility counts round trips of the whole position: a pair's entry and exit are one round trip.
The deploy gate still refuses (unsupported_strategy) a deployed symbol list that does not match the legs, a data series no deployed symbol has (funding without a perpetual, open interest without a BINANCE perpetual), any news declaration, and short_on_spot when the strategy shorts a SPOT symbol (only that symbol counts: a carry that shorts its perpetual leg deploys). When the user needs something hosted strategies do not run, say so plainly and file a feature ticket without asking.
Warm-up per series
A hosted decision loads at most 5,000 bars per series. Up to 5,000 warmup_bars(), nothing changes. Above it, a one-leg strategy with a reference on a coarser timeframe still deploys:
- The traded series: 5,000 bars. The gate measures that this is enough: it runs the strategy on the window the runner will load and on the full
warmup_bars()history, and any decision that differs on the last 3,000 bars refuses the deploy (warmup_too_long,fieldwarmup_bars). A strategy that counts bars or readsseries.tspacing across the warm-up is refused this way. - Each coarser reference: loaded at its own timeframe, counted in its own bars:
ceil(warmup_bars × your timeframe / its timeframe)(the span the backtest warms up on), at most 5,000 (fieldreferences.<name>otherwise). Before the 5,000 traded bars there is onesyntheticrow per older reference bar (flat, volume 0), so an indicator computed on closed reference bars sees the reference's whole history. - Same-timeframe or finer references read the 5,000 real bars only (NaN before them).
- Several legs keep the 5,000 traded-bar cap.
The 4h EMA(200) on a 1m strategy: warmup_bars() is 48,000 (200 × 240), hosted loads 5,000 1m bars and 200 4h bars. Compute it with prims.on_closed, never on the carried rows:
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 Trend4hOn1m(VectorStrategy):
"""1m entries above the 4h EMA(200)."""
name: ClassVar[str] = "trend_4h_on_1m"
references: ClassVar[list[str]] = ["BINANCE:BTCUSDT.P@4h"]
fast: int = 50
def warmup_bars(self) -> int:
return 240 * 200 # 200 4h bars, counted in 1m bars
def run(self, series: BarSeries, decision=None) -> StrategyOutput:
ref = series.refs["BINANCE:BTCUSDT.P@4h"]
h4_ema = prims.on_closed(ref, lambda b: indicators.ema(b.c, 200)) # a 4h EMA(200), closed 4h bars only
fast = indicators.ema(series.c, self.fast)
with np.errstate(invalid="ignore"):
up = series.c > h4_ema
entry = up & prims.cross_over(series.c, fast)
it = Intents.empty(len(series))
it.enter[entry] = 1
it.sl_dist[entry] = 0.01 * series.c[entry]
it.exit[~up] = Exit.LONGS
return StrategyOutput(intents=it, plots={"h4_ema": h4_ema, "fast": fast})
The deploy answer's warmup says what is loaded: {"traded": 5000, "references": {"BINANCE:BTCUSDT.P@4h": 200}} (within 5,000: {"traded": warmup_bars, "references": {}}).
Risk sizing hosted
execution.overrides.risk_per_trade (a fraction in (0, 1]) and risk_skip_above_full (true / false) run hosted, for market entries (limit and stop entries are not risk-sized, as in the backtest). The entry's size is size × min(1, risk / stop distance as a fraction of the price). An entry without a stop is skipped (decision code risk_skipped; the close of a reverse still goes out); with risk_skip_above_full, so is an entry whose fraction would exceed 1. A stop on the wrong side of the price is zero_size.
Drift against the backtest: hosted sizes at the decision close (the stop placed from it); the backtest sizes at the fill (the next open). With sl_dist the fraction is the same up to tick rounding. With an absolute sl or sl_off it moves by the gap between the close and the fill. size_at_fill does not change hosted sizing. Prefer sl_dist for a risk-sized hosted strategy.
Leg atomicity: on_leg_failure
A multi-leg strategy sets it at deploy, like on_error (PATCH changes it on paper): unwind (the default) or keep. With unwind, when one leg's entry is refused or fails, OptAlgo closes the other legs of that entry and logs leg_unwound; the same happens when, on the next bar, one leg's entry is found missing while the other legs are open. With keep, each leg stands on its own. Exits always go out per leg, under both policies. A backtest models unwind for one cause, an entry skipped by risk sizing (risk_skipped, Risk sizing): the legs before it in leg order open and close at once at the same open, the legs after it are not entered. It does not model the other causes (refusals, minimum sizes, exchange errors) nor keep.
Spot + perpetual legs on one account (a carry)
A multi-leg strategy whose legs trade spot and the USDT-M perpetual on BINANCE (a cash and carry: long BTCUSDT, short BTCUSDT.P) deploys as one strategy. Only as legs of one account: independent symbols (no legs) stay one market per strategy (mixed_markets: deploy the spot and the .P symbols as two strategies). OptAlgo opens these deploys for the platform; until it has, the dry run answers mixed_markets ("coming soon").
- The bot in My Bots is a multi-symbol bot whose legs each trade their own market: the spot leg on the spot account, the perpetual on futures.
GET /v1/strategies/{id}addsleg_markets(each leg's market),live_supported(whether this account may take it live now) andmax_leverage(2); once live,margin,hedgeandleg_guard(below). - The allocation is split by market, by how many legs trade in each (a carry: half in the spot wallet, half in futures). On paper, each paper wallet must hold its part.
- Size the legs as in the backtest: they share one wallet (one wallet,
mixed_wallet_overcommit).
Live (Plus, Pro; the user confirms in the app, as for any hosted strategy). Live spot + perpetual trading is opened account by account (live_supported): while it is not open for this account, request-live and the app's confirm answer mixed_live_unsupported, live_eligibility.blockers lists it, and a strategy already live takes exits only (decision code mixed_live_off). Besides the usual checks (Go live), the confirm needs:
| Check | Else |
|---|---|
| Leverage at most 2× (backtest it at 2× or less; every entry is also capped at 2×) | mixed_leverage_cap |
| Both the SPOT and the FUTURES account active on the exchange connection | exchange_not_connected, naming the inactive account |
| Each wallet's part of the allocation free, spot and futures separately | insufficient_balance, naming each short wallet and its shortfall |
| The Binance API key allows Spot & Margin Trading and Futures | exchange_permissions_missing (missing lists them); exchange_permissions_unverified when its permissions cannot be read |
| Each leg big enough to stay hedged: at least 3× the exchange's minimum notional and 50 amount steps of the perpetual | mixed_min_notional, with the min_allocation that passes |
How a live carry trades:
- Entries are
MARKETonly, so both legs fill together: aLIMITorSTOPentry is sent at market (decision codeorder_type_forced, fieldorder_type_forced: {from, to}). Each leg keeps its own stop-loss and take-profit, as in the backtest. - Both wallets are checked before every entry: each wallet's free balance must cover its legs' cost (× 1.02) before any leg is sent; otherwise no leg of that position opens (
mixed_wallet_short, naming the wallet and the amount to transfer) and the user gets a Telegram warning. OptAlgo never moves money between the user's wallets. - The leg guard. One leg open alone is an unhedged position. When the other leg's entry was rejected after it was sent, the other leg is no longer open on the exchange (a stop, a liquidation, a manual close), or it did not open within 20 s, OptAlgo closes the lone leg within seconds (decision code
leg_guard_unwind, withguard_reasonledger_failed/flat_on_exchange/grace_expiredandattempt) and holds new entries for 60 s (leg_guard_hold). Still alone 15 s later: another attempt. After 3 attempts in 2 minutes the strategy pauses with reasonleg_integrity: the user checks the position on the exchange and only the account owner resumes it, in the app.leg_guard{episode_t, attempts, last_at, reason, legs}shows the last episode. - Margin: alerts only.
margin{liq_price, mark, distance_pct, level, checked_at}is the perpetual leg's distance to liquidation;levelok,warn(under 25 %: one warning) ordanger(under 12 %: a Telegram and My Bots alert every 10 minutes naming the USDT to move from spot to futures; re-armed above 30 %). OptAlgo never closes a leg for margin. - Hedge:
hedge{spot_qty, perp_qty, drift_pct, checked_at}; a drift above 2 % is one warning. No automatic correction. - A guard close that never reached the bot is recorded with
outcomenot_sentandnot_sent_reason:no_open_trade(nothing open in OptAlgo),verification_hash_invalid(the account's verification hash does not verify: the user re-saves the strategy or contacts support),listener_refused,send_failed. It is never shown as sent.
Tell the user plainly what only they can do: fund both wallets, fix the key's permissions, resume after leg_integrity.
3.1 Deploy: dry run first
- Pick a backtest of this exact code:
statusdone, a plain backtest (no research block), honesty grade A, B or C. - Check it for free. Send the backtest id; leave out what the backtest already fixes (code, parameters, timeframe, exchange, leverage):
curl -sS -X POST "$OPTALGO_API_BASE/strategies?dry_run=true" \
-H "X-API-Key: $OPTALGO_API_KEY" -H "Content-Type: application/json" \
-d '{"backtest_id": "<id from GET /v1/backtests>", "name": "Breakout 1h", "symbols": ["BTCUSDT.P", "ETHUSDT.P"], "allocated_amount": 1000}'
The answer is {data: {ok, findings, check, plan, would_deploy}, next}. findings lists every problem at once, each with code, message, fix and often field and symbol. Fix them all in one edit (a code change means a new backtest), then check again.
- When
okistrue, send the same body withoutdry_run, with anIdempotency-Key. The answer is201with the strategy:id,statuspaper,bot_id(its bot in My Bots),code(source_sha256,backtest_id,grade). - Tell the user: "deployed on paper; it decides at every bar close of its timeframe; watch it at app.optalgo.com/my-bots". Never say it is trading live.
Optional body fields: symbols (a subset of the backtest's; a strategy on several symbols comes from a basket backtest of them, and each symbol then trades allocated_amount / number of symbols; a multi-leg strategy: exactly its legs in the backtest's order, sized on the whole allocated_amount), allocated_amount (paper budget, default 1000), on_error (hold, the default, keeps positions and their stops when the code fails; close closes them), on_leg_failure (a multi-leg strategy: unwind, the default, closes the other legs when one leg's entry fails; keep lets each leg stand on its own). params, timeframe, exchange, leverage, source / source_sha256 may be sent, but only to state what the backtest used: anything different is refused (params_mismatch …).
3.2 The gate
A deploy is refused (422, every finding at once) unless:
- the backtest is yours,
done, a plain backtest, grade A to C, and ran your own code (spec.strategy.source); - the backtest made money (
no_edgealways blocks) and its search verdict is notlikely_overfit, unlesssearch.validated_byis set; - a deploy of only some symbols of a basket backtest is judged on those symbols' own results: each deployed symbol's grade A to C, and their equal-slot total return not negative (
basket_subset,subset_no_edge); - the deploy uses the backtest's code, parameters, timeframe (whole minutes,
1mand up), exchange and leverage; symbols are a subset of the backtest's (a multi-leg strategy: exactly its legs, in the backtest'smarketorder), all SPOT or all FUTURES (or the legs of one spot + perpetual strategy), one quote asset; - the plan has a free slot and allows that many symbols, and that many legs on one account (
hosted_leg_limit: Free and Plus 4, Pro 16); - the engine's live check passes: the code runs, looks no bar ahead, is deterministic, needs at most 5,000 warm-up bars per series (the traded bars; on a one-leg strategy each coarser reference in its own bars: Warm-up per series), decides within the CPU cap (1 s per decision below 15m, 3 s from 15m; a multi-leg decision runs all its legs within it), and only uses what hosted execution supports (its declared
datamust be on symbols the live feed serves).
Leverage cap: every entry the strategy decides runs at most at the leverage it was backtested and deployed with, lowered to the deploying key's max_leverage when the key has one, on paper and live. An entry asking for more is sent at the cap, not refused; size and stop distances in the code should assume that leverage.
Supported live: entries MARKET, LIMIT, STOP and STOP_LIMIT (STOP_LIMIT on 5m and longer; a limit or stop entry lives one bar; send it again on the next bar if you still want it; what each one does); sl / tp as absolute prices, offsets (sl_off / tp_off) or distances (sl_dist / tp_dist); moving the stop with sl_update (long and short); moving the take-profit with tp_update (one-way position; paper and live); exits; max_bars; size (above 1 needs futures leverage); reversing (a close, then the new entry); target positions on paper (portfolios hosted: targets only, partial closes, an increase re-opens at the new size; live refused with target_paper_only). Not yet: trailing stops (trail_dist, trail_act_dist), break-even moves (be_trigger_dist, be_offset), target live, adding to a position without re-opening it, pyramiding (more than one position per side), shorts on SPOT. The refusal's fix names the closest supported way, for example "move the stop yourself each bar with sl_update".
What each order does: backtest, live, paper
The same rule decides an order in the backtest, in the hosted bot on the exchange and on paper, so the compare stays near 100%. The differences that remain are fills, not decisions:
| Entry | Backtest | Live (hosted bot) | Paper |
|---|---|---|---|
MARKET | the next open plus slippage; sl_dist / tp_dist / *_off brackets measured from the fill | a market order, stop-loss and take-profit placed at once; distance / offset brackets are sent from the decision close and re-based on the fill at the next decision (decision code bracket_rebase; the stop moves only when it tightens) | the order book |
LIMIT | GTC: marketable at its first open fills at the open as a taker, else rests at the limit for one bar (a gap through it: the limit price) | a GTC limit order; still unfilled after the bar: closed at the next decision | rests; a crossed one fills at the book |
STOP | the trigger plus slippage (gapped: the open), one bar | a stop-market order (last price); a trigger already past the price: a market order | rests; crossed: the book |
STOP_LIMIT (5m and longer) | the trigger 10 ticks beyond entry_price; once reached it rests as a limit at entry_price, never filled in the bar that armed it, one bar | a stop-limit order with the same geometry | arms on the minute that reaches the trigger, fills at the limit on a later minute |
| exits | the stop at its level (gapped: the open); the take-profit at its price; a tp_update at or through the close exits at the next open | a stop-market and a take-profit order; a move replaces both; after one fills the other is cancelled | the ticks, with a 1-minute backstop; a same-minute stop and take-profit: the stop |
forex (FX-EXNESS, MT5) | buys on the ask (BID + the bar's spread, else the registry's), sells on the bid, no spread fee; a short's stop / take-profit on the ask; weekly close and the instrument's daily break masked | market orders; LIMIT / STOP pending orders carry their stop-loss and take-profit; STOP_LIMIT not supported | as crypto, on BID |
STOP_LIMIT on a 1m strategy is refused at deploy (stop_limit_needs_minutes): live has no finer bars to arm and fill it on. Accepted drift, not bugs: sizing at the decision close (Risk sizing), the forex rollover-hour spread, a hosted limit filled between the bar close and its expiry, partial fills (the exits protect the whole order).
3.3 Slots and plans
| Plan | Hosted strategies at once | Symbols per strategy | Legs on one account | CPU per day | Live |
|---|---|---|---|---|---|
| Free | 1 | 3 | 4 | 60 s | No (paper only) |
| Plus | 3 | 10 | 4 | 600 s | Yes, the user confirms in the app |
| Pro | 8 | 20 | 16 | 3 000 s | Yes, the user confirms in the app |
A strategy takes a slot unless it is winding_down, stopped or deleted; hosted strategies never count against the plan's bot limit. On Free, hosted paper trades count against the month's paper trades (GET /v1/strategies/limits → paper_trades). An account's admin may set other limits: read limits, do not assume the table.
4. Watch it
GET /v1/strategies/{id} (or the list, GET /v1/strategies) answers:
status:paper·live_requested·live·paused·winding_down·error·stopped; andreason{code, message, fix}when there is one. Quotemessage, act onfix.last_decision(the last bar:status,sent,latency_ms),last_error(code,rule,line,message),runner_pause(no decisions until 00:00 UTC once the day's CPU budget is used).declared: what the code declares besides its own candles,{legs, references, data}(what a hosted strategy runs).live_eligibility:recommended_ready(the recommended paper period is done and nothing blocks;eligibleis the same value, kept for older clients),can_go_live(no hard blocker),paper_days,closed_paper_trades(a multi-leg strategy counts round trips of the whole position: a pair's entry and exit are one),progress,blockers(hard:plan_required,status) andrecommendations(advisory:paper_period,recent_error), each with itsfix;reasonslists both.paper_tradeson paper: what is left this month.
GET /v1/strategies/{id}/decisions[?symbol=&before=&limit=], newest first, kept 90 days, pages that end on whole bars (next_before → the next page's before):
- one row per bar for the whole strategy (
symbol"*"):statusdecided·skipped·error·error_state·pausedwith a plainmessage; - one row per action:
action(LONG,SHORT,CLOSE,MOVE_STOP_LOSS; aMOVE_STOP_LOSScarries both the stop and the take-profit held, and a moved take-profit goes out this way, signal reasontp_update; atp_updateat or through the close is aCLOSEwith that reason), on a multi-leg strategy itslegandsymbol(one decision's leg actions are delivered together),outcomesent·refused·skipped·duplicate·not_sent(a leg guard close that never reached the bot:not_sent_reason), acodeandmessagewhen not sent,latency_ms(bar data final → decision received), andtransaction_id. A sent row carriessignal_statusandsignal_url(GET /v1/signals/{transaction_id}): follow it to the fill; the trade carries the sametransaction_idinGET /v1/trades?bot_id={bot_id}&status=all, and the row carries itstrade_idonce it resolves (nulluntil then); - one row per symbol that did nothing (
outcomequiet).
GET /v1/strategies/{id}/logs: the bot's log feed as My Bots shows it (orders, refusals with their reason, status changes).
code on a decision or bar | Means | Do |
|---|---|---|
stale | It arrived too late after the bar closed | Nothing; it recurs only if OptAlgo is slow, then file a ticket |
already_open, nothing_open, opposite_open | The bot's real position differs from the strategy's (per leg on a multi-leg strategy) | Compare /decisions with /v1/trades; repeated differences pause it (drift) |
reconcile | OptAlgo closed a position the strategy no longer holds | Nothing |
not_running, winding_down, exits_only, kill_switch, live_confirming | Entries are held: the strategy is paused or being removed, OptAlgo holds entries, or the user's confirm-live is closing the paper positions | Read status |
stop_widening | A stop-loss move that would widen the stop, while entries are held: not sent | Nothing; only tighter stops move while entries are held |
data_gap | A declared input was not there by the deadline (15 s after the close on 1m, 30 s otherwise): a leg's or a reference's bar, funding or open interest. The whole decision was skipped, for every leg; missing names what was missing | Nothing; repeated gaps: file a ticket |
leg_unwound | A multi-leg strategy with on_leg_failure unwind: one leg's entry was refused, failed or found missing on the next bar, so OptAlgo closed the other legs of that entry | Read the failed leg's row (its code says why); nothing to fix for the unwind itself |
mixed_live_off | A live spot + perpetual strategy while live spot + perpetual trading is not open for the account: entries skipped on every leg, exits still go out | Tell the user; nothing to fix in the code |
mixed_wallet_short | Live spot + perpetual: a wallet could not cover its leg, so no leg of that position was opened; message names the wallet and the amount to transfer | The user moves funds between the spot and futures wallets |
order_type_forced | (sent) Live spot + perpetual: a LIMIT / STOP entry was sent as MARKET so both legs fill together | Nothing |
bracket_rebase | (sent) A MOVE_STOP_LOSS after a market entry with distance / offset brackets filled away from the decision close: the stop-loss and take-profit re-based on the fill, as the backtest measures them (the stop only when it tightens; see What each order does) | Nothing |
leg_guard_hold, leg_guard_unwind | Live spot + perpetual: a lone leg is being closed (entries held about 60 s); the close row itself, with guard_reason and attempt | Nothing; repeated: read leg_guard and the bot's log |
runner_error | A problem on OptAlgo's side; nothing ran | Nothing; it is ours |
sandbox_error | The strategy failed on this bar (last_error has the line); positions untouched | Fix the code, backtest, deploy the new version |
errors_in_a_row, errors_per_hour, static_check | Status error: it stopped deciding (3 errors in a row, 5 in an hour, or the code check) | Same; or resume to retry as is |
target_open, target_partial, target_close, target_flip, target_reopen | (sent) A target decision traded the real position: opened, partly closed, closed, closed and opened the other side, or closed and re-opened at a larger size (two fees). target_plan on the row has the target, price, held quantity and orders | Nothing; many target_reopen: backtest with a rebalance_band |
band_skipped, at_target | A target within the rebalance band of the real position, or already there: nothing traded | Nothing |
target_paper_only | A target that would add exposure on a bot that is not on paper: not sent (closes still go) | Nothing; target strategies run on paper only |
position_unknown | A target resize while the open position has no fill size yet: not traded this bar | Nothing; it trades on the next target |
risk_skipped | risk_per_trade: the entry had no stop-loss, or (with risk_skip_above_full) its size would exceed the full size. The backtest skips it too | Nothing; give every entry a stop if it should trade |
churn | Paused: more than 2 actions on a symbol in one bar, or more than 30 entries in an hour (a multi-leg strategy: counted per leg) | Make entries rarer, backtest, then resume |
cpu_budget | The day's CPU budget is used; decisions resume at 00:00 UTC | Make it cheaper (sdk.prims, fewer symbols, a longer timeframe) |
daily_loss_limit | Paused: today's live loss reached the key's daily loss limit | Only the user resumes it, in the app |
Other refusal codes on a sent action are the bot's own checks (balance, plan limits, exchange): see Rejections.
Compare with backtest
Does the strategy trade what its backtest says? OptAlgo backtests the exact deployed config (the code by source_sha256, params, timeframe, symbols as a basket or a multi-leg strategy's legs on one account, leverage, the allocation as the starting equity) over the period it has been running in one mode, then pairs every real trade with a backtest trade (same symbol and side, entry on the same bar or one bar apart). The user has the same button in My Bots ("Compare with backtest").
| Endpoint | Scope | Does |
|---|---|---|
POST /v1/strategies/{id}/compare?dry_run=true | backtest | Free estimate: {mode, modes, window {start, end, bars}, units, run_s, quota, existing} |
POST /v1/strategies/{id}/compare | backtest | 202 {id, backtest_id, base_backtest_id, status, units, position, eta_s, reused}. Body {"mode": "paper" | "live", "base_backtest_id": "..."} (default: the strategy's mode, the deploy backtest) |
GET /v1/strategies/{id}/compare/{compare_id}[?offset=&limit=&actual=true] | read | status queued / running (with position, eta_s) until the backtest is done, then report |
GET /v1/strategies/{id}/compare | read | The newest compares with their summary |
- Costs: the compare backtest uses the costs of its base: the deploy backtest by default, or one of its cost variants (
base_backtest_id; anything else is400 compare_base_not_allowed, an unfinished variant409 not_ready). The running strategy is not changed. Compare live trades against an Auto variant when the deploy backtest carried costs the user did not choose. - Window: paper = from the deploy, live = from the switch to live; until the last bar the strategy decided (paper of a strategy now live ends at the switch). The warm-up before it is loaded as in any backtest.
- Cost: like any backtest (1 unit = up to 10 s of run time, the normal quota, queue and
429 daily_quota/monthly_quota). Comparing again before a new bar closed returns the same compare (reused: true,units: 0). Run the dry run first and tell the user the cost. report.summary:decisions_matchedofdecisions_total(entries and exits on both sides),match_rate,missed(only in the backtest),extra(only in the account),pnl_actualvspnl_backtestandpnl_diff(realised, net of fees),avg_entry_slippage_bpsandavg_exit_slippage_bps(positive = worse for the account than the modelled fill),fees_actualvsfees_backtest,shifted(decided one bar apart).report.mismatches: each withtype(missed,extra,exit,shifted),bar_t,symbol,sideand areason: a decision-row code from the table above (data_gap,churn,stale,already_open,nothing_open,exits_only,risk_skipped…; arisk_skippedagainst a backtest trade is the close-vs-fill sizing drift),listener_refused/missed_delivery(sent, but no trade came of it),no_decision(the runner decided nothing that bar),not_from_strategy(a manual or agent signal on the bot),manual_close,exchange_exit_differs(a stop or target filled on one side only),limit_unfilled(aLIMIT/STOP_LIMITentry the exchange never filled before it expired, while the backtest filled it),partial_fill(the exchange filled part of the order),entry_refused:<code>(the exchange refused the entry; the code is the exchange's),decided_flat(the strategy decided flat while the bot held a position),bar_shift(the live candle differed slightly from the final one), orunexplained.- Multi-leg: trades are matched per leg (each mismatch and pair carries its leg's
symbol), andpnl_actual/pnl_backtestare the combined PnL of all legs. - Target portfolios: the backtest holds lots (an increase is a new lot), the bot one position per leg, so trades do not pair one for one.
report.target(andsummary.target) matches rebalance bars per leg:per_leg[]{symbol, rebalances_backtest, rebalances_actual, matched, missed, extra, pnl_actual, pnl_backtest, pnl_diff}and the totals withmatch_rate. report.matched(paged byoffset/limit) has every pair with its entry / exit slippage, fee and PnL difference;histogrambuckets the per-trade drift;open_positionslists what is open at the window end;actual=trueaddsactual_trades. The backtest itself is a normal run:GET /v1/backtests/{backtest_id}for its honesty grade.
How to read it: a match rate near 100% means the hosted strategy decides exactly what its backtest decides. Execution drift is normal: paper fills at the order book and live fills at the exchange are never exactly the modelled fills; a few bps is slippage, not a bug. Investigate missed / extra mismatches with their reason and GET /v1/strategies/{id}/decisions; unexplained ones are OptAlgo's to explain: report them.
5. Go live
Live is the user's decision, made in the app. You can only ask.
- Recommended before live: at least 7 days on paper with at least 1 closed paper trade, or 5 closed paper trades, and no strategy error in the last 24 hours (a multi-leg strategy counts round trips of the whole position: a pair's entry and exit are one trade).
GET /v1/strategies/{id}shows it aslive_eligibility.recommended_readyand theprogress. It is a recommendation, not a rule: the user may go live earlier by accepting the risk in the app. Say so plainly when you suggest live early ("it has 2 of the recommended 7 days on paper; going live now means accepting that risk"); never decide it for them. Plus or Pro only (hard). - With the user's agreement,
POST /v1/strategies/{id}/request-live(needs thetradescope). It is never refused for the paper period; it never flips anything: status becomeslive_requested, the user gets a notification and a Your agent asked to go live card on the bot in My Bots. The answer'slive_eligibilitycarriesrecommended_readyand theprogress. - Tell the user to open My Bots and confirm or decline. Before the recommended paper period ends, the app shows a warning and the user ticks a box to accept the risk; you cannot accept it for them. The app checks everything hard first (plan, a strategy running on paper, the kill switch, the leverage cap, no live position open, the exchange connection, enough free balance for the allocation; on a multi-leg strategy, for every leg; a spot + perpetual strategy also checks both wallets, the key's permissions, the 2× leverage cap and the legs' size) and changes nothing while a check fails; only then does it close the strategy's open paper positions and the bot trades with real money on the user's exchange. No exchange connected: the user sees
exchange_not_connectedand connects it first. - Poll
GET /v1/strategies/{id}. Never say it is live untilstatusislive. Back topapermeans the user declined.
Errors here: plan_required (Free), scope_required (the key needs trade), target_paper_only (409: a target strategy runs on paper only; live_eligibility.blockers lists it too). Once live, PATCH is refused (live_strategy), DELETE ?close=true needs trade, and a daily_loss_limit pause is lifted only by the user, in the app.
6. Errors and what to do
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):
{"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"}]}
erroris a stable code: branch on it.message(=detail) says what happened; quote it.fixis one concrete instruction: do it.field, when present, names the part of your request.docslinks the code's entry below.nextlists 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-Remainingon every response;X-Quota-RemainingandX-Quota-Resets-Aton limits, validate, submit, list and get;Retry-Afteron every429;X-Request-Id(req_…) on every/v1response. - A
5xxon any/v1path (also an unexpected crash:500 internal_error, always JSON) carriesrequest_idand, last innext, areport_issuestep with a ready ticket inbody:{"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 asfixsays; when it repeats, send that body (add the call you made) - see Report problems automatically. OptAlgo also logs every5xxon its own.
Access and plan
invalid_api_key (401)
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)
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)
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)
Wait Retry-After seconds, then retry.
not_in_plan (403)
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 are switched off for the account. Tell the user to contact support (or file a ticket, POST /v1/tickets); stop.
account_suspended (403)
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 [email protected]. 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)
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 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
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). Do not retry.
connector_not_allowed (403)
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)
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 stops connectors too.
Quota
daily_quota (429)
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)
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)
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)
Send your strategy code as source (the text of strategy.py); a strategy by name cannot run.
invalid_request (422)
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)
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)
The spec has no code: send source.
user_code
This account cannot run its own code: the user contacts support.
source (413)
The strategy file is too large (at most 64 KB): shrink it.
security_violation (422)
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 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)
Fix the spec as message and fix say; validate shows every problem with an example.
Execution settings the run refuses
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.
magnifier_timeframe: everyexecution.magnifiersentry must be finer than the timeframe (and the level above it) and divide it.allowedlists them for your timeframe andsuggestionis the default:["5", "1"]from 15m up,["1"]on 5m,[]on 1m. Or send"auto".override_unknown/override_invalid: anexecution.overrideskey that is not an execution setting (allowedlists them), or a value of the wrong type or range (leverage> 0,max_lots_per_side>= 1,tieone ofallowed, ...).venue_option:execution.extended_hourswithout a stock leg; early decision ortickswith a stock leg.early_decision_magnifiers/early_decision_lead:execution.early_decision_sneeds finer data (magnifiersnot[]) and a lead shorter than the bar (allowed).research_unsupported: aresearchblock withearly_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).costs_conflict(execution.costsbesidefee_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.slippage_default_missing,slippage_symbol_unknown,slippage_value_invalid,slippage_key_duplicate,slippage_override_conflict: anexecution.slippagemap per symbol needs adefault, keys that are the spec's symbols (with or withoutEXCHANGE:, each once), values from 0 to 0.05 (a fraction: 0.001 = 0.1 %), and noexecution.overrides.slippagebeside it.
A run that still fails on one says invalid spec: <code> (<field>): <message>; fix: <fix> in error.
declaration (a source_check rule)
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.
Strategy inputs and legs
validate findings about what a strategy declares besides its own candles. value names the reference or symbol.
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) or a stock basket (one stock symbol per run). value is the number of symbols sent, allowed the legs.
unknown_reference
A declared reference has no market data (symbol): declare a symbol GET /v1/markets lists (futures symbols end in .P).
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)
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
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 (warning)
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
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
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)
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)
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
execution.early_decision_s does not work yet with references, data series or several legs: remove it.
hosted_unsupported (warning)
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), 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); 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.
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). Its findings carry rule and kind; the message starts with dry run:.
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)
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 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
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).
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).
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
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)
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)
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).
Per-run limits
max_symbols (413)
Too many legs for the plan: use at most allowed symbols, split the rest over several runs.
max_bars (413)
Too much history per symbol: shorten the window or use a coarser timeframe; validate gives a start date that fits.
max_references (413)
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)
Too many research trials: lower n_trials, set permutations and permutation_trials small.
mem_mb (413)
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)
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)
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 meanwhile.
max_concurrent (429)
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)
No such backtest on this account: list yours (GET /v1/backtests) instead of guessing ids.
not_ready (409)
The run has not finished: poll GET /v1/backtests/{id} until done, then fetch again.
pruned (410)
The run's chart, trade and candle files were deleted under 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)
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)
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)
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)
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)
This run is tagged with a study whose pinned settings 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)
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)
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).
holdout_declared (409)
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)
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)
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)
The study has no holdout: declare one (POST /v1/studies/{tag}/holdout) before tuning, not after.
not_in_study (422)
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)
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)
A robustness check runs one fixed backtest, not a research or robustness row: check the backtest itself.
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).
Service
service_unavailable (500 / 502 / 503 / 504)
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)
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
A failed (or waiting) run's fix.code on GET /v1/backtests/{id}:
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
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 | 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 and internal (the sandbox failed outside your code) | Never | 0: not charged |
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, without asking the user).
capped_wall_s, capped_cpu_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 says beforehand when a run would hit the cap.
capped_mem_mb, capped_mem_oom, capped_mem_worker
The run needed more memory than allowed: shorter window, fewer symbols, coarser timeframe. Charged.
waiting_for_memory, worker_restarted
Not a failure: the run waits or runs again. Keep polling.
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
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)
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 |
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 |
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) |
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); 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 |
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 |
subset_no_edge | The deployed symbols lost money together in the backtest. See subset_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
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
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)
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 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: 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), 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). 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 instead.
backtest_not_found (404)
No such backtest on this account: deploy one of yours (GET /v1/backtests).
hosted_not_available (403)
Hosted strategies are not open for this account yet. Keep backtesting and use paper bots.
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)
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)
The strategy trades live: only the user changes it, in the app.
owner_only (403)
Paused for daily_loss_limit, a suspension, a plan change, leg_integrity (a spot + perpetual 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)
Its status does not allow this now (for example resuming a strategy that is winding down). Read it, then act.
conflict (409)
It changed meanwhile, or a position is open: read it again, then retry.
exchange_not_connected (422)
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 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)
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 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)
A spot + perpetual 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)
The app's confirm-live of a spot + perpetual 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)
The app's confirm-live of a spot + perpetual 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)
The app's confirm-live of a spot + perpetual 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)
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)
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
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)
Compare with backtest: the strategy has not decided enough bars in that mode yet (at least two). Compare again later.
not_live (409)
Compare with backtest with mode: live on a strategy that never traded live: compare paper.
hosted_bot (409)
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
| 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. |
| 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.
7. Reference
Base URL, authentication, scopes
- Base URL
https://api.optalgo.com/v1(alsoOPTALGO_API_BASEin the credentials file). Every request sendsX-API-Key: oa_live_..., loaded from the credentials file inside the command (section 0). - Developers can also create a key by hand in the app under AI agents and store it in the same file or the environment.
| Scope | Allows |
|---|---|
read (always on) | Session context, account, exchanges and symbols, markets, connections, bots, trades, stats, equity, positions, balance, summary, logs, signal outcomes, backtest results, studies and holdouts, tickets |
backtest | POST /v1/backtests/validate, /check and POST /v1/backtests; on your own backtests: annotate (PATCH), rerun, robustness; studies: describe, holdout, final test. Nothing else. bots and trade keys may do all of it too |
bots | Create, edit, start, stop, convert and delete the user's bots; ticker weights, pauses and removal; start a Binance connection; signals and closes on paper bots. Stopping a bot closes its open positions, live ones included |
trade (Plus, Pro) | Real money: signals and closes on live bots, paper-to-live (PATCH {"is_paper": false}), raising a live bot's allocation, creating a live bot, reading a bot's strategy_key |
A key without trade can never put money at risk: it cannot switch a bot to live, and if the user switches a bot to live in the app, that key's signals on it answer 403 scope_required.
In a program, read the same file (an OPTALGO_API_KEY environment variable set by the user wins):
import os
from pathlib import Path
def optalgo_credentials(path=Path.home() / ".config" / "optalgo" / "credentials.env"):
"""(key, base_url) from the environment, else from the credentials file. Never print the key."""
values = {}
if path.exists():
for line in path.read_text().splitlines():
name, sep, value = line.partition("=")
if sep and not name.startswith("#"):
values[name.strip()] = value.strip()
key = os.environ.get("OPTALGO_API_KEY") or values.get("OPTALGO_API_KEY")
base = os.environ.get("OPTALGO_API_BASE") or values.get("OPTALGO_API_BASE") or "https://api.optalgo.com/v1"
if not key:
raise SystemExit("Not connected to OptAlgo: run the agent login (docs.optalgo.com/optalgo-llm.md, section 0).")
return key, base.rstrip("/")
Errors, rate limits, idempotency
- Errors: section 6. A plain-text error that is not JSON (for example
error code: 1010) comes from the network edge: retry once with a descriptiveUser-Agent(my-dashboard/1.0); file a ticket if it persists. - Rate limits per key: 120 requests a minute, 30 a minute for signals and closes.
X-RateLimit-LimitandX-RateLimit-Remainingon every response;429 rate_limitedwithRetry-After. - Idempotency.
POST /v1/bots,/v1/bots/{bot_id}/signal,/close,/start,/stopandPOST /v1/ticketsaccept anIdempotency-Keyheader (1–128 characters, per key). A repeat within 24 hours returns the first answer withIdempotent-Replayed: trueand runs nothing; a repeat while the first is still running is409 idempotency_in_progress. Errors are not stored, so a failed call can be retried with the same key. Use one fresh UUID per intended action. - Every call is logged with the key that made it, and every bot change appears in the bot's log as
… via API key "<name>" (<prefix>).
Account, exchanges, markets, connections (scope read)
GET /v1/me:
{"user_id": "…", "email": "…", "name": "…",
"plan": {"tier": "Pro", "strategy_limit": 20},
"multi_symbol": {"enabled": true, "plan_allowed": true, "max_positions_cap": 20},
"api_key": {"id": "…", "name": "claude", "prefix": "oa_live_AbC123", "scopes": ["read", "backtest", "bots", "trade"],
"autonomy": "confirm_live",
"limits": {"max_allocation_per_bot": 500.0, "max_leverage": 5, "allowed_exchanges": ["BINANCE"],
"allowed_account_types": ["FUTURES"], "daily_loss_limit": 100.0},
"paused": false, "paused_reason": null, "paused_at": null},
"today": {"live_realized_pnl": -42.5, "since": "2026-10-07T00:00:00+00:00", "daily_loss_limit": 100.0},
"tickets": {"submissions_left_today": 20, "resets_at": "2026-10-08T00:00:00+00:00"},
"strike_count": {"used": 0, "max": 3}}
strike_count: security strikes used of the max that suspends API access (honest mistakes and engine stops never count).
max_positions_cap is 0 when the plan has no multi-symbol bots (Free) and null for unlimited. today appears only when daily_loss_limit is set.
GET /v1/exchanges → venues and what the user connected:
{"exchanges": [{"exchange_id": "…", "name": "BINANCE", "account_types": ["FUTURES", "SPOT"], "is_paper": false,
"connected": true, "connected_account_types": ["FUTURES"]},
{"exchange_id": "…", "name": "OPTALGO-PAPER", "account_types": ["FUTURES", "SPOT"], "is_paper": true,
"connected": true, "connected_account_types": []}]}
GET /v1/exchanges/{exchange_id}/symbols?account_type=FUTURES&q=BTC&limit=50 → tradable symbols (account_type required; limit 1..500). Use id as a bot's symbol and a signal's ticker: futures end in .P (BTCUSDT.P), spot does not.
GET /v1/markets?exchange=BINANCE&type=FUTURES → what backtests (and later hosted strategies) can use: per symbol its timeframes, the first date of history per timeframe, tick / step size, minimum notional, market type and whether shorts are allowed.
GET /v1/prices?symbols=BTCUSDT.P,ETHUSDT.P&exchange=BINANCE → the live price of up to 20 symbols (exchange BINANCE, the default, or BYBIT), from the same source paper fills use: OptAlgo's market data first, the exchange's ticker only when that has no price fresher than 5 s. Use it instead of any web lookup.
{"data": {"prices": [{"exchange": "BINANCE", "symbol": "BTCUSDT.P", "price": 60012.5,
"at": "2026-10-09T10:00:00.123+00:00", "source": "data"}]},
"next": [{"action": "send_signal", "method": "POST", "path": "/v1/bots/{bot_id}/signal", "why": "…"}]}
price is the last trade (else the bid / ask mid), at when it was last confirmed, source data (OptAlgo's market data) or exchange (the fallback). A symbol with no fresh price right now is listed in data.unavailable; when none has one, 503 price_unavailable. Unknown symbols are 422 invalid_request with every one in findings. Scope read; connectors may call it.
GET /v1/connections → the user's exchange connections, never their keys: exchange, status, leverage and margin mode per account type.
Paper and live
- Paper or live is a property of the bot, never of a signal. Bots are created on paper unless a live single bot is requested with
trade. - Every bot reports
mode(paperorlive),mode_changed_atandmode_history(last 10 switches,byisapporapi_key:<prefix>). A trade keeps the mode it was opened in;GET /v1/trades?mode=,GET /v1/summaryand the bot stats split paper and live. - Switching paper to live needs
trade, an active exchange connection for the bot's market type, and no open trade. The user normally does it in the app (safety rule 3). - Flatten a live bot:
POST /v1/bots/{bot_id}/close(needstrade; see Signals and closes). Pausing or stopping a live bot (POST /v1/bots/{bot_id}/stop, which also closes its positions) needsbots. A chat-app connector is paper only on every plan: it can do none of this on a live bot (connector_paper_only); tell the user to use the app or an API key. - Paper fills use real market data and have no simulated stop-loss or take-profit: send a
CLOSEwhen a stop or target would be hit.MOVE_STOP_LOSSand trailing stops do nothing on paper. - On Free, paper trades have a monthly limit:
GET /v1/summary→monthly_trade_quota.
Bots
{"bot_id": "…", "name": "BTC breakout", "type": "single",
"status": "active", "is_active": true, "is_paper": true, "mode": "paper", "mode_changed_at": 1791300000.0,
"mode_history": [{"mode": "paper", "at": 1791300000.0, "by": "api_key:oa_live_AbC123"}],
"exchange": "BINANCE", "exchange_id": "…", "account_type": "FUTURES", "symbol": "BTCUSDT.P",
"allocated_amount": 500.0, "has_open_position": false,
"pnl": {"realized": 12.5, "unrealized": 0.0}, "created_at": 1791300000.0, "strategy_key": null}
type:single(one symbol),auto(configured by its first signal),multi(multi-symbol parent),child(one ticker of a multi bot; read-only).status:waiting_signal(not configured yet),pending,active,stopped.- A
multibot addsmax_positions,open_positions,free_slots,slot_amount,budget_used,quote_asset,configuredandchildren([{bot_id, ticker, weight, paused, has_open_position, pnl, slot_amount}]). strategy_key(the webhook key) is returned only totradekeys.
| Method · path | Scope | Notes |
|---|---|---|
GET /v1/bots · GET /v1/bots/{bot_id} | read | Newest first; children inside their multi bot |
POST /v1/bots | bots (trade for live) | Bodies below. 201 with the bot. Idempotency-Key |
PATCH /v1/bots/{bot_id} | bots (trade for "is_paper": false and raising a live allocation) | name, allocated_amount, is_paper, max_positions (multi). 409 conflict while a single bot has an open trade |
POST /v1/bots/{bot_id}/start · /stop | bots | Stop closes the bot's open positions. {"changed", "bot"}; 409 conflict while another start/stop runs |
POST /v1/bots/{bot_id}/convert-to-multi | bots | {"max_positions": 5}: a single bot becomes the first ticker of a new multi bot |
DELETE /v1/bots/{bot_id} | bots | 409 conflict while a trade is open |
GET /v1/bots/{bot_id}/children | read | Multi bots: max_positions, free_slots, weight_sum, children |
PATCH /v1/bots/{bot_id}/children/{ticker} | bots | {"weight": 1.5} and/or {"paused": true} |
DELETE /v1/bots/{bot_id}/children/{ticker} | bots | 409 conflict while the ticker is open |
{"type": "single", "name": "BTC breakout", "exchange_id": "<from /v1/exchanges>", "account_type": "FUTURES",
"symbol": "BTCUSDT.P", "allocated_amount": 500, "is_paper": true}
{"type": "multi", "name": "Momentum basket", "max_positions": 5, "allocated_amount": 1000, "account_type": "FUTURES"}
multiandautobots always start on paper;"is_paper": falsefor them is a 422.- A multi bot needs Plus or Pro and
max_positions≤multi_symbol.max_positions_cap(Plus 10, Pro 20). If creation answersMulti-symbol bots are not available for your account., it is not switched on for the account yet. - The number of active bots is limited per plan (
plan.strategy_limit): over it, create and start answerStrategy limit reached: your … plan allows N active strategies. Stop one or upgrade your plan. - Writes to a
childanswer422 child_bot: act on the parent withticker.
Multi-symbol bots. One budget (allocated_amount) split in max_positions slots; each ticker becomes a child on its first entry. An entry is sized on allocated_amount / max_positions × weight (weight 1 unless set; weights sum to at most max_positions, else 422 weight_budget_exceeded). A slot is held by an open trade or a 20-minute reservation; when all are taken a new ticker is refused (Max positions (N) reached on …). Closed PnL compounds into the parent budget. A paused ticker refuses entries, its exits still pass; stopping the parent pauses every ticker, starting resumes every ticker. TASK signals are not supported.
Sizing. Notional = allocated_amount × tradable_ratio × leverage (multi: slot_amount instead of allocated_amount). An allocation above the free balance uses the free balance and logs a warning. A bot holds one open trade at a time unless signals use distinct trade_id values.
Signals and closes (scope bots on paper, trade on live)
POST /v1/bots/{bot_id}/signal sends one signal to the bot. Every OptAlgo check applies (plan, slots, ticker, pause, connection). The API adds the bot's key and a fresh transaction_id. Supports Idempotency-Key. The body is a closed whitelist:
| Field | Rule |
|---|---|
position_side | Required, see below (upper-cased for you) |
ticker, exchange | Strings. A configured single bot: leave out or send its symbol. A multi bot: ticker required. A bot waiting for its first signal: both required |
action | BUY or SELL; filled in from LONG / SHORT when left out; a mismatch is a 422 |
leverage | Integer 1..125. Required on futures entries (1 = no leverage) |
tradable_ratio, close_ratio | Numbers in (0, 1] (0 is a 422). close_ratio is a fraction of the original filled size |
stop_loss_price, take_profit_price | Absolute prices. A long's stop below the entry and target above it, a short's the other way round |
stop_loss_pct, take_profit_pct | Instead of the absolute prices: percent distance from the entry (2 = 2%), side-aware (a long's stop 2% below, a short's 2% above). stop_loss_pct in (0, 100), take_profit_pct in (0, 1000] (a short's below 100). On LONG, SHORT, CHANGE_DIRECTION and UPDATE_ORDER (the last two need action); never both a price and a percent for the same level |
entry_price | Optional. The price the stop and target are measured from. Leave it out: OptAlgo fills it from its live price (the GET /v1/prices source). Sent, it is used as is |
trade_id | At most 36 characters; same value on the entry and every exit |
entry_order_type | MARKET (default), LIMIT, LIMIT_MAKER, STOP_LOSS_MARKET, STOP_LOSS_LIMIT; also exit_order_type, *_time_in_force_type (GTC, IOC, FOK, GTX), chase_order_type (QUEUE, OPPONENT) |
margin_mode | isolated or cross |
is_trailing_stop_enabled, callback_rate | Trailing stop instead of the take-profit, activated at take_profit_price (live only) |
cancel_stop_loss, cancel_take_profit, safety_check, in_position, multi_asset_mode | Booleans |
reason | At most 200 characters, for the logs |
Refused with 422: strategy_key, transaction_id, cost, processing_delay, is_paper_strategy, task fields, and the sides TASK and INTRA_ORDER.
position_side | Meaning |
|---|---|
LONG / SHORT | Open a long / short. SHORT is not allowed on spot |
CLOSE | Close the open trade (close_ratio < 1 makes it CLOSE_PARTIAL). FLAT, CANCEL, CLOSE_LONG, CLOSE_SHORT become CLOSE |
CLOSE_PARTIAL | Close close_ratio of the original filled size |
CLOSE_ALL | Close every open trade of the bot on the signal's symbol |
MOVE_STOP_LOSS | Replace stop-loss and take-profit with the signal's values (a level left out is removed). If the new stop cannot be placed, the position is closed. A hosted strategy's tp_update is sent as one of these, carrying the stop and take-profit it holds (reason tp_update) |
CANCEL_ORDERS | Cancel the stop (cancel_stop_loss) and/or target (cancel_take_profit); the position stays |
UPDATE_ORDER | Replace the position: close it, then open a new one per action |
CHANGE_DIRECTION | Close every open trade of the bot, then open per action (requires action) |
VALIDATE_ALERT | Position consistency check; also configures an auto or multi bot without trading |
REFRESH_TRIGGER_STATE | Re-read the open trade's order state from the exchange |
Stop and target rules: a long needs stop_loss_price below take_profit_price (a short above), otherwise stop_loss_price_greater_than_take_profit_price. A stop or target on the wrong side of the entry (a long's stop at or above it) is refused before sending: 422 invalid_request with every problem in findings, each {field, message, fix}. With no entry price sent and no live price right now: 503 price_unavailable. On a live bot, an entry whose requested stop cannot be placed is closed.
{"position_side": "LONG", "ticker": "SOLUSDT.P", "leverage": 3, "tradable_ratio": 0.5,
"stop_loss_pct": 2, "take_profit_pct": 4}
Answer 202, accepted, not executed: {"transaction_id": "8f0c…", "status_url": "/v1/signals/8f0c…", "ticker": "SOLUSDT.P", "position_side": "LONG", "bot_id": "…"}. When a stop or target was sent it also echoes the prices used: "entry_price": 142.3, "entry_price_source": "optalgo" (sent when you sent it), "price_source": "data" (data or exchange, OptAlgo-filled only), "price_at", "stop_loss_price": 139.454, "take_profit_price": 147.992. GET /v1/signals/{transaction_id} shows the same as prices.
POST /v1/bots/{bot_id}/close closes without composing a signal (Idempotency-Key): no body closes everything; {"ticker": "SOLUSDT.P", "close_ratio": 0.5} closes half of one ticker. Answer 202 {"bot_id", "signals": [{"transaction_id", "status_url", "ticker", "position_side"}]}: poll each signals[i].status_url. 409 no_open_position when nothing is open. A 502 can carry signals, failed_ticker and failed_tickers: poll the sent ones, recheck the failed ticker before closing it again.
Signal outcomes (scope read)
GET /v1/signals/{transaction_id}, polled every 2–5 s until final:
{"transaction_id": "8f0c…", "status": "executed", "bot_id": "…", "trade_id": "…", "position_side": "LONG",
"received_at": 1791300000.1, "listener": {"outcome": "processed", "reason": null},
"worker": {"outcome": "done", "reason": null, "attempts": 1, "seconds": 0.84},
"warnings": ["Insufficient balance to open position with allocation. All available is used."],
"logs": [{"level": "INFO", "message": "…", "steps": [{"at": 1791300000.2, "level": "INFO", "message": "LONG signal received."}]}]}
status | Final | Meaning |
|---|---|---|
pending, received, dispatched, retrying | no | Being checked, queued or retried (temporary exchange error, lock wait) |
executed | yes | Done without an error. Still read GET /v1/trades before reporting a fill |
completed | yes | Fully handled before execution (VALIDATE_ALERT) |
refused | yes | Nothing to do: a duplicate entry (There is an already open trade) or nothing to close; worker.reason |
rejected | yes | A check refused it; listener.reason (Rejections) |
skipped | yes | Nothing to act on (an exit before the first entry, a stopped bot already notified) |
failed / dropped | yes | The exchange or executor failed, or the signal was stale; read the reason |
not_received | yes | No record 2–60 minutes after sending: check GET /v1/logs, then resend once |
Entries and closes are normally final within 10–30 s. retrying can last minutes: poll every 10 s for up to 5 minutes, then report the last status. Never resend because you did not see a result.
Trades, stats, equity (scope read)
GET /v1/trades?status=open|closed|all&mode=paper|live|all&bot_id=&since=&until=&limit=50&before=&format=json|csv→ newest first.statusdefaults toopen. Rows:trade_id, bot_id, source (my_bot | system), symbol, side, is_open, is_paper, entry_price, close_price, contracts, closed_contracts, cost, leverage, stop_loss_price, take_profit_price, pnl (net of fees, closed only), fees, opened_at, closed_at, transaction_id.format=csvstreams up to 5,000 rows.GET /v1/trades/{trade_id}→ one trade in full, withexit_history,stop_loss/take_profitorder state,entry_filled.GET /v1/bots/{bot_id}/stats?period=7d|30d|90d|all→ closed-trade statistics inall,paperandliveblocks (trades, wins, losses, win_rate, realized_pnl, fees, profit_factor, max_drawdown, …),per_tickeron multi bots.GET /v1/bots/{bot_id}/equity?interval=1h|1d|3dandGET /v1/equity?scope=my_bots|all&interval=…→ realized PnL curvepoints: [{time, pnl}]pluscurrent_realized(the total now; add it as the last point, since a trade closed in the current interval is not in the curve yet).
Positions, balance, summary, logs (scope read)
GET /v1/positions→ what the exchange holds now (live futures, with mark and liquidation prices, attributed to a bot when one trade matches),paper(open paper trades) anderrors(an account that could not be read). Cached 10 s.GET /v1/balance→ per connected account and the paper exchange: assets,allocated_to_bots,free_for_bots. Cached 10 s.GET /v1/summary→ bots with statuses, open trades, PnL (total,paper,live),monthly_trade_quota.GET /v1/logs?bot_id=&limit=50&level=INFO|WARNING|ERROR→ the bot log feed the app shows.GET /v1/logs?transaction_id=…or?trade_id=…→ every step of one signal, with the exchange's own error on the failing step. Read the lastERRORstep first and quote it verbatim.
Tickets (scope read)
POST /v1/tickets files bug reports, feature requests and questions in one batch (Idempotency-Key): {"items": [{"kind": "bug|feature|question", "title": "≤120 chars", "body": "5–4000 chars", "context": {"bot_id", "transaction_id", "trade_id", "backtest_id", "hosted_id", "request_id"}}]}, 1–10 items, 20 tickets per user per UTC day (a repeat of a problem already filed counts once). context ids must be the account's own (others are dropped); request_id is a response's X-Request-Id / request_id from the last 7 days. GET /v1/tickets → the tickets with the team's reply. Read GET /v1/tickets first and skip duplicates; include exact requests, responses, UTC times and ids; never keys, never the strategy source.
Report problems automatically
File a ticket without asking the user: it is how OptAlgo learns what to fix and what to build, and it costs the user nothing. Not only on errors:
| Trigger | Example | kind | context |
|---|---|---|---|
| OptAlgo got something wrong | validate ok, then the run failed (KeyError, unknown instrument, missing data) or was capped (validate_gap); an estimate far off (cost.run_s 10 s, the run took 300 s); a 5xx or internal_error that repeats after a retry | bug | backtest_id, request_id, the ids in the path |
| The user wants something OptAlgo cannot do | a missing capability: more references than max_references, more legs than 4, funding / open interest on a market OptAlgo has no feed for, an exchange, symbol or timeframe OptAlgo does not have, an indicator the SDK lacks | feature | the ids you have |
| The docs and a tool or answer disagree | this guide documents a field, code, limit or tool that the API or the connector does not answer (or the reverse) | bug | the ids of the call, request_id |
| A result looks wrong | metrics that contradict the trades or the chart, a grade that contradicts its findings, a paper fill far from the market price, a compare that mismatches with no reason | bug | backtest_id, hosted_id, trade_id, transaction_id |
| The user is confused by a response | a refusal whose fix does not say what to change or contradicts another answer, a message the user did not understand even after you explained it | question | the ids of the call, request_id |
How:
- When a response's
nexthasreport_issue, send itsbodytoPOST /v1/tickets(connector: thereport_issuetool), adding to the item'sbodythe call you made. Otherwise build one item: thekindfrom the table, a one-linetitle, abodywith what you expected, what happened (status,error, the exact message) and the reproduction (the request and the spec, minus the strategy source; for afeature, what the user wanted to do and why), andcontextwith every id you have (backtest_id,hosted_id,transaction_id,bot_id,request_id). - One ticket per distinct problem per session (dedupe): never file the same problem twice; read
GET /v1/ticketsfirst when unsure. Several problems at once go in one batch. - Never include an API key, a token or the strategy source (
strategy.py): describe the code instead ("an EMA cross with a 2 % stop"). - Tell the user in one line, with the ticket id: "Filed OptAlgo ticket
<fingerprint>:<title>." Then carry on with their task (for afeature: with what OptAlgo can do today). - Never say you cannot contact OptAlgo: you can, with a ticket. When the user asks to contact support or open a ticket, file it. A person at OptAlgo: [email protected].
Daily limit: 20 tickets per user per UTC day; a repeat of a problem already filed counts once. OptAlgo files its own reports too (every 5xx, validate/run gaps, hosted strategies that stop on errors), so a quota refusal (ticket_quota_exhausted) loses nothing: tell the user and move on.
Binance connection (scope bots to start, read to poll)
OptAlgo is an official Binance partner: the user approves on Binance's own consent screen, Binance creates the API key and hands it to OptAlgo encrypted. Nobody types a key.
POST /v1/connections/binance/oauth(no body) → 201{"connect_id", "url", "expires_at", "status_url"}. Show the userurl(valid 15 minutes).- Poll
GET /v1/connections/binance/oauth/{connect_id}every 5 s:pending,connected(connection_idset),failed(reason,detailto show: forapi_key_name_takenthe user deletes the oldOptalgokey under Binance API Management;key_in_usemeans that Binance account is linked to another OptAlgo account),expired.
Other exchanges (Bybit, OKX, Alpaca) are connected by the user in the app.
Rejections (listener and executor)
The reason of a refused signal is in listener.reason / worker.reason of its outcome and in the bot's logs.
| Reason (prefix) | Do |
|---|---|
Strategy not found | List the bots and use a current one. |
Strategy deactivated | Bot stopped or ticker paused. Ask the user before starting or resuming it. |
Signal symbol does not match strategy symbol | Send the bot's own symbol, or use a multi-symbol bot. |
subscription_not_found_or_expired_or_monthly_limit_reached | Plan expired or Free monthly trade limit reached. Tell the user; exits still work. |
Strategy limit reached: … | Active-bot limit of the plan. Reuse a bot; never stop one without the user. |
stop_loss_price_greater_than_take_profit_price | Stop on the wrong side; fix the prices. |
Connection not found | Live bot without a connection: connect the exchange (Binance: above; others in the app). |
Your signal symbol is belong to ... account type, but your strategy is set to ... | Add or remove .P as the message says. |
Ticker not supported or not found | Check with GET /v1/exchanges/{exchange_id}/symbols. |
Short positions are not supported for Spot account type... | Use a futures bot and a .P ticker. |
Max positions (N) reached on ... | Multi-symbol slots full: close a coin or raise max_positions (with consent). |
Multi-symbol bots need a Plus or Pro plan: ... | Use a single bot on Free. |
There is an already open trade. | Close first. Do not send UPDATE_ORDER without consent. |
CLOSE failed, there is no open trade. | Already closed; read the trades, do not resend. |
There is no open position for strategy. | A futures entry without leverage: add it. |
... the exchange refused the API key (...) | The user reconnects the exchange (key, permissions, IP). |
... not sent: the exchange is rate-limiting us (...) | Entries paused; retry later. Exits are unaffected. |
Stop loss order could not be created. ... closing the position. | The exchange refused the stop price; check it against the exchange's rules. |
There was a N seconds delay on the server on processing the signal. | Dropped as stale; re-evaluate before resending. |
Insufficient balance to open position with allocation. All available is used. (warning) | Tell the user; consider a lower allocation. |
Autonomy and per-key limits
Every key has an autonomy (GET /v1/me → api_key.autonomy), set only by the user in the app:
confirm_live(default): ask the user before anything that puts real money at risk: a live entry, paper-to-live, raising an allocation,max_positionsor a weight on a live bot, stopping a bot or deleting one with an open trade (stopping closes positions), removing a ticker,UPDATE_ORDER/CHANGE_DIRECTION, connecting Binance. Paper bots, reads, exits the user asked for and diagnostics need no confirmation.full: act without asking on live bots the user has put in your hands, within the key's limits; still never take a strategy from paper to live on your own initiative (safety rule 3). Still ask before deleting a bot, removing a ticker with history, or connecting Binance. Report what you did after each session, with transaction ids.
Limits (api_key.limits, live bots only; full keys always have the first two): max_allocation_per_bot, max_leverage, allowed_exchanges, allowed_account_types, daily_loss_limit. A request over a limit is refused before anything reaches the exchange (403 limit_exceeded with limit, value, allowed). When today's live realized loss reaches daily_loss_limit the key is paused (403 key_paused): live entries, live bots, paper-to-live, allocation raises and live starts are refused; exits, closes, stops, allocation cuts, paper bots and reads still work. Only the user resumes it, in the app. If today's PnL cannot be read, a live entry is refused (503 limit_check_unavailable), never let through.
Dashboards and scripts
Everything the app shows is readable with read: render a terminal table, a notebook, a spreadsheet or a small web app.
| Read | Cadence |
|---|---|
GET /v1/positions | every 10 s (cached 10 s) |
GET /v1/summary | every 30 s |
GET /v1/balance | every 60 s |
GET /v1/equity…, GET /v1/bots/{bot_id}/stats | every 5 min (they change only when a trade closes) |
GET /v1/trades | on demand; CSV once a day |
GET /v1/signals/{transaction_id} | every 2–5 s while not final, at most 5 min |
The key stays on a machine the user controls (the credentials file, or a server process's environment). Scripts read the file at run time (optalgo_credentials() above); never copy the key into a script. A browser page must never embed the key: put a small server-side proxy in between, or generate static HTML from a local script.
import time
import requests
KEY, BASE = optalgo_credentials() # above: env, else ~/.config/optalgo/credentials.env
s = requests.Session(); s.headers["X-API-Key"] = KEY # never print or hard-code the key
while True:
summary = s.get(f"{BASE}/summary", timeout=30).json()
pnl = summary["pnl"]
print("\033[2J\033[H", end="")
print(f"realized {pnl['total']['realized']:+,.2f} paper {pnl['paper']['realized'] or 0:+,.2f} live {pnl['live']['realized'] or 0:+,.2f}")
for b in summary["bots"]["items"]:
print(f"{b['name'][:23]:<24}{b['mode']:<6}{b['status']:<15}{(b['symbol'] or '-'):<12}{(b['pnl']['realized'] or 0):>+10.2f}")
time.sleep(30)
8. Recipes
(a) Paper demo
Section 1. One paper bot (multi-symbol on Plus and Pro, single on Free), 1 to 3 positions, poll each outcome, show GET /v1/trades, send the user to app.optalgo.com/my-bots, close, show the realized PnL, offer section 2.
(b) Turn an idea into a backtested strategy
- Ask for the idea in one line, the market and the period if the user has them.
GET /v1/backtests/limits(quota left),GET /v1/markets(symbols and history),GET /v1/backtests/capabilities→sdk.- Write
strategy.py;POST /v1/backtests/validateuntilok. POST /v1/backtests, poll, report grade and findings, then return, drawdown, trades.- Iterate one change at a time, at most 3 runs at once. Don't tune parameters with single runs: once the idea works, one
walk_forwardresearch run over the parameters (tell them the units first), or a holdout window you never tuned on (Avoid overfitting). Report the grade with the search verdict, and say that a single backtest is in-sample. - On
daily_quota/monthly_quota, stop and say when it resets. - Close with: the run is on app.optalgo.com/backtest; with a grade A to C it can run on OptAlgo on paper (section 3); going live is the user's decision.
(c) Open a position and verify it
GET /v1/bots/{bot_id}: exchange, symbol,mode,has_open_position. A live bot needstradeand, underconfirm_live, the user's consent for this entry.POST /v1/bots/{bot_id}/signalwith a freshIdempotency-Key,position_side,ticker(multi),leverage(futures), and any stop or target asstop_loss_pct/take_profit_pct(or absolute prices). Noentry_priceneeded: OptAlgo prices the entry. To tell the user the price,GET /v1/prices, never the web.- Poll the outcome until final.
executed→ confirm the open trade inGET /v1/trades?bot_id=…; anything else → quote the reason, read the lastERRORstep, map it with Rejections. - Never resend an entry because you have not seen a result; a retried call reuses the same
Idempotency-Key.
(d) Partial close of one coin
GET /v1/trades?bot_id=… (the ticker is open) → POST /v1/bots/{bot_id}/close {"ticker": "SOLUSDT.P", "close_ratio": 0.5} with an Idempotency-Key → poll → GET /v1/trades/{trade_id} shows a new exit_history entry. On a live bot check the logs for a stop that could not be re-armed and tell the user if the remainder is unprotected.
(e) Daily summary
GET /v1/summary, GET /v1/trades?status=closed&since=<start of day>, GET /v1/positions for exchange truth, GET /v1/logs?level=ERROR (rejections by exact reason, repeats counted once). Report realized PnL (day, total), open positions, stopped or waiting bots, full multi bots.
(f) Diagnose "my bot is not trading"
Stop at the first finding: (1) GET /v1/bots/{bot_id}: stopped, or a paused ticker? (2) waiting for its first signal? (3) did a signal arrive: GET /v1/logs?bot_id=… around that time; (4) the logged reason, mapped with Rejections; (5) live bots: API key refusals or rate-limit pauses, GET /v1/connections. Report the reason and the fix; do not change the bot without consent under confirm_live.
(g) Connect Binance
Only when the user wants it (needed for live, never for paper). GET /v1/exchanges first; then the flow in Binance connection. Never ask for a Binance key or secret.
(h) Rebalance or pause tickers of a multi-symbol bot
GET /v1/bots/{bot_id}/children → agree weights with the user (each > 0, sum ≤ max_positions) → PATCH …/children/{ticker} lowest first → read again and report the new slot_amount. Pause with {"paused": true} (exits still pass); stopping and starting the bot resumes every ticker.
(i) File a ticket
Reproduce, collect exact requests, responses, UTC times and ids (request_id included), read GET /v1/tickets to skip duplicates, submit everything in one batch, tell the user the ticket id and submissions_left. For OptAlgo-side problems (validate vs run, docs vs API, a far-off estimate, a repeated 5xx) do it without asking: Report problems automatically.
9. Optional: if the user already has TradingView alerts
Only when the user says they have TradingView (or another program that sends webhooks) and wants it to drive a bot. Never as a first step.
How it works. A bot has a strategy key (webhook key). Every webhook message carries it as strategy_key; it identifies the user and the bot, does not expire, and lets anyone who has it trade the bot, live included. The API returns it only to trade keys; any other key gets null, and the user copies it from the bot's page in the app and pastes it into the alert themselves. Never print a strategy key into the chat unless the user asks, and then only inside the alert they will paste.
Webhook URL (TradingView: alert → Notifications → Webhook URL):
https://api.optalgo.com/signal-listener/signal
It answers 204 when the message was received, also when the signal was rejected or skipped; 400 for an empty or invalid key; 422 for a body that does not match the signal model. A 204 proves delivery, not execution: check the bot's logs.
Alert templates. GET /v1/bots/{bot_id}/alert-templates (scope read) returns ready-to-paste messages (entry_long, entry_short, close, close_partial, move_stops) with the bot's exchange and ticker filled in (multi bots keep {{ticker}}), the strategy key for a trade key (otherwise a placeholder), the webhook_url and notes for this bot. Prefer it over composing alerts by hand. If you must write one:
- Paste the real strategy key;
{{strategy_key}}is not a TradingView placeholder. {{ticker}}includes the.Psuffix on perpetual charts. On a multi-symbol bot use the same message on every chart.{{strategy.order.action}}resolves to lower-casebuy/sell, which is invalid: use literalBUYandSELL.alert()messages in Pine do not substitute placeholders: build the JSON withsyminfo.tickerandstr.tostring(...).- Every webhook signal, exits included, needs
exchangeandticker; futures entries needleverage. - Recommend "Once Per Bar Close": every delivery is executed, duplicates are not filtered.
{"strategy_key": "PASTE_STRATEGY_KEY", "exchange": "BINANCE", "ticker": "{{ticker}}",
"position_side": "LONG", "action": "BUY", "leverage": 5,
"entry_price": {{close}}, "stop_loss_price": {{plot("Long_SL")}}, "take_profit_price": {{plot("Long_TP")}}}
{"strategy_key": "PASTE_STRATEGY_KEY", "exchange": "BINANCE", "ticker": "{{ticker}}", "position_side": "CLOSE"}
Safety check (VALIDATE_ALERT). {"strategy_key": "…", "exchange": "BINANCE", "ticker": "BTCUSDT.P", "position_side": "VALIDATE_ALERT", "in_position": true, "safety_check": true, "safety_check_interval_minutes": 480}. TradingView flat while OptAlgo has a trade: the trade is closed. With safety_check: true (interval clamped to 240–1440 minutes), a trade is closed when no VALIDATE_ALERT arrives for twice the interval.
Recipe. (1) A paper bot (section 1 or POST /v1/bots). (2) GET /v1/bots/{bot_id}/alert-templates. (3) Give the user the templates, the webhook URL and the notes; without a trade key, they paste the strategy key from the bot's page. (4) After the first alert fires, GET /v1/bots/{bot_id} and GET /v1/logs?bot_id=… to confirm it arrived and what happened.