# VectorialData Terminal — Agent API v1

A brokerage API built for AIs and bots. You create your own wallet, register it
yourself, and trade Hyperliquid perps and Polymarket prediction markets (§4b)
through a non-custodial **prepare → sign → submit** flow. The server never sees your private key; you
sign locally and it enforces your limits, records your authoritative ledger,
and computes your metrics.

Base URL: `https://terminal.vectorialdata.com/api/agent/v1`

All requests/responses are JSON (except this doc). Errors are structured:
`{ "code": "machine_readable_code", "message": "...", "details": ... }`.

Prefer native tools over HTTP? There is an official **MCP server** at
`https://terminal.vectorialdata.com/api/mcp` — see §14.

## What you need

Any EVM private key and an EIP-712/EIP-191 signer. Example with viem (Node):

~~~ts
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
const pk = generatePrivateKey();           // YOU create your own wallet. Store pk safely.
const account = privateKeyToAccount(pk);   // account.address is your identity,
                                           // your Hyperliquid account, and your deposit address.
~~~

## 1. Create your account

~~~ts
// 1a. Get a challenge
const { nonce, message } = await post("/challenge", { address: account.address });

// 1b. Sign it (EIP-191 personal message) and register
const signature = await account.signMessage({ message });
const reg = await post("/register", {
  address: account.address, nonce, signature, label: "my-bot",
});
// reg.api_key ("vd_agt_...") is shown ONCE. Store it. Only its hash is kept server-side.
~~~

Every other call needs `Authorization: Bearer <api_key>`.

New accounts start in **paper mode**: the full pipeline runs against simulated
fills (live mid ± 5 bps, realistic fees) with no funds needed. Your key scopes
are `read, trade`. The `withdraw` scope is never granted by default and cannot
be added by an API-key call — it requires a wallet-signed step-up (see §7).

## 2. Read your account and the markets

- `GET /me` — status, mode, limits, live Hyperliquid balances, your Polymarket deposit wallet.
- `GET /markets` — public unified catalog. Response: `{ "markets": [ { symbol, price, volume_24h_usd, max_leverage, funding_apr, size_decimals, min_size, price_sig_figs, price_max_decimals, min_notional_usd, ... } ] }`.
  Use the precision fields to size orders without guessing: sizes take at most
  `size_decimals` decimals; prices at most 5 significant figures AND at most
  `price_max_decimals` decimals; order notional must be ≥ `min_notional_usd`
  ($10 on Hyperliquid). Out-of-spec values are normalized or rejected at prepare.
- `GET /limits` / `PATCH /limits` — your bounded-autonomy rails (see §6).

## 3. Trade (prepare → sign → submit)

**Prepare** describes intent; the server validates it against your limits and
returns the exact payloads to sign (empty in paper mode):

~~~ts
const prep = await post("/orders/prepare", {
  market: "BTC",
  side: "buy",                       // buy | sell
  type: "market",                    // market | limit (limit needs limit_price)
  risk: { usd: 2, stop_price: 64000 }, // risk-first sizing: size = usd / |entry - stop|
  // ...or explicit: size: 0.001
  tp: 68000,                         // optional take-profit → atomic bracket
  client_order_id: "my-idempotency-key", // optional, unique per account
}, apiKey);
// → { order_id, mode, actions: [{ typed_data, description }], expires_at, sized }
// sized = { size, entry_ref, notional_usd }: the server's sizing audit trail.
// entry_ref is the price used for risk-first sizing (your limit_price, or the
// live mid at prepare time — it may differ slightly from the catalog price).
~~~

Minimum order notional is **$10** (Hyperliquid's floor) — smaller orders are
rejected at prepare with `size_too_small`. Sizes are rounded to the market's
`size_decimals` (see `GET /markets`), so make sure the rounded size still
clears $10.

**Sign** each `typed_data` locally, in order, exactly as returned (do not
re-format numbers or reorder keys):

~~~ts
const signatures = [];
for (const a of prep.actions) {
  signatures.push(await account.signTypedData(a.typed_data));
}
~~~

Some actions sign an opaque hash envelope (Hyperliquid L1 actions), others
readable typed data (builder-fee approval, withdrawals). Your signer treats
them identically. **Live orders are signed by your TRADING key** (§4) — the key
your owner key authorized on your trading wallet.

**Submit** within 30 seconds of prepare:

~~~ts
const result = await post("/orders/submit", { order_id: prep.order_id, signatures }, apiKey);
// → { status: "filled" | "resting" | "rejected", avg_px, size, ... }
// Paper mode: submit with signatures: [] — marketable orders fill instantly
// (live mid ± 5 bps); non-marketable limits REST and fill when the real price
// touches them. TP/SL become simulated triggers that fire against real price
// action (fills carry realistic maker/taker fees + slippage). Live mode rests
// real orders and triggers on HL. Same states either way: your strategy code
// runs identically in both modes.
~~~

Rejections are structured, e.g.
`{ code: "max_daily_loss_exceeded", details: { limit: 100, realized_today: -103.2, resets_at: "…T00:00:00Z" } }`.

### Managing positions and orders

- `GET /positions` — open positions (live: venue truth; paper: derived from your fills).
- `POST /positions/close` `{ market, size_pct? }` — returns a prepare envelope; sign + `POST /orders/submit`.
- `POST /positions/protect` `{ market, tp?, sl? }` — post-hoc reduce-only triggers; sign + `POST /intents/submit`.
- `POST /orders/cancel` `{ order_id }` — cancel a resting order; sign + `POST /intents/submit`.
- `GET /orders?status=&limit=` — your authoritative order ledger. Simulated
  paper triggers appear as `trigger_tp`/`trigger_sl` rows linked to their
  entry via `parent_order_id` (one firing OCO-cancels its sibling).
- Cancel and protect work in paper too: the envelope comes back with
  `actions: []` — submit it with `signatures: []`.

## 4. Go live: your trading wallet

LIVE orders trade from your **trading wallet**: a Hyperliquid account you own,
where fees settle automatically. You pay **0.25% per perps trade — the same
every human on the Terminal pays**: 0.10% builder fee, taken by Hyperliquid
inside each fill, plus 0.15% (UX fee + reserve), accrued from your real fills
and collected from the wallet's free USDC by our fee signer. You never sign a
fee, and a trade is never blocked to collect one: with no free USDC, it waits.

Three keys, three jobs:

- **Agent wallet** (the EOA you registered with): your identity — API keys,
  scope challenges, and withdrawals out of Hyperliquid (§7).
- **Owner key** (P-256, you generate it): owns the trading wallet. Only it can
  authorize a trading key or move money out. It never leaves your process.
- **Trading key** (secp256k1, a NEW address — Hyperliquid refuses to approve
  one that already has an account, so not your agent wallet): signs your
  orders. It is a Hyperliquid API wallet: it can trade, never withdraw.

Our signer on the trading wallet is locked by policy to two things: paying
trading fees to our treasury and approving our builder fee. It cannot send your
money anywhere else and cannot authorize anyone to trade it.

~~~ts
// 1. Create the trading wallet: your owner PUBLIC key + your agent wallet's signature.
const r1 = await post("/trading/wallet", { owner_public_key: ownerPubPem }, apiKey);
//    → { code: "owner_signature_required", nonce, message, owner_key_fingerprint }
const r2 = await post("/trading/wallet", {
  owner_public_key: ownerPubPem, nonce: r1.nonce,
  signature: await agentWallet.signMessage({ message: r1.message }),
}, apiKey);
//    → { wallet: { address, privy_wallet_id, owner_key_fingerprint }, deposit, fees, custody }
//    Check the fingerprint is yours before funding:
//    openssl pkey -pubin -in owner.pub.pem -outform DER | sha256sum
//    SAVE wallet.privy_wallet_id: every request you sign with your owner key must target it.
//    Your agent wallet must have no open positions or resting orders (agent_wallet_has_open_positions).

// 2. Fund it ON HYPERLIQUID: usdSend from your agent wallet's Hyperliquid account to
//    wallet.address (instant), or Circle CCTP (below). Hyperliquid refuses actions from an
//    account that never received a deposit, so this comes BEFORE step 3.

// 3. Authorize a trading key. Your OWNER key signs; we only relay it to Privy.
const tk = privateKeyToAccount(generatePrivateKey());   // a NEW key, no Hyperliquid history
const m = await post("/trading/key", {}, apiKey);       // → { code: "trading_key_proof_required", trading_key_message }
const proof = await tk.signMessage({
  message: m.trading_key_message.replace("<TRADING_KEY_ADDRESS>", tk.address.toLowerCase()),
});
const a = await post("/trading/key", { trading_key_address: tk.address, trading_key_proof: proof }, apiKey);
//    → { code: "owner_signature_required", time, payload_b64, verify, valid_until, how_to_sign }
// Check the bytes YOURSELF, against your own records — never against the response:
const req = JSON.parse(Buffer.from(a.payload_b64, "base64").toString("utf8"));
const td = req.body.params.typed_data;
assert(req.url === `https://api.privy.io/v1/wallets/${savedPrivyWalletId}/rpc` && req.method === "POST");
assert(req.body.method === "eth_signTypedData_v4" && td.primary_type === "HyperliquidTransaction:ApproveAgent");
assert(td.message.agentAddress === tk.address.toLowerCase() && td.message.nonce === a.time);
const owner_signature = crypto
  .sign("sha256", Buffer.from(a.payload_b64, "base64"), ownerPrivateKey)
  .toString("base64");
await post("/trading/key", {
  trading_key_address: tk.address, trading_key_proof: proof, time: a.time, owner_signature,
}, apiKey);
//    → { trading_key: { address, status: "active", valid_until }, builder_fee: "approved" }

// 4. Flip: POST /mode { "mode": "live" }. Then trade exactly as in §3, signing with tk.
~~~

**Never sign bytes you have not checked.** `payload_b64` is the exact request we
will send to Privy, as canonical JSON (base64 → UTF-8 → JSON). Your owner key
can do anything with the trading wallet, so no policy protects you here: decode
it and check every field against YOUR records — the `privy_wallet_id` you saved,
your trading key, your agent wallet, the amount you asked. `verify` lists them;
if anything else appears (a Withdraw, another agentAddress, another URL or
method), do not sign. Then sign those exact bytes: ECDSA P-256 over SHA-256,
DER-encoded, base64 (Node: `crypto.sign("sha256", bytes, ownerPrivateKey)`).
Send it back within 5 minutes with the same `time`; we rebuild the request from
your inputs, so a signature over anything else is rejected and nothing moves.

**Renewing.** Hyperliquid approvals last 180 days. `GET /trading/wallet` →
`trading_key.status` turns `renew_soon` 14 days before; repeat step 3 with the
same or a new key (it replaces the previous one). An expired key answers
`trading_key_expired`: nothing is lost, and only your owner key can
re-authorize.

**Money out.** `POST /trading/home { amount_usd }` moves USDC back to your agent
wallet inside Hyperliquid — the destination is always your agent wallet, and
pending fees are collected first (`fees_collection_attempted_usd`,
`fees_pending_usd`, shown when you call with your API key). `amount_usd` takes at
most 2 decimals and is exactly what gets signed. It returns one `payload_b64` per rail, each with its
`verify` list (destination = your agent wallet, amount = what you asked); check
and sign them with your owner key and repeat with `time` + `owner_signatures`.
At most one rail can execute; if HL rejects the first, ask again. From your
agent wallet, withdraw as in §7. It works while paused, and **without an API
key**: send `agent_wallet` in the body (e.g. if your account was terminated —
`account_killed` — or you lost your keys). Your owner key's signature is the
only authority it needs.

**Before 5 Nov 2026** a live order traded from the agent wallet itself. Until
you create a trading wallet, positions there can still be closed and protected
through the API (reduce-only); opening new ones answers
`trading_wallet_required`. Create the trading wallet only once your agent
wallet has nothing open (we check). With a trading wallet, every live action —
including closing — is signed by your trading key: if it expired, re-authorize
it first (only your owner key can).

**Funding any Hyperliquid address** (the response's `deposit` has every value
filled in for that address):

- **From a Hyperliquid account:** `usdSend` USDC to the address.
- **From Arbitrum, Base, Optimism or Polygon with Circle CCTP:** approve USDC
  to the TokenMessengerV2, then ONE `depositForBurnWithHook` with
  `destinationDomain: 19`, `mintRecipient` and `destinationCaller` =
  Circle's HyperCore forwarder, and the `hookData` we give you. Circle mints
  it straight into the perps account (fee $0.20 from Arbitrum, ~$0.25 from the
  others; quote it first with `hyperCoreDeposit=true`); you pay source-chain
  gas, nobody pays gas on Hyperliquid.

A plain USDC transfer on Arbitrum or any other chain does NOT reach Hyperliquid
(its old Arbitrum bridge is deprecated). Hyperliquid charges $1 to activate a
fresh account.

## 4b. Prediction markets (Polymarket)

Trade the outcomes of real-world events (elections, sports, crypto, economics…)
on Polymarket, from **your own deposit wallet**: a Polymarket smart wallet
(ERC-1271) derived from your agent wallet, which only your agent wallet
controls. The server builds every order with Polymarket's official SDK (order
book, tick size, fees, our builder code, price guards) and your agent wallet
signs it — the same **prepare → sign → submit** shape as perps. Everything here
is gasless for you (Polymarket's relayer sponsors it).

- **Live only.** There is no paper simulation for prediction markets: the account
  must be in live mode (`predictions_live_only`, 409, otherwise).
- **Opt in.** Add `"polymarket"` to `venue_allowlist` (§6; a widening — use
  `POST /limits/escalate` to apply it now).
- **Fees: the same everyone pays.** Polymarket's taker fee and our builder fee
  are charged inside the fill, on top of `amount_usd` — nothing extra to sign,
  nothing billed later.
- **Your caps count both desks.** `max_order_notional_usd` applies to each buy;
  `max_position_notional_usd` = perps notional + the current value of your open
  prediction positions + your prediction buys of the last 10 minutes at cost
  (Polymarket's data lags a fill, so a recent buy may count twice — never zero); `max_daily_loss_usd` = perps realized PnL + Polymarket's
  own PnL of today for your deposit wallet (hourly, up to ~2 h behind). Sells
  only reduce risk and skip the caps, like `reduce_only`. If a prediction read
  fails, new risk waits (`limits_check_unavailable`, 503) — never counted as 0.

**1) Activate (once).** `POST /predictions/activate` deploys your deposit wallet
and returns `actions[]` to sign with your **agent wallet** (EIP-712), in order:
`clob_auth` (links your Polymarket CLOB account — API credentials we store
encrypted; they can't move money: every order still needs your signature) and
`approvals` (a `DepositWallet.Batch` approving Polymarket's settlement contracts,
so your wallet can buy, sell and collect). Then
`POST /predictions/activate/submit { activation_id, signatures }` within 10 min.
If it answers `deploying` (202), repeat the same call ~30 s later. Nothing here
moves money. `GET /predictions/account` shows `status: "ready"` when done.

**2) Fund.** `GET /predictions/account` → `deposit.address`: send USDC on a chain
the Polymarket bridge supports (Polygon, Arbitrum, Base, Ethereum…). It lands as
pUSD (1 pUSD = 1 USD) in your deposit wallet within minutes (`cash_usd`). Min $3.

**3) Find a market.** `GET /predictions/markets?query=…` (public) → events with
markets and, per outcome, its `token_id` and `price` (a probability 0–1 = USD per
share; a winning share pays $1, a losing one $0). `GET /predictions/book?token_id=`
→ the live book.

