Build a U.S. Premarket Watchlist You Can Rerun

TickDB Research ·

Build a U.S. Premarket Watchlist You Can Rerun

Two pulls of the same four stocks gave us different premarket prices about 23 seconds apart. Here’s how to check which quotes belong in your morning scan, keep a missing price visible, and rebuild the watchlist from the exact data you saw.

Tesla was at $407.805 in the Python pull and $407.508 when Codex checked it. Both were from the November 30, 2026, premarket session. The first quote carried a 4:01:11 a.m. Eastern timestamp. The second carried 4:01:31 a.m. Eastern. Those 20 seconds tell you more about the discrepancy than a comparison of the two prices alone.

If you scan for movers before the U.S. opening bell, put the quote time next to the price. Then make the scan answer two questions for every ticker on your list. Does this quote belong to today’s premarket session? Is there enough data to calculate a move from the reference close?

Two Tesla premarket prices on November 30, 2026. Python REST shows $407.805 at 04:01:11 ET. Codex MCP shows $407.508 at 04:01:31 ET.

Tesla quote times, Eastern. The REST response arrived at 4:01:12 a.m. and the successful Codex response at 4:01:34 a.m.

Start with the watchlist, then check what came back

The test used AAPL.US, NVDA.US, TSLA.US, and DORM.US. A Python script requested a TickDB REST snapshot, and Codex called TickDB’s get_ticker tool over MCP. The first MCP request returned HTTP 520. Its retry returned all four stocks. It arrived about 23 seconds after the successful REST response, and the three usable quotes in that response carried timestamps later than the REST receipt.

An earlier check around 2:49 a.m. Eastern also returned four stocks, with all four premarket records dated Friday, November 27. Friday was an early-close day. By Monday’s scan, all four of those records were too old for the new session. After Monday’s 4:00 a.m. premarket open, each route had three usable quotes.

The fourth row was DORM.US. Both responses showed a top-level price of $137.56 from Friday, and a Monday premarket record stamped 4:00 a.m. with a price of zero and volume of zero. DORM.US stays in the watchlist with a “no usable premarket price” status. Leave the price and percentage change blank so a sort can’t turn it into the morning’s biggest decliner.

Use the quote’s clock and its own reference close

Build the check around the New York trading date. For the Nasdaq window used here, accept premarket quote times from 4:00 a.m. up to 9:30 a.m. Eastern, excluding 9:30. Use the millisecond timestamp in pre_market_quote and convert it with America/New_York. For each pull, reject timestamps later than either receipt or your scan cutoff.

For an eligible quote, calculate (last_done / prev_close − 1) × 100 from the two values in that same premarket object. Tesla’s $407.805 against its $400 reference close is about +1.95% in the REST snapshot. If the reference close is missing or invalid, you can show an eligible price and leave the change blank. Keep one row per requested ticker, including symbols omitted from the response.

Keep a quick check and a reproducible run

For a quick Codex check, ask for one ticker’s premarket price, reference close and Eastern quote time. Ask it to call get_ticker and keep the raw response. For a daily handoff, save the requested symbols, trading date, session bounds, cutoff and payloads, along with each response’s receipt time. Save a fresh pull separately when you need an update.

The companion watchlist.py rebuilt all eight rows from the two frozen responses twice. The CSVs matched byte for byte. An offline test also removed a ticker from a sample response and verified that its row stayed in the output with a missing-symbol status. With the saved REST response, its metadata and run/config.json, you can regenerate one side of the check without a new market call:

python3 watchlist.py replay \
  --folder run --config run/config.json \
  --sources rest --output watchlist.csv

Set symbols, trade_date_et, premarket_start_et, premarket_end_et, and an offset-aware observation_cutoff for each run. For a fresh REST pull, use the script’s capture command with your own symbol list and a locally configured TICKDB_API_KEY. Use the snapshot fields and examples on the TickDB U.S. Stock Market Data API page to check your inputs.

