# FlashAlpha Historical API

Point-in-time replay of the core live analytics routes (52 of them; earnings, screener and structures are live-only). Ask what GEX, gamma flip, VRP,
narrative, max pain, or full stock summary looked like at a specific **minute in history** - 
returned in the same response shape as the live API.

Backed by 80+ B option rows across 200+ symbols, 23 M+ stock minute-bars, EOD OI, daily SVI fits, and daily
macro (VIX, VVIX, SKEW, MOVE, SPX, DGS10) for **204 symbols, 54 with 8+ years of minute-level history** (extended
on each pipeline run; SPY and 13 others run from 2017-01-03). More symbols backfill on demand.

| | |
|---|---|
| **Symbols** | 204 in the archive, 54 with 8+ years (SPY, QQQ, SPXW, XSP, IWM, TSLA, NVDA, ...) + more on demand |
| **Range** | 2017-01-03 → present for the deepest 14 (SPY included); per-symbol first dates vary (SPX from 2022) - check `/v1/tickers` |
| **Option rows** | 80+ B |
| **Stock minute-bars** | 23 M+ |
| **Minimum tier** | Alpha |
| **Base URL** | `https://historical.flashalpha.com` |

---

## Host & Authentication
*How to call it - same key as live, tier-gated at Alpha.*

- **Base URL:** `https://historical.flashalpha.com`
- **Auth:** same `X-Api-Key` header as the live API (`lab.flashalpha.com`). Your real
  production key works - Historical validates against the same `AspNetUsers` table as
  live.
- **Tier gate:** **Alpha plan or higher** on every endpoint. Non-Alpha users get `403
  tier_restricted` on any request regardless of path.
