dexbot 1.6.11 → 1.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
package/CHANGELOG.md CHANGED
@@ -2,11 +2,75 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.13] - 2026-10-10 - Spread-Stall Cause Reporting & Chain Sync, Resync-Cascade Guards, Month-Shard Candle Cache, Dedup & Dead-Code Purge, npm 12 Install & PM2 Fixes
6
+
7
+ ### 2026-10-10
8
+
9
+ - **Fix(order-engine)**: report spread-correction stall causes and sync with the chain on every stall — `checkSpreadCondition` reported a single `fundsExhausted` boolean on any zero-placement, so a purely structural "no tightening slot exists" grid re-read account totals + open orders every cooldown (a refresh that cannot change it) and the log always blamed free funds. It now returns a `SpreadCorrectionStall` cause (`no-free-funds` | `unfunded` | `no-candidates` | `batch-not-executed` | `apply-error`) and `prepareSpreadCorrectionOrders` reports `plannedCount`, so "no candidates" is distinguishable from "candidates existed but unfunded"; the TOCTOU re-plan zero-placement branch now carries a cause like every sibling (placed-nothing ⇒ carry-a-cause holds on all paths) and `tightensSpread` rejects null/non-finite prices at the single chokepoint so a price-less rail orphan cannot consume a slice quota seat. Follow-up: the arm is no longer suppressed for `no-candidates` — that cause is derived from LOCAL grid state, and a missed fill leaves a window-edge slot ACTIVE while its chain order is gone, making the phantom the `bestLiveOnRail` and every real tightening slot look non-tightening. `mirrorSpreadStall` now arms the targeted balances + open-orders refresh for every cause, so a stale local snapshot recovers in ~1 tick instead of up to `SPREAD_STALE_ESCALATE_MS` (30 min); the staleness watchdog remains the backstop and a genuinely structural stall pays an account + open-orders read per cooldown while it persists. Covered by `tests/test_spread_correction_market_nearest.ts` (all five causes, the null-price orphan eviction, and the regression where an unfunded plan on one side was masked by an empty opposite side) and `tests/test_targeted_drift_reconcile.ts` (exact cause, flag + cause clear/retain together).
10
+
11
+ - **Fix(order-engine)**: break resync cascades on uncertain broadcast and suspended persistence — a transient credential-daemon ping timeout suspended grid persistence for ~6h because the watchdog never set `_credentialRecoveryNeeded`, so `_runCredentialRecoveryAfterDaemonRestored()` early-returned and `resumeGridPersistence()` was never called; every subsequent COW batch then failed its persist retry and forced a structural grid resync (14 in one window), each clearing the LAST-FILL-GUARD pivot and rebuilding the grid. `resyncIfUnreconciled` now subtracts master-tracked order ids via `collectKnownOnChainOrderIds`, so only chain orders genuinely unknown to master request a resync (UNC-020/021); the COW persist guard treats a `suspended` retry as a deferral (marks the committed grid dirty for the end-of-tick flush, never escalates to a resync, COW-PERSIST-003); and the watchdog sets `_credentialRecoveryNeeded` on a confirmed outage, tolerating one transient timeout via `CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD` while `ENOENT`/`ECONNREFUSED` stay immediate, and uses `TIMING.DAEMON_PING_TIMEOUT_MS` instead of a hardcoded 2s (UNC-009/009b). Impact: fewer structural resyncs and LAST-FILL pivot clears after credential outages and uncertain broadcasts.
12
+
13
+ - **Fix(lifecycle)**: route pm2 npm scripts through the launcher and harden the pm2 bootstrap — `npm run pm2:start`/`pm2:stop` ran raw `pm2 start/stop` against the generated ecosystem, bypassing the keystore unlock and credential daemon (silent no-key runtime); they now delegate to the launcher (`pm2:start` → `pm2:unlock`, `pm2:stop` → `node dist/pm2.js stop all`), and `npm run pm2:stop` also stops dexbot-cred to match `dexbot pm2 stop all`. `pm2.ts` replaces the contradictory `merge_logs: false` + `combine_logs: true` with the canonical `merge_logs: true`, `installPM2` accepts `n`/`no`, resolves npm next to `process.execPath` (version-manager installs land in the right prefix) and verifies `pm2` reachability on all platforms, and dead code (`require.resolve('pm2')` branch, unused `logReuse`, stale comment) is removed.
14
+
15
+ - **Fix(install)**: drop the postinstall hook so npm 12 global installs are clean — npm 12+ blocks dependency lifecycle scripts by default (npm/rfcs#868), so the informational banner never ran and every `npm i -g dexbot` emitted an unsilenceable install-scripts warning (`allowScripts` cannot be self-declared by a package). The hook and `scripts/postinstall.js` are removed; the CLI already prints the same getting-started guidance on first run when no profiles/keyring exist, and `prepare` is untouched. The only loss is two informational banners under npm ≤ 11.
16
+
17
+ - **Refactor(order-engine)**: centralize COW plan-origin labels in `COW_ORIGINS` — the LAST-FILL-GUARD bypass keyed off `origin` strings (`'spread-correction'`, `'gap-evacuation'`) written and read as bare literals in 8 places, so a rename or typo on either side would silently disable a bypass with no compile error. A frozen `COW_ORIGINS` in `modules/constants.ts` is now routed through every producer (`modules/order/grid.ts` planner exits, `stampGapEvacuationRotation`) and consumer (`modules/dexbot_cow_runtime.ts` origin striping, broadcast-loop and final-pivot-gate bypasses). String values are byte-identical; no behavioral change.
18
+
19
+ - **Refactor(cache)**: centralize candle caching on month shards — LP/book/feed fetchers, month-shard naming, query-coverage bookkeeping and LP-series assembly were spread across `window_cache`, `fills_cache`, `data_discovery` and a second LP fetcher. New `market_adapter/utils/month_shards.ts` is the single source for shard key/bounds/range/path/stem naming and coverage-span primitives, imported by both the candle cache and the fills cache so they can no longer disagree on a month boundary; `window_cache` scoped loads enumerate only overlapping calendar-month shards (no directory listing, O(1) per-shard flush lookup, windows aligned to UTC month starts); `data_discovery` gains `loadLatestLpSeries`/`loadLpSeriesFromPath`/`loadLpSeriesFromBasePath` for shard-family assembly; `analysis/ama_fitting/fetch_lp_candles.ts` is now a thin CLI over `fetchCandlesSequentially`; and whole-history exports are derived from assembled shards so a later narrow re-run cannot overwrite them with a subset. `dexbot tv`/`dw`, the optimizer and the analysis loaders share one incremental cache, and `--data <shard>` now yields the full series.
20
+
21
+ - **Refactor(market-adapter)**: deduplicate interval tables, cycle fields and arg parsing — `fetch_cex_synthetic_data.ts` replaces eight near-identical per-exchange interval maps with shape tables plus one `intervalFormatter` (interval output verified identical for every exchange) and fixes the broken `../market_adapter/market_adapter` require so the seed-generator CLI can start; `market_adapter_service.ts` shares the candle-cycle state/result fields via `buildCandleCycleFields()`, the dynamic-weight base inputs and the AMA-slope/weights-meta/dynamicWeights report fragments, and extracts `fetchNativeHistory()` for the duplicated native-fetch try/catch; and a new `cli_args.ts` (`walkCliArgs`) is shared by `market_adapter.ts` and `ama_signal_runner.ts` so the source/window flags, the `--gridResetFactor` guard, `--help` and unknown-flag handling cannot drift between the two entry points. Behavior-preserving.
22
+
23
+ - **Refactor(dedup)**: single-source duplicated helpers and drop dead exports/code — `order/utils/order` gets one `readFillProcessingNumber()` behind the five `resolveCorrection*` readers; `account_orders` replaces 20 inlined read-modify-write preambles with `_reload()`/`_ensureLoaded()`; credit-debt/collateral totals, chain account resolvers, `order/utils/system.sleep()`, `order/format.positiveOrNull()`, shutdown handlers, seam-ms resolution, chain-client caller factories and 56 hand-written lazy require wrappers (via `modules/lazy_shim.ts`) are each collapsed to one home; `analysis/` and `market_adapter/` merge duplicated Kibana sort keys, volatility normalizers, `higherVolumeWins`, `parseChainTimeToMs`, `geometricRange`/`median` and `loadAmaStrategies`, parameterizing the two that legitimately diverged (rounding/quantum, validation/naming) while deliberately NOT merging confirmed-diverged copies (percentile round-vs-floor, `resolveAma`, the classic classifyFills/exportJson pair); a parallel analysis pass extracts `classifyFill`/`matchesAssetRef` into `fills_source`, an option-driven `percentile()`/`fmtNum()` and `loadCandleSeries()` into `math_utils`, a new `analysis/worker_pool.ts` (`runModuleWorker`/`splitIntoShards`, which rejects instead of hanging on a clean worker exit with no result) shared by the optimizer and AMA sweep, shared fee/slope constants plus `consumeBacktestArg()`/`slopeResetThresholdPct()` into bot-fitting `shared_utils`, and `formatTimeLabelFn()`/`refreshChartsPreservingZoomFn()` into `chart_ui` — the last switches TradingView month labels from locale-dependent `toLocaleString()` to a fixed English month table (identical on en locales, deterministic everywhere else), and both bot-fitting backtests now also accept `--reposition`/`--reposition-pct` (additive; no existing flag changed meaning); and dead types (`JsonArray`, `DustCancelResult`, `MissingGenesisReason`), the ignored `fallbackNodes` option, the `quietUnderPm2` opt-in, the single `_onBroadcastRegionEnd` slot and 60 internal-only type exports are removed. Behavior-preserving; covered by `tests/test_chain_orders_account_resolution.ts`.
24
+
25
+ - **Feat(cli)**: add `dexbot git` repository statistics and streamline help — `scripts/analyze-git.ts` is exposed as a source-checkout-only `dexbot git` command (needs `.git`) matching the order/credit/tv dispatch pattern, and the flooding "All Tracked Files" console table is dropped (the HTML chart still renders per-file stats). CLI help is shortened: the multi-line pm2 summary collapses to `| pm2`, a new "Runtime flags (dexbot start)" block keeps `--foreground`/`--isolated`/`--dryrun`/`--headless` discoverable, `pm2 [<sub>]` points at `dexbot pm2 help`, full flag references stay for `tv`/`pnl`/`order`/`dw`, and dev-only `dexbot git` is kept out of the help surfaces (documented in `docs/WORKFLOW.md`). Text-only help diff; no behavior change.
26
+
27
+ - **Chore(tests)**: remove dead and vacuous tests and enforce runner honesty — dropped `test_fee_backwards_compat`/`test_market_fee_deduction` (asserted against local mocks, never imported production), `test_market_adapter_modular`/`test_privatekey_sanitize` (no assertions), `test_color_palette` (ANSI demo), `test_account_selection` (always skipped) and a live-only fee-cache demo, plus two README-only helpers and the removed live runner entry. `test_paths.ts` failure counting now affects the exit code (it previously reported PASS while printing ✗), `walkCliArgs` throws `"Flag X expects a value"` for a missing/flag-shaped value instead of storing `NaN` (negative numerics still accepted), profile-layout-dependent suites (autoderive, analyze-orders, pending-fill-crawls, claw regressions) use temp profile roots or `PATHS.*`, and credential-controller suites replace inert `require.cache` stubbing with the ESM mock loader (they previously passed vacuously). Also dropped the legacy analyzer test build wiring and the stale `analysis/trend_detection/package.json` + its two Kalman suites.
28
+
29
+ - **Chore(claw)**: ratchet claw explicit-`any` and fix plugin paths — the 1.6.12 program claimed the claw subtree was cleaned but it still carried 593 explicit `any` outside the ratchet; `scripts/check_any.ts` now counts root scopes and `claw/` as independent budgets (`any-budget.json` root:4, claw:593) so neither can regress. Claw gains `noUnusedLocals`/`noUnusedParameters` with the revealed dead locals/imports removed, a dead `createRequire`/`require` in `claw_bridge` is dropped, and the OpenClaw plugin's `main`/`openclaw.extensions` now resolve to the compiled `dist/claw` outputs (the source `.js` files were removed in the TS migration).
30
+
31
+ - **Chore(scripts)**: drop stale tools and document the credit analyzer — delete the one-off, pool-hardcoded `scripts/diagnose-kibana-candles.ts` and the dev-only `scripts/git-viewer.sh` (also dropped from the published `files` list); document the previously-unreferenced `analyze-credit.ts` (`dexbot credit`) in `scripts/README.md`.
32
+
33
+ - **Docs**: fix stale references after the month-shard and COW refactors — `analysis/README.md` (fetch_lp_candles is now a thin CLI sharing the month-shard cache; fills-cache shard naming lives in `market_adapter/utils/month_shards.ts`), `docs/COPY_ON_WRITE_MASTER_PLAN.md` (`_currentWorkingGrid` → `_currentWorkingGridStack` + ref-stack API), `market_adapter/README.md` and `scripts/README.md` (any ratchet, analysis scripts, `update_layout.ts`). Docs-only.
34
+
35
+ ## [1.6.12] - 2026-10-08 - Type-Safety Ratchet, Shared ECC & Scrypt Correctness, Fresh-Placement Cancel Grace, Worker Drain & Partial Credit Renewal
36
+
37
+ ### 2026-10-08
38
+
39
+ - **Refactor(types)**: eliminate explicit `any` project-wide behind a downward-only ratchet — explicit `any` is replaced with precise types or `unknown` across the core runtime, order engine, launcher and CLI entry points, native bridge, claw modules and storage layers, the market-adapter pipeline and analysis tooling, and scripts/tests. Shared shapes move into `modules/types.ts`, the DEXBot class / credit-runtime / COW seams and the lazy BitShares proxy are typed, the account-editor draft is typed, and `readJSON` defaults to `Record<string, unknown>`. The new `scripts/check_any.ts` plus `any-budget.json` ratchet (2,204 → 0) counts explicit type tokens only (string/template prose and member accesses such as `Promise.any` are ignored), so the count can only go down. One behavioral fix rides along: `computeCandleStaleness(null)` keeps `Number.isFinite` on the raw value (`Number(null) === 0`) and the `pairObj` cast uses optional chaining so a null pair no longer throws. A guard test pins size-less chain-order tolerance matching (`ParsedChainOrder.size` is `number | undefined`): a size-less parsed order is rejected for a sized slot rather than silently adopted, and the call does not throw. Verified: `tsc --noEmit` clean for root and tests, full suite green (`modules/types.ts`, `scripts/check_any.ts`, `market_adapter/**`, `modules/**`).
40
+
41
+ - **Refactor(crypto)**: share the ECC core between Node and browser and make pure-JS scrypt interoperable — the Node (sync/Buffer) and browser (async/Uint8Array) ECC implementations duplicated the curve math, public-key recovery, verification, DER/WIF encoding and the signing loop verbatim; `modules/bitshares-native/crypto/ecc_core.ts` now holds the platform-neutral parts and both files keep only their sync-vs-async and Buffer-vs-Uint8Array boundaries (`ecc.ts` 396 → 211 lines, `ecc.browser.ts` 350 → 232). A 405-check differential test pins byte-for-byte equality between the two implementations (the browser file previously had no coverage and is `@ts-nocheck`). The browser scrypt (`modules/crypto/pure_scrypt.ts`) had derived a different key than Node `crypto.scrypt` for the same password/salt, so a vault created in a browser could not be unlocked on Node and vice versa: ROMix phase 2 now starts from `X_N = BlockMix(X_{N-1})` per RFC 7914 §5, the single PBKDF2 `deriveBits` call is replaced by RFC 8018 block-wise PBKDF2-HMAC-SHA256 via `subtle.sign` (Firefox caps `deriveBits` output, which made scrypt's 1024-byte first call throw `OperationError`), and empty passwords are handled (WebCrypto rejects zero-length HMAC keys, but HMAC zero-pads sub-block keys). RFC 7914 §12 vectors and native cross-checks (including multi-block PBKDF2 key lengths) were added to `tests/test_browser_abstractions.ts`. Impact: browser and Node now derive identical vault keys; browser vaults created with the previous buggy derivation are not recoverable by the corrected code and would need to be recreated.
42
+
43
+ - **Fix(order-engine)**: defer cancels of freshly placed orders in COW reconcile and divergence paths — the reconcile/COW planner and divergence correction both run on target snapshots that can lag a just-placed order, so a surplus sweep on that snapshot canceled the fresh order (fee bleed, empty level) only for the next cycle to re-place it. `COWRebalanceEngine.execute` now accepts the owning manager and drops the whole slot action group (CANCEL paired with a CREATE) for orders inside `SURPLUS_CANCEL_GRACE_MS`, then re-syncs deferred slots from master via `workingGrid.syncFromMaster`; `applyGridDivergenceCorrections` drops any queued committed-size UPDATE for a not-desired/size-0 slot before skipping the cancel inside the window. The parameter stays optional so tests can drive the engine agelessly, and existing fixtures are aged via `_placedAt.clear()`. Also fixes an orphan double-count: `SyncEngine.synchronizeWithChain`'s createOrder branch kept the deferred-orphan record in `_lastUnmatchedChainOrders` after successful linkage, which fund accounting counts as committed on-chain funds, so a surviving record double-counted the order the slot now sees — the record is now pruned by chain id on successful linkage and kept on rejection or thrown errors. Covered by `tests/test_fresh_placement_cancel_grace_paths.ts` and `tests/test_sync_createorder_unmatched_prune.ts`.
44
+
45
+ - **Fix(order-engine)**: keep spread correction funded by repairing what it places — spread correction on an out-of-spread grid could plan candidates but place nothing. The edge-partial top-up target was always a PARTIAL slot, so `clampPostFillUpdateSize` clamped it to a no-op COW update yet it ran first and consumed the whole budget, leaving the following creates rejected as dust; the target is removed (spread repair is create-only, a top-up cannot move bestBuy/bestSell) and creates are funded exclusively from `funds.available[side]` and the cached `accountTotals[side]Free`, so no resting order is ever shrunk. Candidate ordering now sorts a windowed rail by distance to the live-window anchor instead of raw price, so the correction bridges contiguously from the window and cannot leave an interior hole or over-tighten. `checkSpreadCondition` reports a `stall` cause whenever a correction places nothing — `no-free-funds`/`unfunded`/`no-candidates`/`batch-not-executed`/`apply-error`, merged across the starvation fallback so an unfunded plan on one side is not masked by an empty opposite side — and the targeted-sync refresh arms on the stall, clearing after a successful re-read so it only reconciles on a concrete fund-drift or counted-shortfall signal instead of churning every cycle.
46
+
47
+ - **Fix(order-engine)**: sync with the chain on every spread-correction stall — the previous gate armed the targeted balances + open-orders refresh only for the fund/batch causes and deliberately left a `no-candidates` stall to the out-of-spread staleness watchdog, which can be up to `SPREAD_STALE_ESCALATE_MS` (30 min). But `no-candidates` is derived from the LOCAL grid: a missed fill leaves a slot at the window edge locally ACTIVE while its chain order is gone, so `_getOnChainOrders` makes that phantom the `bestLiveOnRail` and every real tightening slot looks non-tightening. The maintenance mirror (`mirrorSpreadStall`) now arms the refresh for every stall cause, so the next tick re-reads account totals + open orders and virtualizes the phantom; the watchdog remains the backstop. Covered by `tests/test_spread_correction_market_nearest.ts` (a phantom ACTIVE slot reports `no-candidates`, and virtualizing it — what `synchronizeWithChain` does — restores placement) and `tests/test_targeted_drift_reconcile.ts` (the mirror arms every cause; the gate names `no-candidates`).
48
+
49
+ - **Fix(lifecycle)**: drain monolithic workers on stale and absent pid-file stop paths — `stop` returned as soon as the monolithic wrapper exited, but the supervisor pid file is wiped on wrapper exit and the `/proc` worker-drain loop ran only after a clean wrapper exit, so a racing `start` could spawn a SECOND worker over live orders (duplicate trades). `drainMonolithicWorkers` (same 15s deadline, 250ms poll, same warn-on-exhaustion; a failed `/proc` scan yields 0 so it stays a no-op off Linux) is extracted and also run when the pid file is stale (except on `status`) and when there is no wrapper pid file at all for targeted stop/delete and stop-all/delete/restart-all/reload-all. Cost is up to 15s block while a worker lingers, intentional best-effort. Covered by `tests/test_unlock_worker_drain.ts`.
50
+
51
+ - **Fix(credit)**: renew credit deals partially when free balance cannot cover the full deal — renewal repays before the atomic reborrow returns, so when the borrowed asset is deployed into the grid (or the market moved against the collateral) the free balance can be below principal + credit fee, the full repay fails on-chain with "Insufficient Balance", and the deal is left to expire. Each renewal is now sized to the affordable piece (floored to precision, leaving one raw unit as a drift buffer, clamped to the offer's `min_deal_amount` and the policy's `maxBorrowAmountPerOperation`) and the unrepaid remainder keeps its original `latest_repay_time` to be chipped away on later cycles. A reborrow is clamped to the collateral the repay actually released (`capBorrowToCollateral` in the shared builder), applying to the original offer, fallback offers and deferred reborrows; deferred-reborrow retries are bounded (`TIMING.CREDIT_REBORROW_MAX_ATTEMPTS`, default 6, transient offer/source-deal deferrals not counted). The stale-reborrow guard now snapshots pre-repay deal IDs so sibling deals on one offer no longer suppress a legitimate reborrow, and the borrow recompute that could inflate the borrow is dropped. `floorToBlockchainInt`, the on-chain balance-entry lookup and the retry-attempt helper are centralized; sizes are computed in raw integer units with the shared BigInt credit fee so the amount matches the chain's ceil fee and integer collateral release exactly. Covered by `tests/test_credit_runtime.ts`, `tests/test_credit_pricing.ts`, `tests/test_precision_quantization.ts`.
52
+
53
+ - **Fix(market-adapter)**: honor per-bot AMA persistence-gate overrides and align the gate with the replay — the 3-bar persistence gate had three defects: `resolveAmaSlopePersistBars` ORed the global `AMA_SLOPE_PERSIST_ENABLED = true` into the enable flag, so a per-bot `amaSlope.persistEnabled: false` was indistinguishable from unset and the documented rollback was dead (now an explicit tri-state: false disables, true enables, undefined falls back); `amaSlope.persistBars: 0` silently fell through to the global default 3 instead of disabling (now resolves to 1, legacy; negative/NaN still fall back); and `advanceAmaSlopePersistence` ran before trigger A and the grid-range-scaling whitelist check, so a non-whitelisted bot accumulated an unbounded counter and a bar whose price reset failed still advanced (now runs just before the slope reset, gated on `!triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted`, matching `grid_reset_sim`). Regression assertions cover `persistEnabled:false` (nested and flat), `persistBars:0`, `persistBars:2` and `persistEnabled:true`.
54
+
55
+ - **Fix(analyze)**: report boundary-less snapshots by slot type, not rail index — `scripts/analyze-orders.ts` sliced the buy/sell rails with `i <= boundaryIdx`, so a missing boundary (null after GRID-LOAD erases a poisoned persisted boundary) silently collapsed to index 0; live rail orders past slot 0 were hidden/misclassified and the best-buy edge fell onto slot 0 — exactly the recovery state an operator reads `dexbot order` to understand. A finite boundary is now detected explicitly; when absent, slots are classified by type, the slot-0 best-buy fallback returns null, and `boundaryLess` plus a warning banner make clear the counts are type-based not rail geometry. The numeric-boundary path is unchanged. Covered by `tests/test_analyze_orders_dynamic_weight.ts`.
56
+
57
+ - **Fix(update)**: classify the install layout instead of rejecting every non-npm install — `dexbot update` had one failure mode for everything that was not a direct npm global install, conflating two updatable and two must-refuse situations and telling local users to run a no-op `npm update`. The new `scripts/update_layout.ts` is a pure classifier (roots passed in, no fs/spawn) returning the layout, whether it can be replaced in place, and the exact command: npm global is updated in place (`npm install -g <pkg>@<latest>`); local dep is refused with `npm install <pkg>@latest` in the parent project; pnpm/yarn global is detected but refused with the exact manager command (content-addressed/version-hashed trees cannot safely re-resolve and restart the running process); linked/custom-`--prefix`/nested is refused with a reinstall hint. The manager CLI is resolved next to the running Node (`process.execPath`) so a version-manager PATH mismatch no longer rejects a valid global install; manager CLIs spawn via argv with Windows `.cmd` shims routed through `cmd.exe /c`; pnpm globals are classified when Node has resolved the store symlink; Windows paths compare case-insensitively; and the registry probe is best-effort so an unreachable registry installs `@latest` and lets the post-install check confirm. Risk: the Windows spawn branch and the pnpm/yarn refusal are reasoned from documented layouts, not exercised on this host. Covered by `tests/test_update_layout.ts` and `tests/test_update_dist_freshness.ts`.
58
+
59
+ - **Feat(bots)**: default AMA pricing on for new bots when no whitelist record exists — a newly created bot in the interactive editor now defaults the market-adapter "Price" (AMA pricing) flag to true, so a fresh bot participates in AMA recentering without a manual menu-6 toggle. An existing whitelist entry for the bot key is respected; only a genuinely absent record falls back to AMA-on, and the resolved default is persisted on save so the market adapter sees the same value the editor displayed. `modules/market_adapter_whitelist.ts` exports `AMA_ONLY_WHITELIST_FLAGS` and adds `hasWhitelistEntry()` to distinguish a stored all-off entry from an absent one. Covered by `tests/test_account_bots_adapter.ts` and `tests/test_bot_defaults_characterization.ts`.
60
+
61
+ - **Perf(tests)**: cut test-suite wall-clock time (~80s → ~49s sequential, 14.7s with `DEXBOT_TEST_CONCURRENCY=4`, all 315 tests passing) — pure-JS secp256k1 now uses Jacobian projective coordinates so a scalar multiply performs one field inversion instead of one per point operation (native ECC equivalence 8386ms → 1382ms, affine API unchanged); retry/pacing delays become injectable with production-identical defaults (`FILL_PROCESSING.CORRECTION_INTER_OP_DELAY_MS`, `TransportConfig.reconnectBaseDelayMs`, `config.kibanaRetryDelayMs`) so tests no longer sleep; the harness supports bounded concurrency, `multi_asset_distribution` uses loader-hook ESM mocks (previously-inert CJS mocks leaked real WebSocket connections), the stale-daemon watchdog timer is cleared/unref'd, and compute-heavy entropy/clip parity sweeps sample checkpoints instead of every index.
62
+
63
+ - **Refactor(centralize)**: collapse duplicated logic into single sources of truth and drop dead code — CEX candle parsing moves into `market_adapter/inputs/cex_candle_parsing.ts` with declarative `OHLC_*` index tables and a shared row mapper, reducing all nine exchange adapters' `parseCandles` to one-liners (field layout was the only real difference: standard, close-before-high/low, Gate offset, Kraken 7-field); `lp_chart_core` injects the shared `UPLOT_SHARED_SCRIPT`/chart_ui helpers instead of hand-cloning `clampXRange`/`syncXRange`/`bindWheelZoom`/`bindPan`/`bindHoverState`/`resetZoom`, with the shared `bindPan` gaining window-blur/mouseleave drag-end handling (a robustness fix for every generator); `analysis/analyze_args.ts` (`baseAnalysisConfig` + `consumeCommonAnalysisArg`) routes eight analysis runners. Module-level extractions cover credit pricing/ranking, `slotMatchPrecision`/`slotSizeMatches`, account-editor prompt loops, `_flushBatch`, `startPostBootstrapSubsystems`, `createStaleApiEscalation`, `parseBotsContent`, funds formatting, the serializer `lazy_buffer.ts`, and replay-safe fill options. Dead code removed: browser-invisible `pad2()`, unused lambda chart series, unused `decimals`/`_decimals` args that masked fixed precision, legacy draft stripping, unreferenced exports (`LEGACY_DRAFT_KEYS`, `INCREMENT_BOUNDS` factors, `OBJECT_TYPES`, `TRANSPORT RECONNECT_*`, `assertNever`/`CodedError`/`Brand`, `HOME_CONFIG_DIR`/`HOME_PROFILES_DIR`, the `_currentWorkingGrid` accessor), and the backward-compatible `EXPERT` second-pass merge override (risk: an `EXPERT` section in a live `general.settings.json` stops applying silently; `validate_profiles` now flags it as unknown, and no committed/live profile uses it).
64
+
65
+ - **Chore(dynamic-weight)**: retune the research chart's knobs — `lb` narrows 1-32 → 4-32 bars so the AMA-slope lookback can only be dialed within the range the estimator resolves on, and `kalS%` default rises 1.11 → 1.2 with its knob tightened 0.5-1.5 → 0.75-1.5 (a stronger Kalman move is now required before the composite branch reaches full directional strength). `DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT` is a live market-adapter value; the local untracked `profiles/general.settings.json` override was synced to 1.2 separately so the code default is not shadowed.
66
+
67
+ - **Docs**: refresh stale code references, index gaps and tuning guidance — audit of every document linked from `docs/README.md` corrected drifted file/line anchors, symbol names and cross-links across `architecture`, `developer_guide`, `LIFECYCLE`, `FUND_MOVEMENT_AND_ACCOUNTING`, `DEXBOT_COMPARISON`, `GRID_RECONCILE`/`COW_INVARIANTS` (documenting the `SURPLUS_CANCEL_GRACE_MS` fresh-placement deferral as INV-RECON-006), `modules/README` and `GRID_RECALCULATION`; `analysis/` and `market_adapter/` READMEs now name every source file; the never-implemented Telegram design plan and its pointers are removed; and `minPrice`/`maxPrice` tuning is pointed at `dexbot tv <bot>` so the range can be sized from historical price action. Docs-only, no behavior change.
68
+
5
69
  ## [1.6.11] - 2026-10-02 - AMA-Slope Persistence Gate, PnL HTML Report & Fill Cache, Five Order-Engine Safety Fixes
6
70
 
7
71
  ### 2026-10-02
8
72
 
9
- - **Feat(market-adapter)**: gate AMA-slope resets behind a 3-bar persistence window and shorten the Huber lookback to 16 — two coupled default changes measured on a live 1h market-pair pool (`docs/AMA_SLOPE_WINDOW.md`). `DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS` 20 → 16 buys a faster slope signal (AMA group delay 10 → 8 bars, reversal lag 22 → 20, range-tilt wrong-way 13.7% → 12.6%) at ~8% noisier bar-to-bar slope; a new persistence gate on the slope-delta reset trigger (trigger B) — `AMA_SLOPE_PERSIST_ENABLED` (true) + `AMA_SLOPE_PERSIST_BARS` (3) — requires 3 consecutive confirming bars in the same direction before the reset fires, absorbing the shorter window's extra noise. Net vs the old 20h/ungated default: resets −35% (1.45 → 0.95/day), whipsaw ~52% → ~17%, lag and tilt unchanged; the independent price/Drift trigger is unaffected. Per bot/market override via `amaSlope.persistBars` / `amaSlope.persistEnabled`; `1` = legacy fire-on-first-crossing (values `< 1` fall through to the global default). The gate is mirrored everywhere the decision path is replayed so all consumers stay on one logic path: `resolveAmaSlopePersistBars` / `advanceAmaSlopePersistence` in the service (counters persist across restarts via `normalizePersistedAmaSlopeDiagnostics` and clear on every successful reset, bootstrap included), `grid_reset_config` resolves and exports `slopePersistBars` (same override chain), `grid_reset_sim` implements the gate and its panel prints `persist K`, and the backtests follow the production default unless pinned (the fitting harness gains an optional `bandTilt` hook). New tool `analysis/trend_detection/backtest_ama_slope_huber.ts` sweeps the lookback and reports lag, reset churn and noise metrics (`--data` required). Tests: new `test_grid_reset_sim_gate.ts` (K-bar latency, 1-bar blip filtered, direction flip restarts the counter) and `testAmaSlopePersistenceGate`; existing slope-trigger tests pinned to legacy (`persistBars` 1). Verified: `tsc` clean, 305/305 tests, browser bundle 40/40 (`market_adapter/core/market_adapter_service.ts`, `analysis/tradingview/grid_reset_sim.ts`, `modules/constants.ts`, `docs/AMA_SLOPE_WINDOW.md`, `tests/test_grid_reset_sim_gate.ts`).
73
+ - **Feat(market-adapter)**: gate AMA-slope resets behind a 3-bar persistence window and shorten the Huber lookback to 16 — two coupled default changes measured on a live 1h market-pair pool (`docs/AMA_SLOPE_WINDOW.md`). `DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS` 20 → 16 buys a faster slope signal (AMA group delay 10 → 8 bars, reversal lag 22 → 20, range-tilt wrong-way 13.7% → 12.6%) at ~8% noisier bar-to-bar slope; a new persistence gate on the slope-delta reset trigger (trigger B) — `AMA_SLOPE_PERSIST_ENABLED` (true) + `AMA_SLOPE_PERSIST_BARS` (3) — requires 3 consecutive confirming bars in the same direction before the reset fires, absorbing the shorter window's extra noise. Net vs the old 20h/ungated default: resets −35% (1.45 → 0.95/day), whipsaw ~52% → ~17%, lag and tilt unchanged; the independent price/Drift trigger is unaffected. Per bot/market override via `amaSlope.persistBars` / `amaSlope.persistEnabled`; `1` = legacy fire-on-first-crossing, `0` or `persistEnabled: false` disables (the per-bot `false` beats the global default; negative/absent values fall through). The gate is mirrored everywhere the decision path is replayed so all consumers stay on one logic path: `resolveAmaSlopePersistBars` / `advanceAmaSlopePersistence` in the service (counters persist across restarts via `normalizePersistedAmaSlopeDiagnostics` and clear on every successful reset, bootstrap included), `grid_reset_config` resolves and exports `slopePersistBars` (same override chain), `grid_reset_sim` implements the gate and its panel prints `persist K`, and the backtests follow the production default unless pinned (the fitting harness gains an optional `bandTilt` hook). New tool `analysis/trend_detection/backtest_ama_slope_huber.ts` sweeps the lookback and reports lag, reset churn and noise metrics (`--data` required). Tests: new `test_grid_reset_sim_gate.ts` (K-bar latency, 1-bar blip filtered, direction flip restarts the counter) and `testAmaSlopePersistenceGate`; existing slope-trigger tests pinned to legacy (`persistBars` 1). Verified: `tsc` clean, 305/305 tests, browser bundle 40/40 (`market_adapter/core/market_adapter_service.ts`, `analysis/tradingview/grid_reset_sim.ts`, `modules/constants.ts`, `docs/AMA_SLOPE_WINDOW.md`, `tests/test_grid_reset_sim_gate.ts`).
10
74
 
11
75
  - **Refactor(ama)**: remove the two EMA filters and align research charts with the live engine — the AMA had accreted two independent EMA filters that both add lag to address noise the estimator now handles lag-free (the slope is a Huber-robust regression and small residuals are dead-banded): the live `ama.erSmoothPeriod` (an EMA over the raw Efficiency Ratio inside the AMA) and the research `amaEmaSpan` (`--ema`, a post-AMA input EMA in the dynamic-weight chart). Both are removed so the live engine and both research charts run one canonical 3-parameter Kaufman AMA. Live: `ama.ts` gains the 3-param constructor and drops `erSmoothAlpha`/`effectiveER` and the ER-smoothing convergence term from `getAmaWarmupBars`; `AMA_ER_SMOOTH_FAST_PERIOD` is dropped from `constants.ts`; `market_adapter.ts` / `market_adapter_service.ts` / `fetch_cex_synthetic_data.ts` / `log_format.ts` drop the ER-smoothing resolution, warmup, payload fields and the `/esN` log suffix. Research: `analyze_dynamic_weight.ts` + `dynamic_weight_chart_generator.ts` drop the `ema` knob, its Raw reference line and `--ema`; `bot_key_utils` / `resolve_source` / `grid_reset_config` stop threading `erSmoothPeriod`. Two chart divergences from the live regime gate surfaced while verifying parity are also fixed: `peNodes` (the canonical key, not `pNodes`) is passed to `bilinearInterpolate`, and the per-bar multiplier is clamped to 1.0 with 3-decimal rounding before the absolute-threshold dead-band; the AMA clip threshold always comes from `computeAmaSlopeClipThreshold`, so changing the lookback with `clip% = 0` no longer keeps a stale percentile cap. Configs still carrying `ama.erSmoothPeriod` are ignored (the default was 0, so no live behavior change in practice). Docs and tests updated. Verified: `tsc` clean, full suite 303 pass / 0 fail, browser bundle 40/40 (`market_adapter/core/strategies/ama.ts`, `modules/constants.ts`, `analysis/analyze_dynamic_weight.ts`, `analysis/dynamic_weight_chart_generator.ts`).
12
76
 
@@ -685,7 +749,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
685
749
  - **Feat(cli)**: guard raw `npm start` / `pm2 start` with launcher guidance — both previously failed with the cryptic `Missing script: "start"` error or bypassed the credential-daemon unlock, leaving bots unable to reach dexbot-cred; `package.json` gains a `start` guard that prints launcher guidance (`dexbot pm2` / `./pm2` / `npm run pm2:unlock`) and exits 1, and a new root `ecosystem.config.cjs` forwarder rejects raw `pm2 start` the same way; the forwarder ships in the publish `files` list (`package.json`, `ecosystem.config.cjs`).
686
750
  - **Fix(analysis)**: align analysis tools/docs with the AMA optimizer's `_w` result naming — the optimizer writes results as `optimization_results_<base>_w<λ1>_<λ2>_<λ3>_<λ4>.json`, but `backtest_bot_fitting.ts` still auto-derived the legacy unsuffixed path; it now auto-derives the newest `_w*` result in `ama_fitting/` (mtime-based) with a legacy fallback; `analyze_derivatives.ts` drops dead `--pool`/`--precA`/`--precB` flags and unused fields; version:sync targets extended with `analysis/ama_fitting/package-lock.json` and `analysis/trend_detection/package.json` (`analysis/bot_fitting/backtest_bot_fitting.ts`, `analysis/analyze_derivatives.ts`, `analysis/ama_fitting/README.md`, `analysis/bot_fitting/README.md`, `scripts/sync-version.ts`, `AGENTS.md`).
687
751
  - **Fix(claw/tests)**: add strict-mode type annotations across the remaining 16 claw test files (377 TS errors) — explicit params for `clearModule`/`registerMock` helpers, typed call-records (fixing `never[]` inference), typed mock callbacks, `let x: any[] = []` (TS7034/TS7005), `null as any` slots, and `as keyof` index assertions; annotations only, no runtime logic altered (`claw/tests/*.ts`).
688
- - **Docs**: post-1.4.13 documentation audit and Telegram plan rename — `docs/TELEGRAM_IMPLEMENTATION.md` renamed to `docs/TELEGRAM_IMPLEMENTATION_PLAN.md` with a "Proposed — not implemented" banner (EVOLUTION entry kept as planned feature); corrected stale line references (FUND_MOVEMENT_AND_ACCOUNTING, GRID_RECONCILE, COW_INVARIANTS, LOGGING tag table pointing at the split fill/COW/startup runtimes, developer_guide env vars, MPA_CREDIT_USAGE fee rate 1/2900), feature corrections (GRID_RECALCULATION AMA presets, market_adapter warmup table, AMA fitting dataset range/output path, divergence-calc threshold 1 promille, Kalman trend signal inputs, fee_cache fees, ESM-first guidance, Node >= 22.12), Docker/docs updates (node:22 base image, `dexbot start` canonical forms, compose-mode description), and refreshed repo stats (`docs/**`, `claw/skills/**`, `README.md`, `modules/README.md`, `Dockerfile`).
752
+ - **Docs**: post-1.4.13 documentation audit — corrected stale line references (FUND_MOVEMENT_AND_ACCOUNTING, GRID_RECONCILE, COW_INVARIANTS, LOGGING tag table pointing at the split fill/COW/startup runtimes, developer_guide env vars, MPA_CREDIT_USAGE fee rate 1/2900), feature corrections (GRID_RECALCULATION AMA presets, market_adapter warmup table, AMA fitting dataset range/output path, divergence-calc threshold 1 promille, Kalman trend signal inputs, fee_cache fees, ESM-first guidance, Node >= 22.12), Docker/docs updates (node:22 base image, `dexbot start` canonical forms, compose-mode description), and refreshed repo stats (`docs/**`, `claw/skills/**`, `README.md`, `modules/README.md`, `Dockerfile`).
689
753
 
690
754
  ### 2026-08-14
691
755
 
@@ -756,11 +820,10 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
756
820
  - **Fix**: `dexbot start` (and `status`/`stop`/`restart`/`delete`) no longer spawn a hard-coded `dist/unlock.js` — they use `buildRuntimeScriptArgs`, which resolves the unlock entry point per runtime layout (`dist/unlock.js` compiled, `unlock.ts` via tsx in source mode). Previously the source-mode path resolved `modules/dist/unlock.js` (ENOENT → silent `process.exit(0)`), so `dexbot start` was a silent no-op; removed the now-unused `BUILD_DIR` constant (`dexbot.ts`).
757
821
  - **Test**: retarget the CLI tests that validated the in-process one-shot flow to `dexbot test` — after the `start` alias change that flow is covered by the `test` command. `test_dexbot_start_master_password_failure_output.ts`, `test_dexbot_startup_output.ts`, and `test_dexbot_daemon_ready_output.ts` now invoke `test` (previously 282-second suite stall + spurious failures from spawning the real `dist/unlock.js` unlocked password prompts); add `test_dexbot_start_alias_unlock.ts` guarding the `start`→unlock delegation (entry point + exit-status forwarding).
758
822
  - **Fix**: `dexbot status`/`stat` after `dexbot stop` no longer reports "No DEXBot2 processes running" while the credential daemon still runs — `stop` stops bots + market adapter by design but keeps the daemon up for fast re-unlock. `dexbot.ts` now treats a live daemon (via `monolithic-cred.pid`) as a running runtime and delegates to `unlock status`, which gained a branch rendering the daemon (PID/memory/alive/ready/socket) alongside a note that the monolithic runtime (bots + adapter) is stopped; shared `resolveCredentialDaemonForStatus`, `printCredentialDaemonStatusBlock`, and `printMarketAdapterStatusBlock` helpers (`dexbot.ts`, `unlock.ts`, `tests/test_unlock_status_cred_daemon_only.ts`).
759
- - **Docs**: Telegram module implementation plan and aligned EVOLUTION entry (`docs/TELEGRAM_IMPLEMENTATION_PLAN.md`, `docs/EVOLUTION.md`).
760
823
 
761
824
  ### 2026-08-06
762
825
 
763
- - **Docs**: fix stale EVOLUTION release header and broken internal doc links; add Telegram bot to the planned EVOLUTION features.
826
+ - **Docs**: fix stale EVOLUTION release header and broken internal doc links.
764
827
 
765
828
  ### 2026-08-05
766
829
 
package/README.md CHANGED
@@ -194,7 +194,8 @@ Keep the default settings first, and tune these:
194
194
 
195
195
  6. **Tune `minPrice` / `maxPrice`** around the market's volatility range. Once
196
196
  AMA is active, tighten them around the maximum expected market volatility
197
- instead of using an unnecessarily wide range.
197
+ instead of an unnecessarily wide range. Use `dexbot tv <bot>` to see the
198
+ grid range and AMA recentering against real candles.
198
199
 
199
200
  ### Bot Options Reference
200
201
 
@@ -91,7 +91,7 @@ Most runners expect candle data. Two paths to get it:
91
91
  # Via the market adapter LP exporter (recommended for blockchain-backed candles)
92
92
  node dist/market_adapter/inputs/fetch_lp_data.js --pool 133 --precA 4 --precB 5 --interval 1h --lookback 26280h
93
93
 
94
- # Via the analysis fetcher (uses Kibana source directly)
94
+ # Via the analysis fetcher (shares the month-shard candle cache with dexbot tv/dw)
95
95
  node dist/analysis/ama_fitting/fetch_lp_candles.js --pool 1.19.133 \
96
96
  --assetA <ASSET_A> --assetAId <asset_a_id> --assetAPrecision <n> \
97
97
  --assetB <ASSET_B> --assetBId <asset_b_id> --assetBPrecision <n>
@@ -434,21 +434,19 @@ Shared analyzers and chart renderers for the dynamic-weight signal path. Core en
434
434
  | Module | Purpose |
435
435
  |--------|---------|
436
436
  | `dynamic_weight_chart_generator.ts` | 4-panel uPlot chart with interactive knobs for dynamic weight tuning |
437
- | `kalman_trend_analyzer.ts` | Kalman filter with tactical (velocity) and modal (displacement) states |
438
- | `kalman_velocity_smoothing.ts` | Adaptive EMA smoothing for Kalman velocity (kf/kfd/kdt/kfs knobs) |
437
+ | `kalman_trend_analyzer.ts` | Re-export shim → `market_adapter/core/signals/kalman_trend_analyzer.ts` |
438
+ | `kalman_velocity_smoothing.ts` | Re-export shim → `market_adapter/core/signals/kalman_velocity_smoothing.ts` |
439
439
  | `kalman_chart_generator.ts` | Kalman signal chart generator |
440
- | `hurst_analyzer.ts` | Hurst Exponent via R/S analysis (rolling 256-bar window) |
441
- | `permutation_entropy_analyzer.ts` | Permutation Entropy via ordinal pattern counting (m=5, window=54) |
440
+ | `hurst_analyzer.ts` | Re-export shim → `market_adapter/core/signals/hurst_analyzer.ts` |
441
+ | `permutation_entropy_analyzer.ts` | Re-export shim → `market_adapter/core/signals/permutation_entropy_analyzer.ts` |
442
442
  | `volatility_chart_generator.ts` | ATR volatility / symmetric shift chart generator |
443
443
  | `regime_chart_generator.ts` | Regime classification chart generator |
444
444
 
445
445
  </details>
446
446
 
447
- **Tests:**
448
-
449
- ```bash
450
- npm run test:legacy
451
- ```
447
+ The four signal analyzers are canonical in `market_adapter/core/signals/`; the
448
+ files here are thin re-export shims so analysis tooling keeps a local import
449
+ path.
452
450
 
453
451
  **Note:** `trend_detection/` has no external dependencies — runs directly from the compiled build (`node dist/...`).
454
452
 
@@ -523,12 +521,14 @@ Details: [bot_fitting/README.md](bot_fitting/README.md)
523
521
  | `resolve_source.ts` | Shared source resolution: bot-key → candle file, AMA config, `--list-bots` |
524
522
  | `price_sources.ts` | Unified candle source abstraction (`json`, `market_adapter`) |
525
523
  | `chart_utils.ts` | Shared chart rendering utilities |
524
+ | `chart_css.ts` | Shared uPlot CSS fragments for generated charts |
525
+ | `chart_ui.ts` | Shared browser-side uPlot helpers (cursor, hover, zoom-reset, sizing) |
526
526
  | `math_utils.ts` | Shared math utilities |
527
527
  | `bot_key_utils.ts` | Bot-key resolution, candle file lookup, `accountId` persistence (`persistBotAccountId`) |
528
528
  | `account_resolver.ts` | Account resolution for all tools: `preferredAccount` / `--account` → `1.2.x`, stamping the result into `profiles/bots.json` |
529
529
  | `chain_pool.ts` | Ephemeral read-only chain client over the built-in node pool (account + asset lookups) |
530
530
  | `fills_source.ts` | Shared `fill_order` Kibana fetch/query and the static asset-precision table + on-chain cache |
531
- | `fills_cache.ts` | Per-account month-shard cache for `fill_order` fetches (settled months reused, unsettled tail refreshed) |
531
+ | `fills_cache.ts` | Per-account month-shard cache for `fill_order` fetches (settled months reused, unsettled tail refreshed); month-shard naming comes from `market_adapter/utils/month_shards.ts` |
532
532
  | `pnl_report.ts` | Self-contained HTML PnL renderer: hero, card blocks, metrics grid, realized-lots table |
533
533
 
534
534
  On-chain account and asset lookups in the fill-based tools go through `account_resolver.ts` / `fills_source.ts` (both built on `chain_pool.ts`): tool scripts must not open their own read-only clients or carry their own node list. The batch backfill `resolve_bot_accounts.ts` is the exception — it reuses the production chain client over one connection.
@@ -21,9 +21,11 @@ parameters into `profiles/market_profiles.json` for the market adapter.
21
21
 
22
22
  ## Step 1 — Fetch LP Candles
23
23
 
24
- `fetch_lp_candles.ts` fetches bidirectional LP swap data from Kibana and saves
25
- a full uncut candle file. Uses the same `kibana_source` as the market adapter
26
- bootstrap (gaps filled via `candle_utils.fillCandleGaps`), but without pruning.
24
+ `fetch_lp_candles.ts` fetches bidirectional LP swap data from Kibana through
25
+ the shared month-shard cache — the same cache `dexbot tv`/`dexbot dw` write —
26
+ then exports a full uncut candle file. Re-runs reuse the cached months and
27
+ query only the missing buckets; the whole-history file is a convenience
28
+ snapshot of the assembled shards.
27
29
 
28
30
  **Known asset details:**
29
31
 
@@ -1,6 +1,6 @@
1
1
  # TradingView HTML Exporter
2
2
 
3
- This exporter generates a standalone HTML chart in the `analysis/charts/` folder using the local `uPlot`-based TradingView-style renderer.
3
+ This exporter generates a standalone HTML chart in the `analysis/charts/` folder using the local `uPlot`-based TradingView-style renderer. The renderer lives in `analysis/tradingview/tradingview_uplot_chart_generator.ts`; `analysis/tradingview/analyze_tradingview.ts` is the CLI entry point.
4
4
 
5
5
  ## Recommended: `dexbot tv` (One Step)
6
6
 
@@ -96,7 +96,7 @@ Output: `analysis/charts/dynamic_weight_chart.html` (open in browser)
96
96
  | `--chart` | `analysis/charts/dynamic_weight_chart.html` | Output HTML path |
97
97
  | `--alpha` | `0.5` | Initial α blend (0 = pure Kalman, 1 = pure AMA) |
98
98
  | `--dw` | `0.50` | Initial displacement weight (0 = pure velocity, 1 = full displacement) |
99
- | `--lb` | `16` | Initial lookback bars (1-32) for AMA slope calculation |
99
+ | `--lb` | `16` | Initial lookback bars (4-32) for AMA slope calculation |
100
100
  | `--gain` | `1.0` | Initial gain multiplier |
101
101
  | `--clip` | `10` | Initial clip percentile |
102
102
  | `--quiet` | `false` | Suppress console output |
@@ -165,9 +165,9 @@ All panels share aligned vertical time grid lines, and the bottom output panel s
165
165
  | Knob | Range | Default | Purpose |
166
166
  |------|-------|---------|---------|
167
167
  | **nz%** | 0–1 | 0.00 | Neutral zone: dead-band below which offset is forced to 0 |
168
- | **lb** | 1–32 | 16 | Logarithmic. Lookback bars for AMA slope calculation |
168
+ | **lb** | 4–32 | 16 | Logarithmic. Lookback bars for AMA slope calculation |
169
169
  | **amaS%** | 0.06–0.12 | 0.09 | Logarithmic. Gear ratio for per-bar AMA slope saturation |
170
- | **kalS%** | 0.5–1.5 | 1.11 | Logarithmic. Gear ratio for Kalman composite saturation |
170
+ | **kalS%** | 0.75–1.5 | 1.2 | Logarithmic. Gear ratio for Kalman composite saturation |
171
171
  | **clip%** | 0–20 | 10 | Percentile clip: filters extreme inputs (0 = off) |
172
172
 
173
173
  ### Output Controls
package/claw/README.md CHANGED
@@ -233,6 +233,7 @@ Install the native plugin bundle from this repository:
233
233
  ```bash
234
234
  CLAW_ROOT="$(pwd)"
235
235
  DEXBOT_ROOT="$(cd .. && pwd)"
236
+ npm run build
236
237
  openclaw plugins install -l "$CLAW_ROOT"
237
238
  openclaw plugins enable bitshares-claw
238
239
  ```
@@ -319,6 +319,8 @@ type ConstraintSet = {
319
319
 
320
320
  All functions below are implemented in the modules cited under "Core Types" or their headers and are reachable through the adapters/factories they document. Standalone names are exported from the cited modules; methods like `getBotSettings`, `previewBotSettingsUpdate`, `applyBotSettingsPatch`, and `getClawProfileContext` are closures returned by `createDexbotProfileAdapter` (not module-level exports). Signatures reflect the runtime types; see [../modules/types.ts](../modules/types.ts) for the authoritative TypeScript interfaces.
321
321
 
322
+ Internal-only modules that are intentionally **not** re-exported from [../index.ts](../index.ts): `modules/claw_launcher.ts`, `modules/launcher_mode_detector.ts`, `modules/launcher_paths.ts`, `modules/mcp_utils.ts`, `modules/mpa_utils.ts`, `modules/skill_utils.ts`, `modules/utils.ts`, and the type-only `modules/types.ts`. Import them directly when building inside `claw/`; they are not part of the public bridge surface.
323
+
322
324
  ### 1. `createRuntimeContext(options)`
323
325
 
324
326
  Creates a shared runtime object for Claw ([../modules/claw_infra.ts](../modules/claw_infra.ts)).
@@ -41,7 +41,7 @@ That is the practical split:
41
41
  | Basic | `0.5%` | `2.0%` | `20 / 20` | Safe default starting point |
42
42
  | Competitive | `0.4%` | `1.6%` | `10-20 / 10-20` | Liquid enough for tighter quoting |
43
43
  | Very competitive | `0.3%` | `1.2%` | `5-15 / 5-15` | Mature market, higher maintenance, lower slack |
44
- | Good-like / aggressive | `0.2%` | `0.8%` | `3-10 / 3-10` | Only when liquidity, fees, and precision support it |
44
+ | Aggressive | `0.2%` | `0.8%` | `3-10 / 3-10` | Only when liquidity, fees, and precision support it |
45
45
 
46
46
  The main tradeoff is always the same:
47
47
 
@@ -121,7 +121,8 @@ These define the outer range of the grid.
121
121
  - around `2x` = competitive
122
122
  - around `3x` = conservative
123
123
  - above `3x` = very conservative
124
- - treat range ratio as a slow-moving structural setting driven by former price action, not a fast tactical knob
124
+ - treat range ratio as a slow-moving setting driven by former price action, not a fast tactical knob
125
+ - use `dexbot tv <bot>` to see the grid range and AMA recentering against real candles before fixing the bounds
125
126
 
126
127
  ### `gridPrice`
127
128
 
@@ -182,7 +183,7 @@ AMA is the recentering mechanism.
182
183
  - it is calculated from 1h candle closes
183
184
  - it watches how far the adaptive center moves
184
185
  - once the move crosses the configured threshold, DEXBot2 triggers a grid recalculation
185
- - **AMA recently centering requires whitelisting the bot for the market adapter to work live (otherwise it only logs).**
186
+ - **AMA recentering requires whitelisting the bot for the market adapter to work live (otherwise it only logs).**
186
187
  - `gridPrice: "ama"` tells the rebuilt grid to center itself on that AMA reference
187
188
  - `gridPrice: "pool"` or `gridPrice: "book"` centers the rebuilt grid on the live pair price instead
188
189
  - `gridPrice: null` falls back to the current `startPrice` reference
@@ -236,6 +236,9 @@ async function executeOperations(operations: any, options: Record<string, any> =
236
236
  }
237
237
 
238
238
  const client = await getSigningClient(options);
239
+ if (!client) {
240
+ throw new Error('Signing client unavailable');
241
+ }
239
242
  if (client.initPromise) {
240
243
  await client.initPromise;
241
244
  }
@@ -252,7 +255,7 @@ async function executeOperations(operations: any, options: Record<string, any> =
252
255
  if (typeof tx[op.op_name] !== 'function') {
253
256
  throw new Error(`Transaction builder does not support ${op.op_name}`);
254
257
  }
255
- tx[op.op_name](op.op_data);
258
+ (tx[op.op_name] as (data: unknown) => unknown)(op.op_data);
256
259
  }
257
260
 
258
261
  // Direct-key broadcasts must be classified: a timeout/drop here surfaces as
@@ -303,6 +306,9 @@ async function broadcastOperation(operation: any, options: Record<string, any> =
303
306
  }
304
307
 
305
308
  const client = await getSigningClient(options);
309
+ if (!client) {
310
+ throw new Error('Signing client unavailable');
311
+ }
306
312
  try {
307
313
  return await client.broadcast(operation);
308
314
  } catch (err: any) {
@@ -1,7 +1,4 @@
1
1
 
2
- import { createRequire } from 'node:module';
3
- const require = createRequire(import.meta.url);
4
-
5
2
  import { createClawInfrastructure } from './claw_infra.js';
6
3
  import { describeClawBridge } from './claw_manifest.js';
7
4
  import { describeMemuBridge, runMemuCommand } from './memu_bridge.js';
@@ -185,7 +185,7 @@ async function launcherReset(botName: string | null, options: Record<string, any
185
185
 
186
186
  for (const bot of targets) {
187
187
  try {
188
- const triggerFile = getTriggerFile(options, bot.botKey);
188
+ const triggerFile = getTriggerFile(options, bot.botKey || '');
189
189
  storage.writeFile(triggerFile, new Date().toISOString());
190
190
  triggered.push({
191
191
  botName: bot.name,
@@ -177,6 +177,7 @@ function buildRuntimeSetup(runtime: any, repoRoot: string, profileRoot: string)
177
177
  'Install the native plugin from this repository:',
178
178
  '',
179
179
  '```bash',
180
+ 'npm run build',
180
181
  `openclaw plugins install -l ${repoRoot}`,
181
182
  'openclaw plugins enable bitshares-claw',
182
183
  '```',
@@ -33,12 +33,19 @@ function getConfigPath(options: Record<string, any> = {}) {
33
33
  * @param {Object} [options={}]
34
34
  * @returns {Object} { preferredMode, lastUsed, history: [...] }
35
35
  */
36
- function loadConfig(options: Record<string, any> = {}) {
36
+ interface LauncherConfig {
37
+ preferredMode?: string | null;
38
+ lastUsed?: string | null;
39
+ history?: Array<{ mode: string; timestamp: string }>;
40
+ [key: string]: unknown;
41
+ }
42
+
43
+ function loadConfig(options: Record<string, any> = {}): LauncherConfig {
37
44
  const configPath = getConfigPath(options);
38
45
 
39
46
  try {
40
47
  if (storage.exists(configPath)) {
41
- return readJSON(configPath);
48
+ return readJSON<LauncherConfig>(configPath);
42
49
  }
43
50
  } catch (err: any) {
44
51
  // Ignore parse errors, return empty
package/claw/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.11",
3
+ "version": "1.6.13",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
7
- "main": "index.js",
7
+ "main": "../dist/claw/index.js",
8
8
  "peerDependencies": {
9
9
  "openclaw": ">=2026.3.27"
10
10
  },
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "openclaw": {
17
17
  "extensions": [
18
- "./runtimes/openclaw-plugin/index.js"
18
+ "../dist/claw/runtimes/openclaw-plugin/index.js"
19
19
  ]
20
20
  },
21
21
  "scripts": {
@@ -2,7 +2,7 @@
2
2
  "id": "bitshares-claw",
3
3
  "name": "BitShares Claw",
4
4
  "description": "Native BitShares and DEXBot2 tools from the DEXBot2 claw integration",
5
- "version": "1.6.11",
5
+ "version": "1.6.13",
6
6
  "skills": [
7
7
  "skills"
8
8
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bitshares-claw-openclaw-plugin",
3
3
  "private": true,
4
- "version": "1.6.11",
4
+ "version": "1.6.13",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -11,8 +11,8 @@
11
11
  "outDir": "../dist",
12
12
  "rootDir": "..",
13
13
  "strict": true,
14
- "noUnusedLocals": false,
15
- "noUnusedParameters": false,
14
+ "noUnusedLocals": true,
15
+ "noUnusedParameters": true,
16
16
  "esModuleInterop": true,
17
17
  "skipLibCheck": true,
18
18
  "forceConsistentCasingInFileNames": true,
@@ -17,7 +17,7 @@ interface ResolveOptions {
17
17
  interface ResolvedAccount {
18
18
  accountId: string | null;
19
19
  botKey: string | null;
20
- botMeta: any | null;
20
+ botMeta: Record<string, unknown> | null;
21
21
  source: ResolveSource | null;
22
22
  reason: ResolveFailure | null;
23
23
  }
@@ -10,6 +10,7 @@
10
10
  * private copy of this decision tree, of the chain lookup and of the node
11
11
  * handling — all of it lives here now.
12
12
  */
13
+ import { getErrorMessage } from '../modules/utils/errors.js';
13
14
  import { findBotKeyByAccountRef, loadBotMeta, persistBotAccountId, resolveBotKey } from './bot_key_utils.js';
14
15
  import { withReadOnlyClient } from './chain_pool.js';
15
16
  const ACCOUNT_ID_RE = /^1\.2\.\d+$/;
@@ -22,7 +23,7 @@ async function lookupNameOnChain(name) {
22
23
  });
23
24
  }
24
25
  catch (e) {
25
- console.warn(` [warn] Account resolution failed: ${e.message}`);
26
+ console.warn(` [warn] Account resolution failed: ${getErrorMessage(e)}`);
26
27
  return null;
27
28
  }
28
29
  }
@@ -49,14 +49,13 @@ function trackRepositions(amaValues, thresholdPct, warmup) {
49
49
  const avg = steps.length > 0 ? steps.reduce((a, b) => a + b, 0) / steps.length : 0;
50
50
  return { events, steps, min, max, avg };
51
51
  }
52
- // ── Load data ─────────────────────────────────────────────────────────────────
53
52
  function loadData(filePath) {
54
53
  const json = readJSON(filePath);
55
- const candles = json.candles ?? json;
54
+ const candles = (json.candles ?? json);
56
55
  return {
57
56
  candles: candles
58
57
  .map((c) => normalizeCandle(c))
59
- .filter(Boolean)
58
+ .filter((c) => c != null)
60
59
  .map((c) => ({ timestamp: c.time * 1000, close: c.close })),
61
60
  meta: json.meta ?? null,
62
61
  };
@@ -94,7 +93,7 @@ function run() {
94
93
  ? `LP Pool ${meta.pool}`
95
94
  : path.basename(dataFile, '.json');
96
95
  const interval = meta?.intervalSeconds
97
- ? `${meta.intervalSeconds / 3600}h`
96
+ ? `${Number(meta.intervalSeconds) / 3600}h`
98
97
  : '?h';
99
98
  console.log('');
100
99
  console.log('════════════════════════════════════════════════════════════════════════════════');
@@ -10,6 +10,7 @@ import { PATHS } from '../../modules/paths.js';
10
10
  import { MARKET_ADAPTER } from '../../modules/constants.js';
11
11
  import { getErrorMessage } from '../../modules/utils/errors.js';
12
12
  import { uplotInlineTags } from '../chart_utils.js';
13
+ import { geometricRange } from '../math_utils.js';
13
14
  /**
14
15
  * LAMBDA vs SLOW ANALYSIS
15
16
  *
@@ -105,7 +106,6 @@ Options:
105
106
  --help Show this help
106
107
  `);
107
108
  }
108
- // ── Metrics ─────────────────────────────────────────────────────────────────────
109
109
  function calcTotalAmaMovement(amaValues, erPeriod) {
110
110
  const skip = erPeriod + 1;
111
111
  let total = 0;
@@ -123,20 +123,6 @@ function calcTotalRelativeDistance(amaValues, candles, erPeriod) {
123
123
  }
124
124
  return total;
125
125
  }
126
- // ── Geometric range ─────────────────────────────────────────────────────────────
127
- function geometricRange(min, max, count) {
128
- const ratio = Math.pow(max / min, 1 / (count - 1));
129
- const out = [];
130
- for (let i = 0; i < count; i++) {
131
- let v = min * Math.pow(ratio, i);
132
- if (i === 0)
133
- v = min;
134
- if (i === count - 1)
135
- v = max;
136
- out.push(parseFloat(v.toFixed(10)));
137
- }
138
- return [...new Set(out)].sort((a, b) => a - b);
139
- }
140
126
  // ── Precompute (movement, distance) per slow ───────────────────────────────────
141
127
  function precomputeMetrics(closes, candles, erPeriod, fastPeriod, slowValues) {
142
128
  const cache = [];
@@ -184,7 +170,7 @@ function findStartLambda(metricCache, maxSlow, lambdaEnd) {
184
170
  return hi;
185
171
  }
186
172
  // ── HTML Chart (λ → Slow) ──────────────────────────────────────────────────────
187
- function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel, _chartOutPath) {
173
+ function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel) {
188
174
  const xs = results.map((r) => r.lambda);
189
175
  const ys = results.map((r) => r.slow);
190
176
  const dist = results.map((r) => r.distance);
@@ -238,12 +224,8 @@ ${uplotInlineTags()}
238
224
  const slow = ${JSON.stringify(ys)};
239
225
  const dist = ${JSON.stringify(dist)};
240
226
  const move = ${JSON.stringify(move)};
241
- const amaPts = ${JSON.stringify(amaAnnotations)};
242
227
  const cacheSlow = ${JSON.stringify(cacheSlow)};
243
228
  const cacheMove = ${JSON.stringify(cacheMove)};
244
- const revSlow = slow.slice().reverse();
245
- const revMove = move.slice().reverse();
246
- const revDist = dist.slice().reverse();
247
229
 
248
230
  const slowOpts = {
249
231
  width: 1100, height: 440,
@@ -372,7 +354,7 @@ async function run() {
372
354
  const chartName = cfg.outFile || path.join(PATHS.ANALYSIS.CHARTS_DIR, `lambda_vs_slow_er${cfg.fixEr}_fast${cfg.fixFast}_${cfg.lambdaSteps}steps.html`);
373
355
  const chartPath = path.resolve(chartName);
374
356
  ensureDir(path.dirname(chartPath));
375
- const html = generateChartHtml(results, metricCache, cfg.fixEr, cfg.fixFast, dataLabel, chartPath);
357
+ const html = generateChartHtml(results, metricCache, cfg.fixEr, cfg.fixFast, dataLabel);
376
358
  fs.writeFileSync(chartPath, html, 'utf8');
377
359
  console.log(`\n Chart: ${path.relative(process.cwd(), chartPath)}`);
378
360
  console.log('');
@@ -123,7 +123,6 @@ function main() {
123
123
  console.log(`--- ER distribution (erPeriod=${erP}) ---`);
124
124
  console.log(` p5 ${p5} p50 ${p50} p95 ${p95} avg ${refAvgER.toFixed(4)}`);
125
125
  console.log('');
126
- // ── Per-AMA analysis (compute once, cache results) ─────────────────
127
126
  const results = [];
128
127
  // Validate erPeriod / fastPeriod consistency for meaningful naiveSC comparison
129
128
  const erPeriods = new Set();