Skip to content

CLI Reference — swarm ​

A terminal wallet and trading desk over the same package the SDK exposes: one Turnkey wallet, every supported chain, four trading venues, and a guard rail in front of anything that spends.

bash
npm i -g @swarm-ai-labs/turnkey-extensions   # or: npx swarm …
swarm login --email you@example.com
swarm holdings
swarm positions

Every command is one line of a shell script and one tool of an agent: reads print a table (or --json), writes preview first and do nothing until --confirm.


The execution model ​

Four rules cover every command that can move money.

1. Dry run by default. A write prints the exact order, transfer or route it would send and stops. --confirm is the only thing that reaches the key. The preview and the receipt have the same shape, so nothing is hidden between them.

2. A budget is mandatory to confirm. SWARM_BUDGET_USD caps what a single invocation may commit, and --confirm without it is refused. The cap is reserved before signing, so an over-budget order never reaches the key. A leveraged order reserves its notional, not its margin — a cap exists to bound exposure.

3. Standing limits outlive the invocation. swarm risk set stores a daily loss ceiling, a per-order ceiling, a leverage ceiling and a withdrawal whitelist. They are checked before any --confirm signs, and again per reservation. A daily-loss limit that cannot be evaluated stops the run.

4. Paper is not a preview. --simulate replaces the order with one written to the paper ledger. A dry run checks the account you have; paper trading exists to trade one you do not. --simulate with --confirm is refused — one of them is real money.

bash
swarm market hyperliquid buy --coin ETH --notional 250 --leverage 3   # preview
SWARM_BUDGET_USD=500 swarm market hyperliquid buy --coin ETH --notional 250 --leverage 3 --confirm

Addressing: profiles, aliases, flags ​

FlagWhat it does
--account <name>Use a saved profile's addressing (swarm config profile add).
--turnkey-key <key> --wallet <name>Discover addresses via the local turnkey CLI.
--org <sub-org-id>The wallet lives in a sub-organization.
--evm --sol --btc --tron --ton --suiPass addresses directly. NEAR is derived from the Solana key.

Naming any address flag opts out of the profile entirely — the two are never mixed, so --evm 0x… inspects exactly that wallet.

@alias expands from the address book before the command runs, so a dry-run preview always shows the address it will really send to.


Command reference ​

Identity ​

CommandWhat it does
loginEmail-OTP into a Turnkey sub-org. --expiration <seconds> widens the 1 h default.
whoamiWho signs right now: session email, sub-org, time left.
whoami --qr --chain tronDraw one of the session's addresses as a QR, with the address printed under it.
logoutDrop the stored session.

Portfolio and reads ​

CommandWhat it does
holdingsThe whole wallet across every chain plus ADI and 0G, valued. --sort, --hide-zero, --chain, --testnet.
balances <pairs…>Explicit chain:SYMBOL pairs. Accepts @file, - for stdin, and chain:* for every token on a chain.
positionsEvery open position across Hyperliquid, Binance, Polymarket and ADI, valued, with PnL.
ordersEvery resting order across those venues.
pnl [--since 7d]Realized, unrealized, fees and funding per venue. Venues that can only report lifetime figures say so.
report [--since 30d]The executed trades behind that PnL. --csv writes data to stdout and caveats to stderr.
cancel --allPull resting orders everywhere. --order / --instrument need one --venue.
rebalance --to <venue> --usd NWhere collateral sits, and the route to move some. Each leg is waited out before the next starts.
rebalance list | status <id> | resume <id>A route that died mid-way is resumed from its journal, never reconstructed.
prices <SYMBOL…>Spot USD price and 24h change.
activity [--chain X]On-chain history: native coin plus every token actually touched, across every chain with an address.
history [--pages N]The same wallet, paged — a cursor per feed, walking back N pages.
chart <SYMBOL>A price line in the terminal. --tf, --spark, and --watch for a live one.
dashPositions, orders and PnL stacked in one view, built from those same commands.

A venue that cannot be read is named in a NOTE line. It is never rendered as "no positions".

Transfers ​

