dexbot 1.6.12 → 1.6.13

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 (170) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/analysis/README.md +9 -11
  3. package/analysis/ama_fitting/README.md +5 -3
  4. package/claw/README.md +1 -0
  5. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  6. package/claw/modules/claw_bridge.ts +0 -3
  7. package/claw/modules/claw_skill_md.ts +1 -0
  8. package/claw/package.json +3 -3
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/tsconfig.json +2 -2
  12. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  13. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  14. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  15. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  16. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  17. package/dist/analysis/analyze_args.d.ts +12 -0
  18. package/dist/analysis/analyze_args.js +20 -0
  19. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  20. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  21. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  22. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  23. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  24. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  25. package/dist/analysis/chart_ui.d.ts +30 -1
  26. package/dist/analysis/chart_ui.js +37 -1
  27. package/dist/analysis/fills_cache.d.ts +3 -23
  28. package/dist/analysis/fills_cache.js +3 -84
  29. package/dist/analysis/fills_source.d.ts +31 -1
  30. package/dist/analysis/fills_source.js +69 -1
  31. package/dist/analysis/grid_correction_check.d.ts +1 -23
  32. package/dist/analysis/grid_correction_check.js +15 -58
  33. package/dist/analysis/math_utils.d.ts +85 -1
  34. package/dist/analysis/math_utils.js +116 -1
  35. package/dist/analysis/price_sources.d.ts +22 -1
  36. package/dist/analysis/price_sources.js +23 -0
  37. package/dist/analysis/resolve_source.js +31 -10
  38. package/dist/analysis/trade_profitability.d.ts +6 -0
  39. package/dist/analysis/trade_profitability.js +23 -97
  40. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  41. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  42. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
  43. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  44. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  45. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  46. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  47. package/dist/analysis/worker_pool.d.ts +38 -0
  48. package/dist/analysis/worker_pool.js +67 -0
  49. package/dist/dexbot.js +67 -48
  50. package/dist/market_adapter/ama_signal_runner.js +21 -54
  51. package/dist/market_adapter/candle_utils.d.ts +7 -1
  52. package/dist/market_adapter/candle_utils.js +11 -1
  53. package/dist/market_adapter/cli_args.d.ts +22 -0
  54. package/dist/market_adapter/cli_args.js +30 -0
  55. package/dist/market_adapter/core/config_normalizers.js +11 -6
  56. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  57. package/dist/market_adapter/core/kibana_candles.js +3 -2
  58. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  59. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  60. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  61. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  62. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  63. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  64. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  65. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  66. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  67. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  68. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  69. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  70. package/dist/market_adapter/inputs/window_cache.js +52 -177
  71. package/dist/market_adapter/interval_utils.d.ts +11 -1
  72. package/dist/market_adapter/interval_utils.js +16 -1
  73. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  74. package/dist/market_adapter/lp_chart_runner.js +37 -19
  75. package/dist/market_adapter/market_adapter.js +27 -72
  76. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  77. package/dist/market_adapter/utils/data_discovery.js +220 -27
  78. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  79. package/dist/market_adapter/utils/month_shards.js +237 -0
  80. package/dist/modules/account_bots.d.ts +1 -0
  81. package/dist/modules/account_bots.js +102 -121
  82. package/dist/modules/account_orders.d.ts +13 -0
  83. package/dist/modules/account_orders.js +38 -44
  84. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  85. package/dist/modules/bitshares-native/chain_client.js +14 -13
  86. package/dist/modules/bitshares-native/resolvers.js +22 -25
  87. package/dist/modules/bitshares-native/serial/types.js +22 -50
  88. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  89. package/dist/modules/bot_defaults.d.ts +2 -1
  90. package/dist/modules/bot_settings.d.ts +1 -1
  91. package/dist/modules/broadcast_failure.d.ts +2 -1
  92. package/dist/modules/chain_orders.d.ts +1 -1
  93. package/dist/modules/chain_orders.js +51 -96
  94. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  95. package/dist/modules/constants.d.ts +7 -1
  96. package/dist/modules/constants.js +20 -1
  97. package/dist/modules/cr_planner.d.ts +1 -1
  98. package/dist/modules/cr_planner.js +1 -5
  99. package/dist/modules/credit_pricing.d.ts +2 -1
  100. package/dist/modules/credit_pricing.js +36 -40
  101. package/dist/modules/credit_runtime.d.ts +7 -0
  102. package/dist/modules/credit_runtime.js +45 -73
  103. package/dist/modules/daemon_node_health.d.ts +4 -3
  104. package/dist/modules/dexbot_class.d.ts +28 -17
  105. package/dist/modules/dexbot_class.js +105 -58
  106. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  107. package/dist/modules/dexbot_cow_runtime.js +54 -28
  108. package/dist/modules/dexbot_credential_client.d.ts +0 -7
  109. package/dist/modules/dexbot_credential_client.js +1 -2
  110. package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
  111. package/dist/modules/dexbot_fill_runtime.js +5 -6
  112. package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
  113. package/dist/modules/dexbot_maintenance_runtime.js +84 -69
  114. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  115. package/dist/modules/dexbot_startup_runtime.js +13 -14
  116. package/dist/modules/general_settings.d.ts +1 -1
  117. package/dist/modules/graceful_shutdown.js +17 -11
  118. package/dist/modules/key_store.js +0 -1
  119. package/dist/modules/lazy_shim.d.ts +11 -0
  120. package/dist/modules/lazy_shim.js +16 -0
  121. package/dist/modules/node_connect_policy.d.ts +3 -2
  122. package/dist/modules/node_failure_ledger.d.ts +6 -5
  123. package/dist/modules/order/format.d.ts +12 -3
  124. package/dist/modules/order/format.js +15 -3
  125. package/dist/modules/order/genesis_policy.d.ts +3 -3
  126. package/dist/modules/order/genesis_policy.js +5 -2
  127. package/dist/modules/order/grid.d.ts +4 -2
  128. package/dist/modules/order/grid.js +91 -35
  129. package/dist/modules/order/index.d.ts +1 -0
  130. package/dist/modules/order/logger.d.ts +1 -8
  131. package/dist/modules/order/logger.js +0 -9
  132. package/dist/modules/order/manager.d.ts +9 -13
  133. package/dist/modules/order/manager.js +33 -50
  134. package/dist/modules/order/utils/order.js +39 -35
  135. package/dist/modules/order/utils/system.d.ts +9 -29
  136. package/dist/modules/order/utils/system.js +17 -2
  137. package/dist/modules/order/utils/validate.js +2 -2
  138. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  139. package/dist/modules/paths.js +32 -34
  140. package/dist/modules/runtime_settings.d.ts +2 -4
  141. package/dist/modules/settings_merge.d.ts +2 -2
  142. package/dist/modules/socket_json_client.d.ts +2 -1
  143. package/dist/modules/types.d.ts +42 -27
  144. package/dist/modules/utils/errors.js +1 -3
  145. package/dist/modules/version_notice.d.ts +11 -10
  146. package/dist/pm2.d.ts +0 -1
  147. package/dist/pm2.js +56 -35
  148. package/dist/scripts/analyze-git.js +2 -15
  149. package/dist/scripts/chart_command.js +2 -2
  150. package/dist/scripts/check_any.d.ts +4 -0
  151. package/dist/scripts/check_any.js +53 -21
  152. package/dist/scripts/diagnose-pool-history.js +1 -6
  153. package/dist/scripts/run-tests.js +0 -1
  154. package/dist/scripts/sync-version.js +0 -10
  155. package/docs/BITSHARES_ONBOARDING.md +8 -12
  156. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  157. package/docs/DEXBOT_COMPARISON.md +6 -6
  158. package/docs/EVOLUTION.md +9 -8
  159. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  160. package/docs/README.md +1 -1
  161. package/docs/WORKFLOW.md +1 -0
  162. package/docs/architecture.md +19 -10
  163. package/market_adapter/README.md +6 -4
  164. package/package.json +6 -9
  165. package/scripts/README.md +43 -38
  166. package/tests/README.md +25 -10
  167. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  168. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  169. package/scripts/git-viewer.sh +0 -489
  170. package/scripts/postinstall.js +0 -16