Sources

  • Nasdaq, U.S. Market Holidays & Trading Hours, for the session window and November 27 early close.
  • TickDB Docs, Ticker Snapshot, for the premarket fields and epoch timestamps.
  • November 30, 2026, four-symbol test and archived replay.

watchlist.py

"""Capture a US stock snapshot with REST, or build a table from frozen snapshots."""

import argparse
import csv
import hashlib
import io
import json
import os
import re
import ssl
from collections import defaultdict
from datetime import date, datetime, time, timezone
from decimal import Decimal, InvalidOperation
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import HTTPSHandler, HTTPRedirectHandler, Request, build_opener
from zoneinfo import ZoneInfo

ET = ZoneInfo("America/New_York")
SHANGHAI = ZoneInfo("Asia/Shanghai")
ENDPOINT = "https://api.tickdb.ai/v1/market/ticker"
FIELDS = [
    "source", "trade_date_et", "symbol", "company", "status",
    "snapshot_received_et", "cutoff_et", "regular_price", "regular_timestamp_et",
    "premarket_event_ms", "premarket_event_et", "premarket_price_raw",
    "premarket_volume_raw", "premarket_reference_close_raw",
    "eligible_premarket_price", "eligible_change_pct",
]


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def now():
    return datetime.now(timezone.utc)


def write_json(path, data):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def capture_rest(symbols, folder, ca_file):
    key = os.environ.get("TICKDB_API_KEY", "").strip()
    if not key:
        raise SystemExit("TICKDB_API_KEY is missing")

    folder.mkdir(parents=True, exist_ok=True)
    raw_path = folder / "rest.raw.json"
    meta_path = folder / "rest.meta.json"
    if raw_path.exists() or meta_path.exists():
        raise SystemExit("Choose a new capture directory")

    params = {"symbols": ",".join(symbols), "type": "stock"}
    request = Request(
        f"{ENDPOINT}?{urlencode(params)}",
        headers={"X-API-Key": key, "Accept": "application/json", "User-Agent": "TickDB-watchlist/1.0"},
    )
    context = ssl.create_default_context(cafile=ca_file)
    opener = build_opener(HTTPSHandler(context=context), NoRedirect())
    started = now()
    status = body = error = None
    try:
        with opener.open(request, timeout=20) as response:
            status = response.status
            body = response.read()
    except HTTPError as exc:
        status = exc.code
        with exc:
            body = exc.read()
    except (URLError, TimeoutError, OSError) as exc:
        error = type(exc.reason).__name__ if isinstance(exc, URLError) else type(exc).__name__
    received = now()

    code = digest = None
    if body is not None:
        body = body.replace(key.encode(), b"[redacted]")
        raw_path.write_bytes(body)
        digest = hashlib.sha256(body).hexdigest()
        try:
            payload = json.loads(body)
            if isinstance(payload, dict):
                code = payload.get("code")
        except (ValueError, UnicodeError):
            error = "invalid_json"
    meta = {
        "endpoint": ENDPOINT, "method": "GET", "request": params,
        "started_at_utc": started.isoformat(), "received_at_utc": received.isoformat(),
        "received_at_et": received.astimezone(ET).isoformat(),
        "received_at_shanghai": received.astimezone(SHANGHAI).isoformat(),
        "http_status": status, "business_code": code, "error": error, "sha256": digest,
    }
    write_json(meta_path, meta)
    print(json.dumps(meta, ensure_ascii=False))
    return 0 if status == 200 and code == 0 else 1


def event_time(raw):
    if not isinstance(raw, (int, str)) or not re.fullmatch(r"[0-9]{13}", str(raw)):
        return None
    seconds, milliseconds = divmod(int(raw), 1000)
    return datetime.fromtimestamp(seconds, ET).replace(microsecond=milliseconds * 1000)


def positive(raw):
    try:
        value = Decimal(str(raw))
    except InvalidOperation:
        return None
    return value if value.is_finite() and value > 0 else None


