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
@@ -40,7 +40,8 @@ const livePath = PATHS.PROFILES.BOTS_JSON;
40
40
  */
41
41
  function checkConfig(obj, src) {
42
42
  // Normalize: convert single bot to array format for uniform processing
43
- const bots = Array.isArray(obj.bots) && obj.bots.length ? obj.bots : [obj];
43
+ const o = (obj && typeof obj === 'object') ? obj : {};
44
+ const bots = Array.isArray(o.bots) && o.bots.length ? o.bots : [o];
44
45
  console.log(`\n== Checking ${src}: found ${bots.length} bot entries`);
45
46
  // List of required fields that every bot must have
46
47
  const required = ['assetA', 'assetB', 'activeOrders', 'botFunds'];
@@ -196,6 +196,14 @@ const TESTS = [
196
196
  expectFail: false,
197
197
  externalizeNodeBuiltins: true,
198
198
  },
199
+ {
200
+ // Guards the shared ECC core and its browser entry now that ecc.browser.ts
201
+ // delegates its curve math to modules/bitshares-native/crypto/ecc_core.ts.
202
+ label: 'modules/bitshares-native/crypto/ecc.browser.ts (browser-safe)',
203
+ entry: 'modules/bitshares-native/crypto/ecc.browser.ts',
204
+ expectFail: false,
205
+ externalizeNodeBuiltins: true,
206
+ },
199
207
  {
200
208
  label: 'modules/utils/base58check.ts (browser-safe)',
201
209
  entry: 'modules/utils/base58check.ts',
package/dist/unlock.d.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import type { ChildProcess } from 'node:child_process';
2
3
  declare const waitForChildSpawn: any, pidMatchesScriptCandidates: any, candidateRuntimeScriptPaths: any;
3
4
  declare const isLikelyCredentialDaemonProcess: any, ensureNoForeignCredentialDaemon: any, findCredentialSocketOwnerPid: any, buildDexbotStartArgs: any;
4
- declare function waitForStableChildStartup(child: any, { label, timeoutMs }?: any): any;
5
+ declare function waitForStableChildStartup(child: ChildProcess, { label, timeoutMs }?: {
6
+ label?: string;
7
+ timeoutMs?: number;
8
+ }): Promise<void>;
5
9
  /**
6
10
  * Handle first-run setup at the launcher boundary. This is shared by
7
11
  * `dexbot start`, `dexbot unlock`, and direct `node unlock` invocations.
@@ -14,6 +18,27 @@ declare function runStartOnboardingIfNeeded({ allowInteractive, nonInteractiveFl
14
18
  allowInteractive?: boolean;
15
19
  nonInteractiveFlag?: string;
16
20
  }): Promise<boolean>;
17
- declare function main({ argv, startupGraceMs, exitAfterOnboarding, onboard }?: any): Promise<void>;
18
- export { buildDexbotStartArgs, candidateRuntimeScriptPaths, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
21
+ declare function main({ argv, startupGraceMs, exitAfterOnboarding, onboard }?: {
22
+ argv?: string[];
23
+ startupGraceMs?: number;
24
+ exitAfterOnboarding?: boolean;
25
+ onboard?: boolean;
26
+ }): Promise<void>;
27
+ /**
28
+ * Best-effort wait until no `dexbot` worker process remains.
29
+ *
30
+ * `stop` returns as soon as the monolithic wrapper exits, but the wrapper's
31
+ * supervisor pid file is wiped on wrapper exit, so a `start` racing the worker
32
+ * teardown spawns a SECOND worker over the still-live orders (duplicate
33
+ * trades). Poll /proc until every dexbot worker is gone or the deadline
34
+ * expires. No-op off Linux / when /proc is unreadable.
35
+ *
36
+ * Must also run when there is no live wrapper (stale or absent pid file): an
37
+ * orphaned worker is exactly the case the pid-file check cannot see.
38
+ *
39
+ * @param deadlineMs - Maximum time to wait for the workers to exit.
40
+ * @returns True when no worker remains (or the scan is unavailable).
41
+ */
42
+ declare function drainMonolithicWorkers(deadlineMs?: number): Promise<boolean>;
43
+ export { buildDexbotStartArgs, candidateRuntimeScriptPaths, drainMonolithicWorkers, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
19
44
  //# sourceMappingURL=unlock.d.ts.map
package/dist/unlock.js CHANGED
@@ -65,7 +65,7 @@ import { getWhitelistFlags } from './modules/market_adapter_whitelist.js';
65
65
  import { createMarketAdapterWatchdog } from './modules/launcher/market_adapter_watchdog.js';
66
66
  import { isLikelyMarketAdapterProcess } from './modules/launcher/market_adapter_runtime.js';
67
67
  import { Config } from './modules/config.js';
68
- import { getErrorMessage } from './modules/utils/errors.js';
68
+ import { getErrorMessage, getErrorCode } from './modules/utils/errors.js';
69
69
  import { isSameBotName } from './modules/utils/sanitize_key.js';
70
70
  import { withTimeout } from './modules/order/utils/timeout.js';
71
71
  setUmask(0o077);
@@ -143,7 +143,7 @@ function printLauncherSuccess({ botName = null, clawOnly = false, isolated = fal
143
143
  function makeFinishGuard(cleanup) {
144
144
  let settled = false;
145
145
  let timer = null;
146
- const finish = (fn, value) => {
146
+ const finish = (fn, ...args) => {
147
147
  if (settled)
148
148
  return;
149
149
  settled = true;
@@ -152,7 +152,7 @@ function makeFinishGuard(cleanup) {
152
152
  timer = null;
153
153
  }
154
154
  cleanup();
155
- fn(value);
155
+ fn(args[0]);
156
156
  };
157
157
  return { finish, getTimer: () => timer, setTimer: (t) => { timer = t; } };
158
158
  }
@@ -299,12 +299,12 @@ async function launchDetachedSupervisor({ botName = null, credentialDaemonPid =
299
299
  }),
300
300
  stdio: ['ignore', stdoutFd, stderrFd],
301
301
  });
302
- child.unref();
302
+ child?.unref();
303
303
  const ready = await waitForSupervisorReady({ child });
304
304
  if (!ready) {
305
305
  throw new Error(`supervisor did not become ready. Check ${SUPERVISOR_OUT_LOG} and ${SUPERVISOR_ERROR_LOG}`);
306
306
  }
307
- return child.pid || 0;
307
+ return child?.pid || 0;
308
308
  }
309
309
  catch (err) {
310
310
  if (child && child.pid) {
@@ -652,7 +652,6 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
652
652
  const watchdog = createMarketAdapterWatchdog({
653
653
  codeRoot: CODE_ROOT,
654
654
  root: PATHS.PROJECT_ROOT,
655
- logsDir: LOGS_DIR,
656
655
  });
657
656
  const cancelWatchdog = watchdog.schedule(MONOLITHIC_ERROR_LOG);
658
657
  let restartCount = 0;
@@ -728,7 +727,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
728
727
  };
729
728
  const exitCode = await new Promise((resolve, reject) => {
730
729
  botProcess.on('error', reject);
731
- botProcess.on('close', (code) => resolve(code));
730
+ botProcess.on('close', (code) => resolve(code ?? 0));
732
731
  }).catch((err) => {
733
732
  cleanupBotHandlers();
734
733
  throw err;
@@ -869,6 +868,45 @@ function printMarketAdapterStatusBlock() {
869
868
  console.log(` - ${colorStatus(b.name, STATUS_COLORS.ok)} (${b.gridPrice}${suffix})`);
870
869
  }
871
870
  }
871
+ /**
872
+ * Best-effort wait until no `dexbot` worker process remains.
873
+ *
874
+ * `stop` returns as soon as the monolithic wrapper exits, but the wrapper's
875
+ * supervisor pid file is wiped on wrapper exit, so a `start` racing the worker
876
+ * teardown spawns a SECOND worker over the still-live orders (duplicate
877
+ * trades). Poll /proc until every dexbot worker is gone or the deadline
878
+ * expires. No-op off Linux / when /proc is unreadable.
879
+ *
880
+ * Must also run when there is no live wrapper (stale or absent pid file): an
881
+ * orphaned worker is exactly the case the pid-file check cannot see.
882
+ *
883
+ * @param deadlineMs - Maximum time to wait for the workers to exit.
884
+ * @returns True when no worker remains (or the scan is unavailable).
885
+ */
886
+ async function drainMonolithicWorkers(deadlineMs = 15000) {
887
+ const workerPaths = candidateRuntimeScriptPaths(['dexbot']);
888
+ const drainStarted = Date.now();
889
+ while (Date.now() - drainStarted < deadlineMs) {
890
+ let aliveWorkers = 0;
891
+ try {
892
+ for (const procEntry of fs.readdirSync('/proc')) {
893
+ const wpid = Number(procEntry);
894
+ if (!Number.isInteger(wpid) || wpid <= 0)
895
+ continue;
896
+ if (pidMatchesScriptCandidates(wpid, workerPaths))
897
+ aliveWorkers++;
898
+ }
899
+ }
900
+ catch (_) { /* /proc scan is best-effort */ }
901
+ // A failed scan yields 0 and returns immediately, so this is a no-op
902
+ // on platforms without /proc rather than a 15s stall.
903
+ if (aliveWorkers === 0)
904
+ return true;
905
+ await new Promise((res) => setTimeout(res, 250));
906
+ }
907
+ console.warn(`dexbot stop: worker process(es) still alive after ${deadlineMs}ms — not waiting longer (state kept; a start may report the running bot).`);
908
+ return false;
909
+ }
872
910
  async function handleControl({ cmd, target }) {
873
911
  const effectiveCmd = cmd === 'shutdown' ? 'delete' : cmd === 'stat' ? 'status' : cmd;
874
912
  const actionLabel = getControlActionLabel(cmd);
@@ -905,7 +943,7 @@ async function handleControl({ cmd, target }) {
905
943
  runtime.kill(pid, 'SIGUSR2');
906
944
  }
907
945
  catch (err) {
908
- if (err.code !== 'ESRCH')
946
+ if (getErrorCode(err) !== 'ESRCH')
909
947
  throw err;
910
948
  }
911
949
  printControlActionSummary(actionLabel, summaryBotNames, summaryServiceNames);
@@ -985,35 +1023,11 @@ async function handleControl({ cmd, target }) {
985
1023
  // (duplicate trades). Wait for every dexbot worker to actually
986
1024
  // die before returning.
987
1025
  if (monolithicExited) {
988
- const workerPaths = candidateRuntimeScriptPaths(['dexbot']);
989
- const drainDeadlineMs = 15000;
990
- const drainStarted = Date.now();
991
- let drained = false;
992
- while (Date.now() - drainStarted < drainDeadlineMs) {
993
- const aliveWorkers = [];
994
- try {
995
- for (const procEntry of fs.readdirSync('/proc')) {
996
- const wpid = Number(procEntry);
997
- if (!Number.isInteger(wpid) || wpid <= 0)
998
- continue;
999
- if (pidMatchesScriptCandidates(wpid, workerPaths))
1000
- aliveWorkers.push(wpid);
1001
- }
1002
- }
1003
- catch (_) { /* /proc scan is best-effort */ }
1004
- if (aliveWorkers.length === 0) {
1005
- drained = true;
1006
- break;
1007
- }
1008
- await new Promise((res) => setTimeout(res, 250));
1009
- }
1010
- if (!drained) {
1011
- console.warn(`dexbot stop: worker process(es) still alive after ${drainDeadlineMs}ms — not waiting longer (state kept; a start may report the running bot).`);
1012
- }
1026
+ await drainMonolithicWorkers();
1013
1027
  }
1014
1028
  }
1015
1029
  catch (err) {
1016
- if (err.code !== 'ESRCH')
1030
+ if (getErrorCode(err) !== 'ESRCH')
1017
1031
  throw err;
1018
1032
  monolithicExited = true;
1019
1033
  }
@@ -1032,6 +1046,12 @@ async function handleControl({ cmd, target }) {
1032
1046
  return;
1033
1047
  }
1034
1048
  else if (stale) {
1049
+ // Stale pid file: the wrapper is gone, but its worker can outlive
1050
+ // it. Drain before returning so a following start cannot spawn a
1051
+ // duplicate over the live orders.
1052
+ if (effectiveCmd !== 'status') {
1053
+ await drainMonolithicWorkers();
1054
+ }
1035
1055
  if (effectiveCmd === 'delete') {
1036
1056
  const summaryBotNames = getControlBotNames(undefined, true);
1037
1057
  const isolatedDeleted = await sendIsolatedDeleteIfAvailable();
@@ -1063,6 +1083,14 @@ async function handleControl({ cmd, target }) {
1063
1083
  }
1064
1084
  }
1065
1085
  }
1086
+ // No live wrapper pid file: an orphaned worker can still be running (the
1087
+ // wrapper was killed without leaving a pid file, or cleanupStateFiles
1088
+ // already ran). Drain before the isolated fall-through so that path cannot
1089
+ // race a start into a duplicate worker.
1090
+ if (!target && effectiveCmd !== 'status'
1091
+ && (effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all')) {
1092
+ await drainMonolithicWorkers();
1093
+ }
1066
1094
  if (effectiveCmd === 'delete' && !target && storage.exists(MONOLITHIC_CRED_PID_FILE)) {
1067
1095
  await sendIsolatedDeleteIfAvailable();
1068
1096
  const credResult = await stopCredentialDaemon();
@@ -1148,5 +1176,5 @@ if (isUnlockStartDirectRun) {
1148
1176
  }
1149
1177
  })();
1150
1178
  }
1151
- export { buildDexbotStartArgs, candidateRuntimeScriptPaths, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
1179
+ export { buildDexbotStartArgs, candidateRuntimeScriptPaths, drainMonolithicWorkers, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
1152
1180
  //# sourceMappingURL=unlock.js.map
@@ -287,6 +287,8 @@ The only things worth tuning later:
287
287
  `{ "sell": 1.0, "buy": 1.0 }` for your first bot.
288
288
  - `minPrice` / `maxPrice` — grid bounds. Once AMA is active, tighten them
289
289
  around the market's maximum expected volatility instead of a wide range.
290
+ Use `dexbot tv <bot>` to see the grid range and AMA recentering against
291
+ real candles.
290
292
 
291
293
  See the "Recommended Bot Setup" section of the
292
294
  [README](../README.md#recommended-bot-setup).
@@ -413,18 +415,17 @@ npm prefix -g # must be a directory you own
413
415
 
414
416
  Check with `dexbot --help`.
415
417
 
416
- ### "npm says it blocked dexbot's install scripts (`prepare` / `postinstall`)"
418
+ ### "npm says it blocked dexbot's install scripts (`prepare`)"
417
419
 
418
420
  npm 12+ no longer runs lifecycle scripts of installed packages unless they
419
421
  are allowlisted (supply-chain hardening,
420
422
  [npm/rfcs#868](https://github.com/npm/rfcs/blob/master/text/0868-allow-scripts.md)).
421
- You'll see `npm warn install-scripts ... blocked` listing dexbot's
422
- `postinstall` and `prepare`. It shows up with `npm link` because link adds
423
- your checkout to the **global** install tree as a `file:` dependency — npm
424
- treats it like any third-party package and blocks its scripts. The warning's
425
- own advice (`npm install-scripts ls` / `approve`) is a dead end here: in your
426
- project the checkout is the project root, which npm deliberately never lists
427
- or approves. Don't chase it.
423
+ With `npm link` you'll see `npm warn install-scripts ... blocked` listing
424
+ dexbot's `prepare`: link adds your checkout to the **global** install tree as
425
+ a `file:` dependency — npm treats it like any third-party package and blocks
426
+ its scripts. The warning's own advice (`npm install-scripts ls` / `approve`)
427
+ is a dead end here: in your project the checkout is the project root, which
428
+ npm deliberately never lists or approves. Don't chase it.
428
429
 
429
430
  A plain `npm install` is **not** gated — it runs the project's own `prepare`
430
431
  directly, so the correct from-source order is:
@@ -436,10 +437,7 @@ npm link # a blocked prepare here is harmless
436
437
  ```
437
438
 
438
439
  If you skipped the install (or want to be sure), run `npm run build`. Bins
439
- are never gated, so once `dist/` exists the linked `dexbot` works. The
440
- blocked `postinstall` is only the "DEXBot2 installed!" banner — cosmetic;
441
- `npm i -g dexbot` may warn about the same banner and that's harmless too
442
- (the published package ships prebuilt).
440
+ are never gated, so once `dist/` exists the linked `dexbot` works.
443
441
 
444
442
  ### "`Unknown command: dexbot` right after installing/linking"
445
443
 
@@ -230,10 +230,10 @@ syncFromMaster(masterGrid, orderId, masterVersion?) {
230
230
  |--------|-------------|
231
231
  | `performSafeRebalance(fills, excludeIds)` | Entry point — delegates to COW |
232
232
  | `_applySafeRebalanceCOW(fills, excludeIds)` | Creates working grid, runs planning |
233
- | `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts:204`, delegating to `utils/order.ts`) |
233
+ | `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts:205`, delegating to `utils/order.ts`) |
234
234
  | `_commitWorkingGrid(workingGrid, indexes, boundary, options = {})` | Atomic swap to master |
235
235
  | `_setRebalanceState(state)` | Track rebalance state |
236
- | `_currentWorkingGrid` | Reference to working grid during rebalance for fill sync |
236
+ | `_currentWorkingGridStack` | Stack of active working-grid references during rebalance for fill sync; peek the innermost via `_peekWorkingGrid()`, managed with `_pushWorkingGridRef`/`_popWorkingGridRef`/`_releaseWorkingGridRef`/`_clearWorkingGridRef` |
237
237
  | `_applyOrderUpdate(order, context, options = {})` | Lock-free order update (immutable swap); routes fill sync to `_syncWorkingGridFromMasterMutation` |
238
238
  | `_syncWorkingGridFromMasterMutation(orderId, context)` | Adapter: planning-state gate → `markStale()` + `syncFromMaster()` → sync error handling |
239
239
 
@@ -87,11 +87,11 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
87
87
  - `INV-PROJ-002` Preserve on-chain PARTIAL size in projection
88
88
  - If identity is retained (`keepOrderId=true`) and current state is `PARTIAL`, projected size must preserve current on-chain remaining size.
89
89
  - It must not be overwritten by ideal geometric `targetSize`.
90
- - Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path at `modules/order/utils/validate.ts:1129`).
90
+ - Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path at `modules/order/utils/validate.ts:1158`).
91
91
  - Preserve-path size must be normalized to finite, non-negative value.
92
92
 
93
93
  - `INV-PROJ-003` ACTIVE on-chain projection preserves current size (same as PARTIAL)
94
- - If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts:1129`).
94
+ - If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts:1158`).
95
95
  - An explicit UPDATE action targeting the `orderId` is required to apply `targetSize`.
96
96
 
97
97
  - `INV-ID-001` Order identity retention rule
@@ -110,7 +110,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
110
110
  - `INV-ACC-003` Cross-bot fund registry invariant (INVARIANT 3)
111
111
  - Shared-account per-bot commitment must not exceed the bot's proportional share of chain balance.
112
112
  - Checked with widened tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
113
- - Registry failure logs an error (`order/accounting.ts:574-590`, with a "CRITICAL FIX: Log as ERROR instead of WARN" comment), not a silent skip.
113
+ - Registry failure logs an error (`order/accounting.ts:636-685`), not a silent skip.
114
114
 
115
115
  ---
116
116
 
@@ -229,6 +229,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
229
229
  - Cancelled IDs are filtered out of `unmatchedParsed` to prevent reprocessing.
230
230
  - No size guard — any duplicate at the same price is a violation.
231
231
  - The earlier fuzzy `SUSPECTED_DUPLICATE_TOLERANCE_MULTIPLIER` (5× `calculatePriceTolerance`) and `SUSPECTED_DUPLICATE_TOLERANCE_FLOOR` are removed; only exact price-level equality triggers a reconcile cancel.
232
+ - Cancel deferral under `INV-RECON-006` applies before submission.
232
233
 
233
234
  - `INV-RECON-004` Rebalance must not convert on-chain slots to SPREAD via CREATE
234
235
  - `performSafeRebalance` must not emit `CREATE` actions that convert existing on-chain slots into SPREAD orders.
@@ -238,13 +239,19 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
238
239
  - BUY placements must use nearest available free slots first (descending price, so the nearest-to-center slots fill first — `order/utils/order.ts` `buildOutsideInPairGroups`).
239
240
  - SELL placements must use nearest available free slots first (ascending price).
240
241
 
242
+ - `INV-RECON-006` Fresh-placement cancels are deferred for a grace window
243
+ - A CANCEL action targeting an `orderId` placed within `TIMING.SURPLUS_CANCEL_GRACE_MS` (15 min) is deferred. The timestamp is written by `recordOrderPlacement` into `manager._placedAt` and tested by `isFreshlyPlacedOrder`.
244
+ - `COWRebalanceEngine.execute` drops the whole slot's action group for a deferred cancel (dropping only the CANCEL would let a paired CREATE fold back into an UPDATE and re-materialize the placement), then re-syncs the deferred slots from master via `workingGrid.syncFromMaster` so the commit does not virtualize a still-live order.
245
+ - Divergence correction (`applyGridDivergenceCorrections`) applies the same guard after dropping any queued committed-size UPDATE for the not-desired/size-0 slot.
246
+ - `grid-load`/`grid-init` load contexts are excluded so restarts do not suppress the sweep.
247
+
241
248
  ---
242
249
 
243
250
  ## Batch / Pipeline
244
251
 
245
252
  - `INV-BATCH-001` Illegal state batch abort
246
253
  - `executeBatch` throws `ILLEGAL_SPREAD_STATE` on an illegal grid layout (emitted at `modules/order/utils/validate.ts`, propagated via `modules/order/manager.ts` `_throwOnIllegalState`).
247
- - The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:455`) is a test-only dead branch — production never emits that code; only a test stub uses it.
254
+ - The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:501`) is a test-only dead branch — production never emits that code; only a test stub uses it.
248
255
  - In production, recovery + cooldown are armed on the next maintenance tick via `_abortFlowIfIllegalState` (the `INV-MAINT-002` path), returning `abortedForIllegalState: true` to the caller. The caller does not need to return immediately; the maintenance tick handles recovery.
249
256
  - Hard abort triggers one immediate recovery sync (`_triggerStateRecoverySync`) plus arms one maintenance cooldown cycle (`_maintenanceCooldownCycles = Math.max(current, 1)`).
250
257
 
@@ -263,7 +270,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
263
270
  - NOT virtualize the slot.
264
271
  - Preserve `orderId` until sync reconciles it.
265
272
  - NOT mark the order as stale-cleaned.
266
- - Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts:269`), a targeted repair applies the correction directly and skips `_triggerStateRecoverySync`.
273
+ - Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts:273`), a targeted repair applies the correction directly and skips `_triggerStateRecoverySync`.
267
274
 
268
275
  ---
269
276
 
@@ -287,7 +294,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
287
294
  - `INV-REG-001` Cross-bot allocation ≤ proportional share
288
295
  - Per-bot committed amounts (sum of on-chain orders) must not exceed `totalChainBalance × allocatedPercent`.
289
296
  - Violation triggers an error-level log entry (not silent), with tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
290
- - Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts:611` filters `accountGroups[a].length > 1`), and registration completes before any shared-account bot starts.
297
+ - Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts:617` filters `accountGroups[a].length > 1`), and registration completes before any shared-account bot starts.
291
298
  - Release happens in `DEXBot.shutdown`.
292
299
 
293
300
  - `INV-REG-002` Async-locked registry writes
@@ -1,7 +1,7 @@
1
1
  # DEXBot vs DEXBot2 — Detailed Comparison Report
2
2
 
3
3
  > **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
4
- > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.11).
4
+ > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.13).
5
5
  > **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
6
6
 
7
7
  ---
@@ -36,7 +36,7 @@
36
36
 
37
37
  | Attribute | DEXBot (original) | DEXBot2 |
38
38
  |---|---|---|
39
- | **Release Track** | 1.0.0 | v1.6.11 |
39
+ | **Release Track** | 1.0.0 | v1.6.13 |
40
40
  | **Language** | Python 3.6+ | TypeScript 5.x |
41
41
  | **Status** | Released 1.0.0, unmaintained | Active development |
42
42
  | **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
@@ -616,7 +616,7 @@ Where:
616
616
  ### DEXBot2
617
617
 
618
618
  - **Framework:** Native Node `assert` module (no external test framework)
619
- - **256 `test_*.ts` files** auto-discovered via `globSync` (`tests/test_*.ts` + `claw/tests/test_*.ts`), covering:
619
+ - **330 `test_*.ts` files** auto-discovered via `globSync` (`tests/test_*.ts` + `claw/tests/test_*.ts`), covering:
620
620
  - Unit tests: accounting, strategy, grid, manager logic
621
621
  - Copy-on-Write semantics: COW commits, guards, concurrent fills
622
622
  - Edge cases: authoritative full-fill resolution, partial fills, BTS fee accounting, precision
@@ -776,13 +776,13 @@ Where:
776
776
 
777
777
  | Metric | DEXBot | DEXBot2 |
778
778
  |---|---|---|
779
- | **Release Track** | 1.0.0 | v1.6.11 |
779
+ | **Release Track** | 1.0.0 | v1.6.13 |
780
780
  | **Active Since** | ~2018 | December 2025 |
781
- | **Last Commit** | May 23, 2020 | 2026-09-02 |
782
- | **Total Commits** | 2281 | 2,125 (v1.4.25) |
781
+ | **Last Commit** | May 23, 2020 | 2026-10-10 |
782
+ | **Total Commits** | 2281 | 2,372 (current HEAD, v1.6.13 line) |
783
783
  | **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
784
- | **Source Files** | 72 Python files in `dexbot/` | ~544 TS files across the repo |
785
- | **Test Files** | 16 Python test files | 248 `test_*.ts` files (248 auto-discovered via `globSync`) |
784
+ | **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
785
+ | **Test Files** | 16 Python test files | 324 `test_*.ts` files (307 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |
786
786
  | **Documentation** | Sphinx docs + README | 60+ Markdown docs plus Claw skills/references |
787
787
  | **Strategies** | 3 + plugins | 1 |
788
788
  | **Max Concurrent Bots** | Many (one process) | Many (one monolithic process by default; per-bot via `--isolated`/PM2) |
package/docs/EVOLUTION.md CHANGED
@@ -2,14 +2,14 @@
2
2
 
3
3
  ## Executive Summary
4
4
 
5
- DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.11 release.
5
+ DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.13 release.
6
6
 
7
7
  ### Key Milestones
8
8
  - **Project Inception**: December 2, 2025
9
- - **Growth Phase**: 2,322 commits over ~9 active months
9
+ - **Growth Phase**: 2,372 commits over ~9 active months
10
10
  - **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
11
11
  - **Stability**: Progression from manual testing to a suite of 307 automated test files
12
- - **Releases**: 143 version entries in the changelog (v0.1.0 to v1.6.11)
12
+ - **Releases**: 145 version entries in the changelog (v0.1.0 to v1.6.13)
13
13
 
14
14
  > **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
15
15
  > bug families, and lessons — lives in
@@ -145,11 +145,11 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
145
145
 
146
146
  **Completed**: browser-safe core; credit/MPA runtime; storage-adapter I/O centralization; self-healing recovery; Kibana PnL analytics — terminal analyzer plus the self-contained HTML report behind `dexbot pnl` (`analysis/pnl_report.ts`), backed by a per-account month-shard fill cache (`analysis/fills_cache.ts`); credit-only mode; Docker support; npm package. For the grid order engine arc specifically (COW pipeline, orphan/self-trade/fill-guard hardening, invariants) see [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md) §R4.
147
147
 
148
- **Planned**: backtesting engine (historical candle replay via exchange abstraction); injectable interfaces at call boundaries; SQLite persistence + Zod validation at the blockchain boundary; Telegram bot (**not yet implemented**) — owner-gated monitoring (`/status`, `/orders`, `/grid`, `/balance`) and opt-in+confirm gated control (`/start`, `/stop`, `/pause`); DEXBot is the only writer, private keys never reach the module (`TELEGRAM` block + `DEXBOT_TELEGRAM_TOKEN` env).
148
+ **Planned**: backtesting engine (historical candle replay via exchange abstraction); injectable interfaces at call boundaries; SQLite persistence + Zod validation at the blockchain boundary.
149
149
 
150
150
  ## Version History
151
151
 
152
- Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-02), so the column sums to 2,215 — the 107 commits up to and including the `v0.1.0` tag are not attributed to an era (2,215 + 107 = 2,322). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
152
+ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-10), so the column sums to 2,265 — the 107 commits up to and including the `v0.1.0` tag are not attributed to an era (2,265 + 107 = 2,372). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
153
153
 
154
154
  | Era | Commits | Theme |
155
155
  |-----|--------:|-------|
@@ -169,11 +169,13 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
169
169
  | v1.6.8 → v1.6.9 | 6 | Market-adapter cycle-CPU cuts, candle-boundary off-hour idle, spread-correction spread-tightening guard |
170
170
  | v1.6.9 → v1.6.10 | 7 | Huber-robust AMA slope, asset-pair uppercase canonicalization, TradingView indicator ownership (auto opt-in, span bounds) and chart-view preservation |
171
171
  | v1.6.10 → v1.6.11 | 6 | AMA-slope 3-bar persistence gate + 16h Huber lookback, EMA-smoothing removal, PnL HTML report + month-shard fill cache, five order-engine/lifecycle safety fixes |
172
+ | v1.6.11 → v1.6.12 | 27 | Explicit-`any` elimination + ratchet, shared ECC core & Firefox-safe pure-JS scrypt, worker-drain and fresh-placement cancel-grace safety fixes, funded spread correction, partial credit renewal, update install-layout classifier, AMA persistence-override fixes, test-suite speedup, dynamic-weight knob retune |
173
+ | v1.6.12 → v1.6.13 | 21 | Spread-stall cause reporting + chain sync on every stall, resync-cascade guards (uncertain broadcast / suspended persistence), month-shard candle cache, dedup & dead-code purge, npm 12 install & PM2 fixes |
172
174
 
173
175
  ---
174
176
 
175
177
  **Report Originally Generated**: February 19, 2026
176
- **Last Updated**: October 2, 2026
177
- **Total Commits**: 2,322
178
- **Date Range**: December 2, 2025 – October 2, 2026
178
+ **Last Updated**: October 10, 2026
179
+ **Total Commits**: 2,372
180
+ **Date Range**: December 2, 2025 – October 10, 2026
179
181
  **Repository**: DEXBot2 (BitShares DEX Trading Bot)
@@ -52,7 +52,7 @@ funds.allocated → _getSizingContext() (budget for spread correction)
52
52
  **Key points:**
53
53
  - `botFunds` percentage applies to **total** capital (free + locked in orders), not just free. A bot at `"50%"` gets half of everything, not half of what's currently idle.
54
54
  - `funds.allocated` is the ceiling for each side. Existing orders already consume part of it; the remaining free portion is available for new placements.
55
- - The downstream `applyBotFundsAllocation()` (`manager.ts:949`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
55
+ - The downstream `applyBotFundsAllocation()` (`manager.ts:1277`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
56
56
 
57
57
  ---
58
58
 
@@ -123,7 +123,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
123
123
  **Per-Batch Execution**:
124
124
 
125
125
  1. **Peek & Pop**: Check `_incomingFillQueue`, pop up to N fills (batch size)
126
- 2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:227`)
126
+ 2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:305`)
127
127
  - Proceeds credited directly to `chainFree` (via `adjustTotalBalance`)
128
128
  - Same-order fill batching (sync_engine Phase 6 cumulative transition) aggregates multiple fill transitions on one order before a single rebalance
129
129
  - All proceeds immediately available to next rebalance cycle (not split across cycles)
@@ -137,7 +137,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
137
137
 
138
138
  **Result**: 29 fills now processed in ~8 broadcasts (~24s) instead of 29 broadcasts (~90s).
139
139
 
140
- **Residual Dust Cancellation** (post-1.4.12): After a sub-dust fill leaves a residual order on chain (e.g. the quote-side value truncates to 0 on `bitshares-core` `maybe_cull_small_order`), the fill runtime explicitly cancels those residuals via `cancelResidualOrders()` (`dexbot_fill_runtime.ts:74`, `[RESIDUAL]` tag) so a leftover of ≥1 base unit cannot be re-adopted into a grid slot by maintenance.
140
+ **Residual Dust Cancellation** (post-1.4.12): After a sub-dust fill leaves a residual order on chain (e.g. the quote-side value truncates to 0 on `bitshares-core` `maybe_cull_small_order`), the fill runtime explicitly cancels those residuals via `cancelResidualOrders()` (`dexbot_fill_runtime.ts:193`, `[RESIDUAL]` tag) so a leftover of ≥1 base unit cannot be re-adopted into a grid slot by maintenance.
141
141
 
142
142
  #### Grid Regeneration Trigger (Available Funds Ratio — bidirectional)
143
143
 
@@ -154,7 +154,7 @@ SHRINK: overAlloc = (gridTracked - allocatedCapital) / allocatedCapital * 100
154
154
  → Trigger grid regeneration (resize affected orders down)
155
155
  ```
156
156
 
157
- Deliberately no per-side chain-total-drop leg: a normal fill moves value across sides (pays one asset, receives the other — see `recordFillBalances`), so one side's total routinely drops ≥3% on ordinary fills, and the fill pipeline already re-sizes from the post-fill budget.
157
+ Deliberately no per-side chain-total-drop leg: a normal fill moves value across sides (pays one asset, receives the other — see `processFillAccounting`), so one side's total routinely drops ≥3% on ordinary fills, and the fill pipeline already re-sizes from the post-fill budget.
158
158
 
159
159
  **How It Works (grow)**:
160
160
  1. Fill occurs → proceeds added to `chainFree`
@@ -801,4 +801,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
801
801
  **TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
802
802
 
803
803
  ---
804
- *Technical Reference for DEXBot2 v1.6.11 release*
804
+ *Technical Reference for DEXBot2 v1.6.13 release*
@@ -279,7 +279,9 @@ in the same direction, so a 1–2 bar excursion is ignored. A sustained move is
279
279
  confirmed K bars after onset — up to K−1 bars later than the ungated trigger;
280
280
  the independent price/Drift trigger is unaffected.
281
281
  `AMA_SLOPE_PERSIST_ENABLED` (default `true`) is the master switch; a
282
- bot/market can override via `amaSlope.persistBars` or `amaSlope.persistEnabled`.
282
+ bot/market can override via `amaSlope.persistBars` (`>= 1` gate length, `0`
283
+ disables) or `amaSlope.persistEnabled: false`, which disables the gate for that
284
+ bot even while the global switch is on.
283
285
  Versus the ungated path this cuts resets ~35% and whipsaws (~52%→~17%) with lag
284
286
  and range tilt unchanged.
285
287
 
@@ -643,7 +645,7 @@ Removed trigger file.
643
645
 
644
646
  ## Visualizing the AMA Triggers (§3 and §4)
645
647
 
646
- `dexbot tv <bot>` (and `analysis/tradingview/analyze_tradingview.js`) replays the
648
+ `dexbot tv <bot>` (and `dist/analysis/tradingview/analyze_tradingview.js`) replays the
647
649
  two market-adapter recentering triggers over the chart's candle history and draws
648
650
  the accepted grid center, the range that center would own, and one marker per
649
651
  reset (amber = AMA-price Δ, cyan = AMA-slope Δ, grey = first snapshot). The
@@ -125,10 +125,21 @@ but likewise causes no plans to execute because no target remains present.
125
125
  This closes stale-cancellation replays without requiring the whole book to
126
126
  remain unchanged.
127
127
 
128
+ **Fresh-placement grace (`TIMING.SURPLUS_CANCEL_GRACE_MS`, 15 min):** surplus
129
+ and cancel-only cancellations also skip any order whose `orderId` was placed
130
+ inside the grace window. The timestamp is written by `recordOrderPlacement` into
131
+ `manager._placedAt` and tested with `isFreshlyPlacedOrder`; the reconciler's CANCEL
132
+ actions are filtered by `COWRebalanceEngine.execute`, which drops the whole slot's
133
+ action group (a paired CANCEL+CREATE must not lose only its CANCEL, or the CREATE
134
+ folds back into an UPDATE and re-materializes the placement) and re-syncs the
135
+ deferred slots from master via `workingGrid.syncFromMaster` before commit. The
136
+ order stays ACTIVE and is re-drained once the window expires. `grid-load`/
137
+ `grid-init` contexts are excluded so a restart does not suppress the sweep.
138
+
128
139
  Surplus settlement uses the same live-ownership decision. Only an order that is
129
- still untracked and signature-unchanged reaches `_cancelChainOrder`; a now-owned
130
- or geometry-changed order is skipped rather than released from the stale
131
- snapshot.
140
+ still untracked, signature-unchanged, and outside the fresh-placement grace
141
+ window reaches `_cancelChainOrder`; a now-owned or geometry-changed order is
142
+ skipped rather than released from the stale snapshot.
132
143
 
133
144
  **Updates:**
134
145
  - Batch via `_executeStartupUpdateBatch` when `supportsBatchUpdate` is available
package/docs/LIFECYCLE.md CHANGED
@@ -90,7 +90,7 @@ sequenceDiagram
90
90
  participant CO as chain_orders (broadcast)
91
91
  participant STORE as Storage
92
92
 
93
- CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:414)
93
+ CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:458)
94
94
  FR->>FR: drain queue -> _processFillsWithBatching
95
95
  FR->>OM: processFilledOrders() (manager.ts)
96
96
  OM->>AC: processFillAccounting() (single call, batch)
@@ -134,10 +134,10 @@ sequenceDiagram
134
134
  participant STORE as Storage
135
135
 
136
136
  MA->>CL: AMA center snapshot updated
137
- CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1673)
138
- CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1554)
139
- RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2770)
140
- RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:2270)
137
+ CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1685)
138
+ CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1645)
139
+ RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2944)
140
+ RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:2443)
141
141
  RT->>AC: recalculate funds from balances