CommandWhat it does
send <chain:SYMBOL> --to <addr> --amount NTransfer a coin or token. Dry run unless --confirm.
send --eip3009Sign an EIP-712 transfer authorization instead of a plain transfer (USDC and friends).
send --relayer <addr>Someone else submits the authorization and pays the gas; the owner spends no ETH.
send --batch @payouts.csvMany transfers from one file, under one budget. A single bad row refuses the whole file.
deposit adi:USDC --amount NFund the ADI vault with USDC. --qr prints a scannable transfer code.

Swaps and limit orders ​

CommandWhat it does
swap --from … --to … --amount NSwap a pair. Same-chain defaults to Uniswap, cross-chain to 1Click.
swap --provider <name>Pick the venue: 1click, uniswap, gaszip, lifi, or auto to quote them all and take the best.
swap --provider auto --prefer a,b --fallback cauto's order: --prefer wins before price, --fallback is asked only when nothing quoted (or SWARM_SWAP_PREFER, SWARM_SWAP_FALLBACK; SWARM_SWAP_PROVIDERS limits the poll).
swap --provider auto --routing inventoryauto's order from inventory's route plan (GET /routing), minus any venue it marks other than active (or SWARM_SWAP_ROUTING=inventory). Waits 1.5 s at most for it; without one, bebop then 1click, LI.FI as the fallback.
swap --providersList the venues, what each reaches, and any key it needs.
swap --intentsSwap the balance already inside intents.near — one signed token_diff, no origin transaction.
swap --eip3009Cross-chain only: sign the origin deposit as an authorization instead of a transfer.
swap --fee-serviceQuote through Aurora's keyed proxy so integrator fees are attributed.
limit --from … --to … --amount N --price PAn on-chain limit order via CoW Protocol — costs no gas and outlives this process.
limit list | cancel --uid <id> | --allOrders on the book.
feesOur integrator fee on every venue: rate, recipient, payout, and what each venue still needs.
fees earnings [--venue <name>]What Hyperliquid, Polymarket, LI.FI, 1Click and Jupiter report our fees have earned.
constants [section] [--search 0x…]Contract addresses, program ids, public hosts, chain ids, tokens and fee limits the package runs on.

Nothing re-routes silently: omitting --provider keeps today's routing.

Integrator fees come from the environment and are empty by default — a venue charges nothing until both its recipient and its rate are set. Rates are percents (0.25%); a value outside the venue's own range is ignored rather than rounded. Every swap preview states the fee before anything is signed.

Perpetual futures (market hyperliquid) ​