@@ -89,13 +89,26 @@
89
89
  */
90
90
  import { createRequire } from 'node:module';
91
91
  const require = createRequire(import.meta.url);
92
- import { ORDER_TYPES, ORDER_STATES, COW_ACTIONS, DEFAULT_CONFIG, GRID_LIMITS, TIMING, PIPELINE_TIMING, MARKET_ADAPTER, INCREMENT_BOUNDS } from '../constants.js';
92
+ import { ORDER_TYPES, ORDER_STATES, COW_ACTIONS, COW_ORIGINS, DEFAULT_CONFIG, GRID_LIMITS, TIMING, PIPELINE_TIMING, MARKET_ADAPTER, INCREMENT_BOUNDS } from '../constants.js';
93
93
  import * as Format from './format.js';
94
94
  import { resolveMaxAsymmetryFactor, applyAsymmetricBounds, applyNarrowingSideGuard, } from '../../market_adapter/core/asymmetric_bounds.js';
95
95
  // FIX: Extract magic numbers to named constants for maintainability
96
96
  const GRID_CONSTANTS = {
97
97
  RMS_PERCENTAGE_SCALE: 100, // Convert RMS percentage threshold from percent to decimal
98
98
  };
99
+ /**
100
+ * Fold a prepared correction (or the absence of one) into the stall cause the
101
+ * caller reports. A plan that existed but funded nothing ('unfunded'), or a
102
+ * zero sizing budget ('stallHint: unfunded'), is a FUND condition; anything
103
+ * else is a structural 'no-candidates'. The two sides are merged with this so
104
+ * an unfunded plan on one side is never masked by an empty plan on the other
105
+ * (e.g. chosen side planned 1 / placed 0, opposite side planned 0).
106
+ */
107
+ function classifySpreadStall(c) {
108
+ if (Number(c?.plannedCount || 0) > 0 || c?.stallHint === 'unfunded')
109
+ return 'unfunded';
110
+ return 'no-candidates';
111
+ }
99
112
  /**
100
113
  * Central resolution for the RMS structural-divergence threshold (percent).
101
114
  * Single source of truth: per-bot override wins, global GRID_COMPARISON default
@@ -1989,10 +2002,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
1989
2002
  // This prevents concurrent fill processing from modifying funds while we're making decisions
1990
2003
  let correction = null;
1991
2004
  let shouldApplyCorrection = false;
1992
- // Set when determineOrderSideByFunds finds no side to fund: the caller
1993
- // refreshes account totals + open orders so the next cycle re-checks
1994
- // against fresh balances instead of recycling resting orders.
1995
- let fundsExhausted = false;
2005
+ // Why no effective order landed, when that happens. The caller uses the
2006
+ // exact cause (not a boolean) to decide whether a funds/open-orders
2007
+ // refresh can help and to log the truth: 'no-candidates' is structural
2008
+ // and owned by the out-of-spread staleness watchdog, while the fund and
2009
+ // batch causes are what a refresh actually repairs.
2010
+ let stall;
1996
2011
  if (!manager._gridLock) {
1997
2012
  manager.logger?.log?.('Spread check skipped: no grid lock available', 'warn');
1998
2013
  return { ordersPlaced: 0, partialsMoved: 0 };
@@ -2085,18 +2100,27 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2085
2100
  catch { /* best-effort */ }
