dexbot 1.4.20 → 1.4.22

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 (674) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +23 -13
  3. package/analysis/ama_fitting/analyze_ama_price_changes.ts +7 -3
  4. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +3 -3
  5. package/analysis/ama_fitting/calibrate_convergence_er.ts +8 -6
  6. package/analysis/ama_fitting/fetch_lp_candles.ts +8 -3
  7. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +30 -67
  8. package/analysis/ama_fitting/optimizer_high_resolution.ts +22 -13
  9. package/analysis/ama_fitting/package.json +1 -1
  10. package/analysis/analyze_derivatives.ts +4 -4
  11. package/analysis/analyze_dynamic_weight.ts +21 -5
  12. package/analysis/analyze_kalman.ts +54 -25
  13. package/analysis/analyze_regime.ts +2 -2
  14. package/analysis/analyze_regime_windows.ts +27 -19
  15. package/analysis/analyze_risk_profile.ts +3 -3
  16. package/analysis/analyze_trade_heatmap.ts +3 -3
  17. package/analysis/analyze_volatility.ts +2 -2
  18. package/analysis/bot_fitting/README.md +93 -19
  19. package/analysis/bot_fitting/backtest_ama_sweep.ts +316 -199
  20. package/analysis/bot_fitting/backtest_bot_fitting.ts +520 -85
  21. package/analysis/bot_fitting/shared_utils.ts +16 -10
  22. package/analysis/bot_key_utils.ts +14 -11
  23. package/analysis/bot_usage/discover_bot_accounts.ts +5 -3
  24. package/analysis/bot_usage/kibana_bot_queries.ts +2 -257
  25. package/analysis/chart_css.ts +6 -4
  26. package/analysis/chart_ui.ts +0 -1
  27. package/analysis/chart_utils.ts +11 -2
  28. package/analysis/derivative_chart_generator.ts +2 -2
  29. package/analysis/math_utils.ts +1 -8
  30. package/analysis/price_sources.ts +8 -2
  31. package/analysis/resolve_source.ts +1 -1
  32. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +2455 -0
  33. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +218 -0
  34. package/analysis/trade_profitability.ts +61 -28
  35. package/analysis/tradingview/analyze_tradingview.ts +1 -1
  36. package/analysis/tradingview/h-bts_tradingview.html +1570 -0
  37. package/analysis/tradingview/t-bts_tradingview.html +1570 -0
  38. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +302 -74
  39. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  40. package/analysis/trend_detection/derivative_analyzer.ts +12 -3
  41. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +25 -27
  42. package/analysis/trend_detection/hurst_analyzer.ts +1 -1
  43. package/analysis/trend_detection/kalman_chart_generator.ts +42 -14
  44. package/analysis/trend_detection/package.json +1 -1
  45. package/analysis/trend_detection/regime_chart_generator.ts +39 -19
  46. package/analysis/trend_detection/tests/test_kalman_trend.ts +1 -1
  47. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +1 -1
  48. package/analysis/trend_detection/volatility_chart_generator.ts +1 -1
  49. package/claw/ecosystem.config.cjs +2 -3
  50. package/claw/examples/memu_integration_example.ts +17 -17
  51. package/claw/index.ts +1 -1
  52. package/claw/modules/chain_actions.ts +51 -54
  53. package/claw/modules/chain_broadcast.ts +66 -104
  54. package/claw/modules/claw_bridge.ts +63 -83
  55. package/claw/modules/claw_catalog.ts +48 -17
  56. package/claw/modules/claw_infra.ts +1 -5
  57. package/claw/modules/claw_launcher.ts +48 -50
  58. package/claw/modules/claw_skill_md.ts +15 -21
  59. package/claw/modules/credit_runtime_adapter.ts +3 -19
  60. package/claw/modules/decision_loop.ts +9 -9
  61. package/claw/modules/dexbot_bridge.ts +8 -8
  62. package/claw/modules/dexbot_profiles.ts +5 -21
  63. package/claw/modules/feed_price_source.ts +1 -1
  64. package/claw/modules/honest_ecosystem.ts +24 -8
  65. package/claw/modules/kibana_price_source.ts +1 -1
  66. package/claw/modules/launcher_mode_detector.ts +1 -1
  67. package/claw/modules/launcher_paths.ts +1 -1
  68. package/claw/modules/liquidity_pools.ts +10 -3
  69. package/claw/modules/mcp_utils.ts +109 -0
  70. package/claw/modules/memu_bridge.ts +76 -54
  71. package/claw/modules/mpa_utils.ts +26 -3
  72. package/claw/modules/position_discovery.ts +17 -28
  73. package/claw/modules/position_health.ts +1 -1
  74. package/claw/modules/position_manager.ts +32 -41
  75. package/claw/modules/position_manager_watch.ts +3 -2
  76. package/claw/modules/short_mpa_strategy.ts +1 -9
  77. package/claw/modules/skill_utils.ts +5 -3
  78. package/claw/modules/utils.ts +9 -1
  79. package/claw/package.json +3 -3
  80. package/claw/runtimes/openclaw-plugin/index.ts +27 -10
  81. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  82. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  83. package/claw/scripts/claw_bridge.ts +1 -1
  84. package/claw/scripts/claw_mcp_server.ts +19 -78
  85. package/claw/scripts/honest_assets_report.ts +19 -84
  86. package/claw/scripts/memu_mcp_server.ts +57 -155
  87. package/claw/skills/launcher-ops/references/launcher-workflow.md +2 -2
  88. package/claw/tests/package.json +1 -1
  89. package/claw/tests/test_claw_bridge.ts +47 -19
  90. package/claw/tests/test_claw_catalog_and_credentials.ts +8 -4
  91. package/claw/tests/test_claw_chain_layer.ts +39 -19
  92. package/claw/tests/test_claw_data_flow.ts +28 -20
  93. package/claw/tests/test_claw_domain_logic.ts +25 -19
  94. package/claw/tests/test_claw_manifest_and_matrix.ts +23 -3
  95. package/claw/tests/test_claw_mcp_transport.ts +13 -8
  96. package/claw/tests/test_claw_regressions.ts +254 -128
  97. package/claw/tests/test_claw_skill_generation.ts +1 -1
  98. package/claw/tests/test_nullclaw_tmp_integration.ts +2 -3
  99. package/claw/tests/test_position_health.ts +1 -77
  100. package/claw/tests/test_position_manager.ts +20 -18
  101. package/claw/tests/test_position_manager_watch_health.ts +39 -43
  102. package/claw/tests/test_short_mpa_strategy.ts +20 -17
  103. package/claw/tsconfig.json +4 -3
  104. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +7 -3
  105. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +1 -1
  106. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -3
  107. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +1 -1
  108. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +8 -6
  109. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +1 -1
  110. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -3
  111. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +1 -1
  112. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +2 -2
  113. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +1 -1
  114. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +31 -75
  115. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +1 -1
  116. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +1 -1
  117. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +21 -13
  118. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +1 -1
  119. package/dist/analysis/analyze_derivatives.d.ts +0 -18
  120. package/dist/analysis/analyze_derivatives.d.ts.map +1 -1
  121. package/dist/analysis/analyze_derivatives.js +4 -4
  122. package/dist/analysis/analyze_derivatives.js.map +1 -1
  123. package/dist/analysis/analyze_dynamic_weight.d.ts +0 -11
  124. package/dist/analysis/analyze_dynamic_weight.d.ts.map +1 -1
  125. package/dist/analysis/analyze_dynamic_weight.js +19 -5
  126. package/dist/analysis/analyze_dynamic_weight.js.map +1 -1
  127. package/dist/analysis/analyze_kalman.d.ts +0 -10
  128. package/dist/analysis/analyze_kalman.d.ts.map +1 -1
  129. package/dist/analysis/analyze_kalman.js +51 -26
  130. package/dist/analysis/analyze_kalman.js.map +1 -1
  131. package/dist/analysis/analyze_regime.d.ts +0 -17
  132. package/dist/analysis/analyze_regime.d.ts.map +1 -1
  133. package/dist/analysis/analyze_regime.js +2 -2
  134. package/dist/analysis/analyze_regime.js.map +1 -1
  135. package/dist/analysis/analyze_regime_windows.d.ts +0 -16
  136. package/dist/analysis/analyze_regime_windows.d.ts.map +1 -1
  137. package/dist/analysis/analyze_regime_windows.js +28 -21
  138. package/dist/analysis/analyze_regime_windows.js.map +1 -1
  139. package/dist/analysis/analyze_risk_profile.js +3 -3
  140. package/dist/analysis/analyze_risk_profile.js.map +1 -1
  141. package/dist/analysis/analyze_trade_heatmap.js +3 -3
  142. package/dist/analysis/analyze_trade_heatmap.js.map +1 -1
  143. package/dist/analysis/analyze_volatility.d.ts +0 -19
  144. package/dist/analysis/analyze_volatility.d.ts.map +1 -1
  145. package/dist/analysis/analyze_volatility.js +2 -2
  146. package/dist/analysis/analyze_volatility.js.map +1 -1
  147. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +30 -14
  148. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +1 -1
  149. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +330 -193
  150. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +1 -1
  151. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +136 -1
  152. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +1 -1
  153. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +527 -83
  154. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +1 -1
  155. package/dist/analysis/bot_fitting/shared_utils.d.ts +2 -13
  156. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +1 -1
  157. package/dist/analysis/bot_fitting/shared_utils.js +15 -9
  158. package/dist/analysis/bot_fitting/shared_utils.js.map +1 -1
  159. package/dist/analysis/bot_key_utils.d.ts +1 -1
  160. package/dist/analysis/bot_key_utils.d.ts.map +1 -1
  161. package/dist/analysis/bot_key_utils.js +14 -11
  162. package/dist/analysis/bot_key_utils.js.map +1 -1
  163. package/dist/analysis/bot_usage/discover_bot_accounts.js +5 -3
  164. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +1 -1
  165. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -337
  166. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +1 -1
  167. package/dist/analysis/bot_usage/kibana_bot_queries.js +2 -242
  168. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +1 -1
  169. package/dist/analysis/chart_css.d.ts +2 -14
  170. package/dist/analysis/chart_css.d.ts.map +1 -1
  171. package/dist/analysis/chart_css.js +6 -3
  172. package/dist/analysis/chart_css.js.map +1 -1
  173. package/dist/analysis/chart_ui.d.ts.map +1 -1
  174. package/dist/analysis/chart_ui.js.map +1 -1
  175. package/dist/analysis/chart_utils.d.ts.map +1 -1
  176. package/dist/analysis/chart_utils.js +15 -2
  177. package/dist/analysis/chart_utils.js.map +1 -1
  178. package/dist/analysis/derivative_chart_generator.js +2 -2
  179. package/dist/analysis/derivative_chart_generator.js.map +1 -1
  180. package/dist/analysis/math_utils.d.ts +3 -5
  181. package/dist/analysis/math_utils.d.ts.map +1 -1
  182. package/dist/analysis/math_utils.js +3 -5
  183. package/dist/analysis/math_utils.js.map +1 -1
  184. package/dist/analysis/price_sources.d.ts +1 -0
  185. package/dist/analysis/price_sources.d.ts.map +1 -1
  186. package/dist/analysis/price_sources.js +8 -2
  187. package/dist/analysis/price_sources.js.map +1 -1
  188. package/dist/analysis/resolve_source.d.ts.map +1 -1
  189. package/dist/analysis/resolve_source.js +1 -1
  190. package/dist/analysis/resolve_source.js.map +1 -1
  191. package/dist/analysis/trade_profitability.d.ts.map +1 -1
  192. package/dist/analysis/trade_profitability.js +58 -29
  193. package/dist/analysis/trade_profitability.js.map +1 -1
  194. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  195. package/dist/analysis/tradingview/analyze_tradingview.js.map +1 -1
  196. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +1 -1
  197. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +302 -74
  198. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +1 -1
  199. package/dist/analysis/trend_detection/derivative_analyzer.d.ts +1 -0
  200. package/dist/analysis/trend_detection/derivative_analyzer.d.ts.map +1 -1
  201. package/dist/analysis/trend_detection/derivative_analyzer.js +12 -3
  202. package/dist/analysis/trend_detection/derivative_analyzer.js.map +1 -1
  203. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -1
  204. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +26 -27
  205. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -1
  206. package/dist/analysis/trend_detection/hurst_analyzer.d.ts +1 -1
  207. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +1 -1
  208. package/dist/analysis/trend_detection/hurst_analyzer.js +1 -1
  209. package/dist/analysis/trend_detection/hurst_analyzer.js.map +1 -1
  210. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +1 -1
  211. package/dist/analysis/trend_detection/kalman_chart_generator.js +41 -13
  212. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +1 -1
  213. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +1 -1
  214. package/dist/analysis/trend_detection/regime_chart_generator.js +38 -19
  215. package/dist/analysis/trend_detection/regime_chart_generator.js.map +1 -1
  216. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +1 -1
  217. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +1 -1
  218. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +1 -1
  219. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +1 -1
  220. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -1
  221. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +1 -1
  222. package/dist/bot.js +3 -3
  223. package/dist/bot.js.map +1 -1
  224. package/dist/credential-daemon.d.ts +1 -1
  225. package/dist/credential-daemon.js +2 -2
  226. package/dist/credential-daemon.js.map +1 -1
  227. package/dist/dexbot.d.ts.map +1 -1
  228. package/dist/dexbot.js +25 -22
  229. package/dist/dexbot.js.map +1 -1
  230. package/dist/market_adapter/ama_signal_runner.js +6 -4
  231. package/dist/market_adapter/ama_signal_runner.js.map +1 -1
  232. package/dist/market_adapter/candle_utils.d.ts +1 -3
  233. package/dist/market_adapter/candle_utils.d.ts.map +1 -1
  234. package/dist/market_adapter/candle_utils.js +1 -11
  235. package/dist/market_adapter/candle_utils.js.map +1 -1
  236. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +1 -1
  237. package/dist/market_adapter/core/asymmetric_bounds.js +33 -30
  238. package/dist/market_adapter/core/asymmetric_bounds.js.map +1 -1
  239. package/dist/market_adapter/core/config_normalizers.d.ts.map +1 -1
  240. package/dist/market_adapter/core/config_normalizers.js +10 -1
  241. package/dist/market_adapter/core/config_normalizers.js.map +1 -1
  242. package/dist/market_adapter/core/kibana_candles.d.ts +18 -42
  243. package/dist/market_adapter/core/kibana_candles.d.ts.map +1 -1
  244. package/dist/market_adapter/core/kibana_candles.js +101 -7
  245. package/dist/market_adapter/core/kibana_candles.js.map +1 -1
  246. package/dist/market_adapter/core/kibana_client.d.ts +1 -17
  247. package/dist/market_adapter/core/kibana_client.d.ts.map +1 -1
  248. package/dist/market_adapter/core/kibana_client.js +40 -7
  249. package/dist/market_adapter/core/kibana_client.js.map +1 -1
  250. package/dist/market_adapter/core/kibana_market_candles.d.ts +0 -27
  251. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +1 -1
  252. package/dist/market_adapter/core/kibana_market_candles.js +1 -1
  253. package/dist/market_adapter/core/kibana_market_candles.js.map +1 -1
  254. package/dist/market_adapter/core/market_adapter_service.d.ts +22 -13
  255. package/dist/market_adapter/core/market_adapter_service.d.ts.map +1 -1
  256. package/dist/market_adapter/core/market_adapter_service.js +96 -38
  257. package/dist/market_adapter/core/market_adapter_service.js.map +1 -1
  258. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  259. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +1 -1
  260. package/dist/market_adapter/core/signals/hurst_analyzer.js +28 -17
  261. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +1 -1
  262. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts +5 -0
  263. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +1 -1
  264. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js +24 -24
  265. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +1 -1
  266. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +1 -1
  267. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js +5 -1
  268. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +1 -1
  269. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +1 -1
  270. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +20 -3
  271. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +1 -1
  272. package/dist/market_adapter/core/strategies/ama.js +1 -1
  273. package/dist/market_adapter/core/strategies/ama.js.map +1 -1
  274. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  275. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +1 -1
  276. package/dist/market_adapter/core/strategies/ama_slope_model.js +16 -4
  277. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +1 -1
  278. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +4 -3
  279. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +1 -1
  280. package/dist/market_adapter/core/strategies/atr/calculator.js +16 -8
  281. package/dist/market_adapter/core/strategies/atr/calculator.js.map +1 -1
  282. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +1 -1
  283. package/dist/market_adapter/core/strategies/collateral_manager.js +8 -3
  284. package/dist/market_adapter/core/strategies/collateral_manager.js.map +1 -1
  285. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +40 -1
  286. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +1 -1
  287. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +116 -2
  288. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +1 -1
  289. package/dist/market_adapter/core/strategies/regime_gate.d.ts +1 -2
  290. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +1 -1
  291. package/dist/market_adapter/core/strategies/regime_gate.js +27 -21
  292. package/dist/market_adapter/core/strategies/regime_gate.js.map +1 -1
  293. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +1 -1
  294. package/dist/market_adapter/core/strategies/volatility_shift.js +3 -0
  295. package/dist/market_adapter/core/strategies/volatility_shift.js.map +1 -1
  296. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +71 -57
  297. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +1 -1
  298. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +0 -26
  299. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +1 -1
  300. package/dist/market_adapter/inputs/fetch_lp_data.js +72 -19
  301. package/dist/market_adapter/inputs/fetch_lp_data.js.map +1 -1
  302. package/dist/market_adapter/inputs/kibana_source.d.ts +5 -30
  303. package/dist/market_adapter/inputs/kibana_source.d.ts.map +1 -1
  304. package/dist/market_adapter/inputs/kibana_source.js +6 -3
  305. package/dist/market_adapter/inputs/kibana_source.js.map +1 -1
  306. package/dist/market_adapter/lp_chart_core.js +1 -1
  307. package/dist/market_adapter/lp_chart_core.js.map +1 -1
  308. package/dist/market_adapter/lp_chart_runner.d.ts +10 -1
  309. package/dist/market_adapter/lp_chart_runner.d.ts.map +1 -1
  310. package/dist/market_adapter/lp_chart_runner.js +2 -2
  311. package/dist/market_adapter/lp_chart_runner.js.map +1 -1
  312. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +1 -2
  313. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +1 -1
  314. package/dist/market_adapter/lp_chart_strategy_loader.js +5 -5
  315. package/dist/market_adapter/lp_chart_strategy_loader.js.map +1 -1
  316. package/dist/market_adapter/market_adapter.d.ts +1 -2
  317. package/dist/market_adapter/market_adapter.d.ts.map +1 -1
  318. package/dist/market_adapter/market_adapter.js +5 -7
  319. package/dist/market_adapter/market_adapter.js.map +1 -1
  320. package/dist/market_adapter/test_helpers.d.ts +3 -3
  321. package/dist/market_adapter/test_helpers.d.ts.map +1 -1
  322. package/dist/market_adapter/test_helpers.js +3 -3
  323. package/dist/market_adapter/test_helpers.js.map +1 -1
  324. package/dist/market_adapter/utils/adapter_client.js +1 -1
  325. package/dist/market_adapter/utils/adapter_client.js.map +1 -1
  326. package/dist/market_adapter/utils/atomic_write.js +1 -1
  327. package/dist/market_adapter/utils/atomic_write.js.map +1 -1
  328. package/dist/market_adapter/utils/chain.d.ts +0 -2
  329. package/dist/market_adapter/utils/chain.d.ts.map +1 -1
  330. package/dist/market_adapter/utils/chain.js +2 -3
  331. package/dist/market_adapter/utils/chain.js.map +1 -1
  332. package/dist/market_adapter/utils/data_discovery.d.ts.map +1 -1
  333. package/dist/market_adapter/utils/data_discovery.js +24 -8
  334. package/dist/market_adapter/utils/data_discovery.js.map +1 -1
  335. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +1 -1
  336. package/dist/market_adapter/utils/dynamic_grid_snapshot.js +2 -5
  337. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +1 -1
  338. package/dist/market_adapter/utils/file_lock.d.ts +4 -1
  339. package/dist/market_adapter/utils/file_lock.d.ts.map +1 -1
  340. package/dist/market_adapter/utils/file_lock.js +89 -25
  341. package/dist/market_adapter/utils/file_lock.js.map +1 -1
  342. package/dist/market_adapter/utils/native_history.d.ts.map +1 -1
  343. package/dist/market_adapter/utils/native_history.js +5 -1
  344. package/dist/market_adapter/utils/native_history.js.map +1 -1
  345. package/dist/modules/account_bots.d.ts +3 -0
  346. package/dist/modules/account_bots.d.ts.map +1 -1
  347. package/dist/modules/account_bots.js +157 -47
  348. package/dist/modules/account_bots.js.map +1 -1
  349. package/dist/modules/account_orders.d.ts +1 -7
  350. package/dist/modules/account_orders.d.ts.map +1 -1
  351. package/dist/modules/account_orders.js +9 -17
  352. package/dist/modules/account_orders.js.map +1 -1
  353. package/dist/modules/authority_resolver.js +1 -1
  354. package/dist/modules/authority_resolver.js.map +1 -1
  355. package/dist/modules/bitshares-native/chain_client.js +1 -1
  356. package/dist/modules/bitshares-native/chain_client.js.map +1 -1
  357. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts +0 -12
  358. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +1 -1
  359. package/dist/modules/bitshares-native/crypto/ecc.browser.js +1 -1
  360. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +1 -1
  361. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -1
  362. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +1 -1
  363. package/dist/modules/bitshares-native/index.d.ts.map +1 -1
  364. package/dist/modules/bitshares-native/index.js +1 -1
  365. package/dist/modules/bitshares-native/index.js.map +1 -1
  366. package/dist/modules/bitshares-native/lru_cache.js +1 -1
  367. package/dist/modules/bitshares-native/lru_cache.js.map +1 -1
  368. package/dist/modules/bitshares-native/resolvers.d.ts +0 -2
  369. package/dist/modules/bitshares-native/resolvers.d.ts.map +1 -1
  370. package/dist/modules/bitshares-native/resolvers.js +18 -4
  371. package/dist/modules/bitshares-native/resolvers.js.map +1 -1
  372. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -1
  373. package/dist/modules/bitshares-native/serial/chain_constants.js.map +1 -1
  374. package/dist/modules/bitshares-native/serial/index.d.ts.map +1 -1
  375. package/dist/modules/bitshares-native/serial/index.js +1 -1
  376. package/dist/modules/bitshares-native/serial/index.js.map +1 -1
  377. package/dist/modules/bitshares-native/serial/operations.js +1 -1
  378. package/dist/modules/bitshares-native/serial/operations.js.map +1 -1
  379. package/dist/modules/bitshares-native/serial/serializer.js +1 -1
  380. package/dist/modules/bitshares-native/serial/serializer.js.map +1 -1
  381. package/dist/modules/bitshares-native/serial/types.js +1 -1
  382. package/dist/modules/bitshares-native/serial/types.js.map +1 -1
  383. package/dist/modules/bitshares-native/signing_client.js +2 -2
  384. package/dist/modules/bitshares-native/signing_client.js.map +1 -1
  385. package/dist/modules/bitshares-native/subscriptions.d.ts.map +1 -1
  386. package/dist/modules/bitshares-native/subscriptions.js +5 -14
  387. package/dist/modules/bitshares-native/subscriptions.js.map +1 -1
  388. package/dist/modules/bitshares-native/transport.js +1 -1
  389. package/dist/modules/bitshares-native/transport.js.map +1 -1
  390. package/dist/modules/bitshares-native/tx/builder.js +1 -1
  391. package/dist/modules/bitshares-native/tx/builder.js.map +1 -1
  392. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +3 -2
  393. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +1 -1
  394. package/dist/modules/bitshares-native/tx/tx_cache.js +7 -4
  395. package/dist/modules/bitshares-native/tx/tx_cache.js.map +1 -1
  396. package/dist/modules/bitshares_client.d.ts +2 -14
  397. package/dist/modules/bitshares_client.d.ts.map +1 -1
  398. package/dist/modules/bitshares_client.js +32 -41
  399. package/dist/modules/bitshares_client.js.map +1 -1
  400. package/dist/modules/bot_settings.d.ts.map +1 -1
  401. package/dist/modules/bot_settings.js +12 -19
  402. package/dist/modules/bot_settings.js.map +1 -1
  403. package/dist/modules/bots_file_lock.d.ts +1 -1
  404. package/dist/modules/bots_file_lock.js +1 -1
  405. package/dist/modules/broadcast_failure.d.ts +13 -0
  406. package/dist/modules/broadcast_failure.d.ts.map +1 -1
  407. package/dist/modules/broadcast_failure.js +0 -13
  408. package/dist/modules/broadcast_failure.js.map +1 -1
  409. package/dist/modules/chain_keys.js +2 -2
  410. package/dist/modules/chain_keys.js.map +1 -1
  411. package/dist/modules/chain_orders.d.ts +2 -3
  412. package/dist/modules/chain_orders.d.ts.map +1 -1
  413. package/dist/modules/chain_orders.js +23 -42
  414. package/dist/modules/chain_orders.js.map +1 -1
  415. package/dist/modules/config.d.ts.map +1 -1
  416. package/dist/modules/config.js +5 -2
  417. package/dist/modules/config.js.map +1 -1
  418. package/dist/modules/constants.d.ts +21 -21
  419. package/dist/modules/constants.d.ts.map +1 -1
  420. package/dist/modules/constants.js +53 -60
  421. package/dist/modules/constants.js.map +1 -1
  422. package/dist/modules/cr_planner.d.ts +1 -7
  423. package/dist/modules/cr_planner.d.ts.map +1 -1
  424. package/dist/modules/cr_planner.js +3 -77
  425. package/dist/modules/cr_planner.js.map +1 -1
  426. package/dist/modules/credential_policy.d.ts +0 -4
  427. package/dist/modules/credential_policy.d.ts.map +1 -1
  428. package/dist/modules/credential_policy.js +18 -3
  429. package/dist/modules/credential_policy.js.map +1 -1
  430. package/dist/modules/credit_runtime.d.ts +0 -7
  431. package/dist/modules/credit_runtime.d.ts.map +1 -1
  432. package/dist/modules/credit_runtime.js +21 -60
  433. package/dist/modules/credit_runtime.js.map +1 -1
  434. package/dist/modules/crypto/index.d.ts +0 -2
  435. package/dist/modules/crypto/index.d.ts.map +1 -1
  436. package/dist/modules/crypto/index.js +0 -2
  437. package/dist/modules/crypto/index.js.map +1 -1
  438. package/dist/modules/crypto/sync.js.map +1 -1
  439. package/dist/modules/daemon_node_health.js +1 -1
  440. package/dist/modules/daemon_node_health.js.map +1 -1
  441. package/dist/modules/dexbot_class.d.ts +8 -134
  442. package/dist/modules/dexbot_class.d.ts.map +1 -1
  443. package/dist/modules/dexbot_class.js +39 -199
  444. package/dist/modules/dexbot_class.js.map +1 -1
  445. package/dist/modules/dexbot_credential_client.js +1 -1
  446. package/dist/modules/dexbot_credential_client.js.map +1 -1
  447. package/dist/modules/dexbot_fill_runtime.d.ts.map +1 -1
  448. package/dist/modules/dexbot_fill_runtime.js +3 -6
  449. package/dist/modules/dexbot_fill_runtime.js.map +1 -1
  450. package/dist/modules/dexbot_maintenance_runtime.d.ts +6 -34
  451. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -1
  452. package/dist/modules/dexbot_maintenance_runtime.js +27 -19
  453. package/dist/modules/dexbot_maintenance_runtime.js.map +1 -1
  454. package/dist/modules/dexbot_startup_runtime.d.ts.map +1 -1
  455. package/dist/modules/dexbot_startup_runtime.js +31 -15
  456. package/dist/modules/dexbot_startup_runtime.js.map +1 -1
  457. package/dist/modules/dexbot_state_recovery.d.ts +2 -2
  458. package/dist/modules/dexbot_state_recovery.d.ts.map +1 -1
  459. package/dist/modules/dexbot_state_recovery.js +11 -7
  460. package/dist/modules/dexbot_state_recovery.js.map +1 -1
  461. package/dist/modules/fund_registry.d.ts.map +1 -1
  462. package/dist/modules/fund_registry.js +24 -6
  463. package/dist/modules/fund_registry.js.map +1 -1
  464. package/dist/modules/general_settings.d.ts +1 -2
  465. package/dist/modules/general_settings.d.ts.map +1 -1
  466. package/dist/modules/general_settings.js +1 -2
  467. package/dist/modules/general_settings.js.map +1 -1
  468. package/dist/modules/graceful_shutdown.d.ts.map +1 -1
  469. package/dist/modules/graceful_shutdown.js +10 -1
  470. package/dist/modules/graceful_shutdown.js.map +1 -1
  471. package/dist/modules/grid_price_source.d.ts +19 -0
  472. package/dist/modules/grid_price_source.d.ts.map +1 -0
  473. package/dist/modules/grid_price_source.js +23 -0
  474. package/dist/modules/grid_price_source.js.map +1 -0
  475. package/dist/modules/key_store.d.ts +0 -5
  476. package/dist/modules/key_store.d.ts.map +1 -1
  477. package/dist/modules/key_store.js +1 -14
  478. package/dist/modules/key_store.js.map +1 -1
  479. package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -1
  480. package/dist/modules/launcher/bot_supervisor.js +15 -26
  481. package/dist/modules/launcher/bot_supervisor.js.map +1 -1
  482. package/dist/modules/launcher/child_env.d.ts +1 -2
  483. package/dist/modules/launcher/child_env.d.ts.map +1 -1
  484. package/dist/modules/launcher/child_env.js +1 -1
  485. package/dist/modules/launcher/child_env.js.map +1 -1
  486. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -1
  487. package/dist/modules/launcher/foreign_cred_daemon.js +7 -13
  488. package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -1
  489. package/dist/modules/launcher/market_adapter_runtime.d.ts +3 -4
  490. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -1
  491. package/dist/modules/launcher/market_adapter_runtime.js +10 -29
  492. package/dist/modules/launcher/market_adapter_runtime.js.map +1 -1
  493. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +1 -1
  494. package/dist/modules/launcher/market_adapter_watchdog.js +3 -2
  495. package/dist/modules/launcher/market_adapter_watchdog.js.map +1 -1
  496. package/dist/modules/launcher/monolithic_runtime.d.ts +0 -1
  497. package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -1
  498. package/dist/modules/launcher/monolithic_runtime.js +4 -18
  499. package/dist/modules/launcher/monolithic_runtime.js.map +1 -1
  500. package/dist/modules/launcher/runtime_entry.d.ts.map +1 -1
  501. package/dist/modules/launcher/runtime_entry.js +4 -5
  502. package/dist/modules/launcher/runtime_entry.js.map +1 -1
  503. package/dist/modules/launcher/status_reporting.d.ts +1 -2
  504. package/dist/modules/launcher/status_reporting.d.ts.map +1 -1
  505. package/dist/modules/launcher/status_reporting.js +2 -5
  506. package/dist/modules/launcher/status_reporting.js.map +1 -1
  507. package/dist/modules/launcher/supervisor_control.js +1 -1
  508. package/dist/modules/launcher/supervisor_control.js.map +1 -1
  509. package/dist/modules/market_adapter_whitelist.d.ts +2 -2
  510. package/dist/modules/market_adapter_whitelist.d.ts.map +1 -1
  511. package/dist/modules/market_adapter_whitelist.js +12 -6
  512. package/dist/modules/market_adapter_whitelist.js.map +1 -1
  513. package/dist/modules/node_failure_ledger.d.ts +23 -0
  514. package/dist/modules/node_failure_ledger.d.ts.map +1 -1
  515. package/dist/modules/node_failure_ledger.js +0 -23
  516. package/dist/modules/node_failure_ledger.js.map +1 -1
  517. package/dist/modules/node_manager.d.ts.map +1 -1
  518. package/dist/modules/node_manager.js +3 -3
  519. package/dist/modules/node_manager.js.map +1 -1
  520. package/dist/modules/order/accounting.js +3 -3
  521. package/dist/modules/order/accounting.js.map +1 -1
  522. package/dist/modules/order/async_lock.d.ts +6 -0
  523. package/dist/modules/order/async_lock.d.ts.map +1 -1
  524. package/dist/modules/order/async_lock.js +11 -0
  525. package/dist/modules/order/async_lock.js.map +1 -1
  526. package/dist/modules/order/export.d.ts +1 -1
  527. package/dist/modules/order/export.js +10 -10
  528. package/dist/modules/order/export.js.map +1 -1
  529. package/dist/modules/order/format.d.ts +1 -8
  530. package/dist/modules/order/format.d.ts.map +1 -1
  531. package/dist/modules/order/format.js +0 -14
  532. package/dist/modules/order/format.js.map +1 -1
  533. package/dist/modules/order/grid.d.ts +2 -12
  534. package/dist/modules/order/grid.d.ts.map +1 -1
  535. package/dist/modules/order/grid.js +23 -24
  536. package/dist/modules/order/grid.js.map +1 -1
  537. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  538. package/dist/modules/order/grid_reconcile.js +1 -1
  539. package/dist/modules/order/grid_reconcile_internal.js +1 -1
  540. package/dist/modules/order/grid_reconcile_internal.js.map +1 -1
  541. package/dist/modules/order/logger.d.ts +3 -0
  542. package/dist/modules/order/logger.d.ts.map +1 -1
  543. package/dist/modules/order/logger.js +23 -14
  544. package/dist/modules/order/logger.js.map +1 -1
  545. package/dist/modules/order/logger_state.d.ts +5 -22
  546. package/dist/modules/order/logger_state.d.ts.map +1 -1
  547. package/dist/modules/order/logger_state.js +6 -25
  548. package/dist/modules/order/logger_state.js.map +1 -1
  549. package/dist/modules/order/manager.d.ts +1 -4
  550. package/dist/modules/order/manager.d.ts.map +1 -1
  551. package/dist/modules/order/manager.js +34 -33
  552. package/dist/modules/order/manager.js.map +1 -1
  553. package/dist/modules/order/processed_fill_store.d.ts +0 -5
  554. package/dist/modules/order/processed_fill_store.d.ts.map +1 -1
  555. package/dist/modules/order/processed_fill_store.js +10 -15
  556. package/dist/modules/order/processed_fill_store.js.map +1 -1
  557. package/dist/modules/order/strategy.d.ts +6 -4
  558. package/dist/modules/order/strategy.d.ts.map +1 -1
  559. package/dist/modules/order/strategy.js +6 -4
  560. package/dist/modules/order/strategy.js.map +1 -1
  561. package/dist/modules/order/sync_engine.d.ts.map +1 -1
  562. package/dist/modules/order/sync_engine.js +17 -10
  563. package/dist/modules/order/sync_engine.js.map +1 -1
  564. package/dist/modules/order/utils/math.d.ts +7 -1
  565. package/dist/modules/order/utils/math.d.ts.map +1 -1
  566. package/dist/modules/order/utils/math.js +19 -1
  567. package/dist/modules/order/utils/math.js.map +1 -1
  568. package/dist/modules/order/utils/order.d.ts.map +1 -1
  569. package/dist/modules/order/utils/order.js +11 -4
  570. package/dist/modules/order/utils/order.js.map +1 -1
  571. package/dist/modules/order/utils/system.d.ts +3 -8
  572. package/dist/modules/order/utils/system.d.ts.map +1 -1
  573. package/dist/modules/order/utils/system.js +14 -4
  574. package/dist/modules/order/utils/system.js.map +1 -1
  575. package/dist/modules/order/utils/validate.js +1 -1
  576. package/dist/modules/order/utils/validate.js.map +1 -1
  577. package/dist/modules/path_api.js +1 -1
  578. package/dist/modules/path_api.js.map +1 -1
  579. package/dist/modules/paths.d.ts +1 -7
  580. package/dist/modules/paths.d.ts.map +1 -1
  581. package/dist/modules/paths.js +1 -1
  582. package/dist/modules/paths.js.map +1 -1
  583. package/dist/modules/process_discovery.d.ts +3 -0
  584. package/dist/modules/process_discovery.d.ts.map +1 -1
  585. package/dist/modules/process_discovery.js +15 -1
  586. package/dist/modules/process_discovery.js.map +1 -1
  587. package/dist/modules/runtime_settings.js +4 -2
  588. package/dist/modules/runtime_settings.js.map +1 -1
  589. package/dist/modules/settings_merge.d.ts +5 -1
  590. package/dist/modules/settings_merge.d.ts.map +1 -1
  591. package/dist/modules/settings_merge.js +17 -4
  592. package/dist/modules/settings_merge.js.map +1 -1
  593. package/dist/modules/socket_json_client.d.ts.map +1 -1
  594. package/dist/modules/socket_json_client.js +12 -2
  595. package/dist/modules/socket_json_client.js.map +1 -1
  596. package/dist/modules/storage/browser_adapter.d.ts +8 -3
  597. package/dist/modules/storage/browser_adapter.d.ts.map +1 -1
  598. package/dist/modules/storage/browser_adapter.js +58 -7
  599. package/dist/modules/storage/browser_adapter.js.map +1 -1
  600. package/dist/modules/storage/index.d.ts +1 -1
  601. package/dist/modules/storage/index.js +1 -1
  602. package/dist/modules/types.d.ts +1 -1
  603. package/dist/modules/types.d.ts.map +1 -1
  604. package/dist/modules/utils/sanitize_key.d.ts +7 -0
  605. package/dist/modules/utils/sanitize_key.d.ts.map +1 -0
  606. package/dist/modules/utils/sanitize_key.js +15 -0
  607. package/dist/modules/utils/sanitize_key.js.map +1 -0
  608. package/dist/modules/validate_profiles.d.ts.map +1 -1
  609. package/dist/modules/validate_profiles.js +6 -8
  610. package/dist/modules/validate_profiles.js.map +1 -1
  611. package/dist/pm2.d.ts.map +1 -1
  612. package/dist/pm2.js +8 -9
  613. package/dist/pm2.js.map +1 -1
  614. package/dist/scripts/analyze-git.d.ts +1 -1
  615. package/dist/scripts/analyze-git.js +1 -1
  616. package/dist/scripts/analyze-orders.d.ts +2 -2
  617. package/dist/scripts/analyze-orders.d.ts.map +1 -1
  618. package/dist/scripts/analyze-orders.js +39 -28
  619. package/dist/scripts/analyze-orders.js.map +1 -1
  620. package/dist/scripts/diagnose-pool-history.js +1 -1
  621. package/dist/scripts/divergence-calc.d.ts +1 -1
  622. package/dist/scripts/divergence-calc.js +3 -3
  623. package/dist/scripts/native_release_gates.js +4 -2
  624. package/dist/scripts/native_release_gates.js.map +1 -1
  625. package/dist/scripts/print_grid.d.ts +1 -1
  626. package/dist/scripts/print_grid.js +1 -1
  627. package/dist/scripts/run-tests.js +38 -19
  628. package/dist/scripts/run-tests.js.map +1 -1
  629. package/dist/scripts/runner.d.ts +3 -5
  630. package/dist/scripts/runner.d.ts.map +1 -1
  631. package/dist/scripts/runner.js +4 -6
  632. package/dist/scripts/runner.js.map +1 -1
  633. package/dist/scripts/sync-version.d.ts +2 -2
  634. package/dist/scripts/sync-version.js +2 -2
  635. package/dist/scripts/update.d.ts +1 -1
  636. package/dist/scripts/update.js +2 -2
  637. package/dist/scripts/update.js.map +1 -1
  638. package/dist/scripts/validate_bots.d.ts +1 -1
  639. package/dist/scripts/validate_bots.js +1 -1
  640. package/dist/scripts/verify-browser-bundle.d.ts +1 -1
  641. package/dist/scripts/verify-browser-bundle.js +1 -1
  642. package/dist/unlock.js +4 -4
  643. package/dist/unlock.js.map +1 -1
  644. package/docs/BITSHARES_ONBOARDING.md +63 -18
  645. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +14 -23
  646. package/docs/COW_INVARIANTS.md +4 -4
  647. package/docs/CREDENTIAL_SECURITY.md +0 -11
  648. package/docs/DEXBOT_COMPARISON.md +12 -12
  649. package/docs/EVOLUTION.md +17 -43
  650. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +27 -83
  651. package/docs/GRID_RECALCULATION.md +1 -13
  652. package/docs/GRID_RECONCILE.md +24 -24
  653. package/docs/LIFECYCLE.md +4 -4
  654. package/docs/LOGGING.md +1 -1
  655. package/docs/MPA_CREDIT_USAGE.md +3 -3
  656. package/docs/README.md +2 -2
  657. package/docs/WORKFLOW.md +2 -2
  658. package/docs/architecture.md +48 -43
  659. package/docs/developer_guide.md +22 -24
  660. package/market_adapter/README.md +0 -2
  661. package/modules/README.md +2 -1
  662. package/package.json +22 -14
  663. package/scripts/README.md +34 -8
  664. package/scripts/clean-dist.js +10 -2
  665. package/tests/README.md +4 -3
  666. package/claw/openclaw.plugin.json +0 -13
  667. package/dist/market_adapter/merge_lp_data.d.ts +0 -3
  668. package/dist/market_adapter/merge_lp_data.d.ts.map +0 -1
  669. package/dist/market_adapter/merge_lp_data.js +0 -125
  670. package/dist/market_adapter/merge_lp_data.js.map +0 -1
  671. package/dist/market_adapter/utils/paths.d.ts +0 -3
  672. package/dist/market_adapter/utils/paths.d.ts.map +0 -1
  673. package/dist/market_adapter/utils/paths.js +0 -5
  674. package/dist/market_adapter/utils/paths.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,59 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.4.22] - 2026-08-25 - tsx Removal Completion, Exact AMA Bootstrap, Research Parity, Canonical Grid Bounds, Modules-Wide Audit
