← Back to Pull requests

fix(18 exchanges): report the datetime derived from the timestamp #30199

Open
mkzung opened this pull request with 366 lines diff across 32 files
View on GitHub
mkzung mkzung commented on Aug 31, 2026 16:14 UTC
Author

Every unified structure carries an instant twice, a millisecond integer and a string, and types.ts pairs them: the string is the "ISO8601 datetime with milliseconds" of the integer beside it. The base class writes it one way, this.iso8601 (timestamp).

Twenty exchanges report the exchange's own string there instead. The parser reads that string, makes an integer of it with parse8601, and then reports the string, so the two fields are different instants whenever the exchange's format is not millisecond-Z:

coinbase (fetchTicker) BTC/USDC
timestamp 1713952598063 reads 2024-04-24T09:56:38.063Z
datetime says 2024-04-24T09:56:38.063595Z

Reading every recorded pair in all 382 static fixtures, 1473 of them, gives 41 disagreements over eight exchanges on master and none on this branch. coinbase writes microseconds on rest and nanoseconds on the websocket, alpaca nanoseconds, backpack neither a fraction nor a zone, hitbtc as many digits as it likes: 2021-10-26T08:55:55.1Z beside 22:11:45.03Z.

The shape is in 81 places over 33 exchanges, and most cost nothing today because the exchange happens to send exactly the right format. Sending all 81 would be a change with nothing behind it, so the branch stops where the repository proves a difference: is there any value of that wire field, anywhere in this repository, that is not millisecond-Z? The two places that answer are the maintainers' own record, the comment block above the parser and the static fixtures. On master 42 of the 81 are proven, and this branch fixes those 42 plus twelve that share a file with a proven one, since three survivors beside a corrected fourth guarantee the next reader finds them.

Four are proved by the static suite, having recorded output that carries the wrong string, and restoring any one passthrough turns the suite red: alpaca, backpack, coinbase, delta.

Fifteen have no fixture asserting the method, which is why the passthrough survived. For those the evidence is the wire sample the file itself documents above the parser, run through the parser:

kraken.parseWsTrade 1695378785709 -> 2023-09-22T10:33:05.709Z
from 2023-09-22T10:33:05.709950Z
myriad.parseMyriadMarket 1798761540000 -> 2026-12-31T23:59:00.000Z
from 2026-12-31 23:59:00

and independentreserve 2020-04-01T05:26:30.5093622+00:00, zebpay 2025-03-14T14:34:34.4567, bitso 2022-06-08T12:02:49+0000, bingx 2019-10-12 11:12:02, kalshi 2029-07-01T14:00:00Z, plus blockchaincom, krakenfutures, lbank, onetrading and polymarket the same way. One is proved by construction rather than by a sample: hyperliquid turns an expiry code into 2026-05-03T06:00:00Z.

Two commits are fixtures alone. extended stored a datetime unreachable from any input, the wire carrying only an integer, and datetime sits in that file's skipKeys, so the value was never asserted. coinbase and delta each store a market expiryDatetime their own parsers stopped producing; delta's line carries the comment "do not use raw expiry string".

This should merge after https://github.com/ccxt/ccxt/pull/30192, and the reason is alpaca. pro/alpaca.ts:483 feeds ws frames into the rest parseOrder, and the sample documented above that handler is "submitted_at": "2022-12-16T02:28:51.673015558-05:00", an offset west of Greenwich, which parse8601 cannot read on master:

| state | timestamp | datetime |
|---|---|---|
| master | undefined | 2022-12-16T02:28:51.673015558-05:00 |
| this branch alone | undefined | undefined |
| both | 1671175731673 | 2022-12-16T07:28:51.673Z |

Master already loses the instant; this branch on its own loses the string as well. With the base fix in, both are right. That also surfaced a finding worth stating: alpaca watchOrders returns orders with no timestamp today, because all three datetime fields in that stream carry -05:00 and New York is west of Greenwich in every month, which is why fetchOrder has a timestamp and watchOrders does not.

Asking that of the whole branch, 34 wire keys over 15 exchanges and 230 documented values of them, two are west of Greenwich and both are alpaca's ws order frame.

Only parsed output is touched in the fixtures; no httpResponse and no info. Static response, request and ws tests pass in JS and Python. Each of the four fixture-backed exchanges fails alone when its passthrough is restored: alpaca 5, backpack 1, delta 1, coinbase 1.

The 27 places left are unproven rather than safe: every documented and recorded value there is millisecond-Z, so nothing in the repository shows a difference, and hitbtc and bitmex both vary format by endpoint elsewhere.