2086
2101
  const decision = determineOrderSideByFunds(manager, lastPrice);
2087
2102
  if (!decision.side) {
2088
- fundsExhausted = true;
2103
+ stall = 'no-free-funds';
2089
2104
  return false;
2090
2105
  }
2091
2106
  // Perform spread correction by placing orders on the chosen side.
2092
2107
  correction = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
2093
- if (!correction)
2108
+ if (!correction) {
2109
+ stall = 'no-candidates';
2094
2110
  return false;
2111
+ }
2095
2112
  let placeCount = correction.ordersToPlace?.length || 0;
2096
- let updateCount = correction.ordersToUpdate?.length || 0;
2113
+ // Fold each side into the stall cause; merge (never overwrite) across
2114
+ // the starvation fallback so an UNFUNDED plan on the chosen side is
2115
+ // not masked by an empty plan on the opposite side. The old code
2116
+ // overwrote plannedCount with the opposite side's 0, so a
2117
+ // planned-1/placed-0 side followed by a planned-0 opposite reported
2118
+ // 'no-candidates' and the maintenance refresh never armed — exactly
2119
+ // the stale-balance case the refresh exists for.
2120
+ let sideStall = classifySpreadStall(correction);
2097
2121
  // STARVATION FALLBACK: If the selected side has no correctable slots (e.g.
2098
2122
  // all SPREAD slots already filled or misaligned), try the opposite side.
2099
- if ((placeCount + updateCount) === 0) {
2123
+ if (placeCount === 0) {
2100
2124
  const oppositeSide = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
2101
2125
  manager.logger?.log?.(`[SPREAD] Side ${decision.side} produced zero candidates; ` +
2102
2126
  `trying opposite side ${oppositeSide}.`, 'debug');
@@ -2104,20 +2128,26 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2104
2128
  if (oppositeCorrection) {
2105
2129
  correction = oppositeCorrection;
2106
2130
  placeCount = oppositeCorrection.ordersToPlace?.length || 0;
2107
- updateCount = oppositeCorrection.ordersToUpdate?.length || 0;
2131
+ const oppositeStall = classifySpreadStall(oppositeCorrection);
2132
+ sideStall = (sideStall === 'unfunded' || oppositeStall === 'unfunded')
2133
+ ? 'unfunded'
2134
+ : 'no-candidates';
2108
2135
  }
2109
2136
  }
2110
2137
  // Capture fund snapshot under lock for pre-flight verification before broadcast
2111
2138
  fundSnapshot = _snapshotFundState(manager);
2112
- // No executable correction on EITHER side: the balances/holds may be a
2113
- // stale snapshot (the grid does not lose funds, it holds them in
2114
- // resting/virtual slots), so ask the caller to refresh account totals +
2115
- // open orders instead of re-deriving the identical starved plan next
2116
- // tick. Previously only the "no side at all" case set this flag, so a
2117
- // fund-constrained plan on a chosen side never triggered a refresh.
2118
- if ((placeCount + updateCount) === 0)
2119
- fundsExhausted = true;
2120
- return (placeCount + updateCount) > 0;
2139
+ // No executable correction on EITHER side. Carry the exact cause so the
2140
+ // caller refreshes only when a refresh can actually repair something:
2141
+ // * 'no-candidates' — no spread-tightening slot exists at all. This is
2142
+ // structural; the out-of-spread staleness watchdog escalates it to a
2143
+ // re-center, so it must NOT re-arm the per-cooldown fund/open-orders
2144
+ // refresh (previously every zero-placement did, churning a full
2145
+ // account + open-orders reload on a structurally stalled grid).
2146
+ // * 'unfunded' — a plan existed but free funds could not fund any of it;
2147
+ // the balances/holds may be a stale snapshot, so a refresh is warranted.
2148
+ if (placeCount === 0)
2149
+ stall = sideStall;
2150
+ return placeCount > 0;
2121
2151
  };
2122
2152
  try {
2123
2153
  shouldApplyCorrection = await manager._gridLock.acquire(executeSpreadCheck);
@@ -2165,11 +2195,11 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2165
2195
  manager.logger?.log?.(`[SPREAD] Fund state changed; no side has sufficient funds for re-plan. Skipping cycle.`, 'warn');
2166
2196
  // Same no-free-funds condition as the initial decision:
2167
2197
  // signal the caller to refresh account totals/open orders.
2168
- fundsExhausted = true;
2169
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
2198
+ stall = 'no-free-funds';
2199
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2170
2200
  }
