# Strategies

Write, test, and deploy trading bots. Save strategy drafts as versions, run behaviour examples and backtests, propose and deploy bots, stop them and return their funds, and publish, browse, fork, and report community strategies.

`client.strategies` writes, tests, and deploys trading bots of the caller's main account. A strategy holds a bot's drafts as numbered revisions, and each save stores an immutable version (a manifest and its code). A bot goes through these steps:

1. Start a strategy with `create`, blank or from a template, and save drafts with `saveDraftVersion`.
2. Run the version's behaviour examples with `runScenarios`, and backtest it with `startBacktest`.
3. Record a deploy proposal with `proposeDeploy`. The user deploys it with `deployBot` from their own MFA-elevated session, which creates the bot's subaccount, funds it, and starts the bot.
4. Read the bot with `getBot` and `listBotLogs`, stop it with `stopBot`, and move what is left back to the main account with `returnBotFunds`.

A strategy can also be published as a community listing that anyone can read and fork.

IDs of strategies, backtests, proposals, bots, listings, and fund returns are base58 public IDs. A `versionId` is an opaque string. Revisions are decimal strings, starting at `"1"`. Amounts are exact decimal strings in `{ asset, amount }` pairs, and times are epoch milliseconds, `null` when unset. Errors carry `detail: { service: "strategies", code }`, and a `ServiceUnavailableError` is safe to retry unchanged. Tree-shaken builds reach the same service with `strategiesService(core)` from `@polyester/sdk/services/strategies`.

## Methods

| Method               | Summary                                                               |
| -------------------- | --------------------------------------------------------------------- |
| `getReference`       | Read the bot API reference, skill pack, manifest schema, and limits.  |
| `listTemplates`      | List the bot templates, each with a manifest and code.                |
| `create`             | Create a strategy: blank, from a template, or as a copy of a version. |
| `saveDraftVersion`   | Check a bot and save it as the strategy's next revision.              |
| `get`                | Read a strategy, its current version, and its notes.                  |
| `list`               | List the caller's strategies, most recently saved or renamed first.   |
| `listRevisions`      | List a strategy's saved drafts, newest first.                         |
| `rename`             | Rename a strategy.                                                    |
| `delete`             | Delete a strategy and its revisions.                                  |
| `getVersion`         | Read a version's manifest, code, settings form, and check result.     |
| `getNotes`           | Read a strategy's notes.                                              |
| `saveNotes`          | Save a strategy's notes as their next revision.                       |
| `listNotesRevisions` | List a strategy's saved notes, newest first.                          |
| `runScenarios`       | Run a version's behaviour examples.                                   |
| `explain`            | Read the review summary a user approves when deploying a version.     |
| `startBacktest`      | Start a backtest of a version.                                        |
| `getBacktest`        | Read one backtest, with its report once `done`.                       |
| `listBacktests`      | List a strategy's backtests as headlines, newest first.               |
| `listBacktestTrades` | List every trade of a finished backtest.                              |
| `proposeDeploy`      | Record a deploy proposal of a revision and get its deploy page.       |
| `deployBot`          | Deploy a proposal from the user's own MFA-elevated session.           |
| `getDeployStatus`    | Read where a deploy is, without advancing it.                         |
| `getDeployProposal`  | Read a proposal as its deploy page shows it.                          |
| `listBots`           | List the caller's bots, newest first, with counts per status.         |
| `getBot`             | Read one bot's money rules, settings, recent decisions, and errors.   |
| `listBotVersions`    | List the versions a bot ran, newest run first.                        |
| `listBotLogs`        | Read a bot's recent decisions, log lines, and errors.                 |
| `stopBot`            | Stop a bot, keeping or cancelling its open orders.                    |
| `returnBotFunds`     | Return a stopped bot's spendable balances to the main account.        |
| `getBotFundsReturn`  | Read one return of a stopped bot's funds.                             |
| `publishVersion`     | Publish a version as the strategy's community listing.                |
| `unpublish`          | Hide one of the caller's community listings.                          |
| `listCommunity`      | List the public community listings, most recently published first.    |
| `getCommunity`       | Read one public listing with its code and platform backtest.          |
| `fork`               | Copy a public listing into a new strategy of the caller.              |
| `reportCommunity`    | Report a public listing's version to moderation.                      |

## Access

`getReference`, `listTemplates`, `listCommunity`, and `getCommunity` need no credentials. Every other method acts on the caller's main account and needs a session JWT, or an API key whose policy grants the method's action. An API key scoped to a subaccount is refused with `PermissionError`.

