T-135: M2.3b — libs/data/questdb query layer for QuestDB 10.2.0: LATEST ON + parameterized PGWire queries + contract DDL for bars_1m / fx_1m / bar_revisions (pure, no live QuestDB)

This commit is contained in:
Studio 2026-12-01 06:12:25 -05:00
parent c6bd028dcc
commit 35d5de815b
8 changed files with 1523 additions and 305 deletions

View file

@ -1,102 +1,115 @@
# QuestDB Client Library
A comprehensive QuestDB client library for the Stock Bot trading platform, optimized for time-series data, market analytics, and high-performance queries.
## Features
- **Time-Series Optimized**: Built specifically for time-series data patterns
- **Dual Protocol Support**: HTTP REST API and PostgreSQL wire protocol
- **InfluxDB Line Protocol**: High-performance data ingestion
- **SQL Analytics**: Full SQL support for complex analytics
- **Schema Management**: Automatic table creation and partitioning
- **Performance Monitoring**: Query performance tracking and optimization
- **Health Monitoring**: Connection health monitoring and metrics
## Usage
```typescript
import { QuestDBClient } from '@stock-bot/questdb';
// Initialize client
const questClient = new QuestDBClient();
await questClient.connect();
// Insert market data using InfluxDB Line Protocol
await questClient.insert('ohlcv', {
symbol: 'AAPL',
open: 150.00,
high: 152.00,
low: 149.50,
close: 151.50,
volume: 1000000,
timestamp: new Date()
});
// Query with SQL
const prices = await questClient.query(`
SELECT symbol, close, timestamp
FROM ohlcv
WHERE symbol = 'AAPL'
AND timestamp > dateadd('d', -1, now())
ORDER BY timestamp DESC
`);
// Time-series aggregations
const dailyStats = await questClient.aggregate('ohlcv')
.select(['symbol', 'avg(close) as avg_price'])
.where('symbol = ?', ['AAPL'])
.groupBy('symbol')
.sampleBy('1d', 'timestamp')
.execute();
```
## Data Types
The client provides typed access to the following time-series data:
- **ohlcv**: OHLCV candlestick data
- **trades**: Individual trade executions
- **quotes**: Bid/ask quote data
- **indicators**: Technical indicator values
- **performance**: Portfolio performance metrics
- **risk_metrics**: Risk calculation results
## Configuration
Configure using environment variables:
```env
QUESTDB_HOST=localhost
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_INFLUX_PORT=9009
```
## Time-Series Features
QuestDB excels at:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Automatic partitioning by time
- **ASOF JOINs**: Time-series specific joins
- **SAMPLE BY**: Time-based aggregations
- **LATEST BY**: Get latest values by key
## Performance
The client includes performance optimizations:
- Connection pooling for HTTP and PostgreSQL protocols
- Batch insertions for high throughput
- Compressed data transfer
- Query result caching
- Automatic schema optimization
## Health Monitoring
Built-in health monitoring:
```typescript
const health = await questClient.getHealth();
console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy'
```
# QuestDB Client Library
A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized for time-series data, parameterized PGWire queries, and intraday bar storage.
## Features
- **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`)
- **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated
- **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS`
- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string and returns `INT32` `listing_id` values with `known_at` preserved
- **InfluxDB Line Protocol**: Batch ingestion writer
- **Health Monitoring**: Connection health monitoring and metrics
## Usage
### Parameterized Queries & `LATEST ON`
```typescript
import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb';
const questClient = new QuestDBClient({
host: 'localhost',
httpPort: 9000,
pgPort: 8812,
influxPort: 9009,
database: 'qdb',
});
await questClient.connect();
// Parameterized PGWire query via query builder
const { sql, params } = QuestDBQueryBuilder.create(questClient)
.select('listing_id', 'ts', 'close', 'volume')
.from('bars_1m')
.where('listing_id = $1', ['1042'])
.latestOn('ts', 'listing_id')
.buildParameterized();
// sql:
// SELECT listing_id, ts, close, volume FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id
// params: ['1042']
// Execute directly (forwards both SQL and bound params)
const latestBars = await questClient.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', {
where: 'session = $1',
params: ['RTH'],
});
// Override the designated timestamp column explicitly
const latestRevisions = await questClient.latestBy(
'bar_revisions',
['listing_id', 'revised_at', 'new_close'],
'listing_id',
{ timestampColumn: 'revised_at' }
);
// Time-series aggregations with bound filters
const hourlyStats = await questClient
.aggregate('ohlcv_data')
.selectAgg({ avg_close: 'avg(close)' })
.whereSymbol('AAPL')
.whereLastHours(24)
.groupBy('symbol')
.sampleBy('1h')
.execute();
```
### Reading `bars_1m` Ranges
```typescript
import { readBars1m } from '@stock-bot/questdb';
// Queries `[from, to)` ordered by `ts ASC`, binding listingId as decimal string SYMBOL
// and converting returned `listing_id` back to signed INT32.
const bars = await readBars1m(
questClient,
1042,
new Date('2024-01-02T14:30:00.000Z'),
new Date('2024-01-02T21:00:00.000Z')
);
```
> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` and preserves `known_at` on each row without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing.
### M2 Intraday Contract DDL (Offline)
```typescript
import { getM2IntradayDDL } from '@stock-bot/questdb';
const ddl = getM2IntradayDDL();
// ddl.bars_1m -> CREATE TABLE IF NOT EXISTS bars_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id)
// ddl.fx_1m -> CREATE TABLE IF NOT EXISTS fx_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, pair)
// ddl.bar_revisions -> CREATE TABLE IF NOT EXISTS bar_revisions (...) TIMESTAMP(revised_at) PARTITION BY MONTH WAL
```
M2 intraday tables are opt-in and are not auto-created during `QuestDBClient.connect()`.
## Configuration
Configure using environment variables:
```env
QUESTDB_HOST=localhost
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_INFLUX_PORT=9009
```
## Time-Series Features
QuestDB 10.2.0 supports:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Monthly WAL partitions for intraday tables
- **ASOF JOINs**: Time-series specific joins
- **SAMPLE BY**: Time-based aggregations
- **LATEST ON**: Get latest values per partition key (`LATEST ON <ts> PARTITION BY <keys>`)