DEV Community

Cover image for HiBid auction reports in Python: separate bid changes from countdown drift
Dataspryva
Dataspryva

Posted on Fully Autonomous

HiBid auction reports in Python: separate bid changes from countdown drift

Your daily report says nearly every watched lot changed. Before you send it, look at the column doing most of the work: timeLeftSeconds.

A countdown can change while the auction changes nothing. Once a lot closes, real-time fields such as timeLeft can also become historical or stale, and the Actor returns whatever the public API reports.

A countdown difference is not evidence that an auction deadline moved.

The small fix is to stop giving every changed value the same vote. Compare reported bids and auction states directly. Put countdown arithmetic in a separate diagnostic column.

Your manager gets a report about auction changes. The clock can keep its own diary.

Hold the watched lots steady

A fresh search answers “what matches now?” A tracker needs a different question: “what happened to the lots you were already watching?”

Those populations can diverge. A lot disappearing from a search is a coverage observation, not proof that bidding closed.

Use mode="lotDetails" with an explicit lotIds watchlist so the requested population stays fixed. Keep that input alongside your collection metadata.

Example watchlist input, using replaceable lot identifiers:

import os
import json
import re
from decimal import Decimal

import pandas as pd
import duckdb
from apify_client import ApifyClient

run_input = {
    "mode": "lotDetails",
    "lotIds": ["309402453", "309009599"],
    "maxItems": 50,
}

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "dataspryva/hibid-auction-lots-bids-and-auctioneer-directory"
).call(run_input=run_input)

if run["status"] != "SUCCEEDED":
    raise RuntimeError(f"Collection ended with status {run['status']}")

items = client.dataset(run["defaultDatasetId"]).list_items().items
Enter fullscreen mode Exit fullscreen mode

Keep unmatched requested identifiers in a collection coverage report. Don't manufacture an isClosed value for a record you didn't receive.

Give each observation a defensible key

Use lotId as the source identifier and scrapedAt as the observation timestamp. Together, they identify a stored snapshot.

A title is editable text. A row's position is collection order. Neither belongs in the identity key.

This storage convention doesn't establish an upstream guarantee against identifier reuse. If a watched record starts describing something incompatible, inspect its retained payload before treating the difference as ordinary activity.

The fields divide into useful comparison groups:

Fields Treatment
currentBid, currency, bidCount Compare known values; require matching, known currency for bid amounts
isClosed, isLive, isArchived Compare known flags as reported state transitions
biddingExtended Compare the reported flag separately from countdown arithmetic
timeLeftSeconds Use for a timing diagnostic under conservative conditions
timeLeft, timeLeftTitle Keep as context rather than event triggers
softCloseMinutes, softCloseSeconds Treat as rules, not evidence that an extension happened

A changed soft-close rule may deserve attention. Its presence doesn't establish that the rule fired.

Keep missing values missing

Empty fields are omitted from records. Turning an absent flag into False would invent an auction state; turning an absent bid into zero would invent a price movement.

Formatted amounts need similar care. Parse the recognised representation, retain the original record, and leave unrecognised values unknown.

This cell normalises comparison fields without guessing at arbitrary text:

fields = [
    "lotId", "scrapedAt", "currentBid", "currency", "bidCount",
    "timeLeftSeconds", "isClosed", "isLive", "isArchived",
    "biddingExtended",
]
frame = pd.DataFrame(items).reindex(columns=fields)

def money_text(value):
    text = str(value).strip()
    if not re.fullmatch(
        r"\$?\s*(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?", text
    ):
        return None
    amount = Decimal(text.replace("$", "").replace(",", "").strip())
    canonical = format(amount, "f")
    return canonical.rstrip("0").rstrip(".") if "." in canonical else canonical

def nullable_flag(value):
    if isinstance(value, bool):
        return value
    if isinstance(value, str):
        return {"true": True, "false": False}.get(value.strip().lower())
    return None

