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:
- Start a strategy with
create, blank or from a template, and save drafts withsaveDraftVersion. - Run the version's behaviour examples with
runScenarios, and backtest it withstartBacktest. - Record a deploy proposal with
proposeDeploy. The user deploys it withdeployBotfrom their own MFA-elevated session, which creates the bot's subaccount, funds it, and starts the bot. - Read the bot with
getBotandlistBotLogs, stop it withstopBot, and move what is left back to the main account withreturnBotFunds.
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
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.
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:
deployBotneeds the user's own session with recent MFA. API keys and sessions a connected app holds on the user's behalf throwPermissionError; a session without recent MFA throwsSessionElevationRequiredError.publishVersion,unpublish, andreportCommunityneed the user's own session. API keys and connected-app sessions throwPermissionError.forkandreturnBotFundstake 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.
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.
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.
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.
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);
}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.
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.
Reading and managing strategies
get({ strategyId })returns{ strategy, head, notes }: the strategy, its current revision's version (nulluntil the first save), and its notes.list({ limit?, pageToken? })returns{ strategies, nextPageToken }.listRevisions({ strategyId, limit?, pageToken? })returns{ revisions, nextPageToken }. Each revision hasrevision,versionId,valid,savedAt, andsavedBy.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, throwsPreconditionFailedError(STRATEGY_IN_USE); one whose listing moderation holds throwsLISTING_HELD.getVersion({ versionId })returns a version'smanifest,code,settingsForm,valid,flow, and thevalidationstored when it was saved (reading never checks it again). An unknown or expired version throwsResourceNotFoundError(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.
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.
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.
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);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.
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:
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.
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(),
});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:
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, 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.
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),
then call again. From deploying, polling getDeployStatus until a final state is enough.
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 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, orders.listOpen, and profitAndLoss.get.
listBots({ limit?, pageToken? })returns{ bots, nextPageToken, statusCounts }.statusCountscounts 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, theeventhandler, theordersit asked for, and itslogs) and 20 errors, newest first, from its current run.listBotVersions({ botId, limit?, pageToken? })lists the versions the bot ran, newest run first, each withstartedAt,stoppedAt(nullfor the current run), and thestrategyand 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 hassequence,time,kind(log,decision,error), andmessage, 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.
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:
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.
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.
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 });
}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.
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
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
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":
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.
Related
- API keys for the strategy policy actions, and for
setStrategyBotAccessandendStrategyBotAccess, which give and revoke a bot'sstrategy_bottrade key during a deploy. - Subaccounts for
createChallenge, thestop_strategiespermission, andstrategyBot, which marks a subaccount a bot has held. - MFA for elevating a session before
deployBot. - Address book for the internal whitelist a deploy can wait for.
- Assistant for conversations about one strategy.
- Errors for the error type reference.