dexbot 1.6.11 → 1.6.12

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 (354) hide show
  1. package/CHANGELOG.md +35 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +2 -0
  4. package/analysis/tradingview/README.md +1 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  7. package/claw/modules/chain_broadcast.ts +7 -1
  8. package/claw/modules/claw_launcher.ts +1 -1
  9. package/claw/modules/launcher_mode_detector.ts +9 -2
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.d.ts +1 -1
  14. package/dist/analysis/account_resolver.js +2 -1
  15. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  16. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  17. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  18. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  19. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  20. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  21. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  22. package/dist/analysis/analyze_args.d.ts +31 -0
  23. package/dist/analysis/analyze_args.js +41 -0
  24. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  25. package/dist/analysis/analyze_kalman.js +7 -17
  26. package/dist/analysis/analyze_regime.js +7 -17
  27. package/dist/analysis/analyze_regime_windows.js +8 -18
  28. package/dist/analysis/analyze_risk_profile.js +8 -18
  29. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  30. package/dist/analysis/analyze_volatility.js +7 -17
  31. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  32. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
  33. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  34. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
  35. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  36. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  37. package/dist/analysis/bot_key_utils.d.ts +18 -10
  38. package/dist/analysis/bot_key_utils.js +7 -4
  39. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  40. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  41. package/dist/analysis/chain_pool.d.ts +3 -1
  42. package/dist/analysis/chart_ui.d.ts +5 -2
  43. package/dist/analysis/chart_ui.js +6 -3
  44. package/dist/analysis/chart_utils.d.ts +5 -5
  45. package/dist/analysis/chart_utils.js +9 -0
  46. package/dist/analysis/fills_cache.d.ts +1 -1
  47. package/dist/analysis/fills_source.d.ts +2 -2
  48. package/dist/analysis/fills_source.js +14 -12
  49. package/dist/analysis/grid_correction_check.d.ts +1 -1
  50. package/dist/analysis/grid_correction_check.js +12 -11
  51. package/dist/analysis/math_utils.d.ts +7 -6
  52. package/dist/analysis/math_utils.js +5 -8
  53. package/dist/analysis/pnl_report.js +29 -29
  54. package/dist/analysis/price_sources.d.ts +8 -8
  55. package/dist/analysis/price_sources.js +5 -4
  56. package/dist/analysis/resolve_bot_accounts.js +2 -2
  57. package/dist/analysis/resolve_source.d.ts +1 -1
  58. package/dist/analysis/trade_profitability.d.ts +23 -2
  59. package/dist/analysis/trade_profitability.js +50 -50
  60. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  61. package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
  62. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  63. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  64. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  65. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  66. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  67. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
  68. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
  69. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
  70. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  71. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
  72. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  73. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  74. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  75. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  76. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  77. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  78. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  79. package/dist/credential-daemon.js +34 -20
  80. package/dist/dexbot.js +11 -11
  81. package/dist/market_adapter/candle_utils.d.ts +22 -18
  82. package/dist/market_adapter/candle_utils.js +24 -20
  83. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  84. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  85. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  86. package/dist/market_adapter/core/kibana_candles.js +9 -7
  87. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  88. package/dist/market_adapter/core/kibana_client.js +8 -7
  89. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  90. package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
  91. package/dist/market_adapter/core/market_adapter_service.js +137 -113
  92. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  93. package/dist/market_adapter/core/strategies/ama.js +2 -4
  94. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  95. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  96. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  97. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  98. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  99. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  100. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  101. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  102. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  103. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  104. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  106. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  107. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  108. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  109. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  110. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  111. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  112. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
  113. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  114. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  115. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  116. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  117. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  118. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  119. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  120. package/dist/market_adapter/inputs/window_cache.js +8 -8
  121. package/dist/market_adapter/interval_utils.d.ts +4 -4
  122. package/dist/market_adapter/log_format.d.ts +6 -6
  123. package/dist/market_adapter/log_format.js +28 -21
  124. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  125. package/dist/market_adapter/lp_chart_core.js +26 -192
  126. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  127. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  128. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  129. package/dist/market_adapter/market_adapter.d.ts +94 -32
  130. package/dist/market_adapter/market_adapter.js +67 -48
  131. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  132. package/dist/market_adapter/utils/adapter_client.js +2 -2
  133. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  134. package/dist/market_adapter/utils/chain.d.ts +50 -41
  135. package/dist/market_adapter/utils/chain.js +40 -46
  136. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  137. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  138. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  139. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  140. package/dist/market_adapter/utils/file_lock.js +36 -32
  141. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  142. package/dist/market_adapter/utils/native_history.js +35 -28
  143. package/dist/modules/account_bots.d.ts +577 -21
  144. package/dist/modules/account_bots.js +182 -158
  145. package/dist/modules/account_orders.d.ts +66 -30
  146. package/dist/modules/account_orders.js +22 -20
  147. package/dist/modules/authority_resolver.d.ts +12 -2
  148. package/dist/modules/authority_resolver.js +15 -8
  149. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  150. package/dist/modules/bitshares-native/chain_client.js +45 -46
  151. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  152. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  153. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  154. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  155. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  156. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  157. package/dist/modules/bitshares-native/index.d.ts +1 -1
  158. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  159. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  160. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  161. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  162. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  163. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  164. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  165. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  166. package/dist/modules/bitshares-native/serial/types.js +55 -62
  167. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  168. package/dist/modules/bitshares-native/signing_client.js +19 -14
  169. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  170. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  171. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  172. package/dist/modules/bitshares-native/transport.js +5 -4
  173. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  174. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  175. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  176. package/dist/modules/bitshares_client.d.ts +45 -13
  177. package/dist/modules/bitshares_client.js +28 -19
  178. package/dist/modules/bot_defaults.d.ts +6 -15
  179. package/dist/modules/bot_defaults.js +1 -5
  180. package/dist/modules/bot_settings.d.ts +44 -10
  181. package/dist/modules/bot_settings.js +11 -8
  182. package/dist/modules/bots_file_lock.d.ts +6 -6
  183. package/dist/modules/bots_file_lock.js +16 -12
  184. package/dist/modules/broadcast_failure.d.ts +2 -2
  185. package/dist/modules/broadcast_failure.js +5 -4
  186. package/dist/modules/chain_keys.d.ts +42 -40
  187. package/dist/modules/chain_keys.js +53 -45
  188. package/dist/modules/chain_orders.d.ts +93 -59
  189. package/dist/modules/chain_orders.js +31 -23
  190. package/dist/modules/constants.d.ts +527 -31
  191. package/dist/modules/constants.js +15 -47
  192. package/dist/modules/cr_planner.d.ts +40 -2
  193. package/dist/modules/credential_policy.d.ts +68 -8
  194. package/dist/modules/credential_policy.js +37 -31
  195. package/dist/modules/credential_session_cache.d.ts +2 -2
  196. package/dist/modules/credit_pricing.d.ts +42 -6
  197. package/dist/modules/credit_pricing.js +44 -30
  198. package/dist/modules/credit_runtime.d.ts +276 -118
  199. package/dist/modules/credit_runtime.js +462 -165
  200. package/dist/modules/crypto/browser_provider.js +6 -4
  201. package/dist/modules/crypto/node_provider.js +1 -1
  202. package/dist/modules/crypto/pure_scrypt.js +35 -4
  203. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  204. package/dist/modules/crypto/sync.d.ts +9 -9
  205. package/dist/modules/crypto/sync.js +16 -9
  206. package/dist/modules/dexbot_class.d.ts +195 -139
  207. package/dist/modules/dexbot_class.js +78 -28
  208. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  209. package/dist/modules/dexbot_cow_runtime.js +248 -206
  210. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  211. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  212. package/dist/modules/dexbot_fill_runtime.js +48 -41
  213. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  214. package/dist/modules/dexbot_maintenance_runtime.js +108 -83
  215. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  216. package/dist/modules/dexbot_startup_runtime.js +43 -43
  217. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  218. package/dist/modules/dexbot_state_recovery.js +18 -13
  219. package/dist/modules/fund_registry.d.ts +4 -2
  220. package/dist/modules/fund_registry.js +10 -10
  221. package/dist/modules/general_settings.d.ts +30 -4
  222. package/dist/modules/graceful_shutdown.d.ts +3 -3
  223. package/dist/modules/graceful_shutdown.js +2 -2
  224. package/dist/modules/grid_price_source.d.ts +1 -1
  225. package/dist/modules/key_store.d.ts +14 -8
  226. package/dist/modules/key_store.js +7 -6
  227. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  228. package/dist/modules/launcher/adapter_requirement.js +5 -5
  229. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  230. package/dist/modules/launcher/bot_supervisor.js +12 -11
  231. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  232. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  233. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  234. package/dist/modules/launcher/credential_daemon.js +2 -2
  235. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  236. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  237. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  238. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  239. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  240. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  241. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  242. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  243. package/dist/modules/launcher/supervisor_control.js +4 -2
  244. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  245. package/dist/modules/market_adapter_whitelist.js +15 -3
  246. package/dist/modules/node_manager.d.ts +41 -11
  247. package/dist/modules/node_manager.js +5 -4
  248. package/dist/modules/order/accounting.d.ts +53 -24
  249. package/dist/modules/order/accounting.js +16 -15
  250. package/dist/modules/order/async_lock.d.ts +5 -2
  251. package/dist/modules/order/async_lock.js +1 -1
  252. package/dist/modules/order/export.d.ts +7 -6
  253. package/dist/modules/order/export.js +1 -7
  254. package/dist/modules/order/format.d.ts +4 -4
  255. package/dist/modules/order/genesis_policy.d.ts +21 -18
  256. package/dist/modules/order/genesis_policy.js +12 -8
  257. package/dist/modules/order/grid.d.ts +142 -36
  258. package/dist/modules/order/grid.js +148 -123
  259. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  260. package/dist/modules/order/grid_reconcile.js +13 -12
  261. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  262. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  263. package/dist/modules/order/index.d.ts +263 -1
  264. package/dist/modules/order/logger.d.ts +45 -11
  265. package/dist/modules/order/logger.js +38 -40
  266. package/dist/modules/order/logger_state.d.ts +4 -4
  267. package/dist/modules/order/manager.d.ts +225 -180
  268. package/dist/modules/order/manager.js +80 -83
  269. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  270. package/dist/modules/order/processed_fill_store.js +16 -27
  271. package/dist/modules/order/strategy.d.ts +21 -13
  272. package/dist/modules/order/strategy.js +5 -6
  273. package/dist/modules/order/sync_engine.d.ts +91 -33
  274. package/dist/modules/order/sync_engine.js +84 -53
  275. package/dist/modules/order/utils/math.d.ts +157 -102
  276. package/dist/modules/order/utils/math.js +77 -38
  277. package/dist/modules/order/utils/order.d.ts +310 -110
  278. package/dist/modules/order/utils/order.js +122 -99
  279. package/dist/modules/order/utils/slot.d.ts +1 -1
  280. package/dist/modules/order/utils/system.d.ts +176 -26
  281. package/dist/modules/order/utils/system.js +86 -69
  282. package/dist/modules/order/utils/validate.d.ts +89 -41
  283. package/dist/modules/order/utils/validate.js +24 -22
  284. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  285. package/dist/modules/order/utils/withPoolRef.js +18 -12
  286. package/dist/modules/order/working_grid.d.ts +14 -13
  287. package/dist/modules/paths.d.ts +1 -4
  288. package/dist/modules/paths.js +1 -27
  289. package/dist/modules/process_discovery.d.ts +1 -1
  290. package/dist/modules/process_discovery.js +2 -1
  291. package/dist/modules/runtime.d.ts +7 -3
  292. package/dist/modules/runtime.js +4 -3
  293. package/dist/modules/runtime_settings.d.ts +15 -10
  294. package/dist/modules/runtime_settings.js +30 -24
  295. package/dist/modules/settings_merge.d.ts +29 -3
  296. package/dist/modules/settings_merge.js +56 -78
  297. package/dist/modules/socket_json_client.d.ts +7 -4
  298. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  299. package/dist/modules/storage/browser_adapter.js +7 -30
  300. package/dist/modules/storage/index.d.ts +1 -1
  301. package/dist/modules/storage/node_adapter.d.ts +45 -27
  302. package/dist/modules/storage/node_adapter.js +9 -9
  303. package/dist/modules/storage/types.d.ts +5 -4
  304. package/dist/modules/types.d.ts +1071 -2
  305. package/dist/modules/types.js +4 -1
  306. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  307. package/dist/modules/utils/asset_symbols.js +2 -1
  308. package/dist/modules/utils/errors.d.ts +9 -0
  309. package/dist/modules/utils/errors.js +23 -1
  310. package/dist/modules/utils/time_range.d.ts +1 -12
  311. package/dist/modules/utils/time_range.js +1 -1
  312. package/dist/modules/validate_profiles.js +53 -43
  313. package/dist/modules/version_notice.d.ts +14 -3
  314. package/dist/modules/version_notice.js +6 -4
  315. package/dist/pm2.d.ts +29 -27
  316. package/dist/pm2.js +5 -5
  317. package/dist/scripts/analyze-credit.d.ts +2 -1
  318. package/dist/scripts/analyze-credit.js +23 -24
  319. package/dist/scripts/analyze-orders.d.ts +77 -9
  320. package/dist/scripts/analyze-orders.js +65 -40
  321. package/dist/scripts/chart_command.d.ts +27 -18
  322. package/dist/scripts/chart_command.js +13 -11
  323. package/dist/scripts/check_any.d.ts +18 -0
  324. package/dist/scripts/check_any.js +126 -0
  325. package/dist/scripts/diagnose-pool-history.js +12 -7
  326. package/dist/scripts/print_grid.js +0 -1
  327. package/dist/scripts/run-tests.js +39 -7
  328. package/dist/scripts/runner.js +1 -1
  329. package/dist/scripts/test-credit-renewal.js +30 -21
  330. package/dist/scripts/update.d.ts +10 -5
  331. package/dist/scripts/update.js +168 -103
  332. package/dist/scripts/update_dist_freshness.js +1 -0
  333. package/dist/scripts/update_layout.d.ts +61 -0
  334. package/dist/scripts/update_layout.js +180 -0
  335. package/dist/scripts/validate_bots.js +2 -1
  336. package/dist/scripts/verify-browser-bundle.js +8 -0
  337. package/dist/unlock.d.ts +28 -3
  338. package/dist/unlock.js +63 -35
  339. package/docs/BITSHARES_ONBOARDING.md +2 -0
  340. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  341. package/docs/COW_INVARIANTS.md +13 -6
  342. package/docs/DEXBOT_COMPARISON.md +8 -8
  343. package/docs/EVOLUTION.md +10 -9
  344. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  345. package/docs/GRID_RECALCULATION.md +4 -2
  346. package/docs/GRID_RECONCILE.md +14 -3
  347. package/docs/LIFECYCLE.md +11 -11
  348. package/docs/MPA_CREDIT_USAGE.md +22 -3
  349. package/docs/README.md +14 -3
  350. package/docs/architecture.md +12 -9
  351. package/docs/developer_guide.md +6 -6
  352. package/market_adapter/README.md +6 -1
  353. package/modules/README.md +4 -1
  354. package/package.json +4 -1