CommandWhat it does
markets [--search X]The perp board: mark, 24h, funding, OI, max leverage.
market --coin ETHOne perp in detail.
book --coin ETHThe order book — what is available to trade against.
status / positions / orders / fills / fundingAccount value and free collateral; positions; resting orders; trades; funding paid.
buy | sell --coin ETH --notional 100Open or add to a position. --margin sizes by own funds, --limit-px for a limit order, --tp/--sl attach triggers, --idempotent makes a retry safe.
close --coin ETH [--fraction 0.5]Flatten a position, or part of one, at market.
cancel --order <oid> | --all [--coin X]Pull resting orders.
leverage --coin ETH --value 5 [--isolated]The leverage the next position on a coin opens at.
tpsl --coin ETH [--tp N] [--sl N]Protect a position that is already open.
margin --coin ETH --add 25 | --remove 25Move an isolated position's liquidation price.
dead-man --minutes 10 | --offCancel every resting order if nothing checks in.
deposit --amount N / withdraw --amount NUSDC from Arbitrum onto the exchange, and back.
transfer --to 0x… --amount NUSDC to another Hyperliquid account — stays on the exchange, no bridge. An API-wallet destination is refused, naming its owner.
builder [status]Builders the wallet has approved, each with its fee cap (--evm for any address).
builder approve --builder 0x… --max-fee 0.05%Let a builder charge up to a fee per order. Signed by the main wallet. HYPERLIQUID_BUILDER + HYPERLIQUID_BUILDER_FEE then attribute every order.
builder revoke --builder 0x…Withdraw that approval.
builder discover [--window month] [--sample 150] [--top 10]Builders the busiest traders approved, with each builder's rewards, perp balance and account mode.
builder inspect [--builder 0x…]Whether users can approve a builder, and why not.
builder fees [--builder 0x…]A builder's fee earnings: earned (lifetime), unclaimed and claimed, per token. Defaults to HYPERLIQUID_BUILDER.
builder link [--builder 0x…] [--max-fee 0.1%] [--open] [--out f.html]Write a self-contained page users open to approve the builder from their own browser wallet (Hyperliquid's app cannot grant approvals). Host the file as is.
builder links [--builder 0x…]Hyperliquid pages for each task: approvals, rewards (claim), Account Type, the builder on the explorer.
builder ensure [--builder 0x…] [--max-fee 0.1%]Approve only when the wallet has not already approved that fee — signs at most once.
builder claimClaim the account's builder and referral rewards. Main wallet only.
account [--evm 0x…]How Hyperliquid sees an address: role (or API wallet of which owner), account mode, perps and spot.
account-mode --set manual|unified|portfolio|dexChange how the account pools balances. A builder needs manual: its $100 counts on perps only.
move --amount N --to perps|spotMove USDC between the account's perp and spot balances.
leaderboard [--window month] [--limit 20]The busiest accounts over a window. The first call downloads the ~37 MB leaderboard.
buy/sell/close/tpsl --builder 0x… --builder-fee 0.05% / --no-builderWho one order credits. Either flag alone borrows the other half from HYPERLIQUID_BUILDER / _FEE.

Prediction markets (market polymarket, market adi) ​

CommandWhat it does
polymarket markets --search <text>Tradable markets. --closed includes resolved ones.
polymarket book --asset <token id>The order book for an outcome.
polymarket statusTrading readiness on both the chain and the exchange.
polymarket fees [--asset <token id>]Fees on our flow, read from the API: the builder rate observed from attributed trades, plus the market's platform base fee. The configured rate is not readable anywhere, only what was billed.
polymarket builder [--period day|week|month|all]The builder's verification badge, rank, volume and users, read off the public builder leaderboard. The leaderboard lists verified builders only: a code absent from it with attributed trades is "not verified", one with no trades is "unknown".
polymarket setup --confirmDeploy the Deposit Wallet and grant approvals. --fund N moves collateral in.
polymarket bet --asset <id> --side buy --price P --size NPlace a bet; --market-order --amount N for market — N is what it spends, the fee included.
polymarket close --asset <id> [--size N] [--price P]Sell the held position at market, or --size N shares of it; --price P rests the sale on the book until a buyer takes it.
polymarket orders | positions | cancel | withdrawYour book, your shares, pulling an order, freeing pUSD out.
adi markets | book | positions | balances | ordersADI PredictStreet, public and per-wallet reads.
adi place | cancel | deposit | withdrawOrder lifecycle and vault funds. Withdrawals are dual-signed.

Tokenized equities (market xstocks) ​

CommandWhat it does
xstocks list [--search X]Active curated Solana xStocks from the inventory.
xstocks quote --side buy --symbol AAPLX --amount NA Jupiter USDC ↔ xStock quote. No wallet, no signature.
xstocks buy | sell --symbol AAPLX --amount NBuild and inspect the Jupiter transaction.

0G Compute (zg) ​

CommandWhat it does
zg statusLedger balance, provider sub-accounts, the wallet's own 0G.
zg providers [--search X]Inference providers, price per 1M tokens, uptime.
zg fund | refund | retrieveOpen or top up the ledger, take funds back, reclaim parked sub-accounts.
zg ack --provider XAcknowledge a provider's TEE signer, opening its sub-account.
zg topup --provider X --amount NAdd to a provider's sub-account.
zg chat --prompt "…" [--verify]Ask a provider and stream the reply, with TEE attestation.
zg delete-ledgerClose the ledger.

All zg actions take --testnet for 0G Galileo; writes are dry run unless --confirm.

AI signals (signals) ​

CommandWhat it does
signals listLive AI trade signals. --active, --coin, --limit.
signals show <id>One signal, with the rule that fired it.
signals watchTail the live stream until Ctrl-C.
signals watch --auto-open --usd NAlso take them as they arrive, under three ceilings: one shared budget, --max-concurrent, --max-signals.
signals strategiesThe strategy catalogue behind the signals.
signals open <id> --usd NTake a signal as a perp position. --usd is the notional, not your margin.

Backlog on connect is never taken — only signals arriving live.

Automation ​

CommandWhat it does
alert add --when "price:BTC < 90000"A rule that fires on the crossing, with a cooldown. --webhook, --telegram, --exec.
alert list | rm <id> | runrun is the daemon; it re-reads rules each sweep and reports failed deliveries.
exec twap --coin ETH --side buy --notional 5000 --slices 10 --over 30mOne large order released as many. ladder and iceberg too.
exec list | status <id> | resume <id> | cancel <id>The journal is written after every slice, so a crash leaves a record.
strategy check | backtest | run <file.json>A declarative recipe: alert-grammar conditions, execution-layer actions.
trail --coin ETH --distance 2%A trailing stop Hyperliquid does not have natively. It exists only while the process runs — and says so.

--telegram takes <bot-token>:chat:<chat-id> or <bot-token>:<chat-id> — the same string alerts.add({ telegram }) accepts. A bot token has a colon of its own (123456:AAE…), so without the explicit :chat: the target is split on its last colon; the chat id is a number (-100… for a group) or an @channel. A bare token, with no chat, is refused.

The budget is reserved for the whole parent order: ten $99 slices must not slip past a $100 cap, each honestly under it. Child order ids are derived from the parent, so a resend after a crash is refused as a duplicate rather than filling twice.

Safety and maintenance ​

CommandWhat it does
risk statusStanding limits, and today's realized PnL against them.
risk set --max-daily-loss 200 --max-order 1000 --max-leverage 5 --withdraw-whitelist @treasuryLimits that outlive one command. Pass 0 (or an empty list) to clear one.
approvals listERC-20 allowances this tool grants, riskiest first, with its scope printed.
approvals revoke --spender <addr> --chain <id>Set one to zero, naming what stops working first.
tx speedup | cancel --chain <id>Replace a pending transaction: same nonce, higher fee. cancel sends 0 to yourself.
fork --chain 1 --to <addr> --data <hex>Run a transaction on a throwaway forked chain and report gas and balance deltas. Needs anvil.
cex add binance --key <k> --secret <s>Store an exchange key — verified first, and refused if it can withdraw.
cex list | test | rm binancetest re-verifies: permissions can widen on the exchange without the file changing.
paper positions | pnl | fills | resetThe book --simulate writes to, shaped like the real one.

Discovery and screening ​

CommandWhat it does
screen funding [--min-apr 20%]Perps ranked by annualised funding, with the side that collects named.
screen spread [--min-spread 10%]Where Hyperliquid and Binance disagree about funding — a carry with no direction.
screen edge [--min-edge 0.01]Prediction markets whose outcome prices do not sum to 1. Every caveat prints with it.
inventory chains | tokensWhat the inventory knows: chains, tokens and deployments.

Agent surfaces ​

CommandWhat it does
mcp [--allow-writes]Serve the CLI as MCP tools over stdio. The layer never emits --confirm (there is no stripping pass — it is simply never built), and parameter values travel as --flag=value so one cannot be read back as a flag; --allow-writes only adds tools that price an order.
shellA REPL over the same commands. It does not strip --confirm — there is a human at the keyboard. set --account X carries a flag into every later line.

Configuration ​

CommandWhat it does
config showProfiles, address book, and which profile is active.
config profile add <name> [--evm … ]Name an addressing set so commands stop repeating it.
config profile use | rm | listSwitch, drop or list them.
config address add <alias> <address>The address book. Any flag written @alias expands before the run.

State lives under ~/.config/swarm-cli in 0600 files: session.json, config.json, risk.json, paper.json, cex.json, alerts.json, plus the exec/ and routes/ journals. The SDK reads the same documents through fsStore().


Global options ​

OptionWhat it does
--confirmActually do it. Required for every write; refused without SWARM_BUDGET_USD.
--simulateTrade on paper instead of for real. Refused together with --confirm.
--jsonMachine-readable output; live progress becomes one JSON object per line on stderr.
--watch [--interval 30s]Re-run a read on an interval and redraw in place. Refused with --confirm — a write must never repeat on a timer.
--no-progressSilence the live status lines (on by default, so a slow write does not look like a hang).
--log [info|debug]Report signing requests, prepared transactions, broadcasts and venue calls to stderr.
--log-json / --log-file <path>Those events as JSON lines, to stderr or appended to a file.
--slippage <bps>Same-chain swap tolerance (default 50 = 0.5%).
--testnetTestnet endpoints, where a command supports them.

A failed --watch refresh keeps the last good frame under a STALE banner: an empty table where your positions were reads as having none.

A logged run ends with its trace id on stderr — run 63d9b2ee — on the failing path as well as the clean one, after the error text, so it is the line that gets copied into a bug report. Every event of that run carries the same id, and command.run … → exit 2 records how it ended. Credentials in the command line are masked before it is logged. What each event means: observability.


Environment ​

Every variable the CLI and a server reading loadEnv(process.env) understand. A value outside its range or not a URL is ignored and reported — swarm config env shows what is set, masked, and why anything was dropped.

Endpoints (public defaults in ./constants) ​

VariableWhat it does
INVENTORY_API_BASESparkling inventory API. Required by balances, activity, inventory, market xstocks.
CUSTOM_INDEXER_API_BASESparkling Indexer — token discovery for holdings.
INDEXER_API_BASEPrice-graph indexer.
COINGECKO_API_BASECoinGecko-compatible price feed.
NEARBLOCKS_API_BASEnearblocks (NEAR activity).
FASTNEAR_API_BASEFastNear account API (NEAR tokens).
TURNKEY_BASE_URL / TURNKEY_API_BASETurnkey API — every call in the process uses it.
JUPITER_API_BASEJupiter Swap V2 API.
ONE_CLICK_API_BASENEAR Intents 1Click API.
AURORA_FEE_SERVICE_API_BASEAurora fee-service proxy.
SOLVER_RELAY_API_BASENEAR Intents solver relay.
POLYMARKET_CLOB_API_BASEPolymarket CLOB.
POLYMARKET_GAMMA_API_BASEPolymarket Gamma (market metadata).
POLYMARKET_DATA_API_BASEPolymarket data API (positions, activity).
POLYMARKET_RELAYER_API_BASEPolymarket relayer.
POLYMARKET_BRIDGE_API_BASEPolymarket bridge (deposit addresses).
HYPERLIQUID_API_BASEHyperliquid info + exchange API — an origin, no path (the SDK drops one).
HYPERLIQUID_APP_URLHyperliquid web app (links, builder approval page).
HYPERLIQUID_STATS_API_BASEHyperliquid stats files (leaderboard).
ADI_API_BASEADI PredictStreet core API for market adi and deposit adi only (--api-base wins).
ADI_TESTNET_API_BASEADI PredictStreet staging API.
LIFI_API_BASELI.FI API.
BEBOP_API_BASEBebop API.
GAS_ZIP_API_BASEgas.zip backend.
COW_API_BASECoW Protocol order book.
BINANCE_FUTURES_API_BASEBinance USD-M futures API.
ENVY_STREAM_URLEnvy signals proxy, version segment included (or --envy).
PRICE_STREAM_URLPrice-stream service origin — the live Polymarket trade tape.

RPC ​

VariableWhat it does
SOLANA_RPC_URLSolana JSON-RPC.
NEAR_RPC_URLNEAR JSON-RPC.
TRON_API_BASETronGrid REST.
TON_V2_API_BASEtoncenter v2 — public one answers 429 without a key.
TON_V3_API_BASEtoncenter v3 (jettons).
SUI_RPC_URLSui JSON-RPC.
BTC_MEMPOOL_API_BASEmempool.space-compatible REST.
EVM_RPC_URLSPer-chain EVM RPCs as comma-separated chainId=url pairs. Public defaults often refuse receipts.
ZG_RPC_URL0G JSON-RPC (mainnet, or Galileo with --testnet), or --rpc.

Order attribution ​

VariableWhat it does
POLYMARKET_BUILDER_CODEbytes32 builder code from polymarket.com/settings?tab=builder, signed into every order.
POLYMARKET_BUILDER_FEEBuilder fee the dashboard charges on each order; bets count it on top of the venue's fee.
HYPERLIQUID_BUILDERBuilder address credited on perp orders (after the wallet approves it).
HYPERLIQUID_BUILDER_FEEBuilder fee per perp order, up to 0.1%.

Integrator fees (empty charges nothing; see swarm fees) ​

VariableWhat it does
LIFI_INTEGRATORLI.FI integrator id (portal.li.fi; fee wallet per chain).
LIFI_FEELI.FI integrator fee, 0%–10%.
JUPITER_REFERRAL_ACCOUNTJupiter referral account (referral.jup.ag).
JUPITER_REFERRAL_FEEJupiter referral fee, 0.5%–2.55% (Jupiter keeps 20%).
ONE_CLICK_FEE_RECIPIENTintents account credited with 1Click appFees.
ONE_CLICK_FEE1Click appFees, 0%–5% (1Click keeps half).
ONE_CLICK_REFERRAL1Click distribution-channel tag (pays nothing).
BEBOP_FEEBebop partner fee, 0%–5%.
BEBOP_FEE_RECIPIENTWallet Bebop JAM pays the fee to.
BEBOP_SOURCEBebop-verified source the JAM key is issued to.
UNISWAP_FEE_RECIPIENTWallet swept the Uniswap fee.
UNISWAP_FEEUniswap fee from the output, 0.01%–1%.

Credentials (never logged; masked in swarm config env) ​

VariableWhat it does
ADI_API_KEYADI PredictStreet partner key (ps_live_…), or --api-key.
ONE_CLICK_JWT1Click partner JWT (partners.near-intents.org). Without it swaps pay +0.2%.
JUPITER_API_KEYJupiter API key (market xstocks).
LIFI_API_KEYLI.FI key — rate limit, and the integrator's transfer history.
BEBOP_API_KEYBebop RFQ key — production pricing, fee attribution.
BEBOP_JAM_API_KEYBebop Aggregation key (separate from RFQ's).
AURORA_FEE_KEYAurora fee-service key for swap --fee-service (or --fee-key).
POLYMARKET_BUILDER_API_KEY / POLYMARKET_BUILDER_KEYPolymarket builder API key — relayer writes (setup, --fund, withdraw).
POLYMARKET_BUILDER_SECRETPolymarket builder secret.
POLYMARKET_BUILDER_PASSPHRASEPolymarket builder passphrase.

CLI ​

VariableWhat it does
SWARM_GAS_SPONSORSHIPTurnkey Gas Station: off (default) | auto (sponsor on Ethereum, Base, Polygon, Solana) | required (sponsor or refuse).
SWARM_BUDGET_USDMandatory USD spend cap for a --confirm run.
SWARM_TURNKEY_KEYLocal turnkey CLI key name (default "default").
XSTOCKS_LIVEMust be 1 before market xstocks buy|sell --confirm executes.
SWARM_SWAP_PROVIDERSswap --provider auto polls only these venues (comma-separated); omit one to switch it off.
SWARM_SWAP_PREFERswap --provider auto: venues that win before price, best first (or --prefer).
SWARM_SWAP_FALLBACKswap --provider auto: venues asked only when none quoted (or --fallback).
SWARM_SWAP_ROUTINGswap --provider auto sweeps by inventory's route plan (GET /routing); refused beside the three above (or --routing).
SWARM_ANVILanvil binary for fork.
SWARM_DEBUG_STACKPrint the stack behind an unexpected error.
SWARM_CONFIG_DIRWhere CLI state lives (default ~/.config/swarm-cli).

Exit codes ​

CodeMeaning
0It worked (including a dry run that printed a plan).
2The operator got something wrong — a bad flag, a refused limit.
1Something else broke: an RPC, a venue, the network.

The split is deliberate: a script can retry a 1 and must not retry a 2.


The same thing headlessly ​

Every command here is a call on the SDK's product API — swarm holdings is swarm.portfolio.holdings(), market hyperliquid buy is perps.open(). If you are automating rather than typing, see SDK.md.

Released under the MIT License.