| Policy action               | Methods                                                                                                                                                                                                                                                              |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read-strategies`           | `get`, `list`, `listRevisions`, `getVersion`, `getNotes`, `listNotesRevisions`, `explain`, `getBacktest`, `listBacktests`, `listBacktestTrades`, `getDeployStatus`, `getDeployProposal`, `listBots`, `getBot`, `listBotVersions`, `listBotLogs`, `getBotFundsReturn` |
| `draft-strategies`          | `create`, `saveDraftVersion`, `rename`, `delete`, `saveNotes`, `runScenarios`, `startBacktest`                                                                                                                                                                       |
| `propose-strategy-deploy`   | `proposeDeploy`                                                                                                                                                                                                                                                      |
| `stop-strategies`           | `stopBot`                                                                                                                                                                                                                                                            |
| `fork-strategies`           | `fork`                                                                                                                                                                                                                                                               |
| `return-strategy-bot-funds` | `returnBotFunds`                                                                                                                                                                                                                                                     |

`draft-strategies` never deploys, stops, or deletes a bot, and `propose-strategy-deploy` never deploys a bot or moves funds: the user deploys a proposal on its deploy page. Some methods limit who can call them, whatever an API key's policy grants:

- `deployBot` needs the user's own session with recent MFA. API keys and sessions a connected app holds on the user's behalf throw `PermissionError`; a session without recent MFA throws `SessionElevationRequiredError`.
- `publishVersion`, `unpublish`, and `reportCommunity` need the user's own session. API keys and connected-app sessions throw `PermissionError`.
- `fork` and `returnBotFunds` take an API key with their action, but refuse connected-app sessions.

A member of a bot's subaccount whose role grants `stop_strategies` (owner, admin, trader, or leveraged trader) can also stop that bot from a session. Only the bot's owner returns its funds; an invited member gets `ResourceNotFoundError` (`BOT_NOT_FOUND`). Each revision records how the caller that saved it signed in as `savedBy`: `session`, `api_key`, or `connected_app`.

Writes that take an `idempotencyKey` return what the first call recorded when repeated with the same request, and never act twice; the same key with a different request throws `AlreadyExistsError` (`IDEMPOTENCY_CONFLICT`), and the original stands. A key is 1 to 128 letters, digits, `.`, `_`, `:`, or `-`, and is never trimmed. It is required on `create`, `startBacktest`, `proposeDeploy`, `stopBot`, `returnBotFunds`, `publishVersion`, and `fork`, and optional on `saveDraftVersion` and `saveNotes`.

Lists return `nextPageToken`, empty when there is no more. Pass it back as `pageToken` with the same other inputs.

| Method                                                 | Default `limit` | Maximum |
| ------------------------------------------------------ | --------------- | ------- |
| `list`, `listRevisions`, `listBots`, `listBotVersions` | 50              | 200     |
| `listNotesRevisions`                                   | 10              | 20      |
| `listBacktests`                                        | 10              | 50      |
| `listBacktestTrades`                                   | 100             | 1000    |
| `listBotLogs`                                          | 100             | 200     |
| `listCommunity`                                        | 20              | 100     |

## Reference and templates

`getReference({ runtimeVersion? })` returns what bot code is written against: the bot API reference as Markdown (`reference`), the skill pack (`skillPack`, Markdown documents in order, with `skillPackVersion`), and, once the runtime catalog is available, the manifest's JSON Schema (`manifestSchema`), the `indicators` bot code may read, the `indicatorLibrary`, and the `limits` every bot runs under. Until then those are `null`, and `indicators` is empty. Omit `runtimeVersion` for the current one; an unknown one throws `ValidationError` (`RUNTIME_VERSION_UNSUPPORTED`).

`listTemplates()` returns the bot templates. Each has a `templateId`, `name`, `description`, `manifest`, `code`, `runtimeVersion`, and the `moneyCard` a version saved from it unchanged shows.

```ts
const reference = await client.strategies.getReference();
const templates = await client.strategies.listTemplates();
console.log(
	reference.runtimeVersion,
	templates.map((t) => t.templateId)
);
```

## Strategies and drafts

### `create(input, options?)`

Creates a strategy and returns `{ strategy, version }`. Pass `templateId` to start from a template, `versionId` to copy one of the caller's versions, or neither for a blank strategy; passing both throws `ValidationError`. A template or copied version is saved as revision 1, and `version` is its check result; a blank strategy has no revision until its first save, and `version` is `null`.

```ts
const { strategy } = await client.strategies.create({
	name: "Weekly DCA",
	templateId: "weekly-dca",
	idempotencyKey: crypto.randomUUID(),
});
```

The strategy cap throws `PreconditionFailedError` (`STRATEGY_CAP_REACHED`), with `detail.strategyCap` giving the cap and the count. An unknown source throws `ResourceNotFoundError` (`TEMPLATE_NOT_FOUND`, `VERSION_NOT_FOUND`).

### `saveDraftVersion(input, options?)`

Checks a bot and saves it as the strategy's next revision, renaming the strategy to `name`. Returns `{ revision, version }`: the revision saved and its check result.

```ts
const saved = await client.strategies.saveDraftVersion({
	strategyId: strategy.strategyId,
	expectedRevision: strategy.revision,
	name: "Weekly DCA",
	manifest,
	code,
});

if (!saved.version.valid) {
	for (const issue of saved.version.errors) console.log(issue.line, issue.rule, issue.message);
}
```

| Field                   | Type           | Notes                                                                       |
| ----------------------- | -------------- | --------------------------------------------------------------------------- |
| `strategyId`            | `string`       | The caller's strategy.                                                      |
| `expectedRevision`      | decimal string | The strategy's `revision` this draft was made from; `"0"` for a first save. |
| `name`                  | `string`       | The save renames the strategy to it.                                        |
| `manifest`              | JSON object    | Shaped like `getReference`'s `manifestSchema`.                              |
| `code`                  | `string`       | The bot code.                                                               |
| `runtimeVersion`        | `string`       | Omit for the current runtime version.                                       |
| `idempotencyKey`        | `string`       | Optional. Reusing it with the same request returns the revision it saved.   |
| `expectedNotesRevision` | decimal string | Optional. Save only while the notes are still at this revision.             |

A bot with mistakes is saved too, with `valid: false` and its `errors`: fix them and save again; it is not a thrown error. The same runtime version, manifest, and code always give the same `versionId`. A save whose content matches the current revision adds no revision and returns the current one, renaming the strategy if `name` is new. A manifest over 64 KiB throws `ValidationError` (`MANIFEST_TOO_LARGE`).

#### Revision conflicts

`expectedRevision` keeps two writers from overwriting each other. When another save landed first, the call throws `RevisionConflictError` (`DRAFT_REVISION_CONFLICT`), and `detail.revisionConflict` gives the strategy's current `revision` and `headVersionId`. A `headVersionId` equal to the version you tried to save means your own save already landed, for example on a retry without an `idempotencyKey`.

```ts
import { RevisionConflictError } from "@polyester/sdk";