- **Quota:** requests count against the same daily bucket as the live API.

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/tickers"
```

---

## The `at` Parameter
*The as-of timestamp that every analytics endpoint hangs off.*

Every analytics endpoint takes a required `at` query parameter - the as-of timestamp.

| Format | Example | Semantics |
|---|---|---|
| `yyyy-MM-ddTHH:mm:ss` | `2026-03-05T15:30:00` | Minute-level as-of. Treated as ET wall-clock (same clock as the stored data). |
| `yyyy-MM-dd` | `2026-03-05` | Defaults to 16:00 ET; exposure routes use 15:55 ET to retain same-day Greeks. |

### Unreleased change: prior-settled daily enrichment

Macro/VIX and daily realized-volatility inputs exclude the requested ET date. **Date-only,
EOD and after-close replays also use prior-session daily inputs**, even when price is the
requested session's close. For August 5, 2024, VIX is 23.39 from August 2, not 38.57 from
August 5. The same rule applies to 0DTE `vol_context.vix`. Macro changes compare the selected
observation with the observation preceding it. Daily closes are chronological and use the
latest prior-close window, correcting historical HV and directional RV calculations.

`archive_as_of.macro_feed` identifies the observation using a session-close date convention,
not a verified publication timestamp. Release/revision vintages and historical running
intraday macro are not available through these endpoints. Missing macro observations can
make the selected context older. Recompute saved backtest results across this release.

### Data freshness

| Field | Granularity |
|---|---|
| Stock bid / ask / mid / last | 1 minute (9:30 → 16:00 ET) |
| Option bid / ask / mid | 1 minute |
| Implied vol (per contract, BSM) | 1 minute |
| Greeks: delta, gamma, theta, vega, rho, vanna, charm | 1 minute (recomputed from stored IV + spot) |
| Open interest | EOD (one value per trade day, applied to every intraday `at=`) |
| `svi_vol` per contract | EOD-aligned `at=` only; intraday calls return `null` and you should use `implied_vol` |
| SVI parameters, forward prices | EOD |
| HV/RV ladder | Prior daily closes; excludes requested ET date, including EOD requests |
| Macro: VIX, VVIX, SKEW, MOVE, SPX, VIX9D/3M/6M, DGS10 | Latest daily observation strictly before requested ET date |
| VRP percentile / z-score | Reference rows satisfy `SnapshotDate < at.Date`; live nightly RV convention differs from prior-settled replay RV |

VRP percentile/z-score compare the replay against live nightly observations computed with
same-day RV. They are not a uniformly recomputed prior-settled replay distribution.
Shifting the date cutoff alone does not recalculate that stored history.

**Fields that return `0` or `null` on the analytics endpoints:** contract and aggregate volume (`call_volume`/`put_volume`/`total_volume`), prior-day OI deltas (`oi_change`, `top_oi_changes`), CME VIX futures, CNN Fear & Greed. These endpoints are built from the minute quote-and-greeks store, which carries no per-bar volume column - but **volume itself is not missing from the archive.** It lives in the raw options trade tape (4.66 billion prints back to 2017-01-03), which replays as per-minute signed buy/sell/mid/net volume via the flow endpoints - `GET /v1/flow/options/{symbol}/history?at=&minutes=N` and the rest of the `/v1/flow/*` suite, alongside an intraday open-interest simulator at `/v1/flow/oi/{symbol}?at=`. See the [Historical Options Flow Replay](https://flashalpha.com/articles/historical-options-flow-replay-trade-tape-oi-simulator) guide.

**0DTE specifics:** for gamma walls, pin probability, and pain analysis on near-zero-DTE contracts, call `at=YYYY-MM-DD` (EOD snapshot) - intraday minute-level greeks for these very-short-DTE chains are sparse and exposure totals can read as `0`. EOD calls return the close-of-session 0DTE picture with full greek coverage.

Intraday GEX / DEX / VEX / CHEX shifts are driven by greek and spot changes - OI moves slowly enough that EOD stamping is the right granularity for dealer-positioning work.

---

## Full Route Index
*Every route the Historical host serves. 52 in total - 51 Alpha-gated plus the public `/v1/tickers`. Each one is callable from the [Historical Playground](https://flashalpha.com/docs/historical-playground).*

All routes are `GET`. Unless the Params column says otherwise, `at` is required and every other parameter is optional.

### Coverage

| Route | Params | What it returns |
|---|---|---|
| `/v1/tickers` | `symbol`? | Symbols with historical coverage, date range, and gaps |

### Market Data

| Route | Params | What it returns |
|---|---|---|
| `/v1/stockquote/{ticker}` | `at` | Stock bid/ask/mid at the requested minute |
| `/v1/optionquote/{ticker}` | `at` `expiry`? `strike`? `type`? `maxSpreadPct`? `maxSpreadAbs`? | Option quote + BSM greeks + OI at the requested minute |
| `/v1/surface/{symbol}` | `at` | 50x50 implied-vol surface grid over (tenor, log-moneyness) |
| `/v1/stock/{symbol}/prices` | `days`? `adjusted`? | Daily OHLC bars - no as-of required, the series is already point-in-time |

### Exposure Analytics

| Route | Params | What it returns |
|---|---|---|
| `/v1/exposure/summary/{symbol}` | `at` | Composite exposure dashboard - net GEX/DEX/VEX/CHEX, gamma flip, regime |
| `/v1/exposure/gex/{symbol}` | `at` `expiration`? `min_oi`? | Gamma exposure by strike |
| `/v1/exposure/dex/{symbol}` | `at` `expiration`? | Delta exposure by strike |
| `/v1/exposure/vex/{symbol}` | `at` `expiration`? | Vanna exposure by strike |
| `/v1/exposure/chex/{symbol}` | `at` `expiration`? | Charm exposure by strike |
| `/v1/exposure/sheet/{symbol}` | `at` `expiration`? `min_oi`? | All greeks by strike in one call - GEX, DEX, VEX, CHEX side by side |
| `/v1/exposure/term-structure/{symbol}` | `at` | Exposure decomposed by expiry bucket |
| `/v1/exposure/range/{symbol}` | `from` `to` `bucket` | Exposure sampled across a window - one call instead of N point queries |
| `/v1/exposure/levels/{symbol}` | `at` | Support/resistance from dealer positioning |
| `/v1/exposure/narrative/{symbol}` | `at` | Verbal analysis + prior-day GEX comparison + VIX context |
| `/v1/exposure/zero-dte/{symbol}` | `at` `strike_range`? | Same-day expiry exposure, pin risk, and expected move |

### Max Pain

| Route | Params | What it returns |
|---|---|---|
| `/v1/maxpain/{symbol}` | `at` `expiration`? | Max pain strike, pain curve, and dealer alignment |

### Stock Summary

| Route | Params | What it returns |
|---|---|---|
| `/v1/stock/{symbol}/summary` | `at` | Price + volatility + flow + exposure + macro in one call |

### Volatility Analytics

| Route | Params | What it returns |
|---|---|---|
| `/v1/volatility/{symbol}` | `at` | Realized-vol ladder, IV/RV spreads, skew, term structure |
| `/v1/adv_volatility/{symbol}` | `at` | SVI params, variance surface, arb flags, greek surfaces |
| `/v1/volatility/forecast/{symbol}` | `at` | EWMA, HAR-RV, GARCH and the realized-variance models, as of the last completed session |
| `/v1/volatility/skew-term/{symbol}` | `at` | 25-delta and 10-delta skew across the term structure |
| `/v1/liquidity/{symbol}` | `at` | Spread, depth, and tradability scoring of the chain |
| `/v1/dispersion` | `at` `index`? `symbols`? `weights`? `horizon_days`? | Index vs constituent implied correlation |
| `/v1/expected-move/{symbol}` | `at` `expiry`? | Straddle-implied expected move to expiry |

### VRP Analytics

| Route | Params | What it returns |
|---|---|---|
| `/v1/vrp/{symbol}` | `at` | Variance risk premium, percentile and z-score - leak-free |

### Strategy Signals

| Route | Params | What it returns |
|---|---|---|
| `/v1/strategies/skew/{symbol}` | `at` `expiry`? | Skew-based decision signal with component breakdown |
| `/v1/strategies/term-structure/{symbol}` | `at` | Calendar / term-structure decision signal |
| `/v1/strategies/tail-pricing/{symbol}` | `at` `expiry`? | Wing / tail richness decision signal |
| `/v1/strategies/sell-window/{symbol}` | `at` | sell-window: sell or skip per expiry, plus suggested positions (SPY, QQQ, IWM). `at=<session>T09:35:00` returns the backtest's entry strikes |

### Flow Analytics

| Route | Params | What it returns |
|---|---|---|
| `/v1/flow/summary/{symbol}` | `at` `expiry`? | Flow-derived positioning built from the trade tape, not settled OI |
| `/v1/flow/gex/{symbol}` | `at` `expiry`? `polarity`? | Signed gamma exposure from the tape with inferred dealer polarity |
| `/v1/flow/dex/{symbol}` | `at` `expiry`? | Signed delta exposure from the tape |
| `/v1/flow/levels/{symbol}` | `at` `expiry`? `polarity`? | Flow-derived support/resistance and walls |
| `/v1/flow/pin-risk/{symbol}` | `at` `expiry`? | Pin probability by strike from tape-derived positioning |
| `/v1/flow/dealer-risk/{symbol}` | `at` `expiry`? | Dealer risk decomposition from the tape |
| `/v1/flow/oi/{symbol}` | `at` `expiry`? | Intraday open-interest simulator - OI as it built through the session |
| `/v1/flow/live/{symbol}` | `at` `expiry`? | Composite flow snapshot as of the requested minute |
| `/v1/flow/signals/{symbol}` | `at` `minScore`? `intent`? `structure`? `windowMinutes`? `limit`? `expiry`? | Scored, classified notable prints - block/sweep, aggressor, intent |
| `/v1/flow/signals/{symbol}/summary` | `at` `windowMinutes`? `expiry`? | Aggregated signal counts and bias over the window |

### Raw Flow Tape

| Route | Params | What it returns |
|---|---|---|
| `/v1/flow/options/{symbol}/recent` | `at` `limit`? `expiry`? | The most recent option prints as of the timestamp |
| `/v1/flow/options/{symbol}/summary` | `at` `expiry`? | Session-to-date buy/sell/mid volume and premium |
| `/v1/flow/options/{symbol}/blocks` | `at` `minSize`? `expiry`? | Large prints above a size threshold |
| `/v1/flow/options/{symbol}/history` | `at` `minutes`? `expiry`? | Per-minute signed buy/sell/mid/net volume buckets |
| `/v1/flow/options/{symbol}/cumulative` | `at` `minutes`? `expiry`? | Running cumulative net flow over the window |
| `/v1/flow/stocks/{symbol}/recent` | `at` `limit`? | Recent equity prints as of the timestamp |
| `/v1/flow/stocks/{symbol}/summary` | `at` | Session-to-date equity buy/sell split |
| `/v1/flow/stocks/{symbol}/blocks` | `at` `minSize`? | Large equity prints above a size threshold |
| `/v1/flow/stocks/{symbol}/history` | `at` `minutes`? | Per-minute signed equity volume buckets |
| `/v1/flow/stocks/{symbol}/cumulative` | `at` `minutes`? | Running cumulative equity net flow |
| `/v1/flow/options/leaderboard` | `at` `n`? `windowMinutes`? | Cross-symbol option flow ranking at the timestamp |
| `/v1/flow/options/outliers` | `at` `limit`? `minTrades`? `windowMinutes`? | Cross-symbol option flow outliers at the timestamp |
| `/v1/flow/stocks/leaderboard` | `at` `n`? `windowMinutes`? | Cross-symbol equity flow ranking at the timestamp |
| `/v1/flow/stocks/outliers` | `at` `limit`? `minTrades`? `windowMinutes`? | Cross-symbol equity flow outliers at the timestamp |

The sections below document the most-used routes in detail.

---

## Coverage & Support
*What's loaded, how healthy it is, and where the gaps are.*

### `GET /v1/tickers`

Lists every symbol with historical coverage, the date range, and any gaps. Backed by the
`history_coverage` table in QuestDB, written by the pipeline's Data Quality step at the
end of every backfill run.

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/tickers"
```

**Response 200**
```json
{
  "count": 26,
  "tickers": [
    {
      "symbol": "SPY",
      "coverage": {
        "first": "2017-01-03",
        "last": "2026-07-17",
        "total_days": 3483,
        "healthy_days": 2329
      },
      "tables": {
        "stocks_days": 2394,
        "options_days": 2395,
        "option_eod_days": 2329,
        "svi_days": 2394
      },
      "gaps": {
        "missing_eod": 65,
        "missing_svi": 0,
        "uncovered_calendar": 1
      },
      "updated_at": "2026-04-14T07:07:36.55353"
    }
  ]
}
```

| Field | Meaning |
|---|---|
| `coverage.first` / `coverage.last` | Date range of fully healthy days (intersection of stocks ∩ options ∩ option_eod ∩ svi_daily) |
| `coverage.healthy_days` | Trading days on which **every** downstream table has data |
| `tables.*_days` | Per-source day counts - debug signal when something is behind |
| `gaps.missing_eod` | Days with stock data but no `option_eod` row. Affects only EOD-stamped derived fields (SVI surface, term VRP percentiles, EOD `at=YYYY-MM-DD` calls); minute-resolution analytics on those days remain queryable. |
| `gaps.missing_svi` | Days in `option_eod` without an SVI fit |
| `gaps.uncovered_calendar` | NYSE trading days never pulled at all (genuine holidays like 2018-12-05 Bush funeral, 2025-01-09 Carter funeral) |
| `updated_at` | UTC timestamp of the last pipeline quality-report run |

**Confirming a specific backtest window:** the aggregate `gaps` counts span the full coverage range, so a high gap count does not imply gaps in your target window. To verify, hit any analytics endpoint at sample dates inside the window - a `200` confirms the day is queryable, `404 no_data` indicates a gap.

### `?symbol=` filter

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/tickers?symbol=SPY"
```

Returns a single object (not wrapped). `404 no_coverage` if the symbol hasn't been
backfilled.

---

## Market Data
*Raw quotes and surfaces at a single minute in history.*

### `GET /v1/stockquote/{ticker}?at=...`

Stock bid/ask/mid/last at the requested minute.

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/stockquote/SPY?at=2026-03-05T15:30:00"
```

```json
{
  "ticker": "SPY",
  "bid": 679.45,
  "ask": 679.47,
  "mid": 679.46,
  "lastPrice": 679.46,
  "lastUpdate": "2026-03-05T15:30:00"
}
```

### `GET /v1/optionquote/{ticker}?at=...&expiry=&strike=&type=`

Option quotes + BSM greeks + OI at the requested minute. Parameters identical to the live
endpoint.

| Param | In | Required | Description |
|---|---|---|---|
| `ticker` | path | yes | Underlying symbol |
| `at` | query | yes | As-of timestamp |
| `expiry` | query | no | `yyyy-MM-dd` |
| `strike` | query | no | |
| `type` | query | no | `C` / `Call` / `P` / `Put` |

With all three filters → single object. Otherwise → array.

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/optionquote/SPY?at=2026-03-05T15:30:00&expiry=2026-03-06&strike=680&type=C"
```

```json
{
  "type": "C",
  "expiry": "2026-03-06",
  "strike": 680,
  "bid": 3.42,
  "ask": 3.44,
  "mid": 3.43,
  "bidSize": 0,
  "askSize": 0,
  "lastUpdate": "2026-03-05T15:30:00",
  "implied_vol": 0.2579,
  "iv_bid": null,
  "iv_ask": null,
  "delta": 0.4824,
  "gamma": 0.0435,
  "theta": -1.8617,
  "vega": 0.1417,
  "rho": 0.0089,
  "vanna": 0.0891,
  "charm": -0.0147,
  "svi_vol": null,
  "svi_vol_gated": "backtest_mode",
  "open_interest": 6284,
  "volume": 0
}
```

---

### `GET /v1/surface/{symbol}?at=...`

50×50 implied-vol surface grid over (tenor, log-moneyness). Same grid builder as the live
endpoint, computed from OTM contract IVs with bilinear interpolation.

```json
{
  "symbol": "SPY",
  "spot": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "grid_size": 50,
  "tenors": [0.003, 0.023, ... ],
  "moneyness": [-0.25, -0.23, ..., 0.25],
  "iv": [ [0.34, 0.33, ...], ... ],
  "slices_used": 18
}
```

Returns `404 insufficient_data` for historical dates with too few OTM+liquid contracts to
fill the grid (pre-2017 low-volume symbols).

---

## Exposure Analytics
*GEX / DEX / VEX / CHEX, gamma flip, dealer positioning - all at a single historical minute.*

### `GET /v1/exposure/gex/{symbol}?at=...&expiration=&min_oi=`

Gamma exposure by strike. Same response shape as live.

| Param | Default | Description |
|---|---|---|
| `expiration` | all | `yyyy-MM-dd` filter |
| `min_oi` | 0 | Minimum OI threshold |

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "as_of_requested": "2026-03-05T15:30:00",
  "gamma_flip": 689.18,
  "net_gex": -4343591862,
  "net_gex_label": "negative",
  "strikes": [
    {
      "strike": 480,
      "call_gex": 549.06,
      "put_gex": 0,
      "net_gex": 549.06,
      "call_oi": 7,
      "put_oi": 4132,
      "call_volume": 0,
      "put_volume": 0,
      "call_oi_change": null,
      "put_oi_change": null
    }
  ]
}
```

### `GET /v1/exposure/dex/{symbol}?at=...&expiration=`

Delta exposure by strike. Response shape:

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "as_of_requested": "2026-03-05T15:30:00",
  "payload": {
    "net_dex": -10078461360,
    "strikes": [
      { "strike": 480, "call_dex": 472881.33, "put_dex": 0, "net_dex": 472881.33 }
    ]
  }
}
```

### `GET /v1/exposure/vex/{symbol}?at=...&expiration=`

Vanna exposure by strike. Same shape as `dex` with `net_vex` + `vex_interpretation`.

### `GET /v1/exposure/chex/{symbol}?at=...&expiration=`

Charm exposure by strike. Same shape as `dex` with `net_chex` + `chex_interpretation`.

### `GET /v1/exposure/summary/{symbol}?at=...`

Full composite exposure dashboard - net GEX/DEX/VEX/CHEX, gamma flip, regime,
interpretations, ±1% hedging estimates, 0DTE contribution.

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "gamma_flip": 677.5,
  "regime": "positive_gamma",
  "exposures": {
    "net_gex": -10941036971,
    "net_dex": -41195007931,
    "net_vex": 1581599207,
    "net_chex": 1933358
  },
  "interpretation": {
    "gamma": "Dealers long gamma — moves dampened, mean reversion likely",
    "vanna": "Vol up = dealers buy delta — downside dampened if vol spikes",
    "charm": "Time decay pushing dealers to buy — supportive into close"
  },
  "hedging_estimate": {
    "spot_down_1pct": { "dealer_shares_to_trade": -16102548, "direction": "sell", "notional_usd": -10941036971 },
    "spot_up_1pct":   { "dealer_shares_to_trade":  16102548, "direction": "buy",  "notional_usd":  10941036971 }
  },
  "zero_dte": { "net_gex": 0, "pct_of_total_gex": 0, "expiration": "2026-03-05" }
}
```

### `GET /v1/exposure/levels/{symbol}?at=...`

Key technical levels.

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "levels": {
    "gamma_flip": 677.5,
    "max_positive_gamma": 700,
    "max_negative_gamma": 680,
    "call_wall": 685,
    "put_wall": 680,
    "highest_oi_strike": 630,
    "zero_dte_magnet": 500
  }
}
```

### `GET /v1/exposure/narrative/{symbol}?at=...`

Verbal analysis + prior-day GEX comparison + VIX context. Historical-specific wiring:
`gex_change` pulls the previous trading day's net GEX from QuestDB; `vix` comes from
`macro_daily`.

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "as_of_requested": "2026-03-05T15:30:00",
  "narrative": {
    "regime": "Dealers are long gamma (net GEX -$10.9B) — ...",
    "gex_change": "Net GEX decreased from -$4.9B to -$10.9B (-125.2%) — gamma cushion weakening.",
    "key_levels": "Call wall at 685, Put wall at 680, Gamma flip at 677.5.",
    "flow": "...",
    "vanna": "...",
    "charm": "...",
    "zero_dte": "...",
    "outlook": "...",
    "data": {
      "net_gex": -10941036971,
      "net_gex_prior": -4858715464,
      "net_gex_change_pct": -125.2,
      "vix": 23.75,
      "gamma_flip": 677.5,
      "call_wall": 685,
      "put_wall": 680,
      "regime": "positive_gamma",
      "zero_dte_pct": 0,
      "top_oi_changes": []
    }
  }
}
```

### `GET /v1/exposure/zero-dte/{symbol}?at=...&strike_range=`

0DTE-specific analytics. Mirrors live shape exactly: `regime`, `exposures`, `expected_move`,
`pin_risk`, `hedging` (±0.5% / ±1%), `decay`, `flow`, `levels`, `strikes`.

<details>
<summary>Example response (click to expand)</summary>

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "market_open": true,
  "expiration": "2026-03-05",
  "no_zero_dte": null,
  "next_zero_dte_expiry": null,
  "message": null,
  "regime": { "label": "unknown", "gamma_flip": null, "spot_vs_flip": null, "spot_to_flip_pct": null, "description": "..." },
  "exposures": { "net_gex": 0, "net_dex": 0, "net_vex": 0, "net_chex": 0, "pct_of_total_gex": 0, "total_chain_net_gex": -10941036971.26 },
  "expected_move": { "straddle_price": 1.57, "implied_1sd_dollars": 3.7, "implied_1sd_pct": 0.5448, "remaining_1sd_dollars": 1.03, "remaining_1sd_pct": 0.1511, "upper_bound": 680.49, "lower_bound": 678.43, "atm_iv": null },
  "pin_risk": { "magnet_strike": 500, "max_pain": 685, "pin_score": 32, "distance_to_magnet_pct": 26.41, "oi_concentration_top3_pct": 14.6, "description": "..." },
  "decay": { "theta_per_hour_remaining": 0, "net_theta_dollars": 0, "gamma_acceleration": 25.47, "charm_regime": "neutral", "description": "..." },
  "flow": { "call_oi": 161462, "put_oi": 252805, "total_oi": 414267, "call_volume": 0, "put_volume": 0, "total_volume": 0, "pc_ratio_oi": 1.566, "pc_ratio_volume": null, "volume_to_oi_ratio": 0 },
  "hedging": { "spot_up_half_pct": { "...": "..." }, "spot_down_half_pct": { "...": "..." }, "spot_up_1pct": { "...": "..." }, "spot_down_1pct": { "...": "..." } },
  "levels": { "highest_oi_strike": 685, "highest_oi_total": 22397, "call_wall": 500, "put_wall": 500, "call_wall_gex": 0, "put_wall_gex": 0, "max_positive_gamma": null, "max_negative_gamma": null },
  "strikes": [ { "strike": 660, "call_oi": 72, "put_oi": 6554, "call_gex": 0, "put_gex": 0, "net_gex": 0, "call_dex": 0, "put_dex": 0, "net_dex": 0, "call_iv": null, "put_iv": null, "...": "..." } ]
}
```

</details>

For full 0DTE greek and exposure coverage, call `at=YYYY-MM-DD` (EOD snapshot). Intraday minute-level greeks for very-short-DTE contracts are sparse at the minute grain; the chain still lists OI and strike distribution but aggregate exposures may read as `0`.

If a symbol genuinely has no 0DTE expiry on that trade date, the response collapses to
`expiration: null`, `no_zero_dte: true`, `next_zero_dte_expiry: "<next>"`, with the rest
of the analytics blocks omitted. SPY now lists Mon-Fri expirations so this branch is rare;
older history (pre-2022 daily-expiry rollout) hits it more often.

**`time_to_close_hours` is computed** from `at` against 16:00 ET on the same day, so
intraday theta and greek-acceleration numbers (where greeks exist) are accurate to the minute.

---

## Max Pain
*Strike-by-strike pain curve, pin probability, and dealer alignment.*

### `GET /v1/maxpain/{symbol}?at=...&expiration=`

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "max_pain_strike": 684,
  "distance": { "absolute": 4.54, "percent": 0.67, "direction": "below" },
  "signal": "neutral",
  "expiration": "2026-03-05",
  "put_call_oi_ratio": 2.033,
  "pain_curve":    [ { "strike": ..., "call_pain": ..., "put_pain": ..., "total_pain": ... } ],
  "oi_by_strike":  [ { "strike": ..., "call_oi": ..., "put_oi": ..., "total_oi": ..., "call_volume": 0, "put_volume": 0 } ],
  "max_pain_by_expiration": [ { "expiration": "...", "max_pain_strike": ..., "dte": ..., "total_oi": ... } ],
  "dealer_alignment": {
    "alignment": "moderate",
    "description": "...",
    "gamma_flip": 677.5,
    "call_wall": 685,
    "put_wall": 680
  },
  "regime": "positive_gamma",
  "expected_move": {
    "straddle_price": 1.57,
    "atm_iv": 19.6,
    "max_pain_within_expected_range": false
  },
  "pin_probability": 45
}
```

---

## Price History (OHLC)
*Daily OHLC bars for realized / forecast volatility - the only endpoint here that does NOT take `at`.*

### `GET /v1/stock/{symbol}/prices?days=N`

Daily OHLC bars (mid-derived from the QuestDB `stocks` table via `SAMPLE BY 1d`),
oldest-first. Backs the live `/v1/volatility/realized` and `/v1/volatility/forecast`
endpoints. Unlike the replay endpoints this returns the most-recent `N` trading days
up to now rather than a point-in-time snapshot, so it takes `days` (default 600,
clamped 1-2000) instead of `at`. Symbols outside the replay archive return 404. Alpha tier.

Add `adjusted=true` for split-adjusted bars: every bar before a split is divided by the split
ratio (open, high, low and close), so the whole series is on the basis of the latest bar. Split
dates and ratios are the recorded ones. Without it, bars are as traded. The live volatility
endpoints read the adjusted bars.

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/stock/AAPL/prices?days=500"
```

```json
{
  "symbol": "AAPL",
  "bars": [
    { "date": "2024-01-02", "open": 187.15, "high": 188.44, "low": 183.89, "close": 185.64 },
    { "date": "2024-01-03", "open": 184.22, "high": 185.88, "low": 183.43, "close": 184.25 }
  ],
  "coverage": { "first": "2024-01-02", "last": "2026-06-05" }
}
```

Returns `404 no_coverage` when the symbol has no bars in the archive.

---

## Stock Summary (Composite)
*One call, one response: price, vol, flow, exposure, macro - a full snapshot.*

### `GET /v1/stock/{symbol}/summary?at=...`

The big one - mirrors live `GET /v1/stock/{symbol}/summary` exactly. Includes price,
volatility (ATM IV, HV20, HV60, VRP, 25d skew, IV term structure), options flow,
full exposure block, and macro context.

<details>
<summary>Example response (click to expand)</summary>

```json
{
  "symbol": "SPY",
  "as_of": "2026-03-05T15:30:00",
  "market_open": false,
  "price": { "bid": 679.45, "ask": 679.47, "mid": 679.46, "last": 679.46, "last_update": "..." },
  "volatility": {
    "atm_iv": 18.37,
    "hv_20": 10.26,
    "hv_60": 10.83,
    "vrp": 8.11,
    "skew_25d": { "...": "..." },
    "iv_term_structure": [ { "...": "..." } ]
  },
  "options_flow": {
    "total_call_oi": 5204107,
    "total_put_oi": 10577486,
    "total_call_volume": 0,
    "total_put_volume": 0,
    "pc_ratio_oi": 2.033,
    "pc_ratio_volume": null,
    "active_expirations": 37
  },
  "exposure": { "net_gex": ..., "regime": "positive_gamma", "...": "..." },
  "macro": {
    "vix":  { "value": 23.75, "change": 2.6, "change_pct": 12.29 },
    "vvix": { "value": 105.8, "...": "..." },
    "skew": { "...": "..." },
    "spx":  { "...": "..." },
    "move": { "...": "..." },
    "vix_term_structure": { "levels": { "vix9d": ..., "vix": 23.75, "vix3m": ..., "vix6m": ... }, "near_slope_pct": ..., "structure": "contango" },
    "vix_futures":    null,
    "fear_and_greed": null
  }
}
```

</details>

---

## Volatility Analytics
*Realized vs implied, skew, term structure, and SVI surfaces.*

### `GET /v1/volatility/{symbol}?at=...`

Comprehensive vol analysis - realized vol ladder (5/10/20/30/60d), IV-RV spreads, skew
profiles per expiry, term structure, IV dispersion, GEX/theta by DTE bucket, put/call
profile, OI concentration, multi-move hedging, liquidity.

Response fields are identical to the live endpoint. Realized vols come from QuestDB
`stocks` table via `SAMPLE BY 1d` last-tick.

### `GET /v1/volatility/forecast/{symbol}?at=...`

The live volatility forecast as of any past moment. Forecasts use data through the close of the last session completed
at `at`, with no look-ahead, and each model is fitted as of that session. Call it once per session to build a forecast
series.

Returns the same fields as the live `GET /v1/volatility/forecast/{symbol}`, including `realized_models`, except
`realized_models.computed_at`, which only the live endpoint returns. `dist` selects the GARCH innovation distribution:
`student_t` (default) or `gaussian`.

| Status | Description |
|--------|-------------|
| `400` | `invalid_at` or `invalid_symbol` |
| `404` | `insufficient_history` - fewer than 30 archived sessions before that date |
| `429` | `busy` - forecasts are being fitted for other requests; retry shortly |

### `GET /v1/adv_volatility/{symbol}?at=...`

Advanced volatility - SVI parameters, forward prices, total variance surface, arbitrage
flags, variance swap fair values, greek surfaces (vanna, charm, volga, speed).

<details>
<summary>Example response (click to expand)</summary>

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "svi_parameters": [ { "expiry": "...", "a": ..., "b": ..., "rho": ..., "m": ..., "sigma": ..., "forward": ..., "atm_total_variance": ..., "atm_iv": ... } ],
  "forward_prices": [ { "expiry": "...", "days_to_expiry": ..., "forward": ..., "spot": 679.46, "basis_pct": ... } ],
  "total_variance_surface": { "moneyness": [...], "expiries": [...], "tenors": [...], "total_variance": [[...]], "implied_vol": [[...]] },
  "arbitrage_flags": [ { "expiry": "...", "type": "...", "strike_or_k": ..., "description": "..." } ],
  "variance_swap_fair_values": [ { "expiry": "...", "days_to_expiry": ..., "fair_variance": ..., "fair_vol": ..., "atm_iv": ..., "convexity_adjustment": ... } ],
  "greeks_surfaces": {
    "vanna": { "strikes": [...], "expiries": [...], "values": [[...]] },
    "charm": { "...": "..." },
    "volga": { "...": "..." },
    "speed": { "...": "..." }
  }
}
```

</details>

---

## VRP Analytics
*Volatility Risk Premium - leak-free percentiles that only see the past.*

### `GET /v1/vrp/{symbol}?at=...`

Volatility Risk Premium dashboard. Identical calculator chain to live
`GET /v1/vrp/{symbol}`. Crucially, percentile history is **date-bounded** - VRP
percentile and z-score are computed from `DailyVrpSnapshots` rows with
`SnapshotDate < at.Date`, so at any historical point the percentile reflects what
was knowable at that moment (no future leakage).

```json
{
  "symbol": "SPY",
  "underlying_price": 679.46,
  "as_of": "2026-03-05T15:30:00",
  "vrp": {
    "atm_iv": 18.37,
    "rv_5d": 11.38,
    "rv_10d": 9.16,
    "rv_20d": 10.26,
    "rv_30d": 9.28,
    "vrp_5d": 6.99,
    "vrp_10d": 9.21,
    "vrp_20d": 8.11,
    "vrp_30d": 9.09,
    "z_score": 2.84,
    "percentile": 100,
    "history_days": 60
  },
  "variance_risk_premium": 0.0232,
  "convexity_premium": 5.43,
  "fair_vol": 23.8,
  "directional": { "put_wing_iv_25d": ..., "call_wing_iv_25d": ..., "downside_vrp": ..., "upside_vrp": ... },
  "term_vrp": [ { "dte": 7, "iv": ..., "rv": ..., "vrp": ... } ],
  "gex_conditioned": { "regime": "...", "harvest_score": ..., "interpretation": "..." },
  "vanna_conditioned": { "outlook": "...", "interpretation": "..." },
  "regime": { "gamma": "positive_gamma", "vrp_regime": "...", "net_gex": ..., "gamma_flip": 677.5 },
  "strategy_scores": { "short_put_spread": ..., "short_strangle": ..., "iron_condor": ..., "calendar_spread": ... },
  "net_harvest_score": ...,
  "dealer_flow_risk": ...,
  "warnings": [ "..." ],
  "macro": { "vix": 23.75, "vix_3m": ..., "vix_term_slope": ..., "dgs10": ..., "hy_spread": 3.5 }
}
```

---

## Errors
*What the API returns when things go wrong, and what each code means.*

| Status | When | Body |
|---|---|---|
| `400 invalid_at` | `at` parameter missing or wrong format | `{ "error": "invalid_at", "message": "..." }` |
| `400 invalid_expiration` | `expiration` not `yyyy-MM-dd` | `{ "error": "invalid_expiration", ... }` |
| `401 Unauthorized` | Missing or invalid `X-Api-Key` | empty body |
| `403 tier_restricted` | User tier below Alpha | `{ "error": "tier_restricted", "current_plan": "...", "required_plan": "Alpha" }` |
| `404 symbol_not_found` | Symbol has no historical data at the requested `at` | `{ "error": "symbol_not_found", ... }` |
| `404 no_coverage` | `/v1/tickers?symbol=` for a symbol that has never been backfilled | `{ "error": "no_coverage", ... }` |
| `404 no_data` | Specific `(symbol, at)` or `(symbol, at, expiration)` has no data (outside coverage window, or within a gap) | `{ "error": "no_data", ... }` |
| `404 insufficient_data` | Surface grid can't be built (too few OTM+liquid contracts) | `{ "error": "insufficient_data", ... }` |
| `429 rate_limited` | Daily quota exhausted | Shares quota with live API |

---

## Example: single-minute replay of March 16, 2020 (COVID crash)
*What "real dealer positioning during -12%" actually looked like.*

```bash
curl -H "X-Api-Key: YOUR_API_KEY" \
  "https://historical.flashalpha.com/v1/exposure/summary/SPY?at=2020-03-16T15:30:00"
```

Returns real-world exposure data at 15:30 ET on the day SPY closed -12%:

```json
{
  "symbol": "SPY",
  "underlying_price": 246.01,
  "as_of": "2020-03-16T15:30:00",
  "gamma_flip": 270.92,
  "regime": "negative_gamma",
  "exposures": {
    "net_gex": -2633970601,
    "net_dex": -169419489077,
    "net_vex": 152461756844,
    "net_chex": -13122349
  },
  "interpretation": {
    "gamma": "Dealers short gamma — moves amplified, trend following likely",
    "vanna": "Vol up = dealers buy delta — downside dampened if vol spikes",
    "charm": "Time decay pushing dealers to sell — pressure into close"
  },
  "hedging_estimate": { "...": "..." }
}
```

---

## Pipeline
*How new days are ingested.*

Historical data is populated by a gap-aware pipeline. Each run:

1. Pulls raw parquets from ThetaData
2. Hydrates greeks with BSM
3. Ingests options / stocks / option_eod into QuestDB
4. Fits SVI and computes forward prices
5. Refreshes dividend yields and macro
6. Writes the `history_coverage` row surfaced by `/v1/tickers`

The pipeline is idempotent: re-runs on healthy days are no-ops, and gap detection picks up missing files on the next run.

---

## Notes

- **Timezone.** Stored `at` values are ET wall-clock, labelled `Z` in JSON because QuestDB annotates TIMESTAMPs that way. Do not shift by UTC offset.
- **Quota.** Historical calls count against your daily plan quota.
- **Latency.** QuestDB `LATEST ON` queries return in ~50-300 ms; `adv_volatility` and the full stock summary recompute SVI-derived surfaces on demand and run ~500-1500 ms cold. Cache by `(symbol, at, endpoint)` - historical bars are immutable once a day is healthy.
- **`max_pain.signal` enum.** `neutral` | `bullish` | `bearish` describes spot position relative to max-pain strike, not a directional trade recommendation.
- **Coverage scope.** 204 symbols are in the replay archive, 54 of them with 8+ years of minute-resolution history (SPY, QQQ, SPXW, XSP, IWM, TSLA, NVDA, AAPL, AMZN, RUT, SMH and more); 14 run from 2017-01-03, SPX from 2022. Other tickers backfill on request (~48h for liquid US equities/ETFs). Call `/v1/tickers` for the live list.
- **Boundaries.** This API serves precomputed minute-resolution analytics, not raw L1/L2 tick or NBBO. Pre-2017-04 options history is not in scope; corporate-action splits are applied at ingest. For raw NBBO use ThetaData; for deeper EOD history use OptionMetrics/ORATS; for raw tick options use Polygon.

---

## Historical Backtest Cookbook
*The minimum-viable backtest loop. Everything past this is your own strategy code.*

**Complete backtester.** For a full, tested backtester (entry rules, contract selection, exit rules, fills at historical bid and ask, daily marks, trade and equity CSVs) in Python, JavaScript, Go, Java and C#, see [How to Backtest Options Strategies in Python](https://flashalpha.com/articles/how-to-backtest-options-strategies-python-flashalpha-historical-api) and `examples/backtester` in each SDK repo, for example [flashalpha-historical-python](https://github.com/FlashAlpha-lab/flashalpha-historical-python/tree/main/examples/backtester). Rules live in three functions: `entry_rules()`, `select_legs()` and `exit_rules()`.

### Six-step workflow

1. **Discover coverage.** Call `GET /v1/tickers` once. Confirm the symbol is in the
   list and that your backtest window falls inside `coverage.first` → `coverage.last`.
   Don't assume - symbols backfill on demand and the inventory changes.
2. **Pick timestamps strictly before signal time.** The `at` value is the moment
   *as known to the dealer book at that minute*. If your strategy decides at 10:30 ET,
   pass `at=10:30:00`, not `10:31:00`. No future leakage.
3. **Fetch analytics with `?at=...`.** One call per `(symbol, at)` per analytic.
   Same response shape as live, so the same parsing code works.
4. **Cache by `(symbol, at, endpoint)`.** Historical data is immutable once a day is
   `healthy_days`-marked, so cache aggressively. Saves your daily quota and 95% of
   request latency.
5. **Join to your own price/return series.** FlashAlpha gives you the dealer state
   at minute *t*; you compute realised P&L from your own price ticks at *t+1, t+5,
   close, etc.* This is the right place for your strategy's specific entry/exit logic.
6. **Never call live endpoints inside a historical backtest.** `lab.flashalpha.com`
   reflects the present moment, not the replay moment. Mixing the two leaks future
   information into your backtest. Set `base_url` once and stick with it.

### Python recipe - gamma-flip strategy backtest

For historical replay, hit the REST endpoints directly with `requests`. Response shapes match the SDK's live equivalents exactly, so analysis code written against the SDK works unchanged.

```python
from datetime import datetime, timedelta
import requests

API_KEY = "YOUR_ALPHA_KEY"
LIVE = "https://lab.flashalpha.com"
HIST = "https://historical.flashalpha.com"
S = requests.Session()
S.headers.update({"X-Api-Key": API_KEY})

# 1. Coverage check (no `at` parameter on /v1/tickers)
coverage = {t["symbol"]: t["coverage"]
            for t in S.get(f"{HIST}/v1/tickers").json()["tickers"]}
assert "SPY" in coverage, "SPY not backfilled"

def trading_days(start, end):
    d = start
    while d <= end:
        if d.weekday() < 5:           # crude - wire in your own holiday list
            yield d
        d += timedelta(days=1)

# 4. Cache by (symbol, at, endpoint) - historical bars are immutable once healthy
cache = {}
def hist(symbol, at, endpoint="exposure/gex"):
    key = (endpoint, symbol, at)
    if key not in cache:
        r = S.get(f"{HIST}/v1/{endpoint}/{symbol}", params={"at": at})
        r.raise_for_status()
        cache[key] = r.json()
    return cache[key]

# 2-3. Replay one snapshot per trading day at 10:30 ET, detect flip transitions
prev_regime = None
flips = []
for day in trading_days(datetime(2024, 7, 1), datetime(2024, 9, 30)):
    snap = hist("SPY", f"{day:%Y-%m-%d}T10:30:00")
    regime = "neg" if snap["net_gex"] < 0 else "pos"
    if prev_regime and regime != prev_regime:
        flips.append((day, prev_regime, regime,
                      snap["underlying_price"], snap["gamma_flip"]))
    prev_regime = regime

# 5. Join to your own returns series and compute strategy P&L here.
for d, was, now, spot, flip in flips:
    print(f"{d:%Y-%m-%d}  {was}->{now}  spot={spot:.2f}  flip={flip:.2f}")
```

To run the same strategy live, swap the host:

```python
# Live - same response shape, same parsing code, no at= parameter
snap = S.get(f"{LIVE}/v1/exposure/gex/SPY").json()
```

Response shape is identical, so the strategy code is host-agnostic. Live calls can also use the SDK as `FlashAlpha(API_KEY).gex("SPY")`.

### Backtest tips

- **Match resolution to need.** A two-year minute-loop is ~200k requests; a daily-bar loop with `at=YYYY-MM-DD` is ~500. Use minute resolution only where the signal requires it.
- **Default close time.** `at=YYYY-MM-DD` resolves to 16:00 ET except exposure routes, which use 15:55 ET to retain same-day Greeks. Use the same explicit `at=YYYY-MM-DDTHH:mm:ss` when comparing routes, and an actual session time on an early close.
- **Warm up the percentile window.** Skip the first ~60 trading days of any new backtest window or branch on `vrp.percentile == null`.


## Trader-context replay and research-pack additions

These additions require the corresponding Historical service release; local
production-data validation does not establish deployed availability.
Human documentation: [trader context](https://flashalpha.com/docs/historical-trader-context)
and [research packs](https://flashalpha.com/docs/historical-research-packs).

| GET route | Parameters and scope |
|---|---|
| `/v1/exposure/expiry-impact/{symbol}` | Required `at`; SPY/QQQ; optional `expiry`, `limit` 1–20 |
| `/v1/exposure/strike-dependency/{symbol}?strike=...` | Required `at` and positive numeric `strike` query; SPY/QQQ; exact observed strike |
| `/v1/exposure/term-structure/{symbol}` | Existing live route; required `at`; only the new `gamma_concentration` for SPY/QQQ requires this release |
| `/v1/strategies/yield-enhancement/{symbol}` | Required `at`; standard equity options; optional `expiry`, `structure`, `targetDelta`, `minOpenInterest`, `stockCostBasis`, `feesPerContract`, `excludeEarningsBeforeExpiry` |
| `/v1/research/packs` | Optional `symbol`, `strategy`, `at`; Alpha/Enterprise |
| `/v1/research/packs/{packId}` | Optional `at`; manifest |
| `/v1/research/packs/{packId}/artifacts/{name}` | Optional `at`; allowlisted SHA-verified downloads |

The three exposure routes above use 15:55 ET for date-only `at`; income and
full-volatility replay use 16:00 ET. Explicit timestamps are preserved. Use the
same explicit timestamp for matching snapshots and a session time before the
actual close on early-close days.

Gamma exclusion holds spot/Greeks constant: remaining = current − excluded.
GEX is USD delta notional per 1% move, calls positive/puts negative. Gross shares
use gross magnitude. Removal is sensitivity analysis, not next-session P&L.
Income diagnostics use bid × 100 gross credit; put collateral is strike × 100
before credit. Net fields need supplied opening fees; covered-call returns need
stock basis. Legacy ranks use mid; absolute delta is not calibrated assignment
probability and annualized yield is not a sustainable-return forecast.
Omitted income expiry preserves full-chain nearest-absolute-target-delta selection;
an explicit expiry restricts maturity. Quote diagnostics and roll context use the
selected expiry, strike and right. Fixed monthly 28–35 DTE research rules describe
a separate strategy. Long constant definitions use the API's published
`/llms/trader-context.md` methodology; machine quality codes and unknowns remain.
Empty archived roots and a 100-share multiplier do not identify strike-adjusted
series. Adjusted contracts can qualify; standard deliverables remain unverified.

SPY/QQQ earnings are not applicable. Other equities have an unknown historical
calendar and default to insufficient data when earnings exclusion is requested.
No earnings replay route is introduced. Gamma metadata's original OI vintage
remains unknown; income separately returns archived previous-session OI timing.

The SPY/QQQ gamma and full-volatility paths, plus income replay, bypass EOD option
materialized views. Other symbols retain the existing full-volatility loader path.
Daily skew, term, VRP-history and expected-move reconstructions remain disabled
until unhealthy sources are repaired and verified. They fail closed with
503 `historical_source_unhealthy`, never count frozen observations as usable.
Persisted replay-volatility references require both SnapshotDate earlier than
the replay date and CreatedAt no later than replay UTC; in-place revisions are
not fully versioned.

`metrics.research` has `status`, `as_of_utc`, `pack_ids`, `scope`,
`as_of_catalog_url` and separate `retrospective_catalog_url`. Applicability is
strategy-family research, not the returned candidate. Pack publication, frozen
definition and evaluation-data cutoffs must all be <= requested `at`, including
artifact downloads. Omitting `at` permits explicit retrospective discovery.
The first pack's publication timestamp is its 2026-10-16 offline build time, so
older replays return empty pack references. Retrospective discovery is separate
from evidence available at the replay instant; deployment must also be verified.

Pilot `income-spy-qqq-2024-2025-v1-db139753fe8b` includes all four 2025 baseline simulations. QQQ runs containing
2024 are withheld for missing held marks. Portfolios use USD 100,000, one contract,
bid/ask, fees/slippage, zero cash interest, unreinvested dividend receivables and
a separate mechanical assignment scenario. The 2025 holdout is retrospective,
not prospective; accounting checks do not independently validate Greeks, fills
or original publication timing.
Benchmark rankings are conditional on zero cash yield; this pack has no
cash-interest scenario, and interest can change the ranking.