package/CHANGELOG.md CHANGED
@@ -2,11 +2,43 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.12] - 2026-10-08 - Type-Safety Ratchet, Shared ECC & Scrypt Correctness, Fresh-Placement Cancel Grace, Worker Drain & Partial Credit Renewal
6
+
7
+ ### 2026-10-08
8
+
9
+ - **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/**`).
10
+
11
+ - **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.
12
+
13
+ - **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`.
14
+
15
+ - **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 `fundsExhausted` whenever a correction places nothing and the targeted-sync refresh clears it after a successful re-read, so it only reconciles on a concrete fund-drift or counted-shortfall signal instead of churning every cycle.
16
+
17
+ - **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`.
18
+
19
+ - **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`.
20
+
21
+ - **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`.
22
+
23
+ - **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`.
24
+
25
+ - **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`.
26
+
27
+ - **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`.
28
+
29
+ - **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.
30
+
31
+ - **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).
32
+
33
+ - **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.
34
+
35
+ - **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.
36
+
5
37
  ## [1.6.11] - 2026-10-02 - AMA-Slope Persistence Gate, PnL HTML Report & Fill Cache, Five Order-Engine Safety Fixes
6
38
 
7
39
  ### 2026-10-02
8
40
 
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`).
41
+ - **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
42
 
11
43
  - **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
44
 
@@ -685,7 +717,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
685
717
  - **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
718
  - **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
719
  - **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`).
720
+ - **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
721
 
690
722
  ### 2026-08-14
691
723
 
@@ -756,11 +788,10 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
756
788
  - **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
789
  - **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
790
  - **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
791
 
761
792
  ### 2026-08-06
762
793
 
763
- - **Docs**: fix stale EVOLUTION release header and broken internal doc links; add Telegram bot to the planned EVOLUTION features.
794
+ - **Docs**: fix stale EVOLUTION release header and broken internal doc links.
764
795
 
765
796
  ### 2026-08-05
766
797
 
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
 
@@ -523,6 +523,8 @@ Details: [bot_fitting/README.md](bot_fitting/README.md)
523
523
  | `resolve_source.ts` | Shared source resolution: bot-key → candle file, AMA config, `--list-bots` |
524
524
  | `price_sources.ts` | Unified candle source abstraction (`json`, `market_adapter`) |
525
525
  | `chart_utils.ts` | Shared chart rendering utilities |
526
+ | `chart_css.ts` | Shared uPlot CSS fragments for generated charts |
527
+ | `chart_ui.ts` | Shared browser-side uPlot helpers (cursor, hover, zoom-reset, sizing) |
526
528
  | `math_utils.ts` | Shared math utilities |
527
529
  | `bot_key_utils.ts` | Bot-key resolution, candle file lookup, `accountId` persistence (`persistBotAccountId`) |
528
530
  | `account_resolver.ts` | Account resolution for all tools: `preferredAccount` / `--account` → `1.2.x`, stamping the result into `profiles/bots.json` |
@@ -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
@@ -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) {
@@ -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,
@@ -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,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.11",
3
+ "version": "1.6.12",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
@@ -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.12",
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.12",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -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('════════════════════════════════════════════════════════════════════════════════');
@@ -105,7 +105,6 @@ Options:
105
105
  --help Show this help
106
106
  `);
107
107
  }
108
- // ── Metrics ─────────────────────────────────────────────────────────────────────
109
108
  function calcTotalAmaMovement(amaValues, erPeriod) {
110
109
  const skip = erPeriod + 1;
111
110
  let total = 0;
@@ -184,7 +183,7 @@ function findStartLambda(metricCache, maxSlow, lambdaEnd) {
184
183
  return hi;
185
184
  }
186
185
  // ── HTML Chart (λ → Slow) ──────────────────────────────────────────────────────
187
- function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel, _chartOutPath) {
186
+ function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel) {
188
187
  const xs = results.map((r) => r.lambda);
189
188
  const ys = results.map((r) => r.slow);
190
189
  const dist = results.map((r) => r.distance);
@@ -238,12 +237,8 @@ ${uplotInlineTags()}
238
237
  const slow = ${JSON.stringify(ys)};
239
238
  const dist = ${JSON.stringify(dist)};
240
239
  const move = ${JSON.stringify(move)};
241
- const amaPts = ${JSON.stringify(amaAnnotations)};
242
240
  const cacheSlow = ${JSON.stringify(cacheSlow)};
243
241
  const cacheMove = ${JSON.stringify(cacheMove)};
244
- const revSlow = slow.slice().reverse();
245
- const revMove = move.slice().reverse();
246
- const revDist = dist.slice().reverse();
247
242
 
248
243
  const slowOpts = {
249
244
  width: 1100, height: 440,
@@ -372,7 +367,7 @@ async function run() {
372
367
  const chartName = cfg.outFile || path.join(PATHS.ANALYSIS.CHARTS_DIR, `lambda_vs_slow_er${cfg.fixEr}_fast${cfg.fixFast}_${cfg.lambdaSteps}steps.html`);
373
368
  const chartPath = path.resolve(chartName);
374
369
  ensureDir(path.dirname(chartPath));
375
- const html = generateChartHtml(results, metricCache, cfg.fixEr, cfg.fixFast, dataLabel, chartPath);
370
+ const html = generateChartHtml(results, metricCache, cfg.fixEr, cfg.fixFast, dataLabel);
376
371
  fs.writeFileSync(chartPath, html, 'utf8');
377
372
  console.log(`\n Chart: ${path.relative(process.cwd(), chartPath)}`);
378
373
  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();
@@ -123,17 +123,17 @@ function validateArgs(args) {
123
123
  throw new Error('--pool is required');
124
124
  if (!args.assetAId)
125
125
  throw new Error('--assetAId is required');
126
- if (!Number.isFinite(args.assetAPrecision))
126
+ if (!Number.isFinite(Number(args.assetAPrecision)))
127
127
  throw new Error('--assetAPrecision is required');
128
128
  if (!args.assetBId)
129
129
  throw new Error('--assetBId is required');
130
- if (!Number.isFinite(args.assetBPrecision))
130
+ if (!Number.isFinite(Number(args.assetBPrecision)))
131
131
  throw new Error('--assetBPrecision is required');
132
- if (!Number.isFinite(args.hours) || args.hours <= 0)
132
+ if (!Number.isFinite(Number(args.hours)) || Number(args.hours) <= 0)
133
133
  throw new Error('--hours must be > 0');
134
134
  // Reject unknown/NaN intervals here instead of letting NaN flow silently
135
135
  // into Kibana range queries (production throws on unsupported intervals).
136
- if (!Number.isFinite(args.intervalSeconds) || args.intervalSeconds <= 0) {
136
+ if (!Number.isFinite(Number(args.intervalSeconds)) || Number(args.intervalSeconds) <= 0) {
137
137
  throw new Error('Unsupported --interval: use one of 1m, 5m, 15m, 1h, 4h, 1d or a positive number of seconds');
138
138
  }
139
139
  }
@@ -13,11 +13,27 @@ declare function parseArgs(argv: string[]): {
13
13
  quiet: boolean;
14
14
  help: boolean;
15
15
  };
16
- declare function generateChart(options?: Record<string, any>): {
17
- dataFile: any;
16
+ interface GenerateChartOptions {
17
+ logger?: {
18
+ log: (...args: unknown[]) => void;
19
+ };
20
+ dataFile?: string | null;
21
+ outFile?: string | null;
22
+ strategies?: typeof DEFAULT_STRATEGIES;
23
+ [key: string]: unknown;
24
+ }
25
+ declare function generateChart(options?: GenerateChartOptions): {
26
+ dataFile: string;
18
27
  outFile: string;
19
- amaResults: any[];
20
- meta: any;
28
+ amaResults: (Record<string, unknown> & {
29
+ values: number[];
30
+ })[];
31
+ meta: {
32
+ assetA: {};
33
+ assetB: {};
34
+ intervalSeconds: {};
35
+ fetchedAt: {};
36
+ };
21
37
  candleArrays: number[][];
22
38
  };
23
39
  declare function run(argv?: string[]): void;
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ import { getErrorMessage } from '../../modules/utils/errors.js';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { pathToFileURL } from 'node:url';
@@ -72,14 +73,16 @@ function loadCandles(dataFile) {
72
73
  const candleArrays = normalized.map(c => [c.time * 1000, c.open, c.high, c.low, c.close, c.volume]);
73
74
  return { dataFile: resolved, meta, candleObjects, candleArrays };
74
75
  }
75
- // ── Output path ────────────────────────────────────────────────────────────────
76
76
  function defaultChartPath(meta) {
77
- const intervalLabel = meta?.intervalSeconds
78
- ? toIntervalLabel(meta.intervalSeconds)
77
+ const intervalSeconds = Number(meta?.intervalSeconds);
78
+ const intervalLabel = Number.isFinite(intervalSeconds) && intervalSeconds > 0
79
+ ? toIntervalLabel(intervalSeconds)
79
80
  : '1h';
81
+ const assetA = meta?.assetA;
82
+ const assetB = meta?.assetB;
80
83
  const suffix = meta?.pool
81
84
  ? `pool_${String(meta.pool).replace('1.19.', '')}`
82
- : `${meta?.assetA?.symbol || 'unknown'}_${meta?.assetB?.symbol || 'pair'}`;
85
+ : `${assetA?.symbol || 'unknown'}_${assetB?.symbol || 'pair'}`;
83
86
  return path.join(CHARTS_DIR, `lp_chart_${suffix}_${intervalLabel}_UNIFIED_COMPARISON.html`);
84
87
  }
85
88
  // ── Help ───────────────────────────────────────────────────────────────────────
@@ -99,7 +102,7 @@ Options:
99
102
 
100
103
  Notes:
101
104
  - If --data is omitted, the newest lp_pool_*.json under market_adapter/data/lp is used.
102
- - Accepts any candle JSON: flat [[ts,o,h,l,c,v],...], {candles: [...]}, or {data: [...]}.
105
+ - Accepts several candle JSON shapes: flat [[ts,o,h,l,c,v],...], {candles: [...]}, or {data: [...]}.
103
106
  - Separate from Kibana fetching — use fetch_lp_candles.ts to pull data first.
104
107
  `);
105
108
  }
@@ -192,7 +195,7 @@ function run(argv = process.argv.slice(2)) {
192
195
  });
193
196
  }
194
197
  catch (e) {
195
- console.error('Error:', e?.message ?? e);
198
+ console.error('Error:', getErrorMessage(e));
196
199
  process.exitCode = 1;
197
200
  }
198
201
  }
@@ -74,7 +74,7 @@ function geometricRange(min, max, count, quantum = null) {
74
74
  }
75
75
  return [...new Set(out)].sort((a, b) => a - b);
76
76
  }
77
- function buildDimension(_label, cfg) {
77
+ function buildDimension(cfg) {
78
78
  const min = Number(cfg.min);
79
79
  const max = Number(cfg.max);
80
80
  const step = Number(cfg.step);
@@ -262,13 +262,13 @@ function getAmaObjectivesFromArgs(args) {
262
262
  const objectives = cloneObjectives();
263
263
  for (const o of objectives) {
264
264
  const id = o.key.toLowerCase();
265
- const cap = args[`${id}Cap`];
265
+ const cap = Number(args[`${id}Cap`]);
266
266
  if (Number.isFinite(cap))
267
267
  o.distanceCapQuantile = cap;
268
268
  if (!Number.isFinite(o.distanceCapQuantile) || o.distanceCapQuantile <= 0 || o.distanceCapQuantile > 1) {
269
269
  throw new Error(`Invalid cap for ${o.key}: ${o.distanceCapQuantile}. Use 0 < cap <= 1`);
270
270
  }
271
- const w = args[`${id}Weight`];
271
+ const w = Number(args[`${id}Weight`]);
272
272
  if (Number.isFinite(w)) {
273
273
  if (w <= 0)
274
274
  throw new Error(`${o.key} distanceWeight must be positive, got ${w}`);
@@ -278,7 +278,10 @@ function getAmaObjectivesFromArgs(args) {
278
278
  return objectives;
279
279
  }
280
280
  function ensureValidRange(label, cfg) {
281
- const { min, max, step, count } = cfg;
281
+ const min = Number(cfg.min);
282
+ const max = Number(cfg.max);
283
+ const step = Number(cfg.step);
284
+ const count = Number(cfg.count);
282
285
  if (!Number.isFinite(min) || !Number.isFinite(max) || max < min) {
283
286
  throw new Error(`Invalid ${label} range: min=${min}, max=${max}`);
284
287
  }
@@ -290,7 +293,7 @@ function ensureValidRange(label, cfg) {
290
293
  }
291
294
  function boundaryFlags(winner, erValues, fastValues, slowValues, fixedEr = null, fixedFast = null) {
292
295
  if (!winner)
293
- return { er: null, fast: null, slow: null, any: false };
296
+ return { er: null, fast: null, slow: null, onBoundary: false };
294
297
  const eps = 1e-9;
295
298
  const minEr = erValues[0], maxEr = erValues[erValues.length - 1];
296
299
  const minFast = fastValues[0], maxFast = fastValues[fastValues.length - 1];
@@ -298,7 +301,7 @@ function boundaryFlags(winner, erValues, fastValues, slowValues, fixedEr = null,
298
301
  const er = Number.isFinite(fixedEr) ? null : (Math.abs(winner.er - minEr) < eps ? 'min' : (Math.abs(winner.er - maxEr) < eps ? 'max' : null));
299
302
  const fast = Number.isFinite(fixedFast) ? null : (Math.abs(winner.fast - minFast) < eps ? 'min' : (Math.abs(winner.fast - maxFast) < eps ? 'max' : null));
300
303
  const slow = Math.abs(winner.slow - minSlow) < eps ? 'min' : (Math.abs(winner.slow - maxSlow) < eps ? 'max' : null);
301
- return { er, fast, slow, any: !!(er || fast || slow) };
304
+ return { er, fast, slow, onBoundary: !!(er || fast || slow) };
302
305
  }
303
306
  // ── Data loaders ──────────────────────────────────────────────────────────────
304
307
  function normalizeSymbol(value) {
@@ -514,9 +517,9 @@ async function run() {
514
517
  ensureValidRange('ER', args.er);
515
518
  ensureValidRange('Fast', args.fast);
516
519
  ensureValidRange('Slow', args.slow);
517
- const erDim = buildDimension('ER', args.er);
518
- const fastDim = buildDimension('Fast', args.fast);
519
- const slowDim = buildDimension('Slow', args.slow);
520
+ const erDim = buildDimension(args.er);
521
+ const fastDim = buildDimension(args.fast);
522
+ const slowDim = buildDimension(args.slow);
520
523
  const ER_VALUES = Number.isFinite(args.fixedEr) ? [args.fixedEr] : erDim.values;
521
524
  const FAST_VALUES = Number.isFinite(args.fixedFast) ? [args.fixedFast] : fastDim.values;
522
525
  const SLOW_VALUES_AREA = slowDim.values;
@@ -677,7 +680,7 @@ async function run() {
677
680
  console.log(' Boundary Check');
678
681
  console.log('────────────────────────────────────────────────────────────────────────────────');
679
682
  for (const [name, b] of Object.entries(boundarySummary)) {
680
- const txt = b.any ? `ER:${b.er || '-'} Fast:${b.fast || '-'} Slow:${b.slow || '-'}` : 'none';
683
+ const txt = b.onBoundary ? `ER:${b.er || '-'} Fast:${b.fast || '-'} Slow:${b.slow || '-'}` : 'none';
681
684
  console.log(`${name.padEnd(24)} ${txt}`);
682
685
  }
683
686
  console.log();
@@ -772,8 +775,9 @@ async function run() {
772
775
  }
773
776
  }
774
777
  if (!isMainThread) {
775
- if (workerData?.type === 'search_shard') {
776
- const result = runSearchShard(workerData.payload, (p) => {
778
+ const workerMessage = workerData;
779
+ if (workerMessage?.type === 'search_shard') {
780
+ const result = runSearchShard(workerMessage.payload, (p) => {
777
781
  parentPort.postMessage({ type: 'progress', ...p });
778
782
  });
779
783
  parentPort.postMessage({ type: 'done', result });
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Shared command-line parsing for the analysis runners.
3
+ *
4
+ * Every analysis CLI accepts the same base flags (`--source`, `--bot-key`,
5
+ * `--file`, `--list-bots`, `--quiet`) plus its own tool-specific options. The
6
+ * helpers here own the shared base so each `parseArgs` only has to describe the
7
+ * flags it adds.
8
+ */
9
+ import type { SourceConfig } from './resolve_source.js';
10
+ /** Fields every analysis CLI config shares. */
11
+ export interface AnalysisBaseConfig {
12
+ source: {
13
+ type: string;
14
+ config: SourceConfig;
15
+ };
16
+ quiet: boolean;
17
+ listBots: boolean;
18
+ }
19
+ /** Fresh base config for the common `--source market_adapter --bot-key <key>` flow. */
20
+ export declare function baseAnalysisConfig(): AnalysisBaseConfig;
21
+ /**
22
+ * Consume one of the flags shared by every analysis CLI
23
+ * (`--source`, `--bot-key`, `--file`, `--list-bots`, `--quiet`).
24
+ *
25
+ * @param next returns the next argv token and advances the caller's index,
26
+ * e.g. `() => args[++i]`.
27
+ * @returns true when the flag was recognized (and any value consumed), so the
28
+ * caller can `continue` to the next token.
29
+ */
30
+ export declare function consumeCommonAnalysisArg(arg: string, next: () => string, config: AnalysisBaseConfig): boolean;
31
+ //# sourceMappingURL=analyze_args.d.ts.map