# QS Research API — Agent Integration Guide
> **Public trader terminal:** https://research.quantsignals.xyz/terminal/
> The terminal is additive: the root remains JSON and MCP remains the agent entrypoint.

This document describes the RESTful API for programmatic access by AI agents, CLI tools, and mobile apps.

> **Canonical agent-facing version served at:** `https://research.quantsignals.xyz/AGENTS.md`
> **Interactive Swagger UI:** `https://research.quantsignals.xyz/docs`
> **OpenAPI spec:** `https://research.quantsignals.xyz/openapi.json`

## Quickstart (cold-start agents)

No prior context needed — bootstrap entirely from the live surface:

1. **`GET /`** → a machine-readable service map (JSON) linking every entrypoint: `api`, `docs`, `openapi`, `mcp`, `health`, `agents_guide`, `llms`.
2. **`GET /llms.txt`** → the [llmstxt.org](https://llmstxt.org) discovery pointer (terse index of the whole surface), or read this guide / **`GET /openapi.json`** for every typed route.
3. **Connect the MCP server** at `POST /mcp` (Streamable HTTP, JSON-RPC 2.0): `tools/list` returns 48 read tools plus 2 idea-submitting tools (`qs_research_ask` runs a trading idea and waits for the answer), each with a description and an input schema — enough to call them with no other docs.
4. **Enumerate signals** via `GET /api/v1/signals/families` (every family + its read URL), read any family through the uniform `GET /api/v1/signals/{brand_id}`, and use `GET /api/v1/signals/screen` for an honest, confidence-ranked latest batch.
5. **Authenticate every premium read** — QS user clients send a Supabase
   bearer token; internal agents and CLI services send `X-API-Key`. Anonymous
   reads receive `401`.

Every response uses the envelope `{"data": …, "error": null, "meta": {}}`.

## The three hot paths (start here for trading)

Most trading callers only need these three, in order. They are deliberately
narrow, TTL-cached, and **never trigger generation** — safe to call constantly,
on every market.

1. **`GET /api/v1/signals/screen`** — top plays of the day. Reads the cached
   options-flow scan (never runs the LLM inline; a warmer keeps it hot during
   market hours) and returns the deterministically-ranked top plays, each with a
   **reverse news lookup** (`developing_story` flags a fresh headline behind the
   flow). On a cold cache it returns `warming: true`, not a wait. Params: `limit`
   (default 5).

2. **`GET /api/v1/signal/{ticker}`** — one play, opened. Exactly five parallel,
   fail-open legs: **options flow + GEX walls + dark-pool prints + Katy forecast
   chart + guru (13F) positioning**. Nothing else. Reads Katy's latest forecast;
   never starts a run. `unavailable` names any leg that didn't answer in the time
   budget. Param: `timeframe` (`hour` default, or `day`) for the Katy chart.

3. **`GET /api/v1/reports/{id}`** — the long multi-agent write-up. The only place
   the full FST engine research text lives. Fast (disk read).

Everything else under `/api/v1/*` is available but not on the hot path — reach
for it only when these three don't answer the question.

## Signal Marketplace

The Marketplace is a real distribution surface for QS signals:

- `GET /api/v1/marketplace/listings` — live first-party catalog with current
  source metrics for QS Flow, Katy AI, Dealer GEX, and Dark Pool.
- `GET /api/v1/marketplace/me` — followed signals and publisher application
  history for the authenticated Supabase user.
- `PUT /api/v1/marketplace/follows/{listing_id}` / `DELETE ...` — add or remove
  a signal from the user's cross-QS **My Signals** collection.
- `POST /api/v1/marketplace/publisher-applications` — submit a founding-quant
  strategy for QS verification.

Account endpoints require `Authorization: Bearer <Supabase access token>`.
Following a signal distributes research authority only; it never grants
brokerage execution authority.

## Base URL

```
https://research.quantsignals.xyz/api/v1
```

## Authentication

Premium endpoints require a verified Supabase bearer session for QS users or
`X-API-Key` for internal agents and CLI services:

```bash
curl -H "X-API-Key: your-key" https://research.quantsignals.xyz/api/v1/signals
```

## MCP Server

qs-research is also a **Model Context Protocol server** (Streamable HTTP,
JSON-RPC 2.0) at `POST /mcp` — the same dialect as qs-brokerage-backend's
`/mcp`, so an agent can research here and execute there through one protocol.
Auth accepts a verified Supabase bearer session for QS users or `X-API-Key`
for internal agents and CLI services. An outside MCP client (a Claude connector)
gets its own read-only token instead of the service key: `qsm_...`, sent as
`X-API-Key` or `Authorization: Bearer`. It works on `/mcp` only, is revocable on
its own, and sees 27 of the 35 tools: not the four idea tools that act as a
caller (`ask`, `submit_idea`, `get_idea`, `list_ideas`) and not the four that can
run a model (`strategist_scan`, `strategist_analyze`, `team_take`, `team_chair`).
Admins only: `POST /api/v1/mcp-tokens` `{"label"}` (the token is shown once),
`GET /api/v1/mcp-tokens`, `DELETE /api/v1/mcp-tokens/{id}`.
Connecting Claude chat or Duet with one: `docs/claude-connectors.md`.

Read-only research tools (48): `qs_research_company_snapshot`, `qs_research_macro_snapshot`,
`qs_research_market_brief` (one-call data for those questions, `briefs.py`; the server also serves the prompts
`company_snapshot`, `macro_outlook`, `market_brief` and `portfolio_review` through `prompts/list` and `prompts/get`,
the method to follow for each, `mcp_prompts.py`), `qs_research_portfolio_risk`, `qs_research_portfolio_optimize`,
`qs_research_correlation`, `qs_research_sector_screen` (holdings and sector tools, after upstream FST engine 1.x;
`portfolio_api.py`), `qs_research_bounce_read`, `qs_research_katy_forecast`, `qs_research_options_iv`, `qs_research_news`, `qs_research_my_trades`, `qs_research_my_pnl` (the signed-in member's own trades and P&L, FST vs manual; OAuth sign-ins only, `member_trades.py`), `qs_research_get_idea`, `qs_research_list_ideas`,
`qs_research_research_capabilities` (all three below), `qs_research_odte_universe`, `qs_research_signals`,
`qs_research_screen_signals`, `qs_research_signal`,
`qs_research_recent_signals`,
`qs_research_trend_signal`, `qs_research_list_reports`,
`qs_research_get_report`, `qs_research_ticker_timeline`,
`qs_research_strategist_scan`, `qs_research_strategist_analyze`,
`qs_research_ticker_flow`, `qs_research_gex_snapshot`,
`qs_research_dark_pool_levels`, `qs_research_trade_readiness`,
`qs_research_prediction_markets`, `qs_research_prediction_market`,
`qs_research_prediction_forecast`, `qs_research_prediction_readiness`,
`qs_research_catalyst_board`, `qs_research_smallcap_scan`, `qs_research_turtle_params`, `qs_research_sniperopt_policies`,
`qs_research_term_structure`, `qs_research_ticker_verdict`, `qs_research_team_studies`,
`qs_research_team_roster`, `qs_research_team_take`, `qs_research_team_chair`, `qs_research_research_store` (the Equibles point-in-time research store, `/api/v1/datalake/equibles/*`; service key only), `qs_research_dossier` (a liquid400 name's running dossier, `/api/v1/dossiers/{ticker}`; service key only), `qs_research_swarm` (the analyst swarm's morning idea list, or one name's standing view, `/api/v1/swarm/*`; service key only).
`qs_research_screen_signals` and
`qs_research_signal` are the two hot paths above (top plays, then one play's
full card). The options-flow set (scan, per-ticker analysis, raw flow, GEX walls,
dark-pool prints) is also exposed individually. `qs_research_recent_signals` reads the published
QS Copilot / scheduled signal rows (compact levels, 0-1 confidence, one-line
thesis; targets are model output), also at `GET /api/v1/signals/recent`. Each returns the same
brand-scrubbed payload as its REST counterpart.

### Research-idea tools (run research like the Lab page)

Five more tools let an agent test a trading idea in plain language, the way a
member does at `/terminal/?view=lab`. Add the server to Claude Code with:

```bash
claude mcp add --transport http qs-research https://research.quantsignals.xyz/mcp \
  --header "X-API-Key: $QS_API_KEY"
```

| Tool | Use it to | Auth |
|---|---|---|
| `qs_research_research_capabilities` | Read what the engine can and cannot test (rule vocabulary, data coverage, refusals, 6 example phrasings). Call it first. | read-only |
| `qs_research_ask` (`text, wait_seconds=20`) | Submit an idea and wait up to 20 s. Returns within 20 s: if `ready` is false, poll `qs_research_get_idea`. The one-liner. | `X-API-Key`; not read-only |
| `qs_research_submit_idea` (`text`) | Submit an idea and return its id at once (queue several in parallel). | `X-API-Key`; not read-only |
| `qs_research_get_idea` (`id, wait_seconds=0..20`) | Fetch state, member answer and pitch memo; optional server-side wait (clamped to 20 s, the gateway limit). Poll with `wait_seconds=20` until `ready` is true. | `X-API-Key`; read-only |
| `qs_research_list_ideas` (`limit, verdict_kind`) | Recent ideas with verdicts (`edge`, `near_miss`, `no_edge`, `waiting`). | `X-API-Key`; read-only |
| `qs_research_ticker_verdict` (`ticker`) | The research's overall verdict on one ticker: stance, weighted net, and every study and seat behind it. | read-only |
| `qs_research_team_studies` (`days`) | The studies the team started on its own, by day: rule, why today, backtest, status, forward record. | read-only |
| `qs_research_team_roster` | The team's seats (id, style, status, forward record). Use an id with `qs_research_team_take`. | read-only |
| `qs_research_team_take` (`seat_id, topic, ticker, others`) | One seat's take in a group session, with its stance. Call per seat with no `others` for blind takes, again with the others' takes for a reply round. | runs a model; changes nothing |
| `qs_research_team_chair` (`topic, ticker, takes`) | The chair's summary, the count (done in code) and `test`, one rule to send to `qs_research_ask`. | runs a model; changes nothing |

**Sharing one result (REST).** An idea is private to its author. `POST /api/v1/lab/ideas/{id}/share` (the author,
the owner or the service key; an answered idea only) mints an unguessable link and returns the idea with
`share: {token, path, created_at}`; `DELETE` on the same path revokes it, and sharing again makes a new link.
Anyone holding the link can read the result and nothing else: the page is `GET /lab/s/{token}`, its report is
`GET /lab/s/{token}/report.pdf`, and the same view as JSON is `GET /api/v1/lab/shared/{token}` (no credential;
404 once revoked). The view carries the idea's words, how it was tested, the verdict, the key numbers, the curve
when there is one and the limits, never the author, an account or the idea id.
`GET /api/v1/lab/ideas/{id}/report.pdf` is the same PDF for the author without sharing.
The result reads as a strategy tear sheet (cover, hypothesis, method, results, robustness, limitations, memo):
`GET /api/v1/lab/ideas/{id}/tearsheet` returns it for the author as `{html, css}`, the same report the share page and
the PDF show; the JSON view carries its parts under `report` (`kpis`, `spec_card`, `gates`, `method`, `memo`, `signal`).

Submitting needs the API key in the `X-API-Key` header of the MCP request, the
same header the `/api/v1` routes accept; without it the tool returns an error
that names the key. The service key sends an idea straight to the queue; a
signed-in member's idea (Bearer token) waits for owner approval, and a caller
reads only their own ideas. One idea takes about 30-60 seconds, but a call returns within 20 s: `qs_research_ask` returns `{"id", "state", "ready": false, "next": ...}` (a normal result, not an error) when the answer is not ready, and you poll `qs_research_get_idea` with `wait_seconds=20`. Every answer is
**exploratory** (`trial.recorded: false`, "Exploratory backtest, not a
pre-registered test"): the years after the discovery span are held out and never
read, the verdict is `descriptive` or `underpowered` and never pass or fail, and
a good result is a lead to pre-register, not proof. Research only: nothing here
places an order.

```bash
curl -s https://research.quantsignals.xyz/mcp \
  -H 'content-type: application/json' -H "X-API-Key: $QS_API_KEY" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"qs_research_ask","arguments":{"text":"Buy SPY at the next open after a close where RSI(2) is below 5, and sell after 1 day.","wait_seconds":20}}}'
```

```bash
# Discover tools
curl -s https://research.quantsignals.xyz/mcp \
  -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# Call a tool
curl -s https://research.quantsignals.xyz/mcp \
  -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"qs_research_screen_signals","arguments":{"limit":10}}}'
```

Result envelope: `{"content":[{"type":"text","text":"…"}],"structuredContent":{…},"isError":false}`.

## Signal families & the uniform read (canonical)

Discover every family from one catalog:

```bash
curl https://research.quantsignals.xyz/api/v1/signals/families
```

Each record carries a canonical `brand_id` and a `signals_url`, so you never
special-case per-family URL shapes. The canonical, uniform way to read ANY
family's signals is:

```bash
curl https://research.quantsignals.xyz/api/v1/signals/{brand_id}
```

| brand_id | reads |
|---|---|
| `qs-research` | latest research signals |
| `trend` | deterministic daily trend evidence |
| `strategist` | options-flow scan (the unified CF family) |
| `katy` | Katy price predictions |
| `gurus` | guru signals |
| `news-spread` | news-spread credit signals |
| `recoup` | market-recovery signal |
| `fst-trader` | cached FST Trader signals |
| `btc-weekend` | weekend BTC Kalshi stance |
| `qsr` | validated QSR research policies |

`qsr` is the one public family: its findings are the product's marketing
surface (all `research_only`, display/report only), so its uniform read
requires no credential and no premium tier. Every other family keeps the
premium gate exactly as-is.

Retired wire ids still resolve during the migration soak (`FST Trader` →
`fst-trader`, `strategist_QS Options Flow` → `strategist`). The older per-family
paths (`/news-spread/signals`, `/recoup`, `/prediction/btc-weekend`,
`/api/gpt-trader/signals`) keep serving but now return a `Deprecation` header
with a `Link` to their `/api/v1/signals/{brand_id}` successor — prefer the
uniform route in new integrations.

## Endpoints

### Health Check

```bash
curl https://research.quantsignals.xyz/api/v1/health
```

Response:
```json
{"data":{"status":"healthy","version":"1.0.0","auth_enabled":false,"reports_count":429}}
```

The existing keys remain stable. `data.readiness` adds dependency details for
the report store/index, hot-path cache, and market-data flow clock. For the same
payload on an explicit readiness URL:

```bash
curl https://research.quantsignals.xyz/api/v1/health/readiness
```

Dependency states are `ready`, `warming`, or `unavailable`; the aggregate
readiness state is `ready`, `partial`, or `unavailable`. No credentials,
provider names, filesystem paths, or secret values are exposed.

### Trade Readiness (cached-only)

```bash
curl https://research.quantsignals.xyz/api/v1/trade-readiness/AAPL
```

Joins the latest saved report, the current cached flow row, any still-live
cached signal card, and deterministic consensus diagnostics. It never starts a
research run, fetches missing market data, connects to brokerage, previews an
order, or submits an order. `missing_requirements` explains why a ticker is not
ready; `next_allowed_action` is one of `run_research`,
`wait_for_market_data`, `review_research`, or `paper_preview`.

### Run Analysis

Start a multi-agent research analysis. Each ticker is rate-limited to once per 24 hours.

Crypto is asset-aware. Common USD pair forms such as `BTC/USD`, `BTCUSD`,
`BTCUSDT`, and `BTC-USDT` normalize to the canonical Yahoo symbol `BTC-USD`.
Crypto runs use the market, social, and news analysts plus the normal debate,
trader, and risk teams; the equity fundamentals analyst is removed
automatically.

```bash
curl -X POST https://research.quantsignals.xyz/api/v1/analysis \
  -H "Content-Type: application/json" \
  -d '{"ticker":"AAPL","analysis_date":"2026-06-21","research_depth":1,"analysts":["market","social","news","fundamentals"]}'
```

Response (job accepted):
```json
{"data":{"jobId":"abc123...","status":"queued"}}
```

Response (rate-limited):
```json
{"data":{"status":"recent_report_exists","report":{...},"message":"AAPL already has a saved report from the last 24h."}}
```

### Check Job Status

Poll for completion. Jobs typically take 3–10 minutes.

```bash
curl https://research.quantsignals.xyz/api/v1/analysis/{jobId}
```

Response (running):
```json
{"data":{"status":"running","progress_label":"Running multi-agent analysis"}}
```

Response (completed):
```json
{"data":{"status":"completed","result":{"ticker":"AAPL","rating":"Overweight","report_url":"/api/v1/reports/AAPL_..."}}}
```

### Cancel Job

```bash
curl -X POST https://research.quantsignals.xyz/api/v1/analysis/{jobId}/cancel
```

### Check Active Job

Returns a running/queued job for a ticker (if any):

```bash
curl "https://research.quantsignals.xyz/api/v1/analysis/active?ticker=AAPL"
```

Response (active):
```json
{"data":{"jobId":"abc123","status":"running","progress_label":"Running...","created_at":"2026-06-21T04:12:13Z"}}
```

Response (none):
```json
{"data":{}}
```

### List Signals

Returns completed signals sorted by conviction then freshness. Filter strictly by exact ticker match.

```bash
curl "https://research.quantsignals.xyz/api/v1/signals?limit=20&page=1"
curl "https://research.quantsignals.xyz/api/v1/signals?ticker=AAPL"
```

Parameters:
- `ticker` (optional) — exact ticker filter (case-insensitive), applied BEFORE pagination
- `limit` (1-500, default 20) — max results per page
- `page` (1+, default 1) — page number

Note: `ticker` filters by exact symbol match. If the ticker has a signal, it's returned regardless of ranking position.

### Get Report

Full report with stages and agent memos.

```bash
curl https://research.quantsignals.xyz/api/v1/reports/{runId}
```

### List Reports

```bash
curl "https://research.quantsignals.xyz/api/v1/reports?limit=20&page=1"
```

### Delete Report

```bash
curl -X DELETE https://research.quantsignals.xyz/api/v1/reports/{runId}
```

### Ticker Timeline

```bash
curl https://research.quantsignals.xyz/api/v1/tickers/AAPL
```

### List Tickers

```bash
curl https://research.quantsignals.xyz/api/v1/tickers
```

### Market Regime

Deterministic market-regime read from SPY daily history — no LLM call, cached ~15 minutes server-side. Use it to gate or scale strategy risk by regime. States: `trend_up`, `trend_down`, `chop`, `stress` (or `unknown` when fewer than 60 sessions are available). Shares its classifier with the signal scorecard.

```bash
curl https://research.quantsignals.xyz/api/v1/regime
```

Returns `{"data": {"regime": "trend_up", "benchmark": "SPY", "features": {"close": …, "sma50": …, "sma50_rising": true, "vol_20d_ann": …, "drawdown_from_20d_high": …}, "asof": "…"}}`.

Additive `context` (2026-11-19, existing fields unchanged): `ma200` (SPY vs its 200-day, RSI(2)), `gamma` (dealer
gamma state, net GEX, modelled flip), `term_structure` (VIX-family shape), `breadth` (liquid400), `credit` (HYG/IEF
proxy, labelled), each with `as_of`/`stale`, and `unavailable` naming any leg that missed its budget.

### Bounce Read (one call: "the index is oversold near its 200-day, what does the evidence say?")

```bash
curl -H "X-API-Key: $QS_API_KEY" https://research.quantsignals.xyz/api/v1/bounce-read/SPY
```

One payload, legs run in parallel under a budget, never starts generation. MCP tool: `qs_research_bounce_read`.

- `verdict`: the MA200 · RSI2 rule's plain answer, `signal` true/false and `text` saying why (long only when the
  close is above its 200-day and RSI(2) is under 5; below the 200-day the rule stands aside).
- `base_rates`: for today's state (above/below the 200-day, RSI(2) under a band of 2/5/10/20/30), every earlier
  separate episode since 2016: `n`, `win_pct`, `mean_pct`, `median_pct`, `worst_pct`, `worst_drawdown_pct` (lowest
  low inside the trade), for exit on the first close above the 5-day average (`sma5`) and a fixed 5-session hold
  (`hold5`), plus the other side of the 200-day for contrast, the `span`, and `label` (always `exploratory`:
  this service's own replay). `study.counted` carries the counted study `index-oversold-bounce` (SPY 1993-2013,
  next-open fills, net): no trial passes; the below-200 / 5-day-exit arm paid on average but failed the
  pre-registered -15% crash line.
- `what_would_change_the_read`: sorted levels: the exact next close that clears the 5-day average and the 200-day,
  the modelled gamma flip, put and call walls.
- `legs`: `ma200` (rule state, `provisional` read with the forming bar during the session), `gex` (walls, flip
  `ladder` and `model` with stated assumptions, stored `history`), `vol` (IV vs RV), `index_vol`, `breadth`,
  `credit`, `regime`, `events`.
- `freshness`: per-leg `as_of` and `stale`; `unavailable`: legs that failed or missed the budget, with the reason.

Building blocks, each its own endpoint:

| Endpoint | What |
|---|---|
| `GET /api/v1/ma200-rsi2/{ticker}` | the rule layer; additive `as_of` (session date), `stale`, `provisional`, `base_rates`, `levels` |
| `GET /api/v1/breadth[?history=1]` | liquid400: % above 5/50/200-day, % at new 20-day closing lows, 252-session percentiles; cache-only (`warming: true` when cold) |
| `GET /api/v1/index-vol` | VIX, VIX9D, VIX3M, VVIX (Cboe closes), term-structure shape, VIX 1y percentile, VIXY/VIXM futures proxy. Each series is `stale` only when behind Cboe's own publish time (VIX9D/VIX3M/VVIX ~17:30 ET, VIX ~21:15 ET); `pending_publish` names a close not out yet. No VX futures curve: no licensed source |
| `GET /api/v1/gex/{ticker}/history` | daily GEX points (spot, net and near-money GEX, walls, flips), written after the close |
| `GET /api/v1/market-events?days=14` | opex (monthly/quarterly), VIX expiration, FOMC, CPI, PPI, NFP, PCE, GDP, large IPO supply |
| `GET /api/v1/vol-edge/{symbol}` | now with `stale` and `spot_check` (spot vs the tape's last trade) |

### QS Trend Signal

Deterministic, versioned daily trend evidence for an equity, ETF, futures,
index, or crypto symbol. The `qs-trend.v1` calculation combines 252-session
own-price momentum, 50/200-session moving-average position, and a prior
55-session channel breakout. It returns transparent component votes, bounded
score/confidence, volatility context, and non-authoritative invalidation
references.

```bash
curl -H "X-API-Key: your-key" \
  "https://research.quantsignals.xyz/api/v1/signals/trend?ticker=SPY"
```

The signal is informational only. Its payload explicitly sets
`authority.execution_authorized` to `false`; FST policy remains responsible for
portfolio-aware decisions, sizing, and any subsequent action.

## Strategist — Options Flow (the unified CF signal set)

Real-time options-flow signals. Unlike the multi-agent analysis (which takes 3-10 min), these are synchronous — results in ~30 seconds. No report is saved to disk; the analysis is ephemeral and fresh each call.

This one family covers the whole options-flow surface: a market-wide **scan**, per-ticker LLM **analysis**, raw per-ticker **flow**, **GEX** (gamma walls), and **dark-pool** prints — one family, one auth.

### Scan Layout (synchronous)

Returns the top tickers sorted by flow signal quality from your active QS Options Flow layout. No LLM call — deterministic scoring based on net directional premium, short-dated pressure, sweep aggression, and noise penalty.

```bash
curl "https://research.quantsignals.xyz/api/v1/strategist/scan?top_n=5"
```

Parameters:
- `top_n` — number of top recommendations (3-20, default 5)
- `limit` — max QS Options Flow rows to scan (100-5000, default 1000)

Response:
```json
{
  "data": {
    "status": "ok",
    "layout": "45dte",
    "tickers_scored": 34,
    "tickers_passing_filter": 15,
    "rankings": [
      {
        "symbol": "ORCL",
        "score": 80.9,
        "direction": "bullish",
        "premium": "$17.00M",
        "net_directional": 17000000,
        "short_dated_net": 17000000,
        "signal": "aggressive call buying",
        "trades": 11,
        "sweeps": 1,
        "dte_profile": "short-dated"
      }
    ],
    "also_scored": [
      {"symbol": "SPY", "score": 7.5, "direction": "neutral", "premium": "$37.50M", "signal": "mixed / no edge"}
    ]
  }
}
```

### Analyze Ticker (synchronous, LLM-powered)

Fetches a full day's QS Options Flow options flow for a ticker, builds evidence JSON, and calls the QuantSignals Flow Strategist LLM to produce a structured analysis with directional prediction, trade expression, dealer gamma read, and scorecard.

```bash
curl "https://research.quantsignals.xyz/api/v1/strategist/AAPL"
curl "https://research.quantsignals.xyz/api/v1/strategist/SPY?limit=500&min_premium=500000"
```

Parameters:
- `ticker` (path) — symbol to analyze
- `limit` — max trades to fetch (50-2000, default 500)
- `min_premium` — minimum premium filter in dollars (default 0)
- `date_from` — start date YYYY-MM-DD (default: yesterday)
- `date_to` — end date YYYY-MM-DD (default: today)
- `all_expiries` — set to `true` to skip expiry filter

Response:
```json
{
  "data": {
    "status": "ok",
    "ticker": "SPY",
    "date_range": "2026-06-23 -> 2026-06-24",
    "total_trades": 100,
    "total_premium": "$132.84M",
    "analysis": "# Next-Day Flow Prediction\n\nTicker: SPY\n...",
    "context": { "... evidence JSON ..." }
  }
}
```

The `analysis` field contains the full markdown report with: Executive Decision, Flow Verdict, Highest-Signal Trades table, Bull/Bear Cases, Noise/Trap Check, Dealer/Gamma Read, Final Signal, Scorecard, and One-Line Alpha Thesis.

### Raw Ticker Flow (synchronous, no LLM)

Raw options flow for one ticker — trade clusters, premium breakdown, and top trades — without the LLM wrap. Structured data for the agent to reason over.

```bash
curl "https://research.quantsignals.xyz/api/v1/flow/AAPL?limit=1000"
```

Parameters: `limit` — max rows to fetch (100-5000, default 1000).

Top trades include both a full ISO `timestamp` for chart alignment and a
Pacific-time `time` label for display. Trades without explicit buy/sell intent
are classified as `neutral`, not forced into a bullish or bearish bucket.

### Live Options-Flow Chart

The hosted flow chart plots the highest-premium bullish, bearish, and
neutral-intent trades as timestamped markers over intraday candles and
refreshes every 90 seconds:

```text
https://research.quantsignals.xyz/flow-chart/SPY
```

Its combined payload is available to other clients:

```bash
curl "https://research.quantsignals.xyz/api/v1/flow-chart/SPY?period=5d&interval=5m&limit=1000"
```

### GEX Snapshot (gamma exposure)

Dealer gamma positioning for a symbol: call/put walls and net gamma by strike. Matches the FST CLI `qs_gex_snapshot` contract.

```bash
curl "https://research.quantsignals.xyz/api/v1/gex/SPY?sort=abs&limit=30"
```

Parameters:
- `sort` — `abs` | `net` | `strike` (default `abs`)
- `limit` — max strike rows (0-1000, default 30)

### Live GEX Chart

The hosted chart combines intraday candles with the latest GEX snapshot and
refreshes automatically every 90 seconds:

```text
https://research.quantsignals.xyz/gex-chart/SPY
```

Its combined data endpoint is available for other QuantSignals clients:

```bash
curl "https://research.quantsignals.xyz/api/v1/gex-chart/SPY?period=5d&interval=5m&limit=30"
```

The chart uses regular-session Yahoo candles and QS Options Flow's **All
Expiries** semantics. Prefer upstream row tags for call wall, put wall, and
one-day expected-move levels; do not derive replacements when a source tag is
available. Preserve combined tags. `gex.as_of_pt` is the successful CF fetch
time and must remain unchanged when serving a last-good fallback so operators
can detect staleness.

If `QS_API_KEY` is enabled, pass `apikey` in the chart URL fragment; the
page forwards it to refresh requests without storing it.

### Katy Forecast Chart

The user-facing qs-research chart preserves candlesticks and volume while
overlaying Katy's timestamped backtest prediction, `MODEL NOW` boundary, and
forward prediction. Market candles are the visible historical and realized
actual-price layer. Katy remains the upstream data provider; the interactive
chart is hosted only by qs-research:

```text
https://research.quantsignals.xyz/katy-chart/SPY
```

The page defaults to the daily model. Hourly and 5-minute models remain on the
same URL via `?timeframe=hour` and `?timeframe=5min`. The page's five-minute
poll checks for a new signal; it does not change the model production cadence:
daily models run weekly, hourly models run daily, and 5-minute models run on
demand.

Hourly equity candles must match Katy's 04:00-20:00 ET extended session. Build
them from 5-minute extended bars with buckets anchored at 04:00; do not use
Yahoo native 60-minute bars, whose 09:30 regular-session alignment mismatches
Katy. GEX, flow, and dark-pool charts remain regular-session unless their own
source contracts change.

Crypto charts use continuous 24/7 Yahoo candles and retain Katy's crypto
forecast/backtest overlay. QS/Yahoo symbols such as `BTC-USD` are translated
to Katy's `BTC/USD` provider spelling only at the gateway boundary. The
terminal still suppresses equity-only options-flow, GEX, dark-pool, and guru
claims for crypto.

The combined payload supports `5min`, `hour`, and `day` forecast timeframes:

```bash
curl "https://research.quantsignals.xyz/api/v1/katy-chart/SPY?timeframe=hour&max_points=160"
```

If `QS_API_KEY` is enabled, the Katy page accepts `apikey` in its URL fragment
string and forwards it to the combined payload route.

Cash indices use Katy's tradeable ETF proxies (`SPX` to `SPY`, `NDX` to `QQQ`,
`RUT` to `IWM`, and `DJI` to `DIA`) while preserving the requested symbol in
the chart URL.

The complete chart architecture, operational checks, and 2026-07-14 decision
record live in `docs/LIVE_SIGNAL_CHARTS.md`.

### Dark-Pool Levels

Institutional block prints for a symbol: price, size, and premium. Matches the FST CLI `qs_dpool_levels` contract.

```bash
curl "https://research.quantsignals.xyz/api/v1/dark-pool/SPY?limit=30"
```

Parameters:
- `date_from` / `date_to` — YYYY-MM-DD window (default: today PT)
- `limit` — max rows (0-1000, default 30)

### Live Dark-Pool Chart

QS Options Flow returns aggregate dark-pool price levels rather than timestamped
prints, so this chart overlays premium-weighted horizontal levels across the
candle series. Optional dates control the level aggregation window.

```text
https://research.quantsignals.xyz/dark-pool-chart/SPY
```

```bash
curl "https://research.quantsignals.xyz/api/v1/dark-pool-chart/SPY?period=5d&interval=5m&limit=30"
```

For either hosted chart, pass `apikey` in the URL fragment when `QS_API_KEY` is
enabled (for example, `/flow-chart/SPY#apikey=...`). The page removes the key
from the address bar and forwards it in the `X-API-Key` header so it does not
enter server access logs or refresh URLs.

### Additional Signal Charts

QS Research decisions, guru activity, news-driven spreads and validated FST
Trader structures also have hosted charts:

```text
https://research.quantsignals.xyz/research-chart/AAPL
https://research.quantsignals.xyz/guru-chart/AAPL
https://research.quantsignals.xyz/news-spread-chart/FDX
https://research.quantsignals.xyz/fst-trader-chart/AAPL
```

Their combined payloads are `/api/v1/research-chart/{ticker}`,
`/api/v1/guru-chart/{ticker}`, `/api/v1/news-spread-chart/{ticker}`, and
`/api/v1/fst-trader-chart/{ticker}`. The old `/backtest-chart/{ticker}` page is
retired and redirects to `/flow-chart/{ticker}`; `/api/v1/cf-backtest` still
answers. FST chart levels are emitted
only from validated structured option legs or plausible standalone price
levels; model prose and order quantities are never treated as strikes.

## Rate Limits

| Limit | Window | Applies to |
|-------|--------|------------|
| 1 analysis per ticker | 24 hours | `POST /analysis` |
| 1 active job per ticker | concurrent | `POST /analysis` |

## Data Model

```
Signal/Ticker → Report (has stages) → Stage (has items) → Item (agent memo)
```

Each report has 5 stages:
1. **Analyst Inputs** — Market, Social, News, Fundamentals
2. **Research Debate** — Bull, Bear, Research Manager
3. **Trading Plan** — Trader
4. **Risk Debate** — Aggressive, Neutral, Conservative
5. **Portfolio Decision** — Portfolio Manager (final rating)

## Response Format

All endpoints return the standard envelope:

```json
{
  "data": { ... },
  "error": null,
  "meta": { "total": 427, "page": 1, "pageSize": 20 }
}
```

Errors:

```json
{
  "data": null,
  "error": { "code": "not_found", "message": "Report not found" },
  "meta": {}
}
```

## Persistence

Reports are stored on disk and indexed in SQLite. To persist across Railway deploys, mount a volume to `/app/data`. Set `QS_RESEARCH_REPORTS_DIR` to a persistent path if using external storage.

---

## News Spread (NSE) — Credit Spread Signals

News-driven credit spread signals generated by the News Spread pipeline. Scans SP500, filters by price/IV/liquidity, calculates Bull Put / Bear Call spreads, and runs FST engine 5W1H risk analysis.

**Status: under review. No measured edge yet; forward test running until 2027-02-15.** Scored after costs and held to expiration, 482 settled Trade calls (2026-08-01 to 2026-11-10) averaged -1.88% of the capital at risk per trade, 95% interval -9.07% to +4.63%. `pop_pct` and `roi_pct` are a model's win chance and the return at maximum profit; they are not a forecast of profit. Each signal carries `implied_ev_pct`, what those two numbers are worth per trade (win chance x maximum gain - miss chance x maximum loss, after the fee, in percent of the capital at risk), and the response carries a `review` object with the status line and the kill date. Do not present a News Spread row as a positive-expectancy trade.

Since 2026-11 the option-chain snapshot is taken after the open (09:45 New York time or later), and each row records `snapshot_underlying_price`, `snapshot_underlying_at`, `snapshot_chain_at`, `snapshot_session`, `news_read_at` and `news_headlines` (headline ids and publication times, UTC).

### List NSE Signals

Returns all available news spread signals with trade/watch/skip decisions.

```bash
curl https://research.quantsignals.xyz/api/v1/news-spread/signals
```

Response:
```json
{
  "data": {
    "status": "ok",
    "generated_at": "2026-06-27T21:20:39.089493",
    "model": "FST engine-flash",
    "signals": [
      {
        "rank": 1,
        "ticker": "FDX",
        "type": "Bull Put",
        "direction": "bullish",
        "legs": "$305/$300",
        "short_strike": 305.0,
        "long_strike": 300.0,
        "expiration": "2026-07-17",
        "dte": 20,
        "roi_pct": "42.0%",
        "pop_pct": "72.2%",
        "net_credit": "$1.48",
        "max_loss": "$3.52",
        "iv": 31.6,
        "delta": 0.27,
        "score": 30.3,
        "decision": "trade"
      }
    ],
    "analysis": "...",
    "summary": {
      "total_signals": 8,
      "enter": 3,
      "watch": 3,
      "skip": 2,
      "bullish": 5,
      "bearish": 3
    }
  }
}
```

### Get NSE Ticker Signal

```bash
curl https://research.quantsignals.xyz/api/v1/news-spread/signals/FDX
```

Returns the signal matching the ticker if available, or a `no_data` status.

### Trigger NSE Pipeline

```bash
# With a user session this returns the current published book (recomputed: false).
# Only the service key (X-API-Key) recomputes, and only during the regular session.
curl -X POST https://research.quantsignals.xyz/api/v1/news-spread/run
```

Runs the full News Spread pipeline (FST engine analysis, credit spread scoring). May take 1-5 minutes.

### NSE Measured Performance

```bash
curl https://research.quantsignals.xyz/api/v1/news-spread/performance
curl -X POST https://research.quantsignals.xyz/api/v1/news-spread/settle  # service key only
```

What the engine's published spreads actually did, held to expiration: win
rate, realized ROI and P&L per contract, and `pop_overstatement_pts` — how
far the published probability sat above the measured win rate. Cut by
decision tier, direction, short delta, DTE and ticker, each with its own
trade count, so a three-trade bucket is never mistaken for evidence. The
POST scores every expired prediction not yet in the ledger and is
idempotent; a settled trade is never restated.

An empty result means nothing has settled yet — not that the engine has no
losses.

---

## Recoup — Market Recovery Signal

3-step LLM recovery planner for positions in drawdown. Fetches equity market data, runs FST engine analysis, and produces recovery recommendations.

### Get Latest Recoup Signal

```bash
curl https://research.quantsignals.xyz/api/v1/recoup
```

Response:
```json
{
  "data": {
    "status": "complete",
    "timestamp": "2026-06-28T07:02:52.003585",
    "target": 10000.0,
    "timeframe_days": 1,
    "market_data": {
      "market": {
        "SPY": { "price": 728.99, "prev": 734.3, "change": "▼ -0.72%" },
        "QQQ": { "price": 706.52, "prev": 716.38, "change": "▼ -1.38%" }
      },
      "movers": [],
      "options": {}
    },
    "llm_output": "...",
    "duration_seconds": 45.2
  }
}
```

### Trigger Recoup Run

```bash
curl -X POST https://research.quantsignals.xyz/api/v1/recoup/run
```

Initiates a fresh 3-step recovery analysis. May take 1-3 minutes to complete.

---

## FST Trader — Options Trading Signals

LLM-powered options trade signal generator using Alpaca market data + FST engine. Produces structured trade recommendations with direction, confidence, strategy, strikes, and entry/stop/target levels. Auth is separate from the v1 API key — uses Supabase JWT for write endpoints.

### Health

```bash
curl https://research.quantsignals.xyz/api/gpt-trader/health
```

### List Tickers

```bash
curl https://research.quantsignals.xyz/api/gpt-trader/tickers
```

Response:
```json
{
  "data": {
    "tickers": ["AAPL", "NVDA", "TSLA", "AMZN", "META"],
    "total": 16
  }
}
```

### Analyze Ticker (POST)

Generates a fresh options trade analysis for a ticker. Runs in the background
(the LLM pass takes minutes; the gateway reaps requests over 25s), so the
endpoint returns immediately — poll `GET /api/gpt-trader/signals/{ticker}`
for the result.

```bash
curl -X POST "https://research.quantsignals.xyz/api/gpt-trader/analyze?ticker=AAPL" \
  -H "X-API-Key: your-key"
```

Response:
```json
{
  "data": {
    "status": "started",
    "ticker": "AAPL"
  }
}
```

### List All Signals

```bash
curl https://research.quantsignals.xyz/api/gpt-trader/signals
```

Returns all cached FST Trader signals (last analysis for each ticker).

### Get Ticker Signal

```bash
curl https://research.quantsignals.xyz/api/gpt-trader/signals/AAPL
```

Returns the cached signal for one ticker.

---

## Prediction Markets — Generic Kalshi Research

Public, execution-disabled prediction-market discovery:

```bash
curl "https://research.quantsignals.xyz/api/v1/prediction/markets?status=open&limit=100"
curl "https://research.quantsignals.xyz/api/v1/prediction/markets/KXEXAMPLE"
curl "https://research.quantsignals.xyz/api/v1/prediction/markets/KXEXAMPLE/forecast"
curl "https://research.quantsignals.xyz/api/v1/prediction/markets/KXEXAMPLE/readiness"
```

`GET` routes never start generation. An explicit
`POST /api/v1/prediction/markets/{ticker}/forecast` starts research only when
`MIROFISH_OFFLINE_URL` points to a separately deployed compatibility sidecar.
Stock MiroFish-Offline does not expose the QS forecast contract directly: the
sidecar must orchestrate its graph/simulation/report workflow and return
normalized complementary YES/NO probabilities. QS Research imports no AGPL
code, and every forecast/readiness payload carries `execution_authority:false`.
There is intentionally no MCP tool for starting a forecast.

## BTC Weekend — Kalshi Event Stance

Weekend BTC directional stance for Kalshi event contracts: a three-gate decision (Friday IBIT options-flow direction, decay/invalidation vs live spot, and fair-value edge net of fees). Returns `LONG_YES` / `LONG_NO` / `STAND_DOWN` — `STAND_DOWN` unless all three gates pass.

### Get Stance

```bash
curl https://research.quantsignals.xyz/api/v1/signals/btc-weekend
```

The legacy alias `/api/v1/prediction/btc-weekend` still serves (deprecated — carries a `Deprecation` header pointing at the uniform route).

### Recompute Friday Snapshot (POST)

Rebuilds the Friday IBIT options-flow snapshot the stance reads from.

```bash
curl -X POST https://research.quantsignals.xyz/api/v1/prediction/btc-weekend/snapshot
```

### Calibration

Brier calibration summary — the model-beats-market gate history that unlocks live authority.

```bash
curl https://research.quantsignals.xyz/api/v1/prediction/btc-weekend/calibration
```

---

## Universes

### List Universes

```bash
curl https://research.quantsignals.xyz/api/v1/universes
```

Returns available ticker universes with their constituent symbols.

### Scan Universe

Score and rank all tickers in a universe by multi-agent analysis.

```bash
curl -X POST https://research.quantsignals.xyz/api/v1/universe-scan \
  -H "Content-Type: application/json" \
  -d '{"universe": "sp500", "max_tickers": 10}'
```

---

## Backtests

### Run Backtest

```bash
curl -X POST https://research.quantsignals.xyz/api/v1/backtests \
  -H "Content-Type: application/json" \
  -d '{"ticker": "AAPL", "period": "1y"}'
```

### Check Backtest Status

```bash
curl https://research.quantsignals.xyz/api/v1/backtests/{jobId}
```

### QS Options Flow Backtest

Options flow backtest for a ticker. Simulates trading based on QS Options Flow signal entries.

```bash
curl "https://research.quantsignals.xyz/api/v1/cf-backtest?ticker=SPY&min_premium=100000"
```

Response:
```json
{
  "data": {
    "status": "ok",
    "ticker": "SPY",
    "date_range": "2024-10-17 -> 2025-01-15",
    "parameters": {
      "min_premium": 100000,
      "target_pos_pct": 0.25,
      "starting_balance": 100000.0
    },
    "results": {
      "final_balance": 98510.0,
      "total_return_pct": -1.49,
      "win_rate_pct": 53.4,
      "total_trades": 58,
      "sharpe_ratio": -0.12
    }
  }
}
```


## Per-stock dossiers and event triggers (service key only)

One running dossier per liquid400 name, rebuilt nightly (19:30 PT) and, through the session, whenever EDGAR shows a
new filing for the name or the news reader marks a fresh material company read (poll every 20 minutes, 04:00-17:00 PT on weekdays; the name's analyst re-reads it at once). Sections:
`levels`, `filings` (45 days), `insiders` (open-market, 90 days), `calls` (last/next call, newest brief, themes,
guidance; Data by Equibles), `news` (reader reads, 7 days), `thesis` (QS weekly report). Each section names its
`source` and `fetched_at`; `version` rises when the content changes. A change becomes an event with `observed_at`
(real time) and `source_at`, and queues the name for a committee seat run once per New York session.

- `GET /api/v1/dossiers/{ticker}` (`?history=true` adds versions) · MCP `qs_research_dossier`
- `GET /api/v1/dossiers/events?day=YYYY-MM-DD&ticker=` · `GET /api/v1/dossiers/queue?session=YYYY-MM-DD`
- `POST /api/v1/dossiers/queue/taken` `{"tickers": [...]}`: a committee run marks the names it ran
- `GET /api/v1/dossiers`: coverage, recent passes (vendor requests per source, model calls), the queue
- `POST /api/v1/dossiers/run?kind=nightly|poll`: start a pass now

A dossier builds with no model call of its own; it is evidence for a seat, not a forecast and not a trade signal.


## The analyst swarm (service key only)

One analyst agent per liquid400 name. After each nightly dossier rebuild (19:30 PT), and again at 05:40 PT on weekdays,
every name whose dossier changed gets a new typed view: `side` (long / short / none), `conviction` 0-1,
`horizon_sessions`, `catalyst`, `invalidation`, two `reasons` that cite dossier items. Beside it, computed and not
model-written: the QS signal families that agree or disagree on the name with each family's measured 90-day
next-day hit rate, and the swarm's own scored record for views of that side and conviction band. Every view is
logged with the close it saw and scored at its horizon against SPY.

- `GET /api/v1/swarm/ideas`: the morning list (top long and short, the views that flipped, coverage) · MCP `qs_research_swarm`
- `GET /api/v1/swarm/{ticker}`: the standing view with its dossier
- `GET /api/v1/swarm/desk`: the morning's sector leads (one per sector with 3+ views: stance, leaders, laggards, crowding) and the macro strategist (risk on/off, side to lean, what to avoid, today's events from trend, gamma, vol term structure, breadth, credit and the macro calendar). The PM reads both
- `GET /api/v1/swarm/sheet`: the day's trade sheet. One portfolio-manager call (`QS_SWARM_PM_MODEL`) over the top 20 candidates a side, the index backdrop, the open book and the scored record picks at most 10 trades and says what it passed on; a code risk gate (10 new a day, 40 open, 12 names net, one position a name, candidates only) drops what breaks a limit. Falls back to the ranking when the call fails
- `GET /api/v1/swarm/book`: the swarm's paper book beside FST Live (top ideas each morning at the open, 2% of NAV a position, held to the horizon or until the analyst changes its view; no broker)
- `GET /api/v1/swarm`: recent passes (tokens, cost) and the scored record · `POST /api/v1/swarm/run`: a pass now

Research, not a trade signal and not advice: say so whenever a view is shown.

## Member data in tests and checks (Henry, 2026-12-03)

Tests, fixtures and production smoke checks use synthetic or dedicated test accounts only. Never copy a real member's
user id, orders, fills, balances or P&L into a test, a fixture, a recorded response, a log or a JSON file, and never
run a member-data tool (`qs_research_my_trades`, `qs_research_my_pnl`, `/internal/v1/member-read`) against a real
member to verify a change: sign in as the QS test member (see qs-brokerage-backend AGENTS.md, "Test member") and
check that. Output of such a check stays in memory or the terminal; delete any file that captured it.