2171
2201
  const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
2172
- if (rePlanCorrection && ((rePlanCorrection.ordersToPlace?.length || 0) + (rePlanCorrection.ordersToUpdate?.length || 0) > 0)) {
2202
+ if (rePlanCorrection && (rePlanCorrection.ordersToPlace?.length || 0) > 0) {
2173
2203
  activeCorrection = rePlanCorrection;
2174
2204
  activeSnapshot = currentFunds;
2175
2205
  manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
@@ -2177,7 +2207,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2177
2207
  }
2178
2208
  else {
2179
2209
  manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
2180
- return { ordersPlaced: 0, partialsMoved: 0 };
2210
+ // A plan existed before the fund change but the re-plan found
2211
+ // nothing executable. Carry the cause here too (F2): this is the
2212
+ // most fund-relevant outcome of all, so it must not silently skip
2213
+ // the refresh request while every sibling branch signals it.
2214
+ stall = classifySpreadStall(rePlanCorrection);
2215
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2181
2216
  }
2182
2217
  }
2183
2218
  try {
@@ -2187,19 +2222,18 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2187
2222
  // Nothing landed: ask the caller to refresh account totals +
2188
2223
  // open orders (stale holds/balances can make the same plan
2189
2224
  // re-derive every cycle).
2190
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted: true };
2225
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed' };
2191
2226
  }
2192
2227
  await manager.recalculateFunds();
2193
2228
  const placed = activeCorrection.ordersToPlace?.length || 0;
2194
- const updated = activeCorrection.ordersToUpdate?.length || 0;
2195
- return { ordersPlaced: placed + updated, partialsMoved: updated };
2229
+ return { ordersPlaced: placed, partialsMoved: 0 };
2196
2230
  }
2197
2231
  catch (err) {
2198
2232
  manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
2199
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted: true };
2233
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'apply-error' };
2200
2234
  }
2201
2235
  }
2202
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
2236
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2203
2237
  }
2204
2238
  /**
2205
2239
  * Grid health check for structural violations.
@@ -2676,8 +2710,16 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2676
2710
  // With no live order on the side there is no reference to improve, so
2677
2711
  // the market-nearest slot is by definition the best available and the
2678
2712
  // guard stays open.
2713
+ // F3: a null/non-finite price must never enter a candidate pool. The
2714
+ // pools are sorted by distance and sliced to missingSlots BEFORE the
2715
+ // duplicate-price filter drops null prices, so a null-price orphan would
2716
+ // otherwise consume a quota seat (JS coerces null to 0, sorting it first
2717
+ // on a SELL rail) and evict the window-nearest valid slot. Rejecting it
2718
+ // here is the single chokepoint both pools already pass through.
2679
2719
  const tightensSpread = (c) => {
2680
- if (bestLiveOnRail == null || c?.price == null)
2720
+ if (c?.price == null || !Number.isFinite(c.price))
2721
+ return false;
2722
+ if (bestLiveOnRail == null)
2681
2723
  return true;
2682
2724
  return railBestIsMax ? c.price > bestLiveOnRail : c.price < bestLiveOnRail;
2683
2725
  };
@@ -2691,8 +2733,17 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2691
2733
  // Secondary candidates: orphaned virtual slots that have lost their
2692
2734
  // order (e.g. stale-cleaned after a race condition during a crash, or a
2693
2735
  // lowest-sell slot dust-cancelled and then left unplaced after a
2694
- // boundary shift). These sit inside the active window and are invisible
2695
- // to the gap-band SPREAD filter above.
2736
+ // boundary shift). They are invisible to the gap-band SPREAD filter
2737
+ // above because they are stored as railType (not SPREAD).
2738
+ //
2739
+ // SCOPE (F4): this path repairs only orphans at the window's market
2740
+ // edge — the tightensSpread guard below keeps a SELL below the lowest
2741
+ // live sell and a BUY above the highest live buy. An orphan that sits
2742
+ // in the rail INTERIOR (between two live orders) leaves bestBuy/bestSell
2743
+ // bit-for-bit unchanged, so it is deliberately excluded here; interior
2744
+ // holes are a divergence/reconcile concern, not a spread repair. Do not
2745
+ // "fix" the guard to admit them — filling them would not tighten a
2746
+ // spread and would fight the window-contiguous placement strategy.
2696
2747
  //
2697
2748
  // Empty slots are stored SPREAD (side-neutral) after normalization, so
2698
2749
  // the stored type can be railType OR SPREAD — what matters is that the
@@ -2850,7 +2901,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2850
2901
  manager.logger?.log?.(bestLiveOnRail == null
2851
2902
  ? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
2852
2903
  : `[SPREAD-CORRECTION] No spread-tightening slot on ${sideName} (best live ${bestLiveOnRail}); every remaining empty slot sits beyond the live window and cannot narrow the spread. Skipping.`, 'warn');
2853
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
2904
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
2854
2905
  }
2855
2906
  const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
2856
2907
  const sideSlots = allOrders
@@ -2862,7 +2913,12 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2862
2913
  ].sort((a, b) => a.price - b.price);
2863
2914
  const ctx = await _getSizingContext(manager, sideName);
2864
2915
  if (!ctx || ctx.budget <= 0 || syntheticSideSlots.length === 0) {
2865
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
2916
+ // A zero sizing budget is a FUND condition (stale/empty free balance),
2917
+ // not a structural one — mark it 'unfunded' so the caller keeps
2918
+ // arming the refresh for it. A missing context or an empty rail is
2919
+ // genuinely structural.
2920
+ const stallHint = (ctx && Number(ctx.budget) <= 0) ? 'unfunded' : 'no-candidates';
2921
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
2866
2922
  }
2867
2923
  const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
2868
2924
  const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, (manager.config.weightDistribution ?? {})[sideName], (manager.config.incrementPercent ?? 0) / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
@@ -2901,7 +2957,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2901
2957
  }
2902
2958
  }
2903
2959
  if (prioritizedTargets.length === 0) {
2904
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
2960
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
2905
2961
  }
2906
2962
  let remainingBudget = availableFund;
2907
2963
  // FUNDING PROBE (diagnostic): one line per correction cycle showing the
@@ -3013,6 +3069,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3013
3069
  if (ordersToPlace.length > 0) {
3014
3070
  manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length}, remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
3015
3071
  }
3016
- return { ordersToPlace, ordersToUpdate: [], ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: 'spread-correction' };
3072
+ return { ordersToPlace, ordersToUpdate: [], plannedCount: prioritizedTargets.length, ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: COW_ORIGINS.SPREAD_CORRECTION };
3017
3073
  }
3018
3074
  //# sourceMappingURL=grid.js.map
@@ -122,6 +122,7 @@ declare const utils: {
122
122
  resolveAccountRef(manager: import("../types.js").OrderManagerLike, account: string): string | null;
123
123
  deepFreeze<T>(obj: T): T;
124
124
  cloneMap<K, V>(map: Map<K, V>): Map<K, V>;
125
+ fireStructuralResync(bot: import("../types.js").BotLike, reason: string, details: Record<string, unknown>, errorLabel: string, level?: string): void;
125
126
  parseJsonWithComments(raw: string): Record<string, unknown>;
126
127
  applyPersistedPendingCrawls(bot: import("../types.js").BotLike, options?: {
127
128
  log?: (message: string, level?: string) => void;
@@ -83,10 +83,6 @@ declare class Logger {
83
83
  * @param {string} [category='DEXBot'] - Logger category/prefix
84
84
  * @param {Object} [options]
85
85
  * @param {boolean} [options.quiet] - Suppress console output
86
- * @param {boolean} [options.quietUnderPm2=false] - Legacy opt-in to suppress
87
- * console output under PM2. Keep this false in normal operation: under
88
- * PM2 stdout is the only sink (direct file writes are suppressed), so
89
- * auto-quieting drops every log line.
90
86
  * @param {string} [options.logFile] - Optional path to log file
91
87
  * @param {string} [options.level='info'] - Log level
92
88
  * @param {Object} [options.configOverride] - Override LOGGING_CONFIG
@@ -94,7 +90,6 @@ declare class Logger {
94
90
  */