try {
	await client.strategies.saveDraftVersion(draft);
} catch (err) {
	if (!(err instanceof RevisionConflictError)) throw err;
	const { strategy, head } = await client.strategies.get({ strategyId: draft.strategyId });
	// Reapply the change to head, then save again with expectedRevision: strategy.revision.
}
```

With `expectedNotesRevision`, notes saved since also throw `RevisionConflictError` (`NOTES_REVISION_CONFLICT`); both checks run together. See [Notes](#notes).

### Reading and managing strategies

- `get({ strategyId })` returns `{ strategy, head, notes }`: the strategy, its current revision's version (`null` until the first save), and its notes.
- `list({ limit?, pageToken? })` returns `{ strategies, nextPageToken }`.
- `listRevisions({ strategyId, limit?, pageToken? })` returns `{ revisions, nextPageToken }`. Each revision has `revision`, `versionId`, `valid`, `savedAt`, and `savedBy`.
- `rename({ strategyId, name })` returns the renamed strategy; its revisions stay as they are.
- `delete({ strategyId })` deletes the strategy and its revisions, and never stops a bot. A strategy that a bot not yet stopped or a waiting proposal uses, or whose listing is public, throws `PreconditionFailedError` (`STRATEGY_IN_USE`); one whose listing moderation holds throws `LISTING_HELD`.
- `getVersion({ versionId })` returns a version's `manifest`, `code`, `settingsForm`, `valid`, `flow`, and the `validation` stored when it was saved (reading never checks it again). An unknown or expired version throws `ResourceNotFoundError` (`VERSION_NOT_FOUND`).

An unknown strategy, or another account's, throws `ResourceNotFoundError` (`STRATEGY_NOT_FOUND`).

## Notes

A strategy's notes are a one-line `summary` and a Markdown `body`, saved as revisions of their own. `notesRevision` counts apart from the strategy's `revision` and is `"0"` until the first save. Notes are never shown in a community listing, and a fork starts with none.

```ts
const notes = await client.strategies.getNotes({ strategyId });

await client.strategies.saveNotes({
	strategyId,
	expectedNotesRevision: notes.notesRevision,
	summary: "Buys BTC every Monday",
	body: "## Why\n\nDollar-cost averaging into BTC.",
	idempotencyKey: crypto.randomUUID(),
});
```

`summary` is at most 120 characters with no line break, and `body` at most 8192 bytes of UTF-8. Notes equal to the current ones add no revision and return the current one. A stale `expectedNotesRevision` throws `RevisionConflictError` (`NOTES_REVISION_CONFLICT`), with `detail.notesConflict.notesRevision` giving the current revision: read the notes again, reapply the change, and save with the new revision. Without an `idempotencyKey`, a retry after a save that landed throws the same error.

Pass the optional `expectedRevision` to save the notes only against the strategy revision they describe; a stale one throws `RevisionConflictError` (`DRAFT_REVISION_CONFLICT`). `listNotesRevisions({ strategyId, limit?, pageToken? })` lists every saved revision, newest first.

## Behaviour examples

The manifest declares behaviour examples, each with the orders the bot should make. `runScenarios({ versionId })` runs them against the version's code and returns `{ versionId, passed, failed, results }`. Each result has the example's `name`, `passed`, the `expected` and `actual` orders, the code's `logs`, and an `error` when it failed.

```ts
const run = await client.strategies.runScenarios({ versionId: saved.version.versionId });
for (const result of run.results.filter((r) => !r.passed)) console.log(result.name, result.error);
```

Each market's trading rules are the exchange's as they were when the version first ran, so a version always gets the same result. A market not listed on the exchange throws `PreconditionFailedError` (`VERSION_INVALID`). Too many runs throw `RateLimitError` (`SCENARIO_RUN_LIMIT_REACHED`), with `detail.retryAfter`. A version must pass every example before it can be proposed or published.

`explain({ versionId })` returns the review summary a user approves when deploying the version: its `moneyCard`, `settings` form, each example's `outcome` (`not_run`, `passed`, `failed`), its latest `backtest` headline (or `backtestAbsentReason`), `warnings`, and `limitations`.

## Backtests

### `startBacktest(input, options?)`

Starts a backtest of a version and returns `{ backtestId, status, estimatedSeconds }`. Poll `getBacktest` until `status` is `done`, `failed`, or `not_backtestable`.

```ts
const { backtestId } = await client.strategies.startBacktest({
	versionId,
	initialBalances: [{ asset: "USDT", amount: "1000" }],
	idempotencyKey: crypto.randomUUID(),
});

