dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -5,14 +5,16 @@ import { dirname as _esmDirname } from 'node:path';
5
5
  const __filename = fileURLToPath(import.meta.url);
6
6
  const __dirname = _esmDirname(__filename);
7
7
  const require = createRequire(import.meta.url);
8
+ import { lazyShim } from './lazy_shim.js';
8
9
  import fs from 'node:fs';
9
10
  import { spawn } from 'node:child_process';
10
- import { nowIso } from './order/utils/system.js';
11
+ import { nowIso, fireStructuralResync } from './order/utils/system.js';
11
12
  import { path } from './path_api.js';
12
13
  import * as chainOrders from './chain_orders.js';
13
14
  import * as grid from './order/grid.js';
14
15
  import { ORDER_STATES, ORDER_TYPES, TIMING, BTS_PRECISION, NATIVE_CLIENT } from './constants.js';
15
16
  import { BOT_LIVE_CONFIG_KEYS } from './runtime_settings.js';
17
+ import { migrateLegacyOrderKeys } from './bot_defaults.js';
16
18
  import { acquireIfNotHeld } from './order/async_lock.js';
17
19
  const { readOpenOrdersGuarded } = chainOrders;
18
20
  import { PATHS } from './paths.js';
@@ -29,48 +31,48 @@ const { Config } = configModule;
29
31
  import { getErrorMessage } from './utils/errors.js';
30
32
  import { isSameBotName } from './utils/sanitize_key.js';
31
33
  import { usesAmaGridPrice } from './grid_price_source.js';
32
- function hasOpenOrdersSyncLoopMsSet(...args) { return require('./config').hasOpenOrdersSyncLoopMsSet(...args); }
33
- function getOpenOrdersSyncLoopMs(...args) { return require('./config').getOpenOrdersSyncLoopMs(...args); }
34
+ const hasOpenOrdersSyncLoopMsSet = lazyShim('./config', 'hasOpenOrdersSyncLoopMsSet');
35
+ const getOpenOrdersSyncLoopMs = lazyShim('./config', 'getOpenOrdersSyncLoopMs');
34
36
  function isGridBloated(...args) { return grid.isGridBloated(...args); }
35
37
  function isGridBloatGraceActive(...args) { return grid.isGridBloatGraceActive(...args); }
36
38
  function clearGridBloatFlag(...args) { return grid.clearGridBloatFlag(...args); }
37
39
  function recalculateGrid(...args) { return grid.recalculateGrid(...args); }
38
- function buildRuntimeScriptPath(...args) { return require('./launcher/runtime_entry').buildRuntimeScriptPath(...args); }
39
- function applyGridDivergenceCorrections(...args) { return require('./order/utils/system').applyGridDivergenceCorrections(...args); }
40
- function updateGridFromBlockchainSnapshot(...args) { return require('./order/grid').updateGridFromBlockchainSnapshot(...args); }
41
- function loadAmaCenterSnapshot(...args) { return require('./order/utils/system').loadAmaCenterSnapshot(...args); }
42
- function sleep(...args) { return require('./order/utils/system').sleep(...args); }
43
- function parseJsonWithComments(...args) { return require('./order/utils/system').parseJsonWithComments(...args); }
44
- function isPm2Runtime(...args) { return require('./order/logger').isPm2Runtime(...args); }
45
- function isWrapperAdapterOwner(...args) { return require('./launcher/adapter_requirement').isWrapperAdapterOwner(...args); }
46
- function readAdapterRequirement(...args) { return require('./launcher/adapter_requirement').readAdapterRequirement(...args); }
47
- function getSharedMarketAdapterRuntime(...args) { return require('./launcher/market_adapter_runtime').getSharedMarketAdapterRuntime(...args); }
48
- function resetMarketAdapterWhitelistCache(...args) { return require('./market_adapter_whitelist').resetMarketAdapterWhitelistCache(...args); }
49
- function isBotDynamicWeightWhitelisted(...args) { return require('./market_adapter_whitelist').isBotDynamicWeightWhitelisted(...args); }
40
+ const buildRuntimeScriptPath = lazyShim('./launcher/runtime_entry', 'buildRuntimeScriptPath');
41
+ const applyGridDivergenceCorrections = lazyShim('./order/utils/system', 'applyGridDivergenceCorrections');
42
+ const updateGridFromBlockchainSnapshot = lazyShim('./order/grid', 'updateGridFromBlockchainSnapshot');
43
+ const loadAmaCenterSnapshot = lazyShim('./order/utils/system', 'loadAmaCenterSnapshot');
44
+ const sleep = lazyShim('./order/utils/system', 'sleep');
45
+ const parseJsonWithComments = lazyShim('./order/utils/system', 'parseJsonWithComments');
46
+ const isPm2Runtime = lazyShim('./order/logger', 'isPm2Runtime');
47
+ const isWrapperAdapterOwner = lazyShim('./launcher/adapter_requirement', 'isWrapperAdapterOwner');
48
+ const readAdapterRequirement = lazyShim('./launcher/adapter_requirement', 'readAdapterRequirement');
49
+ const getSharedMarketAdapterRuntime = lazyShim('./launcher/market_adapter_runtime', 'getSharedMarketAdapterRuntime');
50
+ const resetMarketAdapterWhitelistCache = lazyShim('./market_adapter_whitelist', 'resetMarketAdapterWhitelistCache');
51
+ const isBotDynamicWeightWhitelisted = lazyShim('./market_adapter_whitelist', 'isBotDynamicWeightWhitelisted');
50
52
  function getRuntimeSettingsKeys() { return require('./runtime_settings').RUNTIME_SETTINGS_KEYS; }