95
91
  constructor(category?: string, options?: {
96
92
  quiet?: boolean;
97
- quietUnderPm2?: boolean;
98
93
  logFile?: string;
99
94
  level?: string;
100
95
  configOverride?: LoggerConfig;
@@ -179,9 +174,7 @@ declare function isPm2Runtime(): boolean;
179
174
  * PM2-managed file.
180
175
  */
181
176
  declare function isPm2LogCaptureActive(): boolean;
182
- declare function createPm2AwareLogger(category: string, options?: {
183
- quietUnderPm2?: boolean;
184
- }): Logger;
177
+ declare function createPm2AwareLogger(category: string, options?: ConstructorParameters<typeof Logger>[1]): Logger;
185
178
  export { createPm2AwareLogger, isPm2Runtime, isPm2LogCaptureActive, setGlobalConsoleLevel, getGlobalConsoleLevel };
186
179
  export default Logger;
187
180
  //# sourceMappingURL=logger.d.ts.map
@@ -105,10 +105,6 @@ class Logger {
105
105
  * @param {string} [category='DEXBot'] - Logger category/prefix
106
106
  * @param {Object} [options]
107
107
  * @param {boolean} [options.quiet] - Suppress console output
108
- * @param {boolean} [options.quietUnderPm2=false] - Legacy opt-in to suppress
109
- * console output under PM2. Keep this false in normal operation: under
110
- * PM2 stdout is the only sink (direct file writes are suppressed), so
111
- * auto-quieting drops every log line.
112
108
  * @param {string} [options.logFile] - Optional path to log file
113
109
  * @param {string} [options.level='info'] - Log level
114
110
  * @param {Object} [options.configOverride] - Override LOGGING_CONFIG
@@ -116,15 +112,10 @@ class Logger {
116
112
  */
117
113
  constructor(category = 'DEXBot', options = {}) {
118
114
  this.category = category;
119
- const isUnderPm2 = !!Config.pm_exec_path;
120
115
  this.logFile = options.logFile || null;
121
116
  if (options.quiet !== undefined) {
122
117
  this.quiet = options.quiet;
123
118
  }
124
- else if (options.quietUnderPm2 === true && isUnderPm2) {
125
- // Legacy escape hatch: explicit opt-in to the old silent behaviour.
126
- this.quiet = true;
127
- }
128
119
  else {
129
120
  // Non-PM2 runs with a logFile write to the file only, so console is
130
121
  // quiet to avoid duplication. Under PM2 the file sink is suppressed
@@ -131,10 +131,7 @@ declare class OrderManager implements OrderManagerLike {
131
131
  lastTriggeredAt: number;
132
132
  };
133
133
  };
134
- private _ordersByTypeCache;
135
- private _ordersByStateCache;
136
- private _ordersByTypeCacheVersion;
137
- private _ordersByStateCacheVersion;
134
+ private _orderIdIndexes;
138
135
  /**
139
136
  * Lazy-compute order-IDs grouped by type.
140
137
  *
@@ -156,6 +153,8 @@ declare class OrderManager implements OrderManagerLike {
156
153
  */
157
154
  get _ordersByState(): Record<string, Set<string>>;
158
155
  set _ordersByState(val: Record<string, Set<string>>);
156
+ /** Rebuild an order-id index for `field` over `keys`, memoized per `_gridVersion`. */
157
+ private _getOrderIdIndex;
159
158
  initialSpreadCount: number;
160
159
  currentSpreadCount: number;
161
160
  outOfSpread: number;
@@ -228,7 +227,6 @@ declare class OrderManager implements OrderManagerLike {
228
227
  fillsAt: number | null;
229
228
  } | null;
230
229
  _heldPlanSuppressionCount: number;
231
- _onBroadcastRegionEnd?: () => void;
232
230
  _onBroadcastRegionEndListeners: Array<() => void>;
233
231
  _lastBoundaryHoldResyncAt: number;
234
232
  _gapEvacStreaks: Map<string, number>;
@@ -339,17 +337,15 @@ declare class OrderManager implements OrderManagerLike {
339
337
  * without rescheduling, so this is the only wake-up for fills enqueued
340
338
  * during a region; the watchdog path must fire it too or a hung broadcast's
341
339
  * queued fills wait for the next fill event.
342
- * Fans out to the legacy single listener plus every registered listener
343
- * (see addBroadcastRegionEndListener): a second wirer must never silently
344
- * displace the fill-queue drain. Guarded so a listener error never escapes
345
- * into a finally/watchdog frame.
340
+ * Fans out to every listener registered via addBroadcastRegionEndListener:
341
+ * a second wirer must never silently displace the fill-queue drain.
342
+ * Guarded so a listener error never escapes into a finally/watchdog frame.
346
343
  * @returns {void}
347
344
  */
348
345
  _fireBroadcastRegionEnd(): void;
349
346
  /**
350
- * Register an additional broadcast-region-end listener without displacing
351
- * the legacy single listener or previously registered ones. Duplicate
352
- * registrations of the same function reference are ignored.
347
+ * Register a broadcast-region-end listener. Duplicate registrations of the
348
+ * same function reference are ignored.
353
349
  * @param {() => void} listener
354
350
  * @returns {void}
355
351
  */
@@ -764,7 +760,7 @@ declare class OrderManager implements OrderManagerLike {
764
760
  }>) | null): Promise<{
765
761
  ordersPlaced: number;
766
762
  partialsMoved: number;
767
- fundsExhausted?: boolean;
763
+ stall?: import("../types.js").SpreadCorrectionStall;
768
764
  }>;
769
765
  /**
770
766
  * @param {Function} batchCb - Batch callback
@@ -322,10 +322,10 @@ class OrderManager {
322
322
  _accountingFailureSignal;
323
323
  _recoveryStateValue;
324
324
  _gridRegenStateValue;
325
- _ordersByTypeCache = null;
326
- _ordersByStateCache = null;
327
- _ordersByTypeCacheVersion = -1;
328
- _ordersByStateCacheVersion = -1;
325
+ _orderIdIndexes = {
326
+ type: { cache: null, version: -1 },
327
+ state: { cache: null, version: -1 },
328
+ };
329
329
  /**
330
330
  * Lazy-compute order-IDs grouped by type.
331
331
  *
@@ -340,48 +340,40 @@ class OrderManager {
340
340
  * next grid-version bump triggers a full rebuild from the real orders.
341
341
  */
342
342
  get _ordersByType() {
343
- if (this._ordersByTypeCache !== null && this._ordersByTypeCacheVersion === this._gridVersion) {
344
- return this._ordersByTypeCache;
345
- }
346
- const byType = {};
347
- for (const key of [ORDER_TYPES.BUY, ORDER_TYPES.SELL, ORDER_TYPES.SPREAD]) {
348
- byType[key] = new Set();
349
- }
350
- for (const [id, o] of this.orders) {
351
- if (byType[o.type])
352
- byType[o.type].add(id);
353
- }
354
- this._ordersByTypeCache = byType;
355
- this._ordersByTypeCacheVersion = this._gridVersion;
356
- return byType;
343
+ return this._getOrderIdIndex('type', [ORDER_TYPES.BUY, ORDER_TYPES.SELL, ORDER_TYPES.SPREAD]);
357
344
  }
358
345
  set _ordersByType(val) {
359
- this._ordersByTypeCache = val;
360
- this._ordersByTypeCacheVersion = this._gridVersion;
346
+ this._orderIdIndexes.type.cache = val;
347
+ this._orderIdIndexes.type.version = this._gridVersion;
361
348
  }
362
349
  /**
363
350
  * Lazy-compute order-IDs grouped by state. Same semantics as
364
351
  * _ordersByType — see getter doc for details.
365
352
  */
366
353
  get _ordersByState() {
367
- if (this._ordersByStateCache !== null && this._ordersByStateCacheVersion === this._gridVersion) {
368
- return this._ordersByStateCache;
369
- }
370
- const byState = {};
371
- for (const key of [ORDER_STATES.VIRTUAL, ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL]) {
372
- byState[key] = new Set();
373
- }
374
- for (const [id, o] of this.orders) {
375
- if (byState[o.state])
376
- byState[o.state].add(id);
377
- }
378
- this._ordersByStateCache = byState;
379
- this._ordersByStateCacheVersion = this._gridVersion;
380
- return byState;
354
+ return this._getOrderIdIndex('state', [ORDER_STATES.VIRTUAL, ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL]);
381
355
  }
382
356
  set _ordersByState(val) {
383
- this._ordersByStateCache = val;
384
- this._ordersByStateCacheVersion = this._gridVersion;
357
+ this._orderIdIndexes.state.cache = val;
358
+ this._orderIdIndexes.state.version = this._gridVersion;
359
+ }
360
+ /** Rebuild an order-id index for `field` over `keys`, memoized per `_gridVersion`. */
361
+ _getOrderIdIndex(field, keys) {
362
+ const slot = this._orderIdIndexes[field];
363
+ if (slot.cache !== null && slot.version === this._gridVersion) {
364
+ return slot.cache;
365
+ }
366
+ const index = {};
367
+ for (const key of keys)
368
+ index[key] = new Set();
369
+ for (const [id, o] of this.orders) {
370
+ const key = o[field];
371
+ if (index[key])
372
+ index[key].add(id);
373
+ }
374
+ slot.cache = index;
375
+ slot.version = this._gridVersion;
376
+ return index;
385
377
  }
386
378
  initialSpreadCount;
387
379
  currentSpreadCount;
@@ -441,7 +433,6 @@ class OrderManager {
441
433
  _deferredRebalanceAt;
442
434
  _lastHeldPlanSignature;
443
435
  _heldPlanSuppressionCount;
444
- _onBroadcastRegionEnd;
445
436
  _onBroadcastRegionEndListeners;
446
437
  _lastBoundaryHoldResyncAt;
447
438
  _gapEvacStreaks;
@@ -804,19 +795,12 @@ class OrderManager {
804
795
  * without rescheduling, so this is the only wake-up for fills enqueued
805
796
  * during a region; the watchdog path must fire it too or a hung broadcast's
806
797
  * queued fills wait for the next fill event.
807
- * Fans out to the legacy single listener plus every registered listener
808
- * (see addBroadcastRegionEndListener): a second wirer must never silently
809
- * displace the fill-queue drain. Guarded so a listener error never escapes
810
- * into a finally/watchdog frame.
798
+ * Fans out to every listener registered via addBroadcastRegionEndListener:
799
+ * a second wirer must never silently displace the fill-queue drain.
800
+ * Guarded so a listener error never escapes into a finally/watchdog frame.
811
801
  * @returns {void}
812
802
  */
813
803
  _fireBroadcastRegionEnd() {
814
- try {
815
- (this._onBroadcastRegionEnd)?.();
816
- }
817
- catch (err) {
818
- this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${getErrorMessage(err)}`, 'warn');
819
- }
820
804
  const listeners = this._onBroadcastRegionEndListeners;
821
805
  if (Array.isArray(listeners)) {
822
806
  for (const listener of listeners) {
@@ -830,9 +814,8 @@ class OrderManager {
830
814
  }
831
815
  }
832
816
  /**
833
- * Register an additional broadcast-region-end listener without displacing
834
- * the legacy single listener or previously registered ones. Duplicate
835
- * registrations of the same function reference are ignored.
817
+ * Register a broadcast-region-end listener. Duplicate registrations of the
818
+ * same function reference are ignored.
836
819
  * @param {() => void} listener
837
820
  * @returns {void}
838
821
  */
@@ -846,6 +846,32 @@ async function _batchCancelCorrections(manager, entries, accountName, privateKey
846
846
  }
847
847
  return { corrected, failed, unresolved };
848
848
  }
849
+ /**
850
+ * Read a numeric fillProcessing setting: bot config override first, then the
851
+ * frozen default, then an optional extra default. Returns null when the raw
852
+ * value is absent/non-finite or fails the minimum bound, so callers keep their
853
+ * own fallback and rounding policy. Shared by the correction backlog resolvers
854
+ * below (see resolveCorrectionHoldBudget et al.).
855
+ * @param {unknown} manager
856
+ * @param {string} key - fillProcessing key
857
+ * @param {Object} [options]
858
+ * @param {unknown} [options.extraDefault] - Third-level default (rare)
859
+ * @param {number} [options.min=0] - Minimum accepted value
860
+ * @param {boolean} [options.exclusive=false] - Require value strictly > min
861
+ * @returns {number|null}
862
+ */
863
+ function readFillProcessingNumber(manager, key, options = {}) {
864
+ const { extraDefault, min = 0, exclusive = false } = options;
865
+ const raw = manager?.config?.fillProcessing?.[key]
866
+ ?? FILL_PROCESSING?.[key]
867
+ ?? extraDefault;
868
+ if (raw == null)
869
+ return null;
870
+ const n = Number(raw);
871
+ if (!Number.isFinite(n))
872
+ return null;
873
+ return exclusive ? (n > min ? n : null) : (n >= min ? n : null);
874
+ }
849
875
  /**
850
876
  * Resolve the wall-clock budget for the sequential price-update drain in
851
877
  * correctAllPriceMismatches. Cancel-class entries are never budgeted; only
@@ -857,12 +883,8 @@ async function _batchCancelCorrections(manager, entries, accountName, privateKey
857
883
  * @returns {number} Positive hold budget in milliseconds
858
884
  */
859
885
  function resolveCorrectionHoldBudget(manager) {
860
- const raw = manager?.config?.fillProcessing?.CORRECTION_LOCK_HOLD_BUDGET_MS
861
- ?? FILL_PROCESSING?.CORRECTION_LOCK_HOLD_BUDGET_MS;
862
- const n = Number(raw);
863
- if (Number.isFinite(n) && n > 0)
864
- return Math.floor(n);
865
- return 4000;
886
+ const n = readFillProcessingNumber(manager, 'CORRECTION_LOCK_HOLD_BUDGET_MS', { exclusive: true });
887
+ return n === null ? 4000 : Math.floor(n);
866
888
  }
867
889
  /**
868
890
  * Resolve the optional hard cap on price updates drained per cycle. Layered
@@ -873,14 +895,8 @@ function resolveCorrectionHoldBudget(manager) {
873
895
  * @returns {number} Finite cap, or Infinity when uncapped
874
896
  */
875
897
  function resolveCorrectionMaxUpdates(manager) {
876
- const raw = manager?.config?.fillProcessing?.CORRECTION_MAX_UPDATES_PER_CYCLE
877
- ?? FILL_PROCESSING?.CORRECTION_MAX_UPDATES_PER_CYCLE;
878
- if (raw == null)
879
- return Infinity;
880
- const n = Number(raw);
881
- if (Number.isFinite(n) && n >= 0)
882
- return Math.floor(n);
883
- return Infinity;
898
+ const n = readFillProcessingNumber(manager, 'CORRECTION_MAX_UPDATES_PER_CYCLE');
899
+ return n === null ? Infinity : Math.floor(n);
884
900
  }
885
901
  /**
886
902
  * Resolve the inter-op delay between successive correction broadcasts.
@@ -891,14 +907,8 @@ function resolveCorrectionMaxUpdates(manager) {
891
907
  * @returns {number} Non-negative delay in milliseconds
892
908
  */
893
909
  function resolveCorrectionInterOpDelayMs(manager) {
894
- const raw = manager?.config?.fillProcessing?.CORRECTION_INTER_OP_DELAY_MS
895
- ?? FILL_PROCESSING?.CORRECTION_INTER_OP_DELAY_MS;
896
- if (raw != null) {
897
- const n = Number(raw);
898
- if (Number.isFinite(n) && n >= 0)
899
- return Math.floor(n);
900
- }
901
- return TIMING.SYNC_DELAY_MS;
910
+ const n = readFillProcessingNumber(manager, 'CORRECTION_INTER_OP_DELAY_MS');
911
+ return n === null ? TIMING.SYNC_DELAY_MS : Math.floor(n);
902
912
  }
903
913
  /**
904
914
  * Resolve the correction-backlog warn threshold (see
@@ -907,12 +917,8 @@ function resolveCorrectionInterOpDelayMs(manager) {
907
917
  * @returns {number}
908
918
  */
909
919
  function resolveCorrectionWarnThreshold(manager) {
910
- const raw = manager?.config?.fillProcessing?.CORRECTION_QUEUE_WARN_THRESHOLD
911
- ?? FILL_PROCESSING?.CORRECTION_QUEUE_WARN_THRESHOLD;
912
- const n = Number(raw);
913
- if (Number.isFinite(n) && n > 0)
914
- return Math.floor(n);
915
- return 0;
920
+ const n = readFillProcessingNumber(manager, 'CORRECTION_QUEUE_WARN_THRESHOLD', { exclusive: true });
921
+ return n === null ? 0 : Math.floor(n);
916
922
  }
917
923
  /**
918
924
  * Resolve the correction-backlog warn rate-limit window.
@@ -920,13 +926,11 @@ function resolveCorrectionWarnThreshold(manager) {
920
926
  * @returns {number}
921
927
  */
922
928
  function resolveCorrectionWarnRateLimitMs(manager) {
923
- const raw = manager?.config?.fillProcessing?.CORRECTION_QUEUE_WARN_RATE_LIMIT_MS
924
- ?? FILL_PROCESSING?.CORRECTION_QUEUE_WARN_RATE_LIMIT_MS
925
- ?? TIMING?.STALE_TOTALS_WARN_RATE_LIMIT_MS;
926
- const n = Number(raw);
927
- if (Number.isFinite(n) && n > 0)
928
- return n;
929
- return 5 * 60 * 1000;
929
+ const n = readFillProcessingNumber(manager, 'CORRECTION_QUEUE_WARN_RATE_LIMIT_MS', {
930
+ extraDefault: TIMING?.STALE_TOTALS_WARN_RATE_LIMIT_MS,
931
+ exclusive: true,
932
+ });
933
+ return n === null ? 5 * 60 * 1000 : n;
930
934
  }
931
935
  /**
932
936
  * Correct all pending price mismatches atomically.