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

# TradeStation: how it works

TradeStation is a US broker whose WebAPI serves market data and trades stocks, options and futures. Taji takes both halves from it: bars, quotes, depth, chains, symbol details and search for seven instrument classes, and the account's money, positions, position groups and orders on a practice (SIM) and a funded host. It is one compiled-in Rust crate, `taji-tradestation`, holding a data source, a venue arm and a link, over three hosts: `signin.tradestation.com` for tokens, `api.tradestation.com` for all market data and funded accounts, and `sim-api.tradestation.com` for practice accounts. What a person links and what was measured are on the [plugin page](https://docs.taji.is/catalog/tradestation.md).

## The vendor

**Hosts and environments.** Live is `https://api.tradestation.com/v3`, SIM is `https://sim-api.tradestation.com/v3`: SIM is "identical to the Live API in all ways except" that its accounts hold fake money and its orders fill by simulation ([SIM vs. LIVE](https://api.tradestation.com/docs/fundamentals/sim-vs-live), fetched 2026-12-02). The vendor's page does not say whether one token serves both hosts; Taji's link lists both hosts' accounts with one sign-in, and one record serves both (`link.rs`, `venue.rs` `FACTS`).

**Auth.** Auth0 OAuth: the authorization-code flow at `https://signin.tradestation.com/authorize` with `audience=https://api.tradestation.com`, then `POST https://signin.tradestation.com/oauth/token` ([Auth Code Flow](https://api.tradestation.com/docs/fundamentals/authentication/auth-code), fetched 2026-12-02). PKCE is offered for single-page and native apps on request ([Authentication](https://api.tradestation.com/docs/fundamentals/authentication/auth-overview), fetched 2026-12-02). An access token lives 20 minutes (`expires_in: 1200`). A refresh token is non-expiring by default; on request it rotates and then lives 24 hours at most. The overview page says such tokens rotate every 40 minutes and the refresh page says every 30 ([Refresh Tokens](https://api.tradestation.com/docs/fundamentals/authentication/refresh-tokens), fetched 2026-12-02). A refresh sends `client_secret` on the standard flow. `offline_access` is required for a refresh token, and `openid` always. The scopes are `MarketData`, `ReadAccount`, `Trade`, `OptionSpreads` (the options endpoints) and `Matrix` (market depth) ([Scopes](https://api.tradestation.com/docs/fundamentals/authentication/scopes), fetched 2026-12-02).

**Keys and accounts.** A key is issued by Client Experience by email to a person with a funded account ([FAQ](https://api.tradestation.com/docs/faq), fetched 2026-12-02); the manifest's link steps say how. `GET /v3/brokerage/accounts` lists the user's accounts on the host asked, each with an `AccountType` (`Cash`, `Margin`, `Futures`, …) and an `AccountDetail.OptionApprovalLevel`; futures are kept in their own accounts (`venue.rs` `Split`). Real-time data is a subscription per exchange ([Data subscriptions](https://docs.taji.is/catalog/tradestation.md#data-subscriptions)); the API docs do not describe entitlements, so Taji measures them at bind (`probe_tier`, below).

**API families Taji calls.** v3 is current; v2 "remains available until its services are upgraded" ([Getting Started](https://api.tradestation.com/docs/), fetched 2026-12-02). Every path is in the vendor's OpenAPI document (45 operations, downloaded 2026-12-01 from [Specification](https://api.tradestation.com/docs/specification)).

| Family | Endpoints Taji calls |
|---|---|
| MarketData v3 | `barcharts/{symbol}`, `stream/barcharts/{symbol}`, `quotes/{symbols}`, `stream/quotes/{symbols}`, `symbols/{symbols}`, `symbollists/cryptopairs/symbolnames`, `options/expirations/{u}`, `options/strikes/{u}`, `stream/options/chains/{u}`, `stream/options/quotes`, `stream/marketdepth/aggregates/{symbol}` |
| MarketData v2 | `data/symbols/search/{criteria}`, `data/symbols/suggest/{text}`, `stream/tickbars/{symbol}/1/1`, `data/symbollists/` (undocumented) |
| Brokerage v3 | `brokerage/accounts`, `accounts/{a}/balances`, `/positions`, `/orders`, `/orders/{ids}`, `/historicalorders`, `stream/accounts/{a}/orders`, `/positions`, `/positiongroups`, `positiongroups/groups` (and `/split`, `/merge`) |
| Order Execution v3 | `orders` (POST, PUT and DELETE `{id}`), `ordergroups`, `orderconfirm`, `ordergroupconfirm`, `routes` |

**Streams** are HTTP/1.1 chunked responses of newline-delimited JSON, `Content-Type: application/vnd.tradestation.streams.v2+json` (orders and positions: `…v3+json`). Chunks are not message boundaries. A v3 stream sends `{"StreamStatus":"EndSnapshot"}` after its snapshot and `{"StreamStatus":"GoAway"}` before the server ends it, and an error frame such as `{"Symbol":"AAPL","Error":"DualLogon"}` ends it ([HTTP Streaming](https://api.tradestation.com/docs/fundamentals/http-streaming), fetched 2026-12-02). Fields may be null or absent ([HTTP Requests](https://api.tradestation.com/docs/fundamentals/http-requests), fetched 2026-12-02).

**Stated limits.** Quotas are per user and per key, over rolling windows that refill continuously; a breach is `429` with `{"Error":"TooManyRequests","Message":"Rate quota exceeded"}` or `"Stream quota exceeded"`. Replies carry `X-RateLimit-{Limit,Period,Remaining,Reset,Resource}` and, on streams, `X-Concurrency-{Limit,Remaining,Resource}` ([Rate Limiting](https://api.tradestation.com/docs/fundamentals/rate-limiting/rate-limiting-overview), fetched 2026-12-02). Minute bars also spend 200 history credits a user a minute; a request costs `barsback × interval / 100,000` or `(days + 1) / 365` credits, free at 0.25 or less; at most 57,600 bars an intraday request ([Historical Bar Data Limits](https://api.tradestation.com/docs/fundamentals/rate-limiting/historical-bar), fetched 2026-12-02). Taji's copy of the tables is `ratelimit.rs` `seed` and `cap_of`.

**Position groups** read an options account's positions as strategies of 2 to 4 legs, options and shares alike (a covered call's shares are a leg): `grouptype` `orderbased` (the order id names the group), `marginbased` (the margin system's pairs, with margin estimates) or `custom` (the user's, edited by create, update, delete, split and merge); identical groups auto-merge; the docs say futures accounts refuse the endpoints ([Position Groups](https://api.tradestation.com/docs/features/complex-options-positions-api), fetched 2026-12-02), but the SIM futures account answered the end-of-snapshot marker alone (`the_marker_alone_reads_empty`).

**Option figures are the vendor's own model.** A chain or option-quote frame's greeks, `ImpliedVolatility`, `TheoreticalValue` and probabilities come from Bjerksund and Stensland pricing off the option's ask and the underlying's 90-day historical volatility ([`GetOptionChain`, `GetOptionQuotes`](https://api.tradestation.com/docs/specification), fetched 2026-12-04). The opt-in header `x-ts-feature-options-pricing: true` on those two streams routes to a newer engine (live dividend yields and schedules, refined greeks, a smoothed IV surface) whose greeks, IV, theoretical values and probabilities differ. Taji sends no header, so every figure it serves off TradeStation (`iv`, `delta` … `rho`, `theo`, `std_dev`, `p_*`) is the legacy engine's (`quotes.rs` `chain_stream_url`, `spread_stream_url`). Figures ride the streams alone: a chain read's rows (`options/expirations`, `options/strikes`, `quotes/`) state a book, last, volume and open interest, and no figure.

**What Taji does not use, and why.**

- `bodbalances`: no Taji product carries a day-start equity.
- `activationtriggers`: the trigger keys are fixed in `offer.rs`.
- `options/spreadname`: the kernel names spreads itself (`presets::recognize`).
- `orders` and `historicalorders` `status`/`symbol` filters: the read-back asks a 10-minute window, so a filter saves nothing measured.
- Plus durations (`DYP`, `GCP`, `GDP`) on an option, which the vendor documents for extended-hours options ([Extended Hours Options](https://api.tradestation.com/docs/fundamentals/extended-hours-options), fetched 2026-12-02): SIM accepts the preview and refuses the order, so the crate refuses an option's non-regular session until a live-host order is walked.
- `positiongroups/mode` and the `orderbased` and `marginbased` group types: Taji edits only `custom` groups, the type the write endpoints apply to.
- `stream/accounts/{a}/positions?changes=true`: its frames are partial objects, and a missing `Quantity` would read as flat (`brokerage_stream.rs`).
- `stream/accounts/{a}/orders/{ids}`: the account-wide stream already wakes the refresh pass for every order.
- `options/riskreward` and `options/spreadtypes`: `riskreward.rs` builds and decodes them for `TsOptionsBroker::preview_order`, but the arm sends every preview to the equity adapter (`venue.rs` `Split`), so no kernel path reaches them.
- The rest of v2: deprecated, and v3 serves it.

### Offered, not read

What Taji reads, down to each field it fills, is [TradeStation coverage](https://docs.taji.is/reference/coverage/tradestation.md). What TradeStation serves past that, every row from the vendor's OpenAPI document ([Specification](https://api.tradestation.com/docs/specification), operation ids named, fetched 2026-12-04) except where a recording is cited. The docs state no plan per field: real-time data is a subscription per exchange ([Data subscriptions](https://docs.taji.is/catalog/tradestation.md#data-subscriptions)).

| Offered | Endpoint | Plan | Source, fetched |
|---|---|---|---|
| The new options pricing engine: live dividend yields and schedules, refined greeks, a smoothed IV surface; its greeks, IV, theoretical values and probabilities differ from the legacy engine's | `stream/options/chains/{underlying}`, `stream/options/quotes` with header `x-ts-feature-options-pricing: true` | opt-in per request | `GetOptionChain`, `GetOptionQuotes`, 2026-12-04 |
| A chain's other spread types, `expiration2`, `strikeInterval`, `strikeRange` (`ITM`, `OTM`), `riskFreeRate` (default `$IRX.X`) and `enableGreeks`: Taji sends `expiration`, `optionType`, `priceCenter` and `strikeProximity` | `stream/options/chains/{underlying}` | OPRA subscription | `GetOptionChain`, 2026-12-04 |
| A chain frame's `AskSize`, `BidSize`, `IntrinsicValue`, `ExtrinsicValue`, `TheoreticalValue_IV`, `Open`, `High`, `Low`, `Close`, `PreviousClose`, `NetChange` and `NetChangePct`: `chains` holds no size, session or intrinsic column | same | OPRA subscription | `GetOptionChain`, 2026-12-04 |
| A quote's `LastVenue` (so `last_exchange` stays null), session `Open`, `High`, `Low`, `Close`, `Volume`, `PreviousClose`, `PreviousVolume`, `NetChange`, `NetChangePct`, `TickSizeTier`, `Restrictions` and `MarketFlags.IsBats`: no `quotes` column holds them (an equity's `Open`, `High`, `Low` and `Volume` feed its forming day, `LastSize` its print) | `quotes/{symbols}`, `stream/quotes/{symbols}` | per exchange | `GetQuoteSnapshots`, `GetQuoteChangeStream`, 2026-12-04 |
| A quote's `FirstNoticeDate`, `LastTradingDate` (futures) and `MarketFlags.IsHardToBorrow`: the `instrument` columns `first_notice_date`, `last_trade_utc` and `easy_to_borrow` stay null, as `symbols/` states none | same | per exchange | `GetQuoteSnapshots`, 2026-12-04; `LastTradingDate` recorded on an option quote ([Examples](#examples)) |
| Forex quotes: `quotes/EURUSD` answers a real bid and ask (SIM and live, 2026-10-31, `offer.rs`); `READS` has no forex `quotes` | same | per exchange | `GetQuoteSnapshots`, 2026-12-04 |
| A bar's `OpenInterest` (options and futures), `UpTicks`, `DownTicks`, `Epoch`; no `bars` column holds them. `unit=Weekly` and `Monthly`: Taji asks `Minute` and `Daily` | `barcharts/{symbol}`, `stream/barcharts/{symbol}` | per exchange | `GetBars`, `StreamBars`, 2026-12-04 |
| The depth book per participant (`Name`, `Size`, `OrderCount`, `TimeStamp`), and an aggregate level's `EarliestTime`, `BiggestSize`, `SmallestSize`, `NumParticipants`; `maxlevels` (default 20) is not sent. Stocks, futures and stock options | `stream/marketdepth/quotes/{symbol}`, `stream/marketdepth/aggregates/{symbol}` | `Matrix` scope, depth subscription (equity 401 not entitled on this login, 2026-12-02) | `StreamMarketDepthQuotes`, `StreamMarketDepthAggregates`, 2026-12-04 |
| A symbol's `FutureType` and `PriceFormat.SubFraction`, and a `Country` other than `United States` (`details.country` is `US` or null): no column holds them | `symbols/{symbols}` | none stated | `GetSymbolDetails`, 2026-12-04 |
| A v2 search row's `Country`, `Currency`, `DisplayType`, `ExchangeID`, `ExpirationType` (`W`, `M`, `Q`, `E`), `FutureType`, `MinMove`, `OptionType`, `PointValue`, `Root` and `StrikePrice`: `search` carries a name, class, exchange, underlying and expiry alone | `v2/data/symbols/search/{criteria}`, `suggest/{text}` | none stated | `searchSymbols`, `suggestsymbols`, 2026-12-04 |

## Code map

Start at `src/lib.rs`, the crate's map and the four vendor behaviours it absorbs.

| File | Owns |
|---|---|
| `taji-plugin.toml` | Identity, `[[sources]]`, the `tradestation-sim` link form, its steps and fields. |
| `src/lib.rs` | `Plugin` (registers the source, the arm and the auth), the three hosts, `spell` (a Taji item to a vendor symbol), the per-endpoint batch caps. |
| `src/link.rs` | `Auth`: the OAuth sign-in it declares (`sign_in`), `check`: a refresh, then both hosts' account listings; `again`: a refresh, then the Paper host's. |
| `src/auth.rs` | `TokenStore`: refresh-token mints shared by every client of one sign-in, renewal 5 minutes early, the mint's retry budget; `limits` and `rate_limits`. |
| `src/http.rs` | `TsClient`, where every API request leaves (the token mint and the link's account listing send through the kernel's login client instead): host and v3 guards, `get_with_auth_retry` (401 and 5xx), one-shot `post_json`/`put_json`/`delete_json`, rate accounting, `WARM_EVERY`. |
| `src/ratelimit.rs` | `RateLimits`: per-sign-in budgets seeded from the published table and learned from `x-ratelimit-*`, bar credits, stream caps; `op` names each request's budget. |
| `src/error.rs` | `TsError`; `is_recoverable` decides redial or stop. |
| `src/v2.rs` | `V2_PREFIXES`, the four allowed v2 paths, and their URL builders. |
| `src/stamp.rs` | Close-stamp to open-stamp, both directions; `daily_session_date`. |
| `src/bars.rs` | `GetBars` (the `barcharts` request), bar decode, `credits`. |
| `src/hist.rs` | `TsBars`: `HistoricalData` over `barcharts`; timeframes, session templates, month chunks, `parse_bars`. |
| `src/stream.rs` | `FrameReader`: whole frames across chunks; `Frame::Control`. |
| `src/barstream.rs` | The bar stream driver: replay against live on `IsRealtime`, final on `BarStatus: Closed`. |
| `src/livestream.rs` | `TsBarStream`: `LiveStream` over `stream/barcharts`. |
| `src/reconnect.rs` | `Reconnector` (redial policy, read deadline) and `GapTracker`. |
| `src/fold.rs` | Quote deltas folded into whole books. |
| `src/quotes.rs` | Quote snapshot and stream URLs and decode (`IsDelayed` refused), option expiration, strike, chain, spread and depth URLs. |
| `src/symbols.rs` | `symbols/{symbols}` details, 50 a request. |
| `src/occ.rs` | An option contract or an OCC-21 string to the vendor's `ROOT YYMMDDC123.5`. |
| `src/source.rs` | `TradeStation`, the `Source`: `FACTS`, the seat, every read, `probe_tier`, the quote groups and the depth, chain and spread relays. |
| `src/offer.rs` | `OFFER` and `VENUE_OFFER`: what the vendor's spec offers, for coverage. |
| `src/venue.rs` | `FACTS` (`VenueFacts`), `Arm` (`bind`, `arm`), `Split`, the account-stream wakes, fees. |
| `src/venue_reads.rs` | `TsVenueReads`: money, routes, multiplier, groups, no clock. |
| `src/balances.rs` | `fetch_money` off `balances`. |
| `src/orders.rs` | Order wire types, `STATUS_TABLE`, paging, the positions decode, the read-back matcher. |
| `src/equity_broker.rs` | `TsEquityBroker`: equity orders, single-leg options, brackets, OTO, OCO, preview, replace, cancel, regroup. |
| `src/options_broker.rs` | `TsOptionsBroker`: multi-leg option orders. |
| `src/futures_broker.rs` | `TsFuturesBroker`: futures orders, two placement budgets, duplicate-refusal adoption. |
| `src/brokerage_stream.rs` | Order, position and position-group streams; `SnapshotPhase`. |
| `src/groups.rs` | Position groups: `read_groups` and `regroup`. |
| `src/riskreward.rs` | The `riskreward` and `spreadtypes` bodies. |
| `tests/` | `egress.rs` (bytes sent, offline), `no_v2.rs`, `auth_retry_is_get_only.rs` (source scans), `live.rs`, `sim_orders.rs`, `auth_retry_live.rs` (keyed), `common/` (the keyed login), `fixtures/`. |
| `examples/ts_parity_probe.rs` | SIM calls the kernel cannot make: crypto bars, a raw `/orders` body, a bracket placed outside Taji. |
| `plugins/tradestation/scripts/tradestation_walk.py` | The walk through a running kernel, phase by phase. |

## How it plugs into Taji

`Plugin::build` registers three things (`lib.rs`), and `engine/crates/taji-open/src/lib.rs` adds the plugin to the kernel.

- **The source**, `source::TradeStation`, implements `Source` (`engine/crates/taji-plugin/src/vendor/mod.rs`). Its `FACTS` (`plugin::Facts`) declares the reads per class (`READS`), the extended sessions, `gated` classes, the depth scope, the bars cap (`CAP`: intervals, first-read sizes, native tiers), the raw formats the store keeps and their parsers, and `OFFER`. `seat` builds the read client and the bar stream (`TsBarStream`, a `LiveStream`) off the stored sign-in; `history` builds `TsBars`, a `HistoricalData` (`substrate/taji-brokerage/src/traits/`).
- **The arm**, `venue::Arm`, implements `VenueArm` (`engine/crates/taji-plugin/src/vendor/venue.rs`). Its `FACTS` (`VenueFacts`) names one record for both envs, the fee table, the adapters' declared capabilities and protection, the sign-in hosts, the link facts (OAuth, refresh given, plan by class) and `VENUE_OFFER`. `bind` resolves the row's account number from the host's listing (the number is never on disk, only its hash), probes the data plan, and builds one arm per account: a `Futures` account trades through `TsFuturesBroker` alone (`ExecutionOps`, `FuturesOps`); a `Cash` or `Margin` account through `Split`, which sends a spread to `TsOptionsBroker` and everything else, previews, replaces, cancels and regroups included, to `TsEquityBroker`. Each arm carries `TsVenueReads` (`VenueReads`) and a wake channel off the account's order and position streams. Other account types are not armed.
- **The link**, `link::Auth`, implements `Auth`. The one form, `tradestation-sim`, takes the key and secret, then opens the browser sign-in that `sign_in` declares: authorization code with PKCE and the secret in the form, the scopes above with `OptionSpreads` and `Matrix` asked up front, the callback `http://localhost:31022`. `check` refreshes where it holds no live access token, then lists both hosts: SIM accounts become paper rows, funded ones live rows; a user with no funded account is no failed sign-in.

Every client of one sign-in, the hub's and each arm's, shares one `TokenStore` turn and one `RateLimits` (`auth.rs` `shared`). The token is held as a marker the login substitutes toward a granted host (`substrate/taji-brokerage/src/egress.rs`), so the crate never holds its value ([ADR 0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md)).

| Taji surface | Vendor call | File |
|---|---|---|
| `GET /get/bars`, history | `GET /v3/marketdata/barcharts/{symbol}` | `hist.rs`, `bars.rs`, `stamp.rs` |
| Live bars (`/ws/market`, the chart) | `GET /v3/marketdata/stream/barcharts/{symbol}` | `livestream.rs`, `barstream.rs`, `reconnect.rs` |
| `GET /get/quotes` now, `GET /get/statistics`, a forming day | `GET /v3/marketdata/quotes/{symbols}` | `source.rs`, `quotes.rs` |
| Live `quotes` | `GET /v3/marketdata/stream/quotes/{symbols}`, up to 100 symbols a connection | `source.rs`, `fold.rs` |
| Live `depth` | `GET /v3/marketdata/stream/marketdepth/aggregates/{symbol}` | `source.rs` `depth_rows` |
| Live `trades`, equity and future | `GET /v2/stream/tickbars/{symbol}/1/1` | `source.rs`, `v2.rs` |
| `GET /get/chains` | the underlying's quote, `options/expirations`, `options/strikes`, the legs' `quotes`; a future option's, v2 search `C=FO` | `source.rs` |
| Live chains | `GET /v3/marketdata/stream/options/chains/{underlying}`: `expiration`, `optionType` from `right`, and with a strike bound `priceCenter` (the bounds' midpoint) and `strikeProximity` 50, rows outside the bounds dropped (`TickAsk::narrows`); unbounded, the vendor's 5 strikes either side of the last price | `source.rs` `chain_row`, `quotes.rs` `chain_stream_url` |
| A `spread:` item's quotes, a leg set's greeks | `GET /v3/marketdata/stream/options/quotes` | `source.rs` `open_spread`, `quote_legs` |
| `GET /get/instrument`, `details` | `GET /v3/marketdata/symbols/{symbols}`; a root's contracts after a v2 search | `source.rs`, `symbols.rs` |
| `GET /get/search` | v2 search, suggest and symbol lists; the crypto pair list | `source.rs`, `v2.rs` |
| `GET /read/trading/<acct>/account`, the venue's money | `GET /v3/brokerage/accounts/{a}/balances` | `venue_reads.rs`, `balances.rs` |
| The refresh pass: positions, orders, fills | `/positions`, `/orders`, `/historicalorders?since=`, `/orders/{ids}` | `equity_broker.rs`, `futures_broker.rs`, `orders.rs` |
| `GET /read/trading/<acct>/groups` | `GET /v3/brokerage/stream/accounts/{a}/positiongroups?grouptype=custom`, to its snapshot | `groups.rs`, `venue_reads.rs` |
| `POST /verb/trading/<acct>/groups/{create,update,split,merge}` (`ExecutionOps::regroup`) | `POST`/`PUT`/`DELETE /v3/brokerage/positiongroups/groups`, `/split`, `/merge` | `groups.rs` |
| `POST /verb/trading/orders/<class>/place` | `POST /v3/orderexecution/orders` or `ordergroups` | `equity_broker.rs`, `options_broker.rs`, `futures_broker.rs` |
| `…/preview` | `POST /v3/orderexecution/orderconfirm` or `ordergroupconfirm` | `equity_broker.rs` |
| `POST /verb/trading/<acct>/orders/<id>/reprice` | `PUT /v3/orderexecution/orders/{id}` | the three brokers |
| `POST /verb/trading/<acct>/orders/<id>/cancel` | `DELETE /v3/orderexecution/orders/{id}` | the three brokers |
| Reconcile wakes | `GET /v3/brokerage/stream/accounts/{a}/orders`, `/positions` | `venue.rs` `brokerage_wakes` |
| Linking `tradestation-sim` | `signin.tradestation.com` `authorize` and `oauth/token`; `GET /v3/brokerage/accounts` on both hosts | `link.rs`, `venue.rs` |
| `GET /read/link/rate_limits` | none: the budgets `ratelimit.rs` holds | `auth.rs` `rate_limits` |
| `GET /read/data/coverage` | none: `FACTS`, `OFFER`, `VenueFacts` | `source.rs`, `offer.rs`, `venue.rs` |

Each route's full contract is its row in the `//!` header of `engine/crates/taji/src/wire/mod.rs`; what the provider serves, cell by cell, is [its coverage page](https://docs.taji.is/reference/coverage/tradestation.md).

**One read, a bar history.** `GET /get/bars?symbols=equity:AAPL&provider=tradestation` reaches the hub (`engine/crates/taji-trading/src/hub/`), which answers from its store and fetches only the missing pieces. For a piece it calls `TsBars` (`hist.rs`), which picks the session template, splits the span by month and builds each `GetBars` URL (`bars.rs`) with its bounds moved from Taji's open-stamps to the vendor's close-stamps (`stamp.rs`). `TsClient::get_bytes` (`http.rs`) checks the URL is a v3 path on `api.tradestation.com`, takes the token (minting if it is within 5 minutes of expiry), admits the request against its budget and the bar credits (`ratelimit.rs`), sends it through the login, folds the reply's headers back into the budgets, and on a 401 refreshes and sends again (a bulk backfill's client, `with_transient_retry`, also resends a 5xx). The answer's `{"Bars":[…]}` pages are stored raw under `tradestation.bars.v1`; `hist::parse_bars` re-stamps each bar to its open and cuts the session, and the kernel answers Arrow.

**One order, a SPY limit buy on a margin account.** `POST /verb/trading/orders/equity/place` reaches the trading model (`engine/crates/taji-trading/`), whose account writer gates the intent, journals it before the wire and calls `place_order` on the bound arm (`substrate/stadium/src/actor.rs`). `Split` sends it to `TsEquityBroker`, whose `order_body` builds the body with an `OrderConfirmID` derived from the intent id (`orders::order_confirm_id`). `post_json` checks the URL is under `/v3/orderexecution/` on the row's host (`sim-api` for a paper row), admits it, and sends `POST /v3/orderexecution/orders` exactly once. A 200 can still be a refusal (`Orders[0].Error`, `orders::placement_rejection`); otherwise `Orders[0].OrderID` is the ack. A transport failure after the bytes left reads the account's orders back and adopts the one matching symbol, action and quantity, else answers acked-unconfirmed. Fills and terminal states are the refresh pass's: the order and position streams wake it, and it reads `/orders` and `/positions`.

## Why it is built this way

- **No vendor shape leaves the crate** ([ADR 0004](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0004-capabilities-through-the-hub.md)). Bars cross as open-stamped `OHLCV`, quotes as `Pair`s, orders as `OrderSnapshot`s; a second provider fills the same products and traits.
- **Market data always comes from the live host.** A practice account is an account fact and market data is not account data (`hist.rs`), so only orders and account reads follow a row's env; `assert_ts_env` pins a paper row to `sim-api` and a live row to `api` at bind.
- **One sign-in, one token turn, one budget set.** The vendor's quotas are per user and key, so every client off a sign-in charges the same `RateLimits`, and a burst of clients mints once (`auth.rs`).
- **Renew 5 minutes early.** A token that dies between send and receipt earns a 401 nobody caused; the margin is cheap (`auth.rs`).
- **GETs retry, writes never.** A GET is idempotent, so a 401 refreshes and resends (3 sends at most) and, on a bulk client, a 5xx backs off and resends; a POST, PUT or DELETE goes once, because a resend of a landed order is a second order (`http.rs`, `tests/auth_retry_is_get_only.rs`).
- **`OrderConfirmID` is a dedupe key, never echoed.** SIM refuses a same-id resend and names the original order, so the key is a pure function of the intent id; no order row echoes it, so an uncertain placement is resolved by a read-back on attributes, and a futures duplicate refusal adopts the original order (`futures_broker.rs`).
- **Budgets are learned, not configured.** Each reply names its resource and window in `x-ratelimit-*`; until one has, the published table seeds a provisional budget. A request the budget refuses is never sent.
- **Streams are framed by newline, classified by flags, and watched by a deadline.** Frames span chunks (4 of 543 in a capture), every connect replays history, and a half-open socket is silent for minutes; each is a module (`stream.rs`, `barstream.rs`, `reconnect.rs`), and a redial after data is normal, not a fault.
- **Account streams wake, reads decide.** A frame journals nothing: it wakes the reconcile pass, which reads `/orders` and `/positions` (`venue.rs`). The snapshot marker is a type (`SnapshotPhase`), so "flat" and "not yet arrived" cannot be confused.
- **Fail closed on the money path.** A delayed quote is refused, not served as live (`quotes.rs`); an unknown order status is `UnrecognizedValue`; a field Taji reads that goes missing fails the decode, while an added field is tolerated (`bars.rs`, `orders.rs`).
- **v3, plus four v2 paths.** Symbol search, suggest, tick bars and symbol lists have no v3 counterpart; `tests/no_v2.rs` and `TsClient::guard_v3` keep every other v2 path out.
- **The data plan is measured at bind.** Entitlements are per exchange and per user, so `probe_tier` quotes AAPL, `$SPX.X`, `@ES` and a near SPY call and seats each class real-time, delayed or refused.
- **Position groups are the venue's.** `TsVenueReads::groups` answers `Some`, so the kernel stores none for these accounts and reads the vendor's `custom` groups.
- **A listed order group is one snapshot.** `/orders` lists a bracket's, OCO's or OSO's members as rows; the listing folds each into its head's snapshot as a leg with its role, id, state, price (stop, else limit), limit (a stop-limit's) and tranche (its `BRK`/`OCO` pair's rank by lowest id). A multi-leg option row states its legs and signed net in `Asked`, or none where it cannot spell them, and each leg's open or close from its `OpenOrClose`; a one-leg option row states it as `Asked.effect` (`equity_broker.rs`).
- **Two option adapters, futures alone.** A multi-leg POST has its own body and read-back, measured apart; the vendor keeps futures in their own accounts, so a futures row has no equity adapter.

## Constraints and limits

- **Rate budgets.** `ratelimit::op` maps each URL to an op; the op charges its learned resource, or a provisional budget seeded by `seed`, and minute bars also charge the bar credits (`bars::credits`). A refusal before the send is `TsError::RateLimited`, which the wire answers 429 `rate_limited` with `rest_after`. A 429 naming its resource holds that budget until the server's reset; a bare 429 holds the op's budget 60 s. A placement's 429 is answered as a vendor error, because it does not prove the order did not land. The spend per sign-in is `GET /read/link/rate_limits`. Measured semantics: [Rate limit and error semantics](https://docs.taji.is/catalog/tradestation.md#rate-limit-and-error-semantics).
- **Stream caps.** Depth, option quote and option chain streams take a concurrency slot (`cap_of`), refused locally when full; a spread whose slot is gone is composed from its legs by the hub instead. `x-concurrency-limit` replaces the published size when a reply states it.
- **Batch caps.** `quotes/` and `stream/quotes/` 100 symbols, `symbols/` 50, account streams 25 accounts; `enforce_batch_cap` refuses before the send.
- **Idle connections.** Both API hosts close an idle connection at about two minutes, so each arm and read client is warmed every 90 s (`WARM_EVERY`).
- **Bars.** Six timeframes (`1m`, `5m`, `30m`, `1h`, `4h`, `D`); any other refuses rather than serving a neighbour. `1h` and `4h` are served only where the vendor's session grid is Taji's. Measured: [OHLCV — daily and 1-minute](https://docs.taji.is/catalog/tradestation.md#ohlcv--daily-and-1-minute).
- **Option sessions.** An option's extended bars ask `USOptPreAndPost`. Measured on SIM, 1m, 2026-11-24 to 12-02 (ET): `SPXW 261203C7475` 525 bars to 16:59, 16 after 16:15 (Cboe's Curb, 16:15–17:00), against 509 to 16:15 under `Default`; no bar before 09:31 on eight SPXW and SPX contracts, so Cboe's GTH (20:15–09:25) is not served. Expiring `SPY 261201` and `QQQ 261201` series printed to 16:15 on their last day, and expiring `SPXW 261201` ended at 16:00. So an index option's extended view runs from its 09:30 open to the Curb's 17:00, and any other option's from 07:30 to 16:15 (`calendar::option_extended`).
- **Symbology.** `spell` and `occ.rs` map Taji items to the vendor's spellings: some index roots only as `$ROOT.X` (`DOT_X_INDEXES`), pairs without `/`, options `ROOT YYMMDDC123.5`. Measured: [Symbology](https://docs.taji.is/catalog/tradestation.md#symbology), [Contract list](https://docs.taji.is/catalog/tradestation.md#contract-list), [Continuous series](https://docs.taji.is/catalog/tradestation.md#continuous-series).
- **Orders.** What SIM refused and accepted, by shape and session: [Orders](https://docs.taji.is/catalog/tradestation.md#orders) and [Options](https://docs.taji.is/catalog/tradestation.md#options). No adapter declares a future option or an option outside the regular session, so Taji refuses both before the send. Order history reaches back 730 days (`VENDOR_MAX_LOOKBACK_DAYS`); the crate asks 729.
- **Entitlements.** A class the probe found refused or delayed is seated so; an unentitled stream is refused by the vendor, as AAPL depth was (401) on the measured login: [Rate limit and error semantics](https://docs.taji.is/catalog/tradestation.md#rate-limit-and-error-semantics), [Data subscriptions](https://docs.taji.is/catalog/tradestation.md#data-subscriptions).
- **Sign-in.** The callback must be the bare origin `http://localhost:31022`: [Sign-in redirect](https://docs.taji.is/catalog/tradestation.md#sign-in-redirect).

## Examples

**The kernel's coverage row, from the statics alone.** `GET /read/data/coverage` renders the crate's `FACTS`, `CAP` and `OFFER` for an unlinked TradeStation (`engine/crates/taji/tests/fixtures/wire/data-coverage.json`, the `data` row for `future`, trimmed):

```json
{"provider": "tradestation", "class": "future", "linked": false, "serves": true,
 "intervals": ["1m", "5m", "30m", "1h", "4h", "D"], "rate_per_min": 100, "cost": "free",
 "reads": {"history": ["bars", "instrument", "search", "details", "statistics"],
           "live": ["bars", "quotes", "depth", "trades"], "realtime": ["quotes"], "more": []},
 "offered_data": {"history": ["bars", "instrument", "statistics"],
                  "live": ["bars", "quotes", "depth", "trades"], "as_of": "2026-10-31",
                  "source": "api.tradestation.com/docs/specification/ (v3 OpenAPI)"},
 "measured": "plugins/tradestation/README.md", "grant": null}
```

`reads` is what Taji sends (`READS`, `WORDS`); `offered_data` is what the vendor's spec offers (`offer.rs`); `grant` stays `null` until a bind's `probe_tier` seats the plan.

**A quote snapshot.** The answer to `GET https://api.tradestation.com/v3/marketdata/quotes/AAPL 261202C307.5`, the request `Source::quotes_now` and `Source::quote` make (`tests/live.rs` `a_fractional_strike_quotes_spelled_with_its_decimal`), shaped as the live host's, its figures made up:

```json
{"Quotes":[{"Ask":"2.6","AskSize":"20","Bid":"2.4","BidSize":"10","Close":"2.5",
 "DailyOpenInterest":"100","High":"2.6","High52Week":"0","Last":"2.5","LastSize":"1",
 "LastTradingDate":"2026-12-01T23:59:59Z","LastVenue":"CBOE","Low":"2.4","Low52Week":"0",
 "MarketFlags":{"IsBats":false,"IsDelayed":false,"IsHalted":false,"IsHardToBorrow":false},
 "NetChange":"0.1","NetChangePct":"4.1667","Open":"2.4","PreviousClose":"2.4",
 "PreviousVolume":"200","Restrictions":[],"Symbol":"AAPL 261202C307.5","TickSizeTier":"0",
 "TradeTime":"2026-12-02T17:47:34Z","VWAP":"0","Volume":"10"}]}
```

Numbers are strings, the strike keeps its decimal, and `MarketFlags.IsDelayed` is `false`, so `decode_quotes_response` resolves it; `true`, or no `MarketFlags`, and the symbol is refused.

**A leg's stream frame.** `GET /v3/marketdata/stream/options/quotes` with one leg `AAPL 261202C345` and greeks enabled, the stream behind a `spread:` item and a chain's legs (same test file, `single_leg_spread_stream_carries_greeks`), a frame shaped as the live host's, its figures made up:

```json
{"Ask":"2.6","AskSize":20,"Bid":"2.4","BidSize":10,"Close":"2.5","DailyOpenInterest":1000,
 "Delta":"0.5","ExtrinsicValue":"0.1","Gamma":"0.05","High":"2.6",
 "ImpliedVolatility":"0.25","IntrinsicValue":"2.4","Last":"2.5",
 "Legs":[{"AssetType":"StockOption","Expiration":"2026-12-02T00:00:00Z","OptionType":"Call",
          "Ratio":1,"StrikePrice":"345","Symbol":"AAPL 261202C345"}],
 "Low":"2.4","Mid":"2.5","NetChange":"0.05","NetChangePct":"0.02","Open":"2.4",
 "PreviousClose":"2.45","ProbabilityBE":"0.5","ProbabilityBE_IV":"0.5",
 "ProbabilityITM":"0.5","ProbabilityITM_IV":"0.5","ProbabilityOTM":"0.5","ProbabilityOTM_IV":"0.5",
 "Rho":"0.01","Side":"Call","Strikes":["345"],"TheoreticalValue":"2.5",
 "TheoreticalValue_IV":"2.5","Theta":"-0.25","Vega":"0.05","Volume":1000}
```

Sizes are numbers here and strings on `quotes/`, which is why `bars.rs` and `quotes.rs` accept both. This frame, on the expiry day, carries no `StandardDeviation`, and the test failed on that assertion.

**A depth book.** `stream/marketdepth/aggregates/MNQZ26` on SIM streamed 10 levels a side, bids falling and asks rising (`tests/live.rs` `a_futures_book_streams_aggregated_levels`, 2026-12-02 18:01Z). `depth_rows` turns each level into one `depth` row, level 0 the best price, stamped at its `LatestTime`.

**A position group read.** `GET /read/trading/<acct>/groups` calls `TsVenueReads::groups`, which dials `GET /v3/brokerage/stream/accounts/<ACCT>/positiongroups?grouptype=custom`, reads to the snapshot marker and hangs up. SIM answered one frame and the marker (`tests/fixtures/positiongroups/custom_vertical.ndjson`, shaped as SIM's 2026-12-02 answer, its figures made up; the eleven ungrouped stock `Positions` and most fields cut):

```json
{"Positions": ["…eleven stock positions…"],
 "Groups": [{"GroupID": "p12", "GroupName": "Dec03 700/705 Call Vertical", "AccountID": "<ACCT>",
   "Quantity": "1", "Underlying": "SPY", "AveragePrice": "2", "Bid": "1.9", "Ask": "2.1",
   "Positions": [
     {"PositionID": "p13", "Symbol": "SPY 261203C700", "Quantity": "1", "LongShort": "Long",
      "AssetType": "STOCKOPTION", "AveragePrice": "3"},
     {"PositionID": "p14", "Symbol": "SPY 261203C705", "Quantity": "-1", "LongShort": "Short",
      "AssetType": "STOCKOPTION", "AveragePrice": "1"}]}]}
{"StreamStatus": "EndSnapshot"}
```

`groups::decode_groups` makes one `Membership` of two signed members; the kernel names the group from its members (a call vertical) and prices it from the account's own rows. No capture yet of the kernel's `Groups` answer off a TradeStation account: one comes from a headless kernel linked to the SIM sign-in (`plugins/tradestation/scripts/tradestation_walk.py <port> link`), then this read.

**A position group edit.** Splitting that group into two of one each, through `ExecutionOps::regroup` (`tests/fixtures/positiongroups/writes.json`, shaped as SIM's 2026-12-02 answers, ids and strikes made up):

```json
POST /v3/brokerage/positiongroups/groups/split
{"AccountID": "<ACCT>", "GroupID": "p20",
 "Groupings": [{"Positions": [{"PositionID": "p13", "Quantity": 1}, {"PositionID": "p14", "Quantity": -1}]},
               {"Positions": [{"PositionID": "p13", "Quantity": 1}, {"PositionID": "p14", "Quantity": -1}]}]}

200 {"AccountID": "<ACCT>", "Groups": [
  {"GroupID": "p21", "Positions": [{"PositionID": "p13", "Quantity": 1, "Symbol": "SPY 261203C700"},
                                   {"PositionID": "p14", "Quantity": -1, "Symbol": "SPY 261203C705"}]},
  {"GroupID": "p22", "Positions": [{"PositionID": "p13", "Quantity": 1, "Symbol": "SPY 261203C700"},
                                   {"PositionID": "p14", "Quantity": -1, "Symbol": "SPY 261203C705"}]}]}
```

Quantities are signed integers here and signed strings on the stream; a member is named by the `PositionID` a fresh snapshot resolved, and the split answers new ids, so the next read re-resolves them.

## Testing

| What | Command | Needs |
|---|---|---|
| Unit and offline tests: decoders (each product's rows held to `FILLS`), guards, budgets, the brokers against `wiremock`, `egress.rs` byte goldens, `no_v2.rs`, `auth_retry_is_get_only.rs` | `cargo test -p taji-tradestation` | nothing |
| The hub replaying the source's stored raw answers (a future's and a future option's chain) | `cargo test -p taji-trading --lib hub::tradestation_tests` | nothing |
| Market data and position groups, no kernel | `cargo test -p taji-tradestation --test live -- --ignored --test-threads=1 [filter]` | `TRADESTATION_API_KEY`, `_API_SECRET`, `_REFRESH_TOKEN`; reads the live host's market data and SIM accounts; `position_group_writes` edits a SIM account's groups |
| Order shapes, placed and cancelled | `cargo test -p taji-tradestation --test sim_orders -- --ignored --nocapture --test-threads=1` | the sign-in and `TRADESTATION_OPTIONS_ACCOUNT`; SIM only, places orders |
| The REST 401 retry against the real server | `cargo test -p taji-tradestation --features integration -- --nocapture` | the sign-in |
| SIM calls the kernel cannot make | `cargo run -p taji-tradestation --example ts_parity_probe -- <command>` | the sign-in; SIM only, exits before any request otherwise |
| The walk through a running kernel | `plugins/tradestation/scripts/tradestation_walk.py <port> <phase>` | a headless kernel; `link` and `data` only read, the other phases place SIM orders, `WALK_MARKET=1` lets them fill |

Without the sign-in a keyed test prints `SKIP` and passes. The fixtures under `tests/fixtures/` are SIM captures, account ids masked as `<ACCT>` and other ids as `pN`, read by `groups.rs` and `venue_reads.rs` tests.

## References

- [Getting Started](https://api.tradestation.com/docs/), fetched 2026-12-02.
- [SIM vs. LIVE](https://api.tradestation.com/docs/fundamentals/sim-vs-live), fetched 2026-12-02.
- [Authentication](https://api.tradestation.com/docs/fundamentals/authentication/auth-overview), [Auth Code Flow](https://api.tradestation.com/docs/fundamentals/authentication/auth-code), [Refresh Tokens](https://api.tradestation.com/docs/fundamentals/authentication/refresh-tokens), [Scopes](https://api.tradestation.com/docs/fundamentals/authentication/scopes), fetched 2026-12-02.
- [Rate Limiting](https://api.tradestation.com/docs/fundamentals/rate-limiting/rate-limiting-overview), [Historical Bar Data Limits](https://api.tradestation.com/docs/fundamentals/rate-limiting/historical-bar), fetched 2026-12-02.
- [HTTP Requests](https://api.tradestation.com/docs/fundamentals/http-requests), [HTTP Streaming](https://api.tradestation.com/docs/fundamentals/http-streaming), fetched 2026-12-02.
- [Extended Hours Options](https://api.tradestation.com/docs/fundamentals/extended-hours-options), [Position Groups](https://api.tradestation.com/docs/features/complex-options-positions-api), fetched 2026-12-02.
- [FAQ](https://api.tradestation.com/docs/faq), fetched 2026-12-02.
- [Specification](https://api.tradestation.com/docs/specification), the OpenAPI document downloaded 2026-12-01.
