Skip to content
项目

alpacahq/alpaca-trade-api-js

在 GitHub 查看

关于

用于 Alpaca Trade API 的 Node.js 库。

开发工具

这些数字如何统计

实测星标增长

24小时
0
7天
0
15天
+2
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

npm version Forum Slack

@alpacahq/alpaca-trade-api

The Alpaca JavaScript/TypeScript SDK for the Trading API and Market Data API. Both APIs live under their own namespace (trading / marketData) in one package, fronted by a unified Alpaca client with typed errors, resilience (retry / timeout / rate limiting), pagination helpers, ergonomic order builders, and real-time streaming.

Upgrading from 3.x? See the migration guide (also on the docs site) — it maps common 3.x calls and workflows to their 4.x equivalents and ships a codemod that automates most of the work.

Requirements

  • SDK consumers: Node.js >= 20 — the REST transport uses the platform-global fetch, Headers, URL, and AbortController, and the package declares engines.node >=20. Node.js 20 reached end-of-life in April 2026. The SDK remains compatible with Node.js 20, but CI no longer executes that EOL runtime. We recommend upgrading to a currently supported Node.js LTS release to continue receiving security fixes.
  • Repository contributors: Node.js >=24.22.1 <25 (.nvmrc pins that minimum locally). Build, docs, generation, release tooling, and CI resolve the latest available Node.js 24 patch above that security floor. The published SDK keeps its Node.js >= 20 compatibility contract.
  • Strict Node TypeScript projects may omit DOM libs; the REST declarations are portable and do not require "dom" in the consumer tsconfig.

Runtime compatibility

Runtime REST / fetch-based SSE WebSockets Notes
Node.js >= 20 ✅ ✅ Compatibility floor; Node.js 20 is EOL.
Bun ✅ ✅ Node-compatible (ws runs).
Deno ✅ ❌ Root auto-resolves to the REST build via the deno export condition.
Cloudflare Workers / workerd ✅ ❌ Root auto-resolves to the REST build (workerd / worker).
Vercel Edge ✅ ❌ Root auto-resolves to the REST build (edge-light).
Browser ✅ ❌ Resolves to the REST build (browser). Not recommended — see caveat.

Legend: ✅ supported · ❌ not supported.

  • WebSocket streaming is Node/Bun only. Those clients use Node-compatible streaming modules, which don't run on edge or in the browser. On those targets the package's export conditions transparently resolve the root import to the WebSocket-free REST build, so REST and fetch-based SSE work while the stream factories (stockStream, stream, …) plus submitAndWait throw if called. For WebSocket streaming, run on Node or Bun.
  • Browser: technically works, but discouraged. Calling Alpaca directly from a browser ships your APCA_API_SECRET_KEY to the client. Prefer a server or proxy (see examples/marketdata-backend.ts) rather than embedding credentials in front-end code.

ESM and CJS module formats, edge export conditions, and the REST-only entrypoint are documented on the docs site: Runtime & module compatibility.

Install

npm install @alpacahq/alpaca-trade-api

Quick start

import { Alpaca } from "@alpacahq/alpaca-trade-api";

const alpaca = new Alpaca({
  keyId: process.env.APCA_API_KEY_ID,
  secret: process.env.APCA_API_SECRET_KEY,
  paper: true, // default; set false for live trading
});

const account = await alpaca.trading.account.getAccount();
const price = await alpaca.marketData.getLatestPrice("AAPL");

const bars = alpaca.marketData.stockStream({ feed: "iex" });
bars.onBar((b) => console.log(b.symbol, b.close));
bars.onConnect(() => bars.subscribeForBars(["AAPL", "MSFT"]));
bars.connect();

Server-Sent Events

The facade provides typed async SSE subscriptions with cancellation, reconnection, and Last-Event-ID resumption:

const controller = new AbortController();
const activities = await alpaca.trading.subscribeActivities(
  {},
  {
    signal: controller.signal,
    onEventFailure: (err) =>
      console.error("skipped SSE event:", err.eventId, err.cause),
  },
);

try {
  for await (const activity of activities) {
    console.log(activity.activityType, activity.details);
  }
} finally {
  activities.close();
}

Corporate-action mutations are available from alpaca.marketData.subscribeCorporateActions(). The longer generated operation names remain available under trading.events and marketData.corporateActions; see the streaming guide.

Documentation

The documentation site is the canonical source for workflows, conventions, and curated API discovery. Installed TypeScript declarations remain authoritative for exact signatures and models. Key guides:

Build from source

npm install      # also builds via the `prepare` script
npm run build    # tsup -> dual ESM + CJS in dist/
npm run typecheck
npm run lint
npm test

Runnable examples live in examples/. To preview the docs site locally:

npm --prefix docs install   # first time only
npm --prefix docs start     # http://localhost:3000/alpaca-trade-api-js/

Releases

Stable versions are published to npm on the latest dist-tag. See CHANGELOG.md for release notes.

Support

  • Library / SDK issues: Bugs, feature requests, or questions specific to this SDK → GitHub Issues.
  • Security vulnerabilities: Do not report them publicly. Follow our Security Policy.
  • Alpaca API bugs: Bugs in the Alpaca API itself, its OpenAPI specs, or its documentation → alpacahq/alpaca-api.
  • Community: API feature requests, general questions, and dashboard bugs → Alpaca Community Forum or Slack.
  • Account help: Questions about your account, funding, or orders → Support request.
  • Outages: Service status and incident updates → Status page.

Contributing

Contributions are welcome. See CONTRIBUTING.md for setup, contribution scope, generated-code boundaries, quality requirements, and the pull-request workflow. Participation is governed by our Code of Conduct.

探索相关项目

加载中…