dexbot 1.6.18 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +95 -3
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  8. package/dist/analysis/analyze_kalman.js +3 -2
  9. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  10. package/dist/analysis/analyze_liquidity.js +325 -0
  11. package/dist/analysis/analyze_regime.js +3 -2
  12. package/dist/analysis/analyze_regime_windows.js +3 -2
  13. package/dist/analysis/analyze_volatility.js +3 -2
  14. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  15. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  16. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  17. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  18. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  19. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  20. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  21. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  22. package/dist/analysis/trade_profitability.js +2 -1
  23. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  24. package/dist/dexbot.js +74 -169
  25. package/dist/modules/asset_lookup.d.ts +25 -0
  26. package/dist/modules/asset_lookup.js +75 -0
  27. package/dist/modules/chain_scan.d.ts +64 -0
  28. package/dist/modules/chain_scan.js +80 -0
  29. package/dist/modules/cli_colors.d.ts +5 -0
  30. package/dist/modules/cli_colors.js +7 -0
  31. package/dist/modules/cli_progress.d.ts +51 -0
  32. package/dist/modules/cli_progress.js +113 -0
  33. package/dist/modules/dexbot_cow_runtime.js +14 -4
  34. package/dist/modules/dexbot_fill_runtime.js +20 -0
  35. package/dist/modules/dexbot_maintenance_runtime.js +16 -1
  36. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  37. package/dist/modules/launcher/runtime_entry.js +36 -1
  38. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  39. package/dist/modules/liquidity_pool_ref.js +116 -0
  40. package/dist/modules/order/grid.js +9 -2
  41. package/dist/modules/order/grid_reconcile.js +22 -1
  42. package/dist/modules/order/grid_reconcile_internal.js +92 -14
  43. package/dist/modules/order/index.d.ts +15 -1
  44. package/dist/modules/order/manager.d.ts +2 -0
  45. package/dist/modules/order/manager.js +3 -0
  46. package/dist/modules/order/sync_engine.d.ts +20 -0
  47. package/dist/modules/order/sync_engine.js +101 -33
  48. package/dist/modules/order/utils/math.d.ts +18 -1
  49. package/dist/modules/order/utils/math.js +30 -1
  50. package/dist/modules/order/utils/order.d.ts +107 -1
  51. package/dist/modules/order/utils/order.js +298 -1
  52. package/dist/modules/order/utils/system.d.ts +63 -1
  53. package/dist/modules/order/utils/system.js +247 -36
  54. package/dist/modules/order/utils/validate.js +33 -2
  55. package/dist/modules/types.d.ts +5 -0
  56. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  57. package/dist/modules/utils/asset_symbols.js +21 -2
  58. package/dist/scripts/analysis_runner.d.ts +10 -0
  59. package/dist/scripts/analysis_runner.js +33 -0
  60. package/dist/scripts/analyze-orders.js +2 -1
  61. package/dist/scripts/asset.d.ts +26 -0
  62. package/dist/scripts/asset.js +165 -0
  63. package/dist/scripts/bts_distribution.d.ts +1 -0
  64. package/dist/scripts/bts_distribution.js +194 -142
  65. package/dist/scripts/chart_command.d.ts +1 -1
  66. package/dist/scripts/chart_command.js +60 -86
  67. package/dist/scripts/chart_targets.d.ts +18 -0
  68. package/dist/scripts/chart_targets.js +52 -0
  69. package/dist/scripts/dw.js +1 -1
  70. package/dist/scripts/liquid.d.ts +24 -0
  71. package/dist/scripts/liquid.js +134 -0
  72. package/dist/scripts/rich_list.js +12 -16
  73. package/dist/scripts/token_distribution.d.ts +2 -0
  74. package/dist/scripts/token_distribution.js +132 -108
  75. package/dist/scripts/tv.js +1 -1
  76. package/dist/scripts/verify-browser-bundle.js +18 -0
  77. package/docs/COW_INVARIANTS.md +2 -2
  78. package/docs/DEXBOT_COMPARISON.md +6 -6
  79. package/docs/EVOLUTION.md +9 -8
  80. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  81. package/docs/GRID_PRICE_INVARIANT.md +4 -1
  82. package/docs/GRID_RECONCILE.md +20 -0
  83. package/docs/LOGGING.md +25 -3
  84. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +2 -1
  85. package/docs/README.md +1 -1
  86. package/docs/WORKFLOW.md +3 -1
  87. package/modules/README.md +5 -1
  88. package/package.json +3 -1
  89. package/scripts/README.md +23 -7
@@ -1375,6 +1375,13 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
1375
1375
  // fill outside its window necessarily puts that slot inside the implied