51
- function cloneWeightDistribution(...args) { return require('./order/utils/math').cloneWeightDistribution(...args); }
52
- function calculateOrderCreationFees(...args) { return require('./order/utils/math').calculateOrderCreationFees(...args); }
53
- function calculateSwapInAmount(...args) { return require('./order/utils/math').calculateSwapInAmount(...args); }
54
- function floatToBlockchainInt(...args) { return require('./order/utils/math').floatToBlockchainInt(...args); }
55
- function blockchainToFloat(...args) { return require('./order/utils/math').blockchainToFloat(...args); }
56
- function updateDynamicGridSnapshotSync(...args) { return require('../market_adapter/utils/dynamic_grid_snapshot').updateDynamicGridSnapshotSync(...args); }
53
+ const cloneWeightDistribution = lazyShim('./order/utils/math', 'cloneWeightDistribution');
54
+ const calculateOrderCreationFees = lazyShim('./order/utils/math', 'calculateOrderCreationFees');
55
+ const calculateSwapInAmount = lazyShim('./order/utils/math', 'calculateSwapInAmount');
56
+ const floatToBlockchainInt = lazyShim('./order/utils/math', 'floatToBlockchainInt');
57
+ const blockchainToFloat = lazyShim('./order/utils/math', 'blockchainToFloat');
58
+ const updateDynamicGridSnapshotSync = lazyShim('../market_adapter/utils/dynamic_grid_snapshot', 'updateDynamicGridSnapshotSync');
57
59
  // Lazy require: dexbot_fill_runtime imports this module, so a static import
58
60
  // would be circular; at call time both modules are fully loaded.
59
- function scheduleFillConsumerRestartFn(...args) { return require('./dexbot_fill_runtime').scheduleFillConsumerRestart(...args); }
60
- function reconcileGridOrders(...args) { return require('./order/grid_reconcile').reconcileGridOrders(...args); }
61
- function resolveReserveCount(...args) { return require('./order/utils/order').resolveReserveCount(...args); }
62
- function reserveEdgeIdSet(...args) { return require('./order/utils/order').reserveEdgeIdSet(...args); }
63
- function liveWindowIdSet(...args) { return require('./order/utils/order').liveWindowIdSet(...args); }
64
- function resolveLiveReserveEdgeAnchorPrice(...args) { return require('./order/utils/order').resolveLiveReserveEdgeAnchorPrice(...args); }
65
- function formatUnmatchedChainOrder(...args) { return require('./order/utils/order').formatUnmatchedChainOrder(...args); }
66
- function isNonBlockingUnmatchedOrder(...args) { return require('./order/utils/order').isNonBlockingUnmatchedOrder(...args); }
67
- function isStrandedHoldOrder(...args) { return require('./order/utils/order').isStrandedHoldOrder(...args); }
68
- function getSideBudget(...args) { return require('./order/utils/order').getSideBudget(...args); }
69
- function getActiveOrdersTotal(config) { return require('./order/utils/order').getActiveOrdersTotal(config); }
70
- function correctAllPriceMismatches(...args) { return require('./order/utils/order').correctAllPriceMismatches(...args); }
71
- function isOrderOnChain(...args) { return require('./order/utils/order').isOrderOnChain(...args); }
72
- function parseChainOrder(...args) { return require('./order/utils/order').parseChainOrder(...args); }
73
- function parseSlotIndex(...args) { return require('./order/utils/order').parseSlotIndex(...args); }
61
+ const scheduleFillConsumerRestartFn = lazyShim('./dexbot_fill_runtime', 'scheduleFillConsumerRestart');
62
+ const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
63
+ const resolveEdgeCount = lazyShim('./order/utils/order', 'resolveEdgeCount');
64
+ const edgeOrderIdSet = lazyShim('./order/utils/order', 'edgeOrderIdSet');
65
+ const liveWindowIdSet = lazyShim('./order/utils/order', 'liveWindowIdSet');
66
+ const resolveLiveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveEdgeAnchorPrice');
67
+ const formatUnmatchedChainOrder = lazyShim('./order/utils/order', 'formatUnmatchedChainOrder');
68
+ const isNonBlockingUnmatchedOrder = lazyShim('./order/utils/order', 'isNonBlockingUnmatchedOrder');
69
+ const isStrandedHoldOrder = lazyShim('./order/utils/order', 'isStrandedHoldOrder');
70
+ const getSideBudget = lazyShim('./order/utils/order', 'getSideBudget');
71
+ function getCoreOrdersTotal(config) { return require('./order/utils/order').getCoreOrdersTotal(config); }
72
+ const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
73
+ const isOrderOnChain = lazyShim('./order/utils/order', 'isOrderOnChain');
74
+ const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
75
+ const parseSlotIndex = lazyShim('./order/utils/order', 'parseSlotIndex');
74
76
  const CODE_ROOT = path.join(__dirname, '..');
