> Every Taji docs page as Markdown: https://docs.taji.is/llms.txt

# Alpaca: how it works

Alpaca is a US broker whose one key pair serves both its trading API and its market-data API. Taji takes three things from it: equity, option and crypto orders on a paper or live account; that account's money, positions, orders, fills and fees; and stock, option and crypto market data, history and live. The integration is one compiled-in crate, `taji-alpaca` (`plugins/alpaca/`). It registers a data `Source`, a brokerage `VenueArm` and a link `Auth`, and it talks to four hosts: the paper or live trading host, `data.alpaca.markets` and `stream.data.alpaca.markets`.

## The vendor

### Hosts and environments

| Host | Serves | Environment |
|---|---|---|
| `https://paper-api.alpaca.markets` | Trading API; `wss://…/stream` for `trade_updates` | paper |
| `https://api.alpaca.markets` | Trading API; `wss://…/stream` for `trade_updates` | live |
| `https://data.alpaca.markets` | Market Data API, REST | both: one host for paper and live keys |
| `wss://stream.data.alpaca.markets/{version}/{feed}` | Market Data API, streams | both |

Paper and live are separate accounts with separate key pairs, and neither trading host takes the other's pair ([paper trading](https://docs.alpaca.markets/docs/paper-trading)). A paper account starts with $100k. Paper fills a non-marketable limit once the NBBO reaches it, fills about 10% of eligible orders partially, and does not simulate dividends, regulatory fees or price improvement (same page).

Alpaca also runs a Broker API (`broker-api.alpaca.markets`) and sandbox hosts. Taji calls neither.

### Auth