1376
1376
  // band. Allow exactly that residual (PARTIAL, same side, same ladder
1377
1377
  // level); every other in-band order still refuses the re-anchor.
1378
+ //
1379
+ // ANCHOR-AWARE: the residual sits at the slot the re-anchor is derived
1380
+ // from (`anchorIdx`), which is the batch EXTREMUM, not necessarily the
1381
+ // last-processed pivot (`idx`). Comparing against `idx`/`price` made this
1382
+ // allow-list dead code for every chunked sweep whose furthest fill is not
1383
+ // the pivot — i.e. exactly the case the extremum resolution exists for —
1384
+ // so the re-anchor was refused as 'unsafe: placed_order_in_band'.
1378
1385
  const allowedInBandSlotIds = [];
1379
1386
  const fillSlotOrder = Array.isArray(slots) ? slots[anchorIdx] : null;
1380
1387
  if (fillSlotOrder && fillSlotOrder.orderId
@@ -1388,8 +1395,8 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
1388
1395
  orderIdx = null;
1389
1396
  }
1390
1397
  const orderPrice = Number(fillSlotOrder.price);
1391
- if (orderIdx === idx && Number.isFinite(orderPrice) && orderPrice > 0
1392
- && Math.abs(orderPrice - price) / price <= maxDrift) {
1398
+ if (orderIdx === anchorIdx && Number.isFinite(orderPrice) && orderPrice > 0
1399
+ && Math.abs(orderPrice - anchorPrice) / anchorPrice <= maxDrift) {
1393
1400
  allowedInBandSlotIds.push(String(fillSlotOrder.id));
1394
1401
  }
1395
1402
  }