def iso(value):
    return value.isoformat(timespec="milliseconds") if value is not None else ""


def classify(record, start, end, received, cutoff):
    if record.get("type") not in (None, "stock"):
        return "unexpected_instrument_type", {}, None
    quote = record.get("pre_market_quote")
    if not isinstance(quote, dict) or not quote:
        return "missing_premarket_object", {}, None
    event = event_time(quote.get("timestamp"))
    if event is None:
        return "missing_or_invalid_premarket_timestamp", quote, event
    if event.date() < start.date():
        return "previous_date", quote, event
    if event.date() != start.date() or not start <= event < end:
        return "outside_premarket_window", quote, event
    if event > min(received, cutoff):
        return "after_observation_cutoff", quote, event
    if positive(quote.get("last_done")) is None:
        return "missing_or_invalid_premarket_price", quote, event
    if positive(quote.get("prev_close")) is None:
        return "price_only_missing_reference_close", quote, event
    return "eligible", quote, event


def frozen_source(folder, source):
    meta = json.loads((folder / f"{source}.meta.json").read_text(encoding="utf-8"))
    raw = folder / f"{source}.raw.json"
    if not raw.exists():
        return meta, {}, "request_failed"
    body = raw.read_bytes()
    if hashlib.sha256(body).hexdigest() != meta["sha256"]:
        raise ValueError(f"{source}: frozen response hash mismatch")
    try:
        payload = json.loads(body)
    except ValueError:
        return meta, {}, "invalid_response"
    if not isinstance(payload, dict):
        return meta, {}, "invalid_response"
    if meta.get("is_error") or meta.get("http_status", 200) != 200 or payload.get("code") != 0:
        return meta, {}, "request_failed"
    if not isinstance(payload.get("data"), list):
        return meta, {}, "invalid_response"
    records = defaultdict(list)
    for record in payload["data"]:
        if isinstance(record, dict) and isinstance(record.get("symbol"), str):
            records[record["symbol"]].append(record)
    return meta, records, None


def rows_for(folder, source, symbols, start, end, cutoff):
    meta, records, failure = frozen_source(folder, source)
    if meta["request"] != {"symbols": ",".join(symbols), "type": "stock"}:
        raise ValueError(f"{source}: frozen request does not match watchlist")
    received = datetime.fromisoformat(meta["received_at_utc"]).astimezone(ET)
    for symbol in symbols:
        candidates = records.get(symbol, [])
        record = candidates[0] if len(candidates) == 1 else {}
        if record:
            status, quote, event = classify(record, start, end, received, cutoff)
        else:
            status = failure or ("duplicate_symbol" if candidates else "missing_symbol")
            quote, event = {}, None
        price = change = None
        if status in ("eligible", "price_only_missing_reference_close"):
            price = positive(quote["last_done"])
        if status == "eligible":
            base = positive(quote["prev_close"])
            change = f"{(price / base - 1) * 100:.4f}"
        yield {
            "source": source, "trade_date_et": start.date().isoformat(), "symbol": symbol,
            "company": record.get("name"), "status": status, "snapshot_received_et": iso(received),
            "cutoff_et": iso(cutoff), "regular_price": record.get("last_price"),
            "regular_timestamp_et": iso(event_time(record.get("timestamp"))),
            "premarket_event_ms": quote.get("timestamp"), "premarket_event_et": iso(event),
            "premarket_price_raw": quote.get("last_done"), "premarket_volume_raw": quote.get("volume"),
            "premarket_reference_close_raw": quote.get("prev_close"),
            "eligible_premarket_price": price, "eligible_change_pct": change,
        }


