dexbot 1.6.17 → 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 (156) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +105 -12
  4. package/analysis/ama_fitting/README.md +2 -2
  5. package/analysis/bot_fitting/README.md +3 -3
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/analyze_args.d.ts +2 -1
  10. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  11. package/dist/analysis/analyze_kalman.js +3 -2
  12. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  13. package/dist/analysis/analyze_liquidity.js +325 -0
  14. package/dist/analysis/analyze_regime.js +3 -2
  15. package/dist/analysis/analyze_regime_windows.js +3 -2
  16. package/dist/analysis/analyze_volatility.js +3 -2
  17. package/dist/analysis/fills_source.d.ts +1 -8
  18. package/dist/analysis/fills_source.js +1 -1
  19. package/dist/analysis/grid_correction_check.d.ts +9 -6
  20. package/dist/analysis/grid_correction_check.js +56 -64
  21. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  22. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  24. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  26. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  27. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  28. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  29. package/dist/analysis/math_utils.d.ts +1 -1
  30. package/dist/analysis/trade_profitability.d.ts +1 -1
  31. package/dist/analysis/trade_profitability.js +2 -1
  32. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  33. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  34. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  35. package/dist/dexbot.js +74 -169
  36. package/dist/market_adapter/cli_args.d.ts +6 -1
  37. package/dist/market_adapter/cli_args.js +16 -2
  38. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  39. package/dist/market_adapter/core/kibana_candles.js +3 -1
  40. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  41. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  42. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  43. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  44. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  45. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  46. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  47. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  48. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  49. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  50. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  51. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  52. package/dist/market_adapter/inputs/window_cache.js +14 -1
  53. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  54. package/dist/market_adapter/lp_chart_runner.js +3 -1
  55. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  56. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  57. package/dist/market_adapter/market_adapter.d.ts +10 -2
  58. package/dist/market_adapter/market_adapter.js +10 -11
  59. package/dist/market_adapter/utils/chain.d.ts +2 -3
  60. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  61. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  62. package/dist/market_adapter/utils/file_lock.js +1 -1
  63. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  64. package/dist/market_adapter/utils/native_history.js +3 -1
  65. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  66. package/dist/modules/asset_lookup.d.ts +25 -0
  67. package/dist/modules/asset_lookup.js +75 -0
  68. package/dist/modules/bots_file_lock.d.ts +2 -2
  69. package/dist/modules/bots_file_lock.js +2 -2
  70. package/dist/modules/chain_scan.d.ts +64 -0
  71. package/dist/modules/chain_scan.js +80 -0
  72. package/dist/modules/cli_colors.d.ts +5 -0
  73. package/dist/modules/cli_colors.js +7 -0
  74. package/dist/modules/cli_progress.d.ts +51 -0
  75. package/dist/modules/cli_progress.js +113 -0
  76. package/dist/modules/constants.js +6 -3
  77. package/dist/modules/dexbot_class.d.ts +8 -0
  78. package/dist/modules/dexbot_class.js +10 -0
  79. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  80. package/dist/modules/dexbot_cow_runtime.js +475 -47
  81. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  82. package/dist/modules/dexbot_fill_runtime.js +20 -0
  83. package/dist/modules/dexbot_maintenance_runtime.js +71 -9
  84. package/dist/modules/dexbot_startup_runtime.js +7 -1
  85. package/dist/modules/graceful_shutdown.d.ts +2 -2
  86. package/dist/modules/graceful_shutdown.js +2 -2
  87. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  88. package/dist/modules/launcher/runtime_entry.js +36 -1
  89. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  90. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  91. package/dist/modules/liquidity_pool_ref.js +116 -0
  92. package/dist/modules/node_manager.d.ts +1 -1
  93. package/dist/modules/node_manager.js +1 -1
  94. package/dist/modules/order/accounting.js +2 -1
  95. package/dist/modules/order/export.d.ts +2 -2
  96. package/dist/modules/order/export.js +2 -2
  97. package/dist/modules/order/grid.d.ts +19 -14
  98. package/dist/modules/order/grid.js +269 -61
  99. package/dist/modules/order/grid_reconcile.js +27 -2
  100. package/dist/modules/order/grid_reconcile_internal.js +94 -15
  101. package/dist/modules/order/index.d.ts +24 -4
  102. package/dist/modules/order/manager.d.ts +12 -0
  103. package/dist/modules/order/manager.js +44 -11
  104. package/dist/modules/order/strategy.js +22 -2
  105. package/dist/modules/order/sync_engine.d.ts +32 -1
  106. package/dist/modules/order/sync_engine.js +209 -26
  107. package/dist/modules/order/utils/math.d.ts +26 -10
  108. package/dist/modules/order/utils/math.js +54 -14
  109. package/dist/modules/order/utils/order.d.ts +158 -11
  110. package/dist/modules/order/utils/order.js +434 -21
  111. package/dist/modules/order/utils/system.d.ts +136 -30
  112. package/dist/modules/order/utils/system.js +465 -63
  113. package/dist/modules/order/utils/validate.d.ts +1 -0
  114. package/dist/modules/order/utils/validate.js +37 -3
  115. package/dist/modules/storage/index.d.ts +3 -2
  116. package/dist/modules/storage/index.js +3 -2
  117. package/dist/modules/types.d.ts +14 -0
  118. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  119. package/dist/modules/utils/asset_symbols.js +21 -2
  120. package/dist/scripts/analysis_runner.d.ts +10 -0
  121. package/dist/scripts/analysis_runner.js +33 -0
  122. package/dist/scripts/analyze-orders.js +2 -1
  123. package/dist/scripts/asset.d.ts +26 -0
  124. package/dist/scripts/asset.js +165 -0
  125. package/dist/scripts/bts_distribution.d.ts +1 -0
  126. package/dist/scripts/bts_distribution.js +194 -142
  127. package/dist/scripts/chart_command.d.ts +1 -1
  128. package/dist/scripts/chart_command.js +60 -86
  129. package/dist/scripts/chart_targets.d.ts +18 -0
  130. package/dist/scripts/chart_targets.js +52 -0
  131. package/dist/scripts/dw.js +1 -1
  132. package/dist/scripts/liquid.d.ts +24 -0
  133. package/dist/scripts/liquid.js +134 -0
  134. package/dist/scripts/rich_list.js +12 -16
  135. package/dist/scripts/token_distribution.d.ts +2 -0
  136. package/dist/scripts/token_distribution.js +132 -108
  137. package/dist/scripts/tv.js +1 -1
  138. package/dist/scripts/verify-browser-bundle.js +18 -0
  139. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  140. package/docs/COW_INVARIANTS.md +21 -11
  141. package/docs/DEXBOT_COMPARISON.md +6 -6
  142. package/docs/EVOLUTION.md +10 -8
  143. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  144. package/docs/GRID_PRICE_INVARIANT.md +28 -5
  145. package/docs/GRID_RECONCILE.md +25 -5
  146. package/docs/LIFECYCLE.md +11 -11
  147. package/docs/LOGGING.md +37 -2
  148. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
  149. package/docs/README.md +1 -1
  150. package/docs/WORKFLOW.md +3 -1
  151. package/docs/architecture.md +115 -13
  152. package/docs/developer_guide.md +12 -0
  153. package/market_adapter/README.md +9 -4
  154. package/modules/README.md +23 -15
  155. package/package.json +6 -3
  156. package/scripts/README.md +23 -7
