Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions 2026-10-databento-orderbook-ingestion/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.env
state/
*.log
152 changes: 152 additions & 0 deletions 2026-10-databento-orderbook-ingestion/README.md
Original file line number Diff line number Diff line change
@@ -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=<your-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='<your-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.
47 changes: 47 additions & 0 deletions 2026-10-databento-orderbook-ingestion/connector.toml
Original file line number Diff line number Diff line change
@@ -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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -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"}}]}]}}
Loading
Loading