documentation/cookbook/sql/finance/ohlc.md
Generate OHLC bars from raw trade data. OHLC summarizes price action within each time period: the first trade (open), highest price (high), lowest price (low), and last trade (close).
You have tick-level trade data and need to aggregate it into standard candlestick bars for charting or technical analysis.
SELECT
timestamp,
symbol,
first(price) AS open,
max(price) AS high,
min(price) AS low,
last(price) AS close,
sum(quantity) AS total_volume
FROM fx_trades
WHERE timestamp IN '$today'
SAMPLE BY 1m;
This query:
SAMPLE BYfirst() and last() to capture opening and closing pricesmax() and min() to capture the price rangeIf you query OHLC bars frequently, such as for a dashboard, create a materialized view to pre-compute the aggregation:
CREATE MATERIALIZED VIEW 'fx_trades_ohlc_1m' WITH BASE 'fx_trades' REFRESH IMMEDIATE AS (
SELECT
timestamp,
symbol,
first(price) AS open,
max(price) AS high,
min(price) AS low,
last(price) AS close,
sum(quantity) AS total_volume
FROM fx_trades
SAMPLE BY 1m
) PARTITION BY HOUR TTL 2 DAYS;
QuestDB automatically refreshes the view as new trades arrive. Queries against the view return instantly regardless of the underlying data volume.
:::info Related documentation