@@ -25,6 +25,11 @@ interface CredentialClientOptions {
25
25
  */
26
26
  onNodeFailed?: (nodeUrl: string) => void;
27
27
  }
28
+ /**
29
+ * Typed daemon reply. Exported because downstream wrapper modules infer it as
30
+ * the return type of `executeOperationsViaCredentialDaemon`; declaration emit
31
+ * cannot name a module-private type there (TS4058).
32
+ */
28
33
  export interface CredentialDaemonResponse {
29
34
  success?: boolean;
30
35
  error?: string;
@@ -6,6 +6,7 @@ import { NATIVE_CLIENT, FILL_PROCESSING, TIMING, MAINTENANCE, ORDER_TYPES } from
6
6
  import { getErrorMessage, resolveSeamMsOrNull, getErrorField } from './utils/errors.js';
7
7
  import { isOrderDoesNotExistError } from './dexbot_maintenance_runtime.js';
8
8
  import { slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail } from './order/utils/math.js';
9
+ import { attributeUnmatchedFillToGrid } from './order/utils/order.js';
9
10
  import { ORDER_STATES } from './constants.js';
10
11
  const buildFillKey = lazyShim('./order/utils/order', 'buildFillKey');
11
12
  const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
@@ -133,6 +134,25 @@ async function processSweepOrphanFill(bot, fill, fillOp, processedFillKeys, opts
133
134
  }
134
135
  return true;
135
136
  }
137
+ // GEOMETRY FIRST, then money. The order is unknown to the grid, but the
138
+ // fill still proves a trade at a price: attribute it (pivot + owed crawl)
139
+ // BEFORE crediting the proceeds, so a fill that never reaches the strategy
140
+ // cannot leave the LAST-FILL-GUARD pivot stale — the same split-brain the
141
+ // unmatched-fill path closes for a virtualised slot. Attribution refuses a
142
+ // price outside the frozen rail, so a shelf/manual order can never arm the
143
+ // pivot at a level this grid does not trade.
144
+ try {
145
+ const pays = fillOp?.pays;
146
+ const receives = fillOp?.receives;
147
+ attributeUnmatchedFillToGrid(bot.manager, {
148
+ orderId: fillOp?.order_id != null ? String(fillOp.order_id) : null,
149
+ paysAssetId: pays?.asset_id ?? null,
150
+ paysAmountRaw: pays?.amount ?? null,
151
+ receivesAssetId: receives?.asset_id ?? null,
152
+ receivesAmountRaw: receives?.amount ?? null,
153
+ });
154
+ }
155
+ catch { /* attribution is best-effort: never block the credit */ }
136
156
  (opts.logger ?? bot.manager.logger).log?.(`[${opts.label}] Processing funds for unknown order ${fillOp.order_id} (not in grid but crediting proceeds)`, 'warn');