frame["lotId"] = frame["lotId"].astype("string").str.strip()
frame["scrapedAt"] = pd.to_datetime(
    frame["scrapedAt"], errors="coerce", utc=True
)
frame["currentBid"] = frame["currentBid"].map(money_text).astype("string")
frame["currency"] = (
    frame["currency"].astype("string").str.strip().replace("", pd.NA)
)

for field in ("bidCount", "timeLeftSeconds"):
    frame[field] = pd.to_numeric(
        frame[field].astype("string").str.replace(",", "", regex=False),
        errors="coerce",
    ).astype("Float64")
    frame[field] = frame[field].where(frame[field].ge(0))

for field in ("isClosed", "isLive", "isArchived", "biddingExtended"):
    frame[field] = frame[field].map(nullable_flag).astype("boolean")

frame["payload"] = pd.Series(
    [json.dumps(item, ensure_ascii=False) for item in items],
    dtype="string",
)

invalid_key = (
    frame["lotId"].isna()
    | frame["lotId"].eq("").fillna(False)
    | frame["scrapedAt"].isna()
)
quarantine = frame.loc[invalid_key].copy()
batch = frame.loc[~invalid_key].copy()

if batch.duplicated(["lotId", "scrapedAt"]).any():
    raise ValueError("Duplicate observation keys require inspection")
Enter fullscreen mode Exit fullscreen mode

The amount parser produces canonical decimal text, so formatting differences don't become bid changes. It doesn't infer currency from a symbol.

quarantine holds records that can't enter an ordered history safely. A collection-time fallback would make those rows sortable, but it would quietly change what their timestamps mean.

Store observations before comparing them

Append snapshots rather than replacing the previous record. You need the earlier observation to explain a change, and the payload to inspect a questionable comparison.

The notebook uses an in-memory database to stay self-contained. A scheduled collector needs the same table in durable storage, retained between collections. Its initial collection establishes a baseline.

This cell creates the keyed table and inserts the batch together:

con = duckdb.connect()
con.execute("""
    CREATE TABLE IF NOT EXISTS snapshots (
        lotId VARCHAR,
        scrapedAt TIMESTAMPTZ,
        currentBid VARCHAR,
        currency VARCHAR,
        bidCount DOUBLE,
        timeLeftSeconds DOUBLE,
        isClosed BOOLEAN,
        isLive BOOLEAN,
        isArchived BOOLEAN,
        biddingExtended BOOLEAN,
        payload VARCHAR,
        PRIMARY KEY (lotId, scrapedAt)
    )
""")
con.register("incoming", batch)
con.execute("INSERT INTO snapshots BY NAME SELECT * FROM incoming")
con.unregister("incoming")
Enter fullscreen mode Exit fullscreen mode

The primary key also rejects collisions with observations already stored. Resolve those collisions explicitly: an exact replay and a conflicting payload deserve different handling.

Silently keeping whichever record arrived first is a surprisingly efficient way to lose an argument later.

Compare reported bids and states in SQL

For this worked example, HiBid Auction Lots, Bids & Auctioneer Directory supplies the observations. The comparison pattern applies whenever a record mixes business state with relative time.

Use LAG within each lot's history. Compare each flag independently so an absent archive flag doesn't erase a known closure transition.

This query leaves unavailable comparisons as SQL NULL:

