A typed, ergonomic TypeScript client for the AlphAI REST API — relevance-scored, ticker-linked financial news plus SEC Form 4 insider data, built for AI agents and trading bots.
- Fully typed — hand-written types for every endpoint, money kept as precise decimal strings, timestamps as ISO 8601 strings.
- Runs everywhere — Node ≥18, browsers, edge runtimes, Deno, and Bun. Uses the
native
fetch; zero runtime dependencies. - Ergonomic — resource namespaces (
client.news.*,client.symbols.*), async iterators for pagination, automatic retries with backoff, typed errors, and rate-limit inspection. - Dual module — ships ESM + CJS with
.d.ts.
Covers news search, feeds (press and SEC filings), symbols, Brief, Radar, the coverage passport and the insider CSV export. Calendar, macro and insider-trades are a plain
fetchaway. API-key management (create / revoke) happens on the website at/account/api-keys— this SDK only consumes a key.
npm install alphai-sdkRequires Node ≥18 (for global fetch), or any browser / edge / Deno / Bun runtime
that provides fetch.
Get an API key from alphai.io/account/api-keys.
Pass it explicitly, or set the ALPHAI_API_KEY environment variable and let the
client pick it up.
import { AlphaAI } from "alphai-sdk";
// Explicit:
const client = new AlphaAI({ apiKey: "ak_live_…" });
// Or from process.env.ALPHAI_API_KEY:
const client = new AlphaAI();If no key is found, the constructor throws MissingAPIKeyError.
import { AlphaAI } from "alphai-sdk";
const client = new AlphaAI();
const page = await client.news.list({ symbol: "NVDA", minRelevance: 7 });
for (const article of page.results) {
console.log(`[${article.enrichment.relevance_score}] ${article.original.title}`);
}// One page of the main feed (newest first). Filter by ticker, category, relevance.
const page = await client.news.list({
symbol: "NVDA",
category: ["earnings", "insider"], // single value, array, or CSV string
excludeCategories: ["crypto"],
minRelevance: 7, // 1–10
collapseStories: true, // collapse reprints into one story
pageSize: 20, // 10 default; 1-20 any key, 21-50 needs Pro
cursor, // opaque cursor from a previous page
});
console.log(page.results, page.next_cursor);
// Auto-pagination — follows next_cursor until the feed ends.
for await (const article of client.news.iterate({ symbol: "NVDA", maxItems: 100 })) {
// …
}
// A publication window: inclusive bounds on time_published, same names as the
// MCP tools. A bare "YYYY-MM-DD" string means the WHOLE day (the server reads
// a bare toDate as that day's end, so equal bounds return the day); a Date is
// an exact instant. Works on news.list/iterate and news.insider/iterateInsider
// in the default published mode only (a window with sort: "ingested" is a 400),
// and respects the key's archive depth (past the horizon is a 403).
const july = await client.news.list({
symbol: "NVDA",
fromDate: "2026-07-01",
toDate: "2026-07-31",
});
// Trending: up to 10 ranked stories from the last 48h (not paginated).
const trending = await client.news.trending();
// Insider feed (SEC Form 4 filings). decision: "discretionary" keeps the sales an
// insider chose to make; is10b5_1: false keeps every event not under a 10b5-1 plan.
const insider = await client.news.insider({ symbol: "NVDA", decision: "discretionary" });
for await (const article of client.news.iterateInsider({ symbol: "NVDA" })) {
// …
}
// A single article by its 16-char hex uid, and related articles (≤6).
const article = await client.news.get("a1b2c3d4e5f60718");
const related = await client.news.related("a1b2c3d4e5f60718");// All active tickers, alphabetical (~10k). Page with limit/offset.
const symbols = await client.symbols.list({ limit: 500, offset: 0 });
const hits = await client.symbols.list({ search: "bitcoin" }); // name / brand / prefix lookup → BTC-USD
// Symbol detail (throws NotFoundError for an unknown ticker).
const aapl = await client.symbols.get("AAPL");
// Crypto + foreign listings are supported too. Each Symbol carries multi-market
// metadata: asset_type ("Stock" | "ETF" | "Crypto"), country, currency, and
// supports_insider (US SEC names only). Crypto is "<SYM>-USD"; foreign uses the
// Yahoo suffix (e.g. "VOD.L").
const btc = await client.symbols.get("BTC-USD");
console.log(btc.asset_type, btc.currency, btc.supports_insider); // "Crypto" "USD" false
// 7-day AI sentiment rollup (excludes Form 4).
const sentiment = await client.symbols.sentimentSummary("AAPL");
// 30-day Form 4 rollup. Money fields are decimal STRINGS.
const insider = await client.symbols.insiderSummary("AAPL");
console.log(insider.buy_value_usd); // e.g. "1284500.00" — a string, not a number
// Earnings reads: AlphAI's structured, filing-verified analysis per quarter.
const earnings = await client.symbols.earnings("AAPL");
console.log(earnings.next_report_date); // "2026-10-29" or null (never an estimate)
for (const read of earnings.reports) {
// read.source_type: "sec_form8k" (US 8-K item 2.02) | "sec_form6k" (FPI 6-K)
const a = read.analysis; // may be null; key_metrics may be empty
if (!a || a.key_metrics.length === 0) continue;
console.log(read.fiscal_period, a.verdict, a.key_metrics[0].name, a.key_metrics[0].value);
}
// Each key_metrics row keeps `value` as printed and adds numeric / unit / scale
// ("$19,345" -> 19345, "USD", "millions" when the filing's table header says so);
// scale is null when the filing did not say. Don't assume millions.
// Latest-read pointer, for the article link. `null` when no read exists yet (HTTP 204).
const latest = await client.symbols.earningsLatest("AAPL");
if (latest) {
const article = await client.news.get(latest.uid);
const read = article.earnings; // may be null, even on an earnings article
if (read) console.log(read.verdict, read.headline);
}sourceType picks where rows come from: gdelt (press coverage), sec_form4,
sec_form8k or sec_form6k, OR-matched (single value, array or CSV string).
item keeps 8-K filings that carry an item code anywhere in the filing ("5.02"
executive changes, "1.01" material agreements, "8.01" other events) and
implies sec_form8k; next to any other source type the API answers 400. Every
8-K row carries a structured filing block:
const page = await client.news.list({ item: "5.02", minRelevance: 6 });
for (const article of page.results) {
const filing = article.filing; // null on press, Form 4 and 6-K rows
if (!filing) continue;
console.log(article.enrichment.tickers, filing.items, filing.primary_item);
console.log(filing.accession_number, filing.filed_at, filing.event_date, filing.exhibit_url);
}items lists every item code in the filing's order and is empty for a filing SEC
served no document for; primary_item is the one that set the row's category.
With collapseStories: true an 8-K that carries a press release joins that
release's story, so read filings uncollapsed.
Rows from SEC 8-K filings, 6-K earnings releases and PR Newswire releases carry a
typed event: what the document reports, the company's side of it, and facts
quoted from its text. eventType filters the feed by it (single value, array or
CSV string, OR-matched like category). It also matches the secondary events in
event.also, so "buyback" finds a buyback announced inside an earnings release.
const page = await client.news.list({ eventType: ["dividend", "buyback"], minRelevance: 5 });
for (const article of page.results) {
const event = article.event; // null on press and Form 4 rows, and until the document is read
if (!event) continue;
console.log(article.enrichment.tickers, event.type, event.role, event.stage, event.counterparty);
for (const fact of event.facts) {
// value is the document's own wording; number, unit and scale are parsed from it
console.log(" ", fact.name, fact.value, fact.number, fact.unit, fact.scale);
}
for (const other of event.also) console.log(" also:", other.type, other.facts.length, "facts");
if (!event.verified) console.log(" a fact was withheld, or the facts are still being read");
}The 17 types are exported as CORPORATE_EVENT_TYPES: earnings, earnings_date,
exec_change, m_and_a, offering, debt_financing, dividend, buyback,
contract_award, guidance_update, stock_split, listing_notice,
shareholder_vote, bankruptcy, restructuring, clinical_regulatory and
other. news.search() and news.get() return the same block; the filter exists
on news.list and news.iterate only.
A fact's value is a quote from the document ("$340 million", "Dec. 21, 2026"),
or the normalized value of an enumerated fact (consideration is "cash",
"stock" or "mixed"). number is that figure as a JSON number in the stated
scale (340 with scale: "millions"; a null scale means the full figure),
number_high is the upper end when the document gives a range, and unit is an
ISO currency code, "percent" or "bps". All four are null for text and dates.
Every quoted value is searched for in the document before it is published, and one
that is not found is withheld: verified: false says that happened, or that the
facts are still being read. The block is AI-generated from the document, so check
the filing before acting on a number.
eventType works in the default order only. With sort: "ingested" the API
answers 400, because a row gets its event after it enters the feed and a delta
cursor would already be past it. To follow new events, poll with fromDate and
de-duplicate by uid. An unknown type is a 400 as well, and its message lists
the allowed values:
import { BadRequestError } from "alphai-sdk";
try {
await client.news.list({ eventType: "buyback", sort: "ingested" });
} catch (err) {
if (err instanceof BadRequestError) {
console.log(err.fields?._); // ["… event_type cannot be combined with sort=ingested …"]
}
}The unknown type is keyed by its parameter (err.fields.event_type). A rule about
a combination of parameters names no single one, so its message is under
err.fields._. With collapseStories: true only the row that leads its story is
matched; omit it for the complete list.
Every Form 4 sale in an article's insider block carries decision. It is
discretionary when nothing in the filing explains the sale, plan_like when the
sale follows from a 10b5-1 plan or from paperwork (shares sold to pay the tax on
vesting, a sale that covers an option exercise), and unknown when the filing
does not say enough to tell. decision_reason names what decided it. The label is
read from the whole filing, not only from the 10b5-1 checkbox, so
is10b5_1: false still includes tax sales. To keep only the sales an insider
chose to make, pass decision: "discretionary":
const page = await client.news.insider({ symbol: "NVDA", decision: "discretionary" });
for (const article of page.results) {
const trade = article.insider;
if (!trade) continue;
console.log(trade.insider_name, trade.total_value_usd, trade.decision, trade.decision_reason);
}
// New discretionary sales as filings arrive: the filter works in delta mode too.
const fresh = await client.news.insider({ decision: "discretionary", sort: "ingested", cursor });decision |
decision_reason |
What the filing shows |
|---|---|---|
plan_like |
plan_10b5_1 |
The 10b5-1 checkbox, or a footnote that places the sale under a pre-arranged plan (so it can appear with is_10b5_1: false) |
plan_like |
tax_withholding |
Shares sold to pay the tax on vesting |
plan_like |
exercise_cover |
The sale covers the cost of an option exercise and its tax |
plan_like |
stated_non_discretionary |
A footnote says the sale was automatic or outside the insider's discretion |
discretionary |
open_market |
No plan or paperwork explains the sale: nothing in the filing points to one, or the sale is far larger than what vested or was exercised |
discretionary |
exercise_and_sell |
Options exercised and the exercised shares sold, beyond what covering the exercise needs |
discretionary |
sold_all_vested |
The shares sold plus those withheld for tax cover everything that vested |
unknown |
partial_vest_sale |
Part of the newly vested shares sold, more than the tax alone would need, or on top of tax already withheld |
unknown |
cover_ambiguous |
The sale could be an exercise cover at a high tax rate or a choice |
unknown |
mixed_acquisitions |
The filing both vests shares and exercises options, so the sale cannot be tied to either |
unknown |
price_disputed |
The filed price failed a price check, so the share arithmetic is not trusted |
unknown |
no_lines |
The rest of the filing is not held |
Only sales (transaction_code S) are labelled. Purchases, D (a sale to the
issuer) and other codes carry decision: null and decision_reason: null, and
they match none of the three filter values: the three filtered feeds plus the
events without a sale add up to the unfiltered feed. An event with several sales
is discretionary if any of them is, else unknown if any of them is, else
plan_like. An unknown sale can come with a null reason.
The filter is an option of news.insider, news.iterateInsider and
news.insiderCsv, and it combines with symbol, is10b5_1, sort: "ingested"
and the date window. news.list does not take it. A value outside the three is a
400, raised as BadRequestError with the message under err.fields.decision.
The values are exported as INSIDER_DECISIONS and INSIDER_DECISION_REASONS,
with the InsiderDecision and InsiderDecisionReason unions. Both fields are
typed as nullable and open: check for null before you branch on a label, and
keep a default branch when you switch over decision_reason, since the API can
add a reason. The label can also be revised when the reading rules improve. The
feed always carries the current one, sort: "ingested" does not send a revised
event again, and news.get() is cached for long, so it can show an older label.
The per-ticker endpoint GET /api/symbols/{ticker}/insider-trades/ is not
wrapped by this SDK. Its events carry the same two fields with the same values,
so the two unions type them when you fetch it yourself. There a sale to the
issuer (D) is listed with side: "sell" and still has decision: null.
news.insiderCsv() returns the insider feed as one file with the same filters,
walked on the server up to your plan's row cap (Free 500, Basic 2,000, Pro
10,000) inside its archive window. The whole file counts as one request.
import { writeFile } from "node:fs/promises";
const filters = { symbol: "NVDA", is10b5_1: false };
const csv = await client.news.insiderCsv(filters);
console.log(csv.rows, "rows of", csv.row_cap, "->", csv.filename);
await writeFile(csv.filename ?? "insider.csv", csv.text);
if (csv.truncated === "row_cap" && csv.next_cursor) {
// more rows exist: continue from the cursor with the same filters
const more = await client.news.insiderCsv({ ...filters, cursor: csv.next_cursor });
}truncated is "row_cap", "archive_horizon" (the walk reached your plan's
archive depth) or null when the file holds everything the filters select. The
next_cursor also works for news.insider() with the same sort. A bad filter
is the same BadRequestError as on the JSON feed, raised before any row.
The file's last two columns are decision and decision_reason, empty for an
event without a sale. New columns are only ever appended after the last one, so
read cells by header name, not by position. csv.text is the file as sent.
news.insiderClusters() lists episodes in which several different insiders of
one issuer bought on the open market together: an issuer's Form 4 purchase dates
are chained while at most 10 days apart (an episode is cut at 30 days), and every
purchase is examined before a buyer counts. IPO and PIPE allocations, ESPP / DRIP
/ director-plan lots, unpriced units and the same trade reported through two
owners are labeled per buyer (role) instead of counted, so a 30-name filing
burst is not one cluster. The default lists only open_market episodes (two or
more independent buyers, one of them an officer or director); ask for
pattern: "plan_or_offering", "holders_only" or "all" to see the rest.
const page = await client.news.insiderClusters({ days: 30, minUsd: 100_000, sort: "value" });
for (const cl of page.results) {
console.log(cl.ticker, cl.buyers, "buyers", cl.total_usd, cl.window_start, cl.window_end);
for (const buyer of cl.buyers_detail) {
console.log(" ", buyer.role, buyer.name, buyer.title || "director", buyer.usd);
}
for (const filing of cl.filings_detail) console.log(" ", filing.accession_number, filing.sec_url);
}
for await (const cl of client.news.iterateInsiderClusters({ symbol: "RAPP", pattern: "all", days: 90 })) {
console.log(cl.known_at, cl.pattern, cl.pattern_reasons);
}days (1–90, default 30) is measured on known_at, when the episode's latest
filing reached EDGAR, so "what became known this month" is one call; deeper than
your plan's archive horizon throws PermissionDeniedError (archive_horizon).
buyers counts independent buyers, buyers_total everyone who bought; money
fields are decimal strings, total_usd is null when no tranche carries a price
and value_partial says it understates. Each buyer's news_uids open the event
with news.get(uid). The list is a descriptive screen (meta.research_only),
not point-in-time; coverage starts at meta.coverage_since. Ranges are checked
locally (RangeError) before any request.
A story is an event that two or more publishers reported, summarised by AlphAI
from the articles themselves: what happened, the figures with the publisher each
came from, why it matters, a read per ticker and the questions the sources leave
open. Every article row carries a permanent story_id (the uid of the story's
first root article, unchanged when a stronger copy takes the root over or two
stories merge); a lone article names itself.
const top = await client.stories.top(); // last 48h, ranked by importance, coverage and freshness
for (const card of top.results.slice(0, 5)) {
console.log(card.importance, card.publishers, card.title);
}
for await (const card of client.stories.iter({ maxItems: 50 })) {
console.log(card.last_material_at, card.story_id, card.summary_state); // newest first
}
// A story_id taken from any article row: most resolve to not_a_story (one
// publisher carried the event), a few to a summarised story.
const lookup = await client.stories.get(top.results[0].story_id);
if (lookup.status === "found" && lookup.story) {
console.log(lookup.story.summary, lookup.story.why_it_matters);
for (const fact of lookup.story.key_facts) console.log("-", fact.text, `(${fact.publisher})`);
for (const take of lookup.story.ticker_takes) console.log(take.ticker, take.impact, take.note);
} else if (lookup.status === "merged" && lookup.redirect_to) {
await client.stories.get(lookup.redirect_to); // or client.stories.getStory(id), which follows merges
} else if (lookup.status === "not_a_story") {
console.log("single-publisher article:", lookup.article?.uid);
}
for await (const m of client.stories.iterMaterials(top.results[0].story_id)) {
console.log(m.time_published, m.publisher, m.url); // oldest first
}summary_state is published, stale (articles joined after the summary; a
rewrite is queued) or preparing (no summary yet; title and summary are the
lead article's). A cursor or a story past your plan's archive horizon throws
PermissionDeniedError with extra.reason === "archive_horizon". Summaries are
AI-generated financial information for research, not investment advice; article
bodies are never returned.
What each data source holds, from when, and with which caveats. Read it before a
backtest: first_row_at is the earliest row we hold, not the start of dense
coverage, and history_note says which months are thin.
const cov = await client.coverage();
console.log(cov.as_of); // computed once a day
for (const source of cov.sources) {
console.log(source.source, source.first_row_at, source.rows_total, source.stale);
}
const eightK = cov.sources.find((s) => s.source === "sec_form8k");
console.log(eightK?.history_note, eightK?.limits, eightK?.archive_days);Type-name note: the symbol model is exported as
Symbol, which shadows the JavaScript global. Alias it on import if needed:import type { Symbol as AlphaSymbol } from "alphai-sdk";
Monetary fields (buy_value_usd, sell_value_usd, net_value) are decimal
strings and are never coerced to number — JavaScript floats lose precision on
large dollar amounts. If you need arithmetic, feed them to a big-decimal library.
Timestamps are ISO 8601 strings (no automatic Date conversion).
A figure parsed next to a quote is a JSON number, exactly as the API sends it:
numeric on an earnings metric, number and number_high on a corporate event
fact. It is expressed in the scale beside it, and the quote (value) remains the
exact figure.
iterate() and iterateInsider() return an AsyncGenerator that follows
next_cursor for you. Bound the work with maxItems and/or maxPages:
for await (const article of client.news.iterate({ symbol: "AAPL", maxItems: 50 })) {
// stops after 50 articles (or when the feed ends)
}Cursors are opaque — never build or parse them; pass page.next_cursor straight back
in as cursor to fetch the next page manually.
Articles reach the feed after their publish time, so a poller that tracks
time_published silently skips late arrivals. sort: "ingested" orders the feed
by arrival instead, and its cursor is a polling position rather than an
end-of-feed marker:
let cursor = await loadCursor(); // undefined on the first run
const page = await client.news.list({
sort: "ingested",
cursor,
symbol: "NVDA",
pageSize: 20,
minRelevance: 7,
});
for (const article of page.results) {
handle(article); // article.original.created_at = when we received it
}
await saveCursor(page.next_cursor); // always set; empty results = caught up
// Branch on the results, never on the cursor: in this mode `next_cursor` is a
// polling position and is never null, so it says nothing about being done.
if (page.results.length === 0) await sleepUntilNextPoll();Send the same sort on every call of a run. Each mode mints its own cursor
family, so replaying an ingested cursor into the default mode is a 400, not a
silent restart. iterate({ sort: "ingested" }) threads it for you and stops on
the first empty page.
Keep up with the feed. One call returns one page, so a poller that drains
slower than the feed publishes drifts backwards and its articles start reading
as hours old — the data is current, the position is not. Raise pageSize and
narrow the stream (minRelevance, symbol, category) until a single poll
covers a single interval, and remember that the per-day call cap bounds how much
of the feed a plan can drain at all.
On Free and Basic the archive horizon applies to where a poll resumes, so a
cursor left unused for longer than your window comes back 403
(extra.reason === "archive_horizon"). Poll on your plan's cadence and you will
not see it; Pro has no window.
import { AlphaAI, ConflictError } from "alphai-sdk";
const client = new AlphaAI(); // reads ALPHAI_API_KEY
const brief = await client.news.brief({
tickers: ["NVDA", "AMD", "BTC-USD"], hours: 24, limit: 10,
});
for (const event of [...brief.events, ...brief.filings]) {
console.log(event.matched_tickers, event.title);
}
console.log(brief.upcoming_earnings, brief.unknown_tickers);
console.log("More coverage:", brief.events_truncated, brief.filings_truncated);
const page = await client.radar.snapshot({ window: "24h", market: "us_equity", limit: 10 });
console.log(page.snapshot_id, page.as_of, page.access, page.freshness);
for (const reading of page.results) {
console.log(reading.ticker, reading.news_z, reading.sent.value);
}
// This reads the key owner's existing saved symbols.
const saved = await client.radar.snapshot({ scope: "watchlist" });
console.log(saved.watchlist_coverage);
try {
for await (const reading of client.radar.iterate({ window: "4h", maxItems: 100 })) {
console.log(reading.ticker, reading.stories);
}
} catch (error) {
if (!(error instanceof ConflictError)) throw error;
console.log("Snapshot expired or context changed. Start a new scan without a cursor.");
}Brief takes 1–100 explicit tickers on every tier; it does not read the saved
account watchlist. hours is a publication window (1–168, default 24); limit
caps each news/filings section separately (1–20, default 20). Check both
truncation flags and unknown_tickers. Confirmed earnings dates remain ISO date
strings; missing dates are not estimated. This ranked snapshot has no cursor.
For complete incremental ingestion, use news.list({ sort: "ingested" }) with a
persisted cursor, not repeated Brief calls.
Radar accepts window (4h / 24h), scope, market, exact ticker or
tickers, search, sort, order, sentiment, minZ, limit, offset and
cursor. Request options use camelCase; response fields remain snake_case.
limit is a page size (1–100, default 50), not a tier ticker cap. Ticker filters
match exactly, with no alias expansion. Empty ticker arrays are rejected.
The server delays the whole snapshot by 60 minutes on Free, 15 on Basic, and no
added delay on Pro. Processing adds latency; inspect as_of and freshness.
Nullable scores stay null. Radar describes news activity, not confirmed trading
signals or point-in-time backtests. An empty saved watchlist returns no readings.
For manual pagination, send next_cursor as cursor with unchanged filters and
page size. Cursors pin snapshots retained for three hours. ConflictError (409)
means start a new scan without a cursor; iteration never restarts silently or
mixes snapshots. Unavailable snapshots raise ServerError (503) after bounded
retries. Both methods and the iterator accept an AbortSignal as signal.
Runnable examples: watchlist brief and Radar.
Every non-2xx response is mapped to a typed error. All extend AlphaAIError.
| Class | When | Notable fields |
|---|---|---|
BadRequestError |
400 | .fields (per-field validation messages), .allowedParams (the endpoint's real parameter names when you sent an unknown one) |
AuthenticationError |
401 | — |
PermissionDeniedError |
403 | — |
NotFoundError |
404 | — |
RateLimitError |
429 | .retryAfter, .limit, .remaining, .reset |
ServerError |
≥500 | — |
AlphaAIAPIError |
other non-2xx | .status, .body, .extra (base for the above) |
AlphaAIConnectionError |
network / timeout / abort | .cause |
MissingAPIKeyError |
no key resolved | — |
import { AlphaAI, RateLimitError, NotFoundError } from "alphai-sdk";
try {
await client.symbols.get("NOPE");
} catch (err) {
if (err instanceof RateLimitError) {
console.log(`Slow down — retry after ${err.retryAfter}s`);
} else if (err instanceof NotFoundError) {
console.log("No such ticker");
} else {
throw err;
}
}The error parser reads message first, then falls back to detail, then the raw
body — so both the app-layer ({ message, extra }) and host-gate
({ detail }) envelopes are handled.
BadRequestError.fields is keyed by parameter name. A rule about a combination of
parameters (for example eventType next to sort: "ingested") names no single
one, and its message is filed under _.
Idempotent GETs are retried automatically on 429, 5xx, and network errors —
maxRetries times (default 2) with exponential backoff and full jitter,
honoring a Retry-After header when the response has one (capped by
maxRetryAfter, default 60s). Each request has a timeout (default 30s)
enforced with AbortController.
Every wait before a retry is reported through logger (default console), so a
client sleeping on a 429 never looks hung:
alphai: HTTP 429 (rate limited) on GET /api/news/; waiting 12.0s before retry 1 of 2 (Retry-After: 12s; daily budget 87/100 left)
Pass any object with a warn(message) method to route it, or logger: null to
silence it.
const client = new AlphaAI({
maxRetries: 3,
backoffFactor: 0.5, // seconds; base for exponential backoff
timeout: 15_000, // ms
});Pass maxRetries: 0 to disable retries.
Limits are per account and two-layer — a per-minute burst plus a per-day volume
cap: Free 20/min · 100/day / Basic 60/min · 10,000/day / Pro 150/min ·
100,000/day. News-archive depth is tiered too (Free 30 days / Basic 90 / Pro
180; deeper pagination — or a fromDate past the horizon — returns 403). Every keyed response carries X-RateLimit-Limit,
X-RateLimit-Remaining, and X-RateLimit-Reset (epoch seconds). The SDK captures
them after each call:
await client.news.list({ symbol: "NVDA" });
console.log(client.lastRateLimit); // { limit: 10000, remaining: 9998, reset: 1700000000 }Cache-served responses may omit the headers; in that case lastRateLimit keeps its
previous value.
The trio reports the per-day layer. The per-minute burst cap is not in any
header: it shows up only as a 429 with a short Retry-After, which the client
waits out (and logs). A 429 while the daily budget still has room is the
per-minute cap; pace bursts yourself if you need to avoid it.
new AlphaAI({
apiKey, // else process.env.ALPHAI_API_KEY
baseURL: "https://api.alphai.io", // default
timeout: 30_000, // ms
maxRetries: 2,
backoffFactor: 0.5, // seconds
maxRetryAfter: 60, // cap on an honored Retry-After, seconds
fetch: customFetch, // inject a fetch (tests, proxies, edge)
userAgent: "alphai-sdk-js/<version>", // default
logger: console, // retry-wait lines; null silences them
});Works anywhere a Web-standard fetch is available: Node ≥18, modern browsers, Cloudflare
Workers / Vercel Edge, Deno, and Bun. For older or custom runtimes, inject a fetch
implementation via the fetch option.
In the browser, the User-Agent header is a forbidden header name and is dropped by
the runtime — that's expected and harmless.
const toDate = new Date();
const fromDate = new Date(toDate.getTime() - 29 * 24 * 60 * 60 * 1000);
const options = { query: "Jane Street", fromDate, toDate, pageSize: 20 };
const page = await client.news.search(options);
console.log(page.query.mode, page.query.note, page.matched);
for (const article of page.results) {
console.log(article.original.title, article.enrichment.tickers, article.search_match?.context);
}
if (page.next_cursor) {
const nextPage = await client.news.search({ ...options, cursor: page.next_cursor });
console.log(nextPage.results);
}news.search() returns a typed NewsSearchPage with query interpretation and
per-article search_match details. Quoted phrases such as query: '"going concern"',
-word exclusions and OR pass through unchanged. Add symbol, category,
sourceType, item, minRelevance or collapseStories to narrow results.
item: "5.02" limits search to 8-Ks carrying that item. Date bounds accept ISO
strings or Date, with the same semantics as the feed. signal supports cancellation.
Inspect query.mode and query.note: broadened may match only some words;
no_match and no_terms are empty answers within the searched coverage, not
proof an event did not happen. matched counts visible candidates among the best
200, not a global total; count is the current page size. Context can be null for
matches in titles/entity names; scores compare only within a response. Continue
with next_cursor and the same query, filters and window. Invalid cursors raise
BadRequestError; downtime raises ServerError after the configured retries,
never a successful empty page.
Runnable example: news search. Try the same queries in AlphAI Search.
Runnable scripts live in examples/:
quickstart.ts— fetch a news page for a tickerpaginate.ts— async-iterate the feed with a capticker-dashboard.ts— compose detail + sentiment + insider + news in parallel
ALPHAI_API_KEY=ak_live_… npx tsx examples/quickstart.tsA standalone, fuller set of runnable scripts lives in its own repo: alphai-sdk-ts-examples.
A worked recipe on the Free tier, with every response of the run logged:
alphai-earnings-week builds one
markdown card per week for a watchlist (confirmed report dates, the latest
filing-verified read per name, the macro calendar) in 26 requests. It is written in
Python; the same calls map onto symbols.earnings() here. The write-up walks through the
run: Earnings week from the filings, not the headlines.