@@ -1487,23 +1494,123 @@ function resolveFillAnchorIndex(fills, side, genesis, maxDrift) {
1487
1494
  * live pivot only when `lastFillPivotSource === 'fill'`; otherwise fall back to
1488
1495
  * the bot-scoped last-market-fill row, which is written only by real fills and
1489
1496
  * survives grid regeneration.
1497
+ *
1498
+ * Read-time TTL applies here too (see resolveFillProvenancedRow): an absolute
1499
+ * geometry move must not be derived from a fill older than the pivot lifetime.
1500
+ *
1490
1501
  * @param {Object} manager - OrderManager instance
1491
1502
  * @returns {{price: number|null, type: string|null}}
1492
1503
  */
1493
1504
  function resolveFillProvenancedReference(manager) {
1494
- if (manager?.lastFillPivotSource === 'fill') {
1495
- const livePrice = Number(manager?._lastFilledPrice);
1496
- const liveType = manager?._lastFilledType;
1497
- if (Number.isFinite(livePrice) && livePrice > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
1498
- return { price: livePrice, type: liveType };
1499
- }
1505
+ const row = resolveFillProvenancedRow(manager);
1506
+ return { price: row?.price ?? null, type: row?.type ?? null };
1507
+ }
1508
+ /**
1509
+ * The pivot lifetime, in ms. 0 means "no lifetime configured" (never expire).
1510
+ * ONE reader for GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS: the persisted-row
1511
+ * restores, the read-time guards and the re-arm all derive from it.
1512
+ */
1513
+ function lastFillPivotTtlMs() {
1514
+ const ttl = Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS);
1515
+ return Number.isFinite(ttl) && ttl > 0 ? ttl : 0;
1516
+ }
1517
+ /**
1518
+ * Is a fill reference older than the pivot lifetime?
1519
+ *
1520
+ * The same bound applies at every reading of a fill reference:
1521
+ * `restoreLastFillPivot` / `restoreLastMarketFill` (persisted rows) and
1522
+ * `resolveLastFillGuardReference` / `resolveFillProvenancedRow` (in-memory
1523
+ * rows). Without the read-time half, a long-lived process keeps a fill older
1524
+ * than 24h vetoing one side forever — and the geometry-bind watchdog
1525
+ * re-centers at most ONCE per pivot and then reports that "a fill or the pivot
1526
+ * TTL restores the side" (trackOutOfSpreadStaleness), a promise the code must
1527
+ * keep without a restart.
1528
+ *
1529
+ * An unknown age (missing/0 timestamp) never expires: legacy managers and the
1530
+ * ambiguous two-sided book seed carry no fill clock, and silently unarming
1531
+ * those would be worse than a stale veto.
1532
+ *
1533
+ * @param {unknown} atMs - Row timestamp (ms epoch)
1534
+ * @param {number} [now=Date.now()] - Injectable clock (tests)
1535
+ * @returns {boolean} True when the row is older than the pivot TTL
1536
+ */
1537
+ function isFillReferenceExpired(atMs, now = Date.now()) {
1538
+ const ttl = lastFillPivotTtlMs();
1539
+ if (ttl <= 0)
1540
+ return false;
1541
+ const at = Number(atMs);
1542
+ if (!Number.isFinite(at) || at <= 0)
1543
+ return false;
1544
+ return now - at > ttl;
1545
+ }
1546
+ /**
1547
+ * Report a pivot expiry once per expired timestamp. The read-time readers run
1548
+ * per probe and per guarded action, so an unguarded line would flood the log;
1549
+ * the marker is the expired row's own clock, which also re-arms the report
1550
+ * when a NEW fill later expires.
1551
+ */
1552
+ function logExpiredFillReference(manager, atMs, now) {
1553
+ const at = Number(atMs);
1554
+ if (!manager || !Number.isFinite(at) || at <= 0)
1555
+ return;
1556
+ if (Number(manager._lastFillPivotExpiryLoggedAt) === at)
1557
+ return;
1558
+ manager._lastFillPivotExpiryLoggedAt = at;
1559
+ try {
1560
+ manager.logger?.log?.(`[LAST-FILL-GUARD] Pivot expired (age ${Math.round((now - at) / 1000)}s > TTL ` +
1561
+ `${Math.round(lastFillPivotTtlMs() / 1000)}s) — guard re-arms on the next fill`, 'info');
1500
1562
  }
1501
- const marketPrice = Number(manager?._lastMarketFillPrice);
1502
- const marketType = manager?._lastMarketFillType;
1503
- if (Number.isFinite(marketPrice) && marketPrice > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1504
- return { price: marketPrice, type: marketType };
1563
+ catch { /* logging is best-effort */ }
1564
+ }
1565
+ /** Normalize one in-memory triple (price, side, clock) into a fill reference row. */
1566
+ function readFillRow(price, type, atMs) {
1567
+ const p = Number(price);
1568
+ if (!Number.isFinite(p) || p <= 0)
1569
+ return null;
1570
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
1571
+ return null;
1572
+ const at = Number(atMs);
1573
+ return { price: p, type, fillsAt: Number.isFinite(at) && at > 0 ? at : null };
1574
+ }
1575
+ /** Keep a row only while it is inside the pivot lifetime (logging the expiry once). */
1576
+ function acceptFillRow(manager, row, now) {
1577
+ if (!row)
1578
+ return null;
1579
+ if (isFillReferenceExpired(row.fillsAt, now)) {
1580
+ logExpiredFillReference(manager, row.fillsAt, now);
1581
+ return null;
1505
1582
  }
1506
- return { price: null, type: null };
1583
+ return row;
1584
+ }
1585
+ /** Live armed pivot as a row, or null when cold OR past the pivot lifetime. */
1586
+ function liveFillRow(manager, now) {
1587
+ return acceptFillRow(manager, readFillRow(manager?._lastFilledPrice, manager?._lastFilledType, manager?._lastFilledAt), now);
1588
+ }
1589
+ /** Bot-scoped last-market-fill row, or null when absent OR past the pivot lifetime. */
1590
+ function marketFillRow(manager, now) {
1591
+ return acceptFillRow(manager, readFillRow(manager?._lastMarketFillPrice, manager?._lastMarketFillType, manager?._lastMarketFillAt), now);
1592
+ }
1593
+ /**
1594
+ * FILL-PROVENANCED row for absolute geometry repairs (boundary re-anchor,
1595
+ * spread market reference): the live pivot only when its provenance is
1596
+ * `'fill'`, else the bot-scoped market row.
1597
+ *
1598
+ * The row's OWN timestamp travels with the row. Pairing one value's price with
1599
+ * another value's clock is what let `rearmLastFillPivotFromMarketFill` stamp a
1600
+ * market-fill price with a BOOK seed's (fresh) timestamp — silently refreshing
1601
+ * the 24h lifetime on every rebuild.
1602
+ *
1603
+ * @param {Object} manager - OrderManager instance
1604
+ * @param {number} [now=Date.now()] - Injectable clock (tests)
1605
+ * @returns {FillPivotRow|null} Row, or null when both sources are cold/expired
1606
+ */
1607
+ function resolveFillProvenancedRow(manager, now = Date.now()) {
1608
+ if (manager?.lastFillPivotSource === 'fill') {
1609
+ const live = liveFillRow(manager, now);
1610
+ if (live)
1611
+ return live;
1612
+ }
1613
+ return marketFillRow(manager, now);
1507
1614
  }
1508
1615
  /**
1509
1616
  * Resolve the reference the generic LAST-FILL-GUARD judges against.
@@ -1525,20 +1632,22 @@ function resolveFillProvenancedReference(manager) {
1525
1632
  * so this fallback covers only the window before that write, not the whole
1526
1633
  * post-rebuild lifetime.
1527
1634
  *
1635
+ * LIFETIME: a fill reference older than GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS is
1636
+ * ignored (read-time expiry, same bound the restore path applies), so a stale
1637
+ * pivot cannot veto one side forever in a long-lived process. Unknown ages
1638
+ * (missing timestamp) never expire.
1639
+ *
1528
1640
  * @param {Object} manager - OrderManager instance
1529
1641
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1530
1642
  */
1531
1643
  export function resolveLastFillGuardReference(manager) {
1532
- const livePrice = Number(manager?._lastFilledPrice);
1533
- const liveType = manager?._lastFilledType;
1534
- if (Number.isFinite(livePrice) && livePrice > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
1535
- return { price: livePrice, type: liveType };
1536
- }
1537
- const marketPrice = Number(manager?._lastMarketFillPrice);
1538
- const marketType = manager?._lastMarketFillType;
1539
- if (Number.isFinite(marketPrice) && marketPrice > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1540
- return { price: marketPrice, type: marketType };
1541
- }
1644
+ const now = Date.now();
1645
+ const live = liveFillRow(manager, now);
1646
+ if (live)
1647
+ return { price: live.price, type: live.type };
1648
+ const market = marketFillRow(manager, now);
1649
+ if (market)
1650
+ return { price: market.price, type: market.type };
1542
1651
  return { price: null, type: null };
1543
1652
  }
1544
1653
  /**
@@ -1583,6 +1692,97 @@ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
1583
1692
  return { blocked: true, pivot, threshold: pivot };
1584
1693
  return { blocked: false, pivot: null, threshold: null };
1585
1694
  }
1695
+ /**
1696
+ * LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
1697
+ *
1698
+ * Wraps isLastFillGuardBlocked with the same pivot resolution the runtime uses
1699
+ * (live fill pivot, then the bot-scoped market-fill row) and adds the
1700
+ * SAME-LEVEL refusal: a placement within half a grid step of the pivot is a
1701
+ * re-place at the level that just traded, which the raw `>=`/`<=` comparison
1702
+ * lets through because a slot price and its execution price differ by
1703
+ * rounding (live: slot 1310.046339 filled at 1310.060435).
1704
+ *
1705
+ * Unlike the COW-path guard this is meant for the reconcile/startup placement
1706
+ * paths (create + relocation), which previously had no last-fill check at all:
1707
+ * a startup-style top-up could therefore re-create a BUY at the price the bot
1708
+ * had just bought at, or place a BUY above it (the "buying later at higher
1709
+ * prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
1710
+ * still builds.
1711
+ *
1712
+ * @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
1713
+ * @param {number} price - Target placement price
1714
+ * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
1715
+ * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
1716
+ */
1717
+ export function isLastFillPlacementBlocked(manager, price, type) {
1718
+ const numPrice = Number(price);
1719
+ if (!Number.isFinite(numPrice) || numPrice <= 0)
1720
+ return { blocked: false, pivot: null };
1721
+ let reference = { price: null, type: null };
1722
+ try {
1723
+ reference = resolveLastFillGuardReference(manager);
1724
+ }
1725
+ catch {
1726
+ reference = { price: null, type: null };
1727
+ }
1728
+ const pivot = reference.price;
1729
+ const pivotType = reference.type;
1730
+ if (pivot == null || pivotType == null)
1731
+ return { blocked: false, pivot: null };
1732
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
1733
+ return { blocked: false, pivot };
1734
+ try {
1735
+ if (MathUtils.pricesWithinHalfStep(numPrice, pivot, manager?.config?.incrementPercent)) {
1736
+ return { blocked: true, pivot, reason: 'same-level' };
1737
+ }
1738
+ }
1739
+ catch { /* fall through to the direction rule */ }
1740
+ const guard = isLastFillGuardBlocked(numPrice, type, pivot, pivotType);
1741
+ if (guard.blocked)
1742
+ return { blocked: true, pivot, reason: 'direction' };
1743
+ return { blocked: false, pivot };
1744
+ }
1745
+ /**
1746
+ * Are fills still UNSETTLED (arrived but not yet absorbed by the grid)?
1747
+ *
1748
+ * While this returns true the master grid still holds filled slots as ACTIVE
1749
+ * and the boundary has not crawled for them, so any geometry-derived plan
1750
+ * (window top-up, startup-style reconcile) is built on the PREVIOUS book. The
1751
+ * live incident: a 120s stale broadcast region deferred 12 fills, the
1752
+ * post-fill reconcile saw "buy 12/20" on that stale master and re-created 8
1753
+ * BUYs at the TOP of the un-crawled rail (1282.78 -> 1310.04), which filled
1754
+ * within seconds (9 buy-lower violations, 23.5% of the window's BTS).
1755
+ *
1756
+ * Accepts a bot (its `manager` is inspected) or a bare manager.
1757
+ *
1758
+ * @param {Object} source - DEXBot-like or OrderManager-like instance
1759
+ * @returns {{unsettled: boolean, reason: string|null}}
1760
+ */
1761
+ export function hasUnsettledFills(source) {
1762
+ if (!source || typeof source !== 'object')
1763
+ return { unsettled: false, reason: null };
1764
+ const outer = source;
1765
+ const mgr = (outer.manager && typeof outer.manager === 'object'
1766
+ ? outer.manager
1767
+ : outer);
1768
+ try {
1769
+ const queued = Array.isArray(outer._incomingFillQueue) ? outer._incomingFillQueue.length : 0;
1770
+ if (queued > 0)
1771
+ return { unsettled: true, reason: `${queued} fill(s) queued for processing` };
1772
+ if (outer._deferredFillsPending === true)
1773
+ return { unsettled: true, reason: 'deferred fill drain pending' };
1774
+ const inFlight = Number(mgr._fillBatchInFlight);
1775
+ if (Number.isFinite(inFlight) && inFlight > 0)
1776
+ return { unsettled: true, reason: 'fill batch in flight' };
1777
+ const owed = Array.isArray(mgr._pendingFillCrawls) ? mgr._pendingFillCrawls.length : 0;
1778
+ if (owed > 0)
1779
+ return { unsettled: true, reason: `${owed} owed boundary crawl(s)` };
1780
+ }
1781
+ catch {
1782
+ return { unsettled: false, reason: null };
1783
+ }
1784
+ return { unsettled: false, reason: null };
1785
+ }
1586
1786
  /**
1587
1787
  * Restore the persisted bot-scoped last-market-fill reference into the
1588
1788
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -1615,9 +1815,8 @@ export function restoreLastMarketFill(manager, persisted, options = {}) {
1615
1815
  catch { /* best-effort */ }
1616
1816
  };
