---
name: market-data-visualizer
description: Drive Structure's Market Data Visualizer (SBE schemas, Parquet files, SQL over them, CME capture replays) from a program through its in-page API `window.Structure.marketDataVisualizer`, called with browser automation (Playwright, Chrome DevTools MCP, CDP). Use to open market-data schemas and read message layouts, add files, run SQL, replay CME captures and read their books, fills, cards and messages, wait for the GUI to settle, and export a capture for a bug report.
---

# Driving the Market Data Visualizer

Structure's Market Data Visualizer is a web app that reads market-data schemas (SBE XML, such as
CME MDP 3.0) and Parquet files: message layouts with every offset and size, file layouts, column
statistics, and SQL (DuckDB) over Parquet files.

Below, `<tool>` stands for the tool's address: the address this skill was served from, without
`/skill.md` (on structure.fi it is `https://structure.fi/tools/market-data-visualizer`).

The files are read by code running in the browser; the site has no endpoint that accepts them.
The only thing the page sends is usage counts, to `<tool>/api/metrics`, unless they are turned
off in the settings. With offline mode on (`command("offline.on")`; `state().offline` tells
whether its copy is ready) it sends nothing and loads nothing from the site, and every method
works with no network.

A program drives it through one object on the page, `window.Structure.marketDataVisualizer`.
Every change it makes goes through the same paths as a person's clicks and is recorded in the
page's action log, so the GUI shows it and a capture replays it. Everything a person can see in
a pane can be read as JSON, and every command of the palette run by its id.

- The app: `<tool>/app/`. Locally: `just dev` in the repository serves the site's layout, the
  app at `http://localhost:5173/tools/market-data-visualizer/app/`.
- Types of every method, answer and intent: `<tool>/app/viewer-api.d.ts`.
- `await window.Structure.marketDataVisualizer.hello()` names the build, the engines, every
  intent (`hello().intents`) with what it does, its fields and an `example` the page takes, every type those fields
  name written out in `types` (`hello().types`: `types.SeekTarget`, `types.ReplayUnit`), every command, and the
  limits. Read it first: it is everything `dispatch` takes, without the declaration file.
- For a person new to the API: the guide's article `<tool>/guides/drive-the-viewer.md`, a short
  introduction to what this file covers in full.
- To find the article on a topic among the guides and the articles on using the tool: the site's
  search, a plain GET that answers Markdown, each article's page and Markdown and the sections
  that hold the words (`https://structure.fi/guides/search.md?q=matching+algorithm`; `lang=` for
  another language, `format=json` on `/guides/search` for JSON; without `q` it says how).

## Calling it

