SDK reference
Every export of @nearai/financial-agents-sdk. Each method calls one API operation and shares its name: users.create calls Create a user, whose page lists every field. Request and response types come from the same schemas the API validates with.
Client
createFinClient(options)
Creates the client your server shares. It keeps no state between calls.
import { createFinClient } from "@nearai/financial-agents-sdk";
export const fin = createFinClient({
baseUrl: "https://api.example.test",
apiKey: "fin_example",
timeoutMs: 30_000,
maxRetries: 2,
});| Option | Type | Description |
|---|---|---|
apiKey | string | Your API key (fin_…). Sent to baseUrl and nowhere else. |
baseUrl | string | URL | Fin's API origin. A path prefix is kept. |
fetch | typeof fetch | The fetch to use. Defaults to the global one. |
timeoutMs | number | How long one attempt waits for response headers. Default 30 seconds. |
maxRetries | number | Retries of a safe request after a network failure, 429, 502, 503 or 504. Default 2. |
A request is safe to retry when it is a GET, a PUT (it replaces what is there, so repeating it changes nothing) or carries an idempotency key. The client is a FinClient: the partner operations below, plus fin.user.
fin.user(credentials)
fin.user({ userId, token }) scopes calls to one signed-in user, with token from users.createSession. It returns a FinUserClient with the user operations below. It costs nothing to create; make one per request.
Call options
Every method takes an options object last.
| Option | Type | Description |
|---|---|---|
signal | AbortSignal | Abandons the request, and any retry it is waiting on. |
idempotencyKey | string | A UUID made once per intent: a repeat returns the first result. Required by wallets.withdraw, wallets.swap, wallets.placeOrder, wallets.createDeposit, wallets.createDepositAddress, perps.openAccount, prediction.openAccount, solana.openAccount, solana.placeTrade and questions.answer; optional for runs.start, runs.steer and conversations.create. |
endUser | EndUser | The person using your app on whose behalf the call is made, as your server saw them. Fin records it beside the request so that a security question about their account can be answered later, and uses it for nothing else. Send what your server observed, never a value your client supplied. |
Their types are CallOptions, IdempotentCallOptions (key required) and OptionallyIdempotentCallOptions (key optional). EndUser is { ip?: string; userAgent?: string }, and either part may be left out. Fin ignores an ip that is not an IPv4 or IPv6 address and keeps the first 512 characters of userAgent. The client sends userAgent as printable ASCII, dropping other characters, and leaves out an ip a header cannot carry, so endUser never fails a call.
Users and sessions
Your API key alone calls these, on fin.
| Method | Returns | Description |
|---|---|---|
users.create(body) | ProvisionedUser | Creates the user for your userId, with their agent. A repeat returns the same user. |
users.createSession(userId, body) | CreatedSession | Opens a session: { controller } vouches for your own sign-in, and with createWallet a passkey you just created opens the account (createsWallet); { challengeId, signature } completes wallet sign-in. |
users.sessionChallenge(userId, body) | SessionChallenge | Starts wallet sign-in: the message the user signs. With createWallet, it also creates a new user's wallet. |
users.me({ token }) | User | Who a session belongs to. Rejects with 401 once it is invalid. |
users.revokeSession(session) | void | Signs { userId, sessionId, token } out. |
Partner
| Method | Returns | Description |
|---|---|---|
partner.usage(query?) | PartnerUsage | Requests and AI spend across your users. |
partner.quotas() | PartnerQuotas | Shared limits and current usage; periods[].capCents includes audited adjustments to current caps. |
partner.notifications(query?) | PartnerNotificationsPage | Your users' notifications after your cursor, oldest first, each with push: what your server delivers to their devices. Keep nextCursor, even from an empty page, and pass it back as after. |
partner.features() | PartnerFeatures | Every feature an operator turns on or off for your key rather than per user, such as market_briefs, and whether your key has it now. Read it each time you need the answer. |
Market briefs
| Method | Returns | Description |
|---|---|---|
market.subjects.list(query?) | MarketSubjects | What a brief can be about, by kind or by an identifier that names it. |
market.briefs.create(body, { idempotencyKey }) | MarketBriefJob | Use mode: "news" for news research even when quiet; default auto may answer ready at once, otherwise generating. |
market.briefs.get(id) | MarketBriefJob | A brief your key created: generating, then ready or failed. |
Market news
Your API key alone calls these too; the news is the same for every user, and no feature turns it on.
| Method | Returns | Description |
|---|---|---|
market.stories.list(query?) | MarketStories | The stories the market is telling, most recently confirmed first. Pass evidence: "reported" to leave out stories one unreviewed source tells, and subject for one coin or stock. A page can be short while nextCursor is set. |
market.stories.get(storyId) | MarketStoryDetail | One story: every source, the figures it states as they read now, and the moves on what it is about. Rejects with 404 story_not_found once Fin no longer shows it. |
market.headlines.list(query?) | MarketHeadlines | Articles from reviewed publishers, newest first, with the coins and stocks each headline names. subject reads the newest 300. |
market.moves.list(query?) | MarketMoves | What moved, newest first, one plain sentence each: one line per market and kind (per leaderboard for a lead change), a newer move replacing an older one. Narrow it with kind or subject. A page can be short while nextCursor is set. |
market.flows.get() | MarketFlows | Market cap, alt volume, perps open interest, stablecoin supply, DEX and launchpad volume, each with its change over a day, a week and a month. |
Conversations
Everything from here on is on fin.user({ userId, token }).
| Method | Returns | Description |
|---|---|---|
conversations.main() | Conversation | The main conversation every user starts with. |
conversations.create(body?, options?) | Conversation | A new conversation, for a separate thread. |
conversations.list(query?) | ConversationPage | The user's conversations, a page at a time. |
conversations.get(id) | Conversation | One conversation. |
conversations.delete(id) | void | Takes it out of the list; its history stays readable, and it takes no new messages. |
Runs
A run is the agent working on one message.
| Method | Returns | Description |
|---|---|---|
runs.start(body, options?) | Run | Sends a message: { conversationId, text, profile?, context? }. After a lost response or unavailable admission, retry with the same idempotency key and body to follow the original run. |
runs.get(runId) | Run | One run, with its reply once completed, the automation that started it (origin) and what it read (reads). |
runs.list(query?) | RunPage | Runs, optionally one conversation's. |
runs.cancel(runId) | Run | Stops a run; resolves once it has stopped. On stop_pending or execution_unavailable, read the same run and retry its stop as needed. Stop does not confirm a payment outcome or cancel a funded order. |
runs.steer(runId, body, options?) | Run | Sends the user's new message to a run that is still working: { text }. The agent reads it at its next step; the run lists it in steers. A run that ended answers 409 run_not_active, so send the text with runs.start instead. |
runs.sendFeedback(runId, body) | RunFeedback | The user's thumbs-up or thumbs-down on a reply once the run has ended: { rating: "up" }, or { rating: "down", reason? } with a reason from a fixed list. Sending again replaces it, and a run still going answers 409 run_active; the run's feedback shows it. |
runs.deleteFeedback(runId) | void | Deletes the feedback, so the run's feedback is null again. Safe to repeat. |
StartRunInput.context.perpsAllowed is an optional boolean your server reports for the current user's perpetual-futures region availability. Unlike context.contacts, it participates in retry identity; a changed value under the same key conflicts. Replaying an unchanged request does not refresh its saved observation time. See perps availability.
Voice
Let the user say their message instead of typing it. See talking instead of typing.
| Method | Returns | Description |
|---|---|---|
voice.get() | Voice | Whether the user can talk instead of type now (status), the longest recording to send (maxSeconds), and the formats it may be, each with its largest size (maxBytes). Show a microphone only while status is available. |
voice.transcribe(recording) | Transcription | One recording, { contentType, bytes }, in a type voice.get() lists (a Blob from MediaRecorder as it is when its type is listed, else made WAV first, as the SDK recipes guide shows), answered as { text } to put where the user writes. Nothing reaches the agent until they send it; an empty text means no speech was heard. It waits at least 75 seconds whatever the client's timeoutMs (Fin waits up to a minute for its speech model), and is never retried by the client, since each call is charged. |
Events
| Method | Returns | Description |
|---|---|---|
events.stream(conversationId, options?) | AsyncIterableIterator<FinStreamEvent> | The conversation's events: a replay, then live. |
events.list(conversationId, query?) | EventPage | Durable events after a cursor, oldest first. prediction.withdrawal updates its original call, including after the run ends; its unique linked deposit receipt establishes arrival. |
events.stream replays from cursor, then follows live. It reconnects after a dropped connection, a close, or a 429, 502, 503 or 504, resuming after the last durable event and honouring Retry-After. It ends when signal aborts.
| Option | Type | Description |
|---|---|---|
cursor | number | Resume after this durable seq. Default 0, the whole conversation. |
signal | AbortSignal | Ends the stream. |
endUser | EndUser | The person the stream is opened for, as a call's endUser. Every connection names them, a reconnect included. |
reconnect | boolean | Reconnect when the stream drops. Default true. |
onUnreadable | (event: UnreadableEvent) => void | Receives each event this version cannot read, which the stream skips. |
Each FinStreamEvent is { type, delivery: "durable", seq, requestId, payload } or { type, delivery: "live", payload }, and narrows on type. Live text arrives as agent.text_delta until the durable agent.entry replaces it. Events lists every type.
Approvals and questions
| Method | Returns | Description |
|---|---|---|
approvals.list(query?) | ApprovalPage | Approvals, including exact one-shot prediction_withdraw consent; pending ones by default, status: "all" for every one, and conversationId for one chat's. An approved money action names the wallet that signed it in signedBy. |
approvals.get(approvalId) | Approval | Exactly what it would do, and for money the authorization to sign. A Polymarket withdrawal binds the exact pUSD amountRaw and explicit maxLossBps. |
approvals.approve(approvalId, body) | Approval | Approves the stored terms. Money, including Polymarket withdrawal, carries { authorization: { controllerId, expiresAt, signature } }. |
approvals.deny(approvalId, body) | Approval | Denies, with an optional reason, and returns the approval. Denying withdrawal consent does not submit a transfer. |
questions.get(questionId) | Question | A questionnaire the agent asked. |
questions.answer(questionId, body, options) | Question | Answers { kind: "answers", answers }, leaving out any skipped question, or skips { kind: "skip" }. |
Portfolio
| Method | Returns | Description |
|---|---|---|
portfolio.get() | Portfolio | What the agent owns across every account now: the total, each account and each holding, with provisional figures and the unpriced holdings left out in excluded. Use it for any figure you show; it also asks Fin to re-read accounts last read over two minutes ago. See the portfolio and its history. |
portfolio.history(query) | PortfolioHistory | The value over a range (default 1D), optionally at a coarser step, with each point's gain and marks, and the range's summary. Its last point is portfolio.get()'s total. |
Agent wallet
| Method | Returns | Description |
|---|---|---|
wallets.get() | WalletStatus | The wallet, or while there is none, the creation message to sign. |
wallets.create(body) | Wallet | Creates the wallet with the user's signature, with an account-opening sign-in's (signIn), or with nothing from the session that opened the account with a new passkey. |
wallets.confirm(body) | Wallet | Confirms ownership of an existing wallet. Moves no funds. |
wallets.startSetup(body) | WalletSetup | Sets up the wallet with the same signature as wallets.create: the first Agent API step the user signs where Agent API wallets apply to them, otherwise the wallet at once. |
wallets.continueSetup(body) | WalletSetup | Sends the user's signature of a setup step: the next step, or the wallet. |
wallets.renewAccess(body) | WalletSetup | Renews the agent's access to an Agent API wallet: the step the user signs next. |
wallets.addDestination(body) | WalletSetup | Lets an Agent API wallet pay one more address (withdrawals, sends, venue funding): the step the user signs (then wallets.continueSetup), or the wallet when it is already allowed. policy_change_throttled with Retry-After within a few minutes of the last change. |
wallets.getAccount() | AccountWalletStatus | The wallet whatever its kind, named by intentsAccount (near, or an Agent API wallet's evm), or while there is none, the creation message to sign; renewal for an Agent API wallet. Use it once your partner is enabled for Agent API wallets. |
wallets.getAccountBalances() | AccountWalletBalances | wallets.balances with the wallet named by intentsAccount, for any wallet. |
wallets.openAccountSession() | AccountWalletSession | wallets.createSession naming the account by intentsAccount, for any wallet. Keep it on your server. |
wallets.balances() | WalletBalances | Available wallet holdings and a portfolio summary: the account's total, with what is available, in open orders and on its way from orders. Preserve a null total as unknown; reasons says why. See current portfolio values. |
wallets.supportedAssets() | SupportedAssets | What the wallet can hold, receive and send. |
wallets.listEarnVaults() | EarnVaults | The curated yield vaults, each provider's current, variable rate (null when it could not be read), the vault's payment asset and the user's own position: what their trades paid and returned in that asset, null with no shares. |
wallets.createSession() | WalletSession | A 1Click session for reading the wallet. Keep it on your server. |
Deposits and withdrawals
| Method | Returns | Description |
|---|---|---|
wallets.quoteDeposit(body) | DepositQuote | What a deposit of an exact amount would credit now, and the least it will. Creates nothing. |
wallets.createDeposit(body, options) | Deposit | Where and what to send to fund the wallet with an exact amount. |
wallets.getDeposit(depositId) | Deposit | One deposit and where it stands. |
wallets.listDeposits(query?) | DepositPage | Newest first; requestKey finds one after a timeout. |
wallets.createDepositAddress(body, options) | DepositAddress | A one-time address for one transfer of any amount, when the amount isn't known yet. |
wallets.getDepositAddress(depositAddressId) | DepositAddress | One deposit address and how its transfer is going. |
wallets.reportDepositTransaction(depositAddressId, body) | DepositAddress | Names the transfer that paid an address, so it is found sooner. |
wallets.quoteWithdrawal(body) | WithdrawalQuote | The priced terms and the message the user signs. |
wallets.withdraw(body, options) | Withdrawal | Withdraws with the quote's terms and signature; the key is its requestKey. After response loss, look up that key and follow the original withdrawal. Any retry keeps the same key and body; expiry alone never resolves uncertainty. |
wallets.getWithdrawal(withdrawalId) | Withdrawal | One withdrawal and where it stands. |
wallets.listWithdrawals(query?) | WithdrawalPage | Newest first; requestKey finds one after a timeout. |
Swaps
| Method | Returns | Description |
|---|---|---|
wallets.quoteSwap(body) | SwapQuote | The priced terms, with the least the swap receives, and the message the user signs. |
wallets.swap(body, options) | Swap | Swaps with the quote's terms and signature; the key is its requestKey. After response loss, look up that key and follow the original swap. Any retry keeps the same key and body; expiry alone never permits a replacement. |
wallets.getSwap(swapId) | Swap | One swap and where it stands. |
wallets.listSwaps(query?) | SwapPage | The user's own swaps, newest first; requestKey finds one after a timeout. |
Trades and orders
| Method | Returns | Description |
|---|---|---|
wallets.listTrades(query?) | WalletTradePage | The agent's trades, newest first; runId narrows to one run. |
wallets.getTrade(tradeId) | WalletTrade | One trade with its legs and settlement. |
wallets.getRemainingTradeActions(tradeId, options?) | RemainingTradeActions | Read current verified recovery candidates after later terminal receipts. This does not create a proposal or execute anything. Candidates distinguish unclaimed, conclusively not-executed and finally refunded prior attempts. |
wallets.prepareRemainingTrade(tradeId, options?, body?) | RemainingTradeProposal | A fresh review of the original root trade's verified recoverable unfinished branches. options.idempotencyKey identifies this review intent: reuse it with the same body after a lost response. Optional body.originalIndices selects original positions; body.maxValueLossBps explicitly chooses a higher all-in limit up to 1000 bps. The returned request needs a new owner signature. A conclusively closed group permits a new keyed review of remaining actions. |
wallets.prepareOrder(body) | PreparedOrder | The order's terms, with the least it receives in all, and the message the user signs. |
wallets.placeOrder(body, options) | WalletOrder | Places it with the prepared terms and signature; the key is its requestKey. After response loss, look up that key and follow the original order. Any retry keeps the same key and body; an unconfirmed order must not be replaced merely because its signature expired. |
wallets.listOrders(query?) | WalletOrderPage | Limit orders, newest first; requestKey finds one after a timeout. |
wallets.getOrder(orderId) | WalletOrder | One limit order, including reported position and separate payout reconciliation. |
wallets.cancelOrder(orderId) | WalletOrder | Records a cancellation request that continues after temporary outages; safe to repeat for the same order. Read the original order to confirm cancellation or a raced fill, and position for payout reconciliation. A request is not a confirmed refund. |
Grids
The agent creates a grid in chat, with the user's signed approval; these read and control it. See grid trading.
| Method | Returns | Description |
|---|---|---|
wallets.listGrids(query?) | GridPage | The user's grids, newest first. |
wallets.getGrid(gridId) | Grid | One grid: its approved terms, each cell's live order, completed cycles, realizedProfit and heldBaseRaw. |
wallets.pauseGrid(gridId) | Grid | Pauses an active grid: its resting orders are cancelled and nothing is placed. 409 grid_not_active in any other state that has not ended. |
wallets.resumeGrid(gridId) | Grid | Resumes a paused grid under the grant the user approved: every cell places again. 409 grid_not_paused in any other state that has not ended; 403 grid_trading_disabled when grid trading is off for the user. |
wallets.cancelGrid(gridId) | Grid | Stops an active or paused grid for good: the grant is revoked and its orders cancelled; nothing is sold, and what it bought stays in the wallet. Never gated, and safe to repeat. |
A grid that ended answers 410 grid_ended to every control, except that cancelling a grid the user already cancelled returns it.
Perps account
| Method | Returns | Description |
|---|---|---|
perps.openAccount(options) | PerpsAccount | Opens the account with a required idempotency key. Needs an agent wallet and the perps feature enabled; moves no funds. The agent's first deposit or opening order opens it too. |
perps.getAccount() | PerpsAccount | The opened account and its live Hyperliquid state with its open positions, even when the perps feature is off; 404 until opened. |
PerpsAccount is { address, createdAt, state }. Its PerpsAccountState is either { status: "observed", observedAt, accountValueUsd, withdrawableUsd, marginUsedUsd, positionCount, positions } or { status: "unavailable", reason }. All three USD values are exact decimal strings; an unavailable state is not a zero balance. Each PerpsPosition is { coin, size, entryPriceUsd, positionValueUsd, unrealizedPnlUsd, marginUsedUsd, liquidationPriceUsd, leverage, marginMode }, largest first and at most 100; its PnL is already in accountValueUsd, so never add it again. See opening a perps account. Positions may also include fundingSinceOpenUsd, the whole position's exact USD funding paid since open (negative when received), already reflected in the account value.
Prediction-market account and orders
| Method | Returns | Description |
|---|---|---|
prediction.openAccount(options) | PredictionAccount | Opens the Polymarket account with a required idempotency key; Fin continues setup automatically. Reuse the key after a lost response. Needs an agent wallet and the prediction feature enabled; moves no funds. The agent's first funding or order starts it too. |
prediction.getAccount() | PredictionAccount | Poll while opening until ready; reads never submit setup. Returns the account, its live pUSD balance and its positions even when the feature is off; 404 until opened. |
prediction.prepareOrder(order) | PreparedPredictionOrder | Checks a Polymarket order the user places themselves and returns it with the authorization message they sign and the requestKey to place it under. Nothing is reserved or placed. |
prediction.placeOrder(body, { idempotencyKey }) | PredictionOrder | Places the prepared order with the user's signature, with requestKey as the idempotency key. A retry with the same key and body answers the same order; an order the worker refuses is 409 prediction_order_changed. |
prediction.listOrders(query?) | PredictionOrderPage | Own retained orders in stable id order: { cursor?, limit? }. Follow nextCursor; reads remain available when placement is disabled. |
prediction.getOrder(orderId) | PredictionOrder | One order and its latest match/settlement observations. Use the resource's Fin id, not its venueOrderId; absent or foreign orders return 404. |
prediction.cancelOrder(orderId) | PredictionOrder | Requests same-order cancellation without a new spending approval. Safe to repeat; an uncertain result is not proof of cancellation. Existing fills remain visible. |
PredictionAccount is { address, signer, status, createdAt, balance, positions }. Its PredictionAccountBalance is { status: "observed", observedAt, pusd } or { status: "unavailable", reason }; pusd is an exact decimal string and an unavailable balance is not zero. PredictionAccountPositions is { status: "observed", observedAt, stale, positions, truncated } or { status: "unavailable", reason }; each PredictionPosition is { assetId, marketQuestion, outcome, sizeSharesDecimal, averagePriceUsdDecimal, currentPriceUsdDecimal, currentValueUsdDecimal, costUsdDecimal, unrealizedPnlUsdDecimal, redeemable }, largest value first and at most 100. stale is true while Polymarket rate-limits Fin and positions is the last read within the past hour, as of observedAt: show them as last known and never size a sale from them. See opening a prediction-market account.
Solana account and tokens
All thirteen are on fin.user({ userId, token }). The token reads take no userId in their path but need the user's session as every user operation does.
| Method | Returns | Description |
|---|---|---|
solana.openAccount(options) | SolanaAccount | Opens the agent's own Solana account with a required idempotency key. Needs an agent wallet and the solana feature enabled; moves no funds. The agent's first approved buy or funding opens it too; returns SOL and recognized token balances. |
solana.getAccount() | SolanaAccount | The opened account's SOL and recognized token balances, even when the feature is off; unresolved recognition makes holdings unavailable. 404 no_account until opened. |
solana.searchTokens({ query }) | SolanaTokenSearch | Candidates for a ticker, a name or a pasted mint, best match first, each with Fin's risk verdict. ambiguous says several share the top symbol. Needs the solana feature. |
solana.listTokens(query?) | SolanaTokenList | Sampled discovery (trending, traded, organic, new, gainers) with membership, exact-value liquidity/capitalization filters, age/launchpad filters, sorting and frozen nextCursor pagination. Includes classification, ranking reasons, source coverage and evidence gaps. Needs the solana feature. |
solana.getToken(mint) | SolanaTokenDetail | One token by its mint: market data, activity and the risk verdict. Needs no feature. |
solana.getTokenChart(mint, query?) | SolanaTokenChart | Closing prices and actual history coverage from the token's deepest pool, or why there are none: { interval?: "1m" | "5m" | "15m" | "1h" | "4h" | "1d" }. Needs no feature. |
solana.getTokenHolders(mint) | SolanaTokenHolders | The ten largest holders from the chain, each owner once with its share of the supply, kind (wallet or program, such as a pool or a bonding curve), the venue of a pool Fin recognizes and creator, with the holder count's holderChange as a percent per window; or unavailable with its reason. Needs no feature. |
solana.listTokenSparklines(query) | SolanaTokenSparklines | A small price line for each of up to 25 tokens from the prices Fin sampled, or why it has none: { mint, interval?: "1h" | "6h" | "24h" }. Needs the solana feature. |
solana.listTokenLaunchStatus(query) | SolanaTokenLaunchStatus | Where each of up to 25 tokens stands on its launchpad: curve with progressPct, graduated with graduatedAt, or unknown: { mint }. Needs the solana feature. |
solana.getTokenIcon(mint) | SolanaTokenIcon | The token's icon as Fin serves it: { contentType, bytes }, a PNG, JPEG, WebP or GIF. A 404 FinApiError when there is no usable icon, and a FinApiError with the answer's status when it is none of those types. Needs no feature. |
solana.prepareTrade(body) | PreparedSolanaTrade | Checks a buy or a sale the user places themselves, as the agent's own are checked, and returns the exact trade to show, authorization.message for the user to sign and the requestKey. Nothing is reserved or moved. A buy needs the solana feature; a sale needs the opened account (404 no_account). A token Fin does not trade is 403 solana_token_not_tradable. A buy carrying payWith is refused: only a chat approval pays a funding with a coin. |
solana.placeTrade(body, options) | SolanaTrade | Starts the prepared trade with { trade, authorization } and idempotencyKey: prepared.requestKey, from the agent's own Solana account; a first buy opens the account. Answers 201 with status processing. One trade runs at a time per user: a second is 409 solana_trade_changed, as is a token whose decimals or program changed. Retry the same key and body after a timeout; you get the same trade. |
solana.getTrade(tradeId) | SolanaTrade | A trade the user placed: status, failureReason, the stage it is on while it runs, paid, received and every transaction it signed. Its status is final by its completeBy, at most nine minutes past the signature. activity.list lists these trades as solana_trade items. |
SolanaAccount is { address, createdAt, holdings }. Its SolanaHoldings is either { status: "observed", observedAt, sol, tokens, valueUsd, unpricedCount } or { status: "unavailable", reason }. Every amount is exact: lamports and each token's amountRaw are integer strings in the asset's smallest unit, and USD values are decimal strings. tokens includes canonical wrapped SOL, venue-verified tokens without a suspicious flag whose mint facts match the chain, and tokens this account has a confirmed landed buy of, including buys paid in SOL. Names, symbols and prices alone do not establish recognition. Unrecognized receipts contribute to neither valueUsd nor unpricedCount. A recognized token without a price stays listed and counts in unpricedCount; unavailable balances or unresolved recognition are not an empty account. See opening a Solana account, finding Solana tokens and trading one from your own screen.
PredictionOrder is { id, order, observation }; the venue hash is observation.venueOrderId. Raw share, collateral and fee fields use six decimals. PredictionOrderPage is { data, nextCursor }. The agent places through the exact signed chat approval; the user places their own with prediction.prepareOrder and prediction.placeOrder. See Polymarket orders for consent and recovery, and placing one yourself.
Activity and budget
| Method | Returns | Description |
|---|---|---|
activity.list(query?) | ActivityPage | Trades, swaps, withdrawals, deposits, deposit addresses, Solana trades and transfers (a sale of several coins under one approval is its own solana_sell_many item), and automation changes, newest first. |
budgets.get() | Budget | How much of the user's AI budget is left. |
Features
| Method | Returns | Description |
|---|---|---|
users.listFeatures() | UserFeatures | Every feature an operator turns on or off per user, such as perps or solana, and whether this user has it now. Show only what they can use, and read it again when they come back. |
| Feature | Default | Consumer behavior |
|---|---|---|
feed_extension | off | Experimental feed extension pages and post handoff. Read it for the signed-in user; do not show /ticket, /ticket/done or /chat/from-post until it is explicitly enabled. Missing or failed reads mean off. It gates no financial tools or exits and grants no permission to transact. |
A post handoff is a draft, not a run. Only the user's explicit Send starts a new conversation; the post is quoted JSON data in the ordinary run text, not a new request field. The host freezes the user's feature decision at admission and adds its quoted-post guidance only to enabled requests, preserving the same statement when history is restored after targeting changes.
Features decided for your key rather than per user, such as market_briefs, are on partner.features(), which your key calls alone.
Notifications
| Method | Returns | Description |
|---|---|---|
notifications.list(query?) | NotificationsPage | What Fin told the user, newest first, with each one's text ready to show and unreadCount for a badge: { unread?, conversationId?, cursor?, limit? }. |
notifications.markRead(body) | MarkedNotificationsRead | Marks { notificationIds }, or { through } the newest one the user saw and everything older, read on every device. Safe to repeat. |
See notifications for the inbox, marking read and delivering pings from the feed, and for fin's own notices and the options they carry.
Suggestions
| Method | Returns | Description |
|---|---|---|
suggestions.list(query?) | PageSuggestions | What Fin suggests for one page, best first, from its latest read of the whole account: { surface?, timeZone?, country?, perpsAllowed? }. It never waits on the model; read again while status is thinking. |
suggestions.review(suggestionId, query?) | SuggestedMove | One suggestion checked again against the account now, with fresh review terms: call it when the user opens a review. 409 suggestion_changed when it no longer holds. |
suggestions.dismiss(suggestionId) | void | Not now: Fin leaves that kind of move on that subject out until the subject changes or seven days pass. |
See suggestions for how Fin's suggestions for the whole account are read, reviewed and set aside.
Idea baskets
Limited to enabled partners. See idea baskets for valuation and shared holdings.
| Method | Returns | Description |
|---|---|---|
baskets.list(query?) | BasketPage | The user's idea baskets, newest first: { cursor?, limit? }. Each includes its unused venue money. |
baskets.get(basketId) | Basket | One basket with settlement quantities, estimated values, cash kept back, its approval time and step count, failed steps by label, unused venue money, and server-computed performance (a planned seven-day estimate or actual since-bought return). Percentage decimals use percent units; missing history is explicit, never zero. |
baskets.delete(basketId) | void | Removes a basket from the user's ideas, draft or bought. Moves nothing. Refused with basket_buying while it buys and basket_awaiting_approval while an approval to buy it is open. Not gated by the baskets feature. |
baskets.link(basketId, { piece, operationId }) | Basket | Links an order the user placed to a step that did not buy, from that step's failures[].linkable, and returns the detailed basket including refreshed performance. Moves nothing; a repeat of the same link answers the basket. Refused with basket_step_not_failed, basket_step_linked or basket_order_not_linkable. |
Automations
| Method | Returns | Description |
|---|---|---|
automations.backtest(input) | BacktestReport | Replays a draft or saved automation with explicit starting holdings, per-purchase contributeInputs: true, or finite upfront funding: "strategy_budget"; automatic modes require empty initial holdings. Read capital contributions, status and limitations before showing performance. |
automations.list(query?) | AutomationPage | The user's automations. |
automations.get(automationId) | Automation | One automation. |
automations.pause(automationId) | Automation | Pauses it until resumed. |
automations.resume(automationId, { countMissedRun? }) | Automation | Resumes it under the permission it already has. countMissedRun: true counts the run fin paused over. |
automations.delete(automationId) | void | Deletes it. |
automations.listRuns(automationId, query?) | AutomationRunPage | What its firings did. |
automations.getRun(automationId, runId) | AutomationRun | One firing. |
automations.listReadings(automationId, query?) | AutomationReadings | What its sources read over time, field by field. |
automations.listSources() | AutomationSourceCatalog | What an automation can watch. |
automations.rotateWebhookSecret(automationId) | WebhookSecret | A new webhook secret, shown once. |
Errors
FinApiError
Every method rejects with it when Fin answers outside 2xx, and solana.getTokenIcon also when the answer is not a PNG, JPEG, WebP or GIF.
| Member | Type | Description |
|---|---|---|
status | number | The HTTP status. |
reason | string | undefined | Fin's machine-readable reason, such as credential_expired. See Errors. |
requestId | string | undefined | What to quote when you report the failure. |
retryable | boolean | Whether repeating the same request can succeed. |
problem | ProblemDetails | null | The RFC 9457 problem details, when the response was one. |
response | Response | The response itself. |
FinStreamError
events.stream rejects with it for a frame no reconnect can fix: an id that disagrees with its sequence, data that is not JSON, or an envelope that is not an event.
Helpers
paginate(list)
Iterates every item of a list, page after page. Pass a function that reads one page:
import { paginate } from "@nearai/financial-agents-sdk";
for await (const approval of paginate((cursor) => user.approvals.list(cursor ? { cursor } : {})))
console.log(approval.summary);It stops after the last page, or rejects with the first page that fails. Page<T> is one page: { data: T[]; nextCursor: string | null }.
isAuthorizationFor(subject, audience, toSign)
Whether toSign is Fin's authorization for this user, their agent and their registered wallet. toSign is any message Fin issues for a signature: an approval's authorization, a withdrawal or swap quote's authorization, or wallet creation's creation. subject is the user as users.me returns them, and audience your Fin deployment's origin.
requestRetryDelay(failures, retryAfter?)
Milliseconds to wait before repeating a refused request: capped exponential backoff (1 s, 2 s, 4 s, up to 30 s), or longer when Retry-After asks. failures counts the attempts that failed. The client uses it for its own retries.
Types
Every request and response type is exported by name.
| Area | Types |
|---|---|
| Users and partner | CreateUserInput, ProvisionedUser, User, SessionChallengeInput, SessionChallenge, CreateSessionInput, CreatedSession, PartnerUsageQuery, PartnerUsage, PartnerQuotas, PartnerNotificationsQuery, PartnerNotificationsPage, PartnerNotification |
| Market briefs | CreateMarketBriefInput, MarketBriefJob, MarketBrief, MarketBriefMode, MarketMetricProvenance, MarketSubjectsQuery, MarketSubjects |
| Market news | MarketStoriesQuery, MarketStories, MarketStory, MarketStoryDetail, MarketNewsSubject, MarketNewsSource, MarketFigure, MarketHeadlinesQuery, MarketHeadlines, MarketHeadline, MarketMovesQuery, MarketMoves, MarketNewsMove, MarketFlows, MarketFlow |
| Conversations | Conversation, CreateConversationInput, ListConversationsQuery, ConversationPage |
| Runs | StartRunInput, Run, ListRunsQuery, RunPage, SteerRunInput, RunSteer, SendRunFeedbackInput, RunFeedback, RunFeedbackRating, RunFeedbackReason |
| Events | FinEventType, EventPayload<T>, FinStreamEvent, StreamOptions, UnreadableEvent, ListEventsQuery, EventPage |
| Approvals and questions | Approval, ListApprovalsQuery, ApprovalPage, ApproveInput, DenyInput, Question, AnswerQuestionInput |
| Portfolio | Portfolio, PortfolioAssetRef, PortfolioHistoryQuery, PortfolioHistory |
| Agent wallet | WalletStatus, Wallet, CreateWalletInput, ConfirmWalletInput, WalletSession, WalletBalances, WalletPortfolioSummary, SupportedAssets |
| Perps | PerpsAccount, PerpsAccountState |
| Solana | SolanaAccount, SolanaHoldings, SolanaTokenHolding, SearchSolanaTokensQuery, SolanaTokenSearch, ListSolanaTokensQuery, SolanaTokenList, SolanaTokenSummary, SolanaTokenDetail, SolanaRisk, SolanaTokenChartQuery, SolanaTokenChart, PrepareSolanaTradeInput, PreparedSolanaTrade, PlaceSolanaTradeInput, SolanaTrade |
| Prediction markets | PredictionAccount, PredictionAccountBalance, PredictionOrder, PredictionOrderPage, ListPredictionOrdersQuery |
| Deposits and withdrawals | CreateDepositInput, Deposit, ListDepositsQuery, DepositPage, CreateDepositAddressInput, DepositAddress, ReportDepositTransactionInput, QuoteWithdrawalInput, WithdrawalQuote, WithdrawInput, Withdrawal, ListWithdrawalsQuery, WithdrawalPage |
| Swaps | QuoteSwapInput, SwapQuote, SwapInput, Swap, ListSwapsQuery, SwapPage |
| Trades and orders | ListTradesQuery, WalletTradePage, WalletTrade, PrepareOrderInput, PreparedOrder, PlaceOrderInput, ListOrdersQuery, WalletOrderPage, WalletOrder |
| Grids | ListGridsQuery, GridPage, Grid |
| Activity and budget | ActivityQuery, ActivityPage, ActivityItem, Budget |
| Features | UserFeatures, UserFeature, PartnerFeatures, PartnerFeature |
| Notifications | NotificationsQuery, NotificationsPage, Notification, NotificationOption, MarkNotificationsReadInput, MarkedNotificationsRead |
| Suggestions | PageSuggestionsQuery, PageSuggestions, SuggestedMove, ReviewTerms, SuggestionReviewQuery |
| Automations | Automation (with missedRun), ListAutomationsQuery, AutomationPage, AutomationRun, ListAutomationRunsQuery, AutomationRunPage, AutomationSourceCatalog, WebhookSecret |
| Idea baskets | Basket, BasketPerformance, BasketPerformancePosition, BasketPerformancePoint, BasketSummary, BasketHolding, ListBasketsQuery, BasketPage, BasketLinkableOrder, BasketLinkInput |
| Signatures | AuthorizationToSign, SignedAuthorization, AuthorizationSubject |
| Client | FinClient, FinUserClient, FinClientOptions, UserCredentials, CallOptions, EndUser, IdempotentCallOptions, OptionallyIdempotentCallOptions, Page, ProblemDetails |
FinEventType is every event type and EventPayload<T> one type's payload. AuthorizationToSign is a message to sign, with its controllerId and expiresAt; SignedAuthorization is the signature you send back with them.