dexbot 1.6.11 → 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 (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -89,19 +89,32 @@
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
102
115
  * is the fallback. Used by compareGrids() and re-exported for the maintenance
103
116
  * runtime so the reset log always shows the level that actually fired.
104
- * @param {any} manager - OrderManager instance (may be null)
117
+ * @param {unknown} manager - OrderManager instance (may be null)
105
118
  * @returns {number} Threshold in percent (0 = disabled)
106
119
  */
107
120
  export function resolveRmsThresholdPct(manager) {
@@ -117,12 +130,13 @@ function _snapshotFundState(manager) {
117
130
  };
118
131
  }
119
132
  import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, priceSlotEqual, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
120
- import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveReserveCount, reserveEdgeIdSet, resolveLiveReserveEdgeAnchorPrice, liveWindowIdSet } from './utils/order.js';
133
+ import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveReserveCount, reserveEdgeIdSet, resolveLiveReserveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
121
134
  import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot } from './utils/system.js';
122
135
  import * as MathUtils from './utils/math.js';
123
136
  import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
124
137
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
125
138
  import { hasGenesisLadder, recordMissingGenesisFault, resolvePersistedGenesis } from './genesis_policy.js';
139
+ import { WorkingGrid } from './working_grid.js';
126
140
  import { getErrorMessage } from '../utils/errors.js';
127
141
  const calculateGapSlots = _mathGapSlots;
128
142
  export { calculateGapSlots };
@@ -301,11 +315,14 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
301
315
  * - n = ceil(ln(1.02) / ln(1.005)) = ceil(3.98) = 4 steps
302
316
  * - G = max(2, 4) = 4 slots
303
317
  *
304
- * @param {any} config - Grid configuration
305
- * @returns {any}
318
+ * @param {unknown} config - Grid configuration
319
+ * @returns {unknown}
306
320
  */