137
157
  const accountingResult = await bot._applyReplaySafeOrphanFillAccounting(fill, fillOp, {
138
158
  context: opts.context,
@@ -8,7 +8,7 @@ const require = createRequire(import.meta.url);
8
8
  import { lazyShim } from './lazy_shim.js';
9
9
  import fs from 'node:fs';
10
10
  import { spawn } from 'node:child_process';
11
- import { nowIso, fireStructuralResync } from './order/utils/system.js';
11
+ import { nowIso, fireStructuralResync, resolveLastFillGuardReference, hasUnsettledFills } from './order/utils/system.js';
12
12
  import { path } from './path_api.js';
13
13
  import * as chainOrders from './chain_orders.js';
14
14
  import * as grid from './order/grid.js';
@@ -72,7 +72,7 @@ function getCoreOrdersTotal(config) { return require('./order/utils/order').getC
72
72
  const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
73
73
  const isOrderOnChain = lazyShim('./order/utils/order', 'isOrderOnChain');
74
74
  const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
75
- const parseSlotIndex = lazyShim('./order/utils/order', 'parseSlotIndex');
75
+ const parseSlotIndex = lazyShim('./order/utils/slot', 'parseSlotIndex');
76
76
  const CODE_ROOT = path.join(__dirname, '..');
77
77
  const PROFILES_DIR = PATHS.PROFILES_DIR;
78
78
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
@@ -734,6 +734,21 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
734
734
  const trigger = getTargetedSyncReason(bot);
735
735
  if (!trigger)
736
736
  return false;
737
+ // UNSETTLED-FILL GATE: a startup-style reconcile derives its window from the
738
+ // master grid. While fills are still queued / draining / in flight / owed a
739
+ // crawl, that master still holds the filled slots as ACTIVE and the boundary
740
+ // has not crawled — the top-up would restore the EXPENSIVE end of the rail
741
+ // (live incident: 8 BUYs at 1282.78 -> 1310.04 re-created from a stale
742
+ // "buy 12/20" shortfall and filled within seconds). Defer to the next tick:
743
+ // the crawl commits in the same fill cycle, after which the same shortfall
744
+ // resolves against the crawled rail. No cooldown stamp, so the retry is
745
+ // immediate once the fills settle.
746
+ const unsettled = hasUnsettledFills(bot);
747
+ if (unsettled.unsettled) {
748
+ bot._log(`[TARGETED-SYNC] Deferring ${context} reconciliation: ${unsettled.reason} — ` +
749
+ `the rail must absorb the fills before it is topped up`, 'debug');
750
+ return false;
751
+ }
737
752
  const now = Date.now();
738
753
  const cooldownMs = Number.isFinite(Number(bot._targetedDriftSyncCooldownMs))
739
754
  ? Number(bot._targetedDriftSyncCooldownMs)
@@ -2516,6 +2531,19 @@ async function executeMaintenanceLogic(bot, context) {
2516
2531
  }
2517
2532
  }
2518
2533
  }
2534
+ /**
2535
+ * Clear the geometry-bind re-center memory (one re-center per fill pivot).
2536
+ * Called whenever the spread actually heals — a placement or a sustained
2537
+ * in-tolerance run — so a later geometry bind on a *different* pivot starts
2538
+ * with a fresh budget.
2539
+ * @param {Object} bot - DEXBot instance
2540
+ */
2541
+ function clearGeometryResyncMemory(bot) {
2542
+ if (!bot)
2543
+ return;
2544
+ bot._lastGeometryResyncPivotKey = '';
2545
+ bot._geometryResyncWarnedPivotKey = '';
2546
+ }
2519
2547
  /**
2520
2548
  * Out-of-spread persistence watchdog: the never-run-stale backstop.
2521
2549
  *
@@ -2547,6 +2575,7 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced, tran
2547
2575
  bot._outOfSpreadStaleWarned = false;
2548
2576
  bot._outOfSpreadTransientCount = 0;
2549
2577
  bot._outOfSpreadToleranceSince = 0;
2578
+ clearGeometryResyncMemory(bot);
2550
2579
  try {
2551
2580
  bot.manager._spreadRailOversubscribed = null;
2552
2581
  }
@@ -2572,6 +2601,7 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced, tran
2572
2601
  bot._outOfSpreadStaleWarned = false;
2573
2602
  bot._outOfSpreadTransientCount = 0;
2574
2603
  bot._outOfSpreadToleranceSince = 0;
2604
+ clearGeometryResyncMemory(bot);
2575
2605
  try {
2576
2606
  bot.manager._spreadRailOversubscribed = null;
2577
2607
  }
@@ -2623,19 +2653,49 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced, tran
2623
2653
  ? Number(TIMING.SPREAD_STALE_FUND_ESCALATE_MS)
2624
2654
  : 5 * 60 * 1000;
2625
2655
  // The geometry bind has its own (longer than funds, shorter than structural)
2626
- // window: the sell window is behind the last sale, which only a re-center
2627
- // repairs.
2656
+ // window: the window is behind the last fill, which a re-center repairs by
2657
+ // re-deriving the center AROUND that same fill. Capped at ONE re-center per
2658
+ // pivot value: the re-center does not move the pivot, so a second attempt on
2659
+ // the same fill re-derives the same veto (the pivot can sit outside the new
2660
+ // grid's placeable side when the market has moved far away) and would only
2661
+ // cancel/re-place the new generation every cooldown. Until a fill refreshes
2662
+ // the pivot (or it expires), the honest repair is a fill — so report once
2663
+ // and stop.
2628
2664
  const geometryBlocked = bot._spreadCorrectionStall === 'last-fill-blocked';
2665
+ let geometryPivotKey = '';
2666
+ if (geometryBlocked) {
2667
+ try {
2668
+ const ref = resolveLastFillGuardReference(bot.manager);
2669
+ if (ref?.price != null && Number.isFinite(Number(ref.price)))
2670
+ geometryPivotKey = `${Number(ref.price)}|${String(ref.type ?? '')}`;
2671
+ }
2672
+ catch {
2673
+ geometryPivotKey = '';
2674
+ }
2675
+ }
2676
+ const geometryAlreadyRecentered = geometryBlocked && !!geometryPivotKey
2677
+ && bot._lastGeometryResyncPivotKey === geometryPivotKey;
2629
2678
  const geometryEscalateMs = Number(TIMING?.SPREAD_STALE_GEOMETRY_ESCALATE_MS) > 0
2630
2679
  ? Number(TIMING.SPREAD_STALE_GEOMETRY_ESCALATE_MS)
2631
2680
  : 10 * 60 * 1000;
2632
2681
  const escalateMs = oversubscribedFresh
2633
2682
  ? fundEscalateMs
2634
- : geometryBlocked
2635
- ? geometryEscalateMs
2636
- : (Number(TIMING?.SPREAD_STALE_ESCALATE_MS) > 0
2637
- ? Number(TIMING.SPREAD_STALE_ESCALATE_MS)
2638
- : 30 * 60 * 1000);
2683
+ : geometryAlreadyRecentered
2684
+ // Do not re-center again for the same fill. Out of the escalation
2685
+ // ladder entirely: a fill (or the pivot TTL) is the only heal.
2686
+ ? Number.POSITIVE_INFINITY
2687
+ : geometryBlocked
2688
+ ? geometryEscalateMs
2689
+ : (Number(TIMING?.SPREAD_STALE_ESCALATE_MS) > 0
2690
+ ? Number(TIMING.SPREAD_STALE_ESCALATE_MS)
2691
+ : 30 * 60 * 1000);
2692
+ if (geometryAlreadyRecentered && staleMs >= warnMs && bot._geometryResyncWarnedPivotKey !== geometryPivotKey) {
2693
+ bot._geometryResyncWarnedPivotKey = geometryPivotKey;
2694
+ bot._log(`[SPREAD-STALE] Still out of tolerance ${staleMin}min after re-centering on fill pivot ` +
2695
+ `${geometryPivotKey.split('|')[0]}: the pivot is outside this generation's placeable side, so a re-center ` +
2696
+ `cannot clear it. A fill (buy back below / sell above the pivot) or pivot expiry restores the side; ` +
2697
+ `no further re-center will be requested for this pivot.`, 'warn');
2698
+ }
2639
2699
  if (staleMs >= warnMs && !bot._outOfSpreadStaleWarned) {
2640
2700
  bot._outOfSpreadStaleWarned = true;
2641
2701
  const stall = bot._spreadCorrectionStall ? `, stall=${bot._spreadCorrectionStall}` : '';
@@ -2655,6 +2715,8 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced, tran
2655
2715
  const lastAt = Number(bot._lastSpreadStaleResyncAt) || 0;
2656
2716
  if (now - lastAt >= cooldownMs) {
2657
2717
  bot._lastSpreadStaleResyncAt = now;
2718
+ if (geometryBlocked && geometryPivotKey)
2719
+ bot._lastGeometryResyncPivotKey = geometryPivotKey;
2658
2720
  bot._log(`[SPREAD-STALE] Spread out of tolerance for ${staleMin}min despite corrections` +
2659
2721
  `${oversubscribedFresh ? ' (rail oversubscribed — re-sizing from chain truth)' : ''}` +
2660
2722
  `${geometryBlocked ? ' (sell window behind the last fill — re-centering)' : ''}` +
@@ -616,7 +616,13 @@ async function finishStartupSequence(bot, startupState) {
616
616
  }
617
617
  else {
618
618
  bot._log('Found active session. Loading and syncing existing grid.');
619
- await botGridModule(bot).loadGrid(bot.manager, persistedGrid, persistedBoundaryIdx, persistedGenesis);
619
+ // Pure in-band stranding is the transient SPREAD-GUARD /
620
+ // partial-fill-anchor state, not snapshot poison: the
621
+ // re-anchor deliberately leaves the fill's own PARTIAL
622
+ // residual inside the band until GAP-EVAC clears it.
623
+ // Keep the persisted boundary (warn + load) exactly like
624
+ // the recovery path; a rebuild here would undo the repair.
625
+ await botGridModule(bot).loadGrid(bot.manager, persistedGrid, persistedBoundaryIdx, persistedGenesis, { tolerateTransientStranding: true });
620
626
  // Phase 3 restart resilience: restore persisted gap-evacuation
621
627
  // streaks (pruned to surviving slots) so an order stranded
622
628
  // in-band across frequent restarts still reaches the cancel
@@ -40,8 +40,8 @@
40
40
  * 6. Log shutdown status
41
41
  * 7. Exit process
42
42
  *
43
- * USAGE:
44
- * const { registerCleanup } = require('./modules/graceful_shutdown');
43
+ * USAGE (from the repo root):
44
+ * import { registerCleanup } from './modules/graceful_shutdown.js';
45
45
  *
46
46
  * // Register cleanups (executed in reverse order on shutdown)
47
47
  * registerCleanup('Database', async () => db.close());
@@ -40,8 +40,8 @@
40
40
  * 6. Log shutdown status
41
41
  * 7. Exit process
42
42
  *
43
- * USAGE:
44
- * const { registerCleanup } = require('./modules/graceful_shutdown');
43
+ * USAGE (from the repo root):
44
+ * import { registerCleanup } from './modules/graceful_shutdown.js';
45
45
  *
46
46
  * // Register cleanups (executed in reverse order on shutdown)
47
47
  * registerCleanup('Database', async () => db.close());
@@ -6,5 +6,25 @@ declare function buildRuntimeScriptArgs({ codeRoot, scriptSegments, scriptArgs,
6
6
  scriptSegments: string[];
7
7
  scriptArgs?: string[];
8
8
  }): string[];
9
- export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, SCRIPTS_ROOT };
9
+ /**
10
+ * Run a compiled entry point in a child process with inherited stdio.
11
+ *
12
+ * Every CLI command that delegates to `dist/scripts/**`, `dist/analysis/**`,
13
+ * `dist/unlock.js` or `dist/pm2.js` needs the same four things: an existence
14
+ * check that names the entry, an inherited-stdio spawn, spawn-error propagation
15
+ * and a non-zero policy. Centralising it keeps those commands reporting
16
+ * identically instead of each one re-deriving the boilerplate.
17
+ *
18
+ * @returns the child's exit status (1 when the child died from a signal).
19
+ * @throws when the entry point is missing, cannot be spawned, or exits non-zero
20
+ * with `nonZero: 'throw'`.
21
+ */
22
+ declare function runRuntimeScript(scriptPath: string, scriptArgs: string[], { label, cwd, nonZero, }: {
23
+ /** Command name used in error messages, e.g. 'order' or 'TradingView exporter'. */
24
+ label: string;
25
+ cwd: string;
26
+ /** 'ignore' (default) returns the status so the caller can mirror it. */
27
+ nonZero?: 'ignore' | 'throw';
28
+ }): number;
29
+ export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, runRuntimeScript, SCRIPTS_ROOT };
10
30
  //# sourceMappingURL=runtime_entry.d.ts.map