let backtest = await client.strategies.getBacktest({ backtestId });
while (backtest.status === "queued" || backtest.status === "running") {
	await new Promise((resolve) => setTimeout(resolve, 2000));
	backtest = await client.strategies.getBacktest({ backtestId });
}
console.log(backtest.report?.evidenceGrade, backtest.report?.metrics?.returnPercent);
```

| Field             | Type                  | Notes                                                                                    |
| ----------------- | --------------------- | ---------------------------------------------------------------------------------------- |
| `versionId`       | `string`              | The version to backtest.                                                                 |
| `startTime`       | `number`              | Window start, epoch ms, inclusive. Omit for the most recent 365 days of data. See below. |
| `endTime`         | `number`              | Window end, epoch ms, exclusive. Omit for the end of the longest window with data.       |
| `settings`        | `{ name, value }[]`   | Settings form values, each once. Settings left out take their default.                   |
| `initialBalances` | `{ asset, amount }[]` | One per asset of the bot's markets, each above 0. Omit for 1,000 of the quote asset.     |
| `idempotencyKey`  | `string`              | Reusing it with the same request returns the backtest it started.                        |

Both bounds are floored to a whole second. A backtest holds at most 30,000 calls of the bot, so without `startTime` a bot that would need more calls over 365 days gets the most whole days that fit, at least one; read the resolved `window` from `getBacktest`. The same version, window, settings, and balances, under the same fees and platform assumptions, return the existing backtest instead of running again.

A bot that cannot be backtested throws `PreconditionFailedError` (`NOT_BACKTESTABLE`), with `detail.notBacktestableReason`. A bot's first limit order is found only while it runs, so a started backtest can also end as `not_backtestable`. A window with no market data for the bot's markets throws `WINDOW_HAS_NO_DATA`. Such a bot can still be proposed and deployed without a backtest.

| `notBacktestableReason`      | Meaning                                                              |
| ---------------------------- | -------------------------------------------------------------------- |
| `reacts_to_trades_or_quotes` | It reacts to trades or quotes, which candles do not carry.           |
| `reads_social_signals`       | It reads social signals, which have no recorded history.             |
| `mixed_quote_assets`         | Its markets have different quote assets.                             |
| `no_reference_candles`       | A market it needs has no price history at all. `startBacktest` only. |
| `places_limit_orders`        | It places limit orders, which are not backtested yet.                |
| `reads_volume`               | It reads trading volume, which the replayed price history lacks.     |

The backtest limits throw `RateLimitError` (`BACKTEST_LIMIT_REACHED`), and `detail.backtestLimit` says which: `dailyUsed` reaching `dailyLimit` is the daily limit, with `detail.retryAfter` at the next UTC day; `active` reaching `activeLimit` is the limit on backtests queued or running at once, with no `retryAfter`, and it clears when one finishes. A request that returns an existing backtest never counts.

### Reading results

`getBacktest({ backtestId })` returns the backtest with its `report` once `done`, `failure` when it failed, and `attempts`, the number of backtests the caller ran of this bot's versions: many make a good result more likely luck. The report holds:

| Field                                               | Meaning                                                                                                              |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `fidelity`                                          | What was simulated and how, naming every assumption.                                                                 |
| `evidenceGrade`                                     | How much the result can be trusted: `not_enough`, `low`, `medium`, or `high`.                                        |
| `period`, `heldBackPeriod`                          | The period the bot was tuned on, and the most recent months held back from it (`null` when the window is too short). |
| `metrics`, `heldBackMetrics`                        | Results over each period under the base cost scenario.                                                               |
| `scenarios`                                         | The results under the low, base, and high cost scenarios, each with its `slippageBps`: the range to read.            |
| `baselines`, `heldBackBaselines`                    | Buy-and-hold and cash over each period.                                                                              |
| `equity`, `heldBackStart`                           | The whole window's equity curve with buy-and-hold's, at most 1,000 points, oldest first.                             |
| `windowMaxDrawdownPercent` (with `Start` and `End`) | The whole window's largest fall, with its peak and trough.                                                           |
| `heldBackSeen`                                      | True when earlier backtests already showed part of the held-back period.                                             |
| `trades`                                            | The window's first 20 trades. `listBacktestTrades` lists all of them.                                                |
| `dataGaps`, `warnings`                              | Spans without market data (`affected` when the bot was exposed across one), and what to keep in mind.                |

Metrics are exact decimal strings in percent or in the quote asset: `returnPercent`, `maxDrawdownPercent` with `maxDrawdownStart` and `maxDrawdownEnd`, `trades`, `winRatePercent`, `fees`, `exposurePercent`, `sharpeRatio` (annualized, `null` with fewer than two daily returns or when they never vary), `realizedPnl`, and the exact `startEquity` and `endEquity`.

`listBacktests({ strategyId, limit?, pageToken? })` lists the backtests of the versions a strategy's revisions saved, newest first, each as a headline (`summary` with `status`, `metrics`, `heldBackMetrics`, and `attempts`) with its `versionId`, `revision`, and `window`. A backtest is kept 30 days after it finishes.

`listBacktestTrades({ backtestId, limit?, pageToken? })` lists a finished backtest's trades in `tradeIndex` order. Each has `time`, `market`, `side`, `price`, `quantity`, `fee`, `reason`, `realizedPnl` (empty on a buy), and `afterGap`, true when it filled at the first price after missing market data. A backtest not yet finished throws `PreconditionFailedError` (`BACKTEST_NOT_DONE`); an unknown or expired one throws `ResourceNotFoundError` (`BACKTEST_NOT_FOUND`).

## Deploying a bot

A deploy has two halves. `proposeDeploy` records what will be deployed, and can run from an API key. `deployBot` carries it out, and only the user's own MFA-elevated session can call it, usually from the proposal's deploy page.

### `proposeDeploy(input, options?)`

Records an immutable deploy proposal of one revision of a strategy and returns `{ proposalId, deployUrl, summary, expiresAt }`. It never deploys a bot, creates a subaccount, or moves funds. Open `deployUrl` for the user to deploy it; never parse it. A proposal expires 24 hours after it is recorded.

```ts
const proposal = await client.strategies.proposeDeploy({
	strategyId,
	revision: saved.revision,
	botName: "BTC weekly DCA",
	settings: [{ name: "amount", value: "50" }],
	funding: [{ asset: "USDT", amount: "500" }],
	idempotencyKey: crypto.randomUUID(),
});
```

| Field                 | Type                  | Notes                                                                        |
| --------------------- | --------------------- | ---------------------------------------------------------------------------- |
| `strategyId`          | `string`              | The caller's strategy.                                                       |
| `revision`            | decimal string        | The revision to deploy, such as `saveDraftVersion`'s `revision`; not `"0"`.  |
| `botName`             | `string`              | Name of the new bot.                                                         |
| `settings`            | `{ name, value }[]`   | Settings form values, each once. Settings left out take their default.       |
| `funding`             | `{ asset, amount }[]` | What to move into the bot's subaccount on deploy: 1 to 16 assets, each once. |
| `fundingSubaccountId` | `string`              | Subaccount that funds the bot. Omit to fund it from the main account.        |
| `idempotencyKey`      | `string`              | Reusing it with the same request returns the proposal it recorded.           |

The revision's version must be valid and pass every behaviour example, its markets must be open to bots, the funding account must hold the funding, and the caller must be under their bot cap. Refusals throw `PreconditionFailedError`:

| `detail.code`           | Meaning                                                                                                              |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `VERSION_INVALID`       | The version did not validate.                                                                                        |
| `SCENARIOS_FAILING`     | A behaviour example fails, or the examples were never run.                                                           |
| `MARKET_NOT_ALLOWED`    | A market is not open to bots; `detail.markets` lists them.                                                           |
| `INSUFFICIENT_FUNDS`    | The funding account lacks the funding; `detail.shortfall` gives the missing amounts.                                 |
| `BOT_CAP_REACHED`       | The caller runs as many bots as their VIP tier allows; `detail.botCap` gives the tier, the cap, and the next tier's. |
| `FUNDING_SOURCE_IS_BOT` | The funding subaccount is, or was, a bot's. A bot's funds never fund another bot.                                    |

Invalid settings or funding throw `ValidationError` (`SETTINGS_INVALID`, `FUNDING_INVALID`, with `detail.fieldPath`). An unknown strategy, revision, or funding subaccount throws `ResourceNotFoundError` (`STRATEGY_NOT_FOUND`, `REVISION_NOT_FOUND`, `FUNDING_SUBACCOUNT_NOT_FOUND`).

### `deployBot(input, options?)`

Deploys one proposal: it checks the version again, creates the bot's subaccount, sets the bot's limits and trading key, funds the subaccount, and starts the bot. Returns the deploy's `StrategyDeployStatus`. A proposal is deployed at most once: calling again, after an error, a timeout, or from another tab, continues the same deploy and never starts a second bot.

A deploy that creates a subaccount needs `subaccountAuthorization`: request a challenge with [`subaccounts.createChallenge`](https://testnet.polyester.com/docs/sdk/typescript/reference/subaccounts), have the user sign it, and pass `{ smartAccountAddress, message, signature }`. Without it, or with a challenge since replaced or expired, the call throws `PreconditionFailedError` (`SUBACCOUNT_AUTHORIZATION_REQUIRED`) and the deploy keeps its progress. A deploy that reuses one of the caller's closed bot subaccounts ignores it.

```ts
const input = { proposalId, subaccountAuthorization };
let status = await client.strategies.deployBot(input);