A Trading API key is a key ID and a secret, sent on every REST request as the headers `APCA-API-KEY-ID` and `APCA-API-SECRET-KEY`. On a socket they go as the first frame, `{"action":"auth","key":…,"secret":…}`. The [authentication page](https://docs.alpaca.markets/docs/authentication) states no lifetime for these keys. Its OAuth client-credentials flow issues 15-minute bearer tokens, but the page says that flow "is not yet available for Trading API". So nothing in this crate refreshes a token: a pair works until you regenerate it in the dashboard. The README's [Linking](https://docs.taji.is/catalog/alpaca.md#linking) section records the dashboard steps.

### API families Taji calls

Every path below is a `format!` or a constant in the crate. Each operationId is the one in Alpaca's OpenAPI specs: `trading-api.json` is version 2.0.1 and `market-data-api.json` is version 1.1, both fetched 2026-12-02 from the [OpenAPI index](https://docs.alpaca.markets/us/openapi).

| Family | Calls | File |
|---|---|---|
| Account | `GET /v2/account` (getAccount); `GET /v2/account/activities/{FILL,FEE,CFEE}` | `exec/http.rs` |
| Orders | `POST /v2/orders`, `GET /v2/orders` (pages back on `until`), `GET /v2/orders/{id}?nested=true`, `GET /v2/orders:by_client_order_id`, `PATCH`/`DELETE /v2/orders/{id}` | `exec/http.rs` |
| Positions | `GET /v2/positions`; `POST /v2/positions/{contract}/exercise` and `/do-not-exercise` | `exec/http.rs` |
| Market clock and calendar | `GET /v3/clock?markets=NYSE` (Clock); `GET /v3/calendar/NYSE` (Calendar); `GET /v2/clock` only to keep a connection warm | `exec/http.rs`, `reads.rs` |
| Assets and contracts | `GET /v2/assets`, `/v2/assets/{symbol}`; `GET /v2/options/contracts`, `/v2/options/contracts/{symbol}` | `lib.rs`, `reads.rs` |
| Order stream | `wss://<trading host>/stream`, `listen` on `trade_updates` | `exec/ws.rs` |
| Stock data | `StockBars`, `StockTrades`, `StockQuotes`, `StockAuctions`, `StockSnapshots`, `StockSnapshotSingle`, `StockLatestTradeSingle` (link check), `StockMetaExchanges` (warm) under `/v2/stocks/` | `lib.rs`, `reads.rs`, `link.rs` |
| Option data | `optionBars`, `OptionTrades`, `OptionSnapshots`, `OptionChain` under `/v1beta1/options/` | `lib.rs`, `reads.rs` |
| Crypto data | `CryptoBars`, `CryptoTrades`, `CryptoQuotes`, `CryptoSnapshots`, `CryptoLatestOrderbooks` under `/v1beta3/crypto/us-1/` | `lib.rs`, `reads.rs` |
| Reference | `News` (`/v1beta1/news`), `Movers` and `MostActives` (`/v1beta1/screener/…`), `CorporateActions` (`/v1/corporate-actions`) | `reads.rs`, `corporate_actions.rs` |
| Streams | `v2/sip`, `v2/delayed_sip`, `v1beta1/boats`, `v1beta1/overnight`, `v1beta1/opra`, `v1beta1/indicative`, `v1beta3/crypto/us-1` | `live.rs` |

Vendor pages, each fetched 2026-12-02:

- [Orders at Alpaca](https://docs.alpaca.markets/docs/orders-at-alpaca): order types; `day`, `gtc`, `opg`, `cls`, `ioc`, `fok`; extended hours (limit with `day` or `gtc` only); bracket, OCO and OTO; replace rules; statuses.
- [Options trading](https://docs.alpaca.markets/docs/options-trading): levels 0 to 3; `day` or `gtc` only; no extended hours; whole quantities; exercise by `POST /v2/positions/{symbol_or_contract_id}/exercise`.
- [Crypto trading](https://docs.alpaca.markets/docs/crypto-trading): 24 hours a day; market, limit and stop-limit; `gtc` and `ioc`; fractionable; no shorting; no margin.
- [WebSocket streaming](https://docs.alpaca.markets/docs/websocket-streaming): `trade_updates`. The paper stream "uses binary frames"; a `listen` replaces the whole stream list; an in-stream error is followed by a close.
- [Real-time stock data](https://docs.alpaca.markets/docs/real-time-stock-pricing-data): feeds `sip`, `iex`, `delayed_sip`, `boats`, `overnight`; channels; `updatedBars` at half-minute marks.
- [Streaming market data](https://docs.alpaca.markets/docs/streaming-market-data): socket error codes 400 to 410; MessagePack via `Content-Type: application/msgpack`; "many subscriptions … are limited to 1 connection".
- [Real-time crypto data](https://docs.alpaca.markets/docs/real-time-crypto-pricing-data): locations `us` (Alpaca's own exchange, where orders execute), `us-1` (Kraken US), `eu-1`; an orderbook frame with `r: true` is the whole book.
- [Real-time option data](https://docs.alpaca.markets/docs/real-time-option-data): `opra` or `indicative`, "only available in msgpack format", no `*` on quotes.
- [Historical stock data](https://docs.alpaca.markets/docs/historical-stock-data-1) and the [market data FAQ](https://docs.alpaca.markets/docs/market-data-faq): feeds; without a subscription a SIP `end` must be at least 15 minutes old; how minute bars are built from trade conditions.

### Accounts and entitlements

One key pair reaches one account, and `GET /v2/account` answers for it. That account's `options_trading_level` and `shorting_enabled` bound what it may trade. Market data is entitled per plan ([about market data](https://docs.alpaca.markets/docs/about-market-data-api)). On Basic, which is free and the default on every new paper or live account, you get real-time IEX, 15-minute history limits on SIP and OPRA, and the indicative option feed. On Algo Trader Plus, at $99 a month, you get SIP and OPRA. Taji never reads IEX (see Why). Crypto data is the same on both plans.

### Stated limits

- Trading API: "200 requests per minute, per account", over which the vendor answers 429 ([usage limit](https://alpaca.markets/support/usage-limit-api-calls)). The [rate limits page](https://docs.alpaca.markets/docs/rate-limits) covers only the Broker API; it names the `X-RateLimit-Limit`, `-Remaining` and `-Reset` headers.
- Historical market data: 200 calls a minute on Basic, 10,000 on Algo Trader Plus.
- Sockets: 30 equity symbols on Basic, unlimited on Algo Trader Plus; 200 or 1,000 option quotes. The connection count per endpoint "depends on their subscription", most often 1.
- `limit` on a history page: at most 10,000, default 1,000. A `client_order_id` holds at most 128 characters (`trading-api.json`).

### What Taji does not use

- **IEX** (`feed=iex`, `v2/iex`): it carries one exchange, about 2.5% of volume. Taji refuses a single-exchange tape at any price (`lib.rs` header).
- **The equity `bars` stream channel**: it emits about 1 s after the minute, which conflicts with end-of-day timers (`lib.rs` header). Taji folds `trades` into bars itself. The `dailyBars` and `imbalances` channels are not yet built.
- **`unit_splits`** in corporate actions: their rows carry `old_symbol`/`new_symbol` and no `ex_date`, which is the wrong shape for a split (`corporate_actions.rs`).
- **Crypto locations `us`, `us-2`, `eu-1`, `bs-1` for data**: `us` printed BTC/USD once in 3 minutes against `us-1`'s 24 a minute (`lib.rs` `CRYPTO_PATH`). Orders still execute on `us`.
- **Asset classes `crypto_perp`, `us_index` and the other new `AssetClass` values**: unread ([README § Trades](https://docs.taji.is/catalog/alpaca.md#trades)).
- **OAuth, the Broker API, the `/v3/stocks/{feed}/bars` family, SSE events, logos, fixed income, watchlists, portfolio history, account configurations, wallets, locates and tokenization**: not yet built.

### Offered, not read

What Taji reads, down to each field it fills, is `docs/reference/coverage/alpaca.md`. What Alpaca serves past that:

| Offered | Endpoint | Plan | Source, fetched |
|---|---|---|---|
| A print's exchange (`x`): the decoders drop it, so a trade's `exchange` and a quote's `last_exchange` stay null | `StockTrades`, `OptionTrades`, the `trades` channels, a snapshot's `latestTrade` | both | `market-data-api.json`, 2026-12-02 |
| A quote's bid and ask exchanges (`bx`, `ax`) and its condition (`c`): no `quotes` column holds them | `StockQuotes`, a snapshot's `latestQuote`, the `quotes` channels | both | `market-data-api.json`, 2026-12-02 |
| A chain row's bid and ask sizes (`bs`, `as`) and its `minuteBar` and `prevDailyBar`: `chains` holds no size or prior-day column | `OptionChain`, `OptionSnapshots` | `opra` on Algo Trader Plus, else `indicative` | [optionchain](https://docs.alpaca.markets/reference/optionchain), [optionsnapshots](https://docs.alpaca.markets/reference/optionsnapshots), 2026-12-03 |
| A contract's `open_interest_date`, `close_price`, `close_price_date` and, with `show_deliverables=true`, its `deliverables` | `GET /v2/options/contracts` | both | [get-options-contracts](https://docs.alpaca.markets/reference/get-options-contracts-1), 2026-12-03 |

## Code map

| File | Owns | Read first |
|---|---|---|
| `plugins/alpaca/taji-plugin.toml` | The manifest: id, `about`, `[[sources]]`, the two `[[link]]` forms | the `[[link]]` tables |
| `plugins/alpaca/src/lib.rs` | `Plugin` (registers source, arm, auth); `AlpacaClient`, the data REST client and `HistoricalData`; host and path constants; bar parsing | `Plugin::build`, then `AlpacaClient::bars_on` |
| `plugins/alpaca/src/source.rs` | `Alpaca`, the hub `Source`: `READS`, `FACTS`, the bars `CAP`, the plan tiers, every non-bar read, ticks and the crypto book | `FACTS`, then `read` |
| `plugins/alpaca/src/reads.rs` | One vendor endpoint per function, answered as sent; the `sip`→`delayed_sip` and `opra`→`indicative` fallback | `fed` |
| `plugins/alpaca/src/corporate_actions.rs` | `/v1/corporate-actions`, batched by symbols, and its parse | `parse_pages` |
| `plugins/alpaca/src/live.rs` | `LiveStream` for `AlpacaClient`: one `LiveCore` per socket (equity, crypto, option, overnight), msgpack framing, refcounted subscriptions, reconnect | `impl LiveStream for AlpacaClient` |
| `plugins/alpaca/src/aggregator.rs` | `AlpacaBarAggregator`: SIP trades into 1-minute bars by Alpaca's own condition rules | the module header |
| `plugins/alpaca/src/forming.rs` | The forming minute sent `is_closed: false` between closes | `FORMING_EVERY` |
| `plugins/alpaca/src/ratelimit.rs` | Per-login budgets (trading, clock, data, bulk) and the stream symbol count; folds `X-RateLimit-*` and 429s | `RateLimits::reply` |
| `plugins/alpaca/src/link.rs` | `Auth`: the REST validate, the SIP-tier probe, the account number | `Auth::check` |
| `plugins/alpaca/src/venue.rs` | `FACTS` (`VenueFacts`), fees, `Arm`; the paper and live URL pins; the `trade_updates` wake | `paper_arm` |
| `plugins/alpaca/src/offer.rs` | `OFFER` and `VENUE_OFFER`, the coverage page's cells | `offered` |
| `plugins/alpaca/src/exec/mod.rs` | `AlpacaEquityBroker`, the order adapter's state | `AlpacaEquityBroker::new` |
| `plugins/alpaca/src/exec/broker.rs` | `ExecutionOps`: place, settle an ambiguous POST, fan-out, status, orders, positions, cancel, replace, exercise; capability and protection matrices | `place_impl` |
| `plugins/alpaca/src/exec/orders.rs` | `OrderIntent` to Alpaca order body; `LEGALITY`, the shape × TIF matrix; the `mleg` body | `build_alpaca_order` |
| `plugins/alpaca/src/exec/http.rs` | `AlpacaHttpClient`: trading REST, submit-failure classes, `VenueReads` | `classify_submit_failure` |
| `plugins/alpaca/src/exec/models.rs` | Trading DTOs, deserialize-only, unknown fields ignored | `AlpacaOrder` |
| `plugins/alpaca/src/exec/coid.rs` | The `client_order_id` an intent stakes | `taji_client_order_id` |
| `plugins/alpaca/src/exec/ws.rs` | The `trade_updates` consumer, which wakes the reconcile | `run_trade_updates` |
| `plugins/alpaca/tests/egress.rs` | Byte goldens of what the crate sends, under `plugins/alpaca/tests/egress/` | the test names |
| `plugins/alpaca/tests/*_live.rs`, `plugins/alpaca/tests/live.rs` | Ignored tests against the real vendor | each file's header |

## How it plugs into Taji

### Traits

- **`Source`** (`engine/crates/taji-plugin/src/vendor/mod.rs`), implemented by `source::Alpaca`. `seat` builds one `AlpacaClient` the hub holds as both history and live. `history` hands out that client. `read` and `raw_read` serve every non-bar product. `quote`, `quotes_now` and `quote_legs` serve snapshots. `open_ticks` opens tick streams. `probe` and `replan` turn the tier word into a plan.
- **`HistoricalData`** (`substrate/taji-brokerage/src/traits/historical_data.rs`), on `AlpacaClient` in `lib.rs`: bars by session and adjustment, many symbols per request (`batch` = 100), equity trades.
- **`LiveStream`** (`substrate/taji-brokerage/src/traits/live_stream.rs`), on `AlpacaClient` in `live.rs`: 1-minute bars only, `closes_every_bar` true.
- **`VenueArm`** (`engine/crates/taji-plugin/src/vendor/venue.rs`), on `venue::Arm`. `bind` answers the order adapter, the `VenueReads` and the `trade_updates` wake.
- **`ExecutionOps`** (`substrate/taji-brokerage/src/traits/execution_ops.rs`), on `exec::AlpacaEquityBroker`. Despite the name, it carries equities, single-leg and `mleg` options, and crypto.
- **`VenueReads`** (`substrate/taji-brokerage/src/traits/venue_reads.rs`), on `AlpacaHttpClient`: `money` from `/v2/account`, `clock` from `/v3/clock`, `fees` and `fills` from account activities.
- **`Auth`** (`engine/crates/taji-plugin/src/vendor/venue.rs`), on `link::Auth`: `check` on a new pair, `again` on `POST /verb/link/venue/redetect`.

No `ReconcileOps` implementation exists. The reconcile reads `orders_since` and `positions` through `ExecutionOps`.

### Statics

- `source::FACTS`: the reads (`READS`), `seat: Venue`, sessions where equities serve bars and trades past regular hours, `permits: 40`, the `atp` and `basic` tiers, `overnight_live`, the formats `parse` reads, `bars_cap: CAP`, `delayed_feeds` (`delayed_sip`, `indicative`), and the crypto `book` scope.
- `source::CAP`: classes, depth by interval (equity from 2016-01-04, option from 2024-01-01, crypto from 2021-01-01), native tiers, the 960 s SIP clip, `rate_per_min: 200`, first-paint sizes.
- `venue::FACTS`: the records `alpaca` (paper) and `alpaca-live`, the `.env` pair names `ALPACA_API_KEY`/`ALPACA_API_SECRET` (paper only), fees, `LinkMethod::Key`, and the declared capability and protection matrices from `exec/broker.rs`.
- `offer::OFFER` and `offer::VENUE_OFFER`: what [the coverage page](https://docs.taji.is/reference/coverage/alpaca.md) prints, cell by cell.

### Link forms

The manifest declares `alpaca-paper` and `alpaca-live`. Both are `kind = "fields"` and take `key` and `secret`; the [manifest](https://github.com/TajiAI/Taji/blob/main/plugins/alpaca/taji-plugin.toml) holds their steps. `link::Auth::check` runs in three steps:

1. **Validate.** One `GET /v2/stocks/SPY/trades/latest` on the data host. A 401 or 403 is `invalid_key`, the only place a bad key is concluded; any other failure is `unreachable`.
2. **Probe the SIP tier.** `link::sip_tier` dials `v2/sip`, authenticates and subscribes `trades: ["SPY"]`. A 409 at auth or subscribe is `basic`. An ack naming SPY, or a trade, is `atp`. Anything else is no tier.
3. **Read the account.** `GET /v2/account` on the env's trading host gives the `account_number`, which the row stores hashed.

`bind` (`venue.rs`) reads that account again and refuses a key that reaches another one.

### Surfaces

| Taji surface | Vendor call | File |
|---|---|---|
| `GET /get/bars`, chart history | `StockBars` (`feed=sip`, else `boats` for the 24h night), `optionBars`, `CryptoBars`; 10,000 a page, 100 symbols a request | `lib.rs` |
| Live bars on `/ws/market` | equity `trades` folded by `AlpacaBarAggregator` and `updatedBars`; crypto `bars`; overnight `trades` | `live.rs`, `aggregator.rs`, `forming.rs` |
| `GET /get/trades`, `GET /get/quotes` (span) | `StockTrades`/`StockQuotes` on `sip`; `OptionTrades`; `CryptoTrades`/`CryptoQuotes` | `lib.rs`, `reads.rs` |
| `GET /get/quotes` (now), quote legs, the forming day | `StockSnapshots`/`StockSnapshotSingle` (`sip`, else `delayed_sip`), `OptionSnapshots` (`opra`, else `indicative`), `CryptoSnapshots` | `reads.rs`, `source.rs` |
| Live trades, quotes, status, depth | stream `trades`, `quotes`, `statuses`, `lulds`; crypto `orderbooks` | `live.rs`, `source.rs` |
| `GET /get/depth` (now) | `CryptoLatestOrderbooks` | `reads.rs` |
| `GET /get/chains` | `get-options-contracts` then `OptionChain`; a past day from contracts and bars | `source.rs` `chains_raw` |
| `GET /get/search`, `instrument`, `details` | `/v2/assets`, held for a day; `/v2/assets/{symbol}`; `/v2/options/contracts/{symbol}` | `source.rs` |
| `GET /get/news`, `screener`, `statistics`, `corporate_actions` | `News`; `Movers`, `MostActives`; `StockAuctions`, then the option volumes (below); `CorporateActions` | `reads.rs`, `corporate_actions.rs`, `source.rs` `statistics_raw` |
| `POST /verb/trading/orders/<class>/place`, draft `place` | `POST /v2/orders` | `exec/broker.rs`, `exec/orders.rs` |
| `…/orders/<id>/reprice`, `…/cancel` | `PATCH /v2/orders/{id}`; `DELETE /v2/orders/{id}` | `exec/broker.rs` |
| `GET /read/trading/<acct>/account` | `/v2/account`, `/v2/positions` | `exec/http.rs` |
| `GET /read/trading/<acct>/orders`, `fills` | `GET /v2/orders`, `account/activities/FILL` | `exec/broker.rs`, `exec/http.rs` |
| The reconcile's wake | `trade_updates` | `exec/ws.rs`, `venue.rs` |
| `GET /read/link/rate_limits` | the budgets' state, no call | `ratelimit.rs` |
| `POST /verb/link/venue/redetect` | the SIP-tier probe | `link.rs` |

### A read, end to end

You ask `GET /get/bars?symbols=equity:AAPL&…`.

1. The wire layer hands the read to `Hub::get` (`engine/crates/taji-trading/src/hub/get.rs`), which answers from the store where it holds the span.
2. On a miss, the hub pulls through the client `Source::history` returned, calling `get_bars_session_raw` or `get_bars_many_raw` (`engine/crates/taji-trading/src/hub.rs`).
3. `AlpacaClient` (`lib.rs`) clips a Basic key's `end` to now − 960 s and builds `GET /v2/stocks/bars?symbols=AAPL&timeframe=1Min&…&limit=10000&feed=sip&adjustment=split,spin-off`.
4. `ratelimit::send` admits the request on the data budget and sends it once through the login, whose egress swaps the key markers in. The reply's `X-RateLimit-*` folds back into the budget.
5. The client follows `next_page_token` to the last page. The pages are kept as sent (`BARS_FORMAT`), `parse_bars` reads them, and the hub stores and answers Arrow.

### An order, end to end

You send `POST /verb/trading/orders/equity/place`.

1. The trading model (`engine/crates/taji-trading/src/model.rs`) builds an `OrderIntent`. The root's funnel (`engine/crates/taji-trading/src/root.rs`) journals it before any wire call, then calls `ops.place_order`.
2. `AlpacaEquityBroker::place_impl` (`exec/broker.rs`) validates the intent offline. It derives the `client_order_id` `taji-<intent_id>` (`exec/coid.rs`) and translates the body (`exec/orders.rs`). A refused shape never touches the wire.
3. `AlpacaHttpClient::submit_order` (`exec/http.rs`) admits the POST on the trading budget and sends it once.
4. On 200, the broker reads the order's executions and answers an `OrderSnapshot`.
   - **Ambiguous** (a transport failure, 5xx, 408 or 429): for a single order with no `order_class`, the broker looks the `client_order_id` up. If none is found, it sends the identical body once more. A duplicate refusal of that resend is looked up again.
   - **Duplicate** (422 "client_order_id must be unique"): for that same single order, the broker adopts the existing order.
   - **Anything else:** a definitive reject.
5. Later, `trade_updates` (`exec/ws.rs`) hears the fill. The frame journals nothing: it wakes the account's reconcile pass (`spawn_reconcile_driver` in `engine/crates/taji-trading/src/root.rs`), which reads `GET /v2/orders` and `/v2/positions` and books the fill.

## Why it is built this way

- **The consolidated tape or nothing.** REST asks `feed=sip`, and the socket dials `v2/sip`. On a Basic key, the socket's 409 moves the process to `v2/delayed_sip`, and each snapshot read that SIP refuses asks `delayed_sip` instead: 15 minutes late but complete. IEX is never asked because one exchange is incomplete at any price (`lib.rs`, `live.rs`; [README § `data/<product>` reads](https://docs.taji.is/catalog/alpaca.md#behaviour-and-limits)).
- **Taji folds equity bars from trades.** The vendor's bar channel emits about 1 s late. `AlpacaBarAggregator` replicates Alpaca's condition-code rules, so its minutes match REST. Retracted prints (`u: "incorrect" | "canceled"`) must reach it, or volume over-counts by about 0.4% a day (`live.rs` header). A crypto minute is the vendor's `bars`, because a crypto bar folds quote midpoints the trades lack (`forming.rs`).
- **A stock print's `off_exchange` is its exchange `x`.** `D` is FINRA's ADF, which carries the TRFs, so `D` is true and any other exchange false, on the socket and in history; a frame with no `x` and every other class states nothing. A stock print carries no side, so its `aggressor` stays null (Alpaca staff on [the forum](https://forum.alpaca.markets/t/17728), fetched 2026-12-02; `source.rs` `tick_event`, `history_tick`). A crypto print's `aggressor` is its taker side `tks`, `B` buy and `S` sell, else null ([crypto trades](https://docs.alpaca.markets/us/reference/cryptotrades-1), fetched 2026-12-02; `source.rs` `taker`).
- **One socket per key, shared.** A key gets one stream connection. A client that left its socket alive got 406 on every later dial (measured 2026-09-17), so `AlpacaClient`'s `Drop` closes its sockets, and bars and ticks share one refcounted subscription per `(channel, symbol)`.
- **Msgpack both ways.** Text JSON sent on the msgpack socket is refused with `400 invalid syntax`, and the option feed is msgpack only. `rmpv` decodes the Timestamp extension that `serde_json` cannot (`Cargo.toml`, `live.rs`).
- **Crypto data from `us-1`.** Alpaca's own `us` venue barely prints. Orders still execute on `us`, so the chart shows Kraken US's tape while fills come from `us` (`lib.rs` `CRYPTO_PATH`).
- **An idempotent `client_order_id`.** `taji-<intent_id>` is a pure function of the journaled intent. A crash and retry re-derives the same id, and Alpaca refuses a second order under it forever, even after a cancel (README [Order handling](https://docs.taji.is/catalog/alpaca.md#order-handling)). That refusal is what makes a resend after an ambiguous POST safe.
- **REST is the truth; the socket only wakes it.** `trade_updates` frames are dropped, never repaired, when a field is missing. The next REST pass reads the change anyway (`exec/ws.rs`).
- **Fail closed on a venue read.** `orders_since` and `positions` never turn a failed GET into an empty list, because an empty broker snapshot would book a fabricated flattening fill (`exec/broker.rs` header).
- **Endpoints pinned twice.** The paper arm asserts `paper-api` in its URL, and the live arm asserts host equality with `api.alpaca.markets`. Each check runs on the constant before any credential is read and again on the built client (`venue.rs`, `engine/crates/taji-trading/src/arms.rs`).
- **No key in the crate.** It holds a `Login` and writes only markers. The egress layer (`substrate/taji-brokerage/src/egress.rs`) substitutes values toward granted hosts alone ([ADR 0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md)).
- **No vendor shape reaches a client.** Every capability is a hub `DataProduct` or an `ExecutionOps`/`VenueReads` answer ([ADR 0004](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0004-capabilities-through-the-hub.md)). Bars carry Alpaca's stated basis, `split,spin-off` by default ([ADR 0007](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0007-vendor-basis-as-given.md)).
- **A tier is proven, never guessed.** Only a socket answer sets `basic` or `atp`. An inconclusive probe leaves no tier, and the plan falls to the 15-minute floor every key holds (`source::tiered`).
- **A 429 is never retried.** It holds its scope until `X-RateLimit-Reset`, else `Retry-After`, else 2 s (the venue refills about one request in that time). On an order POST, a 429 is an unknown outcome, so it goes to the `client_order_id` lookup rather than a blind resend.

## Constraints and limits

The numbers are the README's, measured: [Request budget](https://docs.taji.is/catalog/alpaca.md#request-budget), [Order handling](https://docs.taji.is/catalog/alpaca.md#order-handling), [Bar basis and feeds](https://docs.taji.is/catalog/alpaca.md#bar-basis-and-feeds), [Corporate actions](https://docs.taji.is/catalog/alpaca.md#corporate-actions) and [Price adjustment](https://docs.taji.is/catalog/alpaca.md#price-adjustment). The coverage page holds the cells. This section is the mechanism.

- **Budgets.** `ratelimit::RateLimits` keeps four scopes per login, shared by every client on that key (the arm's and the hub's):
  - trading, 200 a minute;
  - clock, 1,000 a minute (`/v2/clock`, `/v3/clock`);
  - data, 200 a minute, re-seated from `X-RateLimit-Limit`, so Algo Trader Plus reads its 10,000;
  - bulk, a backfill's own ceiling, whose client waits instead of refusing.

  A request is admitted without waiting: a spent scope refuses at once, and the wire answers 429 `rate_limited` with `rest_after`. Reads retry a timeout, a failed connect, a 5xx or a body fault up to 5 times, re-admitting each attempt. Writes go once. `GET /read/link/rate_limits` shows each scope.
- **Stream caps.** A Basic key's socket holds 30 symbols. A subscribe past the cap is answered 405 with no symbol named, so `live.rs` sends one symbol per control frame and reads the `subscription` echo as the truth. A symbol missing from the echo after a 405 is refused with the limit in words, and it is not asked again until a place frees. The `stream` scope on `rate_limits` counts held symbols against 30 only while one socket carries them all.
- **The SIP clip.** Basic REST history 403s an `end` inside about 16 minutes of now, so `CAP.clip_s` is 960 s for equities and options, and `clipped` (`sip_span` for equities) clips equity quote spans and the statistics read's auction and option legs the same way.
- **Option volume.** An equity's `statistics` read also states `call_volume` and `put_volume`, one row each per closed New York session, stamped at the session date's UTC midnight and known from its close. Alpaca states no underlying total, so `option_volume_raw` lists every contract expiring on or after the span's first day with `GET /v2/options/contracts`, `status=active` and `status=inactive` (expired), and `expiration_date_lte=9999-12-31` because the default stops at the next weekend, then reads their daily bars 100 symbols a call (`AlpacaClient::option_bars_raw`, `GET /v1beta1/options/bars`: `symbols` "max 100", `limit` at most 10,000 data points across symbols, pages followed; [optionbars](https://docs.alpaca.markets/reference/optionbars), [get-options-contracts](https://docs.alpaca.markets/reference/get-options-contracts), fetched 2026-12-04). `option_volume_rows` sums them by side per session. A contract with no bar that day trades none. A session is a row only if some contract has a bar (none: a holiday, or before the vendor's history), its close is by the read's `until` (the clipped end), and no contract whose bars call failed was alive in it (expiring on or after it): never a partial sum. The failed contracts and `until` are the raw's last page. A listing that fails, a budget refusal on a bars call, or every bars call failing fails the read instead.
- **Pages.** A bars page ends near its 10,000th minute whatever `limit` says. Pagination runs across a multi-symbol batch, so bars append per symbol and sort at the end.
- **Sessions.** Equity history serves `extended` and `24h` (SIP plus `boats`, each cut to its feed's hours by `own_hours`). Live overnight (20:00–04:00 ET) dials a second socket: `boats` on Algo Trader Plus, else `overnight`, held 15 minutes past 04:00 for its late trades.
- **Orders.** `exec/orders.rs` refuses any shape × TIF cell `LEGALITY` does not mark sendable, `extended_hours` on anything but a `day` or `gtc` limit, and an auction exec with a non-`day` TIF. An `mleg` combo is `day` only, and SPX posts as `SPXW`. Alpaca refuses an option order above $50,000,000 notional, and the adapter does no chunking. A multi-bracket fans out to one bracket per tranche (`{coid}-{i}`), and if a later member is refused it cancels those already resting.
- **Exercise.** Whole positions only: a partial quantity or `force` is refused unsent.
- **Fees.** `venue::fee` declares $0 equity, and $0.50 per option contract (the index-option fee stands for the whole class). Crypto's fee is booked from `CFEE` activities, not declared ([README § Fees](https://docs.taji.is/catalog/alpaca.md#fees)).
- **Symbology.** Crypto is `BTC/USD`; `BTCUSD` and `BTC-USD` are refused 400 on `us`. Options are OCC symbols. An item Alpaca names no symbol for is `Unsupported` before any call (`spell`).

## Examples

### The link check

`taji-link alpaca-paper`, or `POST /verb/link/venue/link` from the window, runs `Auth::check`. The golden `plugins/alpaca/tests/egress/link.txt` records what it sends against a loopback upstream with the test pair `PK-TEST`/`SK-TEST`:

```text
http GET /v2/stocks/SPY/trades/latest
apca-api-key-id: PK-TEST
apca-api-secret-key: SK-TEST

handshake /v2/sip
content-type: application/msgpack
upgrade: websocket

frame hex:83a6616374696f6ea461757468a36b6579a7504b2d54455354a6736563726574a7534b2d54455354
frame hex:82a6616374696f6ea9737562736372696265a674726164657391a3535059
```

The two frames decode to `{"action":"auth","key":"PK-TEST","secret":"SK-TEST"}` and `{"action":"subscribe","trades":["SPY"]}`. A Basic key's answer at auth is `{"T":"error","code":409,"msg":"insufficient subscription"}`, quoted from a measured session in `plugins/alpaca/src/live.rs`; no raw capture is kept. The kernel then serves the tier on `GET /read/link`. From the wire fixture `engine/crates/taji/tests/fixtures/wire/link-linked.json`:

```json
"venues": {
  "alpaca": { "method": "key", "provider": "alpaca",
              "sealed": { "live": false, "paper": true },
              "source": "env", "tier": "basic" }
}
```

### An order and its answer

The request side is `plugins/alpaca/tests/egress/rest.txt`, from `POST /v2/orders` through `AlpacaHttpClient`:

```text
http POST /v2/orders
apca-api-key-id: PK-TEST
apca-api-secret-key: SK-TEST
content-type: application/json
body {"symbol":"AAPL","qty":"1","side":"buy","type":"limit","time_in_force":"day","client_order_id":"coid-TEST","limit_price":"100.00"}
```

`OPG_FIXTURE` in `plugins/alpaca/src/exec/models.rs` is shaped as a paper answer to an `opg` market buy, trimmed, its ids and times made up:

```json
{"id":"p1","client_order_id":"p2","created_at":"2026-06-30T01:15:00.00000000Z",
 "filled_at":null,"replaced_by":null,"replaces":null,"asset_id":"p3",
 "symbol":"AAPL","asset_class":"us_equity","qty":"1","filled_qty":"0",
 "filled_avg_price":null,"order_class":"","type":"market","side":"buy",
 "position_intent":"buy_to_open","time_in_force":"opg","status":"accepted",
 "extended_hours":false,"legs":null, … ,"expires_at":"2026-06-30T20:00:00Z"}
```

The kernel's answer to the `place` verb has no capture yet. `engine/crates/taji-open/tests/lifecycle_drill.rs` drives the same path on the paper account.

### The fill on `trade_updates`

`plugins/alpaca/tests/egress/trade_updates.txt` records the connect:

```text
handshake /stream
frame {"action":"auth","key":"PK-TEST","secret":"SK-TEST"}
frame {"action":"listen","data":{"streams":["trade_updates"]}}
```

`FILL_FIXTURE` in `plugins/alpaca/src/exec/ws.rs` is shaped as a paper fill frame, trimmed, its ids, times and prices made up:

```json
{"data": {"at": "2026-01-02T15:00:01.000100Z", "event": "fill",
  "event_id": "p4", "execution_id": "p5",
  "order": {"asset_class": "us_equity", "client_order_id": "paper-fill-buy",
    "filled_at": "2026-01-02T15:00:01.000000000Z", "filled_avg_price": "10.50",
    "filled_qty": "1", "id": "p6", "order_type": "market", "qty": "1",
    "side": "buy", "status": "filled", "symbol": "F", "time_in_force": "day", …},
  …}}
```

`exec/ws.rs` reads `data.order` alone. It ignores the per-execution `price` and `qty`, because the order's cumulative `filled_qty` and `filled_avg_price` already carry them.

### Bars and the warm

`plugins/alpaca/tests/egress/data.txt` records one bars read and the warm the source repeats every 60 s:

```text
http GET /v2/stocks/bars?symbols=AAPL&timeframe=1Min&start=2024-01-02T14:30:00Z&end=2024-01-02T15:30:00Z&limit=10000&feed=sip&adjustment=split,spin-off
http GET /v2/stocks/meta/exchanges
http GET /v2/clock
```

The vendor's bars answer has no capture yet. `cargo test -p taji-alpaca --test live -- --ignored --test-threads=1` reads real bars and prints their hour starts, not the bodies.

### A quote, as the kernel serves it

`engine/crates/taji/tests/fixtures/wire/data-quotes.json` is `GET /get/quotes?symbols=equity:SPY` answered from an Alpaca-seated hub. The fixture writer stubs the row, so this shows the kernel's shape, not a vendor capture (columns trimmed):

```text
| symbol | ts                   | provider | delayed | bid      | ask      | last     | last_exchange | market_session |
| SPY    | 2026-10-08T14:29:59Z | alpaca   | false   | 501.24…  | 501.26…  | 501.25…  | V             | regular        |
```

The snapshot request behind it has no capture yet. `plugins/alpaca/tests/snapshots_live.rs` exercises it against the vendor.

## Testing

| What | Command | Needs |
|---|---|---|
| Unit tests: parsers, `LEGALITY`, submit classes, msgpack decode, `trade_updates` on captured frames, URL pins | `cargo test -p taji-alpaca` | nothing |
| Egress goldens (`plugins/alpaca/tests/egress/*.txt`), the redirect never followed, the host grant | `cargo test -p taji-alpaca --test egress` | nothing; a loopback upstream |
| Hour tiers and native grids against the data host | `cargo test -p taji-alpaca --test live -- --ignored --test-threads=1` | `ALPACA_API_KEY`, `ALPACA_API_SECRET`; reads only |
| Calendar, contract and book, corporate actions, snapshots | `ALPACA_API_KEY=… ALPACA_API_SECRET=… cargo test -p taji-alpaca --test calendar_live -- --ignored --nocapture` (likewise `contract_book_live`, `corporate_actions_live`, `snapshots_live`) | a key; reads only |
| Ticks per channel | `TICKS=trades:equity:AAPL cargo test -p taji-alpaca --test ticks_live -- --ignored --nocapture` | a key; reads only |
| Crypto minute on the socket | `cargo test -p taji-alpaca --test crypto_bars_live -- --ignored --nocapture` | a key; 15 minutes by default |
| Single-leg option and crypto shapes | `ALPACA_LIVE_CELLS=crypto_limit_gtc,contracts cargo test -p taji-alpaca --test crypto_option_live -- --ignored --nocapture` | a **paper** key; places and cancels or closes real paper orders; option market cells 09:30–16:00 ET |
| Linked over the wire on the shipped binary | `engine/crates/taji-open/scripts/vendor_live.sh alpaca` | the paper key; rests one limit and cancels it; no key is SKIP |
| Lifecycle, reprice fallback, multi-bracket | `TAJI_STATE_DIR=<dir> cargo test -p taji-open --features paper-drills --test lifecycle_drill -- --nocapture` (and `reprice_fallback_drill`, `bracket_pair_probe` with `--ignored`) | the paper key in that state dir; real paper orders; one at a time, fill-dependent ones in regular hours |

Each live test reads its key by name and never prints it; without the key it prints SKIP. No test here runs against a live account. `live.rs`'s `trades_state_off_exchange_and_aggressor` reads SPY's SIP and BTC/USD's trades through `history_tick` and `print_at` and asserts both values of `off_exchange` and of `aggressor` appear.

## References

All fetched 2026-12-02.

- OpenAPI index (`trading-api.json` 2.0.1, `market-data-api.json` 1.1): https://docs.alpaca.markets/us/openapi
- Authentication: https://docs.alpaca.markets/docs/authentication
- About market data (plans, history limits, rate and socket limits): https://docs.alpaca.markets/docs/about-market-data-api
- Usage limit (Trading API, 200 a minute): https://alpaca.markets/support/usage-limit-api-calls
- Rate limits (Broker API, headers): https://docs.alpaca.markets/docs/rate-limits
- Paper trading: https://docs.alpaca.markets/docs/paper-trading
- Orders at Alpaca: https://docs.alpaca.markets/docs/orders-at-alpaca
- Options trading: https://docs.alpaca.markets/docs/options-trading
- Crypto trading: https://docs.alpaca.markets/docs/crypto-trading
- WebSocket streaming (`trade_updates`): https://docs.alpaca.markets/docs/websocket-streaming
- Streaming market data (error codes, msgpack): https://docs.alpaca.markets/docs/streaming-market-data
- Real-time stock data: https://docs.alpaca.markets/docs/real-time-stock-pricing-data
- Real-time crypto data: https://docs.alpaca.markets/docs/real-time-crypto-pricing-data
- Real-time option data: https://docs.alpaca.markets/docs/real-time-option-data
- Historical stock data: https://docs.alpaca.markets/docs/historical-stock-data-1
- Market data FAQ: https://docs.alpaca.markets/docs/market-data-faq
