Blog
Market data recordingNode.js

Recording Public Trades with Node.js and SQLite

Record validated Bybit public trades in SQLite with bounded buffering, transaction batches, scoped trade IDs, and explicit gaps after a process or connection interruption.

Siebly.io2 min readMarkdown

Use a Separate Parser

Saving valid trade messages does not establish that a recording is complete. A process can lose its connection or stop before a write finishes. A duplicate can also arrive after recovery and must not count as a second trade.

This collector records one Bybit linear BTCUSDT trade feed. It commits batches to SQLite, ignores repeated record identities, and records a gap when a process starts or the connection needs recovery. It does not backfill those gaps.

Save trade-event.mjs from the event validation article in the same directory. That module owns the consumed event shape. The collector below imports it rather than maintaining another parser.

The example requires Node.js 24 with node:sqlite and the bybit-api package. Save it as collect.mjs:

collect.mjs

JavaScript
import { DatabaseSync } from 'node:sqlite';
import { WebsocketClient } from 'bybit-api';
import { decodeBybitTrades } from './trade-event.mjs';

const db = new DatabaseSync('trades.sqlite');
db.exec(`
  CREATE TABLE IF NOT EXISTS trades (
    exchange TEXT, category TEXT, symbol TEXT, trade_id TEXT,
    exchange_time INTEGER, received_time INTEGER,
    price TEXT, quantity TEXT, raw_json TEXT,
    PRIMARY KEY (exchange, category, symbol, trade_id)
  );
  CREATE TABLE IF NOT EXISTS gaps (noticed_time INTEGER, reason TEXT);
`);
const insert = db.prepare(
  'INSERT INTO trades VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING',
);
const gap = db.prepare('INSERT INTO gaps VALUES (?, ?)');
gap.run(Date.now(), 'process-start: preceding interval not verified');
const client = new WebsocketClient();
const queue = [];
let scheduled = false;
let closing = false;

function writeBatch() {
  const batch = queue.splice(0, 128);
  db.exec('BEGIN');
  try {
    for (const { trade, receivedTime } of batch) {
      insert.run(
        'bybit',
        'linear',
        trade.symbol,
        trade.id,
        trade.exchangeTime,
        receivedTime,
        trade.price,
        trade.quantity,
        JSON.stringify(trade.raw),
      );
    }
    db.exec('COMMIT');
  } catch (error) {
    db.exec('ROLLBACK');
    throw error;
  }
}
function flush() {
  scheduled = false;
  if (closing) return;
  try {
    writeBatch();
  } catch (error) {
    stop(error);
    return;
  }
  if (queue.length) {
    scheduled = true;
    setImmediate(flush);
  }
}
function stop(error) {
  if (closing) return;
  closing = true;
  clearTimeout(deadline);
  client.closeAll();
  try {
    if (error) {
      gap.run(Date.now(), 'consumer-failure');
      console.error(error.message);
      process.exitCode = 1;
    } else {
      while (queue.length) writeBatch();
    }
  } catch (failure) {
    console.error(failure.message);
    process.exitCode = 1;
  } finally {
    db.close();
  }
}
client.on('update', (message) => {
  if (closing) return;
  try {
    const trades = decodeBybitTrades(message);
    if (queue.length + trades.length > 4_096) throw new Error('Trade queue overflow');
    const receivedTime = Date.now();
    queue.push(...trades.map((trade) => ({ trade, receivedTime })));
    if (queue.length && !scheduled) {
      scheduled = true;
      setImmediate(flush);
    }
  } catch (error) {
    stop(error);
  }
});
client.on('reconnect', () => {
  if (!closing) {
    try {
      gap.run(Date.now(), 'connection-recovery');
    } catch (error) {
      stop(error);
    }
  }
});
client.on('exception', () => stop(new Error('Trade connection exception')));
const deadline = setTimeout(() => stop(), 20_000);
process.once('SIGINT', () => stop());
try {
  await Promise.all(client.subscribeV5('publicTrade.BTCUSDT', 'linear'));
} catch (error) {
  stop(error);
}

Run node collect.mjs. A normal stop drains queued records before closing the database. A consumer failure stops acceptance and marks the recording incomplete instead of discarding events and continuing to claim continuity.

Preserve Identity at the Write

The primary key scopes the native trade ID by exchange, category, and symbol. Prices and quantities remain decimal strings. Receipt time is stored separately from the exchange's trade time.

The deduplication article explains why a check in memory cannot replace uniqueness at the durable write. ON CONFLICT DO NOTHING here assumes repeated IDs describe the same immutable trade; a system needing conflict detection should compare repeated payloads.

Repair Gaps Deliberately

SQLite calls in this example are synchronous. Batching and yielding limit each drain pass, but a slow disk can still block the event loop. Measure write time and queue age before extending the collector. The event-count limit also does not bound the size of an individual frame.

A gap's notice time is not a proven history cursor. Backfill needs a documented history endpoint, matching record identities, an overlap boundary, and progress saved with committed records. A complete SQLite transaction proves which supplied records were saved; it cannot prove which trades were never received.

Related articles

Continue from here

Related Siebly resources

All articles

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.