guides

Odds history in SQLite: record every price change from the WebSocket

By · Published · Updated · 6 min read

To keep your own odds history, leave a WebSocket open and write every price change to a database as it arrives. In a 120-second run on NBA, NHL and NCAAB game markets, the script below stored 9,856 price changes from 13 books in a 1.9 MB SQLite file. The PricedOdds API returns current prices and the changes since a cursor, not history, so a history has to be recorded while it happens. The script is one Node file with no packages, using the built-in WebSocket and node:sqlite.

What do I need to record odds history?

  • A PricedOdds API key on a plan with WebSocket access (All-Access, or the WebSocket add-on; see pricing).
  • Node with the global WebSocket and the node:sqlite module, both built in. We ran the script on Node 24.22.1 without installing anything.
  • A machine that stays on. The history only covers the time your script was connected.

How does the script work?

  1. It opens wss://api.pricedodds.com/v1/stream and sends your key in an auth message.
  2. On the ready frame it sends one subscribe with the leagues and the markets (moneyline, spread and total). include: [] leaves out the best and fair prices, so the frames carry only what each book posted.
  3. Every price frame has a book, an event_id and a list of changes. The script writes each change as one row: when it arrived, the book, the selection, the market, the line, the new price in american and the one before it in prev_american. A NULL price means the book pulled it.
  4. All the rows of a frame go in one transaction, and an index on selection, book and time keeps the history queries fast.
  5. If the connection drops, it reconnects and sends resume with the last seq it saw, so the frames missed during the drop arrive before the new ones. It does not retry on close codes 4001, 4002 and 4003, which mean the key, the billing or the plan needs fixing.

The script does not store the snapshot frames that come right after subscribe. Its history starts with the first change of each price; prev_american on that first row gives the price before it. To start with every current price, write the snapshot rows the same way.

What is the code?

// odds-history-sqlite.mjs: keep your own odds history in SQLite from the PricedOdds WebSocket.
// No packages: WebSocket and node:sqlite are built into Node. Usage: PRICEDODDS_API_KEY=... node odds-history-sqlite.mjs
import { DatabaseSync } from "node:sqlite";

const KEY = process.env.PRICEDODDS_API_KEY;
const LEAGUES = (process.env.LEAGUES ?? "nba").split(",");
const MARKETS = ["moneyline", "spread", "total"];
const SECONDS = Number(process.env.SECONDS ?? 300);
const db = new DatabaseSync(process.env.DB ?? "odds-history.db");