75
77
  const PROFILES_DIR = PATHS.PROFILES_DIR;
76
78
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
@@ -206,7 +208,10 @@ function normalizeBotEntryForFingerprint(entry) {
206
208
  continue;
207
209
  out[key] = e[key];
208
210
  }
209
- return out;
211
+ // Canonicalize legacy order-count keys so the fingerprint and the merged
212
+ // entry agree with the allowlist (`coreOrders`/`edgeOrders`) even when the
213
+ // on-disk bots.json still carries `activeOrders`/`reserveOrders`.
214
+ return migrateLegacyOrderKeys(out);
210
215
  }
211
216
  /**
212
217
  * Build the full-entry fingerprint for one bot (stable across key order and
@@ -252,7 +257,7 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
252
257
  const applied = [];
253
258
  if (!bot?.config || !entry || typeof entry !== 'object')
254
259
  return applied;
255
- const e = entry;
260
+ const e = migrateLegacyOrderKeys({ ...entry });
256
261
  for (const key of keys) {
257
262
  // A deleted key applies as null (mirrors the former ?? null diff
258
263
  // semantics) so the running config can never keep a stale value.
@@ -283,7 +288,7 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
283
288
  function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabel) {
284
289
  const oldKey = bot.config.botKey;
285
290
  const oldIndex = bot.config.botIndex;
286
- const u = updatedBot;
291
+ const u = migrateLegacyOrderKeys({ ...updatedBot });
287
292
  // Preserve runtime-only properties set by the constructor
288
293
  // (timing, gridLimits, feeParams, etc.) that are not present
289
294
  // in the raw profile from bots.json.
@@ -545,50 +550,50 @@ function countLiveGridOrders(manager, type) {
545
550
  const active = manager.getOrdersByTypeAndState?.(type, ORDER_STATES.ACTIVE) || [];
546
551
  const partial = manager.getOrdersByTypeAndState?.(type, ORDER_STATES.PARTIAL) || [];
547
552
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
548
- // deep-*) sit outside window accounting — same gate as reserve
553
+ // deep-*) sit outside window accounting — same gate as edge
549
554
  // classification and startup cancel candidates (issue #27 follow-up).
550
- // Without this, a live shelf inflates the live window+reserves count and
551
- // masks a real window/reserve shortfall, so targeted sync never fires.
555
+ // Without this, a live shelf inflates the live window+edges count and
556
+ // masks a real window/edge shortfall, so targeted sync never fires.
552
557
  // No-op on grids that only mint slot-N ids.
553
558
  return active.concat(partial).filter((o) => o?.orderId && parseSlotIndex(o?.id) !== null).length;
554
559
  }
555
- function getTargetActiveOrders(config, side) {
556
- const configured = Number(config?.activeOrders?.[side]);
557
- // Reserve ladder rests live on-chain: countLiveGridOrders sees window +
558
- // edge orders, so the shortfall target must include reserves too —
559
- // otherwise live reserves mask window shortfalls and a filled/cancelled
560
- // reserve order never triggers targeted reconciliation.
561
- const reserves = resolveReserveCount(config, side);
562
- return Math.max(0, Number.isFinite(configured) ? configured : 1) + reserves;
560
+ function getTargetCoreOrders(config, side) {
561
+ const configured = Number(config?.coreOrders?.[side]);
562
+ // Edge ladder rests live on-chain: countLiveGridOrders sees window +
563
+ // edge orders, so the shortfall target must include edge orders too —
564
+ // otherwise live edge orders mask window shortfalls and a filled/cancelled
565
+ // edge order never triggers targeted reconciliation.
566
+ const edgeCount = resolveEdgeCount(config, side);
567
+ return Math.max(0, Number.isFinite(configured) ? configured : 1) + edgeCount;
563
568
  }
564
569
  /**
565
- * Count live on-chain reserve orders for one side (issue #27 follow-up).
570
+ * Count live on-chain edge orders for one side (issue #27 follow-up).
566
571
  *
567
- * The window shortfall check above compares live window+reserves against
568
- * window+reserves, so a pre-existing window surplus masks a reserve deficit
569
- * (e.g. target 6+2=8 vs 12 live after reserveOrders 0→2: no shortfall, no
570
- * sync, zero reserve placements). Reserves get their own independent reason
571
- * below — the mirror of the masking case getTargetActiveOrders handles.
572
+ * The window shortfall check above compares live window+edges against
573
+ * window+edges, so a pre-existing window surplus masks an edge deficit
574
+ * (e.g. target 6+2=8 vs 12 live after edgeOrders 0→2: no shortfall, no
575
+ * sync, zero edge placements). Edge orders get their own independent reason
576
+ * below — the mirror of the masking case getTargetCoreOrders handles.
572
577
  *
573
- * Classification reuses the single source of truth (reserveEdgeIdSet +
574
- * resolveLiveReserveEdgeAnchorPrice, same anchor the placement pickers use)
578
+ * Classification reuses the single source of truth (edgeOrderIdSet +
579
+ * resolveLiveEdgeAnchorPrice, same anchor the placement pickers use)
575
580
  * over the full master grid, intersected with live ACTIVE/PARTIAL orderIds
576
581
  * (same live definition as countLiveGridOrders). The edge pick excludes the
577
582
  * window (liveWindowIdSet — the same exclusion every placement picker
578
583
  * applies): window + edge are additive in targets/fees/hold-back, but
579
584
  * without the exclusion a window that reaches the grid edge (keep-low
580
585
  * window = bottom slots = floor edge) makes the edge pick land on window
581
- * members and the count reads N/N with zero dedicated reserves, so the
586
+ * members and the count reads N/N with zero dedicated edge orders, so the
582
587
  * deficit never fires (issue #27 follow-up).
583
588
  * @param {unknown} manager - OrderManager
584
- * @param {unknown} config - Bot configuration (reserve count source)
589
+ * @param {unknown} config - Bot configuration (edge count source)
585
590
  * @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
586
- * @returns {number|null} Live reserve count, or null when unclassifiable
591
+ * @returns {number|null} Live edge count, or null when unclassifiable
587
592
  */
