# AGENTS.md — NexusTrade TypeScript SDK
Instructions for coding agents (Claude Code, Cursor, Codex, and friends) writing
NexusTrade strategies with this package. Humans: [README.md](README.md) is the
friendlier read.
## What this package is
A typed client plus ~170 **generated** builders for authoring trading
strategies. The builders are generated from the engine's indicator specification.
They describe draft payloads; the API still validates complete portfolios and
their conditions. A builder's existence does not guarantee support for every
trading method. Read the [option selection and execution limits](README.md#option-selection-and-execution-limits)
before claiming exact option timing, expiration selection, or rolling behavior.
```
author a portfolio → submit a job → poll until terminal → read result
```
## Setup
```bash
npm install nexustrade
export NEXUSTRADE_API_KEY=sk-...
export NEXUSTRADE_API_BASE_URL=https://nexustrade.io/api/v1
```
```ts
import { NexusTradeClient } from "nexustrade";
const client = new NexusTradeClient(); // reads the environment
```
Keys come from https://nexustrade.io/developers. Never hardcode one into a file
you write; read it from the environment. Node 18+.
## Rules that matter
**1. Use the builders. Never hand-write the JSON.**
```ts
// Right — validated shape, correct wire names
nt.buy(nt.stockAsset("SPY"), 100);
// Wrong — silently diverges from the engine's schema
{ type: "Buy", targetAsset: { symbol: "SPY" }, amount: 100 };
```
The client accepts both a builder result and a plain object, so a wrong literal
will typecheck. Prefer the builder.
**2. Comparisons are functions, not operators.**
TypeScript cannot overload `>`, so indicator comparisons go through helpers.
This is the single most common mistake in this SDK.
```ts
// Right
nt.filter(nt.gt(nt.Price(nt.CANDIDATE), nt.SMA(nt.CANDIDATE, 200)));
// Wrong — compares object references, always nonsense
nt.filter(nt.Price(nt.CANDIDATE) > nt.SMA(nt.CANDIDATE, 200));
```
Available: `gt` `gte` `lt` `lte` `eq` `neq`, combined with `and` / `or`.
**3. Every mutation needs an idempotency key, and it must be deterministic.**
Jobs cost money. A retry with the *same* key returns the original operation; a
retry with a new key launches a second paid job.
```ts
// Right — same logical run reuses the key across retries
await client.createBacktest(handle, { idempotencyKey: "momentum-2024-v1" });
// Wrong — every retry is a new billable job
await client.createBacktest(handle, { idempotencyKey: `run-${Date.now()}` });
```
Reusing a key with a *different* payload is a `409 idempotency_conflict`. Version
the key when the request changes: `momentum-2024-v2`.
**4. `create*` does not wait. Poll.**
```ts
const operation = await client.createBacktest(handle, { idempotencyKey: "k" });
// operation.result is ABSENT here — the job has not run yet.
const finished = await client.waitForBacktest(operation.id as string);
console.log(finished.result);
```
A timeout does not cancel the job. Call the waiter again with the same id;
do not resubmit.
**5. Batch when you have several.**
```ts
const operations = await client.createBacktests([h1, h2, h3], {
idempotencyKey: "sweep-v1",
});
const results = await client.waitForBacktests(operations);
```
One request, one key, one rate-limit slot — instead of three of each.
**6. Percent semantics.** `buy(asset, 100)` is **100% of portfolio**, not 100
shares. Deployment and allocation parameters are percentages unless a builder
says otherwise.
**7. Credentials come from the environment, or a `.env` file.** Both
`NEXUSTRADE_API_KEY` and `NEXUSTRADE_API_BASE_URL` are read from `process.env`
first, then from a `.env` at or above the working directory — no `dotenv`
dependency and no `--env-file` needed. Never hardcode a key into a file you
write, and never log one. Exported values win over the file.
**8. Responses are `JsonObject`.** Fields come back typed as `JsonValue`, so
narrow before use (`operation.id as string`). This is deliberate: the envelope is
whatever the API returned, not a promise the SDK can statically make.
**9. Your own data belongs in ONE series.** `createCustomIndicator` mints a new
series every time it is called with a fresh idempotency key. Recurring
collection must `appendCustomIndicatorPoints` onto the id it created the first
time — a new series per run splits the history into fragments no strategy can
read. Persist the id; never re-create by name.
```ts
// Right — one series, appended forever
await client.appendCustomIndicatorPoints(seriesId, todaysPoints, {
idempotencyKey: `mentions-${today}`,
});
// Wrong — a new, disconnected series every run
await client.createCustomIndicator(
{ name: "Mentions", points: todaysPoints },
{ idempotencyKey: `mentions-${today}` },
);
```
Point batches are unlimited in size; the SDK sends them inline or uploads them.
Do not chunk by hand.
Declare `pointKind: "observation"` for point-in-time samples so date-only rows
retain same-day UTC availability on both inline and large-upload paths. Use
`period_aggregate` plus `aggregatePeriod` for closed periods, or `disclosed`
with per-row publication times.
`client.listOrders({ portfolioId, statuses, page, limit })` lists owned orders with a read key. `client.cancelOrders(orderIds, { idempotencyKey, portfolioId })` cancels explicit IDs with a trade key. Inspect both `canceled` and `rejected`, and reuse the same key/payload for retries. Defaults and status gates are documented in README.
## Recipes
Buy and hold
```ts
import * as nt from "nexustrade";
const book = nt.portfolio("Buy and hold SPY", [
nt.strategy("Buy", nt.always(), nt.buy(nt.stockAsset("SPY"), 100)),
]);
```
Condition on an indicator
```ts
const aapl = nt.stockAsset("AAPL");
const oversold = nt.lt(nt.RSI(aapl, 14), 30);
const book = nt.portfolio("Dip buyer", [
nt.strategy("Buy the dip", oversold, nt.buy(aapl, 25)),
nt.strategy(
"Take profit",
nt.gt(nt.PositionPercentChange(aapl), 10),
nt.sell(aapl, 100),
),
]);
```
Combine with `nt.and`, `nt.or`, `nt.atLeast`, `nt.atMost`, `nt.exactly`.
Sequence two events, and freeze a level at entry
`nt.andThen(length, interval, ...conditions)` fires when the LAST condition is true
now and the one before it was true at a **strictly earlier** tick inside the
window. `nt.and(...)` is the simultaneous form. The interval is required and has
no default, because a silent `Day` fallback kills an intraday setup.
`nt.IndicatorAtEntry(operand, asset, side?)` freezes what `operand` read at the
most recent filled entry. A rolling window keeps moving, so a stop written
straight against `nt.MinimumPrice(spy, 5, "Minute")` is a **trailing** stop and
the R-multiple measured off it is measured against a moving risk.
```ts
const spy = nt.stockAsset("SPY");
const entry = nt.LastOrderPrice(spy, "Buy", "Filled");
const stopLevel = nt.IndicatorAtEntry(nt.MinimumPrice(spy, 5, "Minute"), spy, "Buy");
const book = nt.portfolio("Break and hold", [
nt.strategy(
"Red 15m candle, then a break of its high",
nt.and(
nt.eq(nt.PositionValue(spy), 0),
nt.andThen(
30,
"Minute",
nt.lt(nt.IndicatorWindowAgo(nt.PriceRateOfChange(spy, 15, "Minute"), 15, "Minute"), 0),
nt.gt(
nt.CrossAbove(
nt.Price(spy),
nt.IndicatorWindowAgo(nt.MaximumPrice(spy, 15, "Minute"), 15, "Minute"),
),
0,
),
),
),
nt.buy(spy, 100, "percent of buying power"),
),
nt.strategy(
"Stop under the low that was there at entry",
nt.and(nt.gt(nt.PositionValue(spy), 0), nt.lt(nt.Price(spy), stopLevel)),
nt.sell(spy, 100, "percent of current positions"),
),
nt.strategy(
"Take profit at 2.5R off the risk actually taken",
nt.and(
nt.gt(nt.PositionValue(spy), 0),
nt.gte(
nt.Price(spy),
nt.Plus(entry, nt.Multiply(nt.Value(2.5), nt.Minus(entry, stopLevel))),
),
),
nt.sell(spy, 100, "percent of current positions"),
),
]);
```
The stop and the target now reference the same frozen number, so the reward is
measured against the risk actually taken. Scalars are `nt.Value(2.5)` — the
arithmetic builders take indicators on both sides.
`IndicatorAtEntry` reads order state, so a strategy using it cannot be
materialised columnar. `nt.LastOrderPrice` already carries that cost, but it is
a real reason not to reach for either casually.
Rank and rotate a universe
`CANDIDATE` is the placeholder for "each name being evaluated". Use it inside a
pipeline; use a concrete asset outside one.
```ts
const book = nt.portfolio("Momentum", [
nt.strategy("Rotate", nt.always(), nt.dynamicRebalance({
universe: nt.universe("SP500"),
pipeline: [
nt.filter(nt.gt(nt.Price(nt.CANDIDATE), nt.SMA(nt.CANDIDATE, 200))),
nt.selectTop(nt.RSI(nt.CANDIDATE, 14), 10),
],
weightIndicator: nt.RSI(nt.CANDIDATE, 14),
limit: 10,
deploymentPercent: nt.Value(80),
})),
], { initialValue: 100_000 });
```
Note the key is `universe`, not `universeConfig` (the Python SDK spells it
`universe_config`). `deploymentPercent: nt.Value(80)` invests 80% of the portfolio across
the selection and leaves the rest in cash — a **total** cap, not per-name.
Backtest, optimize, walk forward
```ts
const bt = nt.backtest(book, { startDate: "2024-01-01", endDate: "2024-12-31" });
const opt = nt.optimization(book, {
startDate: "2022-01-01",
endDate: "2024-12-31",
});
const wf = nt.walkForward(book, {
globalStartDate: "2022-01-01",
globalEndDate: "2024-12-31",
foldCount: 4,
});
```
Walk-forward uses `globalStartDate` / `globalEndDate` / `foldCount`, not
`startDate` / `endDate`. Each handle goes to its matching `create*` + `waitFor*`
pair.
Screen stocks in plain language
Market data is available only through the natural-language screener.
```ts
const screen = await client.createNlScreen(
"technology stocks with a market cap over 100 billion and a PE under 30",
);
const done = await client.waitForNlScreen(screen.id as string);
const result = done.result as Record;
console.log(result.outcome, result.rows);
```
Branch on `result.outcome`. `EMPTY` is an answer, `CLARIFICATION` means the
question was ambiguous (answer it rather than guessing), and only
`GENERATION_FAILED` is worth retrying. Spends LLM credits.
Run an agent
Agents are the one job kind that is NOT fire-and-poll. Three states —
`pending_plan_approval`, `pending_action_approval`, `awaiting_user_input` — are
ones the run cannot leave on its own, so the caller is the approver.
```ts
const run = await client.createAgent("Find momentum names in the S&P 500", {
idempotencyKey: "momentum-scan-v1",
});
for await (const event of run) {
console.log(event.text);
if (event.needsApproval) await run.approve(); // or run.reject()
else if (event.needsInput) await run.say("focus on semis");
}
```
Iterating waits. If you never answer a blocked run, iteration throws
`agent_awaiting_input` rather than spinning silently — the run keeps going
server-side, so reattach with `client.attachAgent(run.id)`.
Approving can place orders, so it needs the `trade` scope; everything else
needs `write`. Agent runs are unavailable to `run_compute` sandbox code.
## Errors
All failures throw `NexusTradeApiError` with a stable `.status`, `.code`, and
`.message`. Branch on `.code`, never on message text.
| Code | What to do |
| --- | --- |
| `invalid_token` | Key missing/expired, or an OAuth JWT was used. Only `sk-` keys work here. |
| `insufficient_scope` | The key lacks the required scope. Do not retry. |
| `invalid_portfolio` | The book is malformed — fix the builders, do not retry as-is. |
| `idempotency_conflict` | Same key, different payload. Version the key. |
| `idempotency_in_progress` | Same key, first call still running. Wait and re-read; never resubmit. |
| `rate_limit_exceeded` | Back off and retry. |
| `operation_timeout` | Job still running. Re-poll the same id; never resubmit. |
`status === 0` means no HTTP status applies: the request never reached the API
(`transport_error`), or the reply failed an envelope check.
## What is and is not here
**Deploying a portfolio IS supported.** `book.save(...)` persists it and
`book.deploy(...)` starts paper trading it; `client.deploy(portfolioId)` does
the same from an id. `save` and `deploy` return *different* ids — deploying
mints a portfolio rather than converting the draft.
**`deploy` is not always paper.** A portfolio this SDK creates is always paper:
the portfolio spec has no deployment field, so there is no way to ask for a
live one. But `deploy(portfolioId)` accepts the id of a portfolio that is
*already deployed*, and then it reactivates that portfolio as whatever it
already is. Hand it the id of a paused **live** portfolio — `listPortfolios`
will return one under `includeLive: true` — and it resumes live trading against
the connected brokerage. `undeploy` is the same in reverse. Read
`deploymentType` on the response to know which one you got, and treat any id
you did not create in this session as possibly live.
Not in this SDK. Do not attempt to reach them through it:
- **Submitting a live order** — impossible from anywhere, not just here. Live
orders are staged `PENDING_USER_APPROVAL` and a human approves them in the
UI; the brokerage boundary refuses an unapproved live order regardless of
caller. `createOrders` stages them, it does not send them.
- **Minting a live portfolio, and connecting a brokerage** — both happen in the
web app. No route under the SDK prefix creates a live deployment; see above
for reactivating a live portfolio that already exists.
The complete method list — every client and handle method, including the ones
without a worked example above — is the **Complete method reference** table in
[README.md](README.md#complete-method-reference). A test fails if any public
method is missing from it, so it is exhaustive by construction rather than by
maintenance.
## Verifying your work
```ts
// Assemble the book and inspect the JSON before spending money on a backtest.
console.log(JSON.stringify(book, null, 2));
```
If you are editing this repository rather than consuming it:
```bash
npm run typecheck && npm test
```