Every method but `metrics()` returns a promise of plain JSON. A failure is an answer, never a
throw: `{ ok: false, error: { kind, message } }`, `kind` one of a closed set (`invalid_intent`,
`bad_argument`, `unknown_command`, `unavailable`, `needs_user`, `not_found`, `refused`,
`sql_error`, `timed_out`, `failed`). An `invalid_intent` names the `path` of the value refused
and, for an intent type the page has, `expected`: the type's `shape`
(`{ type: "replay.seek"; project: string; target: SeekTarget }`), each type it names written
out, and an `example` to copy. A value outside a closed set is refused with the set's values
(`"msg" is no SeekTarget; these are: message, time, nextFor`); an intent type or command id the
page lacks, with those of the same group (`replay.*`). Values the reader cannot check alone are
checked before anything applies: 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 (`{ start, end
}` in the clause). An intent the page dispatches itself (`hello().intents[].pageOnly`: an
effect's answer such as `replay.events`, or a step of undo, a rewind or a browser move) answers
`invalid_intent` with `problem: "page_only"`, its doc naming the call that does it instead. A
`sql_error`'s message is DuckDB's text (`Parser Error: syntax error at or near "SELEC"` and the
line it points into).

Every call names what it acts on: a project by its key (`state().projects[].key`, never its
name), a file by its node id, a pane by its id (`state().panes[].id`). None acts on whatever
happens to be active. A key or id the page has none of answers `not_found`; one left out answers
`bad_argument`.

A call that changes the app answers once it has **settled**: the work it started (core answers,
store writes, SQL runs, the rows of panes it opened) has ended, so the next `rows()` or
`state()` reads what the GUI shows. `{ settle: "applied" }` answers at once; `effects`, the
default, waits for that work; `{ settle: "painted" }` also waits for the next drawn frame (a
visible tab only). A call waits at most `hello().limits.settleMs`, then answers `timed_out`;
what it applied stays applied. `dispatch` answers `notes` beside what it applied: a
`replay.seek` past the captures' last message (or time) lands on the last one, and its note says
so (`{ kind: "clamped", landed }`).

Work no call started has no call to wait on: a link the page loaded with or a script set
(`location.hash = "#open?…"`), a capture's index pass, its books opening, a replay playing.
`state().pending` lists it (`{ kind: "link" }`, `{ kind: "indexing", project }`, `{ kind:
"books", project }`, `{ kind: "playing", project }`, `{ kind: "work", open }`), and `await
settled()` answers once the list stayed empty for two frames; past `limits.settleMs` it answers
`timed_out` naming what is still under way.

| Method | Does |
| --- | --- |
| `dispatch(intent \| intent[], { settle })` | applies intents (`{ "type": "view.open", … }`, the `Intent` type) as recorded actions; answers their `seqs` and `notes` |
| `command(id, { pane } \| { project })` / `commands()` | runs a palette command by id on the pane or project named, which it makes active first, as a click does; `commands()[].takes` says which it takes, `pane`, `project` or `none` |
| `state()` | projects with their keys, files' paths and node ids, panes with their ids, the whole app state, `pending`: work under way, and `replays`: where each capture's replay is now, playing or not |
| `settled({ settle })` | waits until nothing is under way that no call started: a link opening (`location.hash`), a capture being indexed, its books opening, a replay playing, core calls and SQL runs |
| `rows(pane, { start, count })` | a pane's rows; a book pane answers `{ kind: "ladder" }` with its message, best bid and ask, tick, match algorithm, pinned card and any window of its ladder |
| `eventsTable({ project })` | writes a CME capture project's events table when it has none current (Views → Events), and answers its `node` and the name `sql()` reads it by |
| `messages({ project, file })` | an SBE schema's messages: `{ id, name, path }` each, `path` as a `Root` takes it |
| `instruments({ project })` | a CME capture's instruments as the replay's Instruments column lists them, each with what its card shows |
| `fills({ project, message })` | the replay's Fills pane: each fill of the paused step with its place in the queue and its allocation steps; with `message`, of the event that holds it |
| `matches({ project, start, count })` | the replay's Filter and the messages it matched |
| `captureMessage({ project, message })` | a captured message decoded beside its bytes, as the Message pane's tree shows it |
| `feeds({ project })` | the replay's Feeds: capture files and flows with their packets, duplicates and gaps |
| `goTo({ project, text })` | moves the replay as the Go to field does: a message, a time, `+250us`, `seq 3485 ch 312`, `rpt 812 SR3Z6` |
| `addFiles([{ name, bytes }] \| [{ url }], { project, folder })` | adds files as a drop does, to `project: { kind: "project", key }` or `{ kind: "new", name }`; answers the key; a `url` must be on the page's own origin; a `.zip` adds the SBE schema XML files inside it, as an archive tool unpacks it |
| `sql(query, { project, file, rowsMax })` | runs a statement in the project's SQL console (or the console of Parquet file `file`, a node id), as the Run button does |
| `export(kind)`, `restore(capture)`, `replay(seq)` | captures (`.pvc` as base64) |
| `actions()`, `seek(seq \| "now")`, `rewind(seq)` | the action log (with `causeSeq`), the Timeline |
| `metrics()` | what the page counted since it loaded |

Commands that write the clipboard or open a file picker answer `needs_user`; read with
`rows()` and `state()` instead. Removing a file is a `tree.op` intent and stays undoable
(`command("project.undo")`). `command`'s answer names its `target`; `project.delete` deletes the
project it names without the explorer's confirm.

Intents name their targets in their fields, with a few exceptions that act on what the page
shows: `nav.top` and `nav.front` act on the current place's pane, `addFiles.open` opens the dialog
that adds to the active project (use `command("project.addFile", { project })`), the popup
closers (`palette.close`, `display.close`, `columnMenu.close`) close the one open, and a new pane
(`view.open`, `source.show`, `sql.open`, `status.open`, `guide.open`, `pane.split`) joins the
active group of tabs.

The page fetches nothing from another origin: the site's policy is `connect-src 'self'`, so
`addFiles` answers `bad_argument` for a `url` elsewhere, before any request. For a file on the
web or on disk, fetch or read it on your side and pass its bytes as base64.

## Projects: saved and open

`state().projects[].state` is `open` or `saved`. A project the browser kept from an earlier
visit is `saved` after a load: listed with its files and node ids, but not read yet. An intent
that names a project (`project.activate`, `view.open`, `pane.place`, `source.show`, `sql.open`,
`tree.op`) opens it first, as a click on it in the explorer does; so do `messages`, `sql` and a
command that takes the project. To only open one, activate it (example `open-saved`).

## Ids: nodes and messages

- A file's **node id** is `state().projects[].files[].node`; `addFiles` answers them too. A
  schema is named by its root file's node: an SBE schema's `schema.root` in a `Root` is that
  file's node id.
- A **node path** names a node inside a schema: a message is `m` and its id (`m46`), a group
  `g`, a field `f`, a data field `d` with theirs (`m46/g268/f270`), types sit under `t`
  (`t/PRICENULL9`). `messages({ project, file })` lists a schema's messages with their paths
  (example `message-ids`); `file` is the schema's root file's node id.

## Places

A node `Root` is `{ kind: "node", at: { project, schema, path }, place }`. The places to read
bytes from:

- `layout`: an SBE message's layout, one row per field, group and data with its offset and
  size (example `cme-layout`).
- `bytes`: a Parquet file's layout: its regions with their byte ranges, row groups with their
  column chunks and pages, the indexes and the footer (example `parquet-bytes`).
- The byte map: the same layout drawn as lines of bytes beside its pane. Open it with
  `command("pane.byteMap", { pane })` (Alt+B in the page), `pane` a `layout` or Parquet `bytes`
  pane (example `byte-map`). It has no rows of its own; read the layout pane's.

The others: `declared` (an outline of the schema or node), `table` and `statistics` (a Parquet
file's data and column statistics), `facts` (the detail pane), `uses`, `problems`.

## Replay panes and books

A CME capture project has one replay pane in the dock (`kind: "replay"`, opened by
`replay.open` or a click on the project in the explorer). Its books are not dock panes:
`state().state.replays[project].books` lists them by id, with their layout, the pinned
message and whether the Message pane and instruments column show.

- **Instruments**: `instruments({ project })` lists every instrument of the captures as the
  Instruments column does, each with what its card shows: `security` (the SecurityID intents
  take), `symbol`, `kind`, `exchange`, `group`, `maturity`, `tick` (in the ladder's units) and
  `tickOnWire`, `displayFactor`, `match` (`{ letter: "A", name: "allocation" }`), `legs`,
  `updates`, `firstTrade`, `largestMove`, and the book panes that show it. `card` is the one
  whose card the column shows (`replay.card` opens one).
- **Books**: `book.open` adds a book to the replay pane: `{ type: "book.open", project,
  security, top: null, title: "SR3Z6-SR3H7", follow: "off", tradeColour: "single", implied:
  "hidden", blocks: "shown" }` (`top: null` lets the replay centre it; `hello().intents` gives
  each field); `state().state.replays[project].books` then lists it. `replay.focus` puts one in
  front; `command(id, { pane: bookId })` runs a book command on it. A book answers
  `rows(bookId)` as `{ kind: "ladder", security, message, bestBid, bestAsk, high, low, total,
  first, more, tick, match, card, rows }`. Each row is one price, top down a tick
  apart: `ticks`, the price as a count of the instrument's tick (its definition's
  `MinPriceIncrement`, or the smallest step seen between its prices when the capture has no
  definition), and `price`, the decimal text the pane writes: `ticks` × tick × the definition's
  `DisplayFactor`, so the display units of the venue's quotes (an ES row at `price` `"6851.50"`
  has `ticks` 27406, that many ticks of 0.25, and the ladder's `tick` is `"0.25"`); without a
  definition `price` is in the wire's units. `bestBid` and `bestAsk` are numbers in ticks, like a
  row's `ticks`, not display prices (`null` for an empty side): the best bid's row, when the
  window asked holds it, is `rows.find((row) => row.ticks === bestBid)`, and its `price` is the
  best bid as quoted. Each row has a `bid` and `ask` side with `orders`, `size`, `implied` and
  `blocks`, front of the queue first (`order`, `beforeCapture` or `folded`, with `qty` and
  `count`). The blocks of a book built from empty add up to the side's size and order count. A
  book whose `top` is still `null` answers no rows until it quotes both sides.
- **The whole ladder**: `rows(bookId)` with no window answers the rows the pane shows, however
  few fit its height. The ladder runs from `high`, the highest price the book holds anything at
  (row 0), down to `low`: `total` rows, and the rows on screen start at row `first`. Ask any
  window of it with `rows(bookId, { start, count })`, at most `hello().limits.ladderRowsMax`
  rows at once: `{ start: 0, count: 50 }` from the top, `{ start: high - p, count }` from price
  `p` ticks down; `more` says rows below the last one answered still hold the book. Rows above
  `high` have negative positions.
- **Cards**: `book.pin` pins the card of a block (`{ type: "book.pin", pane, side: "bid", block:
  { kind: "order", order: "<id from the block>" } }`), as a click on it does; `book.unpin` and
  `book.pinMove` close and move it. The ladder's `card` then reads it: for an order its `place`
  in the queue, `state` (resting, left at a message, or absent) and the book's `card` of it
  (`qty`, `firstQty`, `added`, `changed`, `top`: whether it is its side's top order in an
  allocation book and since which message, its `fills`).
- **Fills**: `fills({ project })` answers what the Fills pane lists: the fills of the paused
  step in every book in view, each with the order, contracts `filled` and `rest`, whether it
  `left` the book, its `place` in its queue before the step, and the allocation `steps` that
  gave it (`{ kind: "known", top, proRata, fifo }`; `unallocated` for a book that does not fill
  by allocation). CME sends a trade (its TradeSummary) before the book updates that fill the
  resting orders, so the fills of a trade show at the end of its event, not at the trade's own
  message. `fills({ project, message })` takes any message of the event, such as a trade's
  `message` from the events table or `matches`: it lands the replay on the end of that event,
  stepping from the message before as a link's `message=` does, brings a book of the message's
  instruments into view when none shows, and answers the fills there (`seqs`: the moves it
  recorded). Each fill's `trade` is the trade message that took the contracts and its `message`
  the book update that showed the fill; `trade` is `null` when the step holds the update but not
  the trade (a seek or step straight to the update). With no fill, `books` is empty and `note`
  says why and which call answers them: the replay plays, no book is open, or the step filled
  no resting order.
- **Moving**: `replay.seek` (`target` is a `SeekTarget`: `{ kind: "message", message }`,
  `{ kind: "time", seconds, nanos }` or `{ kind: "nextFor", security }`), `replay.step` (`unit`
  `message`, `packet` or `event`); `state().state.replays[project].message` holds the message.
  `goTo({ project, text })` takes what the transport's Go to field takes and lands where it
  does: `8195`, `14:30:00.5`, `+250us`, a channel's packet `seq 3485 ch 312` or an instrument's
  update `rpt 812 SR3Z6`.
- **Playing**: `replay.speed` sets the rate in its `rate` field:
  `dispatch({ type: "replay.speed", project, rate: { value: 50, unit: "steps" } })` plays 50
  steps a second, `rate: { value: 1, unit: "times" }` real time.
  `dispatch({ type: "replay.play", project })` answers once play has started.
  While it plays, `state().state.replays[project].message` and `state().replays[project]` read
  where play has reached (`message`, `time`, `playing`), though no action records it until the
  replay pauses, and `pending` lists `{ kind: "playing", project }`. To wait for play to reach
  the captures' end, `await settled()`; to stop it where it has reached,
  `command("replay.playPause", { project })`, which records that message (example `replay-play`).
- **Filter**: `replay.filter` sets the Filter's WHERE clause (`kind = trade and symbol =
  SR3Z6-SR3H7`); `matches({ project })` (or `matches({ project, start, count })`) answers its `state`, the `total` matched,
  the cursor's `rank` among them and a window of the matches. `command("replay.nextMatch",
  { project })` and `command("replay.previousMatch", { project })` step to the next or previous
  match as the filter row's ↓ and ↑ do: at the end of the match's event, a book of its
  instruments brought into view. With no match that way the command applies nothing (`seqs` is
  empty).
- **Events table**: every event of the captures as one Parquet table (trades, fills, adds,
  levels) is a file the project holds once written, as Views → Events writes it. Its columns:
  `message`, `packet`, `sending_time` (the packet's SendingTime, a UTC timestamp to the nanosecond),
  `transact_time` (the message's TransactTime, when present), `channel`, `feed`, `template`,
  `security_id`, `symbol`, `kind`, `side`, `price`, `price_ticks`, `display_price`, `qty`,
  `order_id`, `aggressor`, `level`, `orders`. `eventsTable({ project })` writes it, or answers the one
  current with the captures, and answers `{ node, path, written, view, table }`; then
  `sql("SELECT … FROM events …", { project })` reads it. CME tasks that rank or count events (the
  largest trade, an instrument's SecurityID by symbol) start here; `instruments({ project })`
  lists SecurityIDs without it. `replay.events` is what the page records once it wrote the
  file; `dispatch` refuses it (`page_only`). A project's console (`sql.open`, `sql(…)`) writes the table
  itself when it has none current. A result row leads back into the replay with the intents
  the row's links and context menu use in the console: its `message` lands the replay with
  `replay.seek` (`target: { kind: "message", message }`), its `symbol` brings its book forward with
  `book.open`, and an `order_id` with its `side` pins the order's card with `book.pin`
  (`{ pane, side, block: { kind: "order", order } }`) once the replay is on the row's message.
- **Message and Feeds**: `captureMessage({ project, message })` decodes a message as the
  Message pane's tree does (rows with `name`, `value`, `note` and byte range, the record's
  `bytes` in hex); without `message`, `captureMessage({ project })` reads the one the pane shows. `feeds({ project })`
  answers the capture files and flows the index pass read, with each flow's packets,
  `duplicates` and `gaps`.

Captures of schema 0007 and earlier, whose books were dock panes, restore with them moved into
the replay pane under the same ids.

## Links

The address bar names the pane in front as a link, and a link opens a place. A link opens when
the page loads with it, and when the hash changes after load: pasted in the address bar, or set
by a script (`location.hash = "#open?…"`). The grammar (`#open?` then `key=value` pairs joined
by `&`, values percent-encoded):

- `project=<name>`: the project's file list; a saved project opens.
- `project=<name>&file=<path>`: a file of the project, by its path there. `hash=<12 hex digits>`,
  which links the app writes carry, also finds the same file under another path or project.
- `sample=binance-stream`, `sample=binance-spot`, `sample=cme-mdp3-schema` or `sample=trades`: a
  bundled sample (Binance's SBE streams schema, its spot API schema, CME's MDP 3.0 schema, a
  Parquet file of trades).
- `sample=cme-mdp3`: a bundled CME MDP 3.0 capture in its replay pane; with
  `instrument=<symbol or SecurityID>` that instrument's book, and with `message=<n>` the replay
  landed on the end of the event that holds message `n`.
- `article=<id>&heading=<id>`: an article of the guide; `pane=status`: the Status pane.
- With a file or sample: `node=<node path>` (not `path`), `place=<text | symbols | layout |
  bytes | detail | data | stats>`, `select=<node path>` (a row to select), `row=<n>` (a data
  row's display position), `title=<text>`.
- With a sample only: `guide=<article id>` and optionally `section=<anchor>`, the article a link
  sits in and its place there: a heading id, or `block-<n>` for an example. On a wide window the
  app opens that article at the place in the Guide pane along the dock's left edge, beside the
  node; on a phone the article stays behind the node, a Back away.

`place`: `text` and `symbols` show the declaration in that form; `layout` a message's layout;
`bytes` an SBE message's layout with its byte map, or a Parquet file's layout; `detail` the
declaration with the detail pane; `data` and `stats` a Parquet file's data and statistics. A link
with a key the grammar lacks opens nothing and says why on the notice line; the address bar then
names the pane in front again. Links are for people; a program that sets one waits for it with
`settled()` (example `replay-fills`), and opens other places with `view.open`.

## Working in someone's live tab

Every call lands in that person's session: it is recorded in their Timeline and changes what
their window shows. Make a project of your own (`addFiles(…, { project: { kind: "new", name } })`
answers its key), name only it in your calls, leave theirs as they are, and delete yours when
done (example `clean-up`).

## Playwright

```js
const hello = await page.evaluate(() => window.Structure.marketDataVisualizer.hello());
// A file on the web, fetched by Playwright, not the page; one on disk: (await fs.readFile(path)).toString("base64").
const base64 = (await (await page.request.get("https://data.example/trades.parquet")).body()).toString("base64");
const answer = await page.evaluate(([name, bytes]) => window.Structure.marketDataVisualizer.addFiles([{ name, bytes }], { project: { kind: "new", name: "Trades" } }), ["trades.parquet", base64]);
```

For a large local file, open the Add files dialog and use Playwright's own upload; the page
reads the file in ranges and never copies it whole:

```js
await page.evaluate((project) => window.Structure.marketDataVisualizer.command("project.addFile", { project }), answer.project);
await page.locator("input[data-file-picker]").setInputFiles("/data/large.parquet");
```

## The person's own Chrome

To drive a tab the person has open:

1. They open `chrome://inspect/#remote-debugging` in Chrome 144 or later and check "Allow
   remote debugging for this browser instance"
   ([Chrome's post](https://developer.chrome.com/blog/chrome-devtools-mcp-debug-your-browser-session)).
2. Connect to `ws://127.0.0.1:9222/devtools/browser`. The first call waits until they click
   Allow in Chrome's prompt; while attached, Chrome shows that it is controlled by automated
   software.

```js
import { chromium } from "playwright";
const browser = await chromium.connectOverCDP("ws://127.0.0.1:9222/devtools/browser");
const page = browser.contexts().flatMap((context) => context.pages()).find((each) => each.url().includes("/app/"));
```

On macOS an agent cannot read Chrome's `DevToolsActivePort` file under
`~/Library/Application Support/Google/Chrome` (EPERM), and `http://127.0.0.1:9222/json/version`
answers 404 in this mode, so use the address above
([Playwright's issue on it](https://github.com/microsoft/playwright/issues/40027)). The same
switch serves `chrome-devtools-mcp --autoConnect`, whose `evaluate_script` takes each example
below as it stands. Since Chrome 136, `--remote-debugging-port` is ignored on the default
profile ([Chrome's post](https://developer.chrome.com/blog/remote-debugging-port)): it serves
only a Chrome started with a profile of its own. Firefox (WebDriver BiDi) and Safari
(`safaridriver`) run their own automation windows, not the person's tabs. Claude Code's
`claude --chrome` can call the API in their Chrome through the Claude in Chrome extension.

## Any CDP client

`Runtime.evaluate` with `awaitPromise` and `returnByValue`:

```json
{ "method": "Runtime.evaluate", "params": { "expression": "window.Structure.marketDataVisualizer.hello()", "awaitPromise": true, "returnByValue": true } }
```

## Examples

Each is a function to evaluate in the page; its argument is the value passed beside it.

Open CME's schema and read a message's layout (the argument: the schema XML as base64):

<!-- example: cme-layout -->
```js
async (schemaBase64) => {
    const api = window.Structure.marketDataVisualizer;
    const added = await api.addFiles([{ name: "cme-mdp3.xml", bytes: schemaBase64 }], { project: { kind: "new", name: "CME" } });
    if (!added.ok) return added;
    // A message's path is `m` and its id: MDIncrementalRefreshBook46 is m46.
    const at = { project: added.project, schema: { format: "sbe", root: added.files[0].node }, path: "m46" };
    const opened = await api.dispatch({ type: "view.open", title: "MDIncrementalRefreshBook46", form: "symbols", root: { kind: "node", at, place: { kind: "layout" } } });
    if (!opened.ok) return opened;
    const pane = (await api.state()).panes.find((each) => each.active).id;
    return api.rows(pane, { start: 0, count: 20 });
}
```

Find a message by name and open its layout (the argument: the project's key):

<!-- example: message-ids -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    // The schema's root file by its node id, from state().
    const schema = (await api.state()).projects.find((each) => each.key === project).files.find((each) => each.format === "sbe");
    const listed = await api.messages({ project, file: schema.node });
    if (!listed.ok) return listed;
    const book = listed.messages.find((each) => each.name === "MDIncrementalRefreshBook46");
    const at = { project: listed.project, schema: listed.schema, path: book.path };
    const opened = await api.dispatch({ type: "view.open", title: book.name, form: "symbols", root: { kind: "node", at, place: { kind: "layout" } } });
    return opened.ok ? { messages: listed.messages.length, book } : opened;
}
```

Show a layout's bytes in a byte map (the argument: the id of a pane that shows a `layout`):

<!-- example: byte-map -->
```js
async (pane) => {
    const api = window.Structure.marketDataVisualizer;
    const opened = await api.command("pane.byteMap", { pane });
    if (!opened.ok) return opened;
    return (await api.state()).panes.find((each) => each.active);
}
```

Open a saved project (the argument: its key):

<!-- example: open-saved -->
```js
async (project) => {
    // Activating a saved project opens it first, as a click on it in the explorer does.
    return window.Structure.marketDataVisualizer.dispatch({ type: "project.activate", project });
}
```

Add a Parquet file and run SQL over it (the argument: the file as base64, fetched or read on your
side; each file is also a view named by its stem, `trades` here):

<!-- example: parquet-sql -->
```js
async (parquetBase64) => {
    const api = window.Structure.marketDataVisualizer;
    const added = await api.addFiles([{ name: "trades.parquet", bytes: parquetBase64 }], { project: { kind: "new", name: "Trades" } });
    if (!added.ok) return added;
    return api.sql("SELECT count(*) AS trades, max(price) AS high FROM trades", { project: added.project });
}
```

Arithmetic on DECIMAL columns stays DECIMAL and fails with "Overflow in multiplication" once a
result passes the type's digits: `price` here is `DECIMAL(18,9)`, nine digits before the point,
and `price * size` is DECIMAL(18,9) too. Read the column types with `DESCRIBE` and cast to
`DOUBLE` for products and sums (the argument: the project's key):

<!-- example: sql-decimal -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    const types = await api.sql("DESCRIBE trades", { project });
    if (!types.ok) return types;
    const notional = await api.sql("SELECT symbol, sum(price::DOUBLE * size) AS notional FROM trades GROUP BY symbol ORDER BY symbol", { project });
    if (!notional.ok) return notional;
    return { types: types.result, notional: notional.result };
}
```

Open a file's data and read its rows once the pane has them (`settle: "effects"` is the
default; the argument: the project's key):

<!-- example: settle -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    const file = (await api.state()).projects.find((each) => each.key === project).files.find((each) => each.path === "trades.parquet");
    const at = { project, schema: { format: "parquet", root: file.node }, path: "" };
    const opened = await api.dispatch({ type: "view.open", title: "trades.parquet · data", form: "symbols", root: { kind: "node", at, place: { kind: "table" } } }, { settle: "effects" });
    if (!opened.ok) return opened;
    const pane = (await api.state()).panes.find((each) => each.active).id;
    return api.rows(pane, { start: 0, count: 10 });
}
```

Read a Parquet file's layout, its byte ranges (the argument: the project's key):

<!-- example: parquet-bytes -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    const file = (await api.state()).projects.find((each) => each.key === project).files.find((each) => each.path === "trades.parquet");
    const at = { project, schema: { format: "parquet", root: file.node }, path: "" };
    const opened = await api.dispatch({ type: "view.open", title: "trades.parquet · file layout", form: "symbols", root: { kind: "node", at, place: { kind: "bytes" } } });
    if (!opened.ok) return opened;
    const pane = (await api.state()).panes.find((each) => each.active).id;
    return api.rows(pane, { start: 0, count: 20 });
}
```

Open the bundled CME capture at a trade by link, wait for it, and read how the exchange split it
over the queue: the instrument's match algorithm, and each fill with its allocation step (no
argument):

<!-- example: replay-fills -->
```js
async () => {
    const api = window.Structure.marketDataVisualizer;
    // A seller takes 100 of the SOFR spread's best bid, 25.0, by allocation.
    location.hash = "#open?sample=cme-mdp3&instrument=SR3Z6-SR3H7&message=8195";
    const settled = await api.settled();
    if (!settled.ok) return settled;
    const state = await api.state();
    const project = Object.keys(state.state.replays).find((key) => Object.values(state.state.replays[key].books).some((book) => book.title === "SR3Z6-SR3H7"));
    const instruments = await api.instruments({ project });
    if (!instruments.ok) return instruments;
    const spread = instruments.instruments.find((each) => each.symbol === "SR3Z6-SR3H7");
    const fills = await api.fills({ project });
    if (!fills.ok) return fills;
    const book = fills.books.find((each) => each.symbol === "SR3Z6-SR3H7");
    return { project, match: spread.match, fills: book.fills.map((fill) => ({ order: fill.order, filled: fill.filled, place: fill.place, steps: fill.steps })) };
}
```

Filter a capture's events and step from match to match, as the filter row's ↓ does (the
argument: the capture project's key):

<!-- example: filter-matches -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    const filtered = await api.dispatch({ type: "replay.filter", project, filter: "kind = trade and symbol = SR3Z6-SR3H7" });
    if (!filtered.ok) return filtered;
    const matches = await api.matches({ project, count: 5 });
    if (!matches.ok) return matches;
    const stepped = await api.command("replay.nextMatch", { project });
    if (!stepped.ok) return stepped;
    const message = (await api.state()).state.replays[project].message;
    return { total: matches.total, first: matches.matches.map((each) => each.message), message, rank: (await api.matches({ project, count: 1 })).rank };
}
```

Find the largest trade of an instrument with SQL over the events table, land on it with its
fills, and read the whole book there, past the rows on screen (the argument: the capture
project's key):

<!-- example: events-sql -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    const events = await api.eventsTable({ project });
    if (!events.ok) return events;
    const largest = await api.sql(`SELECT message, sending_time, qty, display_price FROM ${events.view} WHERE kind = 'trade' AND symbol = 'ESZ6' ORDER BY qty DESC LIMIT 1`, { project });
    if (!largest.ok) return largest;
    const [message, sent, qty, price] = largest.result.rows[0];
    // Lands on the end of the trade's event, where its fills show, with a book of ESZ6 in view.
    const fills = await api.fills({ project, message: Number(message) });
    if (!fills.ok) return fills;
    const book = Object.values((await api.state()).state.replays[project].books).find((each) => each.title === "ESZ6");
    const shown = await api.rows(book.id);
    if (!shown.ok) return shown;
    const whole = await api.rows(book.id, { start: 0, count: Math.min(shown.total, (await api.hello()).limits.ladderRowsMax) });
    if (!whole.ok) return whole;
    const filled = fills.books.find((each) => each.symbol === "ESZ6")?.fills ?? [];
    return { message: Number(message), sent, qty: Number(qty), price, landed: fills.message, fills: filled.map((fill) => ({ order: fill.order, filled: fill.filled, trade: fill.trade })), note: fills.note, shown: shown.rows.length, total: whole.total, rows: whole.rows.length };
}
```

Play a capture at 50 steps a second, read where play has reached, and pause it there (the
argument: the capture project's key):

<!-- example: replay-play -->
```js
async (project) => {
    const api = window.Structure.marketDataVisualizer;
    const set = await api.dispatch([{ type: "replay.speed", project, rate: { value: 50, unit: "steps" } }, { type: "replay.play", project }]);
    if (!set.ok) return set;
    await new Promise((resolve) => setTimeout(resolve, 500));
    const playing = await api.state();
    const paused = await api.command("replay.playPause", { project });
    if (!paused.ok) return paused;
    const after = await api.state();
    return { playing: playing.replays[project].playing, reached: playing.state.replays[project].message, now: playing.replays[project].message, paused: after.state.replays[project].message, play: after.state.replays[project].play };
}
```

Export a capture for a bug report: the state, the recent actions and the head, without the
files' contents. Attach it as `session.pvc`; `restore` replays it in another page that holds the
same files.

<!-- example: export -->
```js
async () => {
    const api = window.Structure.marketDataVisualizer;
    const capture = await api.export("session");
    if (!capture.ok) return capture;
    const actions = await api.actions();
    return { capture: capture.capture, bytes: capture.bytes, lastActions: actions.slice(-5).map((each) => each.text) };
}
```

Delete your own project when done (the argument: its key):

<!-- example: clean-up -->
```js
async (project) => {
    return window.Structure.marketDataVisualizer.command("project.delete", { project });
}
```

## Limits

- `sql` answers at most `limits.sqlRowsMax` rows (10,000); the console shows its first 1,000.
- `rows` answers at most `limits.rowsMax` rows (1,000) per call, and at most
  `limits.ladderRowsMax` (512) of a book's ladder.
- A detail pane's rows are read with none of its rows opened or closed by hand.
- Files added by bytes or URL cross the automation channel or the network whole; use
  `setInputFiles` for large local files.