**4) Trade.** Fill-or-kill market orders: they fill entirely at a protected price
or nothing happens.

~~~ts
const prep = await vd("POST", "/predictions/orders/prepare", {
  token_id: "…", side: "buy", amount_usd: 10,   // sell: { side: "sell", shares: 12.5 }
  // optional: max_spend_usd (all-in cap incl. fees), limit_price (buy: max, sell: min)
});
const sig = await account.signTypedData(prep.actions[0].typed_data); // your AGENT wallet
const fill = await vd("POST", "/predictions/orders/submit", { order_id: prep.order_id, signatures: [sig] });
// → { status: "filled", shares, avg_price, usd, venue_order_id, … }
~~~

The house price guard always applies (the same one a person gets): a buy is
judged against the whole book and capped ~3% above the best ask; a sell is floored
~3% below the best bid. `limit_price` can only make it stricter: off the market's price grid it is
rounded the strict way (down for a buy, up for a sell), and one that leaves no signable price is
`invalid_limit_price` (400). Sign within 60 s.
`not_filled` (409) = nothing was charged; `venue_status_unknown` (504) = it reached
Polymarket but the fill wasn't confirmed — read `GET /predictions/positions` before
retrying (reading positions, or preparing your next order, settles it in your ledger
once Polymarket answers).

**5) Positions & resolution.** `GET /predictions/positions` → shares, average and
current price, cost, value, P&L. When a market resolves, Polymarket collects
winning positions into your cash automatically. If one shows `collectable: true`,
`POST /predictions/redeem { condition_id? }` → sign → `POST /predictions/batches/submit`.

**6) Money home.** `POST /predictions/home { amount_usd | all: true, to_chain?: polygon|arbitrum|base }`
→ sign the batch → `POST /predictions/batches/submit { batch_id, signatures: [sig] }`.
Polymarket's bridge delivers native USDC to **your agent wallet** on that chain
(min $2). The destination is always your own agent wallet, so it needs no
withdrawal policy, works while paused, and works without an API key
(`{ agent_wallet }` in the body) — only your wallet's signature can execute it.
Your deposit wallet is yours: even without us, your agent wallet can execute a
batch on it directly on Polygon (paying its own gas).

Order events reuse `order_filled` / `order_rejected` with `venue: "polymarket"`;
new events `predictions_activated`, `predictions_funds_sent_home`,
`predictions_redeemed`.

## 4c. Earn and moving money between your accounts

Put idle money to work and move it where you need it — all from **your trading
wallet** (§4), with the same products and fees a person gets in the Terminal:

| Product | What it is | Entry fee | Exit | Lockup |
|---|---|---|---|---|
| **HLP** | Hyperliquid's market-making vault: you share its P&L (it can lose) | 0.55% (USDC) | free | 4 days |
| **HYPE staking** | delegate HYPE to a validator; rewards paid daily on the delegation | 0.25% (in HYPE) | free | 1 day per delegation + 7-day unstaking queue |
| **USDC lending** | USDC on Base in our Morpho vault (Gauntlet USDC Prime) | none — the vault keeps 20% of the yield | free | none |

`GET /earn` (read) → rates (as fractions: 0.05 = 5% a year), fees, lockups, the active validators (neutral order:
by stake — we recommend none), whether you can enter, and your balances and
positions in each product.

**Rules.** Live only. Entering a product (HLP deposit, buying HYPE, staking,
lending USDC, moving into predictions) needs an active account, the API key,
`"earn"` (or, into predictions, `"polymarket"`) in `venue_allowlist` (§6), and —
for Earn — a one-time eligibility certification: `POST /earn/certify
{ certify: true }` after reading `GET /earn → certification_text` (valid one
year; it is the OPERATOR who certifies; if your request comes from an excluded
country because your server runs there, add `confirm_operator_location: true`
only if the operator is elsewhere). Exits (HLP withdraw, unstake, sell HYPE,
USDC withdraw, delegate, spot ↔ perps, moving out of predictions or Base) work
**while paused**, and without an API key with `{ agent_wallet }` in the body —
your keys' signatures are what authorizes them, and the money never leaves your
own wallets. **Your exposure cap counts Earn:** `max_position_notional_usd` =
perps + predictions + what your trading wallet holds in HLP and in HYPE (spot and
staked) at market; HLP deposits and HYPE buys are also checked against
`max_order_notional_usd` and the daily-loss breaker. USDC lent on Base doesn't
count (it is cash earning interest). If an Earn read fails, new risk waits (503).

**One flow for everything: prepare → sign each step → submit.** Every endpoint
below returns `{ operation_id, summary, signatures_needed: [...], expires_at }`.
Each step names its signer:

- `"signer": "owner"` — your **OWNER** P-256 key signs `payload_b64` (base64 of
  the exact Privy request, canonical JSON), exactly as in §4: decode it and check
  every `verify` line against YOUR records first; then
  `crypto.sign("sha256", bytes, ownerPrivateKey).toString("base64")`.
- `"signer": "trading_key"` — your **trading key** signs `typed_data` (EIP-712),
  as it signs orders.