while (status.state === "setting_access" || status.state === "funding") {
	if (status.wait?.reason === "whitelist_required") {
		// Ask the user to add status.wait.address to the funding account's internal whitelist.
		await waitForWhitelist(status.wait.address);
	}
	status = await client.strategies.deployBot(input);
}

// From "deploying", poll getDeployStatus until "live", "failed", or "expired".
```

Each call waits up to about 20 seconds. Call `deployBot` again while it answers `setting_access`, or `funding` without a `wait`. When `wait` is set, do what it says first: with `whitelist_required`, add `wait.address`, the bot subaccount's smart account address, to the funding account's internal whitelist (see [Address book](https://testnet.polyester.com/docs/sdk/typescript/reference/address-book)), then call again. From `deploying`, polling `getDeployStatus` until a final state is enough.

| `state`               | Meaning                                                                      |
| --------------------- | ---------------------------------------------------------------------------- |
| `proposed`            | Recorded; waiting for the user to deploy it.                                 |
| `validating`          | Checking the version, its behaviour examples, and limits again.              |
| `creating_subaccount` | Preparing the bot's subaccount.                                              |
| `setting_access`      | Setting the bot's limits and trading key until the exchange applies them.    |
| `funding`             | Moving the funding into the bot's subaccount.                                |
| `deploying`           | Starting the bot.                                                            |
| `live`                | The bot runs; `botId` is set. Final.                                         |
| `failed`              | The deploy stopped; `failure` says why and `failedAt` names the step. Final. |
| `expired`             | The user did not deploy the proposal in time. Final.                         |

A step that fails ends the deploy as `failed`, answered as a status, not thrown. Thrown refusals: a session without recent MFA throws `SessionElevationRequiredError` (`MFA_ELEVATION_REQUIRED`; complete a `sessionElevation` challenge with [MFA](https://testnet.polyester.com/docs/sdk/typescript/reference/mfa) and call again, nothing was started); an expired proposal throws `PreconditionFailedError` (`PROPOSAL_EXPIRED`); a caller at their bot cap throws `BOT_CAP_REACHED`; an unknown proposal throws `ResourceNotFoundError` (`PROPOSAL_NOT_FOUND`).

`getDeployStatus({ proposalId })` reads the same status without advancing the deploy. `getDeployProposal({ proposalId })` returns the proposal as its deploy page shows it: `summary` (the version, strategy and revision, bot name, money card, settings, funding, whether the examples passed, and the latest backtest or `notBacktestableReason`), `status`, `createdAt`, and `fundingSubaccountLabel`. The summary's `strategyId` and `revision` are `null` once the strategy is deleted.

## Bots

A bot runs on its own subaccount. Read that subaccount's balances, open orders, and profit and loss by the bot's `subaccountId` with [`balances.list`](https://testnet.polyester.com/docs/sdk/typescript/reference/balances), [`orders.listOpen`](https://testnet.polyester.com/docs/sdk/typescript/reference/orders), and [`profitAndLoss.get`](https://testnet.polyester.com/docs/sdk/typescript/reference/profit-and-loss).

- `listBots({ limit?, pageToken? })` returns `{ bots, nextPageToken, statusCounts }`. `statusCounts` counts all the caller's bots per status, on every page, listing only statuses that have a bot; it is not a pagination total.
- `getBot({ botId })` returns `{ bot, moneyCard, settings, decisions, errors }`: at most its last 20 decisions (`decidedAt`, the `event` handler, the `orders` it asked for, and its `logs`) and 20 errors, newest first, from its current run.
- `listBotVersions({ botId, limit?, pageToken? })` lists the versions the bot ran, newest run first, each with `startedAt`, `stoppedAt` (`null` for the current run), and the `strategy` and revision it ran.
- `listBotLogs({ botId, startTime?, limit?, pageToken? })` reads the bot's recent activity, oldest first: the last 20 decisions of its current deployment, each with the lines its call wrote, and its last 20 errors. Each entry has `sequence`, `time`, `kind` (`log`, `decision`, `error`), and `message`, and lags the bot by up to about a minute.

To follow a bot's log, pass the last page's `followToken` as `pageToken`, now or later, never a later `startTime`. The token keeps reading the deployment the first page read. When `deployedAgain` is true, a new run started a new log: list again without `pageToken` to read it.

```ts
let pageToken = "";
let page;
do {
	page = await client.strategies.listBotLogs({ botId, pageToken });
	for (const entry of page.entries) console.log(entry.sequence, entry.kind, entry.message);
	pageToken = page.nextPageToken;
} while (pageToken !== "");

