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

# Massive: how it works

Massive, formerly Polygon.io, sells US market data by asset class. Taji takes bars, trades, quotes, option chains, reference data, fundamentals, news, Benzinga earnings, screeners and the live WebSocket feeds from it, for equities, options, indexes, dated futures, crypto and forex. The plugin is one crate, `taji-massive`, under `plugins/massive/`. It registers one data source, `massive`, which talks to three hosts: `api.massive.com` for REST, and `socket.massive.com` and `delayed.massive.com` for WebSockets. Massive is data only: the key places no orders and reads no account.

## The vendor

Vendor pages were fetched on 2026-12-02 unless a line gives another date.

### Hosts and environments

- **REST:** `https://api.massive.com`. The OpenAPI document at `https://api.massive.com/openapi` is OpenAPI 3.0.3 with 156 paths and needs no key. It also lists `api.staging.massive.com`, which is internal, and Massive offers no sandbox.
- **WebSockets:** real time on `wss://socket.massive.com/<cluster>`, delayed on `wss://delayed.massive.com/<cluster>` ([WebSocket quickstart](https://massive.com/docs/websocket/quickstart)). Taji dials five clusters: `stocks`, `options`, `indices`, `futures` and `crypto`.
- **Old host:** `api.polygon.io` still answers after the rename. Taji never calls it.
- **No paper or sim:** every key reads production data.

### Auth

- One static API key per account, made on the dashboard's Keys page. It has no OAuth, no expiry and no refresh.
- **REST** takes the key as `?apiKey=` or as `Authorization: Bearer <key>` ([REST quickstart](https://massive.com/docs/rest/quickstart)). The OpenAPI document declares only the query form. Taji sends only the header.
- **WebSocket** auth is a frame sent after `connected`: `{"action":"auth","params":"<key>"}`. The server answers `auth_success` or `auth_failed`. The quickstart shows `auth_success` and does not document `auth_failed`; Taji reads the `auth_failed` status by name.

### API families Taji calls

Every path and parameter comes from the OpenAPI document. These pages document the families:

| Family | Paths | Doc |
|---|---|---|
| Aggregates | `/v2/aggs/ticker/{t}/range/{n}/{span}/{from}/{to}` | [custom bars](https://massive.com/docs/rest/stocks/aggregates/custom-bars) |
| Futures aggregates | `/futures/v1/aggs/{t}` | [futures aggregates](https://massive.com/docs/rest/futures/aggregates) |
| Trades and quotes | `/v3/trades/{t}`, `/v3/quotes/{t}`, `/futures/v1/{trades,quotes}/{t}`, `/v2/last/nbbo/{t}` | [trades](https://massive.com/docs/rest/stocks/trades-quotes/trades) |
| Snapshots | `/v3/snapshot/options/{underlying}[/{contract}]`, `/v3/snapshot`, `/v3/snapshot/indices`, `/futures/v1/snapshot`, `/v2/snapshot/locale/...` | [option chain snapshot](https://massive.com/docs/rest/options/snapshots/option-chain-snapshot) |
| Reference | `/v3/reference/tickers[/{t}]`, `/v3/reference/options/contracts[/{t}]`, `/futures/v1/{contracts,products,market-status}`, `/vX/reference/tickers/{t}/events`, `/vX/reference/ipos`, `/v2/reference/news`, `/v1/marketstatus/now` | [ticker overview](https://massive.com/docs/rest/stocks/tickers/ticker-overview), [futures contracts](https://massive.com/docs/rest/futures/contracts) |
| Stock fundamentals | `/stocks/financials/v1/{income-statements,balance-sheets,cash-flow-statements}`, `/stocks/v1/{dividends,splits,short-interest,short-volume}`, `/stocks/vX/float` | OpenAPI document |
| Benzinga | `/benzinga/v1/earnings` | [earnings](https://massive.com/docs/rest/partners/benzinga/earnings) |
| WebSocket | `AM`/`A` (crypto `XA`/`XAS`), `T`/`XT`, `Q`/`XQ`, `V`, `LULD`, `NOI` | [AM](https://massive.com/docs/websocket/stocks/aggregates-per-minute), [A](https://massive.com/docs/websocket/stocks/aggregates-per-second), [options Q](https://massive.com/docs/websocket/options/quotes), [V](https://massive.com/docs/websocket/indices/value), [LULD](https://massive.com/docs/websocket/stocks/luld) |

These vendor facts shape the code:

- **Aggregates.** `t` is the start of the window in epoch milliseconds. `from` and `to` are inclusive. `limit` defaults to 5,000 and caps at 50,000. Minute bars span pre-market to after-hours, and a minute with no qualifying trade has no bar.
- **Futures aggregates.** These take `resolution` (`1min`, `1hour`, `1session`) and `window_start` filters, either a date or epoch nanoseconds. A session opens the evening before the date it settles on, `session_end_date`. `settlement_price` comes only on session and longer candles. The page names no time zone.
- **Option chain snapshot.** `limit` caps at 250. It carries `implied_volatility`, `open_interest` and greeks of delta, gamma, theta and vega only (no rho); the page says some contracts, "such as options contracts that are deep in the money", return no greeks. Its `last_quote` is only on a plan with quotes and its `last_trade` only on a plan with trades ([option chain snapshot](https://massive.com/docs/rest/options/snapshots/option-chain-snapshot), fetched 2026-12-04). Every figure is the vendor's own, none the kernel's model.
- **Aggregate channels.** `AM` and `A` stamp `s` and `e` in milliseconds.
- **LULD.** The doc says `t` is milliseconds, but its sample is 19 digits long.
- **Option quotes.** The options `Q` channel holds at most 1,000 contracts per connection.

### Accounts and entitlements

Plans are sold per asset class, in Basic, Starter, Developer and Advanced tiers. Crypto and forex are sold together as "Currencies". The README's [Fees and data subscriptions](https://docs.taji.is/catalog/massive.md#fees-and-data-subscriptions) owns the tier table. You cannot ask the API which plan a key holds; the only signals are an answer's status and a socket's auth result. Benzinga earnings need the Benzinga add-on.

Each now-quote endpoint's Plan Access table names its tiers. `/v2/last/nbbo` is Stocks Advanced only ([last quote](https://massive.com/docs/rest/stocks/trades-quotes/last-quote)). The option contract snapshot is Options Starter and up, 15 min late below Advanced ([contract snapshot](https://massive.com/docs/rest/options/snapshots/option-contract-snapshot)). The futures snapshot is Futures Starter and up, 10 min late below Advanced ([contracts snapshot](https://massive.com/docs/rest/futures/snapshots/contracts-snapshot)). The indices snapshot is Indices Starter (15 min late) and Advanced ([indices snapshot](https://massive.com/docs/rest/indices/snapshots/indices-snapshot)). The unified snapshot is Currencies Starter ([unified snapshot](https://massive.com/docs/rest/crypto/snapshots/unified-snapshot)). No Basic tier includes any of them.

### Stated limits

From the [request-limit article](https://massive.com/knowledge-base/article/what-is-the-request-limit-for-massives-restful-apis):

- Each product's Basic tier allows 5 requests a minute. A paid tier is unlimited for its own product.
- Requests are counted per asset class: stocks, options, indices, currencies and futures.
- Reference and cross-asset endpoints count in a bucket of their own.
- Going over the limit answers 429 "You've exceeded the maximum requests per minute…".

From the [connections article](https://massive.com/knowledge-base/article/how-many-massive-websocket-connections-can-i-use-at-one-time):

- An individual plan gets one WebSocket connection per cluster.
- A second connection closes the older one on `/stocks`, `/futures`, `/indices` and `/forex`.
- On `/options`, the new connection is refused at auth with `max_connections`.

### What Taji does not use

- **Flat files.** They need their own S3 keys (README `### Not read`).
- **Arrow responses.** The REST quickstart describes Arrow bodies paged by a `Link` header. Not yet built: Taji reads JSON.
- **Forex sockets** (`C`, `CA`). Not yet built: `Cluster::of` names no forex cluster, so forex is history only.
- **Duplicate bar and trade reads.** `/v1/summaries`, grouped daily, `/prev`, `/v1/open-close` and the last-trade paths duplicate what bars and trades serve. The `/v2/ticks` and `/v1/historic` paths are deprecated (README `### Not read`).
- **Futures sub-clusters.** Not yet built.
- **Business-plan feeds.** FMV, `LV`, Launchpad and the business feeds are sold only on business plans (README `### Not read`).
- **SEC filing paths** (`/stocks/filings/...`, `/stocks/insiders/...`). The offer declares them, but the EDGAR plugin serves them (`plugins/massive/src/offer.rs`).
- **`apiKey` in a URL.** Never sent (see the next sections).

### Offered, not read

What Taji reads, down to each field it fills, is [`docs/reference/coverage/massive.md`](https://docs.taji.is/reference/coverage/massive.md). What Massive serves past that:

| Offered | Endpoint | Plan | Source, fetched |
|---|---|---|---|
| Options exposure: gamma and delta exposure, call and put open interest, put/call ratio, `call_wall`, `put_wall`, `gamma_flip`; per strike; per expiry with `max_pain` | `GET /options/v1/analytics/underlying`, `/strike`, `/expiration` | Options Advanced and Options Exposure Business, end of day | [underlying](https://massive.com/docs/rest/options/exposure/underlying.md), [strike](https://massive.com/docs/rest/options/exposure/strike.md), [expiration](https://massive.com/docs/rest/options/exposure/expiration.md), 2026-12-04 |
| A contract's end-of-day IV and greeks including `rho`, with `dividend_yield`, `risk_free_rate` and `model` | `GET /options/v1/analytics` | Options Advanced and Historical Options Analytics Business, end of day | [greeks and IV](https://massive.com/docs/rest/options/analytics/greeks-iv.md), 2026-12-04 |
| Open interest history per contract, from 2022-09-01 | `GET /options/v1/open-interest` | Options Advanced and Historical Options Analytics Business, end of day | [by contract](https://massive.com/docs/rest/options/analytics/open-interest-by-contract.md), 2026-12-04 |
| Unusual option trades, flagged `block_premium`, `block_size` or `iso` | `GET /options/v1/unusual-trades` | Options Advanced and Real-time Unusual Options Trades Business | [unusual trades](https://massive.com/docs/rest/options/unusual-options-activity/unusual-trades.md), 2026-12-04 |
| A contract snapshot's `last_quote` sizes, `midpoint` and exchanges, its `last_trade` size, exchange and conditions, its `day` bar but for `volume`, `break_even_price` and `underlying_asset`: a now quote reads the bid, the ask and the last price, and a chain row holds no size, day-bar or breakeven column | `GET /v3/snapshot/options/{underlying}[/{contract}]` | Options Starter and up, 15 min late below Advanced; quote fields need a plan with quotes, trade fields one with trades; `fmv` Business only | [option chain snapshot](https://massive.com/docs/rest/options/snapshots/option-chain-snapshot.md), 2026-12-04 |
| A print's and a quote's numeric exchange ids (`exchange`, `trf_id`, `bid_exchange`, `ask_exchange`), `tape`, `correction`, a quote's `conditions` and `indicators`: no `trades` or `quotes` column holds them, and the id-to-name table is not read (`off_exchange` reads two ids) | `GET /v3/trades/{t}`, `/v3/quotes/{t}`, `/v3/reference/exchanges`, `/stocks/v1/exchanges` | trades Stocks Developer and up (15 min late below Advanced), quotes Stocks Advanced | [trades](https://massive.com/docs/rest/stocks/trades-quotes/trades.md), [quotes](https://massive.com/docs/rest/stocks/trades-quotes/quotes.md), 2026-12-04 |
| A coin print's side: the `XT` frame's `c` is "0 or empty for none, 1 for sell side, 2 for buy side"; Taji keeps the codes in `conditions` and leaves `aggressor` null | WS `XT` on `crypto` | Currencies Starter, real time | [crypto trades](https://massive.com/docs/websocket/crypto/trades.md), 2026-12-04 |
| The crypto full book (L2); the REST path answered 404 on 2026-10-31 and the `XL2` frame has no page | `GET /v2/snapshot/locale/global/markets/crypto/tickers/{ticker}/book`, WS `XL2` | not stated | [OpenAPI](https://api.massive.com/openapi), 2026-12-04 |
| Forex quote history | `GET /v3/quotes/{fxTicker}` | Currencies Starter, real time | [forex quotes](https://massive.com/docs/rest/forex/quotes/quotes.md), 2026-12-04 |
| A live aggregate's transaction count and dollar volume (a future's `AM` `n`, `dv`), and a session aggregate's `dollar_volume`: the live bar fills `vwap` alone and a future's bar no VWAP | WS `AM` on `futures`, `GET /futures/v1/aggs/{t}` | Futures Starter and up (10 min late below Advanced) | [futures AM](https://massive.com/docs/websocket/futures/aggregates-per-minute.md), [OpenAPI](https://api.massive.com/openapi), 2026-12-04 |
| The vendor's own ratios (`price_to_earnings`, `ev_to_ebitda`, `return_on_equity`, `debt_to_equity`, `free_cash_flow`, ...) | `GET /stocks/financials/v1/ratios` | Stocks Advanced or Financials & Ratios Expansion, end of day | [ratios](https://massive.com/docs/rest/stocks/fundamentals/ratios.md), 2026-12-04 |
| A ticker rename's new ticker (`ticker_change`): the read drops it, so no `corporate_actions` row fills `new_symbol` | `GET /vX/reference/tickers/{id}/events` | every Stocks plan (Basic 2 years) | [ticker events](https://massive.com/docs/rest/stocks/corporate-actions/ticker-events.md), 2026-12-04 |
| A dividend's `frequency`, `distribution_type`, `historical_adjustment_factor` and `split_adjusted_cash_amount`; a split's `historical_adjustment_factor` | `GET /stocks/v1/dividends`, `/stocks/v1/splits` | every Stocks plan (Basic 2 years) | [dividends](https://massive.com/docs/rest/stocks/corporate-actions/dividends.md), [splits](https://massive.com/docs/rest/stocks/corporate-actions/splits.md), 2026-12-04 |
| A story's `insights` (per-ticker `sentiment` and `sentiment_reasoning`), `keywords`, `amp_url` and the publisher's logo and favicon | `GET /v2/reference/news` | every Stocks plan (Basic 2 years) | [news](https://massive.com/docs/rest/stocks/news.md), 2026-12-04 |
| A Benzinga report's `importance`, `previous_eps`, `previous_revenue`, `eps_method`, `revenue_method`, `currency` and `notes`; its own surprise figures, which the kernel computes instead | `GET /benzinga/v1/earnings` | Benzinga Earnings add-on | [earnings](https://massive.com/docs/rest/partners/benzinga/earnings.md), 2026-12-04 |
| Benzinga analyst ratings and price targets, consensus ratings, guidance, analyst and firm details, bulls and bears, news | `GET /benzinga/v1/{ratings,consensus-ratings/{ticker},guidance,analysts,firms,bulls-bears-say,analyst-insights}`, `/benzinga/v2/news` | each its own Benzinga add-on | [analyst ratings](https://massive.com/docs/rest/partners/benzinga/analyst-ratings.md), 2026-12-04 |
| Short interest's `avg_daily_volume`; short volume's `total_volume`, `short_volume_ratio`, `exempt_volume` and per-venue figures; float's `free_float_percent` | `GET /stocks/v1/short-interest`, `/stocks/v1/short-volume`, `/stocks/vX/float` | every Stocks plan | [short interest](https://massive.com/docs/rest/stocks/fundamentals/short-interest.md), [short volume](https://massive.com/docs/rest/stocks/fundamentals/short-volume.md), [float](https://massive.com/docs/rest/stocks/fundamentals/float.md), 2026-12-04 |
| An IPO's `announced_date`, `isin`, `us_code`, `lot_size`, `min_shares_offered`, `total_offer_size`, `security_type` and `security_description` | `GET /vX/reference/ipos` | every Stocks plan (Basic 2 years) | [IPOs](https://massive.com/docs/rest/stocks/corporate-actions/ipos.md), 2026-12-04 |
| A ticker overview's street address (`address1`, `address2`, `postal_code`), `phone_number`, `round_lot`, `sic_code`, `share_class_figi`, `share_class_shares_outstanding`, `ticker_root`, `ticker_suffix` and icon; a delisted ticker's `delisted_utc` in `details` and `search` (`instrument` reads it). The crypto and index overview pages state the stocks page's field list | `GET /v3/reference/tickers[/{t}]` | every Stocks, Currencies and Indices plan | [ticker overview](https://massive.com/docs/rest/stocks/tickers/ticker-overview.md), [crypto](https://massive.com/docs/rest/crypto/tickers/ticker-overview.md), [indices](https://massive.com/docs/rest/indices/tickers/ticker-overview.md), 2026-12-04 |
| Futures products' reference (`sector`, `sub_sector`, `asset_class`, `settlement_method`, `unit_of_measure`, ...) and session schedules | `GET /futures/v1/products`, `/futures/v1/schedules` | every Futures plan, updated daily | [products](https://massive.com/docs/rest/futures/products.md), [schedules](https://massive.com/docs/rest/futures/schedules.md), 2026-12-04 |
| Market holidays and early closes | `GET /v1/marketstatus/upcoming` | every Stocks plan | [market holidays](https://massive.com/docs/rest/stocks/market-operations/market-holidays.md), 2026-12-04 |
| Economy series: treasury yields, inflation, inflation expectations, labor market, funding conditions | `GET /fed/v1/{treasury-yields,inflation,inflation-expectations,labor-market,funding-conditions}` | every Stocks, Options, Indices and Currencies plan, updated daily | [treasury yields](https://massive.com/docs/rest/economy/treasury-yields.md), 2026-12-04 |
| Technical indicators (SMA, EMA, MACD, RSI) per class | `GET /v1/indicators/{sma,ema,macd,rsi}/{ticker}` | Stocks: every plan, end of day on Basic | [stocks SMA](https://massive.com/docs/rest/stocks/technical-indicators/simple-moving-average.md), 2026-12-04 |
| ETF Global (analytics, constituents, fund flows, profiles, taxonomies), TMX corporate events, EU consumer spending, related companies | `/etf-global/v1/*`, `/tmx/v1/corporate-events`, `/consumer-spending/eu/v1/*`, `/v1/related-companies/{t}` | partner add-ons; ETF Global's page: "Available to existing subscribers only" | [ETF Global](https://massive.com/docs/rest/partners/etf-global/analytics.md), 2026-12-04 |

## Code map

- `plugins/massive/taji-plugin.toml`: identity, the `[[sources]]` id and the `massive` link form (one secret field, `key`).
- `plugins/massive/Cargo.toml`: depends on `taji-plugin` with `vendor` alone (ADR 0003). Test dependencies pull the hub's test support and the egress harness.
- `plugins/massive/src/lib.rs`: start here. It holds `Plugin`, `MassiveClient` and every REST send: `send` admits each GET on its budget, `authorized` adds the bearer header, and `walk` follows `next_url`. It also holds the bars read (`bars_raw` and `parse_bars`), the tier probe (`probe_class`), symbology (`spell`, `ws_spell`, `vendor_pair`) and the refusal readers (`plan`, `unlisted`).
- `plugins/massive/src/ratelimit.rs`: the per-class GET budgets, shared by every client on one login and host. `class_of` maps a path to its budget, and `rate_limits` feeds the rate-limit read.
- `plugins/massive/src/products.rs`: trades, quote history and quotes now, `option_flow` and its `FlowPages`, the chain snapshot, search, instrument, a future's status and statistics now. The row readers (`search_rows`, `instrument_row`, …) are free functions of the stored pages.
- `plugins/massive/src/reference.rs`: settlements, corporate actions, IPOs, news, fundamentals, Benzinga earnings and screener snapshots, with their row readers.
- `plugins/massive/src/source.rs`: `Massive`, the `Source` the hub holds. It owns the seat (one client and one stream per login), the key check and plan probe (`answers`, `grant`, `verdict`), `read`/`raw_read`/`parse`, the live tick bridge (`open_ticks`) and the error mapping (`error`). The statics `READS`, `CAP` and `FACTS` live here too.
- `plugins/massive/src/live.rs`: `MassiveStream`, one socket per cluster, and its `LiveStream` impl. Read `attach`, `session_loop` and `run` first.
- `plugins/massive/src/offer.rs`: `OFFER`, the vendor's catalogue per class, for the coverage page.
- `plugins/massive/src/live/tests.rs`, `plugins/massive/src/source/raw_tests.rs`, `plugins/massive/src/source/chains_tests.rs`: the socket tests against a fake server, and the store-and-replay tests through a real hub.
- `plugins/massive/tests/egress.rs`: the bytes sent, held as goldens in `plugins/massive/tests/egress/`.
- `plugins/massive/tests/live.rs`: the keyed bars suite, and `option_flow_spy_states_quotes_where_the_plan_does`.
- `plugins/massive/scripts/massive_walk.py`: the keyed walk against a headless kernel.

## How it plugs into Taji

### SDK traits

- **`taji_plugin::Plugin`.** `build` registers `source::Massive::default`.
- **`Source`** (`engine/crates/taji-plugin/src/vendor/mod.rs`), on `Massive`:
  - `seat` builds one `MassiveClient` and one `MassiveStream` over the login the hub admitted.
  - `check` validates a key at link time. `probe` reads the plan at boot and at each unlock.
  - `read` serves the tick spans and the `ratios` fundamentals. `raw_read` and `parse` serve every stored product.
  - `quote` answers a now quote of every class but `future_option` off its snapshot. `quote_legs` fills a spread's chain rows. `forming_day` builds an equity's day so far.
  - `open_ticks` serves live trades, quotes, index values, LULD and NOI.
  - `rate_limits`, `stream_spend` and `hosts` report budgets, stream load and the dialled hosts.
- **`HistoricalData`**, on `MassiveClient`: `get_bars*` and `get_bars_session_raw` read bars. `listed` asks the vendor whether it lists a symbol, and `reach_share` caps how many bar requests one reach sends at once.
- **`LiveStream`**, on `MassiveStream`: `subscribe_bars` (1m only), `unsubscribe` and `stream_status_rx`.

There is no `VenueReads`, `ExecutionOps` or OAuth `Auth`: the seat is `Seat::Key { anew: false }`, so the hub seats the key once per unlock.

### Statics

- **`FACTS`** (`plugins/massive/src/source.rs`):
  - `reads` lists every class × product × span the source answers.
  - `fills` lists the optional columns each class × product fills; the decode tests hold each entry to its decoder (`each_spans_ticks_fill_what_facts_declares` and the mapper tests in `source.rs`). The `ipos` read has no class, so it declares none.
  - `sessions` declares extended-hours equity bars and trades, and extended-hours option bars.
  - `gated` names every class, so a key's plan decides each one. `grants_first` makes a read check its grants before asking, so a refused class is skipped without a GET.
  - `now_only` lists the products answered only as they stand now: search, details, screener, ipos and status.
  - `permits` is `2 * SOCKETS`, 32.
  - `stamps_book` says a chain row's `ts` is when the vendor's quote stood, not when Taji received it.
  - `bars` names `massive.bars.v1` with `parse_bars`.
  - `formats` lists the eleven `massive.<product>.v1` raw formats.
- **`CAP`**, the bars row:
  - every class but `future_option`;
  - `raw` and `split` adjustments (`adjusted=false|true`);
  - `rate_per_min: 5`, which ranks Massive after unmetered providers;
  - the vendor-native intervals (5m and 30m for every class but the index; equity 1h and 4h only on `extended`; crypto every tier; futures and forex 1h);
  - equity depth since 2003-09-10.
- **`OFFER`** (`plugins/massive/src/offer.rs`): what the vendor sells per class, which the [coverage page](https://docs.taji.is/reference/coverage/massive.md) shows as "offered" beside "sent".

There is no `VenueFacts`.

### Link form

The manifest declares one form, `massive`, of kind `fields`, with a single secret field `key`. Its steps and terms are in [`taji-plugin.toml`](https://github.com/TajiAI/Taji/blob/main/plugins/massive/taji-plugin.toml). `POST /verb/link/data/link` blocks on `Source::check` before it seals the key in the vault.

### Surfaces and the call behind each

Each read below is `GET /get/<product>` on the wire (`engine/crates/taji/src/wire/mod.rs`). The [coverage page](https://docs.taji.is/reference/coverage/massive.md) owns which class reaches which product.

| Taji surface | Vendor call | Made in |
|---|---|---|
| `bars`, every class but futures | `/v2/aggs/ticker/{t}/range/{n}/{minute\|hour\|day}/{from_ms}/{to_ms}?sort=asc&limit=50000[&adjusted=]` | `lib.rs` `bars_raw` |
| `bars`, a dated future | `/futures/v1/aggs/{t}?resolution=…&window_start.gte=<ns>&window_start.lt=<ns>` | `lib.rs` `bars_raw` |
| `/ws/market` bars, 1m | WS `AM` + `A` (`XA` + `XAS` for crypto) on the class's cluster | `live.rs` `subscribe_bars`, `run` |
| `trades` span | `/v3/trades/{t}`, `/futures/v1/trades/{t}` | `products.rs` `trades` |
| `quotes` span | `/v3/quotes/{t}`, `/futures/v1/quotes/{t}` | `products.rs` `quotes` |
| `quotes` now, an equity | `/v2/last/nbbo/{t}` | `products.rs` `quote`; `source.rs` `quote` |
| `quotes` now, an option; chain legs | `/v3/snapshot/options/{root}/{contract}` | `products.rs` `quote`; `source.rs` `quote`, `quote_legs` |
| `quotes` now, a future | `/futures/v1/snapshot?ticker=` | `products.rs` `quote`; `source.rs` `quote` |
| `quotes` now, a crypto or forex pair | `/v3/snapshot?ticker.any_of=` | `products.rs` `quote`; `source.rs` `quote` |
| `quotes` now, an index (its value as the last) | `/v3/snapshot/indices?ticker.any_of=` | `products.rs` `quote`; `source.rs` `quote` |
| live `trades`, `quotes`, `status`, `imbalance` | WS `T`/`XT`, `Q`/`XQ`, `V` (index quotes), `LULD`, `NOI` | `live.rs` `subscribe_ticks`; `source.rs` `open_ticks` |
| `option_flow` | `/v3/reference/options/contracts?underlying_ticker=&as_of=` (and `expired=true`), `/v3/trades/{t}` and `/v3/quotes/{t}` per contract | `products.rs` `option_flow`; `source.rs` `read`, `flow_prints` |
| `chains` | `/v3/snapshot/options/{underlying}?limit=250&expiration_date.gte=…` | `products.rs` `option_chain_raw`; `source.rs` `chains_raw` |
| `search` | `/v3/reference/tickers?search=&market=`, `/v3/reference/options/contracts?underlying_ticker=`, `/futures/v1/contracts?product_code=`, then `/futures/v1/products?name=` | `products.rs` `search_raw` |
| `instrument`, `details` | `/v3/reference/tickers/{t}`, `/v3/reference/options/contracts/{t}?as_of=<expiry>`, `/futures/v1/contracts?ticker=` | `products.rs` `instrument_raw` |
| `status`, a future | `/futures/v1/market-status?product_code=` | `products.rs` `status_raw` |
| `statistics` now / range | the contract or futures snapshot / `/futures/v1/aggs/{t}?resolution=1session`, or for an equity `/options/v1/open-interest/underlying` (calls and puts over the whole chain; the `date` is the session the figure is for, so the row sits on it) | `products.rs` `statistics_raw`; `reference.rs` `settlements_raw`, `open_interest_raw` |
| `corporate_actions` | `/stocks/v1/dividends`, `/stocks/v1/splits`, `/vX/reference/tickers/{t}/events` | `reference.rs` `corporate_actions_raw` |
| `news` | `/v2/reference/news` | `reference.rs` `news_raw` |
| `fundamentals` by `kind` | the three statement paths, short interest, short volume, float; `ratios` is the three statements joined | `reference.rs` `fundamentals_raw`; `source.rs` `read` |
| `earnings` | `/benzinga/v1/earnings` | `reference.rs` `earnings_raw` |
| `screener` by `scan` | `/v2/snapshot/locale/us/markets/stocks/{gainers,losers,tickers}`, the crypto equivalents, `/v3/snapshot/indices`, `/futures/v1/snapshot` | `reference.rs` `screener_raw` |
| `ipos` | `/vX/reference/ipos` | `reference.rs` `ipos_raw` |
| an equity's forming day | `/v2/snapshot/locale/us/markets/stocks/tickers/{t}` | `products.rs` `day_snapshot`; `source.rs` `forming_day` |
| the key check and plan probe | one stocks `/v2/aggs/ticker/AAPL/range/1/minute/{day}/{day}?limit=1`, then one auth per socket cluster | `lib.rs` `probe_class`; `source.rs` `answers`; `live.rs` `probe` |
| `GET /read/link/rate_limits` | none: each class's budget state | `ratelimit.rs` `rate_limits` |

A stock `trades` row carries `off_exchange`: true where the print has a `trf_id` (socket `trfi`) or its exchange is 4 (FINRA ADF) or 62 (ORF), the `type: TRF` rows of `/v3/reference/exchanges`, else false; no other class sets it. `aggressor` stays null: the [trades](https://massive.com/docs/rest/stocks/trades-quotes/trades) and socket pages state no side.

The plan the probe learns is the `data` half of `GET /read/link`. It is a per-class tier of `realtime`, `delayed`, `history`, `refused` or `null`, which the hub keeps in `<state dir>/sources/grants.json` (`engine/crates/taji-trading/src/hub/grants.rs`).

### One read, wire to vendor and back

`GET /get/bars?symbols=equity:AAPL&timeframe=D&from=…&to=…` goes through these steps:

1. The hub's fetch path (`engine/crates/taji-trading/src/hub/get.rs`) finds the span missing from the store and ranks providers. Massive's grant for `equity` admits it.
2. The hub calls `get_bars_session_raw`, which runs `session_served` and then `bars_raw`.
3. `bars_raw` cuts the span into windows of up to 50,000 base aggregates and builds each window's `/v2/aggs` URL with `adjusted=false` for `raw`.
4. `walk` sends each page through `send`. `send` admits the GET on the stocks budget (`queue::admit`), and `authorized` adds `Authorization: Bearer` through the login. `walk` follows `next_url` (rebased onto the client's own host, any `apiKey` dropped) for up to 64 pages.
5. Each page is kept as sent, minus any `apiKey`, in a `Raw` of format `massive.bars.v1`, with one `request` entry per GET and no key.
6. The store logs the pull. `parse_bars` turns the pages into `OHLCV`, sorted and deduplicated, and the hub answers Arrow rows naming `provider: massive`.

A refusal comes back as a `BrokerageError`, and `source.rs` `error` maps it to the hub's words (see [Constraints and limits](#constraints-and-limits)).

### One live subscription

A `/ws/market` bars subscription for `equity:AAPL` at 1m goes through these steps:

1. The hub calls `MassiveStream::subscribe_bars`, and `attach` adds a fan-out under the stream's one lock.
2. If the `stocks` socket does not exist yet, `attach` spawns `session_loop`, which dials `socket.massive.com/stocks` through the login, waits for `connected`, sends the auth frame and expects `auth_success`.
3. `run` sends `subscribe` `AM.AAPL,A.AAPL`. From then on, each `A` second folds into the forming minute, and each `AM` closes it.
4. If the real-time host refuses the key, bar fan-outs lapse and the session moves on to `delayed.massive.com` for ticks alone.
5. A drop redials with backoff from 1 s up to 30 s and resubscribes everything still held. Nothing replays the minutes missed while down, so history fills them.

### `option_flow`

`GET /get/option_flow` and `data.product` for an `equity:` or `index:` underlying are answered by this source, an hour at most, each print with the quote standing at it. `MassiveClient::option_flow` reads the pages and `flow_prints` in `source.rs` turns them into `OptionPrint`s:
- **It fans out because no read answers a whole underlying.** `/v3/trades` and `/v3/quotes` take one contract, and the flat files are end of day only (README `### Not read`). So the read lists the contracts and asks each.
- **The contracts are those of the span's day.** `/v3/reference/options/contracts?underlying_ticker=&as_of=<New York date of from>&limit=1000`, every page. When that date is before today in New York, a second walk adds `expired=true`; the lists are unioned by `ticker`, keeping `expiration_date >= as_of`. Whether `expired=true` adds to the live list or replaces it is unmeasured; the union is right either way, and `option_flow_spy_states_quotes_where_the_plan_does` is the check (README [Open](https://docs.taji.is/catalog/massive.md#open)). A listed ticker that is no OCC contract is dropped and counted in one warning.
- **Trades are read in parallel, bounded.** One `trades` call per contract, at most `FLOW_CALLS` (16) in flight, each admitted on its class's budget by `send`. SPY lists thousands of contracts for one day, so one read is thousands of requests, all inside the one `cx.call` the hub times. The plan pages list "Unlimited API Calls" on Options Starter, Developer and Advanced ([options pricing](https://massive.com/options), fetched 2026-12-03), so the count does not bound the read; its wall time does, unmeasured until the live test runs.
- **Quotes are read for printed contracts only.** A contract that did not print in the span gets no quotes call. A printed one gets its `quotes` over the span, plus a seed (`/v3/quotes/{t}?timestamp.lt=<from ns>&order=desc&sort=timestamp&limit=1`) when its first print precedes its first quote, so a print at the span's open has a standing quote.
- **The join is as of the print.** Each print takes the last quote of its contract at or before its `sip_timestamp`; a quote at the print's exact stamp stands at it, and a print before any quote has no `bid` or `ask`. `multiplier` is the contract's `shares_per_contract`, null where absent. `conditions` are Massive's numeric ids, which the kernel's OPRA-letter exclusion never matches, so no print is left unclassed for being multi-leg or late (README [Open](https://docs.taji.is/catalog/massive.md#open)). The plugin states no side: the kernel classes it from the `bid`, `ask` and the contract's tape, and a mid print goes to the tick rule, `side_by` saying which.
- **A clamp cuts every list at one second.** Each trades or quotes list stops at `TICK_PAGES` pages and is `clamped`. When any is, every print at or after the earliest clamped list's last whole second is dropped and the answer is `clamped`, so the hub's next page re-reads from there and no print is joined to a truncated quote list.
- **A 429 surfaces.** Any trades or contracts error fails the read, a 429 as `RateLimited` with the vendor's wait; none is swallowed or retried. A trades plan refusal is `PlanRefused`, and the hub's walk passes to the next provider.
- **A plan without quotes still answers.** A 403 plan refusal on any quotes call stops the later ones and leaves `FlowPages.quotes` `None`, so every print has no `bid` or `ask` and the kernel classes each by the contract's tick rule (`side_by` `tick`). Any other quotes error fails the read. Quotes need Options Advanced, trades Developer (README [Fees and data subscriptions](https://docs.taji.is/catalog/massive.md#fees-and-data-subscriptions)).
- **It is unmetered.** With Massive linked the hub's tie order answers from it. `POST /fetch` refuses `option_flow`.

## Why it is built this way

- **The key travels only in a header or an auth frame.**
  - ADR [0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md) keeps keys out of clients, logs and stored bodies, and a key in a query string ends up in all three.
  - Massive's own `next_url` can carry `apiKey`. `rebase` drops it before following, and `without_key` rewrites the stored body.
  - `plugins/massive/src/source/raw_tests.rs` asserts that no stored body or request holds the key, `bearer` or `authorization`.
- **Budgets start unlimited and drop to 5 a minute only on evidence.** No answer names the plan. A class is held to Basic's 5 a minute after its first 429, or once both of its sockets refuse the key, since every paid plan streams (`plugins/massive/src/ratelimit.rs`). Every client on one login shares one set, so the probe and the reads draw on the same budget.
- **A 429 is sent once and never retried.** A read holds the hub's store while it waits, so `send` answers `RateLimited` at once, holds the class for `Retry-After` (else 60 s) and leaves the retry to the hub.
- **The probe spends one GET.** A Basic key has 5 GETs a minute per class, and probing six classes over REST would spend them in one link. So the probe makes one stocks GET (every plan serves stocks history) and then one auth per socket cluster, which costs no GET. A socket that takes the key marks a paid class. Refusals on both hosts mark Basic, granted two years of history. Forex has no socket, so its first read learns its plan.
- **One stream per login, one socket per cluster.** An individual plan holds one connection per cluster, and a second one kills the first or is refused. So `MassiveStream` multiplexes every channel and symbol on one socket, the probe goes through the open socket, and `Massive::check` hands its stream to the next seat rather than opening another.
- **Bars stream only in real time.** A delayed key's bar subscription lapses rather than arriving 15 minutes late. Its ticks still flow from `delayed.massive.com`, marked `delayed`.
- **`AM` closes the minute.** A consumer's closed bar is the vendor's own minute aggregate, never Taji's fold of seconds. The next minute's forming bar waits up to 5 s (`AM_GRACE`) for the last `AM`.
- **A plan's refusal falls through to the next provider.** A 403 `NOT_AUTHORIZED` about a data timeframe is `NoSource`, so another provider answers the depth. Any other `NOT_AUTHORIZED` is `PlanRefused`. A ticker Massive does not list (`404 NOT_FOUND` on the one-ticker read) is `NotListed`.
- **A now quote is gated like every other read.** `READS` declares the now quote of each class the vendor sells one for, and the class's grant admits the ask. A plan without the endpoint answers 403 `NOT_AUTHORIZED`, which is `PlanRefused`. The hub then keeps that class's quotes refused, so it is not asked again until a relink. A snapshot row's own `error` (`NOT_FOUND`, `NOT_ENTITLED`) refuses that ticker alone, as `NoSource`.
- **No vendor shape reaches a client** (ADR [0004](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0004-capabilities-through-the-hub.md)). Every product is parsed into the hub's rows, and the raw pages stay in the store so an open replays them without the vendor (`engine/crates/taji-trading/src/hub/raw.rs`).
- **The basis is as given** (ADR [0007](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0007-vendor-basis-as-given.md)). Equity, option and currency bars send `adjusted=false` or `adjusted=true` as asked. Index and futures bars carry no basis, so neither word is sent.
- **Native intervals only where the vendor's grid matches Taji's.** 5m and 30m equal the fold of 1m on every class measured (README `### Measured`, 2026-10-31). An index's plan refuses them. Massive counts hour bars from New York midnight, so only the tiers that land on Taji's grid are asked; the rest fold from 1m (measured 2026-11-07).
- **Futures daily asks begin a day early.** A session opens the evening before the date it settles on, so `bars_raw` sets `window_start.gte` to `from` − 1 day. `future_bar` then keys each session to its `session_end_date`.

## Constraints and limits

- **Rate budgets.** There are six: stocks, options, indices, currencies (crypto and forex), futures and reference. `class_of` routes each path to one. `reach_share` sends one bar request at a time on a class held to Basic, and 16 otherwise. The measured ceiling and the 429 behaviour are the README's [Transport and limits](https://docs.taji.is/catalog/massive.md#transport-and-limits).
- **Read size.** One bars read is at most 64 windows (`WINDOWS`). A window is 30 days of minutes, 365 days of hours or 10 years of days. One paged read follows at most 64 pages (`PAGES`). Past either cap, Taji refuses the read before any GET. Each GET times out after 30 s.
- **Stream load.** The `stream` row counts the distinct symbols on the key's sockets. Its quota is the options socket's 1,000 contracts, shown only while every symbol carried is an option.
- **Entitlements.** Each class's grant comes from the probe. A delayed class's grant still serves bars as history. Depth, the plan windows and the per-tier tables are owned by the README's [Fees and data subscriptions](https://docs.taji.is/catalog/massive.md#fees-and-data-subscriptions) and [Data](https://docs.taji.is/catalog/massive.md#data).
- **Symbology.**
  - An equity is bare, an option is `O:` plus its OCC contract, an index is `I:SPX`, crypto is `X:BTCUSD` (`BTC-USD` on the socket) and forex is `C:EURUSD`.
  - A dated future carries one year digit: `MNQZ26` is sent as `MNQZ6`.
  - A continuous future is `NoContinuous`, because Massive lists contracts alone. Future options are refused.
- **Refusals.**

  | Answer | Taji's word |
  |---|---|
  | 401 or 403 | `Refused` |
  | 403 `NOT_AUTHORIZED` | `NoSource` (a data timeframe) or `PlanRefused` (anything else) |
  | 429 | `RateLimited`, with the vendor's wait |
  | 404 `NOT_FOUND` on a one-ticker read | `NotListed` |
  | any other status | `Provider`, with the vendor's own sentence (`words`) |
  | `auth_failed` on both hosts | `PlanRefused` for tick consumers |

## Examples

Every vendor exchange below runs against a loopback fake, not Massive. No recorded vendor capture exists yet: the plugin has no `tests/fixtures/` directory. The `products` and `reference` phases of `plugins/massive/scripts/massive_walk.py` reach the vendor, and the store keeps each raw answer on its pull, masked of the key; a capture would be taken from there.

**What a read sends.** These are from `plugins/massive/tests/egress/rest.txt`, written by `plugins/massive/tests/egress.rs` `rest`, with the test key masked `p1`. The second answer's `next_url` ends `?cursor=p2&apiKey=leak`, and the third request shows the key dropped:

```
http GET /v3/snapshot/options/SPY/O:SPY251219C00650000
accept: */*
accept-encoding: gzip
authorization: Bearer p1

http GET /v3/trades/AAPL?timestamp.gte=1704205800000000000&timestamp.lt=1704205860000000000&limit=50000&order=asc&sort=timestamp
accept: */*
accept-encoding: gzip
authorization: Bearer p1

http GET /v3/trades/AAPL?cursor=p2
…
```

**What the probe's socket sends.** This is `plugins/massive/tests/egress/socket.txt`, with the key masked. The fake answers `connected` and then `auth_success`, so `probe(Cluster::Stocks)` reads `Realtime`:

```
handshake /stocks
connection: Upgrade
sec-websocket-version: 13
upgrade: websocket

frame {"action":"auth","params":"p1"}
```

**A plan's refusal.** From `plugins/massive/src/lib.rs` `a_403_is_refused_and_the_plans_refusal_named`:

- A 1m bars GET answered `403 {"status": "NOT_AUTHORIZED", "message": "Your plan doesn't include this data timeframe."}` is the plan's refusal. `source.rs` `error` turns it into `NoSource("massive: Your plan doesn't include this data timeframe.")`, so the next provider is asked.
- A 403 `{"status": "ERROR", "message": "Unknown API Key"}` is a plain `Refused`.

**A live minute.** From `plugins/massive/src/live/tests.rs` `seconds_fold_into_one_forming_minute_and_the_minute_closes_it`. After `subscribe` `AM.AAPL,A.AAPL`, the socket sends:

```json
[{"ev": "A", "sym": "AAPL", "o": 1.0, "h": 2.0, "l": 0.5, "c": 1.5, "v": 10, "s": 1790947801000, "e": 1790947802000},
 {"ev": "A", "sym": "AAPL", "o": 1.5, "h": 3.0, "l": 1.0, "c": 2.0, "v": 5, "s": 1790947802000, "e": 1790947803000},
 {"ev": "AM", "sym": "AAPL", "o": 1.0, "h": 3.0, "l": 0.5, "c": 2.0, "v": 15, "s": 1790947800000, "e": 1790947860000},
 {"ev": "A", "sym": "AAPL", "o": 2.5, "h": 2.5, "l": 2.5, "c": 2.5, "v": 1, "s": 1790947860000, "e": 1790947861000}]
```

The consumer receives four bars, each written as (start, [o, h, l, c, v], closed):

- the forming minute `(1790947800, [1, 2, 0.5, 1.5, 10], false)`;
- the forming minute `(1790947800, [1, 3, 0.5, 2, 15], false)`;
- the vendor's closed minute `(1790947800, [1, 3, 0.5, 2, 15], true)`;
- the next forming minute `(1790947860, [2.5, 2.5, 2.5, 2.5, 1], false)`.

**A Taji call and the kernel's answer.** This example comes from the wire fixture. `engine/crates/taji/src/wire/fixture.rs` `reference_answer` seeds Massive's income-statement rows as the source's answer:

```json
{"provider": "massive", "rows": [
  {"kind": "income", "tickers": ["SPY"], "timeframe": "quarterly", "period_end": "2025-03-31",
   "filing_date": "2025-04-30", "fiscal_year": 2025, "fiscal_quarter": 1,
   "revenue": 800000, "cost_of_revenue": 500000}, …]}
```

`GET /get/fundamentals?symbols=equity:SPY&kind=income&at=1780272000` answers Arrow. `engine/crates/taji/tests/fixtures/wire/data-fundamentals.json`, trimmed:

```
| symbol | knowable_utc | kind   | period    | period_end_date | line            | value              | growth_pct | provider |
| SPY    | 1746072000   | income | quarterly | 2025-03-31      | revenue         | 800000.0000000000  |            | massive  |
| SPY    | 1746072000   | income | quarterly | 2025-03-31      | cost_of_revenue | -500000.0000000000 |            | massive  |
| SPY    | 1777608000   | income | quarterly | 2026-03-31      | revenue         | 1000000.0000000000 | 25.00…     | massive  |
…
```

The kernel turns a cost negative, makes each line knowable the day after filing, computes growth, and cuts the quarter filed after `at`.

## Testing

- **Offline.** `cargo test -p taji-massive` needs no key and no network. It runs:
  - the unit tests in each module against `wiremock`;
  - the socket tests against a fake server;
  - the store-and-replay tests through a real hub (`plugins/massive/src/source/raw_tests.rs`, `plugins/massive/src/source/chains_tests.rs`);
  - the egress goldens.

  When the bytes sent change on purpose, rewrite the goldens with `EGRESS_RECORD=1 cargo test -p taji-massive --test egress` and review the diff.
- **Live bars suite.** `cargo test -p taji-massive --test live -- --ignored --test-threads=1 [filter]` runs against `api.massive.com` with your key in `MASSIVE_API_KEY`, read from the environment or the file `substrate/taji-live/src/env.rs` names. Without the key, each test prints SKIP. Each test waits 13 s, so the suite stays under Basic's 5 a minute. It only reads.
- **Every vendor at once.** `engine/crates/taji-open/scripts/vendor_live.sh massive` runs the `massive` leg of `engine/crates/taji-open/tests/vendor_live.rs`. It links the key on a headless kernel and reads `bars`, `search` and `corporate_actions`.
- **The keyed walk.** `plugins/massive/scripts/massive_walk.py <port> link|live|history|products|reference|cleanup` runs against a headless kernel you start with your own `TAJI_STATE_DIR` (the AGENTS.md headless line). It needs `MASSIVE_API_KEY`. It paces itself to 5 vendor GETs a minute and prints numbered PASS/FAIL lines. The `live` phase needs market hours and a plan with a live tier.
- **No paper or sim.** Massive is data only, so no test places an order.

## References

- REST quickstart: https://massive.com/docs/rest/quickstart (fetched 2026-12-02)
- OpenAPI: https://api.massive.com/openapi (fetched 2026-12-04)
- Custom bars: https://massive.com/docs/rest/stocks/aggregates/custom-bars (fetched 2026-12-02)
- Futures aggregates: https://massive.com/docs/rest/futures/aggregates (fetched 2026-12-02)
- Trades: https://massive.com/docs/rest/stocks/trades-quotes/trades (fetched 2026-12-04)
- Option chain snapshot: https://massive.com/docs/rest/options/snapshots/option-chain-snapshot (fetched 2026-12-04)
- Option contract snapshot: https://massive.com/docs/rest/options/snapshots/option-contract-snapshot (fetched 2026-12-04)
- Last quote: https://massive.com/docs/rest/stocks/trades-quotes/last-quote (fetched 2026-12-04)
- Futures contracts snapshot: https://massive.com/docs/rest/futures/snapshots/contracts-snapshot (fetched 2026-12-04)
- Indices snapshot: https://massive.com/docs/rest/indices/snapshots/indices-snapshot (fetched 2026-12-04)
- Unified snapshot: https://massive.com/docs/rest/crypto/snapshots/unified-snapshot (fetched 2026-12-04)
- Ticker overview: https://massive.com/docs/rest/stocks/tickers/ticker-overview (fetched 2026-12-04)
- Futures contracts: https://massive.com/docs/rest/futures/contracts (fetched 2026-12-04)
- Benzinga earnings: https://massive.com/docs/rest/partners/benzinga/earnings (fetched 2026-12-04)
- WebSocket quickstart: https://massive.com/docs/websocket/quickstart (fetched 2026-12-02)
- Aggregates per minute: https://massive.com/docs/websocket/stocks/aggregates-per-minute (fetched 2026-12-02)
- Aggregates per second: https://massive.com/docs/websocket/stocks/aggregates-per-second (fetched 2026-12-02)
- Options quotes: https://massive.com/docs/websocket/options/quotes (fetched 2026-12-04)
- Index value: https://massive.com/docs/websocket/indices/value (fetched 2026-12-02)
- LULD: https://massive.com/docs/websocket/stocks/luld (fetched 2026-12-02)
- Request limits: https://massive.com/knowledge-base/article/what-is-the-request-limit-for-massives-restful-apis (fetched 2026-12-02)
- WebSocket connections: https://massive.com/knowledge-base/article/how-many-massive-websocket-connections-can-i-use-at-one-time (fetched 2026-12-02)
- Pricing: https://massive.com/pricing (fetched 2026-12-02; tiers render client-side, so the README's table, fetched 2026-10-20, stays the owner)