6
+
7
+ ### 2026-08-26
8
+
9
+ - **Feat(analysis)**: TradingView-style price-axis interaction in the tradingview chart exporter — mouse wheel over the right price gutter zooms Y around the cursor (0.91/1.10 factors) and a vertical drag on the axis sets a manual Y range (multiplicative on log scale, additive offset otherwise), while double-clicking the axis restores auto-fit through the existing `visiblePriceRange` range callback; the plot area keeps pure time pan/zoom via `UPLOT_SHARED_SCRIPT` using page-local hoisted overrides so the shared script stays untouched, axis hit-testing uses `chart.bbox` geometry (the `.u-over` overlay spans the axis gutters too), the manual range resets automatically when dataset/timeframe/pair changes (sticky-manual guard keyed on first-time:last-time:count), and the price axis renders larger labels at a fixed 84px width matching the volume axis (`analysis/tradingview/tradingview_uplot_chart_generator.ts`).
10
+ - **Fix(market-adapter)**: keep Kibana LP fetches alive under proxy connection resets — the kibana.bitshares.dev console proxy kills responses mid-transfer once a single search page streams enough data (~8k docs with full `_source`, observed even at ~2k with `_source: true`), and `doKibanaRequest` only listened for request-phase errors, so an aborted response body left the promise pending forever and `fetch_lp_data` hung silently with no retry; the response stream now settles exactly once on 'aborted'/'error' with an actionable message, candle queries send a minimal `_source` projection derived from the field map (legacy `_source: true` preserved when no projection is passed), default page size drops 10000 → 2000, and transient page failures (aborted/reset/socket/timeout) retry up to `kibanaPageRetries` attempts (4) with linear backoff — safe because search_after pagination is stateless server-side; adapted from upstream contribution bitshares/DEXBot2#4 / froooze/DEXBot2#12 (`market_adapter/core/kibana_client.ts`, `market_adapter/core/kibana_candles.ts`, new `tests/test_kibana_candles.ts`).
11
+ - **Refactor(analysis)**: dedupe tradingview fork CSS fragments and zoom-pan stack — the fork hand-cloned zoom/pan logic shared by every other uPlot generator and re-wrote a CSS fragment with identical shape: chart_css export surface narrowed to `sharedChartCSS`/`uplotBgCSS`/`cursorCSS` (dead fragments un-exported, `uplotBgCSS` gains an optional bg color parameter keeping the default), the `.uplot` background rule is interpolated via `uplotBgCSS('#0b0f14')`, local clampRange/syncXRange/bindWheelZoom/bindPan clones plus a bespoke Ctrl+0 handler are replaced by embedding `UPLOT_SHARED_SCRIPT`/`zoomResetScript()` (~90 lines removed) with xMin/xMax maintained in buildData per contract (`analysis/chart_css.ts`, `analysis/tradingview/tradingview_uplot_chart_generator.ts`, `analysis/chart_ui.ts`).
12
+ - **Feat(analysis)**: model bot fitting backtests on the production grid lifecycle — both simulators previously ranked parameters by unrealized inventory marks (>99% phantom profit from cross-gap pair differentials no live slot earns); they now run production-style SLOT ROTATION on `createOrderGrid` geometry where scoring counts realized economics only: a filled buy arms the next rail-node sell booking one hop minus round-trip fees with the freed quote re-bidding behind it, out-of-range falls back to x(1±inc), initial-grid sells execute only against held base at weighted-average entry, production reset triggers fire from MARKET_ADAPTER constants (drift ratchet + slope delta gated behind the asymmetric-bounds whitelist like production) cancelling all orders with fees, BTS op fees are charged at every placement and reset cancel, drawdown tracks realized equity only, and the end-of-run inventory mark is informational/excluded from score; backtest_ama_sweep ports its sized worker simulation to the same model fixing a worker-result race (`analysis/bot_fitting/*`, `tests/test_backtest_ama_sweep_logic.ts`, new `tests/test_backtest_bot_fitting_logic.ts`).
13
+ - **Refactor(analysis)**: align research tools with market_adapter sources to stop signal drift — kalman_chart_generator computes the dynamic-weight channel via the canonical `computeDynamicWeightSeries`/percentile threshold with live config rendered in the legend, regime_chart_generator sources windows/thresholds/boundaries from MARKET_ADAPTER matching `classifyHurst` instead of drifted local copies, dynamic_weight_chart_generator yields Infinity from empty percentile pools like the live path and fixes an axis tick color typo, generate_unified_comparison_chart reuses `findLatestLpData`/`calculateMetrics` from lp_chart_runner, and optimizer_high_resolution/analyzer imports consolidated onto canonical implementations — behavioral changes only where the drifted copies were wrong (`analysis/trend_detection/*_chart_generator.ts`, `analysis/ama_fitting/*`, `market_adapter/lp_chart_runner.ts`).
14
+ - **Fix(analysis)**: correct research-tooling bugs surfaced by a full folder audit — analyze_regime_windows paired Hurst/PE bands sliced from different readiness offsets shifting classification into RANDOM|undefined regimes (now strictly per-bar via the production `classifyHurst` with MARKET_ADAPTER knobs); trade_profitability time bounds went through blind string surgery producing invalid dates for offset ISO strings, date-only --end dropped the final day, zero-amount fills poisoned LIFO lots with infinite prices, and `--fee-per-order 0` was ignored (proper Date parsing, end-of-day expansion, positive-amount guard, nullable fee override); analyze_kalman's --q conflated tactical/modal values with divergent defaults (split into --q-tactical/--q-modal falling through to production); derivative_analyzer used macdMinHist as both histogram threshold and MACD line gate so explicit 0 was ignored; fetch_lp_candles rejects non-numeric --interval instead of NaN-ing requests; discover_bot_accounts uses the node management pool instead of a hardcoded websocket endpoint; price_sources resolves the centers filename through PATHS.MARKET_ADAPTER (`analysis/analyze_regime_windows.ts`, `analysis/trade_profitability.ts`, `analysis/analyze_kalman.ts`, `analysis/trend_detection/derivative_analyzer.ts`, `analysis/ama_fitting/fetch_lp_candles.ts`, `analysis/bot_usage/discover_bot_accounts.ts`, `analysis/price_sources.ts`, `tests/test_trade_profitability.ts`).
15
+ - **Fix(modules)**: correct runtime defects from a modules-wide audit — `accounting.ts` null-guards the fund-invariant baseline so a missing snapshot degrades safe instead of NaN-comparing; `credit_runtime.ts` resolves full accounts wrapper-first, unifies LP collateral-ratio math on `collateralValueInDebtAsset / borrowAmountFloat` across offer and maintenance paths, drops a stale `pendingRepayAmount` when reborrow policies change, requires all groups resolved before prune treats missing deals as closed, honors lowercase `TIMING.*` overrides for credit-deal expiry thresholds, and passes explicit null defaults at nullable numeric reads; `chain_orders.ts` sends the correctly-named `collateral_asset`/`collateral_amount` fields for `includeCreditDeals`, stops caching null resolutions in asset/order resolvers, scopes `listenForFills` prefetch to subscribed accounts, and fetches `get_full_accounts` once per cycle extracting the account id from `full[0][1]`; `dexbot_class.ts` single-flights shutdown flush through a promise holder so concurrent shutdown requests share one drain and awaits `fundRegistry.releaseAllocation` before exit; `dexbot_state_recovery.ts` keys batch abort on the live illegal-state signal (`consumeIllegalStateSignal()`) instead of an error code nothing emits, mirroring the maintenance-path recovery contract; `dexbot_startup_runtime.ts` runs credit-runtime maintenance on the trigger-reset branch like every other reset path; `graceful_shutdown.ts` bounds each cleanup handler at 10s (resolve-mode) instead of one global race that could starve later handlers; `settings_merge.ts` deep-merges EXPERT `GRID_LIMITS.GRID_COMPARISON` over the prior subtree so partial expert overrides keep untouched comparison keys and scalar overrides are ignored rather than char-spreading; `credential_policy.ts` merges policy layers per-op so partial `allowedOps` constraints no longer replace the builtin op map, and skips `__proto__`/`constructor`/`prototype` own-keys from JSON config (pollution-safe); `settings_merge.ts` `deepMerge` skips the same prototype-dangerous keys at every level so crafted config files cannot pollute `Object.prototype`; `fund_registry.ts` reloads the shared registry file on mtime change instead of serving stale cross-bot state and clamps collateral releases like buy/sell sides; `validate_profiles.ts` reports profile syntax errors as `ok:false` issues instead of crashing validation; `bot_settings.ts` shares one duplicate-bot-key detector between assert and collect paths (`modules/order/accounting.ts`, `modules/credit_runtime.ts`, `modules/chain_orders.ts`, `modules/dexbot_class.ts`, `modules/dexbot_state_recovery.ts`, `modules/dexbot_startup_runtime.ts`, `modules/graceful_shutdown.ts`, `modules/settings_merge.ts`, `modules/credential_policy.ts`, `modules/fund_registry.ts`, `modules/validate_profiles.ts`, `modules/bot_settings.ts`).
16
+ - **Fix(orders)**: order-pipeline corrections — `format.ts` gives `toFiniteNumber` proper overload semantics so an explicit null default returns null for non-finite input (previously `undefined` triggered the default-0 overload and nullable call sites silently read 0), with sync_engine residual/drift chain reads converted to the null form and re-guarded; `logger.ts` CSV-quotes exported cells containing delimiters/quotes/newlines, captures fee data timestamps from the log line instead of wall clock, and closes the log-flush race; `processed_fill_store.ts` invokes the explicit flush immediately when configured; `async_lock.ts` makes forceRelease of an orphaned lock a no-op instead of throwing; `utils/order.ts` drops the always-equal gridIndex clause from ordersEqual (it masked real content differences) and rewrites initial-order activation as filter-then-select so underfunded candidates skip cleanly; `grid_reconcile_internal.ts` and `utils/validate.ts` add missing null guards on chain responses (`modules/order/format.ts`, `modules/order/sync_engine.ts`, `modules/order/logger.ts`, `modules/order/processed_fill_store.ts`, `modules/order/async_lock.ts`, `modules/order/utils/order.ts`, `modules/order/grid_reconcile_internal.ts`, `modules/order/utils/validate.ts`).
17
+ - **Fix(launcher)**: launcher and native-client hardening — `process_discovery.ts` adds a pid-liveness fallback discovery (`runtime.kill(pid, 0)`, EPERM counts alive) for environments where tool-based discovery is unavailable; the market-adapter watchdog runs children with the scoped child-env builder; unreachable ESRCH catch branches are removed from bot_supervisor, monolithic_runtime and foreign_cred_daemon stop paths (a pid cannot be observed dead then reused before kill); `bitshares-native/resolvers.ts` invalidation completes alias invalidation and drops unused size getters; `node_manager.ts` updates health stats before the rate-limited early return; `socket_json_client.ts` contains synchronous throws inside request dispatch; `signing_client.ts` exposes an accountId getter used by credential flows; `tx/tx_cache.ts` excludes broadcast fees from cache keys so fee changes are not served stale results; `subscriptions.ts` removes dead open/closing subscription branches and resets history flags per batch; `storage/browser_adapter.ts` warns when degraded to in-memory mode; `storage/index.ts` header corrected (`modules/process_discovery.ts`, `modules/launcher/market_adapter_watchdog.ts`, `modules/launcher/*`, `modules/bitshares-native/resolvers.ts`, `modules/node_manager.ts`, `bitshares-native/socket_json_client.ts`, `bitshares-native/signing_client.ts`, `bitshares-native/tx/tx_cache.ts`, `bitshares-native/subscriptions.ts`, `modules/storage/*`).
18
+ - **Chore(browser-boundary)**: align the browser-safe surface with reality — `package.json` browser-map exclusions added for `modules/runtime_settings.js`, all five Node-bound `bitshares-native` entry files (`transport`, `signing_client`, `subscriptions`, `tx/builder`, `tx/tx_cache`) and `market_adapter/utils/chain.js` (top-level `createRequire(import.meta.url)`); AGENTS.md Node-only list extended with the same files so convention docs match the bundler config (`package.json`, `AGENTS.md`).
19
+ - **Refactor(dead-code)**: remove unreferenced symbols surfaced by the audit — `constants.ts` prunes the ECC mirror block, unused timing/network constants (`SUBSCRIPTION_SILENT_THRESHOLD_MS`, `STARTUP_CONNECT_TIMEOUT_MS`, `MAX_TRANSACTION_SIZE`, `MAX_TIME_UNTIL_EXPIRATION`, `PERCENT_1`) and the supervisor `MAX_MEMORY_MB` fallback, and aligns OBJECT_TYPES with the BitShares enum (`CUSTOM_AUTHORITY` 17 … `CREDIT_DEAL` 22) adding the credit-offer/deal object types used by credit flows; `cr_planner.ts` drops the legacy CR-formula exports (`planCrAdjustment`, collateral/debt target helpers) while keeping `calculateCollateralRatio` internal; `credit_runtime.ts` removes the test-only `openCreditPosition`/`getCollateralOffsets` wrappers (renewOnly coverage retargeted to `buildCreditOfferAcceptOperation`); `key_store.ts` removes the unused `DirectKeyStore`; `crypto/index.ts` drops dead pure-primitive re-exports; `dexbot_fill_runtime.ts` collapses tautological FILL_PROCESSING.MODE comparisons (history processing unconditional, open-orders fallback gated solely on `requiresOpenOrdersSync`); `bots_file_lock.ts` fixes the writeJsonFileAtomic doc drift (`modules/constants.ts`, `modules/cr_planner.ts`, `modules/credit_runtime.ts`, `modules/key_store.ts`, `modules/crypto/index.ts`, `modules/dexbot_fill_runtime.ts`, `modules/bots_file_lock.ts`).
20
+ - **Test**: add regression coverage for the trickier audit fixes — `test_to_finite_number_null.ts` locks the nullable-read semantics, `test_credential_policy_layer_merge.ts` covers per-op allowedOps merging plus `__proto__` rejection, settings-merge tests cover EXPERT GRID_COMPARISON preservation and scalar-override immunity plus deep-merge `__proto__` pollution rejection at nested levels, and the fill-batch suite asserts a deferred fill restores the exact pre-call `_fillBatchInFlight` count so concurrent batches cannot zero each other's guard; fixtures updated for the removed `getSizingContext` wrapper and the signal-based abort path (`tests/test_to_finite_number_null.ts`, `tests/test_credential_policy_layer_merge.ts`, `tests/test_settings_merge.ts`, `tests/test_sync_fill_history_batch.ts`, `tests/*`).
21
+ - **Tune**: raise the AMA slope ceiling default 0.085 → 0.09 and narrow the research slider floor 0.04 → 0.06 — de-sensitizes the AMA trend channel by ~5.6% (factor 0.85/0.9) so grid range-scaling asymmetry, grid price offset, and buy/sell weight tilt react proportionally weaker to the same slope magnitude; applied asymmetry at the current XRP-BTS slope drops ~21.25% → ~20.1% and the AMA-slope grid-reset trigger threshold rises 0.0068 → 0.0072 %/bar; behavior unchanged at |slopePct| ≥ 0.09 (identical saturation cap), research chart paste payloads with amaS% in [0.04, 0.06) clamp up to 0.06 (`modules/constants.ts`, `analysis/trend_detection/dynamic_weight_chart_generator.ts`, `analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md`).
22
+ - **Fix(market-adapter)**: harden locking, signal math, and input tools from a full module review — Hurst buffer cap window+2 → window+1 so the newest candle is always included with shared `classifyHurst()` and a `HURST_STRENGTH_NORMALIZER` strength scale; ATR re-warms per chain segment so a bad candle no longer leaks pre-break values across the gap; dynamic-weight/slope dead-band boundaries inclusive on both sides with exact-zero slopes staying NEUTRAL at the default `neutralZonePct` of 0; permutation entropy validates m/delay/window against `PE_ANALYZER_LIMITS` at construction instead of running degenerate configs silently; Kalman filter defaults unified through a single `_initState()` with beams returned as a copy and null-safe displacement; a malformed custom regimeTable throws at construction instead of producing silent NaN multipliers. File locks gain an ownership token (fresh UUID per holder written into every payload; release only unlinks when the token still matches) so a stolen lock can no longer be deleted by its previous holder, including pid collisions across containers sharing a mounted volume — legacy token-less payloads stay releasable; partial acquisitions clean up their orphaned lock file instead of locking out later contenders, heartbeat derives as clamp(staleMs/2, 1s..30s) so it always fires inside the staleness window, and the holder heuristic recognizes dexbot-embedded adapters while anchoring entrypoint names to argv/path boundaries so unrelated scripts such as robot.js no longer match. Service wiring clamps clipPercentile to (0,100] at the read point, normalizes volatility exponent/scaleX to their effective ranges at the single configured point, derives amaSlopeGated/amaChannelContribution diagnostics from the canonical Kalman-disabled weight series so diagnostics agree with finalOffset whenever gating is active, records `triggerSuppressedReason=stale_candle_data` for stale-but-new cycles, and config normalizers treat null/empty as unset before `Number()` coercion so explicit JSON null no longer means "disabled". Input tools: fetch_lp_data completes the interval map (30m..7d) with loud validation instead of parsing "30m" as 30 seconds, adds linear retry backoff and honest range labels in --start/--end mode; fetch_cex_synthetic_data fixes the dead HTX endpoint (/market/history/kline), honors exchange page caps via `CEX_PAGE_LIMIT_CAPS`, corrects MEXC intervals (6h/12h/1W), rejects zero-price leg candles, and handles --help before bot resolution. Constants: new keys centralized (`FILE_LOCK_HEARTBEAT_MIN/MAX_MS`, `LP_FETCH_RETRY_BACKOFF_BASE_MS`, `CEX_PAGE_LIMIT_CAPS`, `PE_ANALYZER_LIMITS`, `HURST_STRENGTH_NORMALIZER`, `DYNAMIC_WEIGHT_KALMAN_WARMUP_BARS_DEFAULT`, `DYNAMIC_WEIGHT_KALMAN_BEAM_COUNT_DEFAULT`, `DYNAMIC_WEIGHT_VOLATILITY_EXPONENT/SCALE_X_MIN/MAX`), sourceRetries default 3 → 4; misc: kibana_client releases redirect bodies, data_discovery skips unreadable entries and dangling symlinks, asymmetric_bounds/collateral_manager share previously duplicated math, analysis/bot_key_utils delegates to the production createBotKey so unnamed bots resolve identical keys, vestigial exports removed, and 'use strict' hoisted above imports across ~90 files where it sat as a no-op (`market_adapter/**`, `modules/constants.ts`, `analysis/bot_key_utils.ts`).
23
+
24
+ ### 2026-08-25
25
+
26
+ - **Fix(grid)**: route root-level range scaling through canonical asymmetric bounds — the `initializeGrid` root-fallback hand-rolled the DOWN/UP scaling formulas instead of calling `applyAsymmetricBounds`, dropping its geometric safe-clamp: a persisted `appliedAsymmetryFactor` clamped at adapter time against AMA-centered geometry was applied to gridCenter-centered rebuild geometry, so an over-limit factor could distort the widened side and diverge from UI display. The fallback now feeds the persisted factor back through `applyAsymmetricBounds` with neutral caps (keeping the safe-clamp active against rebuild geometry), and the dynamicWeights path prefers rawSlopeOffset over the 2dp-rounded value matching the market adapter service; regression test covers a persisted DOWN factor 0.6 against '2x' bounds (safe limit 0.5) being clamped to 0.5 with correct widened min (`modules/order/grid.ts`, `tests/test_grid_logic.ts`).
27
+ - **Feat(build)**: remove the tsx dependency entirely — every entry point and the full test suite now executes from compiled `dist/` under plain node, making test execution identical to production execution. New `tsconfig.tests.json` compiles tests/ to dist/tests/ with package markers and ESM mock hook files copied in; frozen-ESM-safe production seams replace export patching (`setDerivePriceTestHook`, `_setFeeCache`, bot-level `_submitCancelOrder`/`_syncMarketAdapterHook`/`_readOpenOrdersHook`/`_gridModule`/`_listenForFillsHook`, all no-ops when unset); loader-hook based cross-process ESM mocking lands in `tests/helpers/esm_mocks.ts`; run-tests gains a 240s per-test watchdog; `clean-dist.js` deletes stale tsbuildinfo caches that made tsc emit nothing after clean; ~60 tests converted off tsx-era patterns and the lockfile sheds 78 orphaned @esbuild/* platform packages. Full suite 237/237 green (`package.json`, `tsconfig.tests.json`, `tests/helpers/*`, `scripts/clean-dist.js`, modules seam sites).
28
+ - **Fix(market-adapter)**: code-health sweep and exact AMA bootstrap sizing — persisted adapter state is normalized once at processBot entry, explicit-null meta timestamps are guarded before `Number()` (null masqueraded as epoch 1970), kibana client promises settle once (no timeout+error double rejection), unparseable lock-holder pids are treated as alive, and dead helpers are dropped; the one-shot cold-start Kibana bootstrap now requests exactly rawKeepCount × interval hours instead of the old max() heuristic — sub-hourly bots no longer over-fetch ~4x+ and >1h intervals were previously under-fetching; shared browser-safe `usesAmaGridPrice()` extracted to `modules/grid_price_source.ts` (previously duplicated as regexes in two modules); fetch_lp_data probe output now describes the window actually queried and unknown ama_signal_runner CLI args throw instead of being ignored (`market_adapter/*`, `modules/grid_price_source.ts`).
29
+ - **Fix(analysis)**: align research tools with production AMA slope and range-scaling — `computeAmaSlopeClipThreshold` moves to the import-free `ama_slope_model.ts` as the single source of truth (plus an incremental `createAmaSlopeClipTracker` with identical thresholds via binary insertion), analyze_dynamic_weight uses prefix-only clip pools so research reproduces live asymmetry without look-ahead, the analyze_kalman comparison panel feeds production constants instead of hardcoded drift values (72-bar lookback, MAX_SLOPE_PCT=3.0, NEUTRAL_ZONE=0.15), dynamic_weight_chart_generator drops its hand-copied clip loop for the injected canonical function, and scripts/analyze-orders delegates asymmetric-bounds math to canonical `applyAsymmetricBounds` so displayed bounds stay in lockstep with live grid scaling (`market_adapter/core/strategies/ama_slope_model.ts`, `analysis/*`, `scripts/analyze-orders.ts`).
30
+ - **Docs**: refresh reference documentation against the v1.4.21 codebase — all 15 doc files re-verified against source before editing: stale API references fixed (SPREAD_LIMITS → `GRID_LIMITS.MIN_SPREAD_ORDERS`; validateIndices/_repairIndices snippets → `_gridVersion` cache invalidation + `assertOrdersStructurallySound()`; rebalanceSideRobust fund validation → `validateOperationFunds()`; `_reconcileGridCOW` → `WorkingGrid.buildDelta()`; periodic refresh rewritten around the real `setupBlockchainFetchInterval()` flow; LendingEntryBase → DebtFirstCrPlanOptions; offer cache TTL corrected to 10 minutes; dead BotLoggingOverrides ref → actual runtime_settings merge wiring); ~24 GRID_RECONCILE.md line anchors plus LIFECYCLE/COW_INVARIANTS/FUND_MOVEMENT_AND_ACCOUNTING function anchors re-verified; legacy narrative removed (vault-migration section and masterPasswordHash row dropped from CREDENTIAL_SECURITY.md, FUND_MOVEMENT_AND_ACCOUNTING fix anecdotes rewritten as present-tense rules, archival appendixes trimmed in GRID_RECALCULATION.md/COPY_ON_WRITE_MASTER_PLAN.md/architecture.md); statistics and version context synced (252 test files, v1.4.21). Docs-only change, no runtime code touched (`docs/*`).
31
+ - **Feat(analysis)**: clickable report path in the order-analysis export output — the --export HTML report lives in analysis/charts/ since output-dir centralization, but the console printed a bare absolute path terminals render as plain text; analyze-orders now wraps it in an OSC 8 hyperlink targeting the file:// URL when stdout is a TTY, falling back to the plain file:// URL for pipes and logs (visible label stays the absolute path so copy-paste works even without OSC 8 support), and README corrects the stale claim that --export writes to the repo root (`scripts/analyze-orders.ts`, `README.md`).
32
+ - **Fix(scripts)**: repair native release gates and stale tsx-era docs after the dist migration — `native_release_gates.ts` used bare `__dirname`, undefined in compiled ESM, crashing every run with ReferenceError (now derived via `fileURLToPath(import.meta.url)`); the native:serial-snapshots / native:ecc-invariants / native:release-gates scripts invoked `dist/tests/*.js` after only `npm run build`, which excludes tests/, so all three failed on a fresh build (they now chain `npm run build:tests` matching the npm test order); runner.ts usage docs and scripts/README.md converted off tsx-era invocation examples — the wrapper table points at the dist shims the wrappers actually run, build/test rows describe the compiled flow, and a Native Release Gates section documents the native:* scripts plus the corpus report requirement (passed=true, transactionCount≥50) (`scripts/native_release_gates.ts`, `package.json`, `scripts/runner.ts`, `scripts/README.md`).
33
+
34
+
35
+ ## [1.4.21] - 2026-08-24 - Runtime Audit Fixes, Claw Dedup Hardening, Boundary Ceiling Alignment, Editor Color Feedback
36
+
37
+ ### 2026-08-23
38
+
39
+ - **Feat(ui)**: red/green highlight for botFunds percentage inputs — extend the price-multiplier live color feedback to the Funding section of the account bots editor: percentage allocations ("100%") render green while fixed absolute amounts render red, matching the existing min/maxPrice multiplier treatment. New `isPercentageString`/`colorPercentageInput` helpers mirror `isMultiplierString`/`colorMultiplierInput` (the local percentage check is stricter than `order/utils/math.ts` so partial input like "x%" never flashes green mid-typing); `askNumberOrPercentage` colors its default suffix and wires the `readInput` colorize option, and the Funding summary line renders Sell/Buy values through the same colorizer (`modules/account_bots.ts`).
40
+
41
+ ### 2026-08-24
42
+
43
+ - **Fix**: correct runtime defects found in a modules-wide audit — silent-failure and initialization-order defects could disable safety checks, defeat batching, or poison configuration at load time: `accounting.ts` falls back to `GRID_LIMITS.FUND_INVARIANT_PERCENT_TOLERANCE` when unset (undefined/100 produced NaN and silently disabled the fund invariant); `processed_fill_store.ts` flushes on batch size only when configured (previous `?? 0` comparison made `size >= 0` always true, flushing every write); `sync_engine.ts` tracks per-invocation `fillGuardLowered` so inner and outer finally blocks cannot double-decrement the shared `_fillBatchInFlight` counter under concurrent batches; `bitshares_client.ts` applies the configured node list even when node management is disabled, races node refresh against the remaining wait budget so it cannot overshoot the connection timeout, preserves `lastConnectionError` across disconnects, and reuses the shared `withTimeout` util; `config.ts` `num()` returns the default on empty or non-finite values instead of 0/NaN; `settings_merge.ts` keeps the base value when a raw override for an object section is not an object instead of spreading char-indexed garbage; `fund_registry.ts` clamps `totalAllocatedPct` at zero in `releaseAllocation` and logs loudly before resetting a corrupt registry file; `account_orders.ts` warns on corrupt profile files before falling back to empty state; `credential_policy.ts` uses `Object.hasOwn` for the allowedOps lookup; `dexbot_state_recovery.ts` normalizes stale-id input through a Set; `runtime_settings.ts` warns with bot-name context when market-adapter override resolution fails (`modules/order/accounting.ts`, `modules/order/processed_fill_store.ts`, `modules/order/sync_engine.ts`, `modules/bitshares_client.ts`, `modules/config.ts`, `modules/settings_merge.ts`, `modules/fund_registry.ts`, `modules/account_orders.ts`, `modules/credential_policy.ts`, `modules/dexbot_state_recovery.ts`, `modules/runtime_settings.ts`).
44
+ - **Fix(grid)**: align boundary writers and add a sell-rail ceiling to the commit gate — `deriveTargetBoundary` clamped to length−1 while `calculateFundDrivenBoundary` clamped to N−gapSlots−1, so fill-driven updates could walk the boundary onto or past the SELL rail where `resolveGapBand` re-derives zero-SELL geometry permanently on every cycle. `deriveTargetBoundary` now caps at N−gapSlots−1 matching the fund-driven writer (degenerate geometries fall back to the legacy ceiling preserving the current boundary); `validateBoundaryCommit` rejects proposals past the shared writer ceiling with stable reason `sell_rail_ceiling_exceeded`; `validatePersistedBoundary` inherits the rule so loadGrid restore and `recoverFromPersistedGrid` refuse past-ceiling snapshots and fall through to clean rebuild — legacy persisted snapshots whose boundary sits past the ceiling now trigger the documented rebuild path instead of silently re-legalizing broken geometry (`modules/order/utils/order.ts`, `modules/order/utils/math.ts`, `tests/test_boundary_restore_validation.ts`).
45
+ - **Refactor(claw)**: dedupe shared logic, remove dead code, harden error paths — bug fixes: `position_manager` guards `syncPosition` against unresolved MPA assets and persists close events before the catch-guarded sync; `dexbot_profiles` fixes spread order in `normalizeBotEntries` so active coercion actually applies; `chain_actions.listenForFills` awaits the subscribe promise before registering callbacks so failures surface as errors instead of unhandled rejections; `memu_mcp_server` redacts malformed `--llm-profile`/`--db-config` values in parse errors (secret leak); `claw_launcher.spawnDetached()` waits one macrotask for async spawn errors instead of returning false `started:true`; `mcp_utils` treats stdin EPIPE/EIO as EOF rather than crashing mid-session and maps tools/list catalog failures to −32603; `decision_loop.resetAnalyzers` clears marketPremiums; honest-ecosystem logs live pool-reserve fetch failures and returns null for unhonorable pinned poolRefs; `position_discovery` actually resolves asset triples in parallel; `memu_bridge` adds an EPIPE guard and the openclaw plugin returns isError results. Deduplication: shared `createJsonRpcToolsHandler()`/`jsonRpcError()`, single `validateMemuCommandArgs()` spec, extracted `viaCredentialDaemon()` broadcast path, unified `computeCallOrderAmounts()` call-order math; ~25 unused exports removed across profiles/infra/launcher/ecosystem/bridge modules plus the orphan `claw/openclaw.plugin.json` stale copy (`claw/modules/*`, `claw/scripts/memu_mcp_server.ts`, `claw/openclaw.plugin.json`).
46
+ - **Fix(launcher)**: supervisor and runtime lifecycle corrections — `bot_supervisor.ts` enforces memory limits only for apps that define one (the previous global fallback restarted unlimited apps at MAX_MEMORY_MB) and the status banner prints real per-app limits; `foreign_cred_daemon.ts` SIGKILL path polls liveness until timeout like SIGTERM instead of a single immediate check that could race process exit; `monolithic_runtime.ts` resolves the updater close promise on spawn error (ENOENT left it pending forever and hung the update flow); `market_adapter_runtime.ts` simplifies `isLockStale` to pid-liveness semantics (the mtime branch was unreachable dead logic) (`modules/launcher/bot_supervisor.ts`, `modules/launcher/foreign_cred_daemon.ts`, `modules/launcher/monolithic_runtime.ts`, `modules/launcher/market_adapter_runtime.ts`).
47
+ - **Fix(storage)**: persist deletions, debounce flushes, guard ingest in the browser adapter — deleted files resurrected after reload because unlink never reached IndexedDB; writes required a manual flush call to persist at all; records mutated before the startup load cursor reached them were clobbered by stale IndexedDB state. Deletions are now tracked as tombstones replayed as IndexedDB deletes on flush (cleared only after a successful transaction, so failed flushes replay deletes on the next cycle), mutations schedule a debounced 500ms flush, and the initial load skips tombstoned and locally-mutated keys so pre-load unlinks and writes win over stored records (`modules/storage/browser_adapter.ts`).
48
+ - **Fix(paths)**: stop hardcoding repo-relative `profiles/*` paths in docs and user-facing messages — docs and runtime/error strings still referenced the legacy repo-relative `profiles/logs`, `profiles/bots.json`, and `profiles/keys.json` locations after state resolution moved to the PATHS resolver in v1.4.15/1.4.16, landing npm-install users on paths that do not exist. BITSHARES_ONBOARDING.md rewrites "Where are the logs?" with the resolver-aware location and completes the log-file table (dexbot-cred.log, dexbot-adapter/-error.log, market_adapter.log, dexbot-update/-error.log were undocumented); WORKFLOW.md and scripts/README.md rows corrected; key-vault/bots-not-found/watchdog/update/analyze error messages now print resolver-derived paths; CLI help documents the `<profiles>` resolution rule. No behavioral change: all file I/O already routed through the resolver (`docs/BITSHARES_ONBOARDING.md`, `docs/WORKFLOW.md`, `scripts/README.md`, `credential-daemon.ts`, `modules/chain_keys.ts`, `pm2.ts`, `bot.ts`, `claw/modules/claw_launcher.ts`, `modules/dexbot_class.ts`, `scripts/update.ts`, `dexbot.ts`).
49
+ - **Feat(ui)**: live green/red highlighting for price inputs in the bot editor — extends the bot-editor color feedback to the remaining price fields: startPrice and gridPrice inputs colorize live (green for dynamic sources "pool"/"book"/AMA keywords, red for fixed numeric anchors); null gridPrice resolves through startPrice so the default label inherits the matching color; Active/DryRun flags render green in their healthy state; targetSpreadPercent prompt rounds minimum/validation/input display to 2 decimals instead of surfacing 6-decimal floats (`modules/account_bots.ts`).
50
+ - **Fix(client)**: skip disconnect teardown when the client was never initialized — `disconnectClient()` called `ensureInitialized()`, which lazily built the whole client stack (including the node-config log) just to discard it immediately, e.g. running `dexbot bot` after an idle bot-manager session; it now returns early when not initialized (`modules/bitshares_client.ts`).
51
+ - **Refactor(orders)**: remove the sub-unit price nudge from `buildUpdateOrderOp` — sub-unit price changes that round to the same `min_to_receive` were nudged by one unit to force an update operation; dust orders are cancelled rather than updated now, so the nudge only produced churn broadcasts with no economic effect and masked genuine no-op skips. Unchanged rounded amount+price is treated as no-op returning null; callers count the skip and restore affected slots via `restoreSkippedUpdateSlotsInWorkingGrid` (`modules/chain_orders.ts`).
52
+ - **Refactor**: remove dead code and consolidate duplicated helpers across analysis/market_adapter — delete `market_adapter/merge_lp_data.ts` and `market_adapter/utils/paths.ts` (no importers); prune ~180 lines of unused query builders/wrappers from `analysis/bot_usage/kibana_bot_queries.ts`; un-export zero-consumer symbols (kibana_client INDEX/KIBANA_URL, `normalizeAmaSlopeLookbackBars`, `loadStrategiesFromResults`, kibanaSearch/bilinearInterpolate re-exports, candle high/low/ATR re-exports, internal CSS fragments, `toCandles`); add `modules/utils/sanitize_key.ts` as the single sanitizeKey source; make the candleFileForBot filename template canonical in `analysis/bot_key_utils.ts` eliminating three-way filename drift; fix stale tsx invocation comments to node dist/ paths (`market_adapter/*`, `analysis/*`, `modules/utils/sanitize_key.ts`).
53
+ - **Chore(logging)**: remove dead state-change history and stale docs — logger_state changeHistory/maxHistory fields were written but never read anywhere; drop them plus the phantom audit-trail doc section and the now-unused `GRID_LIMITS.STATE_CHANGE_HISTORY_MAX`; console fund-status output keeps ANSI colors while the file drain strips them as before (`modules/order/logger_state.ts`, `modules/constants.ts`, `modules/order/logger.ts`).
54
+ - **Refactor(ui)**: centralize bot editor ANSI colors into a shared palette — the account-bots editor scattered raw ANSI escape sequences across ~40 lines; a module-level COLORS palette (13 named entries) now routes all ~152 highlight usages, input/error/OFF highlights use bold red matching the Pair line, rendering stays byte-identical for all other colors (`modules/account_bots.ts`).
55
+ - **Docs**: sync tuning guidance between the root README and the BitShares onboarding tutorial — README adds weightDistribution as optional setup step 3 (super-valley..super-mountain legend vocabulary), anchors steps 1–2 on the cycle-profit formula spread − increment − fees and the increment speed/fee tradeoff, documents ama1–ama4 presets in the gridPrice row, and adds a "prefer relative values" callout with editor green/red hints; BITSHARES_ONBOARDING.md mirrors the relative-values guidance, expands its tuning list to match, and fixes the broken prerequisite anchor link (`README.md`, `docs/BITSHARES_ONBOARDING.md`).
56
+ - **Test**: mute intentional failure-path logs in negative-path fixtures — the run diagnostics listed scary FAILED lines that were assertion-passing fixtures exercising failure branches, making real regressions harder to spot; `test_orphan_fill_death_spiral.ts` filters its two expected underfunding warnings and `test_patch17_invariants.ts` mutes expected COW/persist ERROR logs with restore-on-finally semantics; production log wording untouched (`tests/test_orphan_fill_death_spiral.ts`, `tests/test_patch17_invariants.ts`).
57
+
5
58
  ## [1.4.20] - 2026-08-23 - Grid Boundary Hardening, Recovery Poison Gate, Analysis Path Centralization
6
59
 
7
60
  ### 2026-08-22
package/README.md CHANGED
@@ -147,18 +147,26 @@ Both installs use the same CLI and store all user state — keys, `bots.json`, l
147
147
 
148
148
  Keep the default settings first, and tune these:
149
149
 
150
- 1. **Tune `targetSpreadPercent`** — controls profit room per completed cycle. A
151
- wider spread targets more profit per cycle but trades less often.
150
+ 1. **Tune `targetSpreadPercent`** — controls profit room per completed cycle:
151
+ profit ≈ `spread - increment - fees`. A wider spread targets more profit per
152
+ cycle but trades less often.
152
153
 
153
- 2. **Tune `incrementPercent`** — controls grid density and order size. Smaller
154
+ 2. **Tune `incrementPercent`** — controls order steps and order size. Smaller
154
155
  increments create more grid levels and smaller orders; larger increments
155
- create fewer levels and larger orders.
156
+ create fewer levels and larger orders. Smaller increments cycle faster —
157
+ higher profits, but more fees.
156
158
 
157
- 3. **Set `gridPrice` to `"ama"`** — so the market adapter can center the grid
159
+ 3. **Tune `weightDistribution`** (optional) — per-side sizing control. Higher
160
+ weight = more funds in orders near the market price; lower weight = funds
161
+ shifted toward the grid edge. Range `-1` (super-valley) to `2`
162
+ (super-mountain); the default `{ "sell": 1.0, "buy": 1.0 }` suits most
163
+ setups.
164
+
165
+ 4. **Set `gridPrice` to `"ama"`** — so the market adapter can center the grid
158
166
  on AMA. Pick a specific preset if desired: `"ama1"` is the fastest,
159
167
  `"ama4"` the slowest, and `"ama"` uses the pair's default preset.
160
168
 
161
- 4. **Generate the market-adapter whitelist:**
169
+ 5. **Generate the market-adapter whitelist:**
162
170
 
163
171
  ```bash
164
172
  dexbot white
@@ -168,9 +176,9 @@ Keep the default settings first, and tune these:
168
176
  live writes and range scaling. Use `dexbot white --dynamic-weight` for
169
177
  newly generated dynamic-weight entries; existing entries are preserved.
170
178
 
171
- 5. **Start DEXBot2** with `dexbot start`.
179
+ 6. **Start DEXBot2** with `dexbot start`.
172
180
 
173
- 6. **Tune `minPrice` / `maxPrice`** around the market's volatility range. Once
181
+ 7. **Tune `minPrice` / `maxPrice`** around the market's volatility range. Once
174
182
  AMA is active, tighten them around the maximum expected market volatility
175
183
  instead of using an unnecessarily wide range.
176
184
 
@@ -178,6 +186,8 @@ Keep the default settings first, and tune these:
178
186
 
179
187
  Configuration options from `dexbot bot`, stored in `bots.json` in the profiles directory:
180
188
 
189
+ > **Prefer relative values** — use dynamic price sources where available: `"pool"` (liquidity-pool price) or `"book"` (order-book mid) for `startPrice`, `"ama"` for `gridPrice`, `"2x"`-style multipliers for `minPrice` / `maxPrice`, and `"100%"`-style percentages for funds (`botFunds`). Relative values rescale automatically as the market moves; fixed numbers do not. The bot editor highlights these inputs live: **green** = relative/dynamic (recommended), **red** = fixed absolute value.
190
+
181
191
  <details><summary><mark>Full parameter reference (click to expand)</mark></summary>
182
192
 
183
193
  | Parameter | Type | Description |
@@ -192,10 +202,10 @@ Configuration options from `dexbot bot`, stored in `bots.json` in the profiles d
192
202
  | **`poolRef`** | string \| null | Optional pinned pool ID for `startPrice: "pool"`. Overrides pool discovery with a direct fetch (e.g. `"1.19.48"` or `"48"`). Useful when the trading pair has no native pool. Default `null`. |
193
203
  | **`minPrice`** | num \| str | Lower bound. Default `"2x"` means `gridPrice / 2` when AMA is active, otherwise `startPrice / 2`. |
194
204
  | **`maxPrice`** | num \| str | Upper bound. Default `"2x"` means `gridPrice * 2` when AMA is active, otherwise `startPrice * 2`. |
195
- | **`gridPrice`** | num \| str \| null | Grid reference. Use `"ama"` for the recommended AMA center; `null` falls back to `startPrice`; numeric values use that fixed value. |
196
- | **`incrementPercent`** | number | Geometric step between layers. Default `0.5` = 0.5%. |
197
- | **`targetSpreadPercent`** | number | Width of the empty spread zone between buy and sell orders. Default `2` = 2%. |
198
- | **`weightDistribution`** | object | Advanced sizing control. Default `{ "sell": 1.0, "buy": 1.0 }`; leave unchanged for normal setup. |
205
+ | **`gridPrice`** | num \| str \| null | Grid reference. Use `"ama"` for the recommended AMA center (`"ama"` picks the pair's default preset; `"ama1"`–`"ama4"` pin fastest to slowest); `null` falls back to `startPrice`; numeric values use that fixed value. |
206
+ | **`incrementPercent`** | number | Geometric step between orders. Default `0.5` = 0.5%. |
207
+ | **`targetSpreadPercent`** | number | Width of the empty spread zone between buy and sell orders. Default `2` = 2%. Profit per completed cycle ≈ `spread - increment - fees`. |
208
+ | **`weightDistribution`** | object | Advanced sizing control per side. Range `-1` to `2`: `-1` = super-valley, `0` = valley, `0.5` = neutral, `1` = mountain (default), `2` = super-mountain. Higher weight = more funds in orders near the market price; lower weight = more funds shifted toward the grid edge. Default `{ "sell": 1.0, "buy": 1.0 }`; leave unchanged for normal setup. |
199
209
  | **`botFunds`** | object | Capital: `{ "sell": "100%", "buy": 1000 }`. Numbers or percentage strings |
200
210
  | **`activeOrders`** | object | Target active orders per side: `{ "sell": 20, "buy": 20 }` |
201
211
 
@@ -245,7 +255,7 @@ dexbot enable {all|<bot>} # Enable bot in config
245
255
 
246
256
  dexbot stat # Runtime status (unlock or PM2)
247
257
  dexbot order [<bot>] # Analyze order grids
248
- dexbot order --export # Export as HTML to root folder
258
+ dexbot order --export # Export as HTML to analysis/charts/
249
259
 
250
260
  dexbot update # Update DEXBot2
251
261
  dexbot clear # Clear log files
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
  import path from 'node:path';
3
4
  import { calculateAMA } from '../../market_adapter/core/strategies/ama.js';
4
5
  import { getStorage } from '../../modules/storage/index.js';
5
6
  const { readJSON } = getStorage();
7
+ import { normalizeCandle } from '../math_utils.js';
6
8
  import { MARKET_ADAPTER } from '../../modules/constants.js';
7
9
 
8
- 'use strict';
9
10
  /**
10
11
  * AMA REPOSITION FREQUENCY ANALYSIS
11
12
  *
@@ -16,7 +17,7 @@ import { MARKET_ADAPTER } from '../../modules/constants.js';
16
17
  * (modules/constants.ts).
17
18
  *
18
19
  * Usage:
19
- * tsx analysis/ama_fitting/analyze_ama_price_changes.ts --data <path-to-lp-candles.json> --results <path-to-optimization-results.json>
20
+ * node dist/analysis/ama_fitting/analyze_ama_price_changes.js --data <path-to-lp-candles.json> --results <path-to-optimization-results.json>
20
21
  */