307
321
  export function createOrderGrid(config) {
308
- const { startPrice, minPrice, maxPrice, incrementPercent } = config;
322
+ const startPrice = Number(config.startPrice);
323
+ const minPrice = Number(config.minPrice);
324
+ const maxPrice = Number(config.maxPrice);
325
+ const incrementPercent = Number(config.incrementPercent);
309
326
  // FIX: Add comprehensive input validation to prevent silent grid creation failures
310
327
  if (!Number.isFinite(startPrice)) {
311
328
  throw new Error(`Invalid startPrice: ${startPrice}. Must be a finite number.`);
@@ -361,10 +378,6 @@ export function createOrderGrid(config) {
361
378
  //
362
379
  // STRATEGY: Center the spread gap around startPrice
363
380
  const boundaryIdx = calculateIdealBoundary(priceLevels.map((p) => ({ price: p })), startPrice, gapSlots);
364
- // ================================================================================
365
- // STEP 4: CREATE ORDER OBJECTS
366
- // ================================================================================
367
- // Convert price levels to order objects with assigned roles.
368
381
  const orders = priceLevels.map((price, i) => ({
369
382
  id: `slot-${i}`,
370
383
  price,
@@ -445,7 +458,8 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
445
458
  let genesis = null;
446
459
  const validationMode = (() => {
447
460
  try {
448
- const raw = (typeof process !== 'undefined' && process.env?.GRID_PRICE_SLOT_VALIDATION) || 'log';
461
+ const proc = globalThis.process;
462
+ const raw = proc?.env?.GRID_PRICE_SLOT_VALIDATION ?? 'log';
449
463
  return String(raw).toLowerCase() === 'enforce' ? 'enforce' : 'log';
450
464
  }
451
465
  catch {
@@ -667,7 +681,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
667
681
  // a row). Best-effort — load continues boundary-less
668
682
  // either way and the next fill batch re-anchors live.
669
683
  try {
670
- const acct = manager?.accountOrders;
684
+ const acct = manager.accountOrders;
671
685
  if (acct && typeof acct.clearPersistedBoundary === 'function') {
672
686
  await acct.clearPersistedBoundary();
673
687
  manager.logger?.log?.(`[GRID-LOAD] Erased poisoned persisted boundary (${boundaryIdx}); ` +
@@ -693,7 +707,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
693
707
  // same one-increment drift rule the runtime guard applies.
694
708
  if (restoredBoundary !== null) {
695
709
  try {
696
- restoreLastFillPivot(manager, manager?.accountOrders?.loadLastFillPivot?.() ?? null);
710
+ restoreLastFillPivot(manager, manager.accountOrders?.loadLastFillPivot?.() ?? null);
697
711
  }
698
712
  catch (pivotErr) {
699
713
  manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot restore failed (${getErrorMessage(pivotErr)}); book seed takes over`, 'warn');
@@ -784,7 +798,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
784
798
  // Gap 6: Grid size cap — validate grid slot count against expected maximum.
785
799
  // Formula: placedOrders (active+partial with orderId) + gapSlots + 1 tolerance slot.
786
800
  const bloatResult = isGridBloated(manager, grid);
787
- if (bloatResult.bloated) {
801
+ if (bloatResult.bloated && bloatResult.details) {
788
802
  const d = bloatResult.details;
789
803
  const grace = isGridBloatGraceActive(manager);
790
804
  if (grace.active) {
@@ -904,7 +918,7 @@ export async function initializeGrid(manager) {
904
918
  // the old `priceMode || 'auto'` read (priceMode is never set in
905
919
  // the runtime path) let a poolRef override startPrice:"book".
906
920
  const startPriceMode = resolveStartPriceMode(mpRaw, manager.config.priceMode || 'auto');
907
- const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA, manager.config.assetB, startPriceMode, manager.config.poolRef);
921
+ const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA ?? '', manager.config.assetB ?? '', startPriceMode, manager.config.poolRef);
908
922
  if (derived) {
909
923
  manager.logger?.log?.(`[DIAGNOSTIC] initializeGrid: Derived new startPrice=${derived.toFixed(8)} (mode=${startPriceMode})`, 'info');
910
924
  manager.config.startPrice = Number(derived);
@@ -930,7 +944,7 @@ export async function initializeGrid(manager) {
930
944
  let gp = mp;
931
945
  let gpSource = 'startPrice';
932
946
  let amaSnapshot = null;
933
- const whitelistFlags = getWhitelistFlags(manager.config.botKey);
947
+ const whitelistFlags = getWhitelistFlags(manager.config.botKey ?? '');
934
948
  const isGridRangeScalingWhitelisted = whitelistFlags.asymmetricBounds === true;
935
949
  let gridPriceOffsetPct = 0;
936
950
  const gpRaw = manager.config.gridPrice;
@@ -943,7 +957,7 @@ export async function initializeGrid(manager) {
943
957
  else if (gpMode === 'pool' || gpMode === 'book') {
944
958
  try {
945
959
  const { BitShares } = require('../bitshares_client');
946
- const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA, manager.config.assetB, gpMode, manager.config.poolRef);
960
+ const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA ?? '', manager.config.assetB ?? '', gpMode, manager.config.poolRef);
947
961
  if (derived) {
948
962
  gp = Number(derived);
949
963
  gpSource = gpMode;
@@ -958,8 +972,8 @@ export async function initializeGrid(manager) {
958
972
  }
959
973
  }
960
974
  else if (/^ama(?:[1-4])?$/.test(gpMode || '')) {
961
- amaSnapshot = loadAmaCenterSnapshot(manager.config.botKey);
962
- const amaCenter = amaSnapshot?.gridCenterPrice ?? loadAmaCenterPrice(manager.config.botKey);
975
+ amaSnapshot = loadAmaCenterSnapshot(manager.config.botKey ?? '');
976
+ const amaCenter = Number(amaSnapshot?.gridCenterPrice ?? loadAmaCenterPrice(manager.config.botKey ?? ''));
963
977
  if (Number.isFinite(amaCenter) && amaCenter > 0) {
964
978
  gp = amaCenter;
965
979
  gpSource = 'ama';
@@ -1123,7 +1137,7 @@ export async function initializeGrid(manager) {
1123
1137
  // against the OLD generation (manager.orders is replaced below)
1124
1138
  // with the same live anchors the runtime derivation uses, so the
1125
1139
  // fold can never be driven by a reserve fill.
1126
- const oldSlots = Array.from(manager.orders?.values?.() ?? []);
1140
+ const oldSlots = Array.from(manager.orders.values());
1127
1141
  const edgeAnchors = {
1128
1142
  buy: resolveLiveReserveEdgeAnchorPrice(manager, 'buy'),
1129
1143
  sell: resolveLiveReserveEdgeAnchorPrice(manager, 'sell')
@@ -1410,7 +1424,7 @@ export async function recalculateGrid(manager, opts) {
1410
1424
  * Check for grid divergence and trigger update if threshold is met.
1411
1425
  *
1412
1426
  * @param {import('./types').OrderManager} manager - Manager instance with order state
1413
- * @returns {any}
1427
+ * @returns {unknown}
1414
1428
  */
1415
1429
  export function checkAndUpdateGridIfNeeded(manager) {
1416
1430
  const rawThreshold = manager.config?.gridLimits?.GRID_REGENERATION_PERCENTAGE;
@@ -1647,9 +1661,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
1647
1661
  newSize,
1648
1662
  newPrice: slot.price,
1649
1663
  order: {
1650
- id: slot.id,
1651
- type: slot.type,
1652
- price: slot.price,
1664
+ ...slot,
1653
1665
  size: newSize
1654
1666
  }
1655
1667
  });
@@ -1692,7 +1704,6 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
1692
1704
  if (!fromBlockchainTimer && manager.config?.accountId) {
1693
1705
  await manager.fetchAccountTotals(manager.config.accountId);
1694
1706
  }
1695
- const { WorkingGrid } = require('./working_grid');
1696
1707
  const workingGrid = new WorkingGrid(manager.orders, { baseVersion: manager._gridVersion });
1697
1708
  const allActions = [];
1698
1709
  let hasWorkingChanges = false;
@@ -1715,7 +1726,7 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
1715
1726
  const allSlots = Array.from(workingGrid.values())
1716
1727
  .filter((s) => s.price != null)
1717
1728
  .sort((a, b) => a.price - b.price);
1718
- const updatedSlots = assignGridRoles(allSlots, newBoundary, gapSlots, ORDER_TYPES, ORDER_STATES, { assignOnChain: true });
1729
+ const updatedSlots = assignGridRoles(allSlots, overrideBoundaryIdx, gapSlots, ORDER_TYPES, ORDER_STATES, { assignOnChain: true });
1719
1730
  for (const slot of updatedSlots) {
1720
1731
  workingGrid.set(slot.id, slot);
1721
1732
  }
@@ -1726,13 +1737,13 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
1726
1737
  // one is passed, so boundary-crossing slots are now correctly classified.
1727
1738
  if (orderType === ORDER_TYPES.BUY || orderType === 'both') {
1728
1739
  const buyResult = await _recalculateGridOrderSizesFromBlockchain(manager, ORDER_TYPES.BUY, { workingGrid });
1729
- allActions.push(...buyResult.actions);
1730
- hasWorkingChanges = hasWorkingChanges || buyResult.changed;
1740
+ allActions.push(...(buyResult?.actions ?? []));
1741
+ hasWorkingChanges = hasWorkingChanges || (buyResult?.changed ?? false);
1731
1742
  }
1732
1743
  if (orderType === ORDER_TYPES.SELL || orderType === 'both') {
1733
1744
  const sellResult = await _recalculateGridOrderSizesFromBlockchain(manager, ORDER_TYPES.SELL, { workingGrid });
1734
- allActions.push(...sellResult.actions);
1735
- hasWorkingChanges = hasWorkingChanges || sellResult.changed;
1745
+ allActions.push(...(sellResult?.actions ?? []));
1746
+ hasWorkingChanges = hasWorkingChanges || (sellResult?.changed ?? false);
1736
1747
  }
1737
1748
  // Return COW result only if there are changes
1738
1749
  if (allActions.length === 0 && !hasWorkingChanges) {
@@ -1911,7 +1922,6 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
1911
1922
  // 1. Check ratio-based divergence (available funds vs allocated)
1912
1923
  const ratioResult = checkAndUpdateGridIfNeeded(manager);
1913
1924
  if (ratioResult.buyUpdated || ratioResult.sellUpdated) {
1914
- const { getOrderTypeFromUpdatedFlags } = require('./utils/order');
1915
1925
  return {
1916
1926
  needsUpdate: true,
1917
1927
  buy: { updated: ratioResult.buyUpdated, ratio: ratioResult.buyUpdated, rms: false, metric: 0, shrink: ratioResult.buyShrink === true },
@@ -1923,7 +1933,6 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
1923
1933
  const rmsResult = await compareGrids(calculatedGrid, persistedGrid, manager);
1924
1934
  const buyUpdated = ratioResult.buyUpdated || rmsResult.buy.updated;
1925
1935
  const sellUpdated = ratioResult.sellUpdated || rmsResult.sell.updated;
1926
- const { getOrderTypeFromUpdatedFlags } = require('./utils/order');
1927
1936
  return {
1928
1937
  needsUpdate: buyUpdated || sellUpdated,
1929
1938
  buy: { updated: buyUpdated, ratio: ratioResult.buyUpdated, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: ratioResult.buyShrink === true },
@@ -1945,7 +1954,7 @@ function _getOnChainOrders(manager) {
1945
1954
  // Without this, a live shelf masks an empty window side (oneSideEmpty
1946
1955
  // stays false) and skews the spread inputs. No-op on grids that only
1947
1956
  // mint slot-N ids.
1948
- const isGridSlot = (o) => o?.orderId && Number(o?.size || 0) > 0 && parseSlotIndex(o?.id) !== null;
1957
+ const isGridSlot = (o) => !!(o?.orderId && Number(o?.size || 0) > 0 && parseSlotIndex(o?.id) !== null);
1949
1958
  const onChainBuys = [
1950
1959
  ...manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.ACTIVE),
1951
1960
  ...manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.PARTIAL)
@@ -1993,10 +2002,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
1993
2002
  // This prevents concurrent fill processing from modifying funds while we're making decisions
1994
2003
  let correction = null;
1995
2004
  let shouldApplyCorrection = false;
1996
- // Set when determineOrderSideByFunds finds no side to fund: the caller
1997
- // refreshes account totals + open orders so the next cycle re-checks
1998
- // against fresh balances instead of recycling resting orders.
1999
- 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;
2000
2011
  if (!manager._gridLock) {
2001
2012
  manager.logger?.log?.('Spread check skipped: no grid lock available', 'warn');
2002
2013
  return { ordersPlaced: 0, partialsMoved: 0 };
@@ -2071,7 +2082,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2071
2082
  }
2072
2083
  }
2073
2084
  // Limit spread = nominal + half increment tolerance (0.5 steps).
2074
- const limitSpread = nominalSpread + (manager.config.incrementPercent * toleranceSteps);
2085
+ const limitSpread = nominalSpread + ((manager.config.incrementPercent ?? 0) * toleranceSteps);
2075
2086
  // One-sided book: currentSpread is Infinity (no opposing quote), so
2076
2087
  // log the empty side instead of a bogus "0% > limit" comparison.
2077
2088
  const spreadDesc = oneSideEmpty
@@ -2089,31 +2100,54 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2089
2100
  catch { /* best-effort */ }
2090
2101
  const decision = determineOrderSideByFunds(manager, lastPrice);
2091
2102
  if (!decision.side) {
2092
- fundsExhausted = true;
2103
+ stall = 'no-free-funds';
2093
2104
  return false;
2094
2105
  }
2095
2106
  // Perform spread correction by placing orders on the chosen side.
2096
2107
  correction = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
2097
- if (!correction)
2108
+ if (!correction) {
2109
+ stall = 'no-candidates';
2098
2110
  return false;
2111
+ }
2099
2112
  let placeCount = correction.ordersToPlace?.length || 0;
2100
- 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);
2101
2121
  // STARVATION FALLBACK: If the selected side has no correctable slots (e.g.
2102
2122
  // all SPREAD slots already filled or misaligned), try the opposite side.
2103
- if ((placeCount + updateCount) === 0) {
2123
+ if (placeCount === 0) {
2104
2124
  const oppositeSide = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
2105
2125
  manager.logger?.log?.(`[SPREAD] Side ${decision.side} produced zero candidates; ` +
2106
2126
  `trying opposite side ${oppositeSide}.`, 'debug');
2107
2127
  const oppositeCorrection = await prepareSpreadCorrectionOrders(manager, oppositeSide, manager.outOfSpread);
2108
2128
  if (oppositeCorrection) {
2109
2129
  correction = oppositeCorrection;
2110
- placeCount = correction.ordersToPlace?.length || 0;
2111
- updateCount = correction.ordersToUpdate?.length || 0;
2130
+ placeCount = oppositeCorrection.ordersToPlace?.length || 0;
2131
+ const oppositeStall = classifySpreadStall(oppositeCorrection);
2132
+ sideStall = (sideStall === 'unfunded' || oppositeStall === 'unfunded')
2133
+ ? 'unfunded'
2134
+ : 'no-candidates';
2112
2135
  }
2113
2136
  }
2114
2137
  // Capture fund snapshot under lock for pre-flight verification before broadcast
2115
2138
  fundSnapshot = _snapshotFundState(manager);
2116
- 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;
2117
2151
  };
2118
2152
  try {
2119
2153
  shouldApplyCorrection = await manager._gridLock.acquire(executeSpreadCheck);
@@ -2134,11 +2168,13 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2134
2168
  // The lock is only needed for fund verification; order placement doesn't need it.
2135
2169
  // Pre-flight fund verification mitigates TOCTOU between lock release and broadcast.
2136
2170
  if (shouldApplyCorrection && updateOrdersOnChainBatch && correction && fundSnapshot) {
2171
+ let activeCorrection = correction;
2172
+ let activeSnapshot = fundSnapshot;
2137
2173
  const currentFunds = _snapshotFundState(manager);
2138
- const fundChanged = fundSnapshot.buyFree !== currentFunds.buyFree
2139
- || fundSnapshot.sellFree !== currentFunds.sellFree
2140
- || fundSnapshot.buyLocked !== currentFunds.buyLocked
2141
- || fundSnapshot.sellLocked !== currentFunds.sellLocked;
2174
+ const fundChanged = activeSnapshot.buyFree !== currentFunds.buyFree
2175
+ || activeSnapshot.sellFree !== currentFunds.sellFree
2176
+ || activeSnapshot.buyLocked !== currentFunds.buyLocked
2177
+ || activeSnapshot.sellLocked !== currentFunds.sellLocked;
2142
2178
  if (fundChanged) {
2143
2179
  // TOCTOU: fund state changed between lock release and broadcast.
2144
2180
  // Lock-free re-plan — no _gridLock needed because the fund read
@@ -2159,39 +2195,45 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2159
2195
  manager.logger?.log?.(`[SPREAD] Fund state changed; no side has sufficient funds for re-plan. Skipping cycle.`, 'warn');
2160
2196
  // Same no-free-funds condition as the initial decision:
2161
2197
  // signal the caller to refresh account totals/open orders.
2162
- fundsExhausted = true;
2163
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
2198
+ stall = 'no-free-funds';
2199
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2164
2200
  }
2165
2201
  const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
2166
- if (rePlanCorrection && ((rePlanCorrection.ordersToPlace?.length || 0) + (rePlanCorrection.ordersToUpdate?.length || 0) > 0)) {
2167
- correction = rePlanCorrection;
2168
- fundSnapshot = currentFunds;
2202
+ if (rePlanCorrection && (rePlanCorrection.ordersToPlace?.length || 0) > 0) {
2203
+ activeCorrection = rePlanCorrection;
2204
+ activeSnapshot = currentFunds;
2169
2205
  manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
2170
- `re-planned with updated funds: ${correction.ordersToPlace?.length || 0} creates, ` +
2171
- `${correction.ordersToUpdate?.length || 0} updates`, 'info');
2206
+ `re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates`, 'info');
2172
2207
  }
2173
2208
  else {
2174
2209
  manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
2175
- 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 };
2176
2216
  }
2177
2217
  }
2178
2218
  try {
2179
- const batchResult = await updateOrdersOnChainBatch(correction);
2219
+ const batchResult = await updateOrdersOnChainBatch(activeCorrection);
2180
2220
  if (!batchResult || batchResult.executed !== true) {
2181
2221
  manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.`, 'warn');
2182
- return { ordersPlaced: 0, partialsMoved: 0 };
2222
+ // Nothing landed: ask the caller to refresh account totals +
2223
+ // open orders (stale holds/balances can make the same plan
2224
+ // re-derive every cycle).
2225
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed' };
2183
2226
  }
2184
2227
  await manager.recalculateFunds();
2185
- const placed = correction.ordersToPlace?.length || 0;
2186
- const updated = correction.ordersToUpdate?.length || 0;
2187
- return { ordersPlaced: placed + updated, partialsMoved: updated };
2228
+ const placed = activeCorrection.ordersToPlace?.length || 0;
2229
+ return { ordersPlaced: placed, partialsMoved: 0 };
2188
2230
  }
2189
2231
  catch (err) {
2190
2232
  manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
2191
- return { ordersPlaced: 0, partialsMoved: 0 };
2233
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'apply-error' };
2192
2234
  }
2193
2235
  }
2194
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
2236
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2195
2237
  }
2196
2238
  /**
2197
2239
  * Grid health check for structural violations.
@@ -2245,10 +2287,10 @@ export async function checkWindowDust(manager) {
2245
2287
  if (!manager)
2246
2288
  return { buyDust: false, sellDust: false, buyDustOrders: [], sellDustOrders: [] };
2247
2289
  const allOrders = Array.from(manager.orders.values());
2248
- const isLiveOrder = (order) => order &&
2290
+ const isLiveOrder = (order) => !!(order &&
2249
2291
  order.orderId &&
2250
2292
  order.price != null &&
2251
- (order.state === ORDER_STATES.ACTIVE || order.state === ORDER_STATES.PARTIAL);
2293
+ (order.state === ORDER_STATES.ACTIVE || order.state === ORDER_STATES.PARTIAL));
2252
2294
  // Identify top-of-window orders (closest to market per side).
2253
2295
  const topBuyOrder = allOrders
2254
2296
  .filter((o) => o.type === ORDER_TYPES.BUY && isLiveOrder(o))
@@ -2277,8 +2319,8 @@ export async function checkWindowDust(manager) {
2277
2319
  };
2278
2320
  const assets = manager.assets;
2279
2321
  const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === ORDER_STATES.PARTIAL);
2280
- const isTopBuy = (o) => topBuyOrder && o.id === topBuyOrder.id;
2281
- const isTopSell = (o) => topSellOrder && o.id === topSellOrder.id;
2322
+ const isTopBuy = (o) => !!(topBuyOrder && o.id === topBuyOrder.id);
2323
+ const isTopSell = (o) => !!(topSellOrder && o.id === topSellOrder.id);
2282
2324
  // Compute per-slot dust thresholds once per side so the eligibility
2283
2325
  // filter below and _getDustOrders share the same sizing context
2284
2326
  // (avoids a duplicate recalculateFunds round per side). Each side's map
@@ -2334,7 +2376,7 @@ async function _computeDustThresholdMap(manager, type) {
2334
2376
  .filter((o) => o.type === type)
2335
2377
  .sort((a, b) => a.price - b.price);
2336
2378
  const idealSizes = ctx && ctx.budget > 0
2337
- ? allocateFundsByWeights(ctx.budget, sideSlots.length, manager.config.weightDistribution[side], manager.config.incrementPercent / 100, type === ORDER_TYPES.BUY, 0, ctx.precision)
2379
+ ? allocateFundsByWeights(ctx.budget, sideSlots.length, (manager.config.weightDistribution ?? {})[side], (manager.config.incrementPercent ?? 0) / 100, type === ORDER_TYPES.BUY, 0, ctx.precision)
2338
2380
  : [];
2339
2381
  const map = new Map();
2340
2382
  sideSlots.forEach((s, idx) => {
@@ -2540,7 +2582,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2540
2582
  throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${ORDER_TYPES.BUY}' or '${ORDER_TYPES.SELL}'.`);
2541
2583
  }
2542
2584
  const ordersToPlace = [];
2543
- const ordersToUpdate = [];
2544
2585
  const railType = preferredSide;
2545
2586
  const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
2546
2587
  const configuredMissingSlots = Number(outOfSpread || 0);
@@ -2596,38 +2637,45 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2596
2637
  return ORDER_TYPES.SELL;
2597
2638
  return ORDER_TYPES.SPREAD;
2598
2639
  };
2599
- let edgePartial = null;
2600
- const partials = allOrders
2601
- .filter((o) => getSlotCorrectType(o) === railType
2602
- && o.state === ORDER_STATES.PARTIAL)
2603
- .sort((a, b) => railType === ORDER_TYPES.BUY ? b.price - a.price : a.price - b.price);
2604
- if (partials.length > 0) {
2605
- edgePartial = partials[0];
2606
- manager.logger?.log?.(`[SPREAD-CORRECTION] Identified partial order at ${edgePartial.price} for update`, 'debug');
2607
- }
2640
+ // NOTE: rail partials are deliberately NOT correction targets. A
2641
+ // top-up cannot change bestBuy/bestSell (spread is price-based) and is
2642
+ // forbidden in place by clampPostFillUpdateSize, so the old
2643
+ // edge-partial update was always a no-op that starved the creates.
2644
+ // Spread repair is create-only; the sizing/rotation paths own partials.
2608
2645
  // Primary candidates: SPREAD-type slots adjacent to the gap. Filter by
2609
2646
  // boundary-correct type so a SPREAD slot that, after a boundary shift, now sits
2610
2647
  // in the BUY or SELL zone is excluded — it would otherwise be placed on the
2611
2648
  // correction side at a price the grid already considers the opposite side.
2612
2649
  //
2613
- // Candidate ordering: MARKET-NEAREST FIRST, one comparator for both
2614
- // rail states. A correction is only useful if it tightens bestBuy/bestSell,
2615
- // which means it must land on the market side of the live window — the
2616
- // highest empty BUY (live window is the rail top) or the lowest empty
2617
- // SELL (live window is the rail bottom). Empty slots always sit on the
2618
- // far side of the live window, so "adjacent to the window" and "closest
2619
- // to market" are the same slot, and the same comparator also gives the
2620
- // correct answer for a fully-empty rail (no window anchor, so the
2621
- // market-nearest slot is by definition the best one to create).
2650
+ // Candidate ordering: WINDOW-CONTIGUOUS FIRST. The SPREAD-TIGHTENING
2651
+ // GUARD below keeps only candidates on the market side of the live
2652
+ // window; among those the correction must EXTEND the window, i.e. pick
2653
+ // the slot closest to the live edge (highest SELL / lowest BUY). Picking
2654
+ // the far end instead leaves an interior hole between the new order and
2655
+ // the live window and over-tightens past the target spread. With no live
2656
+ // order (fully-empty rail) there is no anchor, so fall back to
2657
+ // market-nearest (lowest SELL / highest BUY) — the best available level.
2622
2658
  //
2623
- // This previously had two branches — windowFirst (windowed) vs
2624
- // edgeFirst (empty) — that were written as exact OPPOSITES, so a SELL
2625
- // rail with a live window sorted DESCENDING and picked the grid
2659
+ // The previous two-branch comparator (windowFirst vs edgeFirst, exact
2660
+ // OPPOSITES) sorted a windowed SELL rail DESCENDING and picked the grid
2626
2661
  // ceiling: an order ~50% above bestSell that cannot tighten the spread
2627
- // by a single tick, and that the next resync then cancels as surplus.
2628
- const sortCandidates = (a, b) => railType === ORDER_TYPES.BUY
2629
- ? b.price - a.price
2630
- : a.price - b.price;
2662
+ // and is cancelled as surplus on the next resync. The single
2663
+ // market-nearest comparator that replaced it fixed that case but sorts
2664
+ // the FAR end first when the empties sit BELOW the window (the normal
2665
+ // post-fill state), which is the same class of bug mirrored.
2666
+ const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
2667
+ const railBestIsMax = railType === ORDER_TYPES.BUY;
2668
+ const bestLiveOnRail = railBestIsMax
2669
+ ? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
2670
+ : (onChainSells.length ? Math.min(...onChainSells.map((o) => o.price)) : null);
2671
+ const sortCandidates = (a, b) => {
2672
+ if (bestLiveOnRail != null && a?.price != null && b?.price != null) {
2673
+ // Callers have already applied tightensSpread, so both prices
2674
+ // are on the same side of the anchor and distance is monotone.
2675
+ return Math.abs(a.price - bestLiveOnRail) - Math.abs(b.price - bestLiveOnRail);
2676
+ }
2677
+ return railBestIsMax ? b.price - a.price : a.price - b.price;
2678
+ };
2631
2679
  // SPREAD-TIGHTENING GUARD: on a rail that already has a live order, only
2632
2680
  // a candidate that IMPROVES that rail's best price is a spread repair at
2633
2681
  // all. A SELL must land below the lowest live sell, a BUY above the
@@ -2662,13 +2710,16 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2662
2710
  // With no live order on the side there is no reference to improve, so
2663
2711
  // the market-nearest slot is by definition the best available and the
2664
2712
  // guard stays open.
2665
- const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
2666
- const railBestIsMax = railType === ORDER_TYPES.BUY;
2667
- const bestLiveOnRail = railBestIsMax
2668
- ? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
2669
- : (onChainSells.length ? Math.min(...onChainSells.map((o) => o.price)) : null);
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.
2670
2719
  const tightensSpread = (c) => {
2671
- if (bestLiveOnRail == null || c?.price == null)
2720
+ if (c?.price == null || !Number.isFinite(c.price))
2721
+ return false;
2722
+ if (bestLiveOnRail == null)
2672
2723
  return true;
2673
2724
  return railBestIsMax ? c.price > bestLiveOnRail : c.price < bestLiveOnRail;
2674
2725
  };
@@ -2682,8 +2733,17 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2682
2733
  // Secondary candidates: orphaned virtual slots that have lost their
2683
2734
  // order (e.g. stale-cleaned after a race condition during a crash, or a
2684
2735
  // lowest-sell slot dust-cancelled and then left unplaced after a
2685
- // boundary shift). These sit inside the active window and are invisible
2686
- // 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.
2687
2747
  //
2688
2748
  // Empty slots are stored SPREAD (side-neutral) after normalization, so
2689
2749
  // the stored type can be railType OR SPREAD — what matters is that the
@@ -2837,11 +2897,11 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2837
2897
  if (spreadCandidates.length > 0) {
2838
2898
  manager.logger?.log?.(`[SPREAD-CORRECTION] Identified ${spreadCandidates.length}/${missingSlots} slot(s) for activation on ${sideName} (orphaned=${orphanedVirtualCandidates.length}, spread=${spreadCandidates.length - orphanedVirtualCandidates.length})`, 'debug');
2839
2899
  }
2840
- if (!edgePartial && spreadCandidates.length === 0) {
2900
+ if (spreadCandidates.length === 0) {
2841
2901
  manager.logger?.log?.(bestLiveOnRail == null
2842
- ? `[SPREAD-CORRECTION] No suitable partials, orphaned virtual slots, or spread slots found. Skipping.`
2902
+ ? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
2843
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');
2844
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
2904
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
2845
2905
  }
2846
2906
  const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
2847
2907
  const sideSlots = allOrders
@@ -2853,66 +2913,88 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2853
2913
  ].sort((a, b) => a.price - b.price);
2854
2914
  const ctx = await _getSizingContext(manager, sideName);
2855
2915
  if (!ctx || ctx.budget <= 0 || syntheticSideSlots.length === 0) {
2856
- 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 };
2857
2922
  }
2858
2923
  const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
2859
- const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, manager.config.weightDistribution[sideName], manager.config.incrementPercent / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
2924
+ const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, (manager.config.weightDistribution ?? {})[sideName], (manager.config.incrementPercent ?? 0) / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
2860
2925
  const idealById = new Map();
2861
2926
  syntheticSideSlots.forEach((slot, idx) => {
2862
2927
  idealById.set(slot.id, Number(idealSizes[idx] || 0));
2863
2928
  });
2864
2929
  const availableFund = Math.max(0, Math.min(Number(manager.funds?.available?.[sideName] || 0), Number(sideName === 'buy' ? manager.accountTotals?.buyFree : manager.accountTotals?.sellFree) || 0));
2865
- // PURE FUND-DRIVEN: corrections are funded exclusively by free
2866
- // available/chainFree. No resting order is ever shrunk to manufacture
2930
+ // PURE FUND-DRIVEN: corrections are funded exclusively by
2931
+ // funds.available[side] and the cached accountTotals[side]Free read.
2932
+ // No resting order is ever shrunk to manufacture
2867
2933
  // budget (the previous self-funded/redistribution paths moved
2868
2934
  // inventory within a rail and were gamed by stale-size snapshots).
2869
- // When free funds cannot cover every target, the loop below places /
2870
- // tops-up what they allow and stops; the caller refreshes account
2871
- // totals + open orders to find out whether the shortfall was a stale
2872
- // accounting read (the grid does not lose funds, it holds them in
2873
- // resting orders).
2935
+ // When free funds cannot cover every candidate, the loop below places
2936
+ // what they allow and stops; the caller refreshes account totals + open
2937
+ // orders to find out whether the shortfall was a stale accounting read
2938
+ // (the grid does not lose funds, it holds them in resting orders).
2874
2939
  const prioritizedTargets = [];
2875
- if (edgePartial && edgePartial.id) {
2876
- const ideal = Number(idealById.get(edgePartial.id) || 0);
2877
- const current = Number(edgePartial.size || 0);
2878
- if (ideal > current + precisionEpsilon) {
2879
- prioritizedTargets.push({
2880
- kind: 'partial-topup',
2881
- order: edgePartial,
2882
- current,
2883
- ideal,
2884
- needed: Math.max(0, ideal - current)
2885
- });
2886
- }
2887
- }
2940
+ // Spread repair works by adding PRICE LEVELS, never by deepening an
2941
+ // existing one: a top-up grows an order at its current price and so
2942
+ // cannot move bestBuy/bestSell, and it is un-executable in place
2943
+ // (a PARTIAL slot may not be grown by a COW update —
2944
+ // clampPostFillUpdateSize). The old edge-partial top-up always clamped
2945
+ // to a no-op yet ran FIRST and consumed the whole budget, leaving the
2946
+ // creates unfunded ("planned N, placing 0") and the batch empty
2947
+ // ("prepared but not executed"). Fund creates only, still from
2948
+ // available free funds alone.
2888
2949
  for (const slot of spreadCandidates) {
2889
2950
  const ideal = Number(idealById.get(slot.id) || 0);
2890
2951
  if (ideal > precisionEpsilon) {
2891
2952
  prioritizedTargets.push({
2892
2953
  kind: 'create',
2893
2954
  order: slot,
2894
- current: 0,
2895
- ideal,
2896
- needed: ideal
2955
+ ideal
2897
2956
  });
2898
2957
  }
2899
2958
  }
2900
2959
  if (prioritizedTargets.length === 0) {
2901
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
2960
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
2902
2961
  }
2903
2962
  let remainingBudget = availableFund;
2963
+ // FUNDING PROBE (diagnostic): one line per correction cycle showing the
2964
+ // quantities that decide whether candidates can be funded. availableFund
2965
+ // is min(funds.available[side], accountTotals[side]Free); when the
2966
+ // virtual rail has already reserved the free balance this reads ~0 even
2967
+ // though the side still holds inventory — the state that makes the loop
2968
+ // below place fewer orders than the plan's candidates.
2969
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Funding probe side=${sideName}: ` +
2970
+ `availableFund=${Format.formatAmount8(availableFund)} ` +
2971
+ `budget=${Format.formatAmount8(Number(ctx.budget || 0))} ` +
2972
+ `virtual=${Format.formatAmount8(Number(sideName === 'buy' ? manager.funds?.virtual?.buy : manager.funds?.virtual?.sell) || 0)} ` +
2973
+ `free=${Format.formatAmount8(Number(sideName === 'buy' ? manager.accountTotals?.buyFree : manager.accountTotals?.sellFree) || 0)} ` +
2974
+ `virtualSell=${Format.formatAmount8(Number(manager.funds?.virtual?.sell || 0))} ` +
2975
+ `sellFree=${Format.formatAmount8(Number(manager.accountTotals?.sellFree || 0))} ` +
2976
+ `candidates=${prioritizedTargets.length} ` +
2977
+ `ideals=[${prioritizedTargets.map((t) => `${t.order.id}:${Format.formatAmount8(Number(t.ideal || 0))}`).join(', ')}]`, 'debug');
2978
+ // A truncated create (ideal >> residual) may fail isOrderHealthy's
2979
+ // dust/minimum check against its OWN ideal; that candidate is skipped
2980
+ // (continue) and the next one is tried with the SAME residual, so a
2981
+ // small budget can still fund a smaller candidate. When every candidate
2982
+ // is too truncated the residual is intentionally left UNSPENT rather
2983
+ // than force-placed as dust — the refresh above is what distinguishes
2984
+ // "genuinely no room" from "stale accounting read".
2904
2985
  for (const target of prioritizedTargets) {
2986
+ // FUNDING PROBE (per candidate): remainingBudget is read BEFORE this
2987
+ // target is applied, so a "placing 0" cycle can be attributed to the
2988
+ // residual gate rather than to isOrderHealthy/dust rejection.
2989
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Funding probe ${target.kind} ${target.order.id}: ` +
2990
+ `ideal=${Format.formatAmount8(Number(target.ideal || 0))} ` +
2991
+ `remainingBudget=${Format.formatAmount8(remainingBudget)} ` +
2992
+ `availableFund=${Format.formatAmount8(availableFund)} ` +
2993
+ `budget=${Format.formatAmount8(Number(ctx.budget || 0))} ` +
2994
+ `virtualSell=${Format.formatAmount8(Number(manager.funds?.virtual?.sell || 0))} ` +
2995
+ `sellFree=${Format.formatAmount8(Number(manager.accountTotals?.sellFree || 0))}`, 'debug');
2905
2996
  if (remainingBudget <= precisionEpsilon)
2906
2997
  break;
2907
- if (target.kind === 'partial-topup') {
2908
- const topUp = Math.min(target.needed, remainingBudget);
2909
- const newSize = target.current + topUp;
2910
- if (newSize > target.current + precisionEpsilon && isOrderHealthy(newSize, railType, manager.assets, target.ideal)) {
2911
- ordersToUpdate.push({ partialOrder: { ...target.order }, newSize });
2912
- remainingBudget -= topUp;
2913
- }
2914
- continue;
2915
- }
2916
2998
  const createSize = Math.min(target.ideal, remainingBudget);
2917
2999
  if (createSize <= precisionEpsilon)
2918
3000
  continue;
@@ -2978,16 +3060,15 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2978
3060
  boundaryIdx = undefined;
2979
3061
  }
2980
3062
  }
2981
- const combinedUpdates = [...ordersToUpdate];
2982
3063
  if (spreadCandidates.length < missingSlots) {
2983
3064
  manager.logger?.log?.(`[SPREAD-CORRECTION] Requested ${missingSlots} extra slot(s), found ${spreadCandidates.length} available slot(s) on ${sideName}`, 'warn');
2984
3065
  }
2985
3066
  if (ordersToPlace.length < spreadCandidates.length) {
2986
3067
  manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained placement on ${sideName}: planned ${spreadCandidates.length}, placing ${ordersToPlace.length}`, 'info');
2987
3068
  }
2988
- if (combinedUpdates.length > 0 || ordersToPlace.length > 0) {
2989
- manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared updates=${combinedUpdates.length}, creates=${ordersToPlace.length}, remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
3069
+ if (ordersToPlace.length > 0) {
3070
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length}, remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
2990
3071
  }
2991
- return { ordersToPlace, ordersToUpdate: combinedUpdates, ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: 'spread-correction' };
3072
+ return { ordersToPlace, ordersToUpdate: [], plannedCount: prioritizedTargets.length, ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: COW_ORIGINS.SPREAD_CORRECTION };
2992
3073
  }
2993
3074
  //# sourceMappingURL=grid.js.map