@@ -2,8 +2,13 @@ import { fileURLToPath } from 'node:url';
2
2
  import { dirname as _esmDirname } from 'node:path';
3
3
  const __filename = fileURLToPath(import.meta.url);
4
4
  const __dirname = _esmDirname(__filename);
5
+ import fs from 'node:fs';
6
+ import { createRequire } from 'node:module';
5
7
  import { path } from '../path_api.js';
6
8
  import { isDistRuntime as isDistCodeRoot } from '../utils/build_dir.js';
9
+ // child_process is resolved lazily so tests (and embedded callers) can stub the
10
+ // spawn binding on the CJS module object before the first run.
11
+ const require = createRequire(import.meta.url);
7
12
  // Centralised scripts root: the directory containing the entry-point scripts.
8
13
  // At this module depth (modules/launcher/), it resolves to <root> (source)
9
14
  // or <root>/dist (compiled). All launcher modules should import this rather
@@ -28,5 +33,35 @@ function buildRuntimeScriptArgs({ codeRoot, scriptSegments, scriptArgs = [], })
28
33
  const scriptPath = buildRuntimeScriptPath(codeRoot, scriptSegments);
29
34
  return [scriptPath, ...scriptArgs];
30
35
  }
31
- export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, SCRIPTS_ROOT };
36
+ /**
37
+ * Run a compiled entry point in a child process with inherited stdio.
38
+ *
39
+ * Every CLI command that delegates to `dist/scripts/**`, `dist/analysis/**`,
40
+ * `dist/unlock.js` or `dist/pm2.js` needs the same four things: an existence
41
+ * check that names the entry, an inherited-stdio spawn, spawn-error propagation
42
+ * and a non-zero policy. Centralising it keeps those commands reporting
43
+ * identically instead of each one re-deriving the boilerplate.
44
+ *
45
+ * @returns the child's exit status (1 when the child died from a signal).
46
+ * @throws when the entry point is missing, cannot be spawned, or exits non-zero
47
+ * with `nonZero: 'throw'`.
48
+ */
49
+ function runRuntimeScript(scriptPath, scriptArgs, { label, cwd, nonZero = 'ignore', }) {
50
+ if (!fs.existsSync(scriptPath)) {
51
+ throw new Error(`${label} not found at ${scriptPath} (run npm run build first)`);
52
+ }
53
+ const { spawnSync } = require('node:child_process');
54
+ const result = spawnSync(process.execPath, [scriptPath, ...scriptArgs], {
55
+ cwd,
56
+ stdio: 'inherit',
57
+ });
58
+ if (result.error)
59
+ throw result.error;
60
+ const status = result.status ?? 1;
61
+ if (nonZero === 'throw' && status !== 0) {
62
+ throw new Error(`${label} exited with status ${status}`);
63
+ }
64
+ return status;
65
+ }
66
+ export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, runRuntimeScript, SCRIPTS_ROOT };
32
67
  //# sourceMappingURL=runtime_entry.js.map