21
22
  const REPOS_THRESHOLD_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
22
23
 
@@ -55,7 +56,10 @@ function loadData(filePath: any) {
55
56
  const json = readJSON(filePath);
56
57
  const candles = json.candles ?? json;
57
58
  return {
58
- candles: candles.map((c: any) => ({ timestamp: c[0], close: c[4] })),
59
+ candles: candles
60
+ .map((c: any) => normalizeCandle(c))
61
+ .filter(Boolean)
62
+ .map((c: any) => ({ timestamp: c.time * 1000, close: c.close })),
59
63
  meta: json.meta ?? null,
60
64
  };
61
65
  }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
 
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
@@ -9,7 +10,6 @@ import { ensureDir } from '../../modules/order/utils/system.js';
9
10
  import { PATHS } from '../../modules/paths.js';
10
11
  import { MARKET_ADAPTER } from '../../modules/constants.js';
11
12
  import { getErrorMessage } from '../../modules/utils/errors.js';
12
- 'use strict';
13
13
 
14
14
  /**
15
15
  * LAMBDA vs SLOW ANALYSIS
@@ -27,7 +27,7 @@ import { getErrorMessage } from '../../modules/utils/errors.js';
27
27
  * Defaults: ER/Fast from MARKET_ADAPTER.AMAS.AMA1 (constants.ts).
28
28
  *
29
29
  * Usage:
30
- * tsx analysis/ama_fitting/analyze_lambda_vs_slow.ts \
30
+ * node dist/analysis/ama_fitting/analyze_lambda_vs_slow.js \
31
31
  * --data market_adapter/data/lp/1_3_5537_1_3_0/lp_pool_133_1h_3y.json \
32
32
  * --maxSlow 1000 --lambdaEnd 0.0045 --lambdaSteps 50
33
33
  */