588
- function countLiveReserveOrders(manager, config, type) {
593
+ function countLiveEdgeOrders(manager, config, type) {
589
594
  try {
590
595
  const side = type === ORDER_TYPES.SELL ? 'sell' : 'buy';
591
- const required = resolveReserveCount(config, side);
596
+ const required = resolveEdgeCount(config, side);
592
597
  if (!(required > 0))
593
598
  return 0;
594
599
  if (!manager)
@@ -601,13 +606,13 @@ function countLiveReserveOrders(manager, config, type) {
601
606
  const allSlots = Array.from(manager.orders.values());
602
607
  if (allSlots.length === 0)
603
608
  return null;
604
- const anchor = resolveLiveReserveEdgeAnchorPrice(manager, side);
609
+ const anchor = resolveLiveEdgeAnchorPrice(manager, side);
605
610
  // Fail open on unknown window geometry (null): without a boundary the
606
- // pickers cannot place reserves either, so keep the previous
611
+ // pickers cannot place edge orders either, so keep the previous
607
612
  // (exclusion-free) classification instead of guessing.
608
613
  const windowIds = liveWindowIdSet(manager, type);
609
- const reserveIds = reserveEdgeIdSet(allSlots, config, type, anchor, windowIds);
610
- if (!reserveIds || reserveIds.size === 0)
614
+ const edgeIds = edgeOrderIdSet(allSlots, config, type, anchor, windowIds);
615
+ if (!edgeIds || edgeIds.size === 0)
611
616
  return 0;
612
617
  const liveIds = new Set();
613
618
  if (typeof manager.getOrdersByTypeAndState === 'function') {
@@ -625,7 +630,7 @@ function countLiveReserveOrders(manager, config, type) {
625
630
  }
626
631
  }
627
632
  let live = 0;
628
- for (const id of reserveIds) {
633
+ for (const id of edgeIds) {
629
634
  if (liveIds.has(String(id)))
630
635
  live++;
631
636
  }
@@ -643,7 +648,7 @@ function _hasBudgetForSide(manager, config, side) {
643
648
  const allocated = side === 'buy' ? (funds.allocatedBuy || 0) : (funds.allocatedSell || 0);
644
649
  if (allocated <= 0)
645
650
  return false;
646
- const totalTarget = getActiveOrdersTotal(config);
651
+ const totalTarget = getCoreOrdersTotal(config);
647
652
  const budget = getSideBudget(side, funds, config, totalTarget);
648
653
  return budget > 0;
649
654
  }
@@ -651,11 +656,30 @@ function _hasBudgetForSide(manager, config, side) {
651
656
  return true;
652
657
  }
653
658
  }
659
+ /**
660
+ * Mirror a spread-check stall into the flags the targeted-sync gate reads.
661
+ *
662
+ * ANY stall — fund, batch, or structural — arms the refresh. When the
663
+ * correction cannot act on the local snapshot, that snapshot may simply be
664
+ * stale relative to the chain: a missed fill leaves an ACTIVE slot occupying
665
+ * the window edge, so `isSlotAvailable` hides every tightening slot and the
666
+ * check reports 'no-candidates' even though real geometry exists. A refresh is
667
+ * the only way to tell a genuinely structural stall from a stale one, so we
668
+ * sync rather than wait for the out-of-spread staleness watchdog to re-center.
669
+ * The stall cause is kept alongside the flag so the log states the truth.
670
+ * Exported for tests.
671
+ * @param {BotLike} bot
672
+ * @param {SpreadCorrectionStall|null|undefined} stall
673
+ */
674
+ export function mirrorSpreadStall(bot, stall) {
675
+ bot._spreadCorrectionStall = stall ?? null;
676
+ bot._spreadFundsExhausted = stall != null;
677
+ }
654
678
  function getTargetedSyncReason(bot) {
655
679
  if (!bot.manager || bot.config?.dryRun)
656
680
  return null;
657
- const targetBuy = getTargetActiveOrders(bot.config, 'buy');
658
- const targetSell = getTargetActiveOrders(bot.config, 'sell');
681
+ const targetBuy = getTargetCoreOrders(bot.config, 'buy');
682
+ const targetSell = getTargetCoreOrders(bot.config, 'sell');
659
683
  const liveBuy = countLiveGridOrders(bot.manager, ORDER_TYPES.BUY);
660
684
  const liveSell = countLiveGridOrders(bot.manager, ORDER_TYPES.SELL);
661
685
  const shortfalls = [];
@@ -669,18 +693,18 @@ function getTargetedSyncReason(bot) {
669
693
  shortfalls.push(`sell ${liveSell}/${targetSell}`);
670
694
  }
671
695
  }
672
- // Reserve deficit is independent of window surplus: a bot carrying extra
673
- // rail/stranded orders can sit above target while its reserve edge is
674
- // empty (live-applied reserveOrders 0→N, filled/cancelled reserve).
696
+ // Edge deficit is independent of window surplus: a bot carrying extra
697
+ // rail/stranded orders can sit above target while its edge order is
698
+ // empty (live-applied edgeOrders 0→N, filled/cancelled edge order).
675
699
  // Without this, placement waits for fills or the 4h fetch (issue #27).
676
700
  for (const [type, side] of [[ORDER_TYPES.BUY, 'buy'], [ORDER_TYPES.SELL, 'sell']]) {
677
- const required = resolveReserveCount(bot.config, side);
701
+ const required = resolveEdgeCount(bot.config, side);
678
702
  if (!(required > 0))
679
703
  continue;
680
- const liveReserves = countLiveReserveOrders(bot.manager, bot.config, type);
681
- if (liveReserves !== null && liveReserves < required) {
704
+ const liveEdges = countLiveEdgeOrders(bot.manager, bot.config, type);
705
+ if (liveEdges !== null && liveEdges < required) {
682
706
  if (_hasBudgetForSide(bot.manager, bot.config, side)) {
683
- shortfalls.push(`${side} reserves ${liveReserves}/${required}`);
707
+ shortfalls.push(`${side} edges ${liveEdges}/${required}`);
684
708
  }
685
709
  }
686
710
  }
@@ -688,14 +712,18 @@ function getTargetedSyncReason(bot) {
688
712
  if (drift && drift.isValid === false) {
689
713
  return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
690
714
  }
691
- // Spread correction placed no effective orders: either it found no free
692
- // funds on either side, or the prepared batch did not execute. The balances
693
- // or holds may simply be a stale snapshot (the grid does not lose funds, it
694
- // holds them in resting/virtual slots), so the only fallback is to refresh
695
- // account totals + open orders and let the next correction cycle re-check.
715
+ // Spread correction placed no effective order for ANY cause. The local
716
+ // snapshot the check reasoned over may be stale relative to the chain —
717
+ // balances/holds can be a stale read (the grid does not lose funds, it
718
+ // holds them in resting/virtual slots), and a missed fill can leave an
719
+ // ACTIVE slot occupying the window edge so no tightening slot appears to
720
+ // exist ('no-candidates'). Only a chain sync can tell a genuinely
721
+ // structural stall from a stale one, so arm the refresh for every cause
722
+ // instead of waiting up to SPREAD_STALE_ESCALATE_MS for the watchdog.
696
723
  // Never recycle resting inventory.
697
724
  if (bot._spreadFundsExhausted === true) {
698
- return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
725
+ const cause = bot._spreadCorrectionStall || 'funds-exhausted';
726
+ return { reason: `spread correction stalled (${cause})`, targetBuy, targetSell, liveBuy, liveSell, drift };
699
727
  }
700
728
  if (shortfalls.length > 0) {
701
729
  return { reason: `active order shortfall: ${shortfalls.join(', ')}`, targetBuy, targetSell, liveBuy, liveSell, drift };
@@ -737,6 +765,9 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
737
765
  // tick (subject to the cooldown below).
738
766
  if (bot._spreadFundsExhausted === true)
739
767
  bot._spreadFundsExhausted = false;
768
+ // Clear the companion cause with the flag so the two never drift apart
769
+ // (a leftover cause would mislabel the next tick's reason).
770
+ bot._spreadCorrectionStall = null;
740
771
  const remaining = getTargetedSyncReason(bot);
741
772
  const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
742
773
  if (remaining || unmatchedCount > 0) {
@@ -1654,19 +1685,11 @@ function considerDeferredHoldEscalation(bot, strandedOrders, strandedMs) {
1654
1685
  `requesting structural resync to resolve the hold (reconcile is update-first, ` +
1655
1686
  `so funds are released by price-updating onto rail slots) — ` +
1656
1687
  `${describeDeferredHolds(bot, strandedOrders)}`, 'error');
1657
- try {
1658
- const res = bot.manager.requestStructuralGridResync('deferred-hold-stale', {
1659
- reason: `${held} deferred chain order(s) held unchanged for ~${heldHours}h`,
1660
- heldCount: held,
1661
- heldMs,
1662
- });
1663
- res?.catch?.((err) => {
1664
- bot.manager?.logger?.log?.(`[HOLD] Structural resync for stale hold failed: ${getErrorMessage(err)}`, 'error');
1665
- });
1666
- }
1667
- catch (err) {
1668
- bot.manager?.logger?.log?.(`[HOLD] Structural resync for stale hold failed: ${getErrorMessage(err)}`, 'error');
1669
- }
1688
+ fireStructuralResync(bot, 'deferred-hold-stale', {
1689
+ reason: `${held} deferred chain order(s) held unchanged for ~${heldHours}h`,
1690
+ heldCount: held,
1691
+ heldMs,
1692
+ }, '[HOLD] Structural resync for stale hold failed');
1670
1693
  }
1671
1694
  /**
1672
1695
  * Render the per-order detail for a deferred-hold summary: side, price, size,
@@ -2464,10 +2487,13 @@ async function executeMaintenanceLogic(bot, context) {
2464
2487
  const spreadResult = await bot.manager.checkSpreadCondition(BitShares, bot.updateOrdersOnChainPlan.bind(bot));
2465
2488
  if (await bot._abortFlowIfIllegalState(`${context} spread check`))
2466
2489
  return;
2467
- // Mirror the check result so the next tick's targeted-sync gate
2468
- // (getTargetedSyncReason) refreshes funds/open orders when the
2469
- // correction could not find any free funds.
2470
- bot._spreadFundsExhausted = spreadResult?.fundsExhausted === true;
2490
+ // Mirror the stall cause and arm the targeted-sync refresh for
2491
+ // every cause. The check can report 'no-candidates' on a stale
2492
+ // local snapshot (a missed fill leaves an ACTIVE slot hiding the
2493
+ // tightening slot), so the refresh must fire here too rather than
2494
+ // wait for trackOutOfSpreadStaleness to re-center. The stall cause
2495
+ // is kept so the next tick's reason names the truth.
2496
+ mirrorSpreadStall(bot, spreadResult?.stall ?? null);
2471
2497
  const spreadPlaced = Number(spreadResult?.ordersPlaced) || 0;
2472
2498
  if (spreadPlaced > 0) {
2473
2499
  bot._log(`✓ Spread correction during ${context}: ${spreadResult.ordersPlaced} order(s) placed`);
@@ -2550,17 +2576,9 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2550
2576
  bot._lastSpreadStaleResyncAt = now;
2551
2577
  bot._log(`[SPREAD-STALE] Spread out of tolerance for ${staleMin}min despite corrections; ` +
2552
2578
  `requesting structural re-center`, 'warn');
2553
- try {
2554
- const res = bot.manager.requestStructuralGridResync('spread-stale-persistent', {
2555
- reason: `Spread out of tolerance for ${staleMin}min with no effective correction (outOfSpread=${outOfSpread})`
2556
- });
2557
- res?.catch?.((err) => {
2558
- bot.manager?.logger?.log?.(`[SPREAD-STALE] Structural re-center request failed: ${getErrorMessage(err)}`, 'error');
2559
- });
2560
- }
2561
- catch (err) {
2562
- bot.manager?.logger?.log?.(`[SPREAD-STALE] Structural re-center request failed: ${getErrorMessage(err)}`, 'error');
2563
- }
2579
+ fireStructuralResync(bot, 'spread-stale-persistent', {
2580
+ reason: `Spread out of tolerance for ${staleMin}min with no effective correction (outOfSpread=${outOfSpread})`
2581
+ }, '[SPREAD-STALE] Structural re-center request failed');
2564
2582
  return { staleMs, escalated: true };
2565
2583
  }
2566
2584
  }
@@ -2744,7 +2762,7 @@ async function checkBtsBalanceAndAcquire(bot) {
2744
2762
  return;
2745
2763
  if (!bot.manager || !bot.manager.btsBalance)
2746
2764
  return;
2747
- const totalTarget = getActiveOrdersTotal(bot.config);
2765
+ const totalTarget = getCoreOrdersTotal(bot.config);
2748
2766
  const btsReservationMultiplier = bot.config?.feeParams?.BTS_RESERVATION_MULTIPLIER;
2749
2767
  const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
2750
2768
  if (minBtsVal <= 0)
@@ -3157,6 +3175,11 @@ function getMetrics(bot) {
3157
3175
  const heldUnmatched = unmatched.filter((u) => isNonBlockingUnmatchedOrder(u));
3158
3176
  return {
3159
3177
  ...bot._metrics,
3178
+ // The boundary-drift counter is written by the strategy engine on the
3179
+ // MANAGER's metrics object (calculateTargetGrid has no bot reference),
3180
+ // so overlay it here — otherwise the P2 signal is counted but never
3181
+ // surfaced by getMetrics().
3182
+ boundaryDriftExceedsWindowCount: bot.manager?._metrics?.boundaryDriftExceedsWindowCount ?? bot._metrics.boundaryDriftExceedsWindowCount,
3160
3183
  queueDepth: bot._incomingFillQueue.length,
3161
3184
  fillProcessingLockActive: bot.manager?._fillProcessingLock?.isLocked() || false,
3162
3185
  divergenceLockActive: bot.manager?._divergenceLock?.isLocked() || false,
@@ -3240,15 +3263,10 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3240
3263
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3241
3264
  }
3242
3265
  }
3243
- export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3266
+ export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveEdgeOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3244
3267
  export default {
3245
- loadBotsConfigSnapshot,
3246
- isWrapperAdapterOwner,
3247
- checkAndApplyBotConfigChanges,
3248
- buildBotConfigFingerprint,
3249
3268
  refreshDynamicWeightDistribution,
3250
3269
  performGridResync,
3251
- updateBotGridResetMetadata,
3252
3270
  handlePendingTriggerReset,
3253
3271
  setupTriggerFileDetection,
3254
3272
  performPeriodicGridChecks,
@@ -3260,21 +3278,9 @@ export default {
3260
3278
  setupBotsConfigPollInterval,
3261
3279
  stopBotsConfigPollInterval,
3262
3280
  executeMaintenanceLogic,
3263
- getTargetedSyncReason,
3264
- countLiveReserveOrders,
3265
- maybeRunTargetedDriftReconciliation,
3266
3281
  cancelDustOrders,
3267
- isOrderDoesNotExistError,
3268
3282
  runGridMaintenance,
3269
- trackOutOfSpreadStaleness,
3270
- stopMarketAdapterPm2,
3271
3283
  releaseMarketAdapterRuntime,
3272
- syncMarketAdapterOnPeriodicConfigCheck,
3273
- findSnapshotBotForRuntimeConfig,
3274
- runtimeConfigNeedsMarketAdapter,
3275
- usesAmaGridPrice,
3276
- checkBtsBalanceAndAcquire,
3277
- acquireBts,
3278
3284
  runDustHealthCheck,
3279
3285
  setupDustHealthCheckInterval,
3280
3286
  requestGridReset,
@@ -3283,8 +3289,6 @@ export default {
3283
3289
  markGridActivity,
3284
3290
  getMetrics,
3285
3291
  syncOpenOrdersAndProcessFills,
3286
- shouldDeferMaintenanceForBroadcast,
3287
- checkGridLockHoldDuration,
3288
3292
  _internalDeferredHold: { logDeferredHoldSummary, describeDeferredHolds, considerDeferredHoldEscalation },
3289
3293
  };
3290
3294
  //# sourceMappingURL=dexbot_maintenance_runtime.js.map
@@ -1,4 +1,3 @@
1
- /** Startup runtime - bot initialization, grid placement, and startup sequence */
2
1
  import type { BotLike } from './types.js';
3
2
  /**
4
3
  * Initialize the startup state: account orders, manager, persisted data.
@@ -1,6 +1,5 @@
1
1
  /** Startup runtime - bot initialization, grid placement, and startup sequence */
2
- import { createRequire } from 'node:module';
3
- const require = createRequire(import.meta.url);
2
+ import { lazyShim } from './lazy_shim.js';
4
3
  import { path } from './path_api.js';
5
4
  import * as chainOrders from './chain_orders.js';
6
5
  import { readOpenOrdersGuarded } from './chain_orders.js';
@@ -14,21 +13,22 @@ import { BitShares, onReconnect as registerReconnectHook } from './bitshares_cli
14
13
  import orderModule from './order/index.js';
15
14
  import { getErrorMessage } from './utils/errors.js';
16
15
  import { processSweepOrphanFill } from './dexbot_fill_runtime.js';
16
+ import { restoreLastMarketFill } from './order/utils/system.js';
17
17
  import { ON_MISSING_GENESIS, recordMissingGenesisFault, resolvePersistedGenesis } from './order/genesis_policy.js';
18
18
  const { OrderManager, grid: Grid } = orderModule;
19
- function initializeFeeCache(...args) { return require('./order/utils/system').initializeFeeCache(...args); }
20
- function parseJsonWithComments(...args) { return require('./order/utils/system').parseJsonWithComments(...args); }
21
- function withBlockchainRetry(...args) { return require('./order/utils/system').withBlockchainRetry(...args); }
22
- function buildFillKey(...args) { return require('./order/utils/order').buildFillKey(...args); }
23
- function correctAllPriceMismatches(...args) { return require('./order/utils/order').correctAllPriceMismatches(...args); }
24
- function parseChainOrder(...args) { return require('./order/utils/order').parseChainOrder(...args); }
25
- function restoreGapEvacStreaks(...args) { return require('./order/utils/system').restoreGapEvacStreaks(...args); }
26
- function applyPersistedPendingCrawls(...args) { return require('./order/utils/system').applyPersistedPendingCrawls(...args); }
27
- function startupSleep(...args) { return require('./order/utils/system').sleep(...args); }
19
+ const initializeFeeCache = lazyShim('./order/utils/system', 'initializeFeeCache');
20
+ const parseJsonWithComments = lazyShim('./order/utils/system', 'parseJsonWithComments');
21
+ const withBlockchainRetry = lazyShim('./order/utils/system', 'withBlockchainRetry');
22
+ const buildFillKey = lazyShim('./order/utils/order', 'buildFillKey');
23
+ const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
24
+ const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
25
+ const restoreGapEvacStreaks = lazyShim('./order/utils/system', 'restoreGapEvacStreaks');
26
+ const applyPersistedPendingCrawls = lazyShim('./order/utils/system', 'applyPersistedPendingCrawls');
27
+ const startupSleep = lazyShim('./order/utils/system', 'sleep');
28
28
  const storage = getStorage();
29
- function attemptResumePersistedGridByPriceMatch(...args) { return require('./order/grid_reconcile').attemptResumePersistedGridByPriceMatch(...args); }
30
- function decideStartupGridAction(...args) { return require('./order/grid_reconcile').decideStartupGridAction(...args); }
31
- function reconcileGridOrders(...args) { return require('./order/grid_reconcile').reconcileGridOrders(...args); }
29
+ const attemptResumePersistedGridByPriceMatch = lazyShim('./order/grid_reconcile', 'attemptResumePersistedGridByPriceMatch');
30
+ const decideStartupGridAction = lazyShim('./order/grid_reconcile', 'decideStartupGridAction');
31
+ const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
32
32
  function botRetryLogger(bot) {
33
33
  return { log: (msg) => bot._log(msg) };
34
34
  }
@@ -210,6 +210,17 @@ async function startPostBootstrapSubsystems(bot) {
210
210
  async function finishStartupSequence(bot, startupState) {
211
211
  let { persistedGrid, persistedBtsFeesOwed, persistedBoundaryIdx, persistedBtsBalance, persistedRecentFillKeys, persistedGenesis, persistedGapEvacStreaks, } = startupState;
212
212
  try {
213
+ // Bot-scoped last-market-fill reference: restore BEFORE any chain
214
+ // touching/placement work so spread correction (including the
215
+ // post-reset path below) always has the last real trade price it must
216
+ // not cross. Independent of the boundary/genesis restore, so a
217
+ // regenerated grid still gets the anchor the genesis-bound pivot lost.
218
+ try {
219
+ restoreLastMarketFill(bot.manager, bot.manager?.accountOrders?.loadLastMarketFill?.() ?? null);
220
+ }
221
+ catch (marketRefErr) {
222
+ bot._warn(`[SPREAD-CORRECTION] Last-market-fill restore failed (${getErrorMessage(marketRefErr)}); spread correction runs without a market anchor`);
223
+ }
213
224
  if (typeof bot._fillsUnsubscribe === 'function') {
214
225
  await bot._fillsUnsubscribe().catch(() => { });
215
226
  }
@@ -591,6 +591,22 @@ async function rejectCorruptedGridSnapshot(bot, context) {
591
591
  `drift sell=${Number(driftCheck.driftSell ?? 0).toFixed(2)} buy=${Number(driftCheck.driftBuy ?? 0).toFixed(2)}. ` +
592
592
  `Deleting corrupted snapshot.`);
593
593
  if (bot.accountOrders && typeof bot.accountOrders.clearGrid === 'function') {
594
+ // Keep a timestamped copy before the destructive clear. Drift is not
595
+ // always corruption (genuine unadopted orphans, re-anchoring), so the
596
+ // pre-reject grid/boundary/pivot/crawls are the only forensics and the
597
+ // only path to manual recovery. AccountOrders owns the path/storage
598
+ // knowledge. Best-effort: the clear proceeds either way.
599
+ try {
600
+ const backupPath = typeof bot.accountOrders.backupSnapshot === 'function'
601
+ ? await bot.accountOrders.backupSnapshot('rejected-drift')
602
+ : null;
603
+ if (backupPath) {
604
+ bot._warn(`${tag} Kept pre-reject snapshot copy at ${backupPath}`);
605
+ }
606
+ }
607
+ catch (backupErr) {
608
+ bot._warn(`${tag} Failed to keep pre-reject snapshot copy: ${getErrorMessage(backupErr)}`);
609
+ }
594
610
  try {
595
611
  await bot.accountOrders.clearGrid();
596
612
  bot._warn(`${tag} Corrupted grid snapshot deleted.`);
@@ -10,7 +10,7 @@ declare const SETTINGS_FILE: string;
10
10
  * The on-disk general settings document. Open-ended (dynamic top-level
11
11
  * sections) but `NODES` is typed because several callers read it directly.
12
12
  */
13
- export interface GeneralSettingsDocument {
13
+ interface GeneralSettingsDocument {
14
14
  NODES?: {
15
15
  enabled?: boolean;
16
16
  list?: string[];