Then `POST /operations/submit { operation_id, signatures: [one per step, in order] }`
within 5 minutes. Every signature is checked **before** the first step is sent;
the steps run in order and stop at the first "no". When an operation has
**Base transactions** (USDC lending, Base → perps/predictions), also send
`owner_public_key` (your owner public key, SPKI PEM or base64; its fingerprint
must match your trading wallet's): Privy executes a transaction the moment it
receives it, so we verify all your owner signatures ourselves first.

The answer: `status` = `done` · `failed` (the first step was rejected — nothing
moved) · `partial` (a step executed and a later one was rejected: `steps` says
which, and `summary.if_partial` the call that finishes it — your money is in your
own wallet) · `uncertain` (202: a step was sent and the answer was lost; it MAY
have executed — check `GET /earn` before retrying). A submit runs for at most
~40 s: after that no further step is sent and it answers `partial` (prepare the
rest again) or `uncertain`. `GET /operations` lists your last ones, step by step;
`executing` there means a submit is still running — don't prepare the same thing
again until it ends.

~~~ts
const prep = await vd("POST", "/earn/hlp/deposit", { amount_usd: 50 });
const signatures = [];
for (const s of prep.signatures_needed) {
  if (s.signer === "owner") {
    const bytes = Buffer.from(s.payload_b64, "base64");
    checkAgainstMyRecords(JSON.parse(bytes.toString("utf8")), s.verify); // never sign blind
    signatures.push(crypto.sign("sha256", bytes, ownerPrivateKey).toString("base64"));
  } else {
    signatures.push(await tradingKey.signTypedData(s.typed_data));
  }
}
const r = await vd("POST", "/operations/submit", { operation_id: prep.operation_id, signatures });
// → { status: "done", steps: [...], summary: { amount_usd: 50, entry_fee_usd: 0.28, into_hlp_usd: 49.72, … } }
~~~

**HLP.** `POST /earn/hlp/deposit { amount_usd }` (min $5.03 — Hyperliquid takes
≥ $5 into a vault after our fee): the NET goes in (your trading key signs the
`vaultTransfer`; in a classic account a spot → perps step comes first); the fee
stays in your wallet and is collected right after the deposit lands — if HLP
rejects it, nothing is charged. `POST /earn/hlp/withdraw { amount_usd | all }`.

**HYPE staking.** No HYPE? `POST /earn/staking/buy { amount_usd }` (spot,
immediate-or-cancel at up to +1% from mid; 0.25% in USDC; Hyperliquid's minimum
order is $10; `outcome.hype_received` says what arrived after Hyperliquid's own
fee). Then `POST /earn/staking/stake { amount_hype, validator }` — two owner
steps: into your staking balance (the fee is earned here), then delegate. If the
delegation step fails, `POST /earn/staking/delegate { amount_hype, validator }`
finishes it for free. `POST /earn/staking/unstake { amount_hype, validator? }`:
with `validator` it undelegates first, then starts the 7-day withdrawal (max 5 in
the queue); without it, only the withdrawal of HYPE already undelegated.
`POST /earn/staking/sell { amount_hype | all }` turns spot HYPE back into USDC.

**USDC lending (Base).** Your trading wallet has the same address on Base. Move
USDC there (`POST /move { from: "perps", to: "earn_usdc" }`), then
`POST /earn/usdc/deposit { amount_usd | all }` (approve once + deposit in your
name) and later `POST /earn/usdc/withdraw { amount_usd | all }`. Gas is ~1¢ per
Base transaction, paid in USDC by your own wallet (we never pay gas), so a few
cents stay aside for this operation and for withdrawing later.

**Spot ↔ perps.** In a classic Hyperliquid account spot and perps are separate
balances: `POST /trading/transfer { amount_usd, to: "perps" | "spot" }` (free;
a unified account doesn't need it). Selling HYPE lands in spot.

**Moving money: `POST /move { from, to, amount_usd | all }`** between `perps`
(your trading wallet on Hyperliquid), `predictions` (your Polymarket deposit
wallet) and `earn_usdc` (your trading wallet's USDC on Base), in any direction.
No fee of ours; nothing ever changes owner:

| Route | How | Who signs | Costs |
|---|---|---|---|
| perps → predictions | `sendAsset` to YOUR deposit wallet's Polymarket deposit address (min $2.01) | owner | ~0.03%; the first time, Hyperliquid charges $1 to open that address |
| predictions → perps | Polymarket's bridge to Hyperliquid, to YOUR trading wallet | agent wallet (a predictions batch → `POST /predictions/batches/submit`) | ~$0.02 + ~0.1% |
| perps → earn_usdc | Circle CCTP to YOUR trading wallet on Base | owner | Circle $0.20; Hyperliquid gas ~$0.02 aside |
| earn_usdc → perps | Circle CCTP to YOUR trading wallet on Hyperliquid | owner (Base: approve once + burn) | Circle's live fee (~$0.26) |
| earn_usdc → predictions | USDC on Base to YOUR Polymarket deposit address (min $2.01) | owner (Base) | ~0.03% + gas |
| predictions → earn_usdc | Polymarket's bridge to YOUR trading wallet on Base | agent wallet (predictions batch) | ~0.1% |

Before money leaves Hyperliquid, pending trading fees are collected (as before a
withdrawal) and anything still pending can't leave. Moving into predictions
needs `"polymarket"` in `venue_allowlist`; the other routes work while paused.
For a route that goes to Polymarket, check `destination` yourself:
`POST https://bridge.polymarket.com/deposit {"address": "<your deposit wallet>"}`
→ `address.evm`.

Events: `earn_certified`, `earn_operation_done`, `earn_operation_partial`,
`funds_moved` (only when the money moved; from predictions, `status` says
`confirmed` or `pending` on Polymarket's relayer) and `funds_move_partial` —
each with `status`. A Base step counts as done only once it is mined; one that reverts is a
rejection, and one not confirmed in time leaves the operation `uncertain`.

## 5. Know thyself

- `GET /metrics?window=7d|30d|90d|all&mode=paper|live` — win rate, gross/net
  PnL (`net = gross − fees`), fees, max drawdown, Sharpe, equity curve.
  Computed server-side from your authoritative ledger.
- `POST /decisions` `{ reasoning, model?, input_summary?, order_id? }` → `{ ok: true }`.
  Log WHY you traded; pass `order_id` to correlate a decision to its trade.
  `GET /decisions` → `{ decisions: [ { id, order_id, model, reasoning, created_at, ... } ] }`.
  This trail is your audit log and future public track record (opt-in leaderboard coming).

## 6. Safety rails (enforced server-side at prepare, re-checked at submit — not suggestions)

`GET /limits` defaults: max order notional $250, max position $1,000, max
daily realized loss $100, withdrawals disabled (empty allowlist).

- `PATCH /limits` adjusts numeric limits, `asset_allowlist`, `venue_allowlist`.
- **Tightening is instant, loosening waits 24h — on everything.** Lowering a
  numeric cap (or setting one where none existed) applies immediately; raising
  a cap or setting it to `null` (unlimited) is staged in `pending_limits` and
  applies 24h later. The same goes for `asset_allowlist` and `venue_allowlist`:
  narrowing them is instant, widening them (adding an entry, or `null` = all
  assets) is staged for 24h. `withdrawal_allowlist` additions also take **24 hours**
  (removals are instant). Pending cap and asset/venue changes share one date:
  staging a new one restarts the 24h for all of them (`withdrawal_allowlist`
  additions keep their own). Tightening a field cancels any pending loosening of
  that field; `POST /kill` or a wallet-signed `/keys/revoke` cancels every
  pending loosening — here and in `/withdrawals/config` (the response carries
  `pending_cancelled`, or `pending_cancel_failed: true` if we could not confirm
  it — we are alerted, and you should check `GET /limits` and
  `GET /withdrawals/config`). While the agent is paused, the key can only
  tighten, here and in `/withdrawals/config` (`agent_paused`, 423): resume first
  (for limits, `/limits/escalate` also works; for `/withdrawals/config`, only
  `/resume`). A swap (`["BTC","ETH"]` → `["BTC","SOL"]`) drops ETH now and
  stages SOL (if the two lists share nothing, the current one stays until the new
  one takes effect); `reduce_only` orders and `/positions/close` ignore both allowlists, so
  narrowing never traps a position. If you think a key leaked, `/keys/revoke` — not
  `/kill` — is what evicts it. The point: a leaked API key can only make your rails
  stricter; it can never widen them or redirect funds — every consequential
  action also requires your wallet signature.
- `POST /limits/escalate` — the wallet-signed exception: applies loosening of
  caps and allowlists **immediately**. Call it with `{ limits: {...} }` to get a challenge
  bound to that exact patch, sign the message (EIP-191), call again with
  `{ limits, nonce, signature }`. Use this to un-brick a tripped daily-loss cap
  without waiting. `withdrawal_allowlist` additions still mature 24h even here.
- `asset_allowlist`: `null` (and `[]`, which is treated as `null`) clears the
  filter — all assets allowed. A non-empty array allows only those symbols.
  `venue_allowlist` may not be `[]` — use `POST /kill` to stop trading.
- Tripping `max_daily_loss_usd` blocks NEW risk until UTC midnight
  (`details.resets_at` on the rejection). `reduce_only` orders and
  `/positions/close` keep working — you can always exit risk. To resume opening
  positions sooner, raise the cap via `POST /limits/escalate`.
- `POST /kill` — instant pause; in-flight submits are rejected. While paused, every `trade`, `copy` or `withdraw`
  action answers `agent_paused` (423) — placing or cancelling orders, closing or protecting positions, preparing
  withdrawals and starting a live copy — except what only stops or tightens: `/kill`, `/resume`, tightening
  limits and withdrawal settings, `DELETE /copy/follows` (stop copying), webhooks, guardian, decisions, and
  `/mode` back to paper (switching to live waits for `/resume`).
  A key with `copy` (no `trade`) can `/kill` too.
- `POST /resume` (trade) — reactivates, and needs the **wallet's signature**: the api key alone cannot undo a pause,
  so a leaked api key cannot lift the brake its owner pulled. Call it with `{}` to get a challenge (`not_paused`,
  409, if there is nothing to resume), sign the message with the account wallet (EIP-191), and call again with
  `{ nonce, signature }`. The challenge is single-use, expires, and only works for resuming. If your bot also holds
  the wallet key, it can sign this too: `/kill` then pauses a bot that cooperates, not one you no longer trust — for
  that, take the wallet key away from it (and `/keys/revoke` if an api key leaked). Resuming gives every api key of
  the account its permissions back; if one may have leaked, revoke first.
- `POST /keys/rotate` `{ scopes? }` — new key now, old keys valid 24h more. A key can only mint scopes it already holds (no self-escalation). It retires the calling key plus only those keys whose scopes are a subset of the caller's; a key already in its 24h grace cannot rotate (`key_superseded`).
- `POST /keys/revoke` — wallet-signed, no api key needed: `{ address }` returns a challenge; sign it (EIP-191) and send `{ address, nonce, signature }`. Every key, including keys in their grace window, stops working **immediately**, and one new `["read","trade"]` key is returned. Use this to evict a leaked key.

## 7. Withdrawing your money

Whether the API can withdraw at all is the operator's choice, set per account:

- `GET /withdrawals/config` → `{ withdrawals_mode, autonomous_strict_destinations, guardian_linked }`.
- `PATCH /withdrawals/config` `{ mode?, strict_destinations? }` — `mode` is one of:
  - **`disabled`** (default): the API can never withdraw. Funds only leave by a human path. Choose this if you run a bot but keep control of the money.
  - **`autonomous`**: the AI withdraws on its own, gated by the rails below.
  - **`human_passkey`**: the AI initiates, a linked human guardian approves each withdrawal with a passkey verified server-side. Requires a linked guardian (else `guardian_not_linked`).
  - Loosening the mode (toward more autonomy: disabled → human_passkey → autonomous) takes **24 hours**; tightening is instant (autonomous → human_passkey applies immediately). `POST /kill` and `/keys/revoke` cancel a pending loosening, and a paused agent can't stage one (`agent_paused`, 423).
  - `strict_destinations: true` (autonomous only): withdrawals may go **only** to an address that has previously funded this agent — a leaked key can at most send money back to a funder.

### The guardian (human_passkey mode)

Your guardian is a human terminal user who approves each withdrawal with a
passkey ceremony our servers verify (WebAuthn assertion against a stored
credential — not a client-side check). Linking is opt-in and driven by you:

~~~ts
// 1. Mint a single-use invite (48h TTL) and hand accept_url to your human.
const inv = await post("/guardian", {}, apiKey);   // { invite_code, expires_at, accept_url }
// 2. They open accept_url, sign in, accept, and enroll their approval passkey.
// 3. Check the link: GET /guardian → { linked: true, ... } — now you can:
await patch("/withdrawals/config", { mode: "human_passkey" }, withdrawKey);
~~~

Withdrawing under human_passkey: `POST /withdrawals/prepare` returns
`approval_state: "pending"` (and an `intent_id`) instead of signable actions —
nothing moves yet. Poll `GET /withdrawals/pending`; when your guardian approves,
that intent shows `approval_state: "approved"` WITH fresh `actions` — sign them
and `POST /intents/submit` to execute. A rejection surfaces as
`approval_rejected`; an undecided request expires after 24h
(`approval_expired`). `DELETE /guardian` unlinks (instant; the mode then fails
closed — pendings can never be approved). All other rails (allowlist
maturation, strict destinations, caps, kill switch) apply underneath unchanged.

To actually withdraw (autonomous):

~~~ts
// 1. Grant the withdraw scope — a WALLET-signed step-up (not an api_key call).
const ch = await get("/keys/escalate", api_key);              // { message, nonce }
const sig = await account.signMessage({ message: ch.message });
const { api_key: withdrawKey } = await post("/keys/escalate", { nonce: ch.nonce, signature: sig }, api_key);

// 2. Allowlist the destination (24h maturation) and switch mode to autonomous.
await patch("/limits", { withdrawal_allowlist: ["0xYourDestination"] }, withdrawKey);
await patch("/withdrawals/config", { mode: "autonomous" }, withdrawKey);

// 3. After maturation: withdraw (prepare → sign → submit, same as everything else).
const prep = await post("/withdrawals/prepare", { destination: "0xYourDestination", amount_usd: 25 }, withdrawKey);
const sigs = await Promise.all(prep.actions.map(a => account.signTypedData(a.typed_data)));
await post("/intents/submit", { intent_id: prep.intent_id, signatures: sigs }, withdrawKey);
~~~

Withdrawals are Hyperliquid USDC to Arbitrum (min $2, HL nets a $1 fee). Errors:
`withdrawals_disabled`, `destination_not_allowlisted`, `destination_not_a_funder`
(strict), `insufficient_withdrawable`, `awaiting_approval` (human_passkey).

## 8. Jurisdiction & eligibility

By registering, the OPERATOR of this agent (the person or entity that controls
its key and funds it) represents that they are not located in, organized in, or
acting on behalf of any OFAC-sanctioned jurisdiction, and that using this API
to trade derivatives is lawful in THEIR jurisdiction. Your server's IP location
is not your jurisdiction — responsibility follows the operator, not the
datacenter. Requests from sanctioned jurisdictions are refused (HTTP 451).

Prediction markets add Polymarket's own terms: Polymarket does not allow trading
from some countries (including the United States). The operator is responsible
for being allowed to trade prediction markets where they are; using them through
this API does not change who may.

Earn adds the same eligibility certification a person gives (§4c): the operator
certifies, once a year, that it is not in a jurisdiction where these products
are excluded (`GET /earn → certification_text`). We never block by IP.

## 9. Operational notes

- Prepared actions expire 30s after prepare — sign promptly, re-prepare if late.
- `client_order_id` gives you idempotency (409 `duplicate_client_order_id` on reuse).
- Rate limits: 60 order-preps/min, 120 decisions/min, 10 challenges/min per IP.
  Limited responses carry `x-ratelimit-limit`, `x-ratelimit-remaining` and
  `x-ratelimit-reset` (DELTA seconds until the window resets — not an epoch);
  429s add `retry-after`. Back off until reset instead of hammering. Counters
  are per server instance and reset on every deploy: the headers always
  reflect the live counter that applies to you, but treat `remaining` as
  advisory — the authoritative signal is a 429 with `retry-after`.
- Every response carries an `x-vercel-id` header — that is your request id.
  Include it when reporting an integration issue; it correlates directly to
  our server logs.
- Pagination on `GET /orders` and `GET /decisions`: `limit` (max 200) +
  cursor. Responses include `next_cursor` (the timestamp of the last row, or
  null when there are no more); pass it back as `?before=<next_cursor>` to
  fetch the next older page.
- Paper resting orders and triggers are settled against real 1m price action
  (candle highs/lows — a crossing fills even if nobody was watching), checked
  every minute and again on your reads of `/positions`, `/orders`, `/me`.
  Fill timestamps land at detection, so expect up to ~60s of latency vs the
  actual crossing. Resting limits fill AT the limit price with maker fees;
  triggers fill at the trigger price ± 5 bps with taker fees.
- Common error codes: `agent_paused` (423), `prepare_expired` (410),
  `max_order_notional_exceeded`, `max_position_notional_exceeded`,
  `max_daily_loss_exceeded`, `asset_not_allowed`, `venue_not_allowed` (403),
  `signature_count_mismatch` (400), `venue_rejected` (502).
- Don't poll for state changes you can be TOLD about: `GET /stream` (SSE) and
  webhooks push fills, fired triggers, cancels, kill-switch flips, limit
  maturations and guardian decisions to you — see §15.

## 10. Endpoint reference

Every response is JSON. Auth = `Authorization: Bearer <api_key>` with the scope
listed. Errors follow `{ code, message, details? }` — see §11 for every code.
List endpoints accept `limit` (max 200, default 50); pass `status=` to filter
`/orders`. Machine-readable spec: `GET https://terminal.vectorialdata.com/api/agent/v1/openapi.json`.

| Endpoint | Auth | Rate limit | Request → Response |
|---|---|---|---|
| `POST /challenge` | none | 10/min/IP | `{address}` → `{nonce, message, expires_at}` |
| `POST /register` | none | 5/min and 10/h per IP; a shared cap across everyone | `{address, nonce, signature, label}` → `{api_key, wallet}` (key shown once). The documented funding routes (HL `usdSend`, CCTP with forwarding to perps) land directly on Hyperliquid and don't depend on our deposit sweep. USDC sent to your Arbitrum/Polygon addresses is found by the sweep, which visits agents in turns of 40: in your first 48 h, every 2 minutes per turn (minutes); from day 2 to day 7, and afterwards while you have a booked deposit, hourly per turn (ceil(agents/40) hours); otherwise once a day while you've used the API in the last 30 days (ceil(active agents/40) days; not at all after 30 days of inactivity). Instant detection starts once $10+ is booked (subject to a daily cap) |
| `GET /me` | read | — | → `{wallet, label, status, mode, scopes[], created_at, hyperliquid:{account, perp:{account_value_usd, withdrawable_usd}, spot_usdc}, polymarket:{deposit_wallet, balance_usd}, deposit:{asset, address, hyperliquid, cctp, do_not}, limits:{…§6}}` |
| `GET /markets` | none | — | → `{markets:[{id, symbol, name, asset_class, price, change_24h, volume_24h_usd, max_leverage, funding_apr, size_decimals, min_size, price_sig_figs, price_max_decimals, min_notional_usd}]}` |
| `GET /limits` | read | — | → limits row incl. `pending_limits`, `pending_limits_effective_at`, `pending_withdrawal_allowlist`, `pending_allowlist_effective_at` |
| `PATCH /limits` | trade | — | partial `{max_order_notional_usd?, max_position_notional_usd?, max_daily_loss_usd?, max_withdrawal_usd?, max_daily_withdrawal_usd?, asset_allowlist?, venue_allowlist?, withdrawal_allowlist?}` → updated row + `notice?` (loosening = pending 24h) |
| `POST /limits/escalate` | trade | — | `{limits}` → `{nonce, message}`; then `{limits, nonce, signature}` → row + `applied:"immediate"` |
| `POST /orders/prepare` | trade | 60/min | §3 request → `{order_id, mode, actions:[{typed_data, description}], expires_at, sized:{size, entry_ref, notional_usd}}` |
| `POST /orders/submit` | trade | — | `{order_id, signatures[]}` → `{status: filled\|resting\|rejected, avg_px?, size?, fee_usd?, closed_pnl_usd?, triggers?, venue_order_id?, child_statuses?, note?}` |
| `GET /predictions/markets` | none | 60/min/IP | `?query=&event_slug=&tag=&limit=&offset=` → `{events:[{event_slug, title, end_date, neg_risk, volume_24h_usd, markets:[{question, condition_id, market_slug, end_date, neg_risk, tick_size, min_order_size, volume_24h_usd, liquidity_usd, outcomes:[{name, token_id, price}]}]}], next_offset}` (§4b) |
| `GET /predictions/book` | none | 120/min/IP | `?token_id=` → `{token_id, tick_size, best_bid, best_ask, mid, bids:[{price, size}], asks:[…]}` |
| `GET /predictions/account` | read | — | → `{agent_wallet, deposit_wallet, status: ready\|activating\|not_activated, steps:{wallet_deployed, approvals, clob_linked}, cash_usd, deposit:{address, how, min_usd}, pending:{activation, batches:[{batch_id, kind, expires_at}]}, last_relayer, next?}` |
| `POST /predictions/activate` | trade | 10/min | `{}` → `{status: ready\|needs_signatures, deposit_wallet, activation_id?, actions:[{kind: clob_auth\|approvals, typed_data, description}], expires_at?}` |
| `POST /predictions/activate/submit` | trade | — | `{activation_id, signatures[]}` → `{status: ready\|approvals_pending\|deploying, deposit_wallet, clob_linked, relayer_tx?}` |
| `POST /predictions/orders/prepare` | trade | 30/min | `{token_id, side: buy\|sell, amount_usd (buy) \| shares (sell), max_spend_usd?, limit_price?, client_order_id?}` → `{order_id, mode:"live", venue:"polymarket", actions:[{typed_data, description}], expires_at, quote}` |
| `POST /predictions/orders/submit` | trade | — | `{order_id, signatures:[sig]}` → `{status:"filled", venue_order_id, token_id, title, side, shares, avg_price, usd, realized_pnl_usd?}` |
| `GET /predictions/positions` | read | — | → `{deposit_wallet, positions:[{token_id, condition_id, title, outcome, shares, avg_price, current_price, cost_usd, value_usd, unrealized_pnl_usd, realized_pnl_usd, end_date, resolved, collectable}], totals}` |
| `POST /predictions/home` | trade, or none with `agent_wallet` | 10/min | `{amount_usd \| all, to_chain?}` → `{batch_id, kind:"home", actions:[{typed_data, description}], expires_at, summary}` |
| `POST /predictions/redeem` | trade, or none with `agent_wallet` | 10/min | `{condition_id?}` → `{batch_id, kind:"redeem", actions, expires_at, summary}` |
| `GET /earn` | read | — | → `{trading_wallet, eligible:{live, active, earn_in_venue_allowlist, certified, certification_text?}, hype_price_usd, products:{hlp, staking:{validators[]}, usdc}, balances, positions:{hlp, usdc, staking}}` (§4c) |
| `POST /earn/certify` | trade | 10/min | `{certify: true, confirm_operator_location?}` → `{certified, certified_at, expires_at}` |
| `POST /earn/hlp/deposit` · `/earn/hlp/withdraw` | trade · trade or none with `agent_wallet` | 10/min | `{amount_usd}` · `{amount_usd \| all}` → an operation (below) |
| `POST /earn/staking/buy` · `/stake` · `/delegate` · `/unstake` · `/sell` | trade (buy, stake) · trade or none with `agent_wallet` (the rest) | 10/min | `{amount_usd}` · `{amount_hype, validator}` · `{amount_hype, validator}` · `{amount_hype, validator?}` · `{amount_hype \| all}` → an operation |
| `POST /earn/usdc/deposit` · `/earn/usdc/withdraw` | trade · trade or none with `agent_wallet` | 10/min | `{amount_usd \| all}` → an operation (Base transactions) |
| `POST /trading/transfer` | trade, or none with `agent_wallet` | 10/min | `{amount_usd, to: perps\|spot}` → an operation |
| `POST /move` | trade (into predictions) · trade or none with `agent_wallet` (every other route) | 10/min | `{from, to: perps\|predictions\|earn_usdc, amount_usd \| all}` → `{via:"operation", …operation}` or `{via:"predictions_batch", batch_id, actions, …}` |
| `POST /operations/submit` | trade, or none with `agent_wallet` (exits) | 10/min | `{operation_id, signatures:[…], owner_public_key? (Base transactions)}` → `{status: done\|failed\|partial\|uncertain, steps:[{step, status, detail?, tx_hash?}], summary, outcome?}`. An operation = `{operation_id, kind, summary, expires_at, signatures_needed:[{step, signer: owner\|trading_key, description, payload_b64 + verify \| typed_data}], how_to_sign, next}` |
| `GET /operations` | read | — | `?limit=` → `{operations:[{operation_id, kind, status, summary, steps, outcome, created_at, finished_at}]}` |
| `POST /predictions/batches/submit` | trade, or none with `agent_wallet` | 10/min | `{batch_id, signatures:[sig]}` → `{status: confirmed\|pending, kind, relayer_tx, summary}` |
| `GET /orders` | read | — | `?status=&limit=&before=` → `{orders:[{id, mode, venue, market, side, order_type: market\|limit\|trigger_tp\|trigger_sl, size, limit_price, tp_price, sl_price, trigger_price, reduce_only, grouping, leverage, notional_usd, client_order_id, parent_order_id, status, reject_reason, venue_order_id, prepared_at, submitted_at}], next_cursor}` |
| `POST /orders/cancel` | trade | — | `{order_id}` → intent envelope `{intent_id, kind, actions, expires_at}`; submit via `/intents/submit` |
| `GET /positions` | read | — | → `{mode, positions:[{market, size, entry_px, position_value_usd, unrealized_pnl_usd, liquidation_px, leverage}]}` (paper: derived from fills; liquidation_px/leverage null) |
| `POST /positions/close` | trade | — | `{market, size_pct?}` → prepare envelope; submit via `/orders/submit` |
| `POST /positions/protect` | trade | — | `{market, tp?, sl?}` → intent envelope; submit via `/intents/submit` |
| `POST /intents/submit` | trade | — | `{intent_id, signatures[]}` → `{status: done\|partial\|resting, …}` (kind-specific fields) |
| `GET /metrics` | read | — | `?window=7d\|30d\|90d\|all&mode=` → `{window, mode, perps:{fills, closing_trades, wins, losses, win_rate, gross_pnl_usd, fees_usd, net_pnl_usd, volume_usd, max_drawdown_usd, best_trade_usd, worst_trade_usd, sharpe}, predictions: null, equity_curve:[[ts, equity]]}` |
| `POST /decisions` | trade | 120/min | `{reasoning, model?, input_summary?, order_id?}` → `{ok: true}` |
| `GET /decisions` | read | — | `?limit=&before=` → `{decisions:[{id, order_id, model, reasoning, input_summary, created_at}], next_cursor}` |
| `POST /mode` | trade | — | `{mode: paper\|live}` → `{mode}` |
| `GET|POST /trading/wallet` | read / trade | 5/min | POST `{owner_public_key}` → `{code:"owner_signature_required", nonce, message, purpose, owner_key_fingerprint}`; POST `{owner_public_key, nonce, signature}` → `{wallet:{address, privy_wallet_id, owner_key_fingerprint, already_existed, fee_collection}, deposit, fees, custody, next}`; 409 `agent_wallet_has_open_positions` if your agent wallet has anything open. GET → `{wallet, trading_key:{address, status: active\|renew_soon\|expired\|none, valid_until}, balances, deposit, fees, custody}` (§4) |
| `POST /trading/key` | trade | 6/min | `{}` → 400 `{code:"trading_key_proof_required", trading_key_message}`; `{trading_key_address, trading_key_proof}` → `{code:"owner_signature_required", time, payload_b64, verify, valid_until, how_to_sign}` (409 `fund_trading_wallet_first` if unfunded); add `{time, owner_signature}` → `{trading_key:{address, status, valid_until}, builder_fee: approved\|pending}` (§4) |
| `POST /trading/home` | trade (also while paused), or none with `agent_wallet` | 6/min (3/min without a key) | `{amount_usd, agent_wallet?}` → `{code:"owner_signature_required", time, amount_usd, destination, fees_collection_attempted_usd, fees_pending_usd, requests:[{rail, payload_b64, verify}]}`; add `{time, owner_signatures:{sendAsset?, usdSend?}}` → `{status:"sent", rail}` or 202 `{status:"unknown"}` (check both balances before retrying) (§4) |
| `POST /kill` | trade or copy | — | `{}` → `{status: "paused"}` (+ `pending_cancelled` or `pending_cancel_failed`). Any key that acts can stop itself. |
| `POST /resume` | trade + wallet signature | — | `{}` → `{nonce, message, expires_at, purpose: "agent_resume"}` (still paused; 409 `not_paused` if nothing to resume); `{nonce, signature}` → `{status: "active"}` |
| `POST /keys/rotate` | read | — | `{scopes?}` (subset only) → `{api_key, scopes, previous_keys_valid_until}`. 403 `key_superseded` if the calling key is already in its grace window. |
| `POST /keys/revoke` | none (wallet signature) | 10/min | `{address}` → `{nonce, message, purpose}`; `{address, nonce, signature}` → `{api_key, scopes, revoked_keys}` (every key revoked now; + `pending_cancelled` or `pending_cancel_failed`) |
| `GET→POST /keys/escalate` | read | — | `?intent=enable_withdraw|enable_copy` (default withdraw). GET → `{nonce, message, purpose}`; POST `{nonce, signature, intent?}` → `{api_key, scopes, previous_keys_valid_until}`. Rotate can only narrow — new authority always costs a signature. |
| `GET /withdrawals/config` | read | — | → `{withdrawals_mode, autonomous_strict_destinations, guardian_linked, pending?}` |
| `GET /guardian` | read | — | → `{linked, accepted, guardian_label, linked_at, invite_pending, invite_expires_at}` |
| `POST /guardian` | trade | — | `{}` → `{invite_code, expires_at, accept_url}` (single-use, 48h) |
| `DELETE /guardian` | trade | — | → `{unlinked: true, withdrawals_mode: "disabled"}` (instant tightening); `unlinked: false` when there was nothing to remove |
| `GET /withdrawals/pending` | read | — | `?limit=` → `{withdrawals:[{intent_id, destination, amount_usd, approval_state, status, reject_reason, expires_at, decided_at, created_at, actions?}]}` (`actions` only when approved) |
| `PATCH /withdrawals/config` | trade | — | `{mode?, strict_destinations?}` → config + `notice?` (loosening = 24h) |
| `POST /withdrawals/prepare` | withdraw | — | `{destination, amount_usd, source?}` → intent envelope + `approval_state`; submit via `/intents/submit` |
| `GET|POST /copy/wallet` | read / copy | 5/min | POST `{owner_public_key}` → `{code:"owner_signature_required", nonce, message, purpose, owner_key_fingerprint}`; POST `{owner_public_key, nonce, signature}` (agent-wallet signature) → `{wallet:{address, ready_for_live, owner_key_fingerprint}, deposit:{asset, address, hyperliquid, cctp, do_not}, custody, next[]}`. Same key again → the same wallet; a different key → 409 `copy_wallet_owner_mismatch` |
| `GET /copy/leaders` | read | 30/min | → `{leaders:[{leader_id, name, terms:{min_capital_usd, success_fee_bps, mgmt_fee_bps_annual, mgmt_period_days, max_followers}, performance:{return_pct, return_basis, net_of_fees, max_drawdown_usd, max_drawdown_pct, sharpe, trades, open_positions, started_at}}], supported_modes:["live"], note}`. **A daily snapshot (UTC):** the same object all day, for everyone — it changes once a day. `return_pct` is the **time-weighted** return (`return_basis:"time_weighted"`): chained across every capital change, so the leader's deposits and withdrawals never inflate or dilute it. It is the only return we publish; `on_declared_capital` appears solely for a strategy with no history yet. |
| `GET /copy/follows` | read | — | → `{follows:[{leader_id, leader_name, mode, status, allocation_usd, started_at, result, retired?}], supported_modes:["live"]}`. A retired paper follow carries `result:null` and `retired:{code:"paper_copy_retired", message}` |
| `POST /copy/follows` | copy | 10/min | `{leader_id, allocation_usd, mode:"live"}` → live follow from your funded copy wallet. `mode:"paper"` → 410 `paper_copy_retired` |
| `DELETE /copy/follows?leader_id=` | copy | — | → `{leader_id, status:"stopped"}` (live: `"stopping"` while positions close) |
| `GET /stream` | read | 30 conns/5min | SSE event stream, `?cursor=<event_id>` or `Last-Event-ID` to resume → frames `{id, type, created_at, data}` (§15) |
| `GET /webhooks` | read | — | → `{webhooks:[…], max_webhooks, event_types_catalog}` |
| `POST /webhooks` | trade | 20/min | `{url, event_types?}` → webhook + `secret` (shown once) (§15) |
| `GET /webhooks/:id` | read | — | → webhook + `recent_deliveries` (last 20 attempts) |
| `PATCH /webhooks/:id` | trade | — | `{url?, event_types?, status?: "active"}` → updated (re-enable resets failure counter) |
| `DELETE /webhooks/:id` | trade | — | → `{deleted: id}` |
| `POST /webhooks/:id/test` | trade | 10/min, 100/day | `{}` → `{delivered, status_code, duration_ms?}` (synchronous signed test event; `duration_ms`, rounded up to whole seconds, only when your receiver answered; a failure always answers after the full 5s) |

## 10b. Copying a human strategy

A leader's **operations and open positions are visible only to followers copying
with real capital.** Everyone else — including you before you copy — sees each
leader's public stats as a **daily snapshot (UTC)**: the same numbers all day,
changing once a day. Paper copy was retired on 2026-10-20 (`mode:"paper"` →
410 `paper_copy_retired`; active paper follows were stopped with a
`copy_stopped` event, `reason:"paper_copy_retired"`). Simulating a copy means
seeing the leader's trades, which is exactly what is now reserved for followers
with money in the strategy.

```bash
# 1. See what is copyable — and read max_drawdown_pct, not just return_pct.
curl -s $BASE/api/agent/v1/copy/leaders -H "Authorization: Bearer $KEY"

# 2. Copy one with real funds from your copy wallet (create and fund it first, below).
curl -s -X POST $BASE/api/agent/v1/copy/follows \
  -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d '{"leader_id":6,"allocation_usd":500,"mode":"live"}'

# 3. Watch it. Your copy wallet is a Hyperliquid account you own: read its positions and every fee
#    transfer directly from Hyperliquid (clearinghouseState, userNonFundingLedgerUpdates) with the
#    address from GET /copy/wallet. (GET /positions reads your TRADING wallet, not the copy wallet.)
curl -s $BASE/api/agent/v1/copy/follows -H "Authorization: Bearer $KEY"
```

**Sizing.** Every mirror is sized on your copy wallet's **full value** — what you
funded plus profits, minus losses — in proportion to the leader's equity, not on
`allocation_usd`, which is only recorded (the copy wallet itself must hold the
leader's minimum). To copy with less, fund the copy wallet with less. Money you add to the
copy wallet later sizes the next mirrors too; open positions keep their size.

**Scope.** Writes need `copy`, not `trade`. Copying delegates decisions to a
third party — a different class of risk from sending your own orders — so an
operator can grant one without the other. New keys are minted with
`["read","trade"]`, and **`/keys/rotate` cannot give you `copy`** — it can only
narrow. Gaining authority always costs a wallet signature, the same bar as
`withdraw`:

```bash
# 1. Ask for a challenge scoped to THIS intent.
curl -s "$BASE/api/agent/v1/keys/escalate?intent=enable_copy" -H "Authorization: Bearer $KEY"
# 2. Sign the returned message (EIP-191) with the agent wallet, then:
curl -s -X POST $BASE/api/agent/v1/keys/escalate \
  -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d '{"nonce":"…","signature":"0x…","intent":"enable_copy"}'
```

The challenge carries the intent, so a signature given to enable copying can
never be replayed to enable withdrawals. And `enable_copy` does **not** hand you
`trade` along the way — if it did, the separation between "send my own orders"
and "follow someone else's" would be decorative.

**What paper reproduces faithfully:**

- Open-vs-close is decided by **arithmetic on `startPosition`**, not by the
  venue's display text. A liquidation does not say "close", and treating it as
  an open would put you short while you are still long.
- The same `sizeMirror` as live, **including the $10 minimum bump**. If your
  allocation is small enough that every mirror gets inflated to the minimum,
  your risk profile does not match the leader's — and you need to see that
  before funding, not after.
- The same adverse slippage and taker fee as the Agent API's paper engine. Two
  simulators that disagree are worse than one.

**What paper does NOT charge, so live is worse:** execution (0.10%), reserve
(0.05%) and the leader's success fee. Every response repeats this next to the
number so a model reading one array element still sees it.

**The success fee is charged on net profit.** `terms.success_fee_bps` applies to
each winning trade's profit after every fee of the round trip (Hyperliquid's
trading fee, execution and reserve, on entry and exit) and including the
position's funding with its sign (funding received adds, funding paid
subtracts), never to the gross PnL. A trade whose fees and funding exceed its
gross profit pays no success fee.

**Mirrors start at the leader's NEXT fill.** History is never backfilled — that
would hand you a record this agent did not live.

**Live copying is not available to agents yet** and returns
`501 live_copy_unavailable`. It needs two things that do not exist for agent
wallets: an `approveAgent` signature flow, and a way to collect fees from a
wallet the platform cannot sign for.

## 10c. Live copying: the copy wallet, and why it exists

**The constraint, stated plainly.** A Hyperliquid *agent* wallet can place
orders, cancel them, change leverage and move margin. It **cannot sign
transfers** — moving USDC always requires the master account's signature. That
is Hyperliquid's rule, not ours.

So collecting fees was never a permissions problem. It is a question of **who
holds the master key**. If that is your own process, then every fee needs a
fresh signature from you, and a leader can never know whether they will be paid.

**The copy wallet solves it without taking anything from you.** You create a
wallet whose *owner* is a P-256 key **you generate and keep** — Privy never sees
it, and neither do we. We are added as one extra signer, locked by a policy that
only permits sends to fee destinations. Then all four fees settle automatically,
forever, from one approval.

```bash
# 1. Generate a P-256 keypair. Keep the private key; send only the public one.
openssl ecparam -genkey -name prime256v1 -noout -out owner.pem
openssl ec -in owner.pem -pubout -out owner.pub.pem

# 2. Create the wallet (needs the 'copy' scope — see §10b). Binding an owner
#    key costs a signature from your AGENT WALLET, not just an API key: a
#    leaked key must never be able to make someone else the owner of the
#    wallet you are about to fund. First call → a message naming your key's
#    fingerprint; sign it (EIP-191) and repeat with nonce + signature.
curl -s -X POST $BASE/api/agent/v1/copy/wallet \
  -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d "{\"owner_public_key\": \"$(cat owner.pub.pem)\"}"
#    → {code:"owner_signature_required", nonce, message, owner_key_fingerprint}
curl -s -X POST $BASE/api/agent/v1/copy/wallet \
  -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d "{\"owner_public_key\": \"$(cat owner.pub.pem)\", \"nonce\": \"$NONCE\", \"signature\": \"$SIG\"}"
#    → {wallet:{address, owner_key_fingerprint, …}}. Check the fingerprint is
#    yours before funding: openssl pkey -pubin -in owner.pub.pem -outform DER | sha256sum

# 3. Fund the returned address ON HYPERLIQUID — only what you want to
#    allocate to copying. Your main trading wallet is untouched.
#
#    The response's deposit.hyperliquid / deposit.cctp say how, with the
#    CCTP hookData already computed for THIS address. A plain USDC transfer
#    on Arbitrum does not reach Hyperliquid; until the copy wallet holds the
#    leader's minimum there, a live follow answers 400 copy_wallet_underfunded.

# 4. Follow with mode:"live".
```

**What you keep.** You own the wallet. Withdraw whenever you like with your
owner key — you do not need us, and we cannot stop you. Our signer is confined
by policy to fee destinations; it cannot send anywhere else even if our servers
were compromised.

**What this buys you beyond fees: your trading agent never expires on you.**
Hyperliquid agent wallets die after at most 180 days. When one expires the
engine can no longer sign for that account — and neither can you through us —
which means **open positions cannot be closed by anybody**. The same policy that
lets us collect fees lets us rotate the agent before it lapses, so you never
have to think about it. Live copying always runs in a copy wallet: there is no
way to copy from your agent wallet or any other account.

**Going live, once the wallet is funded:**

```bash
curl -s -X POST $BASE/api/agent/v1/copy/follows \
  -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d '{"leader_id":6,"allocation_usd":500,"mode":"live"}'
```

**You sign nothing.** We authorize the trading agent and the builder fee on your
copy wallet ourselves, because the policy that confines our signer permits
exactly those two authorizations and nothing else. Neither can move money: a
Hyperliquid agent cannot withdraw — the protocol forbids it — and a builder-fee
approval only lets us charge a percentage of your fills, hard-capped at 10 bps.

The response tells you your trading agent's address and its `valid_until`.
Rotation is automatic, but the date is published anyway: a fact you can verify
against `extraAgents` on-chain is worth more than our promise to handle it.

**One leader at a time per copy wallet.** The copy wallet mirrors ONE leader:
closing a coin closes the whole position on the account, and stopping closes
everything, so two leaders would trade over each other. Following a leader while
another is `active` or `stopping` returns `copy_wallet_in_use` (409, stop);
following one you already follow returns `already_following` (409, stop).
Stop first (`DELETE /copy/follows`), wait for `stopped`, then follow the next.

**One trading agent per copy wallet.** Following again after you stopped — the
same leader or the next one — reuses the agent already authorized on it: nothing
new is signed, and `valid_until` is that agent's. A new one is authorized only
when none is left, or when the current one is within 30 days of expiry (it then
replaces the old one).

**Leaving:** `DELETE /copy/follows?leader_id=N` returns `status:"stopping"`, not
`"stopped"` — your mirrors are closed at market and accrued fees settled first.
Poll until it reads `stopped`. Your capital never leaves your copy wallet, and
only your owner key can withdraw it.

**Fees, and when each one lands:**

| Fee | Rate | Charged | How it is collected |
|---|---|---|---|
| Builder | 0.10% | every fill | Hyperliquid deducts it on-chain |
| Execution | 0.10% | every mirror | from your copy wallet |
| Reserve | 0.05% | every mirror | from your copy wallet |
| Success | leader's rate | profitable closes | from your copy wallet |
| Management | leader's annual rate, prorated | periodically | from your copy wallet |

Everything after the first row settles from the copy wallet with no signature
from you. Each charge is a transfer out of your copy wallet, visible on
Hyperliquid (`userNonFundingLedgerUpdates` for the address from
`GET /copy/wallet`), so you can reconcile independently — we expect you to.

There is no paper copy: to judge a strategy before copying, read its daily
public stats in `GET /copy/leaders`.

## 11. Error catalog

Structured as `{ code, message, what_to_do, support_ref }`.

- `code` — machine-readable and stable. **Decide with this, never with
  `message`.** The catalog below is the contract.
- `message` — fixed, human-facing, and deliberately free of internals. It
  will not tell you what broke; that is not an omission, it is the design.
- `what_to_do` — `retry` (transient, ours), `fix_and_retry` (change what
  you sent), or `stop` (we understood and said no; repeating gets the same
  no). When in doubt we say `retry`: leaving a strategy frozen over something
  that heals itself costs more than one extra request.
- `support_ref` — **your failure is already reported.** You do not have to do
  anything to file it; quote this reference to a human and they can pull the
  whole diagnosis. Empty only when the request failed before we knew who you
  were.

### Stuck? Escalate to a person

`POST /report` — `{ endpoint, what_happened, support_ref? }`. Use it when
you have already done your part (retried the transient, fixed what
`fix_and_retry` asked for) and still cannot proceed. It opens a ticket that
**pages a human and keeps paging until someone closes it** — the same queue a
person reaches from the app's support button. Pass your `support_ref` so the
escalation and the automatic record are one case, not two.

Three per day per agent. That is not a throttle to get around: a loop that
escalates on every failure would make the pager useless for everyone, including
you. Everything else you hit is already recorded without asking. A person is
paged when your account holds real money right now — at least $10 in your
Arbitrum address or on Hyperliquid (so a stuck first deposit of $10+ still
pages); otherwise the escalation is queued and reviewed, without a page. `support_ref` is reused only
if we issued it to your account. Your text reaches a person verbatim, fenced and
marked as untrusted.

Codes by family:

**Auth (401/403)**: `missing_token`, `bad_token`, `unknown_key`, `revoked_key`,
`insufficient_scope`, `scope_escalation_denied` (rotate can only mint scopes the
key already holds), `auth_unavailable` (503, retry).

**Registration (400/409/429/503)**: `invalid_body`, `bad_challenge` (missing,
expired, used, or wrong purpose), `bad_signature` (malformed),
`signature_mismatch` (recovers to a different wallet), `already_registered`,
`rate_limited`, `challenge_failed`, `register_failed`.

**Copy wallet (400/403/409/503)**: `bad_owner_key` (not a P-256 public key in
SPKI form), `bad_challenge` / `bad_signature` / `signature_mismatch` (the
owner-key binding signature), `copy_wallet_owner_mismatch` (409 — this agent's
copy wallet is bound to a DIFFERENT owner key; `details` carries its address and
fingerprint. Do not fund it unless that key is yours), `policy_failed`,
`wallet_create_failed`, `wallet_orphaned`.

**Prediction markets (400/403/404/409/410/423/502/503/504)**: `predictions_live_only`
(409 — switch the account to live), `venue_not_allowed` (403 — add `polymarket`
to `venue_allowlist`), `predictions_not_activated` (409 — `POST /predictions/activate`),
`predictions_credentials_invalid` (409 — re-activate: one new ClobAuth signature),
`invalid_token_id` / `amount_too_small` (buys ≥ $1) / `invalid_shares` /
`invalid_limit_price` (400), `insufficient_shares` (409), `book_unavailable` /
`positions_unavailable` / `chain_unavailable` / `markets_unavailable` (503 —
retry), `liquidez_insuficiente` (409 — not enough on the other side to fill all of
it at once; nothing was placed), `precio_sin_respaldo` (409 — the asks you would
pay are far above what buyers would pay back; nothing was placed),
`price_far_below_book` (400 — a sell priced far below the best bid),
`limits_check_unavailable` (503 — your caps count both desks and a prediction read
failed; reducing orders still work), `signature_wrong_signer` (403 — sign with your
AGENT wallet exactly the typed_data you were given), `prepare_expired` (410 — 60 s),
`not_filled` (409 — fill-or-kill missed; nothing charged), `rejected_by_venue`
(502), `venue_unreachable` (503 — nothing placed), `venue_status_unknown` (504 —
sent but unconfirmed: read `/predictions/positions` before retrying),
`order_format_unexpected` (502 — nothing placed), `clob_link_failed` (502 —
re-activate and sign promptly), `relayer_unavailable` / `relayer_rejected` /
`approvals_failed` / `batch_failed` (502/503 — nothing moved; prepare again),
`unknown_activation` / `unknown_batch` (404 — a batch also disappears 10 min after
it was prepared), `activation_expired` (410 — 10 min), `relayer_status_unknown`
(504 — sent to the relayer but not confirmed: it may still execute; read
`/predictions/account` before repeating), `insufficient_balance` (409),
`nothing_to_redeem` (409), `bridge_unavailable` (503).

**Trading wallet (400/403/409/500/502/503)**: `trading_wallet_required` (409 —
live orders trade from your trading wallet; closing from your agent wallet
still works), `trading_key_required` (409 — authorize one with
`POST /trading/key`), `trading_key_expired` (409 — re-authorize; nothing is
lost), `bad_trading_key` (400 — must be a NEW address: not your agent wallet nor
the trading wallet), `bad_trading_key_proof` (400/403 — the trading key itself
must sign `trading_key_message`), `owner_signature_invalid` (403 — Privy did not
accept it: sign exactly `payload_b64` with your OWNER key), `owner_signature_expired`
(400 — start again for a fresh `time`), `no_trading_wallet` (404),
`invalid_amount` (400 — `amount_usd` with more than 2 decimals),
`agent_wallet_has_open_positions` (409 — close positions and cancel orders on
your agent wallet before creating the trading wallet; `details` has the counts),
`fund_trading_wallet_first` (409 — deposit on Hyperliquid before authorizing
the key), `venue_unreadable` (503 — retry),
`trading_wallet_owner_mismatch` (409 — bound to a DIFFERENT owner key; do not
fund it unless that key is yours), `trading_key_not_recorded` (500 — Hyperliquid
approved it but we could not record it; support is alerted; retry with a NEW
key), `signer_unavailable` (503), `db_unavailable` (503), `venue_rejected`
(502), `amount_too_small` (min $1 for /trading/home), plus the copy wallet
codes above for the owner-key binding.

**Live copy (400/409/500/503)**: `copy_wallet_required` (409),
`copy_wallet_underfunded` (400 — fund it on Hyperliquid), `balance_unreadable`
/ `agents_unreadable` (503, retry — nothing was changed),
`activation_in_progress` (409, or 503 if we could not check — another
activation on this copy wallet is running; retry in a few seconds, nothing was
changed),
`agent_rotation_not_due` (409 — your copy wallet holds a trading agent we
cannot use, and a replacement is only allowed within 31 days of its expiry;
retrying will not change it, escalate with your `support_ref`),
`approve_agent_failed` (503), `builder_not_configured` (503),
`activation_not_recorded` (500).

**Trading rails (400/403/404/409/410/422/423/502)**: `size_too_small` (notional
< $10), `bad_risk` (stop equals entry), `bad_tp` / `bad_sl` (wrong side of the
mark), `unknown_market`, `no_price`, `max_order_notional_exceeded`,
`max_position_notional_exceeded`, `max_daily_loss_exceeded` (carries
`resets_at`; reduce-only still allowed — un-brick via /limits/escalate),
`asset_not_allowed`, `venue_not_allowed`, `market_blocked` (403 — a HIP-3 market whose
operator Vectorial Data no longer offers because it has been delisting its markets; reduce-only still allowed),
`agent_paused` (423, kill switch),
`duplicate_client_order_id` (409 — your idempotency key working),
`prepare_expired` (410 — re-prepare), `already_submitted` (409),
`signature_count_mismatch`, `signature_invalid`, `signature_wrong_signer`,
`reduce_only_would_increase` (422), `unknown_order`, `no_position`,
`not_cancellable` (409 — already filled/cancelled), `unknown_intent`,
`venue_rejected` (502 — HL said no; details carry the venue error),
`paper_fill_failed`, `prepare_failed` (503).

**Limits (400/409/423/503)**: `empty_patch`, `limits_update_failed`, `no_limits`,
`escalate_failed`, `limits_conflict` (409 — limits changed while your patch
applied; we already retried twice), `agent_paused` (423 — loosening while paused),
`revoked_key` (401 — the key was revoked while the request was in flight).

**Mode / lifecycle (400/409/503)**: `invalid_mode`, `invalid_window`,
`mode_failed`, `kill_failed`, `resume_failed`, `not_paused`, `rotate_failed`,
`no_account`, `account_killed`.

**Withdrawals (400/403/409/423/503)**: `withdrawals_disabled`,
`agent_paused` (423 — loosening `/withdrawals/config` while paused),
`revoked_key` (401 — the key was revoked while the request was in flight),
`config_update_failed` (503),
`destination_not_allowlisted`, `destination_not_a_funder` (strict mode),
`insufficient_withdrawable`, `amount_too_small` (min $2),
`max_withdrawal_exceeded`, `max_daily_withdrawal_exceeded` (atomic daily cap),
`bad_destination`, `awaiting_approval` (409 — guardian hasn't decided),
`approval_rejected` (403 — guardian said no), `approval_expired` (410 —
undecided for 24h), `guardian_not_linked` (422 — human_passkey needs a linked
guardian), `guardian_already_linked` (409 — unlink before re-inviting),
`ledger_write_failed`.

**Reads (400/503)**: `invalid_cursor` (400 — `?before=` must be the
`next_cursor` we returned; URL-encode it, though a `+` decoded to a space is
accepted), `invalid_status` (400 — `GET /orders?status=` must be one of
`prepared`, `submitted`, `resting`, `filled`, `rejected`, `cancelled`,
`expired`), `ledger_read_failed`, `metrics_read_failed`,
`decisions_read_failed`, `decision_insert_failed`.

**Streaming & webhooks (400/404/409/429/503)**: `invalid_cursor` (cursor must
be a non-negative integer event id), `invalid_webhook_url` (public https only —
no credentials, no private hosts; `details.reason` is one of `invalid_url`,
`not_public`, `not_allowed`, `unreachable`, `redirect`),
`webhook_limit_reached` (409 — max 5 per account), `webhook_not_found`,
`webhook_create_failed` / `webhook_update_failed` / `webhook_delete_failed` /
`webhooks_unavailable` (503), `rate_limited` (429 on stream connects, webhook
writes and tests).

## 12. Paper vs live — exactly what differs

| | Paper | Live |
|---|---|---|
| Signatures on submit | `signatures: []` — nothing to sign | sign every `typed_data` |
| Marketable fills | instant, live mid ± 5 bps, taker fee | real HL fills |
| Resting limits | rest + fill at limit on real price touch (maker fee, ≤~60s detection) | rest on HL's book |
| TP/SL triggers | simulated child rows, fire on real price ± 5 bps | real HL trigger orders |
| cancel / protect | work (empty-actions envelopes) | work (signed venue actions) |
| Where it trades | your simulated ledger | your trading wallet (§4) |
| Who signs | nothing | your trading key; your owner key only authorizes it and moves money out |
| Fees | simulated | 0.25% per perps trade (0.10% builder in the fill + 0.15% collected automatically) — the same everyone pays |
| Builder-fee approval | never | done for you on your trading wallet (you sign nothing) |
| Funding payments / liquidations | not simulated | real |
| Balances in /me | venue shows your real (unused) wallet | `trading_wallet.balances` |
| Everything else | identical: same endpoints, limits, kill switch, ledger, metrics | identical |

## 13. Changelog

- **2026-11-07 — Real-money orders from a connected AI app, approved one by
  one.** With the new `live` permission (asked on the sign-in screen; the
  person can uncheck it), a connected app can read the person's Terminal
  account (`GET /live/account`) and PROPOSE real orders on it
  (`POST /live/proposals`: open, close, protect, cancel). Nothing is sent
  until the person approves it in the Terminal (`approve_url`, 15 minutes);
  then it goes through the same path as their trade ticket. MCP tools
  `get_live_account`, `propose_live_order`, `get_live_proposal`,
  `list_live_proposals`, `cancel_live_proposal`; an older connection gets a
  403 `insufficient_scope` so the app asks the person again (§14).
- **2026-11-07 — Connect from Claude or ChatGPT with a sign-in.** `/api/mcp` is
  now an OAuth 2.1 protected resource (discovery at
  `/.well-known/oauth-protected-resource/api/mcp`, dynamic client
  registration, PKCE S256, rotating refresh tokens). Add the URL as a custom
  connector in Claude (web, desktop, mobile) or ChatGPT and sign in with a
  Terminal account: the app gets the person's own agent account, in paper mode
  only (§14). Tools that need an account now answer an HTTP 401 with
  `WWW-Authenticate` when called without a valid token, instead of a tool
  error. Header keys keep working exactly as before.
- **2026-11-06 — Earn and moving money.** HLP, HYPE staking (buy, stake,
  delegate, unstake, sell) and USDC lending on Base, plus `POST /move` between
  perps, predictions and Earn USDC in any direction — all from your trading
  wallet, every step signed by your own keys (§4c): `/earn`, `/earn/certify`,
  `/earn/hlp/*`, `/earn/staking/*`, `/earn/usdc/*`, `/trading/transfer`,
  `/move`, `/operations/submit`, `/operations`. Same fees as everyone
  (HLP 0.55%, staking 0.25% on entry; USDC lending 20% of yield). Opt in with
  `"earn"` in `venue_allowlist`. Your exposure cap now also counts HLP and
  HYPE (the rejection's `breakdown` has `earn_usd`). New events
  `earn_certified`, `earn_operation_done`, `earn_operation_partial`,
  `funds_moved`, `funds_move_partial`. Fixed: a LIVE order signed by your
  trading key could be refused as `signature_wrong_signer` at submit even when
  correctly signed (we re-derived the action in a different key order). MCP grows `get_earn`, `certify_earn`, `earn_hlp_deposit`,
  `earn_hlp_withdraw`, `buy_hype`, `sell_hype`, `stake_hype`,
  `delegate_hype`, `unstake_hype`, `earn_usdc_deposit`, `earn_usdc_withdraw`,
  `transfer_spot_perps`, `move_funds`, `submit_operation`, `list_operations`.

- **2026-11-06 — Prediction markets (Polymarket).** Trade event outcomes from
  your own deposit wallet with the same prepare → sign → submit flow (§4b):
  `/predictions/markets`, `/book`, `/account`, `/activate`, `/orders/*`,
  `/positions`, `/home`, `/redeem`, `/batches/submit`. Live only; opt in with
  `venue_allowlist`. Fees inside the fill, the same everyone pays. Your
  exposure and daily-loss caps now count perps and predictions together (the
  rejections carry a `breakdown`). New events `predictions_activated`,
  `predictions_funds_sent_home`, `predictions_redeemed`. MCP grows
  `list_prediction_markets`, `get_prediction_book`, `get_predictions_account`,
  `activate_predictions`, `place_prediction_order`, `submit_prediction_order`,
  `get_prediction_positions`, `send_predictions_home`,
  `collect_prediction_winnings`, `submit_predictions_batch`.

- **2026-11-05 — Trading wallet: agents pay what everyone pays.** LIVE orders
  now trade from your trading wallet (`/trading/wallet`, `/trading/key`,
  `/trading/home`; §4): your owner key owns it, your trading key signs orders,
  and fees settle automatically — 0.25% per perps trade, the same as every
  human, with nothing extra to sign and no trade ever blocked to collect a fee.
  Before, an agent paid only the 0.10% builder fee. Opening a live position
  from the agent wallet now answers `trading_wallet_required`; closing and
  protecting positions there still works. New events `trading_wallet_created`,
  `trading_key_authorized`, `trading_funds_sent_home`. MCP grows
  `get_trading_wallet`, `create_trading_wallet`, `authorize_trading_key`,
  `send_trading_funds_home`.

- **2026-07-23 — Streaming + webhooks**: `GET /stream` (SSE, cursor-resumable)
  and HMAC-signed webhooks (`/webhooks` CRUD + test) push your event spine —
  fills, fired triggers, cancels, kill switch, limit maturations, guardian
  decisions — instead of you polling (§15). New event kinds `order_filled`,
  `order_triggered`, `order_resting`, `order_cancelled`, `order_rejected`,
  `mode_changed`, `webhook_*`. MCP grows `list/create/get/delete/test_webhook`.
- **2026-07-19 — MCP server**: `/api/mcp` (Streamable HTTP) exposes the whole
  API as native MCP tools; paper trading executes end-to-end without code (§14).
- **2026-07-19 — Guardian human_passkey (withdrawals Phase D)**: the last
  withdrawal mode is live. `POST /guardian` invites a human guardian; they
  accept on the web and enroll a server-verified approval passkey; withdrawals
  then stay `pending` until approved (`GET /withdrawals/pending` to track;
  approved intents return signable `actions`). New codes: `guardian_not_linked`,
  `guardian_already_linked`, `approval_rejected`, `approval_expired`.
- **2026-07-19 — Pagination + ops notes**: cursor pagination on /orders and
  /decisions (`before` + `next_cursor`); request id (`x-vercel-id`) and the
  per-deploy rate-limit counter reset documented.
- **2026-07-18 — Paper v2**: resting limits fill on real price touch; TP/SL are
  simulated triggers (OCO); cancel/protect work in paper. New order_types
  `trigger_tp`/`trigger_sl` and `parent_order_id`/`trigger_price` fields in /orders.
- **2026-07-18 — Operator fixes**: precision metadata in /markets; rate-limit
  headers; `asset_allowlist: []` clears the filter; daily-loss no longer blocks
  reduce-only, rejection carries `resets_at`; wallet-signed `POST /limits/escalate`
  applies numeric loosening immediately; 24h loosening asymmetry documented.
- **2026-07-12 — Withdrawals (Phase C)**: `/withdrawals/config|prepare`,
  `/keys/escalate` step-up, modes disabled/autonomous(+strict), amount caps,
  atomic daily cap.
- **2026-07-07 — v1 launch**: register, paper/live perps prepare→sign→submit,
  rails, kill switch, metrics, decisions.

## 14. MCP server — connect without writing code

`https://terminal.vectorialdata.com/api/mcp` (Streamable HTTP) wraps this entire API as native MCP tools
for any MCP client (Claude, Cursor, VS Code, custom agents). Two ways in:

**A person in Claude or ChatGPT — sign in, no key.** Add `https://terminal.vectorialdata.com/api/mcp` as a
custom connector (Claude: Customize → Connectors → Add custom connector) and
sign in with a Vectorial Data Terminal account when the app asks. Standard
OAuth 2.1: protected resource metadata at
`https://terminal.vectorialdata.com/.well-known/oauth-protected-resource/api/mcp`, authorization server
metadata at `https://terminal.vectorialdata.com/.well-known/oauth-authorization-server`, dynamic client
registration, PKCE S256, one-hour access tokens and rotating refresh tokens
(a refresh token reused outside a short race window disconnects the app).
- The app operates the person's own **agent account** — one per person, shared
  by every app they connect — in **paper mode** (real money only through
  approved proposals, below). That account has no wallet key: its own live
  mode, deposits, prediction markets, Earn, moving money, webhooks and key
  management answer `403 connected_app_paper_only`
  (`connected_app_key` for `/keys/*`), and `get_account` shows no deposit
  address (never send funds to the account's address: it is an identifier).
- Scopes are `read` and `trade` (paper) and, if the person allows it, `live`;
  `withdraw` and `copy` are never granted.
- **Real money, approved one by one (`live`).** The app reads the person's
  Terminal account — `GET /live/account` (balance, positions in every market,
  open orders with `order_id`) — and PROPOSES orders on it with
  `POST /live/proposals`:
  `{ action: "open", coin, side, size_usd, leverage, order_type?: "market"|"limit", limit_price?, stop_loss?, take_profit?, note? }`,
  `{ action: "close", coin, fraction? }`, `{ action: "protect", coin, stop_loss?, take_profit? }`
  or `{ action: "cancel", coin, order_id }`. `leverage` is required on an
  open. A market open fills up to 5% from the price at approval (the trade
  ticket's own 1.5% → 3% → 5% ladder); a limit entry needs `stop_loss` and,
  if it crosses the market, must be within 5% of it; `take_profit` on an open
  goes with `stop_loss` (one bracket). Nothing is
  sent: the person gets a push notification on their devices (and sees it in
  the Terminal's bell), the answer carries `approve_url`, the person reviews
  and approves it in the Terminal within 15 minutes, and the Terminal places it on their main
  account through the same path as their trade ticket (same fees and checks).
  Poll `GET /live/proposals/{id}`: `pending`, `executed` (with the total
  fill or the resting `order_id`), `failed` (refused: nothing entered),
  `rejected`, `cancelled`, `expired` or `uncertain` (it may have
  entered: read the account before proposing again). Each app sees only its
  own proposals. Withdraw
  one with `POST /live/proposals/cancel`. At most 5 pending at once, 30 per
  hour; the agent's `max_order_notional_usd` and `asset_allowlist` apply, and
  `kill_switch` stops new proposals. A connection without `live` gets 403
  `insufficient_scope` from the MCP, so the app asks the person again.
- The person sees and disconnects apps, and resumes the agent after
  `kill_switch`, at `https://terminal.vectorialdata.com/agents/connections`.

**A bot with its own wallet — api key header.** Configure your agent api key as
a bearer header:

~~~
claude mcp add --transport http vectorialdata https://terminal.vectorialdata.com/api/mcp \
  --header "Authorization: Bearer vd_agt_…"
~~~

JSON client config equivalent:

~~~json
{ "mcpServers": { "vectorialdata": {
  "type": "http", "url": "https://terminal.vectorialdata.com/api/mcp",
  "headers": { "Authorization": "Bearer vd_agt_…" } } } }
~~~

- Public tools (`get_docs`, `list_markets`, `get_registration_challenge`,
  `register_agent`, `list_prediction_markets`, `get_prediction_book`) work
  without the header. Any other tool called without a valid token gets an
  HTTP 401 with `WWW-Authenticate: Bearer … resource_metadata="…"` (that is
  what makes an OAuth client open its sign-in, or renew an expired token).
- Prediction markets (§4b): `activate_predictions` → `place_prediction_order` →
  `submit_prediction_order`; `send_predictions_home` / `collect_prediction_winnings`
  → `submit_predictions_batch`. They are live only, so every one of them returns
  typed_data for your agent wallet to sign outside the MCP boundary.
- **Paper mode is fully executable through MCP alone** — paper needs no
  signatures, so `place_order`/`close_position`/`protect_position`/
  `cancel_order` execute end-to-end (a bare LLM can trade, check
  `get_positions`, and read its `get_metrics` tear-sheet natively).
- Live mode stays non-custodial: the same tools return the `typed_data` to
  sign with the agent's wallet OUTSIDE the MCP boundary; `submit_order` /
  `submit_intent` take the signatures. The MCP server can never move funds by
  itself, and money-out keeps every rail (allowlist, caps, guardian, kill).
- The tool surface mirrors this document 1:1 — same rails, same errors.

## 15. Streaming & webhooks — stop polling

Every meaningful change to your account is appended to your **event spine** and
pushed to you two ways. Event shape everywhere:

~~~json
{ "id": 12345, "type": "order_triggered", "created_at": "2026-07-23T…Z",
  "data": { "order_id": "…", "market": "ETH", "mode": "paper", "order_type": "trigger_sl",
            "side": "sell", "size": 0.05, "price": 3401.3, "trigger_price": 3400,
            "fee_usd": 0.08, "closed_pnl_usd": -12.4 } }
~~~

**Event kinds** — order lifecycle: `order_filled` (entry/limit fill, live and
paper), `order_triggered` (your TP/SL fired — subscribe to exits alone),
`order_resting`, `order_cancelled` (data.reason: `cancelled_by_agent`,
`oco_sibling_filled`, `position_closed`, `no_position_to_reduce`),
`order_rejected` (venue said no). Account: `paused`, `resumed`, `killed`,
`mode_changed`, `limits_updated` (incl. the 24h maturation applying),
`allowlist_change_requested` / `allowlist_change_applied` (your 24h clock).
Money-out: `withdrawal_prepared`, `withdrawal_pending_approval`,
`withdrawal_approved` / `withdrawal_rejected` (guardian decided),
`withdrawal_executed`. Guardian: `guardian_invited` / `_linked` / `_unlinked`,
`guardian_replace_ticket_issued` / `guardian_credential_replaced` (the
approver's passkey is being / was replaced).
Webhook admin: `webhook_created` / `_updated` / `_deleted` / `_disabled`.
The authoritative list: `GET /webhooks` → `event_types_catalog`.

### SSE stream (`GET /stream`, read scope)

~~~
curl -N https://terminal.vectorialdata.com/api/agent/v1/stream -H "Authorization: Bearer vd_agt_…"
~~~

- Frames: `id:` = event id, `event:` = kind, `data:` = the JSON above. A
  `hello` frame opens (your cursor + TTL); heartbeat comments every 15s.
- **Connections are finite on purpose** (~290s, serverless): you'll get a
  `goodbye` frame — reconnect with `Last-Event-ID` (or `?cursor=<id>`) and
  you miss nothing, because the cursor is the durable event id. Without a
  cursor you start at the tip (new events only).
- Freshness: events appear within ~1.5s of being recorded while events are
  flowing; when nothing happens the check spaces out to at most every 10s
  (`hello.poll_interval_max_ms`) and snaps back on the next event. Up to 10
  connection opens per account per 5 minutes (≈5 concurrent streams, with
  reconnects to spare); beyond that, 429 with `retry-after`. Paper fills are
  detected sub-minute while you're connected (the stream sweeps your resting
  orders every ~20s; the cron guarantees ≤60s regardless).
- Auth is the bearer HEADER only — no `?key=` (keys must never hit access
  logs). Native `EventSource` can't set headers; use any fetch-based SSE
  reader. The SDK ships one: `for await (const ev of agent.streamEvents())`.

### Webhooks (`/webhooks`, at-least-once, HMAC-signed)

For bots that aren't always connected: register up to 5 endpoints and we POST
each event to you.

1. `POST /webhooks` `{url, event_types?}` → returns `secret` (`vd_whsec_…`)
   **once**. `event_types` omitted/null = everything.
2. Each delivery: headers `x-vd-event` (kind), `x-vd-delivery-id`, and
   `x-vd-signature: t=<unix>,v1=<hex>` where
   `v1 = hmac_sha256(secret, t + "." + raw_body)`. Verify before trusting;
   reject if `|now − t|` > 5 min. SDK: `verifyWebhookSignature(secret, header, rawBody)`.
3. Respond 2xx fast (do the work async). Anything else (or >5s in total, body
   included — we read only your status code) = failure →
   retries at ~1m, 5m, 30m, 2h, 8h, then the delivery is dead-lettered
   (inspect via `GET /webhooks/:id` → `recent_deliveries`; `last_error` is
   `unreachable`, `not_public`, `redirect` or `http_<code>`). 20 consecutive
   failures auto-disable the endpoint (`webhook_disabled` event fires;
   re-enable with `PATCH /webhooks/:id {"status":"active"}`, at most 3 times a
   day per webhook).
   Limits that keep one account from crowding out the others: each retry run
   serves at most 10 due deliveries per account, least-recently-served accounts
   first; while other accounts are waiting, a webhook whose receiver is slow
   (>2s) yields after that delivery until the next run (its rest stay pending;
   your other webhooks keep going);
   up to 600 events per hour per account are delivered, and at most 300 may sit
   pending — past either, deliveries are recorded as dead with `last_error:
   "rate_limited"` or `"backlog_full"` (catch up from `GET /stream` with your
   cursor). Security and configuration events (keys, pauses, limits, withdrawals,
   guardian, mode, webhook changes) are always delivered; instead, the actions
   that emit them are limited: configuration changes (`/mode` to live, `/resume`,
   `PATCH /limits`, `/limits/escalate`, `POST /guardian`, `/withdrawals/config`,
   webhook create/update) share 60 per hour per account; new keys
   (`/keys/rotate`, `/keys/escalate`) 10 per hour; `/keys/revoke` 20 per day;
   `/withdrawals/prepare` 30 per hour. Changes that really tighten (lowering a
   cap, narrowing a list, removing a withdrawal address, less withdrawal
   autonomy, strict destinations on) use their own bucket of 60 per hour, which
   loosening never touches. Undoing something costs nothing: re-sending the
   current value to cancel a scheduled loosening, going back to paper,
   unlinking the guardian, deleting a webhook. So someone holding a stolen key
   can only use up your tightening bucket by actually tightening your account,
   and `/kill` (pauses and cancels everything pending) is never limited. A
   request that changes nothing returns the current state without emitting an
   event.
4. **At-least-once means duplicates happen** — dedupe by event `id`. Ordering
   is not guaranteed under retries; `id` is monotonic, use it.
5. `POST /webhooks/:id/test` sends a signed `webhook.test` event synchronously
   and reports your receiver's response — wire this up first.
6. URL rules: public https, no credentials, no private/internal hosts.

Happy-path latency: webhooks dispatch within seconds of the event (inline),
with the per-minute cron as the retry net. If you need sub-second reaction to
your own orders, remember the submit RESPONSE already tells you the outcome —
events are for the asynchronous world (resting fills, triggers, guardian
decisions, kill switches).

## Minimal helper

~~~ts
const BASE = "https://terminal.vectorialdata.com/api/agent/v1";
async function call(method: string, path: string, body?: unknown, apiKey?: string) {
  const res = await fetch(BASE + path, {
    method,
    headers: { "content-type": "application/json",
               ...(apiKey ? { authorization: "Bearer " + apiKey } : {}) },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const json = await res.json();
  if (!res.ok) throw Object.assign(new Error(json.message), json);
  return json;
}
const post = (p: string, b: unknown, k?: string) => call("POST", p, b, k);
const patch = (p: string, b: unknown, k?: string) => call("PATCH", p, b, k);
const get = (p: string, k?: string) => call("GET", p, undefined, k);  // GETs need the Bearer header too
~~~

That's everything. Generate a key, register, trade paper, prove yourself, go live.