// Later, read what the same deployment wrote since.
const next = await client.strategies.listBotLogs({ botId, pageToken: page.followToken });
```

A bot's `status` is one of:

| `status`    | Meaning                                                                                   |
| ----------- | ----------------------------------------------------------------------------------------- |
| `deploying` | Being deployed.                                                                           |
| `running`   | Handling its events.                                                                      |
| `paused`    | Paused, with its orders kept; `pauseReason` says why and `statusReason` says it in words. |
| `stopping`  | A stop is recorded, and the bot has not yet reported it complete.                         |
| `stopped`   | Stopped by the user.                                                                      |

| `pauseReason`       | Meaning                                                                                                    |
| ------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bot_decided`       | The bot's own code paused it; `statusReason` carries its message.                                          |
| `failures_in_a_row` | Its calls failed too many times in a row.                                                                  |
| `environment_reset` | The environment was reset, and every bot paused until its user starts it again.                            |
| `unrecorded_order`  | It found one of its own orders whose placement it had not recorded, and paused so you can check its state. |

A bot's `activity` lists what it did in each of the last 24 UTC hours, oldest first: the hour's `start`, the `decisions` it was called for, its `fills`, and the events that `expired` before it could run.

### `stopBot(input, options?)`

Stops a bot: it makes no new decisions, and its holdings stay in its subaccount. `mode` is `keep_orders`, which hands its open orders to the subaccount as the subaccount's own, or `cancel_orders`, which cancels them. Returns `{ bot, mode }`; the bot reads `stopping` until the stop completes, then `stopped`. Poll `getBot` to follow it. Stopping needs no MFA.

```ts
await client.strategies.stopBot({
	botId,
	mode: "cancel_orders",
	idempotencyKey: crypto.randomUUID(),
});
```

A stopped bot throws `PreconditionFailedError` (`BOT_NOT_RUNNING`). On a bot already stopping, a call in the same mode returns the existing stop, and one in the other mode throws `BOT_ALREADY_STOPPING`. A bot the caller may not stop throws `ResourceNotFoundError` (`BOT_NOT_FOUND`).

## Returning bot funds

`returnBotFunds({ botId, idempotencyKey })` moves every spendable balance of a stopped bot's subaccount to the caller's main account, its only destination, so it needs no MFA. It returns a `StrategyBotFundsReturn`; poll `getBotFundsReturn({ returnId })` while `status` is `processing`.

```ts
let ret = await client.strategies.returnBotFunds({ botId, idempotencyKey: crypto.randomUUID() });
while (ret.status === "processing") {
	await new Promise((resolve) => setTimeout(resolve, 2000));
	ret = await client.strategies.getBotFundsReturn({ returnId: ret.returnId });
}
```

| `status`        | Meaning                                                                                     |
| --------------- | ------------------------------------------------------------------------------------------- |
| `processing`    | Under way. It completes on its own, and stays here while open orders hold amounts (`held`). |
| `completed`     | Every asset was credited to the main account.                                               |
| `nothing_moved` | It ended with nothing left to return.                                                       |

A return never takes what open orders hold. After a `keep_orders` stop, `held` lists what the orders still reserve, and the return takes it as they fill or end. `assets` lists the confirmed amounts moved so far.

A bot that may still trade (deploying, running, paused, or stopping) throws `PreconditionFailedError` (`BOT_NOT_STOPPED`), as does a subaccount with nothing to return (`NOTHING_TO_RETURN`). While a stopped bot's trading access is still live, an API key also gets `BOT_NOT_STOPPED`: the owner must call `returnBotFunds` once from their own session to end that access, after which a root-scoped key with `return-strategy-bot-funds` can return funds. The same `idempotencyKey` for another bot throws `AlreadyExistsError`; retry a `ServiceUnavailableError` with the same key.

## Community strategies

A strategy has at most one community listing. `publishVersion` makes one of its versions readable by everyone (code, manifest, and settings form at their defaults) and starts the platform's backtest of it. Anyone can browse listings without credentials and fork one into a strategy of their own.

### `publishVersion(input, options?)`

Publishes a version as the strategy's listing and returns its `StrategyListing`. Publishing again shows the new version and makes a `hidden` listing `public` again. Needs the user's own session.

```ts
const listing = await client.strategies.publishVersion({
	strategyId,
	versionId,
	title: "Weekly BTC DCA",
	description: "Buys a fixed amount of BTC every Monday.",
	tags: ["dca"],
	idempotencyKey: crypto.randomUUID(),
});
```

`versionId` must be one of the strategy's revisions' versions, valid, with every behaviour example passing. `tags` are from a fixed list: `trend`, `mean_reversion`, `grid`, `dca`, `market_making`, `arbitrage`, and `signals`. Publishing shows the author by username.

Refusals throw `PreconditionFailedError`: `VERSION_INVALID`, `SCENARIOS_FAILING`, `WINDOW_HAS_NO_DATA` (the default window holds no market data), `USERNAME_REQUIRED` (claim a username first), `LISTING_CAP_REACHED` (with `detail.listingCap`), `PUBLISH_LIMIT_REACHED` (with `detail.retryAfter` at the next UTC day), and `LISTING_HELD`.

### Listing states

| `state`  | Meaning                                                                                                                                                                           |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `public` | Listed and readable by everyone.                                                                                                                                                  |
| `hidden` | Unpublished by its author: out of the list, and `getCommunity` throws `ResourceNotFoundError`.                                                                                    |
| `held`   | Held by moderation, with `holdReason` shown to its author only. Out of the list, and it can't be published, unpublished, or its strategy deleted (`LISTING_HELD`) until released. |

`unpublish({ listingId })` hides one of the caller's listings and returns it. Copies already made stay. Unpublishing a `hidden` listing changes nothing; a `held` one throws `PreconditionFailedError` (`LISTING_HELD`); another account's listing throws `ResourceNotFoundError` (`LISTING_NOT_FOUND`). Needs the user's own session.

### Browsing and forking