def replay(folder, config, output, sources):
    settings = json.loads(config.read_text(encoding="utf-8"))
    symbols = parse_symbols(",".join(settings["symbols"]))
    day = date.fromisoformat(settings["trade_date_et"])
    start = datetime.combine(day, time.fromisoformat(settings["premarket_start_et"]), ET)
    end = datetime.combine(day, time.fromisoformat(settings["premarket_end_et"]), ET)
    cutoff = datetime.fromisoformat(settings["observation_cutoff"])
    if cutoff.tzinfo is None or cutoff.astimezone(ET).date() != day or not start < end:
        raise ValueError("Invalid ET session bounds or observation cutoff")
    cutoff = cutoff.astimezone(ET)

    buffer = io.StringIO(newline="")
    writer = csv.DictWriter(buffer, FIELDS, lineterminator="\n")
    writer.writeheader()
    for source in sources:
        writer.writerows(rows_for(folder, source, symbols, start, end, cutoff))
    result = buffer.getvalue().encode("utf-8")
    output.write_bytes(result)
    print(f"{hashlib.sha256(result).hexdigest()}  {output.name}")


def parse_symbols(value):
    symbols = [symbol.strip().upper() for symbol in value.split(",")]
    if len(symbols) > 50 or len(set(symbols)) != len(symbols):
        raise argparse.ArgumentTypeError("Use a unique list of 1–50 symbols")
    if any(not re.fullmatch(r"[A-Z0-9.-]+\.US", symbol) for symbol in symbols):
        raise argparse.ArgumentTypeError("Use US symbols with a .US suffix")
    return symbols


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    capture = commands.add_parser("capture")
    capture.add_argument("--symbols", required=True, type=parse_symbols)
    capture.add_argument("--folder", required=True, type=Path)
    capture.add_argument("--ca-file")
    frozen = commands.add_parser("replay")
    frozen.add_argument("--folder", required=True, type=Path)
    frozen.add_argument("--config", required=True, type=Path)
    frozen.add_argument("--output", required=True, type=Path)
    frozen.add_argument("--sources", nargs="+", choices=("mcp", "rest"), default=("mcp", "rest"))
    args = parser.parse_args()
    if args.command == "capture":
        return capture_rest(args.symbols, args.folder, args.ca_file)
    replay(args.folder, args.config, args.output, args.sources)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Category coverage

US stocks
14,809
12/1/2026

Explore related data tools

Related articles

U.S. Trading Calendar API: How to Schedule After-Close Backfills on Holidays and Early Closes

When scheduling U.S. stock reports or minute-bar backfills, skip confirmed closures, adjust the window on early-close days, and flag failed calendar checks for review. Using an actual calendar response and the 2026 Thanksgiving exchange schedules, we calculate the 210-minute window for November 27 and lay out four scheduling states you can implement.

TickDB Research ·

How to reconcile an ex-dividend price change before the dividend arrives

Microsoft closed \$8.69 lower per share on November 20, 2025, its ex-dividend date. For an eligible holder, adding the \$0.91 gross dividend entitlement gives a price-plus-dividend change of −\$7.78. Here is how to reconcile the price, entitlement and eventual cash receipt.

TickDB Research ·

How to Get US Stock After-Hours Data? Market Data API Integration and Quality Verification

After connecting to a US stock market data API, how do you determine whether the returned prices and volume belong to after-hours trading? This article explains after-hours field reading, cross-midnight time attribution, the difference between missing data and zero volume, and provides reproducible request examples and Python validation code using synthetic samples, helping you check the after-hours data quality of your US stock data source.

TickDB Research ·

Full-Market Real-Time Stock WebSocket Architecture: Streaming 26,000+ US, HK & China A-Share Instruments with permessage-deflate and Backpressure Control (2026)

Polling 26,397 US, Hong Kong, and China A-Share instruments every 2 seconds via batch REST requires 15,840 requests/minute. This guide shares single-run Nov 30, 2026 TLS wire measurements (83.9% REST zstd and 79.1% WS permessage-deflate savings), a 6-tier technical comparison, a Node.js 22+ reference consumer skeleton, and 6 pre-launch checks.

TickDB Research ·