# Drive the app from a program or an AI agent

> Automate the Market Data Visualizer from a script or AI agent via window.Structure.marketDataVisualizer to add files, inspect layouts, run SQL and read CME replays.

Page: https://structure.fi/tools/market-data-visualizer/guides/drive-the-viewer/

Open in the Market Data Visualizer: https://structure.fi/tools/market-data-visualizer/app/#open?article=drive-the-viewer

The Market Data Visualizer exposes one page-level API, `window.Structure.marketDataVisualizer`, for scripts and AI agents driving a browser. Every call executes through the same action pipeline and history as a user click—adding files, opening layouts or Parquet tables, running SQL, stepping a replay, and reading what every pane shows—so the window updates live.

Give your agent [the skill file](https://structure.fi/tools/market-data-visualizer/skill.md) for the complete guide, and consult [the TypeScript declarations](https://structure.fi/tools/market-data-visualizer/app/viewer-api.d.ts) for exact method, action, and return types.

## Three ways to connect

Each evaluates JavaScript in the Market Data Visualizer tab and receives JSON back:

- **Playwright:** `page.evaluate(() => window.Structure.marketDataVisualizer.hello())`.
- **Chrome DevTools MCP:** pass functions directly to `evaluate_script`; Claude Code (`claude --chrome`) can call the API in your open Chrome via the Claude in Chrome extension.
- **Raw Chrome DevTools Protocol:** call `Runtime.evaluate` with `window.Structure.marketDataVisualizer.hello()`, `awaitPromise: true`, and `returnByValue: true`.

Start with `hello()`: it returns the build id, every supported action/command, and API limits. Every method except `metrics()` returns a promise, and failures return `{ ok: false, error: { kind, message } }` instead of throwing.

Calls always address targets explicitly—never "whatever is active"—using project keys, file node ids, and pane ids from `state()`. Commands take `{ pane }` or `{ project }` as declared by `hello()`.

## Example: query a Parquet file

Run all three steps inside one page evaluation:

1. Read the `.parquet` file locally and base64-encode its bytes.
2. Call `api.addFiles([{ name: "trades.parquet", bytes: parquetBase64 }], { project: { kind: "new", name: "Trades" } })` to create a project and get its key. Each file becomes a SQL view named after the file without its extension (`trades`).
3. Call `api.sql("SELECT count(*) AS trades, max(price) AS high FROM trades", { project: added.project })` to execute in the project's SQL console and return columns and rows.

To inspect an SBE schema instead, add the XML file, call `messages({ project, file })` to map message names to paths (such as `m46` for [`MDIncrementalRefreshBook46`](https://structure.fi/tools/market-data-visualizer/app/#open?sample=cme-mdp3-schema&node=m46&place=text&guide=drive-the-viewer&section=example-query-a-parquet-file)), open its layout, and read it with `rows()`.

A CME capture's replay reads the same way. Its books live in the capture's replay pane, not the dock: `state().state.replays[project].books` lists them by id, and `rows(bookId)` answers a book's ladder, one row per price with each side's order count, size, implied size and order blocks front of the queue first, with the book's replay message, best bid and ask in ticks, the tick, the match algorithm and any pinned order card. The replay pane's other parts have reads of their own: `instruments({ project })` lists every instrument with what its card shows, `fills({ project })` the Fills pane's fills with each one's queue place and allocation step, `matches({ project })` the Filter's matches, `captureMessage({ project })` the Message pane's tree, and `feeds({ project })` the files, flows and gaps. CME sends a trade before the book updates that fill its orders, so a trade's fills show at the end of its event: `fills({ project, message })` with a trade's message lands there, opens a book of its instruments when none shows, and answers them, each fill's `trade` the trade message and its `message` the book update. Move the replay with `replay.seek` and `replay.step` intents, `goTo({ project, text })` as the Go to field takes it, or `command("replay.nextMatch", { project })` from one filter match to the next, and read again.

## Events, the whole ladder and play

- **Events table:** `eventsTable({ project })` writes a CME capture's events as one Parquet table, as Views → Events does, and answers `{ node, path, written, view, table }`; a second call answers the same file with `written: false`. Then `sql("SELECT … FROM events …", { project })` reads it: `SELECT message, sending_time, qty, display_price FROM events WHERE kind = 'trade' AND symbol = 'ESZ6' ORDER BY qty DESC LIMIT 1` finds the largest trade, and `fills({ project, message })` with its message lands on its event and answers its fills.
- **The whole ladder:** `rows(bookId)` with no window answers the rows on screen, plus `high`, `low`, `total`, `first` and `more`. Row 0 is `high`, the highest price the book holds anything at, so `rows(bookId, { start, count })` with `{ start: 0, count: 50 }` reads from the top and with `{ start: high - p, count }` from price `p` ticks down, at most `hello().limits.ladderRowsMax` (512) rows at once; `more` says rows below the last one answered still hold the book.
- **Play:** `dispatch({ type: "replay.speed", project, rate: { value: 50, unit: "steps" } })` sets the speed, and `dispatch({ type: "replay.play", project })` answers once play has started. While it plays, `state().state.replays[project].message` and `state().replays[project]` read where it is (`message`, `time`, `playing`) and `state().pending` lists `{ kind: "playing", project }`. `await settled()` waits for play to reach the captures' end; `command("replay.playPause", { project })` stops it where it has reached.

## Drive your existing Chrome window

1. In Chrome 144+, open `chrome://inspect/#remote-debugging` and enable "Allow remote debugging for this browser instance" ([Chrome's announcement](https://developer.chrome.com/blog/chrome-devtools-mcp-debug-your-browser-session)). Note that `--remote-debugging-port` no longer works on your default profile as of Chrome 136 ([Chrome's post](https://developer.chrome.com/blog/remote-debugging-port)).
2. Connect via Playwright (`chromium.connectOverCDP`) or `chrome-devtools-mcp --autoConnect` to `ws://127.0.0.1:9222/devtools/browser`, then approve Chrome's prompt.

Because agent actions land in your live tab and history, instruct the agent to create its own project, scope calls to that project, and delete it when done.

## Saved projects, links and settling

- **Saved projects:** persisted projects from earlier visits appear as `saved` in `state().projects` until opened. Any read call activates them automatically, or dispatch `project.activate` explicitly.
- **Hash links:** navigating or updating the hash to `#open?project=CME&file=cme-mdp3.xml&node=m46&place=layout` (or `#open?sample=cme-mdp3&instrument=SR3Z6-SR3H7&message=8195`) opens that target (note the key is `node`, not `path`). The link opens after the script returns: call `await settled()` before reading what it opened.
- **Settling:** mutating calls resolve once resulting reads, writes, SQL runs, and pane row updates finish, so an immediate `rows()` or `state()` sees the new view. Pass `{ settle: "applied" }` to return immediately or `{ settle: "painted" }` to also wait for the next painted frame. Calls time out at `hello().limits.settleMs` returning `timed_out` (applied changes remain applied). Work no call started (a link, a capture's indexing, a replay playing) shows in `state().pending`, and `settled()` waits for it.
- **Argument shapes:** `hello().intents` gives each intent's fields, their docs and an `example`, and `hello().types` writes out every type they name (`SeekTarget`, `ReplayUnit`); a refused intent answers `invalid_intent` with the `expected` shape and an example.
- **Refusals:** a value outside a closed set is refused with the set's values (`"msg" is no SeekTarget; these are: message, time, nextFor`), and an unknown intent type or command id with those of its group. A `replay.filter` that does not parse answers `bad_argument` with the Filter field's own message, the value's `path` and the `span` it marks, and nothing applies. An intent the page dispatches itself (`pageOnly` in `hello().intents`, such as `replay.events`, which records the events file the page wrote) answers `invalid_intent` with `problem: "page_only"` and names the call to make instead, here `eventsTable({ project })`.
- **Notes:** `dispatch` answers `notes` beside what it applied: a `replay.seek` past the captures' last message lands on it, with `{ kind: "clamped", landed }`.
- **SQL errors:** a `sql_error`'s message is DuckDB's text, such as `Parser Error: syntax error at or near "SELEC"`.

## Limits and privacy

- **No remote fetches:** `addFiles` accepts URLs only on the Market Data Visualizer's own origin. Fetch remote or disk files on your side and pass base64 bytes.
- **User-gesture commands:** clipboard and native file-picker commands return `needs_user`; read via `rows()` and `state()`.
- **Large local files:** `addFiles` sends bytes whole across the automation channel. For large disk files, call `command("project.addFile", { project })` to open the dialog and attach the file with your tool (e.g. Playwright's `setInputFiles`) so the app reads it in chunks without copying it whole.
- **Row caps:** `sql` returns at most 10,000 rows, `rows()` at most 1,000 rows per call and at most 512 of a book's ladder.

Files stay in your browser; the site has no upload endpoint. Aside from optional usage counts (disable in Settings), turning on **Offline mode** (Settings or `command("offline.on")`) stops all network traffic and runs from a cached local copy, SQL included (`state().offline` reports readiness).

## Sources

- https://playwright.dev/docs/evaluating
- https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/tool-reference.md
- https://code.claude.com/docs/en/chrome
- https://chromedevtools.github.io/devtools-protocol/tot/Runtime/
- https://developer.chrome.com/blog/chrome-devtools-mcp-debug-your-browser-session
- https://developer.chrome.com/blog/remote-debugging-port
- https://github.com/microsoft/playwright/issues/40027

Reviewed by Structure on 2026-11-12. Last changed 2026-11-26.
