{"_id":"@alpacahq/alpaca-ts-alpha","_rev":"3-a7aa3d8745e9c6c7b6fcef0d006e97e2","name":"@alpacahq/alpaca-ts-alpha","dist-tags":{"latest":"0.2.0"},"versions":{"0.1.0":{"name":"@alpacahq/alpaca-ts-alpha","version":"0.1.0","license":"Apache-2.0","_id":"@alpacahq/alpaca-ts-alpha@0.1.0","maintainers":[{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"}],"dist":{"shasum":"de81069f4026cc87c24321eca7a5b2d3016388eb","tarball":"https://registry.npmjs.org/@alpacahq/alpaca-ts-alpha/-/alpaca-ts-alpha-0.1.0.tgz","fileCount":309,"integrity":"sha512-eFq/oUh5J3hL06D5gJoUOc8oHRHpxFEr1TU1iJY9vS1lO1gZYNwnb4J0bCocAuulwv6pUY3oslCn5/NjAf2SKQ==","signatures":[{"sig":"MEQCIFZEhSYVu9+DxMwQKy5RJuZOaT32StjTA9yH1xpsHmyuAiBnsYGN5kARarX7+tFQ/nVmj4MrondvGXAduKTDqrCeJA==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":19328555},"main":"./dist/index.js","type":"commonjs","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=20"},"exports":{".":{"import":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"require":{"types":"./dist/index.d.ts","default":"./dist/index.js"}},"./rest":{"import":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"require":{"types":"./dist/rest.d.ts","default":"./dist/rest.js"}},"./testing":{"import":{"types":"./dist/testing.d.mts","default":"./dist/testing.mjs"},"require":{"types":"./dist/testing.d.ts","default":"./dist/testing.js"}},"./package.json":"./package.json"},"gitHead":"0b1edf7d8025bc8e25ca9ecbd0601e7d0a887056","scripts":{"lint":"biome lint .","test":"vitest run","build":"tsup","prepare":"npm run build","docs:api":"tsx scripts/gen-api-reference.ts","lint:fix":"biome lint --write .","typecheck":"tsc --noEmit && npm run typecheck:examples","typecheck:examples":"tsc --noEmit -p tsconfig.examples.json"},"_npmUser":{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"},"overrides":{"esbuild":"^0.28.1"},"_npmVersion":"11.12.1","description":"TypeScript SDK for the Alpaca Trading and Market Data APIs (generated).","directories":{},"sideEffects":false,"_nodeVersion":"24.15.0","dependencies":{"ws":"^8.21.0","@msgpack/msgpack":"^3.1.3"},"typesVersions":{"*":{"rest":["./dist/rest.d.ts"],"testing":["./dist/testing.d.ts"]}},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.22.4","tsup":"^8.5.1","vitest":"^4.1.8","@types/ws":"^8.18.1","typescript":"^5.4.0","@types/node":"^22.0.0","@biomejs/biome":"2.5.0","@microsoft/api-extractor":"^7.58.9"},"_npmOperationalInternal":{"tmp":"tmp/alpaca-ts-alpha_0.1.0_1781642735854_0.6390818111228489","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@alpacahq/alpaca-ts-alpha","version":"0.1.1","license":"Apache-2.0","_id":"@alpacahq/alpaca-ts-alpha@0.1.1","maintainers":[{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"}],"dist":{"shasum":"1dab5cc37c85d9d602018ff05b8e2a505850b552","tarball":"https://registry.npmjs.org/@alpacahq/alpaca-ts-alpha/-/alpaca-ts-alpha-0.1.1.tgz","fileCount":309,"integrity":"sha512-0i5v2+MD27D/sNY7gXxVpdndGDX6fUpCaD89iG+b2+DOt63KV/D3VbIhvBnYCAUW+BtJUdyblj3LoQmv5Q6wxg==","signatures":[{"sig":"MEQCIFga/owsyMZI5DGkRcIIKl3gLTZ9miecKUt+GCIV11I5AiA+Vaye/R1GCMcwH6OoFNEBTLwvO3z0lxeR1xvspYHUvQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":19408685},"main":"./dist/index.js","type":"commonjs","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=20"},"exports":{".":{"import":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"require":{"types":"./dist/index.d.ts","default":"./dist/index.js"}},"./rest":{"import":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"require":{"types":"./dist/rest.d.ts","default":"./dist/rest.js"}},"./testing":{"import":{"types":"./dist/testing.d.mts","default":"./dist/testing.mjs"},"require":{"types":"./dist/testing.d.ts","default":"./dist/testing.js"}},"./package.json":"./package.json"},"gitHead":"6daff1282766e9e308c91249e437ecf1ec4a54d5","scripts":{"lint":"biome lint .","test":"vitest run","build":"tsup","prepare":"npm run build","docs:api":"tsx scripts/gen-api-reference.ts","lint:fix":"biome lint --write .","typecheck":"tsc --noEmit && npm run typecheck:examples","typecheck:examples":"tsc --noEmit -p tsconfig.examples.json"},"_npmUser":{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"},"overrides":{"esbuild":"^0.28.1"},"_npmVersion":"11.12.1","description":"TypeScript SDK for the Alpaca Trading and Market Data APIs (generated).","directories":{},"sideEffects":false,"_nodeVersion":"24.15.0","dependencies":{"ws":"^8.21.0","@msgpack/msgpack":"^3.1.3"},"typesVersions":{"*":{"rest":["./dist/rest.d.ts"],"testing":["./dist/testing.d.ts"]}},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.22.4","tsup":"^8.5.1","vitest":"^4.1.8","@types/ws":"^8.18.1","typescript":"^5.4.0","@types/node":"^22.0.0","@biomejs/biome":"2.5.0","@microsoft/api-extractor":"^7.58.9"},"_npmOperationalInternal":{"tmp":"tmp/alpaca-ts-alpha_0.1.1_1781717110501_0.17385687793489324","host":"s3://npm-registry-packages-npm-production"}},"0.2.0":{"name":"@alpacahq/alpaca-ts-alpha","version":"0.2.0","description":"TypeScript SDK for the Alpaca Trading and Market Data APIs (generated).","license":"Apache-2.0","type":"commonjs","engines":{"node":">=20"},"main":"./dist/index.js","module":"./dist/index.mjs","types":"./dist/index.d.ts","typesVersions":{"*":{"rest":["./dist/rest.d.ts"],"testing":["./dist/testing.d.ts"]}},"exports":{".":{"workerd":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"worker":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"edge-light":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"deno":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"browser":{"import":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"require":{"types":"./dist/rest.d.ts","default":"./dist/rest.js"}},"import":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"require":{"types":"./dist/index.d.ts","default":"./dist/index.js"}},"./rest":{"import":{"types":"./dist/rest.d.mts","default":"./dist/rest.mjs"},"require":{"types":"./dist/rest.d.ts","default":"./dist/rest.js"}},"./testing":{"import":{"types":"./dist/testing.d.mts","default":"./dist/testing.mjs"},"require":{"types":"./dist/testing.d.ts","default":"./dist/testing.js"}},"./package.json":"./package.json"},"sideEffects":false,"scripts":{"build":"tsup","typecheck":"tsc --noEmit && npm run typecheck:examples","typecheck:examples":"tsc --noEmit -p tsconfig.examples.json","test":"vitest run","lint":"biome lint .","lint:fix":"biome lint --write .","docs:api":"tsx scripts/gen-api-reference.ts","prepare":"npm run build"},"dependencies":{"@msgpack/msgpack":"^3.1.3","ws":"^8.21.0"},"overrides":{"esbuild":"^0.28.1"},"devDependencies":{"@biomejs/biome":"2.5.0","@microsoft/api-extractor":"^7.58.9","@types/node":"^22.0.0","@types/ws":"^8.18.1","tsup":"^8.5.1","tsx":"^4.22.4","typescript":"^5.4.0","vitest":"^4.1.8"},"gitHead":"df18a8015e1638097efc5af03c94264874e0fe51","_id":"@alpacahq/alpaca-ts-alpha@0.2.0","_nodeVersion":"24.15.0","_npmVersion":"11.12.1","dist":{"integrity":"sha512-DyYsRSfRv8x1jeay2V9qg7TN0saPdC2Iv2V9ORYim9qDKubmXwxqrl5Rkz1uMeSoUEruzcTZ/a4AN/YRL36k6g==","shasum":"736019cf4de915fbe802aea463236782fd0866b2","tarball":"https://registry.npmjs.org/@alpacahq/alpaca-ts-alpha/-/alpaca-ts-alpha-0.2.0.tgz","fileCount":309,"unpackedSize":19434444,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIArM9RXM5WLAAsKjRjDuSrL7FuGb5iW1L27bkC+sYgPgAiEAqNiP8nskaJ6cTwdoqLF3bYWTlJdThGgHIWA8UbmzBEQ="}]},"_npmUser":{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"},"directories":{},"maintainers":[{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/alpaca-ts-alpha_0.2.0_1781763551249_0.8685245675107021"},"_hasShrinkwrap":false}},"time":{"created":"2026-06-16T20:45:35.643Z","modified":"2026-06-18T06:19:11.756Z","0.1.0":"2026-06-16T20:45:36.061Z","0.1.1":"2026-06-17T17:25:10.778Z","0.2.0":"2026-06-18T06:19:11.579Z"},"license":"Apache-2.0","description":"TypeScript SDK for the Alpaca Trading and Market Data APIs (generated).","maintainers":[{"name":"oss.alpaca.markets","email":"oss@alpaca.markets"}],"readme":"# @alpacahq/alpaca-ts-alpha\n\nA single Node.js TypeScript SDK for the Alpaca **Trading API** and **Market Data\nAPI**. Both APIs live under their own namespace (`trading` / `marketData`) in one\npackage, fronted by a unified `Alpaca` client with typed errors, resilience\n(retry / timeout / rate limiting), pagination helpers, ergonomic order builders,\nand real-time streaming.\n\n## Requirements\n\n- **Node.js** >= 20 (developed against v24) — the REST transport uses the\n  platform-global `fetch`, `Headers`, `URL`, and `AbortController`. (Node 18\n  reached end-of-life in April 2025; the package declares `engines.node >=20`.)\n\n## Runtime compatibility\n\n| Runtime | REST | Streaming | Notes |\n| --- | :---: | :---: | --- |\n| **Node.js** >= 20 | ✅ | ✅ | Primary target. |\n| **Bun** | ✅ | ✅ | Node-compatible (`ws` runs). |\n| **Deno** | ✅ | ❌ | Root auto-resolves to the REST build via the `deno` export condition. |\n| **Cloudflare Workers** / `workerd` | ✅ | ❌ | Root auto-resolves to the REST build (`workerd` / `worker`). |\n| **Vercel Edge** | ✅ | ❌ | Root auto-resolves to the REST build (`edge-light`). |\n| **Browser** | ✅ | ❌ | Resolves to the REST build (`browser`). Not recommended — see caveat. |\n\nLegend: ✅ supported · ❌ not supported.\n\n- **Streaming is Node/Bun only.** The WebSocket clients depend on\n  [`ws`](https://github.com/websockets/ws) and `node:events`, which don't run on\n  edge or in the browser. On those targets the package's\n  [export conditions](#edge--browser-runtimes) transparently resolve the root\n  import to the streaming-free [REST build](#rest-only-entrypoint), so REST works\n  and the stream factories (`stockStream`, `stream`, ...) plus `submitAndWait`\n  throw if called. For real-time streaming, run on Node or Bun.\n- **Browser: technically works, but discouraged.** Calling Alpaca directly from a\n  browser ships your `APCA_API_SECRET_KEY` to the client. Prefer a server or\n  proxy (see [`examples/marketdata-backend.ts`](./examples/marketdata-backend.ts))\n  rather than embedding credentials in front-end code.\n\n## Install\n\n```bash\nnpm install @alpacahq/alpaca-ts-alpha\n```\n\n## Install the agent skill\n\nBuilding on this SDK with an AI coding agent? This repo ships an\n[Agent Skill](https://agentskills.io) that teaches agents the SDK's mental\nmodel, idioms, and where to look. Install it with the open `skills` CLI — it\nauto-detects your agent (Claude Code, Cursor, Codex, …) and installs there:\n\n```bash\nnpx skills add alpacahq/alpaca-ts-alpha\n```\n\nThe skill lives at\n[`skills/alpaca-ts-alpha-sdk/SKILL.md`](./skills/alpaca-ts-alpha-sdk/SKILL.md).\n\n\n## Quick start: the `Alpaca` client\n\nThe SDK ships ~16 trading and ~11 market-data `Api` classes. The `Alpaca` client\nbundles all of them (plus the real-time streams) behind a single constructor:\npass credentials once and reach everything through the `.trading` and\n`.marketData` namespaces. Sub-APIs are created lazily and memoized.\n\n```ts\nimport { Alpaca } from \"@alpacahq/alpaca-ts-alpha\";\n\nconst alpaca = new Alpaca({\n  keyId: process.env.APCA_API_KEY_ID,\n  secret: process.env.APCA_API_SECRET_KEY,\n  paper: true, // default; set false for live trading\n});\n\n// REST — no manual Configuration / Api wiring\nconst account = await alpaca.trading.account.getAccount();\nconst positions = await alpaca.trading.positions.getAllOpenPositions();\n\n// Ergonomic order placement (see \"Placing orders\")\nawait alpaca.trading.orders.market({ symbol: \"AAPL\", qty: 1, side: \"buy\" });\n\n// Streaming — shares the same credentials (market data ignores paper/live)\nconst bars = alpaca.marketData.stockStream({ feed: \"iex\" });\nbars.onBar((b) => console.log(b.symbol, b.close));\nbars.onConnect(() => bars.subscribeForBars([\"AAPL\", \"MSFT\"]));\nbars.connect();\n```\n\nThe `paper` flag controls the trading REST host (`paper-api` vs `api`) and the\ndefault trading-updates stream endpoint; market data always uses\n`data.alpaca.markets`. The `trading` / `marketData` namespaces remain available\nif you prefer to construct `Api` classes yourself:\n\n```ts\nimport { trading, marketData } from \"@alpacahq/alpaca-ts-alpha\";\n\nconst orders = new trading.OrdersApi(new trading.Configuration({ keyId, secret }));\nconst stocks = new marketData.StockApi(new marketData.Configuration({ keyId, secret }));\n```\n\n## How the facade is organized\n\nThe `Alpaca` client is **two layers**, and knowing the rule is the whole mental\nmodel:\n\n1. **Generated (always present, uniform).** Every generated REST method is\n   reachable raw at `alpaca.<group>.<resource>.<method>(...)` — e.g.\n   `alpaca.trading.assets.getV2Assets()` or `alpaca.marketData.stocks.stockBars(...)`.\n   Nothing is ever hidden or removed.\n2. **Ergonomic (additive, never replaces layer 1).** A curated set of\n   hand-written conveniences sits on top: order builders, normalized\n   market-data accessors, pagination, and workflow helpers. They are *additions*\n   — the raw method each one builds on is still there.\n\nSo the rule you can rely on: **if there's no ergonomic helper for what you need,\nthe raw generated method is always available.** You never have to guess whether\na resource is \"ergonomic\" or \"raw\" — it's both.\n\nThree maps make this queryable (each also has a lookup):\n\n| Layer | Map | Lookup |\n| --- | --- | --- |\n| Generated methods | `capabilities` | `findCapabilities(\"getAccount\")` |\n| Ergonomic helpers | `ergonomicCapabilities` | `findErgonomic(\"market\")` |\n| Real-time streams | `streamingCapabilities` | — |\n\nThe ergonomic layer follows predictable naming conventions, so helpers are\nguessable:\n\n- **Order builders:** one verb method per kind on `trading.orders` (`market`,\n  `limit`, `stop`, `stopLimit`, `trailingStop`, `bracket`, `oco`, `oto`), plus a\n  generic `submit` escape hatch.\n- **Normalized REST:** `get<Asset><Thing>` returns canonical, symbol-keyed\n  shapes (`getStockBars`, `getCryptoTrades`, ...); `get<Asset>Candles` returns\n  the chart-ready columnar form. Each has a single-symbol `get<Asset><Thing>For(symbol)`\n  variant (`getStockBarsFor`, `getStockCandlesFor`, ...) that returns the\n  unwrapped value instead of a `{ [symbol]: ... }` map.\n- **Pagination:** `iterate<X>` lazily yields across pages; `collect<X>` /\n  `collect<X>BySymbol` eagerly returns them.\n- **Workflow:** verb-named one-offs (`submitAndWait`, `closeAllPositions`,\n  `getLatestPrice`).\n\n## Authentication\n\nAlpaca authenticates with two distinct headers (`APCA-API-KEY-ID` and\n`APCA-API-SECRET-KEY`). Pass `keyId` and `secret` directly.\n\n```ts\nconst alpaca = new Alpaca({ keyId, secret });\n```\n\n### Environment variables\n\nAny credential may be omitted and resolved from the standard Alpaca environment\nvariables; explicitly-passed values always win.\n\n| Option        | Environment variable    |\n| ------------- | ----------------------- |\n| `keyId`       | `APCA_API_KEY_ID`       |\n| `secret`      | `APCA_API_SECRET_KEY`   |\n| `accessToken` | `APCA_API_OAUTH_TOKEN`  |\n\n```ts\n// With APCA_API_KEY_ID and APCA_API_SECRET_KEY set in the environment:\nconst alpaca = new Alpaca();\n```\n\n### OAuth\n\nPass an `accessToken` to authenticate via OAuth2; it is sent as\n`Authorization: Bearer <token>`. OAuth is mutually exclusive with `keyId`/`secret`\nand takes precedence over them.\n\n```ts\nconst alpaca = new Alpaca({ accessToken });\n```\n\n> Real-time streaming authenticates with a key/secret pair, so OAuth-only\n> clients cannot open WebSocket streams.\n\n> Do **not** pass `apiKey` as a plain string — it would send the same value for\n> both headers and Alpaca would reject it. The SDK throws a guided error if you\n> try. To compute credentials lazily (e.g. from a vault), use the helper:\n>\n> ```ts\n> import { trading, auth } from \"@alpacahq/alpaca-ts-alpha\";\n> const config = new trading.Configuration({ apiKey: auth.apiKeyAuth({ keyId, secret }) });\n> ```\n\n## Paper vs live\n\nTrading defaults to **paper**. Switching to live is a deliberate flag, never an\naccidental missing host:\n\n```ts\nconst live = new Alpaca({ keyId, secret, paper: false });\n```\n\nNamed hosts are exported too: `trading.TRADING_PAPER_HOST`,\n`trading.TRADING_LIVE_HOST`, `marketData.MARKET_DATA_HOST`.\n\n## Resilience & configuration\n\nAll options below are optional and conservative by default. On the `Alpaca`\nclient they are passed at the top level; on a raw `Configuration` they are\nidentical fields.\n\n```ts\nconst alpaca = new Alpaca({\n  keyId,\n  secret,\n\n  // Abort a stalled request after N ms (default: no timeout).\n  timeoutMs: 10_000,\n\n  // Opt-in automatic retry. Disabled unless maxRetries > 0.\n  retry: {\n    maxRetries: 3,\n    retryDelayMs: 500,        // base for exponential backoff (default 500)\n    maxDelayMs: 30_000,       // cap per delay (default 30000)\n    retryableStatuses: [429, 500, 502, 503, 504], // default\n    respectRetryAfter: true,  // honor a Retry-After header (default true)\n  },\n\n  // Proactive client-side rate limiting (the Alpaca client enables a safe\n  // default; pass a config to tune or `false` to disable). See below.\n  rateLimit: { maxRequests: 200, intervalMs: 60_000, maxConcurrent: 16 },\n\n  userAgent: \"my-app/1.0\", // default `@alpacahq/alpaca-ts-alpha/<version>`; \"\" disables\n});\n```\n\n### Retry semantics\n\n- Off unless `retry.maxRetries > 0`.\n- `429` is always retried; the `retryableStatuses` (5xx by default) are retried\n  **only for idempotent verbs** (`GET/HEAD/PUT/DELETE/OPTIONS`), so a\n  non-idempotent `POST` is never silently re-sent.\n- **Transient network failures** (DNS, connection reset, TLS — surfaced as a\n  `FetchError`) are also retried, again **only for idempotent verbs**. A\n  deliberate abort (caller `AbortSignal` or the `timeoutMs` deadline) is *not*\n  retried.\n- A `Retry-After` header (seconds or HTTP-date) is honored when present;\n  otherwise exponential backoff with jitter, capped at `maxDelayMs`.\n\n### Timeouts\n\n`timeoutMs` wires an `AbortController` into the underlying `fetch`. A per-call\n`AbortSignal` (passed via `initOverrides`) still works and composes with the\ntimeout — whichever aborts first wins.\n\n### Rate limiting\n\nAlpaca enforces roughly 200 requests/minute per host. The `Alpaca` client\nenables a safe default token bucket (~200/min, applied independently to the\ntrading and market-data hosts) so burst workloads self-throttle instead of\ntripping 429s. Tune it with a `rateLimit` config or pass `rateLimit: false` to\nopt out. When constructing raw `Api` classes the limiter is **off** unless you\nset `rateLimit` on the `Configuration`.\n\n### Typed errors\n\nNon-2xx responses reject with an `ApiError` (a `ResponseError` subclass) exposing\n`status`, `code`, and `message` parsed from Alpaca's `{ code, message }` error\nenvelope; the raw `Response` stays on `.response`. Branch on the status-specific\nsubclasses instead of magic numbers:\n\n```ts\nimport { RateLimitError, NotFoundError, ApiError } from \"@alpacahq/alpaca-ts-alpha\";\n\ntry {\n  await alpaca.trading.orders.getOrderByOrderID({ orderId });\n} catch (err) {\n  if (err instanceof RateLimitError) {\n    console.warn(`rate limited; retry in ${err.retryAfterMs}ms`, err.rateLimit);\n  } else if (err instanceof NotFoundError) {\n    console.warn(\"no such order\");\n  } else if (err instanceof ApiError) {\n    console.error(err.status, err.code, err.message);\n  }\n}\n```\n\nSubclasses: `AuthError` (401), `PermissionError` (403), `NotFoundError` (404),\n`ValidationError` (400/422), `RateLimitError` (429). Every `ApiError` also\nsurfaces `rateLimit` (`X-RateLimit-*`), `retryAfterMs`, and `requestId` —\nAlpaca's `X-Request-ID` for the failed call. That id can't be looked up after\nthe fact, so log it (or include it in a support ticket) when something fails:\n\n```ts\ncatch (err) {\n  if (err instanceof ApiError) {\n    console.error(`request ${err.requestId} failed`, err.status, err.message);\n  }\n}\n```\n\nA failed `fetch` itself (network/abort) rejects with `FetchError`.\n\n## Placing orders\n\n`alpaca.trading.orders` is the generated `OrdersApi` plus one ergonomic method\nper common order kind that drops the `postOrder({ postOrderRequest })` wrapper,\naccepts `number | string` amounts, and enforces the required fields per kind at\ncompile time. Each returns the created `Order`; `timeInForce` defaults to\n`\"day\"`.\n\n```ts\nawait alpaca.trading.orders.market({ symbol: \"AAPL\", qty: 1, side: \"buy\" });\nawait alpaca.trading.orders.limit({ symbol: \"AAPL\", qty: 1, side: \"buy\", limitPrice: 150 });\nawait alpaca.trading.orders.stop({ symbol: \"AAPL\", qty: 1, side: \"sell\", stopPrice: 140 });\nawait alpaca.trading.orders.stopLimit({ symbol: \"AAPL\", qty: 1, side: \"sell\", stopPrice: 140, limitPrice: 139.5 });\nawait alpaca.trading.orders.trailingStop({ symbol: \"AAPL\", qty: 1, side: \"sell\", trailPercent: 5 });\n\nawait alpaca.trading.orders.bracket({\n  symbol: \"AAPL\", qty: 10, side: \"buy\", limitPrice: 150,\n  takeProfit: { limitPrice: 155 },\n  stopLoss: { stopPrice: 145, limitPrice: 144.5 },\n});\n```\n\nFor shapes the typed methods don't cover (e.g. multi-leg `mleg`), use\n`alpaca.trading.orders.submit(input)` or the raw `postOrder`. The pure builders\nare also exported under the `orders` namespace.\n\n## Workflow helpers\n\nA few high-level flows that would otherwise be boilerplate:\n\n```ts\n// Latest trade price as a number (undefined if unavailable).\nconst price = await alpaca.marketData.getLatestPrice(\"AAPL\");\n\n// Close every open position (optionally cancelling open orders first).\nawait alpaca.trading.closeAllPositions({ cancelOrders: true });\n\n// Place an order and await its terminal state over the trading-updates stream\n// (resolves on fill/canceled/rejected/expired/done_for_day; rejects on timeout).\nconst filled = await alpaca.trading.submitAndWait(\n  { type: \"market\", symbol: \"AAPL\", qty: 1, side: \"buy\" },\n  { timeoutMs: 30_000 },\n);\nconsole.log(filled.status, filled.filledAvgPrice);\n```\n\n## Pagination\n\nEvery paginated endpoint is iterable out of the box on the `Alpaca` client — you\nnever thread page tokens or merge per-symbol arrays. `iterate*` lazily yields\nitems across all pages; `collect*` eagerly returns them.\n\n```ts\nfor await (const { symbol, value } of alpaca.marketData.iterateStockBars({\n  symbols: [\"AAPL\", \"MSFT\"],\n  timeframe: TimeFrame.Day,\n  start: new Date(\"2024-01-01\"),\n})) {\n  // value is a StockBar for symbol\n}\n\nconst bars = await alpaca.marketData.collectStockBarsBySymbol({\n  symbols: \"AAPL,MSFT\",\n  timeframe: TimeFrame.Day,\n  start: new Date(\"2024-01-01\"),\n});\nbars.AAPL; // StockBar[]\n\nconst articles = await alpaca.marketData.collectNews({ symbols: \"AAPL\" });\n\nfor await (const activity of alpaca.trading.iterateActivities({ activityTypes: [\"FILL\"] })) {\n  // ...\n}\n```\n\nThe same pattern exists for stock/crypto/option trades, quotes, bars and\nauctions, `indexValues`, forex `rates`, option `snapshots`/`chain`,\n`iterateOptionsContracts`, and `collectCorporateActions`. For custom cases the\nlower-level `pagination` namespace exposes the building blocks: `paginate`/\n`collect`, `paginateSymbolMap`/`collectBySymbol`, `paginateSymbolObjects`/\n`collectSymbolObjects`, and `paginateCursor`/`collectCursor`.\n\n### Bounding large fetches\n\nA multi-symbol `collect*BySymbol` (and the normalized `get*` accessors) accept a\n`SymbolCollectOptions` to keep big back-fills cheap. By default every symbol is\nmultiplexed into one request whose page token is followed to exhaustion; pass\noptions to bound memory and parallelize:\n\n```ts\n// Cap each symbol's history (stops paging once every symbol is full).\nconst recent = await alpaca.marketData.getStockBars(\n  { symbols: [\"AAPL\", \"MSFT\"], timeframe: TimeFrame.Minute, start },\n  { maxPerSymbol: 1_000 },\n);\n\n// Fetch a large basket in parallel: split into one request per symbol,\n// up to 4 in flight. The client-side rate limiter still applies.\nconst basket = await alpaca.marketData.getStockBars(\n  { symbols: bigList, timeframe: TimeFrame.Day, start },\n  { concurrency: 4, chunkSize: 1, maxPerSymbol: 5_000 },\n);\n```\n\n`concurrency` defaults to `1` (the single combined request); `chunkSize`\n(default `1`) controls how many symbols share each parallel request. The generic\n`pagination.collect`/`collectCursor` take a `maxItems` cap, and\n`pagination.collectBySymbol` takes `maxPerSymbol`; `pagination.mapConcurrent` and\n`pagination.chunk` are exposed for custom fan-out.\n\n## Values & types\n\nMoney/quantities are wire-truthful numeric `string`s (no float64 precision\nloss). Parse or format with the `values` helpers; for exact arithmetic keep the\nstring and feed a decimal library (`big.js`/`decimal.js`, not bundled).\n\n```ts\nimport { values } from \"@alpacahq/alpaca-ts-alpha\";\n\nvalues.toNumber(account.buyingPower);          // number | undefined\nvalues.toNumberOr(account.cash, 0);            // number with fallback\nvalues.formatMoney(account.equity);            // \"$12,345.67\" (display only)\n```\n\nBuild timeframes with the validated builders instead of hand-writing strings\nlike `\"1minute\"` (which the API rejects); the facade bar methods require the\nbranded `TimeFrameString` these return:\n\n```ts\nimport { TimeFrame, TimeFrameUnit, timeFrame } from \"@alpacahq/alpaca-ts-alpha\";\n\ntimeFrame(15, TimeFrameUnit.Minute); // \"15Min\"\nTimeFrame.Day;                       // preset \"1Day\"\n```\n\nMulti-symbol market-data methods accept a comma-separated `string` or a\n`string[]`. Time fields: trading models parse timestamps to `Date`, and\nmarket-data models also **type** them as `Date`. Note that the multi-symbol/list\nresponses deserialize their symbol-keyed maps verbatim, so nested timestamps can\nstill arrive as ISO `string`s at runtime despite that type. The fix is to prefer\nthe normalized accessors below (`getStockBars`, the single-symbol `getStockBarsFor`,\netc.), which always hand back real `Date`s; only the **raw** generated map\nresponses (e.g. `alpaca.marketData.stocks.stockBars`) carry the caveat, and there\nyou can normalize with `values.toDate` / `values.toISO`.\n\n## Normalized market-data shapes (REST + streaming unified)\n\nThe generated REST models keep Alpaca's compact wire keys (`StockBar` is\n`{ o, h, l, c, v, vw, n, t }`), while the real-time stream surfaces readable\ncamelCase. The `marketDataShapes` namespace bridges them onto one canonical\n`Bar` / `Trade` / `Quote` shape — the *same* type the streaming clients emit —\nso you can backfill history over REST and append live updates over the\nWebSocket without reconciling two shapes.\n\nThe `Alpaca` client exposes normalized accessors (auto-paginated, keyed by\nsymbol) alongside the raw `collect*`/`iterate*` ones:\n\n```ts\nimport { Alpaca, marketDataShapes, TimeFrame } from \"@alpacahq/alpaca-ts-alpha\";\n\nconst alpaca = new Alpaca({ keyId, secret });\n\n// REST history as canonical Bars: { [symbol]: Bar[] }\nconst history = await alpaca.marketData.getStockBars({\n  symbols: [\"AAPL\"], timeframe: TimeFrame.Day, start: new Date(\"2024-01-01\"),\n});\n\n// Live bars arrive in the SAME shape - just append them.\nconst stream = alpaca.marketData.stockStream({ feed: \"iex\" });\nstream.onBar((bar) => history.AAPL?.push(bar)); // bar is a Bar\nstream.onConnect(() => stream.subscribeForBars([\"AAPL\"]));\nstream.connect();\n```\n\nNormalized accessors: `getStockBars`/`getCryptoBars`/`getOptionBars`,\n`getStockTrades`/`getCryptoTrades`, `getStockQuotes`/`getCryptoQuotes`, and the\nchart-ready `getStockCandles`/`getCryptoCandles`. Each returns a `{ [symbol]: T }`\nmap; for a single symbol, the `*For(symbol)` variants\n(`getStockBarsFor`, `getStockCandlesFor`, ... one per accessor) return the\nunwrapped value directly so you skip the `result[symbol]` step. For any other\nendpoint, normalize a raw response yourself with the pure mappers:\n`marketDataShapes.toBar`, `toStockTrade`/`toCryptoTrade`/`toOptionTrade`,\n`toStockQuote`/`toCryptoQuote`/`toOptionQuote`, and the `*BySymbol` helpers.\n\n### Chart-ready helpers\n\nReshape a `Bar[]` into the forms plotting libraries expect:\n\n```ts\nimport { toCandles, toCandlestickSeries, toLineSeries } from \"@alpacahq/alpaca-ts-alpha\";\n\ntoCandles(history.AAPL);              // { time[], open[], high[], low[], close[], volume[] }\ntoCandles(history.AAPL, { time: \"seconds\" }); // unix seconds instead of epoch ms\ntoCandlestickSeries(history.AAPL);    // [{ time, open, high, low, close }]\ntoLineSeries(history.AAPL, \"close\");  // [{ time, value }]\n```\n\nThese live in the `marketDataShapes` namespace too and are re-exported at the top\nlevel. Everything here is REST-only (no `ws`/`msgpack`), so it is available from\nthe `@alpacahq/alpaca-ts-alpha/rest` entrypoint as well.\n\n### Data feeds & the free-tier 15-minute delay\n\nA few market-data gotchas are worth knowing before your first request — they\ncome from Alpaca's data plans, not the SDK:\n\n- **Feeds.** US-equity endpoints take a `feed` parameter: `iex` (free), `sip`\n  (all US exchanges, paid), plus `otc`/`boats`. The SDK does **not** force a\n  default for REST — when you omit `feed`, Alpaca picks the *best feed your\n  subscription allows* (`iex` on the free plan), so a free key won't 403 on a\n  default request. The streaming helpers default to `feed: \"iex\"` so a free key\n  connects out of the box; pass `{ feed: \"sip\" }` explicitly once you have a\n  subscription.\n- **The 15-minute rule.** On the free plan, SIP data for the **last 15 minutes**\n  is restricted. Two consequences:\n  - Explicitly requesting `feed: \"sip\"` with `end` defaulting to *now* fails\n    with `403 subscription does not permit querying recent SIP data`. The SDK\n    detects this 403 and appends guidance to the error message (pass\n    `{ feed: \"iex\" }`, move `end` back ≥15 min, or upgrade).\n  - With `iex`, recent bars exist but the trailing ~15 minutes can be sparse or\n    empty, so `end: new Date()` may look like it \"returns nothing\". If you need\n    a guaranteed-populated window on the free tier, set `end` ~15 minutes in the\n    past yourself.\n\n  The SDK deliberately does **not** clamp `end` for you — doing so silently\n  would hide data that paid subscribers are entitled to.\n- **`paper` is irrelevant to market data.** The `paper` flag only switches the\n  *trading* host (`paper-api` vs `api`); every market-data REST/stream call goes\n  to `data.alpaca.markets` regardless. Free vs paid *data* is governed by your\n  subscription and the `feed` parameter, not by `paper`.\n\n## Real-time streaming\n\nWebSocket clients for a market-data stream (stocks, crypto, options, news) and a\ntrading stream (order/account updates). Both authenticate automatically,\nreconnect with backoff, re-subscribe after a reconnect, and ping/pong. The API\nis a typed `EventEmitter`: register listeners, then `connect()`.\n\n```ts\nconst stocks = alpaca.marketData.stockStream({ feed: \"iex\" }); // \"iex\" | \"sip\" | \"delayed_sip\"\nstocks.onBar((bar) => pushToClients(bar)); // typed StreamBar\nstocks.onError((msg) => console.error(\"stream error:\", msg));\nstocks.onConnect(() => stocks.subscribeForBars([\"AAPL\", \"MSFT\"]));\nstocks.connect();\n\nconst updates = alpaca.trading.stream();\nupdates.onTradeUpdate((u) => console.log(u.event, u.order.symbol, u.order.clientOrderId));\nupdates.onConnect(() => updates.subscribeTradeUpdates());\nupdates.connect();\n```\n\n`cryptoStream()`, `optionStream()`, and `newsStream()` share the same surface.\n\n## Capability map (which method lives where)\n\nThe `capabilities` namespace maps each **generated** facade accessor to its\nunderlying `Api` class and common methods; `findCapabilities(name)` answers\n\"where does this method live?\":\n\n```ts\nimport { capabilities, findCapabilities } from \"@alpacahq/alpaca-ts-alpha\";\n\nfindCapabilities(\"getAccount\");\n// [{ accessor: \"trading.account\", api: \"AccountsApi\", group: \"trading\", ... }]\n```\n\nThe **ergonomic** (layer 2) helpers have their own map, `ergonomicCapabilities`,\nwith a matching `findErgonomic(name)` lookup — so \"is there a helper for this,\nand where?\" is answerable the same way:\n\n```ts\nimport { ergonomicCapabilities, findErgonomic } from \"@alpacahq/alpaca-ts-alpha\";\n\nfindErgonomic(\"market\");\n// [{ accessor: \"trading.orders\", kind: \"orderBuilder\", wraps: \"OrdersApi.postOrder\", ... }]\nfindErgonomic(\"getStockBars\");\n// [{ accessor: \"marketData\", kind: \"normalized\", ... }]\n```\n\nFor the full, per-method listing of both layers (description + example for every\nmethod), see the generated [API reference](#api-reference) below.\n\n## Observability\n\nBuilt-in middleware for logging and metrics, layered on the transport's\n`pre`/`post`/`onError` hooks. Pass them via `middleware`; they observe only\n(never alter the request), so they compose with retries and with each other.\n\n```ts\nimport { Alpaca, middleware } from \"@alpacahq/alpaca-ts-alpha\";\n\nconst alpaca = new Alpaca({\n  keyId,\n  secret,\n  middleware: [\n    // One log line per request attempt: method, url, status, duration, requestId.\n    middleware.loggingMiddleware({ logger: console, level: \"info\" }),\n    // A metric per request attempt for Prometheus / StatsD / OpenTelemetry.\n    middleware.metricsMiddleware({\n      onRequest: (m) =>\n        statsd.timing(\"alpaca.request\", m.durationMs, { method: m.method, status: m.status }),\n    }),\n  ],\n});\n```\n\n`loggingMiddleware` redacts the `APCA-*` and `Authorization` headers by default\n(and only includes headers at all when `logHeaders: true`). Both accept a\n`genRequestId` to supply your own correlation ids.\n\n## Dependencies\n\nThe REST client needs nothing beyond the Node platform globals. The **streaming**\nclients (WebSockets) pull in two small runtime dependencies — [`ws`](https://github.com/websockets/ws)\nand [`@msgpack/msgpack`](https://github.com/msgpack/msgpack-javascript). At\nruntime the `Alpaca` facade only constructs them when you actually open a stream,\nbut the **root entrypoint's module graph statically includes them** (it\nre-exports the `streaming` namespace), so a bundler resolving\n`@alpacahq/alpaca-ts-alpha` will see `ws` / `@msgpack/msgpack` / `node:events`.\nIf you only use REST — or you target an edge/browser runtime where `ws` cannot\nrun — import from the [`@alpacahq/alpaca-ts-alpha/rest`](#rest-only-entrypoint)\nsubpath (or rely on the automatic edge resolution described in\n[Module formats](#module-formats-esm--cjs)) and they are never pulled in.\n\n## REST-only entrypoint\n\nIf you never open a stream, import from `@alpacahq/alpaca-ts-alpha/rest` to keep the `ws` /\n`@msgpack/msgpack` dependencies out of your module graph (smaller bundles,\nfaster cold starts). It re-exports everything except the `streaming` namespace.\nThe `Alpaca` facade is the same class, so all REST methods work unchanged; the\nstream factories (`stockStream`, `stream`, ...) and `submitAndWait` throw if\ncalled from this entrypoint — import from `@alpacahq/alpaca-ts-alpha` when you need streams.\n\n```ts\nimport { Alpaca } from \"@alpacahq/alpaca-ts-alpha/rest\";\n```\n\nOn edge and browser runtimes you usually don't need to reach for this subpath\nexplicitly — the root entrypoint resolves here automatically (see\n[Module formats](#module-formats-esm--cjs)).\n\n## Testing your integration\n\n`@alpacahq/alpaca-ts-alpha/testing` provides a network-free harness so your unit tests don't\nhit Alpaca. `mockFetch` answers canned responses by method + path; `createMockAlpaca`\nwires one into a ready `Alpaca` client (dummy credentials, rate limiting off).\n\n```ts\nimport { createMockAlpaca } from \"@alpacahq/alpaca-ts-alpha/testing\";\n\nconst alpaca = createMockAlpaca([\n  { method: \"GET\", path: \"/v2/account\", body: { account_number: \"PA42\", status: \"ACTIVE\" } },\n  { path: /\\/v2\\/stocks\\/[A-Z]+\\/trades\\/latest$/, respond: ({ url }) => ({\n      symbol: url.pathname.split(\"/\")[3],\n      trade: { p: 99.5 },\n    }) },\n]);\n\nconst account = await alpaca.trading.account.getAccount(); // { accountNumber: \"PA42\", ... }\nconst price = await alpaca.marketData.getLatestPrice(\"AAPL\"); // 99.5\n```\n\nRoutes match the first entry whose `path` (exact string or RegExp) and optional\n`method` match; unmatched requests get your `fallback` or a descriptive 404. A\nroute's `body` is JSON-encoded automatically (objects) or sent verbatim\n(strings); `respond` is the dynamic escape hatch.\n\n## Module formats (ESM & CJS)\n\nThe package ships both native ESM (`dist/index.mjs`) and CommonJS\n(`dist/index.js`), selected via conditional `exports`, with per-format type\ndeclarations and `sideEffects: false` for tree-shaking.\n\n```ts\nimport { Alpaca } from \"@alpacahq/alpaca-ts-alpha\";       // ESM\n```\n```js\nconst { Alpaca } = require(\"@alpacahq/alpaca-ts-alpha\");  // CJS\n```\n\n> Dual-package caveat: don't load the SDK through *both* `import` and `require`\n> in the same process if you rely on `instanceof` against its exported classes\n> (e.g. `ApiError`), or you may compare against two copies.\n\n### Edge & browser runtimes\n\nThe streaming clients depend on `ws` and `node:events`, which don't run on edge\nruntimes (Cloudflare Workers / `workerd`, Vercel Edge, Deno) or in the browser.\nTo keep the root import working there, the package `exports` map declares\n`workerd`, `worker`, `edge-light`, `deno`, and `browser` conditions that resolve\n`@alpacahq/alpaca-ts-alpha` to the streaming-free\n[REST-only build](#rest-only-entrypoint) automatically — so a plain\n`import { Alpaca } from \"@alpacahq/alpaca-ts-alpha\"` builds and runs on those\ntargets without the `Class extends value [object Module]` failure that comes\nfrom a bundler trying to load `ws` / `node:events` on a runtime that lacks them.\n\nThe trade-off is the same as importing `/rest` directly: REST works unchanged,\nbut the stream factories (`stockStream`, `stream`, ...) and `submitAndWait`\nthrow. For real-time streaming, run on Node and import the root entry there.\n\n## Development\n\n```bash\nnpm install      # also builds via the `prepare` script\nnpm run build    # tsup (esbuild) -> dual ESM+CJS + types in dist/\nnpm run typecheck # tsc --noEmit (type authority; does not emit)\nnpm test         # vitest\n```\n\n`dist/` is git-ignored and produced by the build (and automatically on\n`npm publish` / `npm pack` via `prepare`). Runnable end-to-end examples live in\n[`examples/`](./examples).\n\nThis SDK was originally scaffolded with\n[OpenAPI Generator](https://openapi-generator.tech), but it is now **fully\nhand-maintained** — there are no further regenerations. The generated REST\nclients and models under `src/trading/{apis,models}` and\n`src/market-data/{apis,models}` are left untouched so they remain a faithful\nsnapshot of Alpaca's OpenAPI spec; everything else — the `Alpaca` facade, order\nbuilders, normalized market-data shapes, pagination, streaming, and the shared\ntransport — is hand-written in separate modules. When contributing, edit the\nhand-written modules and don't hand-edit the generated `apis`/`models` trees.\n\n## Background\n\n- **One package, two namespaces.** The Trading and Market Data APIs are exposed\n  as the `trading` and `marketData` namespaces of a single package. This avoids\n  collisions between the two specs, which both define a `CorporateActionsApi`\n  and overlapping model names.\n\n## API reference\n\nEvery method on the facade — all generated REST methods, the real-time streaming\nfactories, and the ergonomic helpers — with a one-line description and a short\nexample. This section is **generated** from [`src/capabilities.ts`](src/capabilities.ts)\nplus a hand-maintained examples map; run `npm run docs:api` to regenerate it (a\ntest fails the build if it drifts out of sync). Headings are the real facade call\npaths, so every entry is individually anchor-linkable.\n\n<!-- API-REFERENCE:START -->\n\n### Trading API\n\n<details>\n<summary><strong>Operations</strong> (64)</summary>\n\n- `account` — [getAccount](#alpacatradingaccountgetaccount)\n- `accountActivities` — [getAccountActivities](#alpacatradingaccountactivitiesgetaccountactivities), [getAccountActivitiesByActivityType](#alpacatradingaccountactivitiesgetaccountactivitiesbyactivitytype)\n- `accountConfigurations` — [getAccountConfig](#alpacatradingaccountconfigurationsgetaccountconfig), [patchAccountConfig](#alpacatradingaccountconfigurationspatchaccountconfig)\n- `assets` — [getV2Assets](#alpacatradingassetsgetv2assets), [getV2AssetsSymbolOrAssetId](#alpacatradingassetsgetv2assetssymbolorassetid), [getOptionsContracts](#alpacatradingassetsgetoptionscontracts), [getOptionContractSymbolOrId](#alpacatradingassetsgetoptioncontractsymbolorid), [usCorporates](#alpacatradingassetsuscorporates), [usTreasuries](#alpacatradingassetsustreasuries)\n- `calendar` — [calendar](#alpacatradingcalendarcalendar), [clock](#alpacatradingcalendarclock), [legacyCalendar](#alpacatradingcalendarlegacycalendar), [legacyClock](#alpacatradingcalendarlegacyclock)\n- `corporateActions` — [getV2CorporateActionsAnnouncements](#alpacatradingcorporateactionsgetv2corporateactionsannouncements), [getV2CorporateActionsAnnouncementsId](#alpacatradingcorporateactionsgetv2corporateactionsannouncementsid)\n- `cryptoFunding` — [createCryptoTransferForAccount](#alpacatradingcryptofundingcreatecryptotransferforaccount), [getCryptoFundingTransfer](#alpacatradingcryptofundinggetcryptofundingtransfer), [listCryptoFundingTransfers](#alpacatradingcryptofundinglistcryptofundingtransfers), [getCryptoTransferEstimate](#alpacatradingcryptofundinggetcryptotransferestimate), [listCryptoFundingWallets](#alpacatradingcryptofundinglistcryptofundingwallets), [createWhitelistedAddress](#alpacatradingcryptofundingcreatewhitelistedaddress), [deleteWhitelistedAddress](#alpacatradingcryptofundingdeletewhitelistedaddress), [listWhitelistedAddress](#alpacatradingcryptofundinglistwhitelistedaddress)\n- `cryptoPerpetualsAccountVitals` — [getCryptoPerpAccountVitals](#alpacatradingcryptoperpetualsaccountvitalsgetcryptoperpaccountvitals)\n- `cryptoPerpetualsFunding` — [createCryptoPerpTransferForAccount](#alpacatradingcryptoperpetualsfundingcreatecryptoperptransferforaccount), [getCryptoPerpFundingTransfer](#alpacatradingcryptoperpetualsfundinggetcryptoperpfundingtransfer), [getCryptoPerpTransferEstimate](#alpacatradingcryptoperpetualsfundinggetcryptoperptransferestimate), [listCryptoPerpFundingTransfers](#alpacatradingcryptoperpetualsfundinglistcryptoperpfundingtransfers), [listCryptoPerpFundingWallets](#alpacatradingcryptoperpetualsfundinglistcryptoperpfundingwallets), [createWhitelistedPerpAddress](#alpacatradingcryptoperpetualsfundingcreatewhitelistedperpaddress), [deleteWhitelistedPerpAddress](#alpacatradingcryptoperpetualsfundingdeletewhitelistedperpaddress), [listWhitelistedPerpAddress](#alpacatradingcryptoperpetualsfundinglistwhitelistedperpaddress)\n- `cryptoPerpetualsLeverage` — [getCryptoPerpAccountLeverage](#alpacatradingcryptoperpetualsleveragegetcryptoperpaccountleverage), [setCryptoPerpAccountLeverage](#alpacatradingcryptoperpetualsleveragesetcryptoperpaccountleverage)\n- `events` — [subscribeToActivitiesSSE](#alpacatradingeventssubscribetoactivitiessse)\n- `orders` — [getAllOrders](#alpacatradingordersgetallorders), [postOrder](#alpacatradingorderspostorder), [getOrderByOrderID](#alpacatradingordersgetorderbyorderid), [getOrderByClientOrderId](#alpacatradingordersgetorderbyclientorderid), [patchOrderByOrderId](#alpacatradingorderspatchorderbyorderid), [deleteOrderByOrderID](#alpacatradingordersdeleteorderbyorderid), [deleteAllOrders](#alpacatradingordersdeleteallorders)\n- `portfolioHistory` — [getAccountPortfolioHistory](#alpacatradingportfoliohistorygetaccountportfoliohistory)\n- `positions` — [getAllOpenPositions](#alpacatradingpositionsgetallopenpositions), [getOpenPosition](#alpacatradingpositionsgetopenposition), [deleteAllOpenPositions](#alpacatradingpositionsdeleteallopenpositions), [deleteOpenPosition](#alpacatradingpositionsdeleteopenposition), [optionExercise](#alpacatradingpositionsoptionexercise), [optionDoNotExercise](#alpacatradingpositionsoptiondonotexercise)\n- `tokenization` — [getTokenizationRequests](#alpacatradingtokenizationgettokenizationrequests), [postTokenizationMint](#alpacatradingtokenizationposttokenizationmint)\n- `watchlists` — [getWatchlists](#alpacatradingwatchlistsgetwatchlists), [getWatchlistById](#alpacatradingwatchlistsgetwatchlistbyid), [getWatchlistByName](#alpacatradingwatchlistsgetwatchlistbyname), [postWatchlist](#alpacatradingwatchlistspostwatchlist), [updateWatchlistById](#alpacatradingwatchlistsupdatewatchlistbyid), [updateWatchlistByName](#alpacatradingwatchlistsupdatewatchlistbyname), [addAssetToWatchlist](#alpacatradingwatchlistsaddassettowatchlist), [addAssetToWatchlistByName](#alpacatradingwatchlistsaddassettowatchlistbyname), [removeAssetFromWatchlist](#alpacatradingwatchlistsremoveassetfromwatchlist), [deleteWatchlistById](#alpacatradingwatchlistsdeletewatchlistbyid), [deleteWatchlistByName](#alpacatradingwatchlistsdeletewatchlistbyname)\n\n</details>\n\n#### `alpaca.trading.account` — AccountsApi\n\nAccount details, balances, buying power and status.\n\n##### `alpaca.trading.account.getAccount`\n\nAccount details, balances, buying power and status.\n\n```ts\nawait alpaca.trading.account.getAccount();\n```\n\n#### `alpaca.trading.accountActivities` — AccountActivitiesApi\n\nAccount activity history (fills, fees, dividends, transfers).\n\n##### `alpaca.trading.accountActivities.getAccountActivities`\n\nList account activities (fills, fees, dividends, transfers), newest first.\n\n```ts\nawait alpaca.trading.accountActivities.getAccountActivities({\n  activityTypes: [\"FILL\"],\n  pageSize: 50,\n});\n```\n\n##### `alpaca.trading.accountActivities.getAccountActivitiesByActivityType`\n\nList activities of a single type (e.g. only fills).\n\n```ts\nawait alpaca.trading.accountActivities.getAccountActivitiesByActivityType({\n  activityType: \"FILL\",\n});\n```\n\n#### `alpaca.trading.accountConfigurations` — AccountConfigurationsApi\n\nRead and update trading account configuration.\n\n##### `alpaca.trading.accountConfigurations.getAccountConfig`\n\nRead the account's trading configuration.\n\n```ts\nawait alpaca.trading.accountConfigurations.getAccountConfig();\n```\n\n##### `alpaca.trading.accountConfigurations.patchAccountConfig`\n\nUpdate trading configuration (e.g. block short selling).\n\n```ts\nawait alpaca.trading.accountConfigurations.patchAccountConfig({\n  accountConfigurations: { noShorting: true },\n});\n```\n\n#### `alpaca.trading.assets` — AssetsApi\n\nTradable assets, option contracts and instrument reference data.\n\n##### `alpaca.trading.assets.getV2Assets`\n\nList tradable assets, filterable by class, status and exchange.\n\n```ts\nawait alpaca.trading.assets.getV2Assets({\n  status: \"active\",\n  assetClass: \"us_equity\",\n});\n```\n\n##### `alpaca.trading.assets.getV2AssetsSymbolOrAssetId`\n\nFetch a single asset by symbol or asset id.\n\n```ts\nawait alpaca.trading.assets.getV2AssetsSymbolOrAssetId({\n  symbolOrAssetId: \"AAPL\",\n});\n```\n\n##### `alpaca.trading.assets.getOptionsContracts`\n\nList option contracts for underlying symbols (paginated).\n\n```ts\nawait alpaca.trading.assets.getOptionsContracts({\n  underlyingSymbols: \"AAPL\",\n  limit: 100,\n});\n```\n\n##### `alpaca.trading.assets.getOptionContractSymbolOrId`\n\nFetch a single option contract by symbol or id.\n\n```ts\nawait alpaca.trading.assets.getOptionContractSymbolOrId({\n  symbolOrId: \"AAPL250117C00150000\",\n});\n```\n\n##### `alpaca.trading.assets.usCorporates`\n\nReference data for US corporate bonds (by ISIN, CUSIP or ticker).\n\n```ts\nawait alpaca.trading.assets.usCorporates({ tickers: \"AAPL\" });\n```\n\n##### `alpaca.trading.assets.usTreasuries`\n\nReference data for US Treasury instruments.\n\n```ts\nawait alpaca.trading.assets.usTreasuries({ cusips: \"912797JL3\" });\n```\n\n#### `alpaca.trading.calendar` — CalendarApi\n\nMarket calendar and clock (open/close, sessions).\n\n##### `alpaca.trading.calendar.calendar`\n\nMarket calendar (sessions) for a market and date range.\n\n```ts\nawait alpaca.trading.calendar.calendar({\n  market: \"us_equity\",\n  start: new Date(\"2024-01-01\"),\n  end: new Date(\"2024-01-31\"),\n});\n```\n\n##### `alpaca.trading.calendar.clock`\n\nCurrent market clock: open/closed and next open/close.\n\n```ts\nawait alpaca.trading.calendar.clock();\n```\n\n##### `alpaca.trading.calendar.legacyCalendar`\n\nLegacy market-calendar endpoint (prefer `calendar`).\n\n```ts\nawait alpaca.trading.calendar.legacyCalendar({\n  start: new Date(\"2024-01-01\"),\n  end: new Date(\"2024-01-31\"),\n});\n```\n\n##### `alpaca.trading.calendar.legacyClock`\n\nLegacy market-clock endpoint (prefer `clock`).\n\n```ts\nawait alpaca.trading.calendar.legacyClock();\n```\n\n#### `alpaca.trading.corporateActions` — CorporateActionsApi\n\nCorporate-action announcements (splits, dividends, mergers).\n\n##### `alpaca.trading.corporateActions.getV2CorporateActionsAnnouncements`\n\nDeprecated: corporate-action announcements over a date range.\n\n```ts\nawait alpaca.trading.corporateActions.getV2CorporateActionsAnnouncements({\n  caTypes: \"dividend\",\n  since: \"2024-01-01\",\n  until: \"2024-01-31\",\n});\n```\n\n##### `alpaca.trading.corporateActions.getV2CorporateActionsAnnouncementsId`\n\nDeprecated: a single corporate-action announcement by id.\n\n```ts\nawait alpaca.trading.corporateActions.getV2CorporateActionsAnnouncementsId({\n  id: \"be3c368a-4c7c-4384-808e-f02c9f5a8afe\",\n});\n```\n\n#### `alpaca.trading.cryptoFunding` — CryptoFundingApi\n\nCrypto wallets, transfers and whitelisted withdrawal addresses.\n\n##### `alpaca.trading.cryptoFunding.createCryptoTransferForAccount`\n\nInitiate a crypto withdrawal/transfer for the account.\n\n```ts\nawait alpaca.trading.cryptoFunding.createCryptoTransferForAccount({\n  createCryptoTransferRequest: {\n    amount: \"0.5\",\n    address: \"0xabc...\",\n    asset: \"ETH\",\n  },\n});\n```\n\n##### `alpaca.trading.cryptoFunding.getCryptoFundingTransfer`\n\nFetch a single crypto transfer by id.\n\n```ts\nawait alpaca.trading.cryptoFunding.getCryptoFundingTransfer({\n  transferId: \"f1...e9\",\n});\n```\n\n##### `alpaca.trading.cryptoFunding.listCryptoFundingTransfers`\n\nList crypto transfers for the account.\n\n```ts\nawait alpaca.trading.cryptoFunding.listCryptoFundingTransfers();\n```\n\n##### `alpaca.trading.cryptoFunding.getCryptoTransferEstimate`\n\nEstimate fees for a crypto transfer.\n\n```ts\nawait alpaca.trading.cryptoFunding.getCryptoTransferEstimate({\n  asset: \"ETH\",\n  fromAddress: \"0xabc...\",\n  toAddress: \"0xdef...\",\n  amount: \"0.5\",\n});\n```\n\n##### `alpaca.trading.cryptoFunding.listCryptoFundingWallets`\n\nList the account's crypto wallets.\n\n```ts\nawait alpaca.trading.cryptoFunding.listCryptoFundingWallets({\n  asset: \"ETH\",\n});\n```\n\n##### `alpaca.trading.cryptoFunding.createWhitelistedAddress`\n\nWhitelist a crypto withdrawal address.\n\n```ts\nawait alpaca.trading.cryptoFunding.createWhitelistedAddress({\n  createWhitelistedAddressRequest: { address: \"0xabc...\", asset: \"ETH\" },\n});\n```\n\n##### `alpaca.trading.cryptoFunding.deleteWhitelistedAddress`\n\nRemove a whitelisted crypto address.\n\n```ts\nawait alpaca.trading.cryptoFunding.deleteWhitelistedAddress({\n  whitelistedAddressId: \"a1...c2\",\n});\n```\n\n##### `alpaca.trading.cryptoFunding.listWhitelistedAddress`\n\nList whitelisted crypto withdrawal addresses.\n\n```ts\nawait alpaca.trading.cryptoFunding.listWhitelistedAddress();\n```\n\n#### `alpaca.trading.cryptoPerpetualsAccountVitals` — CryptoPerpetualsAccountVitalsBetaApi\n\nCrypto perpetual-futures account vitals (beta).\n\n##### `alpaca.trading.cryptoPerpetualsAccountVitals.getCryptoPerpAccountVitals`\n\nCrypto perpetual-futures account vitals: margin, collateral, P&L (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsAccountVitals.getCryptoPerpAccountVitals();\n```\n\n#### `alpaca.trading.cryptoPerpetualsFunding` — CryptoPerpetualsFundingBetaApi\n\nCrypto perpetual-futures wallets and transfers (beta).\n\n##### `alpaca.trading.cryptoPerpetualsFunding.createCryptoPerpTransferForAccount`\n\nInitiate a crypto perpetual-futures transfer (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.createCryptoPerpTransferForAccount({\n  createCryptoTransferRequest: { amount: \"100\", asset: \"USDT\" },\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.getCryptoPerpFundingTransfer`\n\nFetch a single perpetual-futures transfer by id (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.getCryptoPerpFundingTransfer({\n  transferId: \"f1...e9\",\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.getCryptoPerpTransferEstimate`\n\nEstimate fees for a perpetual-futures transfer (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.getCryptoPerpTransferEstimate({\n  asset: \"USDT\",\n  amount: \"100\",\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.listCryptoPerpFundingTransfers`\n\nList perpetual-futures transfers (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.listCryptoPerpFundingTransfers();\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.listCryptoPerpFundingWallets`\n\nList perpetual-futures wallets (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.listCryptoPerpFundingWallets({\n  asset: \"USDT\",\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.createWhitelistedPerpAddress`\n\nWhitelist a perpetual-futures withdrawal address (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.createWhitelistedPerpAddress({\n  createWhitelistedPerpAddressRequest: {\n    address: \"0xabc...\",\n    asset: \"USDT\",\n  },\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.deleteWhitelistedPerpAddress`\n\nRemove a whitelisted perpetual-futures address (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.deleteWhitelistedPerpAddress({\n  whitelistedAddressId: \"a1...c2\",\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsFunding.listWhitelistedPerpAddress`\n\nList whitelisted perpetual-futures addresses (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsFunding.listWhitelistedPerpAddress();\n```\n\n#### `alpaca.trading.cryptoPerpetualsLeverage` — CryptoPerpetualsLeverageBetaApi\n\nRead/set crypto perpetual-futures account leverage (beta).\n\n##### `alpaca.trading.cryptoPerpetualsLeverage.getCryptoPerpAccountLeverage`\n\nRead crypto perpetual-futures account leverage (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsLeverage.getCryptoPerpAccountLeverage({\n  symbol: \"BTC-PERP\",\n});\n```\n\n##### `alpaca.trading.cryptoPerpetualsLeverage.setCryptoPerpAccountLeverage`\n\nSet crypto perpetual-futures account leverage (beta).\n\n```ts\nawait alpaca.trading.cryptoPerpetualsLeverage.setCryptoPerpAccountLeverage({\n  symbol: \"BTC-PERP\",\n  leverage: 5,\n});\n```\n\n#### `alpaca.trading.events` — EventsApi\n\nServer-sent event streams for account activity.\n\n##### `alpaca.trading.events.subscribeToActivitiesSSE`\n\nServer-sent event stream of account activities.\n\n```ts\nawait alpaca.trading.events.subscribeToActivitiesSSE({\n  sinceId: \"20240101000000000::...\",\n});\n```\n\n#### `alpaca.trading.orders` — OrdersApi\n\nPlace, read, replace and cancel orders.\n\n##### `alpaca.trading.orders.getAllOrders`\n\nList orders, filterable by status, side and symbol.\n\n```ts\nawait alpaca.trading.orders.getAllOrders({ status: \"open\", limit: 100 });\n```\n\n##### `alpaca.trading.orders.postOrder`\n\nPlace an order (raw). Prefer the typed builders under Ergonomic helpers.\n\n```ts\nawait alpaca.trading.orders.postOrder({\n  postOrderRequest: {\n    symbol: \"AAPL\",\n    qty: \"1\",\n    side: \"buy\",\n    type: \"market\",\n    timeInForce: \"day\",\n  },\n});\n```\n\n##### `alpaca.trading.orders.getOrderByOrderID`\n\nFetch a single order by its order id.\n\n```ts\nawait alpaca.trading.orders.getOrderByOrderID({ orderId: \"f1...e9\" });\n```\n\n##### `alpaca.trading.orders.getOrderByClientOrderId`\n\nFetch a single order by your client order id.\n\n```ts\nawait alpaca.trading.orders.getOrderByClientOrderId({\n  clientOrderId: \"my-order-1\",\n});\n```\n\n##### `alpaca.trading.orders.patchOrderByOrderId`\n\nReplace (amend) an open order.\n\n```ts\nawait alpaca.trading.orders.patchOrderByOrderId({\n  orderId: \"f1...e9\",\n  patchOrderRequest: { qty: \"2\" },\n});\n```\n\n##### `alpaca.trading.orders.deleteOrderByOrderID`\n\nCancel a single open order.\n\n```ts\nawait alpaca.trading.orders.deleteOrderByOrderID({ orderId: \"f1...e9\" });\n```\n\n##### `alpaca.trading.orders.deleteAllOrders`\n\nCancel all open orders.\n\n```ts\nawait alpaca.trading.orders.deleteAllOrders();\n```\n\n#### `alpaca.trading.portfolioHistory` — PortfolioHistoryApi\n\nTime series of account equity / P&L.\n\n##### `alpaca.trading.portfolioHistory.getAccountPortfolioHistory`\n\nTime series of account equity and profit/loss.\n\n```ts\nawait alpaca.trading.portfolioHistory.getAccountPortfolioHistory({\n  period: \"1M\",\n  timeframe: \"1D\",\n});\n```\n\n#### `alpaca.trading.positions` — PositionsApi\n\nOpen positions; close positions; exercise options.\n\n##### `alpaca.trading.positions.getAllOpenPositions`\n\nList all open positions.\n\n```ts\nawait alpaca.trading.positions.getAllOpenPositions();\n```\n\n##### `alpaca.trading.positions.getOpenPosition`\n\nFetch a single open position by symbol or asset id.\n\n```ts\nawait alpaca.trading.positions.getOpenPosition({ symbolOrAssetId: \"AAPL\" });\n```\n\n##### `alpaca.trading.positions.deleteAllOpenPositions`\n\nLiquidate every open position (optionally cancel orders first).\n\n```ts\nawait alpaca.trading.positions.deleteAllOpenPositions({\n  cancelOrders: true,\n});\n```\n\n##### `alpaca.trading.positions.deleteOpenPosition`\n\nClose a position: whole, partial qty, or a percentage.\n\n```ts\nawait alpaca.trading.positions.deleteOpenPosition({\n  symbolOrAssetId: \"AAPL\",\n  percentage: 50,\n});\n```\n\n##### `alpaca.trading.positions.optionExercise`\n\nExercise a held option position.\n\n```ts\nawait alpaca.trading.positions.optionExercise({\n  symbolOrContractId: \"AAPL250117C00150000\",\n});\n```\n\n##### `alpaca.trading.positions.optionDoNotExercise`\n\nSubmit a do-not-exercise instruction for an option position.\n\n```ts\nawait alpaca.trading.positions.optionDoNotExercise({\n  symbolOrContractId: \"AAPL250117C00150000\",\n});\n```\n\n#### `alpaca.trading.tokenization` — TokenizationApi\n\nTokenization requests and minting.\n\n##### `alpaca.trading.tokenization.getTokenizationRequests`\n\nList tokenization (mint/redeem) requests.\n\n```ts\nawait alpaca.trading.tokenization.getTokenizationRequests({\n  status: \"completed\",\n});\n```\n\n##### `alpaca.trading.tokenization.postTokenizationMint`\n\nSubmit a tokenization mint request.\n\n```ts\nawait alpaca.trading.tokenization.postTokenizationMint({\n  tokenizationMintRequest: { underlyingSymbol: \"AAPL\", quantity: \"1\" },\n});\n```\n\n#### `alpaca.trading.watchlists` — WatchlistsApi\n\nCreate and manage watchlists and their assets.\n\n##### `alpaca.trading.watchlists.getWatchlists`\n\nList all watchlists.\n\n```ts\nawait alpaca.trading.watchlists.getWatchlists();\n```\n\n##### `alpaca.trading.watchlists.getWatchlistById`\n\nFetch a single watchlist by id.\n\n```ts\nawait alpaca.trading.watchlists.getWatchlistById({\n  watchlistId: \"f1...e9\",\n});\n```\n\n##### `alpaca.trading.watchlists.getWatchlistByName`\n\nFetch a single watchlist by name.\n\n```ts\nawait alpaca.trading.watchlists.getWatchlistByName({ name: \"My List\" });\n```\n\n##### `alpaca.trading.watchlists.postWatchlist`\n\nCreate a watchlist with an initial set of symbols.\n\n```ts\nawait alpaca.trading.watchlists.postWatchlist({\n  updateWatchlistRequest: { name: \"Tech\", symbols: [\"AAPL\", \"MSFT\"] },\n});\n```\n\n##### `alpaca.trading.watchlists.updateWatchlistById`\n\nUpdate a watchlist (name and/or symbols) by id.\n\n```ts\nawait alpaca.trading.watchlists.updateWatchlistById({\n  watchlistId: \"f1...e9\",\n  updateWatchlistRequest: { name: \"Renamed\" },\n});\n```\n\n##### `alpaca.trading.watchlists.updateWatchlistByName`\n\nUpdate a watchlist (name and/or symbols) by name.\n\n```ts\nawait alpaca.trading.watchlists.updateWatchlistByName({\n  name: \"Tech\",\n  updateWatchlistRequest: { symbols: [\"AAPL\"] },\n});\n```\n\n##### `alpaca.trading.watchlists.addAssetToWatchlist`\n\nAdd an asset to a watchlist by id.\n\n```ts\nawait alpaca.trading.watchlists.addAssetToWatchlist({\n  watchlistId: \"f1...e9\",\n  addAssetToWatchlistRequest: { symbol: \"NVDA\" },\n});\n```\n\n##### `alpaca.trading.watchlists.addAssetToWatchlistByName`\n\nAdd an asset to a watchlist by name.\n\n```ts\nawait alpaca.trading.watchlists.addAssetToWatchlistByName({\n  name: \"Tech\",\n  addAssetToWatchlistRequest: { symbol: \"NVDA\" },\n});\n```\n\n##### `alpaca.trading.watchlists.removeAssetFromWatchlist`\n\nRemove an asset from a watchlist by id.\n\n```ts\nawait alpaca.trading.watchlists.removeAssetFromWatchlist({\n  watchlistId: \"f1...e9\",\n  symbol: \"NVDA\",\n});\n```\n\n##### `alpaca.trading.watchlists.deleteWatchlistById`\n\nDelete a watchlist by id.\n\n```ts\nawait alpaca.trading.watchlists.deleteWatchlistById({\n  watchlistId: \"f1...e9\",\n});\n```\n\n##### `alpaca.trading.watchlists.deleteWatchlistByName`\n\nDelete a watchlist by name.\n\n```ts\nawait alpaca.trading.watchlists.deleteWatchlistByName({ name: \"Tech\" });\n```\n\n### Market Data API\n\n<details>\n<summary><strong>Operations</strong> (42)</summary>\n\n- `stocks` — [stockBars](#alpacamarketdatastocksstockbars), [stockTrades](#alpacamarketdatastocksstocktrades), [stockQuotes](#alpacamarketdatastocksstockquotes), [stockAuctions](#alpacamarketdatastocksstockauctions), [stockSnapshots](#alpacamarketdatastocksstocksnapshots), [stockLatestBars](#alpacamarketdatastocksstocklatestbars), [stockLatestQuotes](#alpacamarketdatastocksstocklatestquotes), [stockLatestTrades](#alpacamarketdatastocksstocklatesttrades), [stockMetaConditions](#alpacamarketdatastocksstockmetaconditions), [stockMetaExchanges](#alpacamarketdatastocksstockmetaexchanges)\n- `crypto` — [cryptoBars](#alpacamarketdatacryptocryptobars), [cryptoTrades](#alpacamarketdatacryptocryptotrades), [cryptoQuotes](#alpacamarketdatacryptocryptoquotes), [cryptoSnapshots](#alpacamarketdatacryptocryptosnapshots), [cryptoLatestBars](#alpacamarketdatacryptocryptolatestbars), [cryptoLatestQuotes](#alpacamarketdatacryptocryptolatestquotes), [cryptoLatestTrades](#alpacamarketdatacryptocryptolatesttrades), [cryptoLatestOrderbooks](#alpacamarketdatacryptocryptolatestorderbooks)\n- `cryptoPerpetualFutures` — [cryptoPerpLatestBars](#alpacamarketdatacryptoperpetualfuturescryptoperplatestbars), [cryptoPerpLatestQuotes](#alpacamarketdatacryptoperpetualfuturescryptoperplatestquotes), [cryptoPerpLatestTrades](#alpacamarketdatacryptoperpetualfuturescryptoperplatesttrades), [cryptoPerpLatestOrderbooks](#alpacamarketdatacryptoperpetualfuturescryptoperplatestorderbooks), [cryptoPerpLatestFuturesPricing](#alpacamarketdatacryptoperpetualfuturescryptoperplatestfuturespricing)\n- `fixedIncome` — [fixedIncomeLatestPrices](#alpacamarketdatafixedincomefixedincomelatestprices), [fixedIncomeLatestQuotes](#alpacamarketdatafixedincomefixedincomelatestquotes)\n- `forex` — [rates](#alpacamarketdataforexrates), [latestRates](#alpacamarketdataforexlatestrates)\n- `indices` — [indexValues](#alpacamarketdataindicesindexvalues), [indexLatestValues](#alpacamarketdataindicesindexlatestvalues)\n- `logos` — [logos](#alpacamarketdatalogoslogos)\n- `news` — [news](#alpacamarketdatanewsnews)\n- `options` — [optionBars](#alpacamarketdataoptionsoptionbars), [optionTrades](#alpacamarketdataoptionsoptiontrades), [optionChain](#alpacamarketdataoptionsoptionchain), [optionSnapshots](#alpacamarketdataoptionsoptionsnapshots), [optionLatestQuotes](#alpacamarketdataoptionsoptionlatestquotes), [optionLatestTrades](#alpacamarketdataoptionsoptionlatesttrades), [optionMetaConditions](#alpacamarketdataoptionsoptionmetaconditions), [optionMetaExchanges](#alpacamarketdataoptionsoptionmetaexchanges)\n- `screener` — [mostActives](#alpacamarketdatascreenermostactives), [movers](#alpacamarketdatascreenermovers)\n- `corporateActions` — [corporateActions](#alpacamarketdatacorporateactionscorporateactions)\n\n</details>\n\n#### `alpaca.marketData.stocks` — StockApi\n\nUS-equity bars, trades, quotes, auctions and snapshots.\n\n##### `alpaca.marketData.stocks.stockBars`\n\nHistorical bars for one or more stocks (paginated).\n\n```ts\nawait alpaca.marketData.stocks.stockBars({\n  symbols: \"AAPL,MSFT\",\n  timeframe: \"1Day\",\n  start: new Date(\"2024-01-01\"),\n});\n```\n\n##### `alpaca.marketData.stocks.stockTrades`\n\nHistorical trades for one or more stocks (paginated).\n\n```ts\nawait alpaca.marketData.stocks.stockTrades({\n  symbols: \"AAPL\",\n  start: new Date(\"2024-01-02\"),\n});\n```\n\n##### `alpaca.marketData.stocks.stockQuotes`\n\nHistorical quotes for one or more stocks (paginated).\n\n```ts\nawait alpaca.marketData.stocks.stockQuotes({\n  symbols: \"AAPL\",\n  start: new Date(\"2024-01-02\"),\n});\n```\n\n##### `alpaca.marketData.stocks.stockAuctions`\n\nHistorical opening/closing auctions for stocks (paginated).\n\n```ts\nawait alpaca.marketData.stocks.stockAuctions({\n  symbols: \"AAPL\",\n  start: new Date(\"2024-01-02\"),\n});\n```\n\n##### `alpaca.marketData.stocks.stockSnapshots`\n\nLatest snapshot (trade, quote, bars) for one or more stocks.\n\n```ts\nawait alpaca.marketData.stocks.stockSnapshots({ symbols: \"AAPL,MSFT\" });\n```\n\n##### `alpaca.marketData.stocks.stockLatestBars`\n\nLatest minute bar for one or more stocks.\n\n```ts\nawait alpaca.marketData.stocks.stockLatestBars({ symbols: \"AAPL,MSFT\" });\n```\n\n##### `alpaca.marketData.stocks.stockLatestQuotes`\n\nLatest quote for one or more stocks.\n\n```ts\nawait alpaca.marketData.stocks.stockLatestQuotes({ symbols: \"AAPL,MSFT\" });\n```\n\n##### `alpaca.marketData.stocks.stockLatestTrades`\n\nLatest trade for one or more stocks.\n\n```ts\nawait alpaca.marketData.stocks.stockLatestTrades({ symbols: \"AAPL,MSFT\" });\n```\n\n##### `alpaca.marketData.stocks.stockMetaConditions`\n\nTrade/quote condition-code mappings for a tape.\n\n```ts\nawait alpaca.marketData.stocks.stockMetaConditions({\n  ticktype: \"trade\",\n  tape: \"A\",\n});\n```\n\n##### `alpaca.marketData.stocks.stockMetaExchanges`\n\nExchange-code mappings.\n\n```ts\nawait alpaca.marketData.stocks.stockMetaExchanges();\n```\n\n#### `alpaca.marketData.crypto` — CryptoApi\n\nCrypto bars, trades, quotes, orderbooks and snapshots.\n\n##### `alpaca.marketData.crypto.cryptoBars`\n\nHistorical crypto bars (paginated); `loc` selects the data region.\n\n```ts\nawait alpaca.marketData.crypto.cryptoBars({\n  loc: \"us\",\n  symbols: \"BTC/USD,ETH/USD\",\n  timeframe: \"1Day\",\n  start: new Date(\"2024-01-01\"),\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoTrades`\n\nHistorical crypto trades (paginated).\n\n```ts\nawait alpaca.marketData.crypto.cryptoTrades({\n  loc: \"us\",\n  symbols: \"BTC/USD\",\n  start: new Date(\"2024-01-02\"),\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoQuotes`\n\nHistorical crypto quotes (paginated).\n\n```ts\nawait alpaca.marketData.crypto.cryptoQuotes({\n  loc: \"us\",\n  symbols: \"BTC/USD\",\n  start: new Date(\"2024-01-02\"),\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoSnapshots`\n\nLatest snapshot for one or more crypto pairs.\n\n```ts\nawait alpaca.marketData.crypto.cryptoSnapshots({\n  loc: \"us\",\n  symbols: \"BTC/USD,ETH/USD\",\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoLatestBars`\n\nLatest bar for one or more crypto pairs.\n\n```ts\nawait alpaca.marketData.crypto.cryptoLatestBars({\n  loc: \"us\",\n  symbols: \"BTC/USD\",\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoLatestQuotes`\n\nLatest quote for one or more crypto pairs.\n\n```ts\nawait alpaca.marketData.crypto.cryptoLatestQuotes({\n  loc: \"us\",\n  symbols: \"BTC/USD\",\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoLatestTrades`\n\nLatest trade for one or more crypto pairs.\n\n```ts\nawait alpaca.marketData.crypto.cryptoLatestTrades({\n  loc: \"us\",\n  symbols: \"BTC/USD\",\n});\n```\n\n##### `alpaca.marketData.crypto.cryptoLatestOrderbooks`\n\nLatest order book for one or more crypto pairs.\n\n```ts\nawait alpaca.marketData.crypto.cryptoLatestOrderbooks({\n  loc: \"us\",\n  symbols: \"BTC/USD\",\n});\n```\n\n#### `alpaca.marketData.cryptoPerpetualFutures` — CryptoPerpetualFuturesApi\n\nCrypto perpetual-futures latest market data.\n\n##### `alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestBars`\n\nLatest bar for one or more crypto perpetual-futures contracts.\n\n```ts\nawait alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestBars({\n  loc: \"global\",\n  symbols: \"BTC-PERP\",\n});\n```\n\n##### `alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestQuotes`\n\nLatest quote for one or more perpetual-futures contracts.\n\n```ts\nawait alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestQuotes({\n  loc: \"global\",\n  symbols: \"BTC-PERP\",\n});\n```\n\n##### `alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestTrades`\n\nLatest trade for one or more perpetual-futures contracts.\n\n```ts\nawait alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestTrades({\n  loc: \"global\",\n  symbols: \"BTC-PERP\",\n});\n```\n\n##### `alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestOrderbooks`\n\nLatest order book for one or more perpetual-futures contracts.\n\n```ts\nawait alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestOrderbooks({\n  loc: \"global\",\n  symbols: \"BTC-PERP\",\n});\n```\n\n##### `alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestFuturesPricing`\n\nLatest funding/mark pricing for perpetual-futures contracts.\n\n```ts\nawait alpaca.marketData.cryptoPerpetualFutures.cryptoPerpLatestFuturesPricing({\n  loc: \"global\",\n  symbols: \"BTC-PERP\",\n});\n```\n\n#### `alpaca.marketData.fixedIncome` — FixedIncomeApi\n\nFixed-income latest prices and quotes.\n\n##### `alpaca.marketData.fixedIncome.fixedIncomeLatestPrices`\n\nLatest fixed-income prices by ISIN.\n\n```ts\nawait alpaca.marketData.fixedIncome.fixedIncomeLatestPrices({\n  isins: \"US0378331005\",\n});\n```\n\n##### `alpaca.marketData.fixedIncome.fixedIncomeLatestQuotes`\n\nLatest fixed-income quotes by ISIN.\n\n```ts\nawait alpaca.marketData.fixedIncome.fixedIncomeLatestQuotes({\n  isins: \"US0378331005\",\n  tradeSize: 100,\n});\n```\n\n#### `alpaca.marketData.forex` — ForexApi\n\nForeign-exchange historical and latest rates.\n\n##### `alpaca.marketData.forex.rates`\n\nHistorical forex rates for currency pairs (paginated).\n\n```ts\nawait alpaca.marketData.forex.rates({\n  currencyPairs: \"EUR/USD\",\n  timeframe: \"1Day\",\n  start: new Date(\"2024-01-01\"),\n});\n```\n\n##### `alpaca.marketData.forex.latestRates`\n\nLatest forex rates for one or more currency pairs.\n\n```ts\nawait alpaca.marketData.forex.latestRates({\n  currencyPairs: \"EUR/USD,GBP/USD\",\n});\n```\n\n#### `alpaca.marketData.indices` — IndexApi\n\nIndex historical and latest values.\n\n##### `alpaca.marketData.indices.indexValues`\n\nHistorical index values (paginated).\n\n```ts\nawait alpaca.marketData.indices.indexValues({\n  symbols: \"SPX\",\n  start: new Date(\"2024-01-01\"),\n});\n```\n\n##### `alpaca.marketData.indices.indexLatestValues`\n\nLatest values for one or more indices.\n\n```ts\nawait alpaca.marketData.indices.indexLatestValues({ symbols: \"SPX\" });\n```\n\n#### `alpaca.marketData.logos` — LogosApi\n\nCompany logo images.\n\n##### `alpaca.marketData.logos.logos`\n\nCompany logo image bytes for a symbol.\n\n```ts\nawait alpaca.marketData.logos.logos({ symbol: \"AAPL\" });\n```\n\n#### `alpaca.marketData.news` — NewsApi\n\nMarket news articles.\n\n##### `alpaca.marketData.news.news`\n\nLatest news articles across stocks and crypto (paginated).\n\n```ts\nawait alpaca.marketData.news.news({ symbols: \"AAPL,TSLA\", limit: 10 });\n```\n\n#### `alpaca.marketData.options` — OptionApi\n\nOptions bars, trades, chains and snapshots.\n\n##### `alpaca.marketData.options.optionBars`\n\nHistorical option bars (paginated).\n\n```ts\nawait alpaca.marketData.options.optionBars({\n  symbols: \"AAPL250117C00150000\",\n  timeframe: \"1Day\",\n  start: new Date(\"2024-01-01\"),\n});\n```\n\n##### `alpaca.marketData.options.optionTrades`\n\nHistorical option trades (paginated).\n\n```ts\nawait alpaca.marketData.options.optionTrades({\n  symbols: \"AAPL250117C00150000\",\n  start: new Date(\"2024-01-02\"),\n});\n```\n\n##### `alpaca.marketData.options.optionChain`\n\nSnapshots for an underlying's full option chain (paginated).\n\n```ts\nawait alpaca.marketData.options.optionChain({\n  underlyingSymbol: \"AAPL\",\n  type: \"call\",\n});\n```\n\n##### `alpaca.marketData.options.optionSnapshots`\n\nLatest snapshots for one or more option contracts.\n\n```ts\nawait alpaca.marketData.options.optionSnapshots({\n  symbols: \"AAPL250117C00150000\",\n});\n```\n\n##### `alpaca.marketData.options.optionLatestQuotes`\n\nLatest quotes for one or more option contracts.\n\n```ts\nawait alpaca.marketData.options.optionLatestQuotes({\n  symbols: \"AAPL250117C00150000\",\n});\n```\n\n##### `alpaca.marketData.options.optionLatestTrades`\n\nLatest trades for one or more option contracts.\n\n```ts\nawait alpaca.marketData.options.optionLatestTrades({\n  symbols: \"AAPL250117C00150000\",\n});\n```\n\n##### `alpaca.marketData.options.optionMetaConditions`\n\nOption trade/quote condition-code mappings.\n\n```ts\nawait alpaca.marketData.options.optionMetaConditions({ ticktype: \"trade\" });\n```\n\n##### `alpaca.marketData.options.optionMetaExchanges`\n\nOption exchange-code mappings.\n\n```ts\nawait alpaca.marketData.options.optionMetaExchanges();\n```\n\n#### `alpaca.marketData.screener` — ScreenerApi\n\nMarket movers and most-active screeners.\n\n##### `alpaca.marketData.screener.mostActives`\n\nMost-active stocks by volume or trade count.\n\n```ts\nawait alpaca.marketData.screener.mostActives({ by: \"volume\", top: 10 });\n```\n\n##### `alpaca.marketData.screener.movers`\n\nTop market gainers and losers.\n\n```ts\nawait alpaca.marketData.screener.movers({ marketType: \"stocks\", top: 10 });\n```\n\n#### `alpaca.marketData.corporateActions` — CorporateActionsApi\n\nHistorical corporate-action data.\n\n##### `alpaca.marketData.corporateActions.corporateActions`\n\nHistorical corporate-action data by symbol and type (paginated).\n\n```ts\nawait alpaca.marketData.corporateActions.corporateActions({\n  symbols: \"AAPL\",\n  types: \"cash_dividend\",\n  start: new Date(\"2024-01-01\"),\n});\n```\n\n### Real-time streaming\n\n#### `alpaca.trading.stream` — TradingStream\n\nOpen the trading-updates WebSocket (order/account events, JSON).\n\n```ts\nconst updates = alpaca.trading.stream();\nupdates.onTradeUpdate((u) => console.log(u.event, u.order.symbol));\nupdates.onConnect(() => updates.subscribeTradeUpdates());\nupdates.connect();\n```\n\n#### `alpaca.marketData.stockStream` — StockDataStream\n\nOpen the US-equity market-data WebSocket (msgpack).\n\n```ts\nconst stocks = alpaca.marketData.stockStream({ feed: \"iex\" });\nstocks.onBar((bar) => console.log(bar.symbol, bar.close));\nstocks.onConnect(() => stocks.subscribeForBars([\"AAPL\", \"MSFT\"]));\nstocks.connect();\n```\n\n#### `alpaca.marketData.cryptoStream` — CryptoDataStream\n\nOpen the crypto market-data WebSocket (msgpack).\n\n```ts\nconst crypto = alpaca.marketData.crypt","readmeFilename":"README.md"}