con.execute("""
    CREATE OR REPLACE TEMP VIEW comparisons AS
    WITH previous AS (
        SELECT *,
            lag(scrapedAt) OVER w AS prev_at,
            lag(currentBid) OVER w AS prev_bid,
            lag(currency) OVER w AS prev_currency,
            lag(bidCount) OVER w AS prev_count,
            lag(timeLeftSeconds) OVER w AS prev_seconds,
            lag(isClosed) OVER w AS prev_closed,
            lag(isLive) OVER w AS prev_live,
            lag(isArchived) OVER w AS prev_archived,
            lag(biddingExtended) OVER w AS prev_extended
        FROM snapshots
        WINDOW w AS (PARTITION BY lotId ORDER BY scrapedAt)
    )
    SELECT *,
        CASE WHEN currentBid IS NOT NULL AND prev_bid IS NOT NULL
                  AND currency IS NOT NULL AND prev_currency IS NOT NULL
                  AND currency = prev_currency
             THEN currentBid <> prev_bid END AS bid_changed,
        CASE WHEN bidCount IS NOT NULL AND prev_count IS NOT NULL
             THEN bidCount <> prev_count END AS count_changed,
        CASE WHEN isClosed IS NOT NULL AND prev_closed IS NOT NULL
             THEN isClosed <> prev_closed END AS closed_changed,
        CASE WHEN isLive IS NOT NULL AND prev_live IS NOT NULL
             THEN isLive <> prev_live END AS live_changed,
        CASE WHEN isArchived IS NOT NULL AND prev_archived IS NOT NULL
             THEN isArchived <> prev_archived END AS archive_changed,
        CASE WHEN biddingExtended IS NOT NULL AND prev_extended IS NOT NULL
             THEN biddingExtended <> prev_extended END AS extension_flag_changed
    FROM previous
    WHERE prev_at IS NOT NULL
""")
Enter fullscreen mode Exit fullscreen mode

These are reported value changes, not a reconstructed event ledger. A bid-count decrease remains a change worth inspecting; the query doesn't quietly force it into an expected direction.

Keep transitions in both directions. A changed extension flag means the source reported a different flag, not that you've counted an extension event.

Treat countdown residuals as review candidates

For an unchanged deadline, the countdown should fall by approximately the elapsed observation time.

Add elapsed time back to the countdown difference. The remainder is a diagnostic residual: a positive value means the later countdown is longer than simple clock passage would predict.

Rounding, collection timing, stale values and an actual extension can all complicate that interpretation. Choose a tolerance for review, not a threshold that magically proves causation.

This cell computes the residual only when both observations explicitly report an open, unarchived lot:

timing_tolerance_seconds = 30

compared = con.execute("""
    SELECT *,
        CASE WHEN isClosed = FALSE AND prev_closed = FALSE
                  AND isArchived = FALSE AND prev_archived = FALSE
                  AND timeLeftSeconds IS NOT NULL
                  AND prev_seconds IS NOT NULL
                  AND scrapedAt > prev_at
             THEN timeLeftSeconds - prev_seconds
                  + epoch(scrapedAt - prev_at)
        END AS countdown_residual
    FROM comparisons
""").df()

compared["timing_review"] = (
    compared["countdown_residual"]
    .gt(timing_tolerance_seconds)
    .fillna(False)
)

change_columns = [
    "bid_changed", "count_changed", "closed_changed",
    "live_changed", "archive_changed", "extension_flag_changed",
]
report = compared.loc[
    compared[change_columns].fillna(False).any(axis=1)
    | compared["timing_review"],
    [
        "lotId", "prev_at", "scrapedAt", *change_columns,
        "countdown_residual", "timing_review",
    ],
].copy()

comparison_gaps = compared.loc[
    compared[change_columns].isna().any(axis=1)
].copy()

con.close()
Enter fullscreen mode Exit fullscreen mode

The report keeps reported changes and timing candidates in separate columns. comparison_gaps preserves the distinction between “unchanged” and “couldn't compare”.

Closed observations can't generate a deadline interpretation here. Unknown status also fails the timing gate. An apparently open record could still contain a stale countdown, so even a qualifying residual remains a review candidate.

The gap between observations stays a gap

Polling establishes states at observation times. It doesn't establish the exact moment of a closure, bid or extension, and changes can occur between collections without surviving into the next snapshot.

The public bid ledger is aggregated by amount. It doesn't supply bidder identities or per-bid timestamps.

Your report can defend “the reported bid changed between these observations”. It can't defend “this bid arrived at this instant” from these snapshots alone.

Let the uncertainty keep its column. The clock has already contributed enough fiction.

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)