diff --git a/2026-10-databento-orderbook-ingestion/.gitignore b/2026-10-databento-orderbook-ingestion/.gitignore new file mode 100644 index 0000000..d6df153 --- /dev/null +++ b/2026-10-databento-orderbook-ingestion/.gitignore @@ -0,0 +1,3 @@ +.env +state/ +*.log diff --git a/2026-10-databento-orderbook-ingestion/README.md b/2026-10-databento-orderbook-ingestion/README.md new file mode 100644 index 0000000..dc87f50 --- /dev/null +++ b/2026-10-databento-orderbook-ingestion/README.md @@ -0,0 +1,152 @@ +# Databento order book ingestion into QuestDB + +Companion code for the QuestDB blog post on streaming Databento market data +into QuestDB. + +The example streams top-of-book quotes (`mbp-1`) and trades for every symbol +in Databento's `EQUS.MINI` dataset into two QuestDB tables, then queries them +with QuestDB SQL. The connector streams until you stop it, so stop it once +you have the sample you want. + +The Databento connector requires QuestDB Enterprise. On QuestDB open source, +see [Databento with Python](https://questdb.com/docs/integrations/other/databento/). + +## What's inside + +| File | Purpose | +| --- | --- | +| `connector.toml` | Connector configuration: dataset, subscriptions, tables, recovery | +| `sql/queries.sql` | Queries over the ingested data | +| `run_sql.py` | Runs the named statements in a `.sql` file and prints the results | +| `questdb-databento-dashboard.json` | QuestDB Web Console dashboard over the two tables | + +`run_sql.py` uses only the Python standard library. + +## Requirements + +- QuestDB Enterprise 4.0.0 or later. The connector writes with the QuestDB + Wire Protocol (QWP) over WebSocket on port `9000`. +- The `databento-questdb` connector binary on your `PATH`. Get it through + your QuestDB Enterprise contact; see + [installing the connector](https://questdb.com/docs/connect/connectors/databento/#1-install-the-connector). +- A QuestDB service account token with `HTTP` and `CREATE TABLE` grants; see + [authentication and TLS](https://questdb.com/docs/connect/connectors/databento/#questdb-authentication-and-tls). +- A Databento API key with Live access to `EQUS.MINI`. +- Python 3.9 or later, for `run_sql.py`. + +## Quick start + +```bash +# 1. Set credentials. Point QDB_CLIENT_CONF at your QuestDB Enterprise +export DATABENTO_API_KEY='db-your-key-here' +export QDB_CLIENT_CONF='ws::addr=localhost:9000;token=;' + +# 2. Stream live data. Press Ctrl+C to stop when you have enough +databento-questdb --config connector.toml + +# 3. Query what arrived. The connector's service account owns the tables it +# creates, so its token can read them +export QDB_HTTP='http://localhost:9000' +export QDB_TOKEN='' +python3 run_sql.py sql/queries.sql +``` + +`databento-questdb --config connector.toml --check-config` validates the file +and prints the effective settings, with the API key redacted, without +connecting to anything. + +Open the QuestDB Web Console at http://localhost:9000 to explore the +`equs_orderbook` and `equs_trades` tables. + +Run a single query by name: + +```bash +python3 run_sql.py sql/queries.sql latest_quotes +``` + +## Dashboard + +`questdb-databento-dashboard.json` is a native QuestDB Web Console dashboard, built as a +notebook. To install, open +the **⋮** menu at the right end of the Web Console tab bar, choose **Import tabs**, and import the +file. It opens as a new notebook tab, **Databento EQUS.MINI: US Equities Live**, already in the +grid layout. + +| Cell | Shows | +| --- | --- | +| Trades: OHLC (5s) and Volume | 5-second candles from trades, with traded shares on the right axis | +| Top of Book: Bid, Ask and Spread (1s) | Best bid and ask, with the spread in basis points on the right axis | +| Most Active Symbols (last 60s) | Top 10 symbols by quote updates, with latest quote, spread, trades, and last price | +| Feed Activity: Updates and Trades per Second | Book updates and trades per second across all symbols | + +It uses notebook variables: `@symbol` (`'NVDA'` by default) selects the symbol for the two +charts at the top, and `@asof` (`now()`) is the end of the window. Each cell shows the latest data +up to `@asof`, ten minutes for the charts and sixty seconds for the table, so it still renders +after the connector stops. Set `@asof` to a past instant to look at an earlier window. The +dashboard refreshes every second. + +![Databento EQUS.MINI: US Equities Live in the QuestDB Web Console](images/databento-us-equities-dashboard.png) + +## How it works + +The connector subscribes to two Databento schemas and writes each to its own +table. Tables are created on first write, partitioned by day, with +nanosecond `ts_event` and `ts_recv` columns and `ts_recv` as the designated +timestamp. + +| Table | Schema | Contents | +| --- | --- | --- | +| `equs_orderbook` | `mbp-1` | Every change to the best bid or offer, plus trade events | +| `equs_trades` | `trades` | Trades only | + +Book levels are stored as `DOUBLE[][]` arrays of shape `[2, N]`, best level +first: row 1 holds prices and row 2 sizes. `bids[1][1]` is the best bid price +and `bids[2][1]` its size. An empty side of the book is `NULL`. + +On Ctrl+C (`SIGINT`) or `SIGTERM`, the connector drains in-flight rows, waits +for QuestDB to acknowledge them, and saves a checkpoint under `state/`. If you +run it under a service manager, give it more than the 30-second drain timeout +before it kills the process, for example `terminationGracePeriodSeconds: 60` +on Kubernetes or `docker stop --time 60`. + +## Recovery after downtime + +Start the connector again with the same config and it resumes from the +checkpoint. It asks Databento to replay from shortly before the last +acknowledged record, using intraday replay, so rows published while it was +stopped arrive first and the timeline has no gap: + +```bash +databento-questdb --config connector.toml +# Ctrl+C after a minute, then: +python3 run_sql.py sql/queries.sql arrival_timeline duplicate_check +``` + +Delivery is at least once. The replay overlaps the previous run by a few +seconds, which writes those rows twice. `replay_dedup = true` in +`connector.toml` filters the replayed records out. It relies on `ts_event` +never going backwards per instrument, which holds for `EQUS.MINI`. + +Intraday replay generally covers the last 24 hours. After a longer outage, +backfill the gap with the connector's Historical mode, which Databento bills +separately. + +## QuestDB downtime + +If QuestDB stops while the connector is running, for example during an +upgrade, the connector keeps receiving from Databento and holds unacknowledged +rows in memory. When QuestDB is back it resends them, and each row keeps its +original Databento `ts_recv` timestamp. The buffers are bounded: when they +fill, the connector pauses reading from Databento rather than dropping data. +Start QuestDB before the connector; by default the connector's first +connection fails if QuestDB is down. + +## Notes + +- **Market hours matter.** Outside US regular trading hours few symbols + trade, so some queries return few rows. +- **Stop it when you are done.** `ALL_SYMBOLS` on `mbp-1` is a heavy stream + during regular hours, and the connector keeps writing until you press + Ctrl+C. +- **Start fresh.** To start over, drop both tables and delete `state/`. + Changing the subscriptions or tables also requires a new state directory. diff --git a/2026-10-databento-orderbook-ingestion/connector.toml b/2026-10-databento-orderbook-ingestion/connector.toml new file mode 100644 index 0000000..3804568 --- /dev/null +++ b/2026-10-databento-orderbook-ingestion/connector.toml @@ -0,0 +1,47 @@ +# Databento -> QuestDB connector configuration. +# +# Streams top-of-book quotes (mbp-1) and trades for every symbol in +# Databento's EQUS.MINI dataset into two QuestDB tables. +# +# Credentials come from the environment: +# DATABENTO_API_KEY Databento API key with Live access to EQUS.MINI +# QDB_CLIENT_CONF QuestDB client configuration string +version = 1 +on_task_failure = "exit" +progress_log_interval_s = 30 + +[pools.main] +conf_env = "QDB_CLIENT_CONF" + +[[tasks]] +name = "equs-mini" +pool = "main" +dataset = "EQUS.MINI" +# Checkpoints live here. Restarting with the same directory resumes from the +# last acknowledged record using Databento intraday replay. Relative paths +# resolve from this file's directory. +state_dir = "./state/equs-mini" + +[tasks.source] +api_key_env = "DATABENTO_API_KEY" + +# Recovery replays from slightly before the last checkpoint, so a restart can +# deliver some rows twice. replay_dedup filters the replayed records the +# connector has already written; it assumes ts_event never goes backwards +# per instrument, which holds for EQUS.MINI. + +# Top of book: every change to the best bid or offer, plus trades. +[[tasks.subscriptions]] +schema = "mbp-1" +symbols = "ALL_SYMBOLS" +stype_in = "raw_symbol" +table = "equs_orderbook" +replay_dedup = true + +# Trades only. +[[tasks.subscriptions]] +schema = "trades" +symbols = "ALL_SYMBOLS" +stype_in = "raw_symbol" +table = "equs_trades" +replay_dedup = true diff --git a/2026-10-databento-orderbook-ingestion/images/databento-us-equities-dashboard.png b/2026-10-databento-orderbook-ingestion/images/databento-us-equities-dashboard.png new file mode 100644 index 0000000..e9db5b2 Binary files /dev/null and b/2026-10-databento-orderbook-ingestion/images/databento-us-equities-dashboard.png differ diff --git a/2026-10-databento-orderbook-ingestion/questdb-databento-dashboard.json b/2026-10-databento-orderbook-ingestion/questdb-databento-dashboard.json new file mode 100644 index 0000000..c3264eb --- /dev/null +++ b/2026-10-databento-orderbook-ingestion/questdb-databento-dashboard.json @@ -0,0 +1 @@ +{"formatName":"dexie","formatVersion":1,"data":{"databaseName":"web-console","databaseVersion":9,"tables":[{"name":"buffers","schema":"++id,label,position,archived,archivedAt","rowCount":1}],"data":[{"tableName":"buffers","inbound":true,"rows":[{"label":"Databento EQUS.MINI: US Equities Live","value":"","editorViewState":0,"metricsViewState":0,"notebookViewState":{"cells":[{"id":"91f9411e-afaa-427d-bc74-935aa39aecf1","position":0,"value":"SELECT ts_recv, first(price) AS open, max(price) AS high, min(price) AS low, last(price) AS close\nFROM equs_trades\nWHERE symbol = @symbol\n AND ts_recv >= (SELECT dateadd('m', -10, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= (SELECT max(ts_recv) FROM equs_orderbook WHERE ts_recv <= @asof)\nSAMPLE BY 5s;\nSELECT ts_recv, sum(size) AS volume\nFROM equs_trades\nWHERE symbol = @symbol\n AND ts_recv >= (SELECT dateadd('m', -10, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= (SELECT max(ts_recv) FROM equs_orderbook WHERE ts_recv <= @asof)\nSAMPLE BY 5s","name":"Trades: OHLC (5s) and Volume","topHeight":296,"paneView":"result","mode":"draw","chartConfig":{"xColumn":"ts_recv","queries":[{"type":"candlestick","yColumns":[],"ohlc":{"open":"open","high":"high","low":"low","close":"close"},"axis":"left","name":"OHLC 5s"},{"type":"bar","yColumns":["volume"],"axis":"right","name":"Volume"}],"rightAxis":{"name":"Volume (shares)"}},"bottomHeight":380,"bottomResized":true,"result":0,"lastRunStatus":0,"lastRunError":0},{"id":"2b6f6566-3c33-4d60-8251-2b701821168d","position":1,"value":"SELECT ts_recv, last(bids[1][1]) AS bid, last(asks[1][1]) AS ask\nFROM equs_orderbook\nWHERE symbol = @symbol\n AND ts_recv >= (SELECT dateadd('m', -10, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= @asof\nSAMPLE BY 1s;\nSELECT ts_recv, avg(spread(bids[1][1], asks[1][1]) / mid(bids[1][1], asks[1][1]) * 10000) AS spread_bps\nFROM equs_orderbook\nWHERE symbol = @symbol\n AND ts_recv >= (SELECT dateadd('m', -10, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= @asof\nSAMPLE BY 1s","name":"Top of Book: Bid, Ask and Spread (1s)","topHeight":296,"paneView":"result","mode":"draw","chartConfig":{"xColumn":"ts_recv","queries":[{"type":"stepLine","yColumns":["bid","ask"],"axis":"left","name":"Top of book"},{"type":"area","yColumns":["spread_bps"],"axis":"right","name":"Spread"}],"rightAxis":{"name":"Spread (bp)","min":0}},"bottomHeight":380,"bottomResized":true,"result":0,"lastRunStatus":0,"lastRunError":0},{"id":"6df38bc2-e99c-4b80-b44b-1ffbf54871bf","position":2,"value":"WITH q AS (\n SELECT symbol, count() AS quote_updates\n FROM equs_orderbook\n WHERE ts_recv >= (SELECT dateadd('s', -60, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= @asof\n ORDER BY quote_updates DESC\n LIMIT 10\n), l AS (\n SELECT symbol, bids[1][1] AS bid, asks[1][1] AS ask\n FROM equs_orderbook\n WHERE ts_recv >= (SELECT dateadd('s', -60, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= @asof\n LATEST ON ts_recv PARTITION BY symbol\n), t AS (\n SELECT symbol, count() AS trades, sum(size) AS shares, last(price) AS last_price\n FROM equs_trades\n WHERE ts_recv >= (SELECT dateadd('s', -60, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= (SELECT max(ts_recv) FROM equs_orderbook WHERE ts_recv <= @asof)\n)\nSELECT q.symbol AS Symbol, l.bid AS Bid, l.ask AS Ask,\n cast(round(spread(l.bid, l.ask) / mid(l.bid, l.ask) * 10000, 2) AS DECIMAL(10, 2)) AS Spread_bps,\n q.quote_updates AS Quote_updates, t.trades AS Trades, t.shares AS Shares, t.last_price AS Last_trade\nFROM q\nLEFT JOIN l ON (q.symbol = l.symbol)\nLEFT JOIN t ON (q.symbol = t.symbol)\nORDER BY Quote_updates DESC","name":"Most Active Symbols (last 60s)","topHeight":632,"paneView":"result","highlightConfig":{"identityColumns":["Symbol"],"rules":[{"id":"89f06413-787b-4224-a3f4-8fc01cf50a46","enabled":true,"target":{"kind":"column","name":"Bid"},"kind":"previous","appliesTo":"cell","display":"temporary","color":"dataPositive","condition":{"op":"gt"}},{"id":"56fdf9a3-caa6-47cf-9a80-3ac9e2ecdaf7","enabled":true,"target":{"kind":"column","name":"Bid"},"kind":"previous","appliesTo":"cell","display":"temporary","color":"dataNegative","condition":{"op":"lt"}},{"id":"a347c3a6-0af0-4c12-a7b2-98aae114acb8","enabled":true,"target":{"kind":"column","name":"Ask"},"kind":"previous","appliesTo":"cell","display":"temporary","color":"dataPositive","condition":{"op":"gt"}},{"id":"2138673c-8ebc-409b-8d75-f48b3b5fd4db","enabled":true,"target":{"kind":"column","name":"Ask"},"kind":"previous","appliesTo":"cell","display":"temporary","color":"dataNegative","condition":{"op":"lt"}},{"id":"106bf69e-6268-4288-9040-c3cd0e67b2dc","enabled":true,"target":{"kind":"column","name":"Last_trade"},"kind":"previous","appliesTo":"cell","display":"temporary","color":"dataPositive","condition":{"op":"gt"}},{"id":"94bb0dae-7378-4d90-9c79-0b25127d4b72","enabled":true,"target":{"kind":"column","name":"Last_trade"},"kind":"previous","appliesTo":"cell","display":"temporary","color":"dataNegative","condition":{"op":"lt"}},{"id":"3d24e22a-d325-4686-a037-00f50df9e57e","enabled":true,"target":{"kind":"column","name":"Spread_bps"},"kind":"value","appliesTo":"cell","display":"always","color":"dataSeries2","condition":{"op":"between","from":null,"to":null,"fill":{"kind":"gradient","highColor":"dataSeries3"}}},{"id":"e974dcef-f4c8-4006-ac81-048b15ba40c7","enabled":true,"target":{"kind":"column","name":"Quote_updates"},"kind":"value","appliesTo":"cell","display":"always","color":"dataSeries9","condition":{"op":"between","from":null,"to":null,"fill":{"kind":"gradient","highColor":"dataSeries6"}}}]},"bottomHeight":420,"bottomResized":true,"result":0,"lastRunStatus":"success","lastRunError":0},{"id":"ec95ad02-3c90-444b-b7ee-3ee872d0186a","position":3,"value":"SELECT ts_recv, count() AS book_updates\nFROM equs_orderbook\nWHERE ts_recv >= (SELECT dateadd('m', -10, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= @asof\nSAMPLE BY 1s;\nSELECT ts_recv, count() AS trades\nFROM equs_trades\nWHERE ts_recv >= (SELECT dateadd('m', -10, max(ts_recv)) FROM equs_orderbook WHERE ts_recv <= @asof)\n AND ts_recv <= (SELECT max(ts_recv) FROM equs_orderbook WHERE ts_recv <= @asof)\nSAMPLE BY 1s","name":"Feed Activity: Updates and Trades per Second (all symbols)","topHeight":248,"paneView":"result","mode":"draw","chartConfig":{"xColumn":"ts_recv","queries":[{"type":"bar","yColumns":["book_updates"],"axis":"left","name":"Book updates"},{"type":"line","yColumns":["trades"],"axis":"right","name":"Trades"}],"rightAxis":{"name":"Trades per second","min":0}},"bottomHeight":420,"bottomResized":true,"result":0,"lastRunStatus":0,"lastRunError":0}],"focusedCellId":0,"maximizedCellId":0,"settings":{"layoutMode":"grid","layout":[{"i":"91f9411e-afaa-427d-bc74-935aa39aecf1","x":0,"y":0,"w":6,"h":15},{"i":"2b6f6566-3c33-4d60-8251-2b701821168d","x":6,"y":0,"w":6,"h":15},{"i":"6df38bc2-e99c-4b80-b44b-1ffbf54871bf","x":0,"y":1,"w":6,"h":17},{"i":"ec95ad02-3c90-444b-b7ee-3ee872d0186a","x":6,"y":1,"w":6,"h":17},{"i":"ad798c01-31af-4699-9d65-cce2937239e3","x":0,"y":18,"w":12,"h":1}],"autoRefreshDefault":"1s","variables":[{"name":"asof","value":"now()"},{"name":"symbol","value":"'NVDA'"}]}},"position":30,"archived":0,"archivedAt":0,"isTemporary":0,"isPreviewBuffer":0,"previewContent":0,"id":41,"$types":{"editorViewState":"undef","metricsViewState":"undef","notebookViewState.cells":"arrayNonindexKeys","notebookViewState.cells.0.chartConfig.queries":"arrayNonindexKeys","notebookViewState.cells.0.chartConfig.queries.0.yColumns":"arrayNonindexKeys","notebookViewState.cells.0.chartConfig.queries.1.yColumns":"arrayNonindexKeys","notebookViewState.cells.0.result":"undef","notebookViewState.cells.0.lastRunStatus":"undef","notebookViewState.cells.0.lastRunError":"undef","notebookViewState.cells.1.chartConfig.queries":"arrayNonindexKeys","notebookViewState.cells.1.chartConfig.queries.0.yColumns":"arrayNonindexKeys","notebookViewState.cells.1.chartConfig.queries.1.yColumns":"arrayNonindexKeys","notebookViewState.cells.1.result":"undef","notebookViewState.cells.1.lastRunStatus":"undef","notebookViewState.cells.1.lastRunError":"undef","notebookViewState.cells.2.highlightConfig.identityColumns":"arrayNonindexKeys","notebookViewState.cells.2.highlightConfig.rules":"arrayNonindexKeys","notebookViewState.cells.2.result":"undef","notebookViewState.cells.2.lastRunError":"undef","notebookViewState.cells.3.chartConfig.queries":"arrayNonindexKeys","notebookViewState.cells.3.chartConfig.queries.0.yColumns":"arrayNonindexKeys","notebookViewState.cells.3.chartConfig.queries.1.yColumns":"arrayNonindexKeys","notebookViewState.cells.3.result":"undef","notebookViewState.cells.3.lastRunStatus":"undef","notebookViewState.cells.3.lastRunError":"undef","notebookViewState.focusedCellId":"undef","notebookViewState.maximizedCellId":"undef","notebookViewState.settings.layout":"arrayNonindexKeys","notebookViewState.settings.variables":"arrayNonindexKeys","archived":"undef","archivedAt":"undef","isTemporary":"undef","isPreviewBuffer":"undef","previewContent":"undef"}}]}]}} \ No newline at end of file diff --git a/2026-10-databento-orderbook-ingestion/run_sql.py b/2026-10-databento-orderbook-ingestion/run_sql.py new file mode 100644 index 0000000..122ea3b --- /dev/null +++ b/2026-10-databento-orderbook-ingestion/run_sql.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Run the named statements in a .sql file against QuestDB and print the results. + +Statements are separated by `-- name: ` comment lines. Uses the QuestDB +REST API and the Python standard library only. + + QDB_HTTP QuestDB HTTP endpoint (default: http://127.0.0.1:9000) + QDB_TOKEN QuestDB REST token, sent as a bearer token + +Usage: + python3 run_sql.py sql/queries.sql # run every statement + python3 run_sql.py sql/queries.sql latest_quotes # run one by name +""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.parse +import urllib.request + +QDB_HTTP = os.environ.get("QDB_HTTP", "http://127.0.0.1:9000").rstrip("/") +QDB_TOKEN = os.environ.get("QDB_TOKEN") +MAX_ROWS = 20 + + +def parse_statements(path): + """Return [(name, sql)] from `-- name:` delimited blocks.""" + statements, name, lines = [], None, [] + with open(path) as f: + for line in f: + if line.startswith("-- name:"): + if name and "".join(lines).strip(): + statements.append((name, "".join(lines).strip().rstrip(";"))) + name, lines = line.split(":", 1)[1].strip(), [] + elif name: + lines.append(line) + if name and "".join(lines).strip(): + statements.append((name, "".join(lines).strip().rstrip(";"))) + return statements + + +def execute(sql): + url = f"{QDB_HTTP}/exec?" + urllib.parse.urlencode({"query": sql, "limit": MAX_ROWS}) + headers = {"Authorization": f"Bearer {QDB_TOKEN}"} if QDB_TOKEN else {} + try: + with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as resp: + return json.load(resp) + except urllib.error.HTTPError as e: + return json.load(e) + + +def fmt(value): + if isinstance(value, float): + return f"{value:.6g}" + if isinstance(value, list): + return json.dumps(value) + return "" if value is None else str(value) + + +def print_result(result): + if "error" in result: + print(f" ERROR: {result['error']}") + return + if "columns" not in result: + print(f" OK ({result.get('ddl') or result.get('dml') or 'done'})") + return + headers = [c["name"] for c in result["columns"]] + rows = [[fmt(v) for v in row] for row in result["dataset"]] + widths = [max(len(h), *(len(r[i]) for r in rows)) if rows else len(h) for i, h in enumerate(headers)] + print(" " + " ".join(h.ljust(w) for h, w in zip(headers, widths))) + print(" " + " ".join("-" * w for w in widths)) + for row in rows: + print(" " + " ".join(v.ljust(w) for v, w in zip(row, widths))) + total = result.get("count", len(rows)) + if total > len(rows): + print(f" ... {total - len(rows)} more row(s)") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("file") + parser.add_argument("names", nargs="*", help="statement names to run (default: all)") + args = parser.parse_args() + + statements = parse_statements(args.file) + if args.names: + unknown = set(args.names) - {n for n, _ in statements} + if unknown: + sys.exit(f"Unknown statement(s): {', '.join(sorted(unknown))}") + statements = [(n, s) for n, s in statements if n in args.names] + + failed = False + for name, sql in statements: + print(f"\n== {name}") + result = execute(sql) + failed |= "error" in result + print_result(result) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/2026-10-databento-orderbook-ingestion/sql/queries.sql b/2026-10-databento-orderbook-ingestion/sql/queries.sql new file mode 100644 index 0000000..2a6095d --- /dev/null +++ b/2026-10-databento-orderbook-ingestion/sql/queries.sql @@ -0,0 +1,145 @@ +-- Queries over the tables the connector creates. +-- Run with: python3 run_sql.py sql/queries.sql [name ...] + +-- name: row_counts +-- How much arrived, and over which time range. +SELECT 'equs_orderbook' AS table_name, count() AS row_count, + min(ts_recv) AS first_ts, max(ts_recv) AS last_ts, + count_distinct(symbol) AS symbols +FROM equs_orderbook +UNION ALL +SELECT 'equs_trades', count(), min(ts_recv), max(ts_recv), count_distinct(symbol) +FROM equs_trades; + +-- name: latest_quotes +-- Current top of book per symbol. Book levels are DOUBLE[][] arrays of shape +-- [2, N]: row 1 holds prices, row 2 sizes, best level first. +SELECT ts_recv, symbol, + bids[1][1] AS bid_px, bids[2][1] AS bid_sz, + asks[1][1] AS ask_px, asks[2][1] AS ask_sz +FROM equs_orderbook +WHERE symbol IN ('AAPL', 'MSFT', 'NVDA', 'TSLA', 'SPY', 'QQQ') +LATEST ON ts_recv PARTITION BY symbol; + +-- name: most_traded +-- Most traded symbols by notional value. +SELECT symbol, count() AS trades, sum(size) AS shares, + sum(price * size) AS notional +FROM equs_trades +ORDER BY notional DESC +LIMIT 10; + +-- name: ohlcv_1m +-- One-minute bars per symbol, built from raw trades. +SELECT ts_recv, symbol, + first(price) AS open, max(price) AS high, + min(price) AS low, last(price) AS close, + sum(size) AS volume, count() AS trades +FROM equs_trades +SAMPLE BY 1m +ORDER BY trades DESC +LIMIT 10; + +-- name: spread_bps +-- Average quoted spread in basis points of the mid price, per minute. +SELECT ts_recv, symbol, + avg((asks[1][1] - bids[1][1]) / ((asks[1][1] + bids[1][1]) / 2) * 10000) AS spread_bps, + count() AS quote_updates +FROM equs_orderbook +WHERE symbol IN ('AAPL', 'NVDA', 'TSLA', 'SPY', 'QQQ') + AND bids[1][1] > 0 AND asks[1][1] > 0 +SAMPLE BY 1m; + +-- name: trades_vs_quote +-- Each trade next to the quote prevailing when it printed. ASOF JOIN matches +-- the latest quote at or before the trade's ts_recv for the same symbol. An +-- empty side of the book is NULL, so one-sided quotes get their own label. +SELECT t.ts_recv, t.symbol, t.price, t.size, + q.bids[1][1] AS bid_px, q.asks[1][1] AS ask_px, + CASE + WHEN q.bids[1][1] = NULL OR q.asks[1][1] = NULL THEN 'no two-sided quote' + WHEN t.price >= q.asks[1][1] THEN 'at or above ask' + WHEN t.price <= q.bids[1][1] THEN 'at or below bid' + ELSE 'inside spread' + END AS trade_location +FROM equs_trades t +ASOF JOIN equs_orderbook q ON (symbol) +LIMIT -10; + +-- name: arrival_timeline +-- Rows per 30 seconds. After a restart with the same state directory, the +-- buckets covering the downtime fill in from Databento intraday replay. +SELECT ts_recv, count() AS book_updates +FROM equs_orderbook +SAMPLE BY 30s; + +-- name: duplicate_check +-- Rows that are identical in every field. Recovery replays from slightly +-- before the last checkpoint; replay_dedup removes those replayed rows. A +-- few identical records can still be genuine, such as two equal-sized fills +-- at the same price in the same nanosecond. +SELECT 'equs_orderbook' AS table_name, count() AS row_count, + count() - count_distinct(concat(ts_recv::long, '|', instrument_id, '|', + ts_event::long, '|', action, '|', side, '|', price, '|', size)) AS identical_rows +FROM equs_orderbook +UNION ALL +SELECT 'equs_trades', count(), + count() - count_distinct(concat(ts_recv::long, '|', instrument_id, '|', + ts_event::long, '|', side, '|', price, '|', size)) +FROM equs_trades; + +-- name: spread_distribution +-- Spread distribution in basis points for the most actively quoted symbols, +-- using QuestDB's native spread() and mid() functions. Precision 3 keeps +-- approx_percentile accurate for small values. +SELECT symbol, + min(spread(bids[1][1], asks[1][1]) / mid(bids[1][1], asks[1][1]) * 10000) AS min_bps, + approx_percentile(spread(bids[1][1], asks[1][1]) / mid(bids[1][1], asks[1][1]) * 10000, 0.5, 3) AS p50_bps, + max(spread(bids[1][1], asks[1][1]) / mid(bids[1][1], asks[1][1]) * 10000) AS max_bps, + count() AS updates +FROM equs_orderbook +WHERE bids[1][1] > 0 AND asks[1][1] > 0 +ORDER BY updates DESC +LIMIT 8; + +-- name: event_to_receive +-- Gap between each record's event timestamp and Databento's receive +-- timestamp, in microseconds. Both are stored with nanosecond precision. +SELECT approx_percentile((ts_recv - ts_event) / 1000.0, 0.5, 3) AS p50_us, + approx_percentile((ts_recv - ts_event) / 1000.0, 0.99, 3) AS p99_us, + approx_percentile((ts_recv - ts_event) / 1000.0, 0.999, 3) AS p999_us, + max((ts_recv - ts_event) / 1000.0) AS max_us, + count() AS updates +FROM equs_orderbook +WHERE ts_recv >= ts_event; + +-- name: burstiness +-- Per-second update rates. Averages hide bursts; size buffers for the peak. +SELECT max(n) AS peak_per_second, avg(n) AS avg_per_second, + approx_percentile(n, 0.99, 3) AS p99_per_second, count() AS seconds +FROM (SELECT ts_recv, count() AS n FROM equs_orderbook SAMPLE BY 1s); + +-- name: busiest_milliseconds +-- The busiest single milliseconds, using SAMPLE BY 1T (one millisecond). +SELECT ts_recv, count() AS updates, count_distinct(symbol) AS symbols +FROM equs_orderbook +SAMPLE BY 1T +ORDER BY updates DESC +LIMIT 5; + +-- name: trade_location_mix +-- Where trades print relative to the prevailing quote, across all symbols. +WITH located AS ( + SELECT t.size, + CASE + WHEN q.bids[1][1] = NULL OR q.asks[1][1] = NULL THEN 'no two-sided quote' + WHEN t.price >= q.asks[1][1] THEN 'at or above ask' + WHEN t.price <= q.bids[1][1] THEN 'at or below bid' + ELSE 'inside spread' + END AS trade_location + FROM equs_trades t + ASOF JOIN equs_orderbook q ON (symbol) +) +SELECT trade_location, count() AS trades, sum(size) AS shares +FROM located +ORDER BY trades DESC;