1617
1817
  const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
1618
- const ttl = Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS);
1619
- if (Number.isFinite(ttl) && ttl > 0 && now - row.fillsAt > ttl) {
1620
- manager.logger?.log?.(`[SPREAD-CORRECTION] Persisted last-market-fill expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(ttl / 1000)}s) — reference dropped`, 'info');
1818
+ if (isFillReferenceExpired(row.fillsAt, now)) {
1819
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Persisted last-market-fill expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(lastFillPivotTtlMs() / 1000)}s) — reference dropped`, 'info');
1621
1820
  dropPersistedRow();
1622
1821
  return false;
1623
1822
  }
@@ -1643,21 +1842,32 @@ export function restoreLastMarketFill(manager, persisted, options = {}) {
1643
1842
  * rewritten: an off-new-ladder value is handled by the same one-increment
1644
1843
  * `resolveOnGridPivot` rule every other probe uses.
1645
1844
  *
1845
+ * The timestamp comes from the SAME row as the price (see
1846
+ * resolveFillProvenancedRow). Reading `_lastFilledAt` unconditionally paired a
1847
+ * market-row price with a book-seed clock: a book seed writes `_lastFilledAt`
1848
+ * but never the market row, and `setLastFillPivot(..., 'fill')` then re-stamps
1849
+ * `_lastMarketFillAt` with that newer time — refreshing the 24h lifetime on
1850
+ * every rebuild until the row never expires.
1851
+ *
1852
+ * EXPIRED ROWS DO NOT RE-ARM (resolveFillProvenancedRow drops them), so the
1853
+ * documented pivot lifetime holds with or without a restart.
1854
+ *
1646
1855
  * @param {Object} manager - OrderManager instance
1647
1856
  * @returns {boolean} True when a pivot was re-armed
1648
1857
  */
1649
1858
  export function rearmLastFillPivotFromMarketFill(manager) {
1650
1859
  if (!manager)
1651
1860
  return false;
1652
- const ref = resolveFillProvenancedReference(manager);
1653
- const price = Number(ref?.price);
1654
- const type = ref?.type;
1655
- if (!Number.isFinite(price) || price <= 0 || (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL))
1861
+ const row = resolveFillProvenancedRow(manager);
1862
+ if (!row)
1656
1863
  return false;
1657
- const at = Number(manager?._lastFilledAt) || Number(manager?._lastMarketFillAt) || Date.now();
1658
- if (!setLastFillPivot(manager, type, price, 'fill', at))
1864
+ // A source with no clock cannot be aged; stamping `now` keeps the re-armed
1865
+ // pivot inside the same lifetime from this rebuild on (production rows
1866
+ // always carry the fill's own `fillsAt`).
1867
+ const at = row.fillsAt != null ? row.fillsAt : Date.now();
1868
+ if (!setLastFillPivot(manager, row.type, row.price, 'fill', at))
1659
1869
  return false;
1660
- manager.logger?.log?.(`[LAST-FILL-GUARD] Re-armed on the new generation: ${price}(${type}) from the last real fill ` +
1870
+ manager.logger?.log?.(`[LAST-FILL-GUARD] Re-armed on the new generation: ${row.price}(${row.type}) from the last real fill ` +
1661
1871
  `(age ${Math.max(0, Math.round((Date.now() - at) / 1000))}s) — the guard survives a rebuild by design`, 'info');
1662
1872
  return true;
1663
1873
  }
@@ -1856,10 +2066,11 @@ export function restoreLastFillPivot(manager, persisted, options = {}) {
1856
2066
  }
1857
2067
  catch { /* best-effort */ }
1858
2068
  };
1859
- // TTL first: an expired pivot is dropped, not re-armed.
2069
+ // TTL first: an expired pivot is dropped, not re-armed (one shared bound
2070
+ // with the read-time readers and the market-row restore).
1860
2071
  const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
1861
- if (now - row.fillsAt > Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS)) {
1862
- manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS) / 1000)}s) — guard re-arms on the next fill`, 'info');
2072
+ if (isFillReferenceExpired(row.fillsAt, now)) {
2073
+ manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(lastFillPivotTtlMs() / 1000)}s) — guard re-arms on the next fill`, 'info');
1863
2074
  dropPersistedRow();
1864
2075
  return false;
1865
2076
  }
@@ -454,6 +454,15 @@ function reconcileGrid(masterGrid, targetGrid, targetBoundary, options = {}) {
454
454
  for (const [id, targetOrder] of targetGrid) {
455
455
  const masterOrder = masterGrid.get(id);
456
456
  if (!masterOrder || masterOrder.state === ORDER_STATES.VIRTUAL) {
457
+ // A VIRTUAL slot that still OWNS a chain order id is not a hole: the
458
+ // level already holds a live order (the dark-level state owned by the
459
+ // sync/startup revive path). Planning a CREATE here would place a
460
+ // second order at the same price. A genuinely stale id is cleared by
461
+ // sync pass 1 (`sync-clear-stale-id`), which makes the slot a plain
462
+ // hole again on the next cycle.
463
+ if (masterOrder && masterOrder.state === ORDER_STATES.VIRTUAL && masterOrder.orderId) {
464
+ continue;
465
+ }
457
466
  // Slot is empty or virtual - check if we need to fill it
458
467
  if (targetOrder.size > 0 && targetOrder.state === ORDER_STATES.ACTIVE) {
459
468
  // This is a hole that needs filling
@@ -767,8 +776,17 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
767
776
  if (!targetId || releasedSlotIds.has(targetId))
768
777
  continue;
769
778
  const current = orderMap.get(targetId);
770
- // isOrderOnChain already checks orderId is truthy
771
- if (current && isOrderOnChain(current)) {
779
+ // OCCUPANCY = the slot still owns a chain order ID, in ANY state.
780
+ // isOrderOnChain() (ACTIVE/PARTIAL only) was too narrow: a slot
781
+ // virtualised while its order was still live (phantom cleanup on a
782
+ // truncated read, refused-commit adoption) kept its orderId but read as
783
+ // "empty", so a CREATE could be planned onto a level that already held a
784
+ // live order (duplicate price level). A genuinely STALE id is cleared by
785
+ // sync pass 1 (`sync-clear-stale-id`), which turns the slot back into a
786
+ // plain hole on the next cycle — so this gate cannot strand a level.
787
+ const currentOwnsChainId = Boolean(current?.orderId);
788
+ const currentCreateUncertain = current?.createUncertain === true;
789
+ if (current && (isOrderOnChain(current) || currentOwnsChainId)) {
772
790
  violations.push({
773
791
  targetId,
774
792
  currentOrderId: current.orderId,
@@ -777,6 +795,19 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
777
795
  reason: 'slot_occupied'
778
796
  });
779
797
  }
798
+ else if (current && currentCreateUncertain) {
799
+ // A CREATE whose broadcast outcome is unknown. Unlike slot_occupied
800
+ // this is NOT proof of a live order, so it must not abort the whole
801
+ // batch (runPreBroadcastGuards only hard-aborts on slot_occupied) —
802
+ // it only withholds this CREATE until the uncertainty resolves.
803
+ violations.push({
804
+ targetId,
805
+ currentOrderId: current.orderId,
806
+ currentType: current.type,
807
+ currentState: current.state,
808
+ reason: 'slot_create_uncertain'
809
+ });
810
+ }
780
811
  if (action.order?.price != null && action.order?.type != null) {
781
812
  // Key on the BROADCAST price (action.order.price — the price
782
813
  // actually placed on chain), never the live slot price: layer-5
@@ -1099,6 +1099,11 @@ export interface OrderManagerLike {
1099
1099
  _lastFilledPrice: number | null;
1100
1100
  _lastFilledType: string | null;
1101
1101
  _lastFilledAt: number | null;
1102
+ /**
1103
+ * Timestamp of the fill reference whose expiry was already logged, so the
1104
+ * read-time pivot TTL reports once per expired value instead of per probe.
1105
+ */
1106
+ _lastFillPivotExpiryLoggedAt?: number | null;
1102
1107
  lastFillPivotSource: 'fill' | 'book' | null;
1103
1108
  _lastMarketFillPrice?: number | null;
1104
1109
  _lastMarketFillType?: string | null;
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
- * null (not an error), so a lowercase input silently drops the asset. Casing
6
+ * The chain's asset lookups (`get_assets` / `lookup_asset_symbols`) are
7
+ * case-sensitive: a lowercase symbol resolves to null (not an error), so a
8
+ * lowercase input silently drops the asset. Casing
8
9
  * also leaks into everything built from a resolved symbol: the `symbol` field
9
10
  * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
11
  * strict in-process comparisons such as `assetA === 'CORE'`. That is a
@@ -35,6 +36,16 @@ export declare function normalizeAssetSymbol(value: unknown): string;
35
36
  * mixed "id or symbol" reference (credit runtime, credential policy, pools).
36
37
  */
37
38
  export declare function normalizeAssetRef(value: unknown): string;
39
+ /**
40
+ * Both spellings of a human-typed asset reference: the reference as typed
41
+ * (trimmed) and its canonical UPPERCASE form. Resolvers query the canonical form
42
+ * first and retry the as-typed spelling only when that misses (see
43
+ * modules/asset_lookup.ts), because `get_assets` is case-sensitive and a node
44
+ * may still hold a non-canonical symbol. Object ids collapse to one entry.
45
+ *
46
+ * @returns [] for empty input, otherwise 1-2 distinct spellings.
47
+ */
48
+ export declare function assetSymbolCandidates(value: unknown): string[];
38
49
  /** Case- and whitespace-insensitive asset-symbol equality. */
39
50
  export declare function isSameAssetSymbol(a: unknown, b: unknown): boolean;
40
51
  /**
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
- * null (not an error), so a lowercase input silently drops the asset. Casing
6
+ * The chain's asset lookups (`get_assets` / `lookup_asset_symbols`) are
7
+ * case-sensitive: a lowercase symbol resolves to null (not an error), so a
8
+ * lowercase input silently drops the asset. Casing
8
9
  * also leaks into everything built from a resolved symbol: the `symbol` field
9
10
  * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
11
  * strict in-process comparisons such as `assetA === 'CORE'`. That is a
@@ -50,6 +51,24 @@ export function normalizeAssetSymbol(value) {
50
51
  export function normalizeAssetRef(value) {
51
52
  return normalizeAssetSymbol(value);
52
53
  }
54
+ /**
55
+ * Both spellings of a human-typed asset reference: the reference as typed
56
+ * (trimmed) and its canonical UPPERCASE form. Resolvers query the canonical form
57
+ * first and retry the as-typed spelling only when that misses (see
58
+ * modules/asset_lookup.ts), because `get_assets` is case-sensitive and a node
59
+ * may still hold a non-canonical symbol. Object ids collapse to one entry.
60
+ *
61
+ * @returns [] for empty input, otherwise 1-2 distinct spellings.
62
+ */
63
+ export function assetSymbolCandidates(value) {
64
+ if (value === null || value === undefined)
65
+ return [];
66
+ const typed = String(value).trim();
67
+ if (!typed)
68
+ return [];
69
+ const canonical = normalizeAssetSymbol(typed);
70
+ return typed === canonical ? [canonical] : [typed, canonical];
71
+ }
53
72
  /** Case- and whitespace-insensitive asset-symbol equality. */
54
73
  export function isSameAssetSymbol(a, b) {
55
74
  const na = normalizeAssetSymbol(a);
@@ -0,0 +1,10 @@
1
+ /** Absolute path to an analysis script, e.g. ['tradingview','analyze_tradingview.js']. */
2
+ declare function analysisScriptPath(segments: string[]): string;
3
+ /**
4
+ * Resolve, run and validate an analysis script.
5
+ * Throws with a command-specific `label` when the build is missing or the
6
+ * renderer exits non-zero; child stdio is inherited.
7
+ */
8
+ declare function runAnalysisScript(segments: string[], args: string[], label: string): void;
9
+ export { analysisScriptPath, runAnalysisScript };
10
+ //# sourceMappingURL=analysis_runner.d.ts.map
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ /**
3
+ * Spawn an analysis entry point (compiled `dist/analysis/**\/*.js`).
4
+ *
5
+ * Chart-style commands (`tv`, `dw`, `liquid`) all render through a separate
6
+ * analysis binary. This helper centralises the path resolution, existence
7
+ * check, project-root cwd, and exit-status handling so a missing build or a
8
+ * crashed renderer reports the same way everywhere.
9
+ */
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
14
+ import { PATHS } from '../modules/paths.js';
15
+ import { runRuntimeScript } from '../modules/launcher/runtime_entry.js';
16
+ /** Absolute path to an analysis script, e.g. ['tradingview','analyze_tradingview.js']. */
17
+ function analysisScriptPath(segments) {
18
+ return path.join(__dirname, '..', 'analysis', ...segments);
19
+ }
20
+ /**
21
+ * Resolve, run and validate an analysis script.
22
+ * Throws with a command-specific `label` when the build is missing or the
23
+ * renderer exits non-zero; child stdio is inherited.
24
+ */
25
+ function runAnalysisScript(segments, args, label) {
26
+ runRuntimeScript(analysisScriptPath(segments), args, {
27
+ label,
28
+ cwd: PATHS.PROJECT_ROOT,
29
+ nonZero: 'throw',
30
+ });
31
+ }
32
+ export { analysisScriptPath, runAnalysisScript };
33
+ //# sourceMappingURL=analysis_runner.js.map
@@ -25,6 +25,7 @@ import { getStorage } from '../modules/storage/index.js';
25
25
  const { readJSON } = getStorage();