Diff: 366 lines (+175 / -191) across 32 files Reviewer: carlotestor Review duration: 137457m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.74) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.74 · 366 lines diff across 32 files
0.74
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.353
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
14 items
carlotestor carlotestor commented on code on Aug 31, 2026 16:26 UTC
Code Review
ts/src/pro/lbank.ts:1
@@ -363,12 +363,12 @@ export default class lbank extends lbankRest {
         //
         const marketId = this.safeString (ticker, 'pair');
         const symbol = this.safeSymbol (marketId, market);
-        const datetime = this.safeString (ticker, 'TS');
+        const timestamp = this.parse8601 (this.safeString (ticker, 'TS'));

parseWsTicker is fixed here, but parseWsTrade at line 534 in this same file still passes the raw TS through as 'datetime': datetime, reading the same wire key. The sample documented above it is "TS":"2019-06-28T19:55:49.460" — no zone — and running it through the parser on this branch gives timestamp 1561751749460 beside datetime "2019-06-28T19:55:49.460", while the derived string is "2019-06-28T19:55:49.460Z". Documented and divergent, so it meets the same bar as the fifteen you included, and it is the last one in this file.

carlotestor carlotestor commented on code on Aug 31, 2026 16:26 UTC
Code Review
ts/src/prediction/polymarket.ts:1
@@ -2629,10 +2632,10 @@ export default class polymarket extends Exchange {
             'active': active,
             'url': this.safeString (rawEvent, 'url'),
             'image': this.safeString2 (rawEvent, 'image', 'image_url'),
-            'created': this.parse8601 (createdAt),
-            'createdDatetime': createdAt,
-            'end': this.parse8601 (endDate),
-            'endDatetime': endDate,
+            'created': created,
+            'createdDatetime': this.iso8601 (created),
+            'end': end,
+            'endDatetime': this.iso8601 (end),
             'category': this.safeString (rawEvent, 'category'),
             'lastUpdatedAt': this.parse8601 (updatedAt),
             'lastUpdatedAtDatetime': updatedAt,

createdDatetime and endDatetime are now derived, but lastUpdatedAtDatetime two lines below still returns the raw updatedAt. Gamma sends microseconds on that key — the comment block above this method documents "updatedAt": "2026-03-14T14:38:21.25643Z" and ts/src/test/static/events/polymarket.json records "updatedAt": "2026-06-12T18:19:21.195957Z" — so parseEvent currently returns lastUpdatedAt 1773499101256 next to lastUpdatedAtDatetime "2026-03-14T14:38:21.25643Z" where the derived string is "2026-03-14T14:38:21.256Z". Same one-line fix: hoist const lastUpdatedAt = this.parse8601 (updatedAt); and use this.iso8601 (lastUpdatedAt).

carlotestor carlotestor commented on Aug 31, 2026 16:26 UTC
Reviewer

Summary

The invariant is right and the diff is a faithful application of it: timestamp is the source, datetime is this.iso8601 (timestamp), and the base class already does exactly this in safeOrder, parseOrderBook and parseLedgerEntry. Every hunk here is the same mechanical shape — hoist parse8601 into a timestamp local, derive the string from it — so it reads uniformly and transpiles the same way in all six languages (iso8601 is a base method with matching implementations in Exchange.Time.cs, exchange_time.go, php/Exchange.php and python/ccxt/base/exchange.py).

Verification I ran on f9b947d

Worktree at the PR head, toolchain from master:

  • tsc --noEmit — exit 0.

  • Scoped eslint over all 24 changed .ts files — 5 errors, all in ts/src/prediction/{hyperliquid,kalshi,myriad,polymarket}.ts at the import block (lines 6/9/11/22), and identical on origin/master. Pre-existing, not this PR.

  • npm run response-js on every fixture-backed exchange: alpaca 16, backpack 31, coinbase 10, coinbaseinternational 13, delta 9, extended 41 — all green.

  • npm run ws-tests-js -- coinbase — 2 passed.

  • The fixture churn is genuinely the parser's new output, not a hand edit. Spot-checked response/extended.json: master recorded timestamp: 1754050449502 next to "datetime": "2025-08-01T10:54:09.502Z", and iso8601 (1754050449502) is 2025-08-01T12:14:09.502Z — the two fields were 80 minutes apart, and datetime sits in that file's skipKeys so nothing caught it. The new value is the derived one.
  • On the #30192 ordering

    Confirmed rather than taken on trust — ran parseOrder on the ws order frame documented above parseWsOrder (submitted_at: "2022-12-16T02:28:51.673015558-05:00") against both trees:

    | | timestamp | datetime |
    |---|---|---|
    | master | undefined | 2022-12-16T02:28:51.673015558-05:00 |
    | this branch | undefined | undefined |

    So the table in the description is accurate, and the collateral finding is real: alpaca ws orders carry no timestamp on master today because parse8601 cannot read a negative offset. Merging this before #30192 trades a wrong string for a missing one on that one path — still an improvement in consistency, but #30192 first is the right order, as stated.

    Two survivors your own inclusion rule reaches

    The stated rule is "proven, plus twelve that share a file with a proven one, since three survivors beside a corrected fourth guarantee the next reader finds them." Two passthroughs sit in files this PR already corrects and are provably divergent from the samples documented in those same files — flagged inline. Both are one-line, same shape as the rest; including them would leave those two files clean rather than half-clean. Not merge-blocking.

    Merge gate: 🟢
    Merge probability: 83%

    mkzung mkzung commented on code on Sep 01, 2026 16:55 UTC
    Code Review
    ts/src/pro/lbank.ts:1
    @@ -363,12 +363,12 @@ export default class lbank extends lbankRest {
             //
             const marketId = this.safeString (ticker, 'pair');
             const symbol = this.safeSymbol (marketId, market);
    -        const datetime = this.safeString (ticker, 'TS');
    +        const timestamp = this.parse8601 (this.safeString (ticker, 'TS'));

    Half of that holds. The main path derives: datetime is iso8601 (timestamp) whenever the integer is present. What leaks is the fallback, where the raw TS goes out as the docstring's "2019-06-28T19:55:49.460", no zone. Fixing the fallback.

    mkzung mkzung commented on code on Sep 01, 2026 16:55 UTC
    Code Review
    ts/src/prediction/polymarket.ts:1
    @@ -2629,10 +2632,10 @@ export default class polymarket extends Exchange {
                 'active': active,
                 'url': this.safeString (rawEvent, 'url'),
                 'image': this.safeString2 (rawEvent, 'image', 'image_url'),
    -            'created': this.parse8601 (createdAt),
    -            'createdDatetime': createdAt,
    -            'end': this.parse8601 (endDate),
    -            'endDatetime': endDate,
    +            'created': created,
    +            'createdDatetime': this.iso8601 (created),
    +            'end': end,
    +            'endDatetime': this.iso8601 (end),
                 'category': this.safeString (rawEvent, 'category'),
                 'lastUpdatedAt': this.parse8601 (updatedAt),
                 'lastUpdatedAtDatetime': updatedAt,

    Missed it. lastUpdatedAt parses the raw value on 2637 and lastUpdatedAtDatetime returns it unparsed on 2638. Fixing with the rest.

    carlotestor carlotestor commented on Sep 04, 2026 18:32 UTC
    Reviewer

    Follow-up on f740e49 (test(coinbase, delta): record the expiryDatetime the parsers return).

    Two one-line market-fixture updates, and both are the derived value rather than a hand edit — checked each against the expiry integer sitting beside it:

    | file | expiry | recorded now |
    |---|---|---|
    | ts/src/test/static/markets/coinbase.json | 1714143600000 | 2024-04-26T15:00:00.000Z |
    | ts/src/test/static/markets/delta.json | 1711713600000 | 2024-03-29T12:00:00.000Z |

    iso8601 on those integers gives exactly the new strings, so the stored .000Z is now reachable from the input where the previous bare-Z form was not. Same shape as the extended fixture commit earlier on the branch, and consistent with the do not use raw expiry string comment already on delta's line.

    Nothing new to raise on this commit, and nothing here touches the two survivors flagged inline on the previous review.

    Merge gate: 🟢

    mkzung mkzung commented on Sep 15, 2026 16:11 UTC
    Author

    Both are in and pushed: pro/lbank and prediction/polymarket lastUpdatedAtDatetime were the same mechanical change as the rest of the branch.

    The branch is conflicting a long way behind master now. The rebase onto master is built and held locally, 35 files, one conflict in ts/src/hitbtc.ts that upstream caused by moving positions to safeList. Say whether you would rather have it force-pushed here or opened fresh.

    mkzung mkzung commented on Sep 22, 2026 20:54 UTC
    Author

    Force-pushed the rebase as one commit on master, and it fixes something the old head had wrong: four prediction guards written ((a) && (b)) ? x : y transpiled to Python with no else, so kalshi, myriad and polymarket did not import. They now use master's own shape for the same guard and all three parse. Five files conflicted, each kept at master's shape with the datetime derived, and master's alpaca fetchOrders case stores the derived datetime.

    carlotestor carlotestor commented on Sep 22, 2026 20:54 UTC
    Reviewer

    Follow-up on 2a29d16 (rebase onto master as one commit).

    The branch is squashed onto 1d8b674. The conflict resolutions keep master's typed accessors (safeDict / safeList), parse the timestamp once and derive datetime from it, which is the same shape as the rest of the branch. The prediction guard change is also right: dropping the inner parentheses leaves one bracketed condition, (endDate !== undefined && endDate !== '') ? this.parse8601 (endDate) : undefined, hoisted into a local and out of the dict literal. That avoids the else-less conditional the Python transpiler produced from ((a) && (b)) ? x : y.

    Both survivors from the first review are fixed at this head:

  • ts/src/pro/lbank.ts parseWsTrade now returns 'datetime': this.iso8601 (timestamp) (line 533).

  • ts/src/prediction/polymarket.ts parseEvent now parses updatedAt once and returns 'lastUpdatedAtDatetime': this.iso8601 (lastUpdated) (line 2639).
  • Nothing new to raise on this commit.

    Merge gate: 🟢

    carlotestor carlotestor commented on Oct 02, 2026 00:37 UTC
    Reviewer

    Follow-up on 1ddbcbf (second squash-rebase, onto 8ee4326).

    Compared against the previously reviewed squash 2a29d16 with git range-diff. Nearly every difference is master context the patch now sits on, such as marketResolved locals, handleBookDeltas, safeList typing, and the kraken takerOrMaker unfold. The PR's own +/- lines change in only two places, and both are correct:

  • ts/src/pro/lbank.ts parseWsTrade: master had already rewritten the ternary into an if/else. The resolution drops that block and keeps the same end state: timestamp from [0], falling back to parse8601 (TS), then 'datetime': this.iso8601 (timestamp).

  • ts/src/test/static/response/coinbaseinternational.json: the fetchFundingRateHistory record master stores has lost its fundingDatetime key, so only the datetime line changes now (...11:00:00Z → ...11:00:00.000Z). That matches iso8601 (1709809200000).
  • I found no new raw passthroughs on the PR's added lines, no blank lines inside methods and no || coalescing. The four prediction guards are still single-bracket hoisted ternaries.

    Farm job 2618 at this head ran js,python scoped to alpaca, backpack, coinbase, coinbaseinternational, delta, extended, kalshi and polymarket. It succeeded, including the static suites.

    The two survivors from the first review are still fixed at this head (pro/lbank.ts parseWsTrade, polymarket.ts lastUpdatedAtDatetime). Nothing new to raise.

    Merge gate: 🟢

    carlotestor carlotestor commented on Oct 06, 2026 15:12 UTC
    Reviewer

    Follow-up on 7d9c8ed (third squash-rebase, onto 5ab8292).

    I compared it with the previously reviewed squash 1ddbcbf using git range-diff. The PR's own +/- lines differ in one hunk only, ts/src/bingx.ts parseTransaction. Master's #30745 (parse deposit and withdrawal status by direction) had already changed this method to derive the string, using a datetime local that is set to this.iso8601 (timestamp) both before and after the applyTime fallback. The resolution removes that local and returns 'datetime': this.iso8601 (timestamp) inline, which is the same shape as the rest of the branch. For both paths (insertTime/timestamp and the applyTime fallback) the returned value is the same as on master. The rebase also keeps master's new parseTransactionStatus (…, type) argument.

    Everything else is unchanged from 1ddbcbf. Both items from the first review are still fixed at this head: pro/lbank.ts parseWsTrade (line 533) and polymarket.ts lastUpdatedAtDatetime (line 2662). There is nothing new to raise.

    Merge gate: 🟢

    mkzung mkzung commented on Oct 21, 2026 16:40 UTC
    Author

    Rebased onto master. I dropped coinbaseinternational: master rewrote it for the Deribit API and none of its hunks apply. Tests pass for the other 18 in JS and Python.

    mkzung mkzung commented on Nov 12, 2026 01:17 UTC
    Author

    Rebased onto master. alpaca parseTransaction and the pro/coinbase ticker conflicted; both keep master's shape with the derived datetime. Static tests pass for all 18 in JS and Python.

    Reviewers
    Assignees
    mkzung mkzung
    Labels
    risk: low confidence: 88.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 73.9% (HIGH) · Higher = larger blast radius
    73.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.8% · Lower = rushed or shallow review
    88.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.3% · Safe to merge
    8.3%
    Repository