@@ -81,7 +81,7 @@ Lambda vs Slow Analysis
81
81
  Start lambda derived from --maxSlow; only --lambdaEnd is the upper bound.
82
82
 
83
83
  Usage:
84
- tsx analysis/ama_fitting/analyze_lambda_vs_slow.ts --data <lp-file.json> [options]
84
+ node dist/analysis/ama_fitting/analyze_lambda_vs_slow.js --data <lp-file.json> [options]
85
85
 
86
86
  Options:
87
87
  --data FILE LP candle JSON file (required)
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
  import path from 'node:path';
3
4
  import { MARKET_ADAPTER } from '../../modules/constants.js';
4
5
  import { getStorage } from '../../modules/storage/index.js';
5
6
  const { readJSON } = getStorage();
6
7
  import { PATHS } from '../../modules/paths.js';
7
8
  import { roundTo } from '../../modules/order/utils/math.js';
9
+ import { getCandleClose } from '../math_utils.js';
8
10
 
9
- 'use strict';
10
11
  /**
11
12
  * AMA CONVERGENCE ER CALIBRATION
12
13
  *
@@ -22,9 +23,9 @@ import { roundTo } from '../../modules/order/utils/math.js';
22
23
  * the recommended constant for modules/constants.ts.
23
24
  *
24
25
  * Usage:
25
- * tsx analysis/ama_fitting/calibrate_convergence_er.ts
26
- * tsx analysis/ama_fitting/calibrate_convergence_er.ts --data <lp-file.json>
27
- * tsx analysis/ama_fitting/calibrate_convergence_er.ts --data <lp-file.json> --amas AMA3
26
+ * node dist/analysis/ama_fitting/calibrate_convergence_er.js
27
+ * node dist/analysis/ama_fitting/calibrate_convergence_er.js --data <lp-file.json>
28
+ * node dist/analysis/ama_fitting/calibrate_convergence_er.js --data <lp-file.json> --amas AMA3
28
29
  */