142
142
  RT->>GD: promote AMA center -> grid center
143
143
  RT->>GD: recalculateGrid() (grid.ts)
@@ -157,13 +157,13 @@ The AMA signal stack (AMA/Kalman/Hurst/PE) is *research-tuned* in `analysis/` an
157
157
  the parameters.
158
158
 
159
159
  > Note: `runMaintenance()` is a **different** subsystem — the credit/MPA debt
160
- > runtime (`modules/credit_runtime.ts:3019`, reached via
161
- > `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1790`). The grid maintenance
160
+ > runtime (`modules/credit_runtime.ts:3468`, reached via
161
+ > `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1802`). The grid maintenance
162
162
  > chain above is the one that matters for order/price upkeep.
163
163
 
164
- References: `modules/dexbot_class.ts:1673` (`_performPeriodicGridChecks`) →
165
- `modules/dexbot_maintenance_runtime.ts:1554` (`performPeriodicGridChecks`) →
166
- `:1845` (`runGridMaintenance`) → `:1452` (`executeMaintenanceLogic`),
164
+ References: `modules/dexbot_class.ts:1685` (`_performPeriodicGridChecks`) →
165
+ `modules/dexbot_maintenance_runtime.ts:1645` (`performPeriodicGridChecks`) →
166
+ `:2944` (`runGridMaintenance`) → `:2443` (`executeMaintenanceLogic`),
167
167
  `docs/GRID_RECALCULATION.md`, `docs/GRID_RECONCILE.md`.
168
168
 
169
169
  ---
@@ -192,7 +192,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
192
192
  | How a fill becomes orders | `modules/dexbot_fill_runtime.ts` → `modules/order/manager.ts` |
193
193
  | Grid math / recalculation | `modules/order/grid.ts`, `docs/GRID_RECALCULATION.md` |
194
194
  | Funds & accounting | `modules/order/accounting.ts`, `docs/FUND_MOVEMENT_AND_ACCOUNTING.md` |
195
- | Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1673` |
195
+ | Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1685` |
196
196
  | Market signal source | `market_adapter/market_adapter.ts`, `analysis/README.md` |
197
197
  | Startup & orchestration | `modules/dexbot_class.ts`, `docs/developer_guide.md` §"Startup Sequence" |
198
198
  | Why COW exists | `docs/architecture.md` §"Copy-on-Write (COW) Grid Pattern", `docs/COW_INVARIANTS.md` |