alpacahq/alpaca-trade-api-js/alpaca-trade-api-sdk
Claude Code and agent skill by alpacahq/alpaca-trade-api-js
- community
Checking that the SKILL.md file is still in the repository.
Integrate and build on the @alpacahq/alpaca-trade-api TypeScript SDK for the Alpaca Trading and Market Data APIs (the unified Alpaca client, ergonomic order builders, normalized market-data shapes, pagination, typed errors, resilience, and real-time streaming). Use when writing or reviewing code that imports @alpacahq/alpaca-trade-api, places orders, fetches bars/trades/quotes, opens market-data or trading WebSocket streams, or builds a trading bot, backtester, or market-data backend on top of…
Install
npx vskill@latest install alpacahq/alpaca-trade-api-js/alpaca-trade-api-sdkSKILL.md
Building on @alpacahq/alpaca-trade-api
Guidance for LLMs and coding agents writing applications with @alpacahq/alpaca-trade-api. Packaged LLMS.md and the installable Agent Skill share this exact guidance body; use whichever integration your agent supports:
For changes to the SDK repository itself, read the repo-only AGENTS.md instead.
This is a map, not the territory. It gives you the mental model, the idioms agents most often get wrong, and where to look. It deliberately omits the full API surface. Whenever you need specifics, use the hosted guides and curated API reference for discovery, then confirm exact signatures and response models in the installed package's TypeScript declarations (dist/*.d.ts), your editor's type information, or the installed src/ source. Do not guess method signatures from this file alone.
Where to look
Paths are relative to the package root—the repository root when developing here, or node_modules/@alpacahq/alpaca-trade-api/ when installed. The published tarball includes src/.
| You need… | Read / search | |
|---|---|---|
| Workflows, conventions, and safety guidance | Hosted guides: Getting started, Trading, Market data, Streaming & events, Authentication, Resilience & configuration, Pagination, Values & types, Testing, Runtime compatibility, Examples, the migration overview, the primary migration from 3.x, and the separate 4.x to 5.0 migration. | |
| Curated per-method discovery and examples | Hosted API Reference: Trading, Market data, Streaming, and Ergonomic helpers. | |
| Exact installed-version signatures and model fields | Installed dist/*.d.ts, your editor's type information, or installed src/. | |
| Runnable end-to-end examples | Hosted Examples or the repository examples. | |
| The unified client / facade wiring | src/client.ts | |
| Order builders | src/orders.ts | |
| Normalized bar/trade/quote shapes + chart helpers | src/marketDataShapes.ts | |
| Curated, representative discovery maps | src/capabilities.ts | |
| Shared REST/SSE transport (retry/timeout/rate-limit/errors) | src/core/runtime.ts, src/core/sse.ts | |
| WebSocket clients | src/streaming/ |
When unsure where a method lives, prefer the programmatic lookups below over guessing, then confirm against the hosted API Reference and installed TypeScript declarations.
Mental model: a two-layer facade
The Alpaca client bundles every Trading and Market Data API behind one constructor, reached via the .trading and .marketData namespaces.
- Generated (always present, uniform). Every generated API method is
reachable raw at alpaca.<group>.<resource>.<method>(...)—for example, alpaca.trading.assets.getV2Assets() and alpaca.marketData.stocks.stockBars(...). Nothing is hidden.
- Ergonomic (additive, never replaces layer 1). Hand-written conveniences
sit on top: order builders, normalized market-data accessors, pagination, typed SSE subscriptions, and workflow helpers. The raw method each one wraps remains available.
The rule: if there is no ergonomic helper for what you need, use the raw generated method. You never have to choose between the two layers.
Setup essentials
- Node.js >= 20 remains compatible. Node.js 20 reached end-of-life in April
2026, and CI no longer executes that EOL runtime. Use a currently supported Node.js LTS release to continue receiving security fixes. See Runtime compatibility.
- Credentials resolve from environment variables when omitted:
APCA_API_KEY_ID, APCA_API_SECRET_KEY, and APCA_API_OAUTH_TOKEN. A non-empty explicit accessToken, Promise, or provider selects OAuth; otherwise any non-empty explicit key field selects key authentication ahead of an environment token. Empty strings are absent. With no explicit scheme, environment OAuth takes precedence over environment keys. Token providers are evaluated before every REST request and fetch-based SSE reconnect.
- Never pass
apiKeyas a plain string. Alpaca needs two distinct headers
and rejects a single value. Use OAuth via accessToken, or auth.apiKeyAuth({ keyId, secret }) for lazy credentials.
- OAuth-only clients cannot open WebSocket streams; WebSocket authentication
needs a key and secret. Fetch-based SSE accepts OAuth or key credentials.
Idioms agents get wrong
- Money and quantities are numeric strings to preserve wire values without
float loss. Convert for display with values.toNumber, values.toNumberOr, or values.formatMoney; for exact arithmetic, keep the string and use a decimal library. Never use parseFloat blindly for financial arithmetic.
- Timeframes are branded. Do not hand-write
"1minute"; build with
TimeFrame.Day or timeFrame(15, TimeFrameUnit.Minute) to produce the TimeFrameString required by facade bar methods.
- Orders: prefer ergonomic builders on
alpaca.trading.orders
(market, limit, stop, stopLimit, trailingStop, bracket, oco, and oto). They remove the postOrder({ createOrderRequest }) wrapper and enforce required fields per order kind at compile time. For uncovered shapes such as multi-leg mleg, use orders.submit(input) or raw postOrder.
- Order safety: agent-generated trading code must put a stable, unique
clientOrderId in every order request and persist it with the strategy's audit record. Never add a custom idempotency header and never retry an order-placement POST. If a FetchError makes placement ambiguous, call orders.getOrderByClientOrderId({ clientOrderId }) before any further submission. Duplicate client IDs are rejected; they do not replay the prior response. A lookup miss is not proof that placement failed, and visibility is not guaranteed to become eventual.
- Pagination is built in.
iterate*lazily yields across pages;
collect* and collect*BySymbol eagerly return them. Do not thread page tokens by hand. For large backfills, pass SymbolCollectOptions (maxPerSymbol, concurrency, and chunkSize) to bound memory and parallelism. Every helper stops before refetching any previously visited token or cursor, including longer cycles, after preserving valid pages already fetched.
- REST and streaming share one shape. Normalized accessors such as
getStockBars, getCryptoTrades, single-symbol *For(symbol) variants, and chart-ready get*Candles return the same Bar, Trade, or Quote type that streams emit. Raw generated map responses keep Alpaca's compact wire keys and may carry ISO-string timestamps. Required raw map fields normalize an unexpected null or missing wire value to {}, matching their non-nullable generated types; individual symbol keys can still be absent. Prefer normalized accessors or marketDataShapes.toBar and related helpers. A single-symbol *For reads only the exact requested key; absent data is [] or empty Candles, never another symbol's value.
- Errors are typed. Non-2xx responses reject with
ApiErrorand
status-specific subclasses: AuthError (401), PermissionError (403), NotFoundError (404), ValidationError (400/422), and RateLimitError (429). Branch on the subclass rather than magic numbers. Always log err.requestId from X-Request-ID; it cannot be looked up later. Network and abort failures reject with FetchError.
- Resilience defaults depend on the entry point. The
Alpacafacade
defaults to 2 retries (3 attempts total) for eligible idempotent requests. Bare generated Configuration retries are off unless configured. Only GET, HEAD, OPTIONS, and TRACE are automatically retried; POST, PATCH, PUT, and DELETE are not automatically retried. timeoutMs, retry, rateLimit, and userAgent are top-level client options. The facade enables a safe rate limit near 200 requests/minute; raw Api classes do not. onRetry and onGiveUp receive RetryEvent; thrown hook exceptions are swallowed so observability cannot break a request.
- Timeout and cancellation scopes matter.
timeoutMsis fresh per attempt
and covers rate-limit waits, middleware, fetch, and response-body reads. Backoff is outside that attempt budget; caller abort spans the entire operation and backoff. Every cancellation phase throws FetchError with an AbortError or TimeoutError cause. For a successful 200/204 SSE connection, timeoutMs ends after validated response headers; on non-2xx it remains active while the bounded error body is read for a typed ApiError. connectTimeoutMs overrides this deadline per subscription, and 0 disables it. Use SSE idleTimeoutMs or maxDurationMs only when you deliberately want to bound the live body.
- Redirects reject by default. Requests use
redirect: "error"so secret
APCA-API-* headers cannot follow an off-host redirect. Set redirect: "follow" only when deliberately opting out.
- Response metadata: methods normally return the body. Wrap a generated
*Raw sibling with withResponse(...) to receive { data, status, headers, rateLimit } as AlpacaApiResponse<T>.
- REST-only builds: import
@alpacahq/alpaca-trade-api/restto keepwsand
@msgpack/msgpack out of the module graph. Stream factories and submitAndWait throw from this entrypoint. Fetch-based SSE, including subscribeActivities and subscribeCorporateActions, remains available. Edge and browser runtimes resolve the root import to this build; direct browser API use is still discouraged because it exposes credentials and depends on API CORS.
- ESM and CJS: do not load the SDK through both
importandrequirein one
process if you rely on instanceof against classes such as ApiError; the process may contain two class copies.
Streaming
WebSocket clients are typed EventEmitters. Register listeners, then call connect(). They authenticate, reconnect with backoff, and resubscribe.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/alpaca-trade-api-sdk/SKILL.md
Popularity
- Repository stars
- 601
- Repository forks
- 154
- 7-day trend score
- 0
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/alpacahq/alpaca-trade-api-js/alpaca-trade-api-sdk)