db.exec(`
  PRAGMA journal_mode = WAL;
  CREATE TABLE IF NOT EXISTS price_changes (
    received_at   TEXT NOT NULL,      -- ts of the frame, UTC
    seq           INTEGER NOT NULL,   -- stream sequence number
    event_id      TEXT NOT NULL,
    book          TEXT NOT NULL,
    selection_id  TEXT NOT NULL,
    market        TEXT NOT NULL,
    period        TEXT,
    side          TEXT,
    line          REAL,
    american      INTEGER,            -- NULL when the book pulled the price
    prev_american INTEGER
  );
  CREATE INDEX IF NOT EXISTS by_selection ON price_changes (selection_id, book, received_at);
`);
const insert = db.prepare(`INSERT INTO price_changes VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
let lastSeq = 0;
let frames = 0;

function save(frame) {
  const { event_id, book, changes } = frame.data;
  db.exec("BEGIN");
  for (const c of changes) {
    insert.run(frame.ts, frame.seq, event_id, book, c.selection_id, c.market, c.period ?? null,
      c.side ?? null, c.line ?? null, c.american ?? null, c.prev_american ?? null);
  }
  db.exec("COMMIT");
  frames++;
}

function run(resumed = false) {
  const ws = new WebSocket("wss://api.pricedodds.com/v1/stream");
  ws.addEventListener("open", () => ws.send(JSON.stringify({ type: "auth", key: KEY })));
  ws.addEventListener("message", (event) => {
    const frame = JSON.parse(event.data);
    if (frame.seq) lastSeq = Math.max(lastSeq, frame.seq);
    if (frame.type === "ready") {
      // include: [] leaves out the best and fair prices; this history keeps only what each book posted.
      const filters = { leagues: LEAGUES, markets: MARKETS, include: [] };
      ws.send(JSON.stringify(resumed && lastSeq ? { type: "resume", since_seq: lastSeq, ...filters } : { type: "subscribe", ...filters }));
    }
    if (frame.type === "price") save(frame);
    if (frame.type === "error") console.error(frame);
  });
  ws.addEventListener("close", (event) => {
    if (stopping || [4001, 4002, 4003].includes(event.code)) return;   // key, billing or plan: fix the account first
    setTimeout(() => run(true), 2000);
  });
  return ws;
}

let stopping = false;
const ws = run();

setTimeout(() => {
  stopping = true;
  ws.close();
  const one = (sql) => db.prepare(sql).get();
  const t = one(`SELECT COUNT(*) AS rows, COUNT(DISTINCT event_id) AS events, COUNT(DISTINCT book) AS books,
                        COUNT(DISTINCT selection_id) AS selections FROM price_changes`);
  console.log(`stored: ${t.rows} price changes from ${frames} frames, ${t.events} events, ${t.books} books, ${t.selections} selections`);
  // The selection and book that moved most often, and its history.
  const top = one(`SELECT selection_id, book, market, period, side, COUNT(*) AS n FROM price_changes
                   GROUP BY selection_id, book ORDER BY n DESC LIMIT 1`);
  if (!top) return console.log("no price changes in this window");
  console.log(`most changes: ${top.book} ${top.market}@${top.period} ${top.side}, ${top.n} changes`);
  const rows = db.prepare(`SELECT received_at, line, prev_american, american FROM price_changes
                           WHERE selection_id = ? AND book = ? ORDER BY received_at`).all(top.selection_id, top.book);
  for (const r of rows.slice(0, 8)) console.log(`  ${r.received_at}  line ${r.line ?? "-"}  ${r.prev_american ?? "pulled"} -> ${r.american ?? "pulled"}`);
  const size = one(`SELECT page_count * page_size AS bytes FROM pragma_page_count(), pragma_page_size()`);
  console.log(`database: ${(size.bytes / 1e6).toFixed(1)} MB after ${SECONDS} seconds`);
  db.close();
}, SECONDS * 1000);

Run it with PRICEDODDS_API_KEY=$PRICEDODDS_API_KEY node odds-history-sqlite.mjs. By default it records NBA for 300 seconds; set LEAGUES to a comma list of league ids from the coverage page, SECONDS to how long it runs and DB to the file name. To record without a stop, remove the final setTimeout and run it under a process manager.

What did a real run store?

We ran the script on November 25, 2026, 05:41 UTC, with LEAGUES=nba,nhl,ncaab and SECONDS=120, against live prices. Its summary:

stored: 9856 price changes from 2462 frames, 134 events, 13 books, 1738 selections
most changes: kalshi spread@game home, 56 changes
  2026-11-25T05:41:19.699Z  line -25.5  -118 -> -104
  2026-11-25T05:41:20.608Z  line -25.5  -104 -> -109
  2026-11-25T05:41:26.631Z  line -25.5  -109 -> 100
  2026-11-25T05:41:27.698Z  line -25.5  100 -> -118
  2026-11-25T05:41:28.860Z  line -25.5  -118 -> -104
  2026-11-25T05:41:30.624Z  line -25.5  -104 -> 104
  2026-11-25T05:41:33.798Z  line -25.5  104 -> 113
  2026-11-25T05:41:35.191Z  line -25.5  113 -> 122
database: 1.9 MB after 120 seconds

In 120 seconds it wrote 9,856 rows from 2,462 frames, for 134 events and 1,738 selections. The selection that changed most often was a spread at Kalshi, with 56 changes in two minutes; its first rows above show the price going back and forth by a few points. A price that moves several times a minute writes a row each time, so a few busy selections can fill much of the table. These are prices of one night, shown as an example and not as current prices.

The file grew to 1.9 MB in 120 seconds. How fast it grows depends on the hour, the number of games in play and the leagues and books you subscribe to, so watch the size during your first evening before you leave it running.

How do I query the history?

Three queries cover most uses: the price at every book at a given moment, the first and last price of each book, and deleting old rows.

-- 1. The price at every book for one selection at a given moment (:sel, :at).
SELECT book, line, american
FROM price_changes AS p
WHERE selection_id = :sel
  AND received_at = (SELECT MAX(received_at) FROM price_changes
                     WHERE selection_id = p.selection_id AND book = p.book AND received_at <= :at)
ORDER BY book;

-- 2. Per book: the price before the first change you stored, the last price, and how many changes.
SELECT DISTINCT book,
  FIRST_VALUE(prev_american) OVER w AS before_first,
  LAST_VALUE(american) OVER w AS last_price,
  COUNT(*) OVER (PARTITION BY book) AS changes
FROM price_changes
WHERE selection_id = :sel
WINDOW w AS (PARTITION BY book ORDER BY received_at, seq
             ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY changes DESC;

-- 3. Keep the file small: delete what is older than a cutoff (:cutoff).
DELETE FROM price_changes WHERE received_at < :cutoff;

We ran the three of them on the database of that run, for a moneyline selection with changes at 8 books, and :at and :cutoff set to the middle of the run. The first one returned the last stored price of 5 books at that moment:

bet365 1600
betmgm 3300
caesars pulled
draftkings pulled
fanatics 4000

A book appears only once you have stored a change for it before that moment, which is why the other 3 books with changes are missing; storing the snapshot frames fixes that. The second query returned one row per book:

bet365 before 1300, last 1700, 3 changes
betmgm before 2800, last 3300, 3 changes
fanatics before 3500, last 3500, 3 changes
draftkings before none, last pulled, 2 changes
polymarket before 5782, last pulled, 2 changes
caesars before 2200, last pulled, 1 change
fanduel before 2500, last 3500, 1 change
kalshi before 4900, last pulled, 1 change

The third deleted the 4,838 rows of the 9,856 stored before the cutoff. To compare a price with the no-vig fair price, the no-vig calculator takes the two prices of a market, and the implied probability calculator turns one price into a probability.

What can I do with my own odds history?

  • Line movement: see how a price moved before and during a game; line movement explained covers how to read a move.
  • Closing line value: keep the last price before the start and compare it with the price you took; the CLV calculator does the math.
  • Back-testing: test a rule on prices you recorded, at the times you recorded them.
  • Alerts: the same frames can drive alerts while they are written, as in the Discord odds alert bot.

Should I record from the WebSocket or poll for changes?

The WebSocket pushes each change as it arrives, and resume fills short drops, so it is the natural source for a history. Polling GET /v1/changes with a cursor also works, but you get the changes in batches at your polling interval. The trade-offs are in WebSocket vs polling, and a client that keeps prices in memory is in the JavaScript WebSocket tutorial.

What are the limits of a home-made history?

It covers only the time the script was running: the API does not return older prices, so a gap in your recording stays a gap. A resume after a short drop fills it; after a long one the server answers resync and sends a fresh snapshot instead, and the changes in between are lost. The time in each row is when the API received the change, not when the book changed its price. In play, prices follow the score and the clock, so a recorded move is not always a market opinion. Nothing here is betting advice.

To write the subscribe message for other leagues, books or markets, use the WebSocket subscription builder.

FAQ

Does PricedOdds keep historical odds?

No. The API returns current prices and changes, not history. This article shows how to keep your own from the WebSocket.

Why SQLite?

It is a single file, it needs no server, and Node can write to it with the built-in node:sqlite module, so the script has no dependencies. For many machines writing at once, or months of every league, a server database is a better fit; the table and the queries stay the same.

Can I record player props?

Yes. Add the prop markets to MARKETS and a player column for c.player?.name. Props add many selections to each game, so the file grows faster.

Where do I start?

Run the script for two minutes on one league and open the file with any SQLite tool. The fields are in the docs and the books and leagues are on the coverage page. Every plan starts with a 3-day free trial with a $1 card verification that is refunded immediately. The plan you pick at signup is charged from day 4 unless you cancel before the trial ends. See pricing or create an account.