`listCommunity({ tags?, markets?, limit?, pageToken? })` lists the public listings, most recently published first, optionally only those with any of `tags` or trading any of `markets` (symbols such as `BTC-USDT`; a name that isn't a symbol throws `ValidationError`). Each summary has `title`, `tags`, `markets`, `authorUsername`, `forks`, the platform `backtest` without its report, and `publishedAt`.

`getCommunity({ listingId })` reads one public listing with its `description`, published `versionId`, `runtimeVersion`, `manifest`, `code`, `settingsForm`, `moneyCard`, `flow`, `forks`, `forkedFrom`, and the platform `backtest` with its report once `done`. An unknown or unpublished listing throws `ResourceNotFoundError` (`LISTING_NOT_FOUND`), for its author too.

The platform backtest runs at each publish with the default window, default settings, 1,000 of the quote asset, and the standard fees, so listings compare alike. It shows nothing of the author's own backtests. Its `status` is `queued` or `running` until it ends as `done`, `failed`, or `not_backtestable`.

`fork({ listingId, name, idempotencyKey })` copies a listing's published version into a new strategy of the caller as its revision 1 and returns `{ strategy, version }`. The strategy's `origin` is `{ kind: "fork", listingId, title, authorUsername, sourceVersionId }`; nothing the author does later changes the copy. `forks` counts accounts that forked a listing, each once, never its author. Once the source listing isn't public, `listingId` in `origin` and `forkedFrom` is `null` and `title` and `authorUsername` are empty: show "forked from a community strategy". The strategy cap throws `PreconditionFailedError` (`STRATEGY_CAP_REACHED`).

`reportCommunity({ listingId, versionId, reason, note? })` reports the version of a listing the reader saw to moderation and returns `{ reportedAt }`. `reason` is `misleading_results`, `harmful_code`, `spam`, `copied_without_credit`, or `other`, which needs a `note` (at most 500 characters). Reporting the same version again returns the first report's time. Needs the user's own session. The caller's own listing throws `PreconditionFailedError` (`CANNOT_REPORT_OWN_LISTING`), as does the daily limit (`REPORT_LIMIT_REACHED`, with `detail.retryAfter`).

## Shapes

```ts
import type {
	Strategy,
	StrategyBacktest,
	StrategyBot,
	StrategyBotFundsReturn,
	StrategyDeployStatus,
	StrategyListing,
	StrategyMoneyCard,
	StrategyNotes,
	StrategyVersionValidation,
} from "@polyester/sdk";

interface Strategy {
	strategyId: string;
	name: string;
	revision: string; // current revision; "0" until the first save
	headVersionId: string; // the current revision's version; "" until the first save
	valid: boolean;
	origin:
		// what it started from; null for a blank strategy
		| { kind: "template"; templateId: string }
		| { kind: "duplicate"; sourceVersionId: string }
		| {
				kind: "fork";
				listingId: string | null; // null once the listing isn't public
				title: string;
				authorUsername: string;
				sourceVersionId: string; // the strategy's revision 1
		  }
		| null;
	createdAt: number | null;
	updatedAt: number | null; // last saved or renamed
	bot: { botId: string; status: StrategyBotStatus | "unspecified" } | null; // newest bot not stopped
	markets: string[]; // the current revision's markets, e.g. "BTC-USDT"
	summary: string; // the notes' one-line summary
	listing: StrategyListing | null; // null when never published
}

interface StrategyListing {
	listingId: string;
	state: "public" | "hidden" | "held" | "unspecified";
	versionId: string; // the version last published
	publishedAt: number | null;
	holdReason: string; // author only; "" unless held
}

interface StrategyVersionValidation {
	versionId: string;
	runtimeVersion: string;
	valid: boolean; // false: fix errors and save again
	errors: StrategyValidationIssue[]; // { manifestPath, line, column, rule, message, hint }
	warnings: StrategyValidationIssue[];
	moneyCard: StrategyMoneyCard | null;
	settingsForm: StrategySettingField[]; // { name, description, kind, asset, defaultValue, minimum, maximum }
	flow: StrategyFlow | null; // null unless valid
}

interface StrategyMoneyCard {
	budget: StrategyMoney | null; // unset until a total spending limit is enforced
	maxOrder: StrategyMoney | null; // largest single order
	maxOpenGtcOrders: number;
	dailyLossThreshold: StrategyMoney | null; // declared by the manifest only
	markets: string[];
	events: string[]; // e.g. "candles BTC-USDT 1h"
}

interface StrategyNotes {
	strategyId: string;
	notesRevision: string; // "0" when never saved
	summary: string;
	body: string; // Markdown
	savedAt: number | null;
	savedBy: "session" | "api_key" | "connected_app" | "unspecified";
}

interface StrategyBacktest {
	backtestId: string;
	versionId: string;
	status: "queued" | "running" | "done" | "failed" | "not_backtestable" | "unspecified";
	window: { startTime: number | null; endTime: number | null } | null;
	createdAt: number | null;
	finishedAt: number | null;
	report: BacktestReport | null; // set once done; see "Reading results"
	failure: string; // "" unless failed
	attempts: number;
	notBacktestableReason: StrategyNotBacktestableReason | "unspecified";
}

interface StrategyDeployStatus {
	proposalId: string;
	state: StrategyDeployState | "unspecified"; // live, failed, and expired are final
	step: string; // the current step as the user sees it
	botId: string | null; // null until the bot exists
	subaccountId: string | null; // null until the bot's subaccount exists
	failure: string; // "" unless failed
	failedAt: StrategyDeployState | "unspecified";
	expiresAt: number | null;
	updatedAt: number | null;
	wait: { reason: "whitelist_required" | "unspecified"; address: string } | null;
}

interface StrategyBot {
	botId: string;
	name: string;
	subaccountId: string; // the bot's own subaccount
	status: StrategyBotStatus | "unspecified";
	statusReason: string; // "" unless paused
	pauseReason: StrategyBotPauseReason | "unspecified";
	versionId: string;
	strategy: { strategyId: string; revision: string } | null; // null once the strategy is unlinked
	lastDecisionAt: number | null;
	createdAt: number | null;
	quoteAsset: string;
	markets: string[];
	funding: {
		subaccountId: string | null; // null when the main account funded it
		subaccountLabel: string;
		initialFunding: StrategyMoney[];
	} | null;
	uptimeRatio: string; // "0" to "1"
	runningSince: number | null; // null unless running
	activity: { start: number | null; decisions: number; fills: number; expired: number }[];
}

interface StrategyBotFundsReturn {
	returnId: string;
	botId: string;
	status: "processing" | "completed" | "nothing_moved" | "unspecified";
	assets: StrategyMoney[]; // confirmed amounts moved so far
	requestedAt: number | null;
	finishedAt: number | null; // null while processing
	held: StrategyMoney[]; // what open orders still hold; empty once finished
}
```

`StrategyMoney` is `{ asset, amount }`. `BacktestReport` above is `NonNullable<StrategyBacktest["report"]>`; the SDK exports no name for it. A `Strategy`'s `bot`, `markets`, `summary`, and `listing` read as empty or `null` when the caller may not read bots. An enum value newer than this SDK build reads as `"unspecified"`.

## Errors

Invalid input throws `ValidationError` before the request is sent. The service's refusals carry `detail.service === "strategies"`:

| `detail.code`                                                                                                                                                                                           | Error                           | Meaning                                                                                                                           |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `STRATEGY_NOT_FOUND`, `VERSION_NOT_FOUND`, `REVISION_NOT_FOUND`, `BACKTEST_NOT_FOUND`, `PROPOSAL_NOT_FOUND`, `BOT_NOT_FOUND`, `LISTING_NOT_FOUND`, `TEMPLATE_NOT_FOUND`, `FUNDING_SUBACCOUNT_NOT_FOUND` | `ResourceNotFoundError`         | No such resource of the caller. Another account's is reported the same way.                                                       |
| `RUNTIME_VERSION_UNSUPPORTED`, `MANIFEST_TOO_LARGE`, `SETTINGS_INVALID`, `FUNDING_INVALID`                                                                                                              | `ValidationError`               | The request is invalid. `detail.fieldPath` names the field for the last three.                                                    |
| `DRAFT_REVISION_CONFLICT`, `NOTES_REVISION_CONFLICT`                                                                                                                                                    | `RevisionConflictError`         | Another save landed first. `detail.revisionConflict` or `detail.notesConflict` gives the current revision.                        |
| `VERSION_INVALID`, `SCENARIOS_FAILING`, `BACKTEST_MISSING`, `MARKET_NOT_ALLOWED`, `INSUFFICIENT_FUNDS`, `BOT_CAP_REACHED`, `FUNDING_SOURCE_IS_BOT`                                                      | `PreconditionFailedError`       | The version or account can't be proposed or deployed now. See [proposeDeploy](#proposedeployinput-options).                       |
| `WINDOW_HAS_NO_DATA`, `NOT_BACKTESTABLE`, `BACKTEST_NOT_DONE`                                                                                                                                           | `PreconditionFailedError`       | The backtest can't run, or hasn't finished. `detail.notBacktestableReason` says why a bot can't be backtested.                    |
| `STRATEGY_CAP_REACHED`, `STRATEGY_IN_USE`                                                                                                                                                               | `PreconditionFailedError`       | The strategy cap is reached (`detail.strategyCap`), or the strategy is in use.                                                    |
| `PROPOSAL_EXPIRED`, `SUBACCOUNT_AUTHORIZATION_REQUIRED`                                                                                                                                                 | `PreconditionFailedError`       | Propose the deploy again, or deploy again with a fresh signed subaccount authorization.                                           |
| `BOT_NOT_RUNNING`, `BOT_ALREADY_STOPPING`, `BOT_NOT_STOPPED`, `NOTHING_TO_RETURN`                                                                                                                       | `PreconditionFailedError`       | The bot is in the wrong state to stop or to return its funds.                                                                     |
| `USERNAME_REQUIRED`, `LISTING_CAP_REACHED`, `PUBLISH_LIMIT_REACHED`, `LISTING_HELD`, `CANNOT_REPORT_OWN_LISTING`, `REPORT_LIMIT_REACHED`                                                                | `PreconditionFailedError`       | The listing can't be published, changed, or reported now. The daily limits carry `detail.retryAfter`.                             |
| `INDICATOR_SETTINGS_LIMIT_REACHED`                                                                                                                                                                      | `PreconditionFailedError`       | The caller's bots and backtests would read too many distinct indicator settings. Reuse one or stop a bot; retrying does not help. |
| `MFA_ELEVATION_REQUIRED`                                                                                                                                                                                | `SessionElevationRequiredError` | `deployBot` needs a session with recent MFA. Nothing was started.                                                                 |
| `SCENARIO_RUN_LIMIT_REACHED`, `BACKTEST_LIMIT_REACHED`                                                                                                                                                  | `RateLimitError`                | Too many example runs or backtests. Retry after `detail.retryAfter`, or, without one, when a backtest finishes.                   |
| `IDEMPOTENCY_CONFLICT`                                                                                                                                                                                  | `AlreadyExistsError`            | The `idempotencyKey` was used with a different request. The original stands.                                                      |
| `SERVICE_UNAVAILABLE`                                                                                                                                                                                   | `ServiceUnavailableError`       | Retry the same request.                                                                                                           |

A refused credential throws `PermissionError` with an auth detail: an API key without the method's policy action or scoped to a subaccount, or an API key or connected-app session on a session-only method. See [Access](#access).

## Related

- [API keys](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys) for the strategy policy actions, and for `setStrategyBotAccess` and `endStrategyBotAccess`, which give and revoke a bot's `strategy_bot` trade key during a deploy.
- [Subaccounts](https://testnet.polyester.com/docs/sdk/typescript/reference/subaccounts) for `createChallenge`, the `stop_strategies` permission, and `strategyBot`, which marks a subaccount a bot has held.
- [MFA](https://testnet.polyester.com/docs/sdk/typescript/reference/mfa) for elevating a session before `deployBot`.
- [Address book](https://testnet.polyester.com/docs/sdk/typescript/reference/address-book) for the internal whitelist a deploy can wait for.
- [Assistant](https://testnet.polyester.com/docs/sdk/typescript/reference/assistant) for conversations about one strategy.
- [Errors](https://testnet.polyester.com/docs/sdk/typescript/reference/errors) for the error type reference.