@@ -1,4 +1,4 @@
1
- export type RuntimeMode = 'monolithic' | 'isolated' | 'pm2' | 'none';
1
+ type RuntimeMode = 'monolithic' | 'isolated' | 'pm2' | 'none';
2
2
  export interface Pm2Proc {
3
3
  pid?: number | string;
4
4
  name?: string;
@@ -28,7 +28,7 @@ export interface RuntimeInfo {
28
28
  }
29
29
  /** True when `name` matches a configured bot (case-insensitive). */
30
30
  export declare function isConfiguredBotName(name: string): boolean;
31
- export interface StatusTargetCheck {
31
+ interface StatusTargetCheck {
32
32
  error: string | null;
33
33
  notice: string | null;
34
34
  }
@@ -38,7 +38,7 @@ export interface StatusTargetCheck {
38
38
  * one is rejected — the same contract the unlock control path applies.
39
39
  */
40
40
  export declare function checkStatusTarget(target?: string | null): StatusTargetCheck;
41
- export type StatusRoute = 'unlock' | 'pm2' | 'empty';
41
+ type StatusRoute = 'unlock' | 'pm2' | 'empty';
42
42
  /**
43
43
  * Which branch `dexbot status` takes. PM2 wins when PM2 bots are running (even
44
44
  * if a stray credential daemon lingers) so the report and the help banner name
@@ -76,4 +76,5 @@ export interface RuntimeHelpEntry {
76
76
  * so the reference is always complete before anything is running.
77
77
  */
78
78
  export declare function runtimeControlHelp(mode: RuntimeMode): RuntimeHelpEntry[];
79
+ export {};
79
80
  //# sourceMappingURL=runtime_mode.d.ts.map
@@ -0,0 +1,32 @@
1
+ interface RawPoolLike {
2
+ id?: string;
3
+ asset_a?: string;
4
+ asset_b?: string;
5
+ asset_ids?: string[];
6
+ share_asset?: string;
7
+ }
8
+ /** Minimal database_api read surface: `(method, args) → decoded result`. */
9
+ type ChainRead = (method: string, args?: unknown[]) => Promise<unknown>;
10
+ /** `133` / `1.19.133` → `1.19.133`; anything else (a pool token) → null. */
11
+ declare function normalizePoolRef(ref: unknown): string | null;
12
+ /** True when the reference is a numeric pool id rather than a pool token. */
13
+ declare function isPoolIdRef(ref: unknown): boolean;
14
+ /**
15
+ * True when the reference *could* name a pool (numeric id or pool-token shape).
16
+ * Used by the CLI wrappers to fail fast on junk while still accepting tokens;
17
+ * only the chain can confirm a token exists.
18
+ */
19
+ declare function isPoolRefLike(ref: unknown): boolean;
20
+ /** Pool asset ids, tolerating both `asset_a`/`asset_b` and the `asset_ids` array. */
21
+ declare function poolAssetIds(pool: RawPoolLike | null | undefined): [string | null, string | null];
22
+ /**
23
+ * Resolve one pool reference to its raw chain object.
24
+ *
25
+ * Numeric references hit `get_objects` directly; a pool token is resolved
26
+ * through `lookup_asset_symbols` (the symbol as typed, then its canonical
27
+ * UPPERCASE form) and `get_liquidity_pools_by_share_asset`.
28
+ */
29
+ declare function resolvePoolRef(read: ChainRead, ref: unknown): Promise<RawPoolLike>;
30
+ export { normalizePoolRef, isPoolIdRef, isPoolRefLike, poolAssetIds, resolvePoolRef };
31
+ export type { RawPoolLike, ChainRead };
32
+ //# sourceMappingURL=liquidity_pool_ref.d.ts.map
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+ /**
3
+ * modules/liquidity_pool_ref.ts - Liquidity-pool reference resolution.
4
+ *
5
+ * Every command that takes a pool or an asset pair (`dexbot liq`, `dexbot tv`,
6
+ * `dexbot dw`, and the liquidity analyzer behind them) accepts the same two
7
+ * pool spellings:
8
+ *
9
+ * - object id: 133 or 1.19.133
10
+ * - pool token: the symbol of the pool's LP share asset — the same value a
11
+ * bot can name in its `pool` setting.
12
+ *
13
+ * Parsing and chain lookup live here so those commands cannot drift (numeric
14
+ * ids recognised by one, pool tokens by another) and so they all report the
15
+ * same "not a pool" error.
16
+ *
17
+ * Browser-safe: the chain is reached through a caller-supplied read function,
18
+ * so the same logic serves the script wrappers (shared client), the analysis
19
+ * entries (ephemeral RPC client) and unit tests (stubs).
20
+ */
21
+ import { resolveAssetRef } from './asset_lookup.js';
22
+ const POOL_ID_RE = /^1\.19\.\d+$/;
23
+ const POOL_NUM_RE = /^\d+$/;
24
+ /** `133` / `1.19.133` → `1.19.133`; anything else (a pool token) → null. */
25
+ function normalizePoolRef(ref) {
26
+ const probe = String(ref ?? '').trim();
27
+ if (POOL_ID_RE.test(probe))
28
+ return probe;
29
+ if (POOL_NUM_RE.test(probe))
30
+ return `1.19.${probe}`;
31
+ return null;
32
+ }
33
+ /** True when the reference is a numeric pool id rather than a pool token. */
34
+ function isPoolIdRef(ref) {
35
+ return normalizePoolRef(ref) !== null;
36
+ }
37
+ // Deliberately a junk filter, not a symbol validator: the chain owns the real
38
+ // symbol rules, so this only rejects references that could never name anything
39
+ // (empty, whitespace, or pair syntax) and lets every plausible token through.
40
+ const POOL_REF_SHAPE_RE = /^[^\s/]{1,64}$/;
41
+ /**
42
+ * True when the reference *could* name a pool (numeric id or pool-token shape).
43
+ * Used by the CLI wrappers to fail fast on junk while still accepting tokens;
44
+ * only the chain can confirm a token exists.
45
+ */
46
+ function isPoolRefLike(ref) {
47
+ const probe = String(ref ?? '').trim();
48
+ return isPoolIdRef(probe) || POOL_REF_SHAPE_RE.test(probe);
49
+ }
50
+ /** Pool asset ids, tolerating both `asset_a`/`asset_b` and the `asset_ids` array. */
51
+ function poolAssetIds(pool) {
52
+ if (!pool)
53
+ return [null, null];
54
+ const ids = Array.isArray(pool.asset_ids) ? pool.asset_ids : [];
55
+ return [pool.asset_a ?? ids[0] ?? null, pool.asset_b ?? ids[1] ?? null];
56
+ }
57
+ /**
58
+ * Normalize one `get_objects` / share-asset result entry: nodes answer with the
59
+ * pool object, occasionally nested in a result array, and some wrap it as
60
+ * `{ pool: {...} }`. All three shapes resolve to the pool itself.
61
+ */
62
+ function unwrapPool(entry) {
63
+ if (Array.isArray(entry)) {
64
+ for (const inner of entry) {
65
+ const pool = unwrapPool(inner);
66
+ if (pool)
67
+ return pool;
68
+ }
69
+ return null;
70
+ }
71
+ if (!entry || typeof entry !== 'object')
72
+ return null;
73
+ const record = entry;
74
+ if (record.id)
75
+ return record;
76
+ return record.pool && record.pool.id ? record.pool : null;
77
+ }
78
+ /**
79
+ * Resolve one pool reference to its raw chain object.
80
+ *
81
+ * Numeric references hit `get_objects` directly; a pool token is resolved
82
+ * through `lookup_asset_symbols` (the symbol as typed, then its canonical
83
+ * UPPERCASE form) and `get_liquidity_pools_by_share_asset`.
84
+ */
85
+ async function resolvePoolRef(read, ref) {
86
+ const probe = String(ref ?? '').trim();
87
+ if (!probe)
88
+ throw new Error('Pool reference is empty');
89
+ const poolId = normalizePoolRef(probe);
90
+ if (poolId) {
91
+ const raw = await read('get_objects', [[poolId]]);
92
+ const pool = unwrapPool(raw);
93
+ if (!pool?.id)
94
+ throw new Error(`Liquidity pool ${poolId} not found on chain`);
95
+ return pool;
96
+ }
97
+ const shareAsset = await resolveShareAsset(read, probe);
98
+ const raw = await read('get_liquidity_pools_by_share_asset', [[shareAsset.id], false, false]);
99
+ const pools = (Array.isArray(raw) ? raw : [])
100
+ .map(unwrapPool)
101
+ .filter((entry) => entry != null);
102
+ if (pools.length === 0) {
103
+ throw new Error(`'${probe}' (${shareAsset.id}) is not a liquidity-pool token; pass a pool id (133/1.19.133) or the pool token symbol`);
104
+ }
105
+ return pools[0];
106
+ }
107
+ /** Look up the LP share asset by symbol, case-insensitively (shared resolver). */
108
+ async function resolveShareAsset(read, symbol) {
109
+ const asset = await resolveAssetRef(read, symbol);
110
+ if (!asset?.id) {
111
+ throw new Error(`Pool token '${symbol}' not found on chain (expected the pool's LP share-asset symbol or a pool id like 133/1.19.133)`);
112
+ }
113
+ return { id: String(asset.id), symbol: String(asset.symbol ?? symbol) };
114
+ }
115
+ export { normalizePoolRef, isPoolIdRef, isPoolRefLike, poolAssetIds, resolvePoolRef };
116
+ //# sourceMappingURL=liquidity_pool_ref.js.map
@@ -30,7 +30,7 @@
30
30
  *
31
31
  * In bitshares_client.ts:
32
32
  *
33
- * const NodeManager = require('./node_manager').default;
33
+ * import NodeManager from './node_manager.js';
34
34
  * const nodeManager = new NodeManager(config);
35
35
  * await nodeManager.checkAllNodes();
36
36
  * const bestNode = nodeManager.getBestNode();
@@ -30,7 +30,7 @@
30
30
  *
31
31
  * In bitshares_client.ts:
32
32
  *
33
- * const NodeManager = require('./node_manager').default;
33
+ * import NodeManager from './node_manager.js';
34
34
  * const nodeManager = new NodeManager(config);
35
35
  * await nodeManager.checkAllNodes();
36
36
  * const bestNode = nodeManager.getBestNode();
@@ -88,7 +88,8 @@ import { createRequire } from 'node:module';
88
88
  const require = createRequire(import.meta.url);
89
89
  import { ORDER_TYPES, ORDER_STATES, PIPELINE_TIMING, TIMING, FEE_PARAMETERS, GRID_LIMITS } from '../constants.js';
90
90
  import { resolveAccountRef } from './utils/system.js';
91
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, resolveEdgeCount } from './utils/order.js';
91
+ import { resolveSpreadOrderSide, parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, resolveEdgeCount } from './utils/order.js';
92
+ import { parseSlotIndex } from './utils/slot.js';
92
93
  import { isSlotInRail, floatToBlockchainInt } from './utils/math.js';
93
94
  import * as Format from './format.js';
94
95
  import * as fundRegistry from '../fund_registry.js';
@@ -4,8 +4,8 @@
4
4
  * Trading history extraction and CSV export engine.
5
5
  * Parses PM2 log files to extract trading fills and exports to standardized format.
6
6
  *
7
- * Usage:
8
- * const exporter = require('./order/export');
7
+ * Usage (from the repo root):
8
+ * import * as exporter from './modules/order/export.js';
9
9
  * const result = await exporter.exportBotTrades(botKey, botConfig, outputDir);
10
10
  *
11
11
  * Output Format:
@@ -4,8 +4,8 @@
4
4
  * Trading history extraction and CSV export engine.
5
5
  * Parses PM2 log files to extract trading fills and exports to standardized format.
6
6
  *
7
- * Usage:
8
- * const exporter = require('./order/export');
7
+ * Usage (from the repo root):
8
+ * import * as exporter from './modules/order/export.js';
9
9
  * const result = await exporter.exportBotTrades(botKey, botConfig, outputDir);
10
10
  *
11
11
  * Output Format:
@@ -103,12 +103,22 @@
103
103
  *
104
104
  * ===============================================================================
105
105
  */
106
+ interface SpreadCorrectionRotation {
107
+ id: string;
108
+ orderId: string;
109
+ oldOrder: ManagedOrder;
110
+ newGridId: string;
111
+ newPrice: number;
112
+ newSize: number;
113
+ type: OrderType;
114
+ }
106
115
  interface SpreadCorrection {
107
116
  ordersToPlace: ManagedOrder[];
108
117
  ordersToUpdate: Array<{
109
118
  partialOrder: ManagedOrder;
110
119
  newSize: number;
111
120
  }>;
121
+ ordersToRotate?: SpreadCorrectionRotation[];
112
122
  plannedCount?: number;
113
123
  stallHint?: SpreadCorrectionStall;
114
124
  boundaryIdx?: number;
@@ -145,7 +155,7 @@ export declare const SPREAD_CORRECTION_REFUSAL: Readonly<{
145
155
  /** Unclassified non-execution (fallback). */
146
156
  readonly BATCH_NOT_EXECUTED: "batch-not-executed";
147
157
  }>;
148
- export type SpreadCorrectionRefusalCause = (typeof SPREAD_CORRECTION_REFUSAL)[keyof typeof SPREAD_CORRECTION_REFUSAL];
158
+ type SpreadCorrectionRefusalCause = (typeof SPREAD_CORRECTION_REFUSAL)[keyof typeof SPREAD_CORRECTION_REFUSAL];
149
159
  /**
150
160
  * Whether a refusal cause is retryable by the bounded spread-correction re-plan.
151
161
  * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
@@ -169,13 +179,6 @@ export declare function classifySpreadRefusalCause(batchResult: unknown): Spread
169
179
  * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
170
180
  */
171
181
  export declare function recordSpreadCorrectionRefusal(manager: OrderManagerLike, cause: SpreadCorrectionRefusalCause): void;
172
- /**
173
- * P5 observability: count a bounded spread-correction re-plan retry. Churn
174
- * signal — a rising retry rate means concurrent commits are repeatedly
175
- * invalidating corrections. Counter-only; never throws.
176
- * @param {Object} manager - OrderManager instance
177
- */
178
- export declare function recordSpreadCorrectionRetry(manager: OrderManagerLike): void;
179
182
  /**
180
183
  * P2 plan-time dedupe: which of a correction's planned CREATE destinations are
181
184
  * now occupied by a live (ACTIVE/PARTIAL) order with a chain id?
@@ -196,11 +199,12 @@ export declare function getOccupiedCorrectionSlots(manager: OrderManagerLike, co
196
199
  /**
197
200
  * P1/P3 shared re-plan: derive a spread correction from the CURRENT master
198
201
  * state (side chosen from fresh on-chain book, opposite-side starvation
199
- * fallback). Used both for the plan-time collision dedupe and the bounded
200
- * refusal retry. Read-only against the grid; no _gridLock needed (matches the
201
- * existing TOCTOU fund re-plan contract).
202
+ * fallback). A zero-free decision still tries the rotation-only fallback.
203
+ * Used both for the plan-time collision dedupe and the bounded refusal retry.
204
+ * Read-only against the grid; no _gridLock needed (matches the existing TOCTOU
205
+ * fund re-plan contract).
202
206
  * @param {Object} manager - OrderManager instance
203
- * @returns {Promise<Object|null>} A correction with at least one create, or null
207
+ * @returns {Promise<Object|null>} A correction with at least one executable action, or null
204
208
  */
205
209
  export declare function replanSpreadCorrectionFromFreshMaster(manager: OrderManagerLike): Promise<SpreadCorrection | null>;
206
210
  /**
@@ -209,7 +213,7 @@ export declare function replanSpreadCorrectionFromFreshMaster(manager: OrderMana
209
213
  * - 'replanned': a destination was taken and a fresh correction was derived.
210
214
  * - 'blocked': a destination was taken and no fresh correction exists — refuse.
211
215
  */
212
- export type OccupiedCorrectionResolution = {
216
+ type OccupiedCorrectionResolution = {
213
217
  action: 'broadcast';
214
218
  } | {
215
219
  action: 'replanned';
@@ -696,11 +700,12 @@ export declare function getDustOrders(manager: OrderManagerLike, partials: Manag
696
700
  * @param {import('./types').OrderManager} manager - The manager instance.
697
701
  * @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
698
702
  * normalize sell-side funds into buy-side units for a fair cross-asset comparison.
699
- * @returns {{ side: import('./types').OrderType|null, reason: string }} The side to correct on, or null if insufficient funds.
703
+ * @returns {{ side: import('./types').OrderType|null, reason: string, code?: 'market-price-unavailable'|'no-free-funds' }} The side to correct on, or null with a structured cause.
700
704
  */
701
705
  export declare function determineOrderSideByFunds(manager: OrderManagerLike, currentMarketPrice: number): {
702
706
  side: OrderType | null;
703
707
  reason: string;
708
+ code?: 'market-price-unavailable' | 'no-free-funds';
704
709
  };
705
710
  /**
706
711
  * Prepares one or more orders to correct a wide spread.