29
30
  const DEFAULT_DATA = path.join(PATHS.MARKET_ADAPTER.LP_DATA_DIR,
30
31
  '1_3_5537_1_3_0', 'lp_pool_133_1h.json');
@@ -84,7 +85,7 @@ function main() {
84
85
  if (e.code === 'ENOENT') {
85
86
  console.error(`Data file not found: ${opts.data}`);
86
87
  console.error('Export LP candles first, or point --data at an existing file.');
87
- console.error(' tsx market_adapter/inputs/fetch_lp_data.ts --pool 133 --precA 4 --precB 5 --interval 1h --lookback 26280h');
88
+ console.error(' node dist/market_adapter/inputs/fetch_lp_data.js --pool 133 --precA 4 --precB 5 --interval 1h --lookback 26280h');
88
89
  } else if (e instanceof SyntaxError) {
89
90
  console.error(`Failed to parse JSON from: ${opts.data}`);
90
91
  console.error(e.message);
@@ -93,7 +94,8 @@ function main() {
93
94
  }
94
95
  process.exit(1);
95
96
  }
96
- const closes = (data.candles || []).map((c: any) => Number(c[4]))
97
+ // Canonical candle accessor (handles array rows and object candles alike).
98
+ const closes = (data.candles || []).map((c: any) => Number(getCandleClose(c)))
97
99
  .filter((v: any) => Number.isFinite(v) && v > 0);
98
100
  if (closes.length < 100) {
99
101
  console.error(`Not enough candles (need > 100, got ${closes.length})`);
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { normalizePoolId } from '../../market_adapter/utils/chain.js';
@@ -10,7 +11,6 @@ import { getStorage } from '../../modules/storage/index.js';
10
11
  const { ensureDir, writeJSON } = getStorage();
11
12
  import { getErrorMessage } from '../../modules/utils/errors.js';
12
13
 
13
- 'use strict';
14
14
  /**
15
15
  * Fetch LP pool candles from Kibana for AMA optimizer input.
16
16
  *
@@ -18,7 +18,7 @@ import { getErrorMessage } from '../../modules/utils/errors.js';
18
18
  * the full uncut dataset (no pruning) for optimizer use.
19
19
  *
20
20
  * Usage:
21
- * tsx analysis/ama_fitting/fetch_lp_candles.ts \
21
+ * node dist/analysis/ama_fitting/fetch_lp_candles.js \
22
22
  * --pool 1.19.133 \
23
23
  * --assetA IOB.XRP --assetAId 1.3.3926 --assetAPrecision 4 \
24
24
  * --assetB BTS --assetBId 1.3.0 --assetBPrecision 5 \
@@ -91,7 +91,7 @@ function printHelp() {
91
91
  console.log('fetch_lp_candles.ts — fetch LP pool candles from Kibana for AMA optimizer');
92
92
  console.log('');
93
93
  console.log('Usage:');
94
- console.log(' tsx fetch_lp_candles.ts --pool 1.19.133 \\');
94
+ console.log(' node dist/analysis/ama_fitting/fetch_lp_candles.js --pool 1.19.133 \\');
95
95
  console.log(' --assetA IOB.XRP --assetAId 1.3.3926 --assetAPrecision 4 \\');
96
96
  console.log(' --assetB BTS --assetBId 1.3.0 --assetBPrecision 5');
97
97
  console.log('');
@@ -114,6 +114,11 @@ function validateArgs(args: Record<string, any>) {
114
114
  if (!args.assetBId) throw new Error('--assetBId is required');
115
115
  if (!Number.isFinite(args.assetBPrecision)) throw new Error('--assetBPrecision is required');
116
116
  if (!Number.isFinite(args.hours) || args.hours <= 0) throw new Error('--hours must be > 0');
117
+ // Reject unknown/NaN intervals here instead of letting NaN flow silently
118
+ // into Kibana range queries (production throws on unsupported intervals).
119
+ if (!Number.isFinite(args.intervalSeconds) || args.intervalSeconds <= 0) {
120
+ throw new Error('Unsupported --interval: use one of 1m, 5m, 15m, 1h, 4h, 1d or a positive number of seconds');
121
+ }
117
122
  }
118
123
  async function main() {
119
124
  const args = parseArgs();
@@ -1,16 +1,18 @@
1
+ 'use strict';
1
2
 
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { pathToFileURL } from 'node:url';
5
6
  import { calculateAMA } from '../../market_adapter/core/strategies/ama.js';
6
7
  import { generateHTML } from '../../market_adapter/lp_chart_core.js';
8
+ import { calculateMetrics } from '../../market_adapter/lp_chart_runner.js';
9
+ import { findLatestLpData } from '../../market_adapter/utils/data_discovery.js';
7
10
  import { toIntervalLabel } from '../../market_adapter/interval_utils.js';
8
- import { loadCandleFile } from '../math_utils.js';
11
+ import { loadCandleFile, normalizeCandle } from '../math_utils.js';
9
12
  import { MARKET_ADAPTER } from '../../modules/constants.js';
10
13
  import { getStorage } from '../../modules/storage/index.js';
11
14
  const { ensureDir } = getStorage();
12
15
  import { PATHS } from '../../modules/paths.js';
13
- 'use strict';
14
16
 
15
17
  /**
16
18
  * UNIFIED COMPARISON CHART GENERATOR — Self-contained analysis chart
@@ -19,18 +21,20 @@ import { PATHS } from '../../modules/paths.js';
19
21
  * or {data: [...]}), computes AMA series, and writes an interactive HTML chart
20
22
  * via the shared lp_chart_core renderer.
21
23
  *
22
- * No Kibana fetch, no market_adapter runtime deps beyond the core renderer.
24
+ * No Kibana fetch. Candle normalization, LP data discovery, and drift metrics
25
+ * are imported from the canonical implementations (math_utils →
26
+ * market_adapter/candle_utils, market_adapter/utils/data_discovery,
27
+ * lp_chart_runner.calculateMetrics) instead of local copies.
23
28
  *
24
29
  * Usage:
25
- * tsx analysis/ama_fitting/generate_unified_comparison_chart.ts --data <file.json>
26
- * tsx analysis/ama_fitting/generate_unified_comparison_chart.ts (auto-discovers newest lp_pool_*.json)
30
+ * node dist/analysis/ama_fitting/generate_unified_comparison_chart.js --data <file.json>
31
+ * node dist/analysis/ama_fitting/generate_unified_comparison_chart.js (auto-discovers newest lp_pool_*.json)
27
32
  */
28
33
 
29
34
 
30
35
 
31
36
  // ── Config ─────────────────────────────────────────────────────────────────────
32
37
 
33
- const LP_DATA_DIR = PATHS.MARKET_ADAPTER.LP_DATA_DIR;
34
38
  const CHARTS_DIR = PATHS.ANALYSIS.CHARTS_DIR;
35
39
 
36
40
  const DEFAULT_COLORS = ['#26a69a', '#fb8c00', '#5c9ee6', '#ef5350'];
@@ -50,41 +54,7 @@ function buildDefaultStrategies() {
50
54
 
51
55
  const DEFAULT_STRATEGIES = buildDefaultStrategies();
52
56
 
53
- // ── Data loading (self-contained, no lp_chart_runner dep) ──────────────────────
54
-
55
- function findLatestLpDataFile() {
56
- if (!fs.existsSync(LP_DATA_DIR)) return null;
57
- const stack = [LP_DATA_DIR];
58
- const matches: { path: string; mtime: number }[] = [];
59
- while (stack.length > 0) {
60
- const dir = stack.pop();
61
- if (!dir) continue;
62
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
63
- const full = path.join(dir, entry.name);
64
- if (entry.isDirectory()) { stack.push(full); continue; }
65
- if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
66
- if (!entry.name.startsWith('lp_pool_')) continue;
67
- matches.push({ path: full, mtime: fs.statSync(full).mtimeMs });
68
- }
69
- }
70
- matches.sort((a, b) => b.mtime - a.mtime);
71
- return matches.length > 0 ? matches[0].path : null;
72
- }
73
-
74
- function normalizeCandle(c: any, index: any) {
75
- if (Array.isArray(c)) {
76
- if (c.length < 5) throw new Error(`Invalid candle at index ${index}: need at least 5 entries`);
77
- return { timestamp: c[0], open: c[1], high: c[2], low: c[3], close: c[4], volume: c[5] ?? 0 };
78
- }
79
- if (c && typeof c === 'object') {
80
- const { timestamp, open, high, low, close, volume = 0 } = c;
81
- if ([timestamp, open, high, low, close].some(v => v == null)) {
82
- throw new Error(`Invalid candle object at index ${index}`);
83
- }
84
- return { timestamp, open, high, low, close, volume };
85
- }
86
- throw new Error(`Unsupported candle format at index ${index}`);
87
- }
57
+ // ── Data loading (canonical implementations, no local copies) ────────────────
88
58
 
89
59
  function loadCandles(dataFile: any) {
90
60
  const resolved = path.resolve(dataFile);
@@ -96,33 +66,26 @@ function loadCandles(dataFile: any) {
96
66
  throw new Error('No candles found in file');
97
67
  }
98
68
 
99
- const candleObjects = candles.map((c, i) => normalizeCandle(c, i));
100
- const candleArrays = candleObjects.map(c => [c.timestamp, c.open, c.high, c.low, c.close, c.volume]);
69
+ // normalizeCandle is the canonical accessor transform (market_adapter/
70
+ // candle_utils.ts via math_utils re-export); it returns seconds-based time.
71
+ const normalized = candles.map((c: any, i: number) => {
72
+ const nc = normalizeCandle(c);
73
+ if (!nc) throw new Error(`Invalid candle at index ${i}`);
74
+ return nc;
75
+ });
76
+ const candleObjects = normalized.map(c => ({
77
+ timestamp: c.time * 1000,
78
+ open: c.open,
79
+ high: c.high,
80
+ low: c.low,
81
+ close: c.close,
82
+ volume: c.volume,
83
+ }));
84
+ const candleArrays = normalized.map(c => [c.time * 1000, c.open, c.high, c.low, c.close, c.volume]);
101
85
 
102
86
  return { dataFile: resolved, meta, candleObjects, candleArrays };
103
87
  }
104
88
 
105
- // ── Metrics ────────────────────────────────────────────────────────────────────
106
-
107
- function calculateMetrics(amaValues: any, candles: any) {
108
- let maxDriftUp = 0, maxDriftDown = 0, areaAbove = 0, areaBelow = 0;
109
- const skip = Math.max(20, Math.floor(candles.length * 0.1));
110
- for (let i = skip; i < candles.length; i++) {
111
- const ama = amaValues[i];
112
- const driftUp = (candles[i].high - ama) / ama;
113
- const driftDown = (ama - candles[i].low) / ama;
114
- if (driftUp > maxDriftUp) maxDriftUp = driftUp;
115
- if (driftDown > maxDriftDown) maxDriftDown = driftDown;
116
- if (candles[i].high > ama) areaAbove += driftUp;
117
- if (candles[i].low < ama) areaBelow += driftDown;
118
- }
119
- return {
120
- maxDriftUp, maxDriftDown, areaAbove, areaBelow,
121
- totalArea: areaAbove + areaBelow,
122
- maxDistance: Math.max(maxDriftUp, maxDriftDown),
123
- };
124
- }
125
-
126
89
  // ── Output path ────────────────────────────────────────────────────────────────
127
90
 
128
91
  function defaultChartPath(meta: any) {
@@ -142,7 +105,7 @@ function showHelp() {
142
105
  Unified Comparison Chart Generator
143
106
 
144
107
  Usage:
145
- tsx generate_unified_comparison_chart.ts [options]
108
+ node dist/analysis/ama_fitting/generate_unified_comparison_chart.js [options]
146
109
 
147
110
  Options:
148
111
  --data FILE LP candle export JSON file
@@ -187,7 +150,7 @@ function generateChart(options = {} as Record<string, any>) {
187
150
 
188
151
  const dataFile = options.dataFile
189
152
  ? path.resolve(options.dataFile)
190
- : findLatestLpDataFile();
153
+ : findLatestLpData();
191
154
  if (!dataFile) {
192
155
  throw new Error(`No LP data file found. Use --data <path> or run fetch_lp_candles.ts first.`);
193
156
  }
@@ -217,7 +180,7 @@ function generateChart(options = {} as Record<string, any>) {
217
180
  amaResults.push({ ...strategy, lineWidth: index === 0 ? 2 : 1.5, values });
218
181
 
219
182
  logger.log(`${strategy.name}`);
220
- logger.log(` ├─ Total Area: ${metrics.totalArea.toFixed(2)}%`);
183
+ logger.log(` ├─ Total Area: ${metrics.totalDeviation.toFixed(2)}%`);
221
184
  logger.log(` ├─ Max UP: ${(metrics.maxDriftUp * 100).toFixed(2)}%`);
222
185
  logger.log(` ├─ Max DOWN: ${(metrics.maxDriftDown * 100).toFixed(2)}%`);
223
186
  logger.log(` └─ Band Factor: ${(metrics.maxDistance * 200).toFixed(2)}%\n`);
@@ -1,10 +1,11 @@
1
+ 'use strict';
1
2
 
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import os from 'node:os';
5
- import { pathToFileURL } from 'node:url';
6
+ import { pathToFileURL, fileURLToPath } from 'node:url';
6
7
  import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
7
- import { calculateAMA } from '../../market_adapter/core/strategies/ama.js';
8
+ import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
8
9
  import { toIntervalLabel } from '../../market_adapter/interval_utils.js';
9
10
  import { generateHTML } from '../../market_adapter/lp_chart_core.js';
10
11
  import { PATHS } from '../../modules/paths.js';
@@ -12,7 +13,6 @@ import { ensureDir } from '../../modules/order/utils/system.js';
12
13
  import { range } from '../math_utils.js';
13
14
  import { getStorage } from '../../modules/storage/index.js';
14
15
  const { readJSON, writeJSON } = getStorage();
15
- 'use strict';
16
16
 
17
17
  import {
18
18
  loadLpDataFile,
@@ -354,8 +354,15 @@ function updateAmaProfilesFile({ dataFile, meta, winners, sourceResultsFile }: {
354
354
  writeJSON(AMA_PROFILES_FILE, payload);
355
355
  }
356
356
 
357
- function calcTotalAmaMovement(amaValues: number[], erPeriod: number): number {
358
- const skip = erPeriod + 1;
357
+ // Warmup skips through the full production AMA seeding + convergence window
358
+ // (getAmaWarmupBars) rather than just the ER seed boundary (erPeriod + 1), so
359
+ // objective metrics are never measured on SMA-warmup or unconverged values.
360
+ function amaWarmupSkip(erPeriod: number, fastPeriod: number, slowPeriod: number): number {
361
+ return getAmaWarmupBars(erPeriod, slowPeriod, 0, fastPeriod);
362
+ }
363
+
364
+ function calcTotalAmaMovement(amaValues: number[], erPeriod: number, fastPeriod: number, slowPeriod: number): number {
365
+ const skip = amaWarmupSkip(erPeriod, fastPeriod, slowPeriod);
359
366
  let total = 0;
360
367
  for (let i = skip + 1; i < amaValues.length; i++) {
361
368
  total += Math.abs(amaValues[i] - amaValues[i - 1]) / amaValues[i - 1];
@@ -365,8 +372,8 @@ function calcTotalAmaMovement(amaValues: number[], erPeriod: number): number {
365
372
 
366
373
  // ── Informational: area above/below AMA ──────────────────────────────────────
367
374
 
368
- function calcArea(amaValues: number[], candles: any[], erPeriod: number) {
369
- const skip = erPeriod + 1;
375
+ function calcArea(amaValues: number[], candles: any[], erPeriod: number, fastPeriod: number, slowPeriod: number) {
376
+ const skip = amaWarmupSkip(erPeriod, fastPeriod, slowPeriod);
370
377
  let above = 0, below = 0, maxUp = 0, maxDown = 0;
371
378
  for (let i = skip; i < candles.length; i++) {
372
379
  const ama = amaValues[i];
@@ -386,8 +393,8 @@ function calcArea(amaValues: number[], candles: any[], erPeriod: number) {
386
393
  return { above, below, total, maxUp, maxDown, maxDist };
387
394
  }
388
395
 
389
- function calcTotalRelativeDistance(amaValues: number[], candles: any[], erPeriod: number): number {
390
- const skip = erPeriod + 1;
396
+ function calcTotalRelativeDistance(amaValues: number[], candles: any[], erPeriod: number, fastPeriod: number, slowPeriod: number): number {
397
+ const skip = amaWarmupSkip(erPeriod, fastPeriod, slowPeriod);
391
398
  let total = 0;
392
399
  for (let i = skip; i < candles.length; i++) {
393
400
  const ama = amaValues[i];
@@ -428,9 +435,9 @@ function runSearchShard(payload: any, onProgress: ((msg: any) => void) | null =
428
435
  valid++;
429
436
 
430
437
  const ama = calculateAMA(closes, { erPeriod: er, fastPeriod: fast, slowPeriod: slow });
431
- const area = calcArea(ama, candles, er);
432
- const amaMovementTotal = calcTotalAmaMovement(ama, er);
433
- const distanceTotal = calcTotalRelativeDistance(ama, candles, er);
438
+ const area = calcArea(ama, candles, er, fast, slow);
439
+ const amaMovementTotal = calcTotalAmaMovement(ama, er, fast, slow);
440
+ const distanceTotal = calcTotalRelativeDistance(ama, candles, er, fast, slow);
434
441
  const bandFactorPct = area.maxDist * 200;
435
442
  const entry = {
436
443
  er, fast, slow,
@@ -454,7 +461,9 @@ function runSearchShard(payload: any, onProgress: ((msg: any) => void) | null =
454
461
 
455
462
  function spawnShardWorker(payload: any, onProgress: ((msg: any) => void) | null): Promise<any> {
456
463
  return new Promise((resolve, reject) => {
457
- const worker = new Worker(__filename, { workerData: { type: 'search_shard', payload } });
464
+ // ESM: resolve this module's path from import.meta.url
465
+ // (__filename is undefined in ES modules).
466
+ const worker = new Worker(fileURLToPath(import.meta.url), { workerData: { type: 'search_shard', payload } });
458
467
  worker.on('message', (msg) => {
459
468
  if (!msg || typeof msg !== 'object') return;
460
469
  if (msg.type === 'progress') {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ama_fitting",
3
- "version": "1.4.20",
3
+ "version": "1.4.22",
4
4
  "description": "Tools for fitting AMA parameters to market data",
5
5
  "main": "../../dist/analysis/ama_fitting/optimizer_high_resolution.js",
6
6
  "scripts": {