26
26
  import { getErrorMessage } from '../modules/utils/errors.js';
27
27
  import { toFileUrl } from '../analysis/chart_utils.js';
28
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
28
29
  import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
29
30
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
30
31
  import { pathToFileURL } from 'node:url';
@@ -1420,7 +1421,7 @@ function generateHtmlReport(analyses) {
1420
1421
  const outPath = path.join(PATHS.ANALYSIS.CHARTS_DIR, 'order-analysis.html');
1421
1422
  fs.mkdirSync(PATHS.ANALYSIS.CHARTS_DIR, { recursive: true });
1422
1423
  fs.writeFileSync(outPath, html, 'utf-8');
1423
- console.log(`\nšŸ“„ Order Analysis saved. Open report: (${toFileUrl(outPath)})`);
1424
+ console.log(savedLine(CLI_TAGS.orders, 'Order Analysis', toFileUrl(outPath), 'report'));
1424
1425
  }
1425
1426
  function main() {
1426
1427
  const rawArgs = process.argv.slice(2);
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ type AssetKind = 'bts' | 'token';
3
+ interface AssetConfig {
4
+ /** Distribution analyzer to run, or null when no target was given. */
5
+ kind: AssetKind | null;
6
+ /** Token symbol or asset id (token kind only). */
7
+ asset: string | null;
8
+ /** Flags forwarded verbatim to the analyzer. */
9
+ scriptArgs: string[];
10
+ help: boolean;
11
+ }
12
+ declare const CORE_ASSET_ID = "1.3.0";
13
+ declare const ANALYZERS: Record<AssetKind, {
14
+ script: string;
15
+ label: string;
16
+ }>;
17
+ /**
18
+ * Split `<target> <flags...>` into the analyzer identity plus the untouched
19
+ * flag list. `bts` (and the core asset id) route to the core-asset analyzer;
20
+ * anything else is an issued-asset symbol/id. Flags are validated per target so
21
+ * a `bts`-only option cannot be silently accepted (and ignored) by the token
22
+ * analyzer, or vice versa.
23
+ */
24
+ declare function parseArgs(argv: string[]): AssetConfig;
25
+ export { parseArgs, ANALYZERS, CORE_ASSET_ID };
26
+ //# sourceMappingURL=asset.d.ts.map