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/dist/dexbot.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { getErrorMessage, getErrorCode } from './modules/utils/errors.js';
2
3
  import { fileURLToPath } from 'node:url';
3
4
  import { CLI_COLORS } from './modules/cli_colors.js';
4
5
  import { dirname as _esmDirname } from 'node:path';
@@ -43,17 +44,16 @@ const __dirname = _esmDirname(__filename);
43
44
  * `dexbot help` is the single source of truth (grouped one-liners below;
44
45
  * `dexbot --cli-examples` prints curated snippets):
45
46
  *
46
- * Runtime: dexbot start [bot] | stop | reload | restart | delete | status
47
- * dexbot pm2 [stop|delete|restart|reload|claw-only|update|help]
47
+ * Runtime: dexbot start [bot] | stop | reload | restart | delete | status | pm2
48
48
  * Trading: dexbot test <bot> | drystart <bot> | reset {all|<bot>}
49
49
  * Config: dexbot bot | key | enable {all|<bot>} | disable {all|<bot>} | default | update
50
- * Analysis: dexbot order [<bot>] [--export] | export <bot> | credit [<bot>]
51
- * dexbot tv <target> | dw <target>
50
+ * Analysis: dexbot order [<bot>] | export <bot> | credit [<bot>]
51
+ * dexbot tv <target> | dw <target> | pnl <account>
52
52
  * Files: dexbot clear | clear-orders | clear-market-adapter | clear-all
53
53
  *
54
54
  * NPM SCRIPTS (alternative invocation):
55
- * npm run pm2:start - Start bots (requires ecosystem.config.cjs pre-generated)
56
- * npm run pm2:stop - Stop all PM2 bots
55
+ * npm run pm2:start - Unlock + start bots via PM2 (alias of pm2:unlock)
56
+ * npm run pm2:stop - Stop all dexbot PM2 processes via the launcher
57
57
  * npm run pm2:unlock - Run dist/pm2.js (authenticate + generate config + start all)
58
58
  * npm run pm2:claw-only - Run dist/pm2.js claw-only
59
59
  *
@@ -125,7 +125,6 @@ const { parseWorkerArgs, LAUNCHER_WORKER_COMMAND } = require('./modules/launcher
125
125
  const { PATHS, getHomeProfilesDir, getRecalculateTriggerFile, printRelocationNotices } = require('./modules/paths');
126
126
  const credentialPolicy = require('./modules/credential_policy');
127
127
  const { Config } = require('./modules/config');
128
- const { getErrorMessage } = require('./modules/utils/errors');
129
128
  const { isSameBotName } = require('./modules/utils/sanitize_key');
130
129
  const { normalizeAssetRef } = require('./modules/utils/asset_symbols');
131
130
  // Setup graceful shutdown handlers
@@ -143,28 +142,23 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
143
142
  // Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
144
143
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
145
144
  const PROFILES_DIR = PATHS.PROFILES_DIR;
146
- const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
145
+ const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
147
146
  const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload' };
148
147
  const CLI_HELP_FLAGS = ['-h', '--help'];
149
148
  const CLI_EXAMPLES_FLAG = '--cli-examples';
150
149
  const CLI_EXAMPLES = [
151
- { title: 'Run a bot from the tracked config', command: 'dexbot test <bot>', notes: 'Runs live; targets the named entry in profiles/bots.json.' },
152
- { title: 'Dry-run a bot without broadcasting', command: 'dexbot drystart <bot>', notes: 'Forces the run into dry-run mode even if the stored config was live.' },
153
- { title: 'Disable a bot in config', command: 'dexbot disable <bot>', notes: 'Marks the bot inactive in config.' },
154
- { title: 'Enable a bot in config', command: 'dexbot enable <bot>', notes: 'Marks the bot active in config.' },
155
- { title: 'Reset all active bot grids', command: 'dexbot reset all', notes: 'Triggers full grid regeneration for every active bot.' },
156
- { title: 'Reset a bot grid', command: 'dexbot reset <bot>', notes: 'Triggers a full grid regeneration for the named bot.' },
157
- { title: 'Manage keys', command: 'dexbot key', notes: 'Runs modules/chain_keys.ts to add or update master passwords.' },
158
- { title: 'Edit bot definitions', command: 'dexbot bot', notes: 'Launches the interactive modules/account_bots.ts helper for the JSON config.' },
159
- { title: 'Start bots with PM2', command: 'dexbot pm2', notes: 'Generates ecosystem config, authenticates, and starts PM2.' },
160
- { title: 'Update DEXBot2', command: 'dexbot update', notes: 'Fetches latest code, updates dependencies, and restarts PM2.' },
161
- { title: 'Export bot trades for local analysis', command: 'dexbot export <bot>', notes: 'Exports trading history and settings to CSV/JSON (see analysis/).' },
162
- { title: 'Analyze persisted order grids', command: 'dexbot order', notes: 'Runs the order analyzer across the orders directory (<profiles>/orders) and prints spread/increment/funds/distribution metrics. Add a bot key to render only that bot, and --export for an HTML report.' },
163
- { title: 'Show live credit/MPA positions', command: 'dexbot credit', notes: 'Queries get_margin_positions + get_credit_deals_by_borrower per preferredAccount and prints debt/collateral sums plus one Curr. CR line per whitelisted pair (active CR, else borrow-now CR vs funds avail. on the offer) and one Avar. CR line per bot. CR covers only pairs whitelisted in bots.json and listed on the current credit offer. Add a bot key to render only that bot.' },
164
- { title: 'TradingView chart for a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'Fetches 1h candles for N months (default 3, pool-first with orderbook fallback; --feed charts MPA price-feed history) and writes an auto-named HTML chart.' },
165
- { title: 'PnL report for a bot or blockchain account', command: 'dexbot pnl <bot|account|1.2.x> --month 3 [--pair BASE/QUOTE]', notes: 'Resolves a local bot profile first, then the chain account, analyzes its fills for the requested window and writes a self-contained HTML PnL report.' },
166
- { title: 'Clear all bot log files', command: 'dexbot clear', notes: 'Runs scripts/clear-logs.sh to remove *.log, rotated *.log.N and *.jsonl* from the logs directory (<profiles>/logs), including the credential audit trail daemon-audit.jsonl and its rotated siblings (named in the preview). Offline only: the scripts warn when a live runtime is detected, but a running bot keeps writing to unlinked files and the space is not freed until it restarts; dexbot clear-orders / clear-market-adapter / clear-all are undone within seconds (grid state is re-persisted, the adapter rewrites its state file and lock). Stop first with dexbot stop / dexbot pm2 stop all.' },
167
- { title: 'Reset settings to defaults', command: 'dexbot default', notes: 'Runs scripts/reset-settings.sh to delete general.settings.json, market_profiles.json, and market_adapter_settings.json.' }
150
+ { title: 'Run a bot live', command: 'dexbot test <bot>', notes: 'Runs the named entry in profiles/bots.json once.' },
151
+ { title: 'Dry-run a bot', command: 'dexbot drystart <bot>', notes: 'Same as test, but never broadcasts.' },
152
+ { title: 'Reset every grid', command: 'dexbot reset all', notes: 'Pass a bot name to reset just one.' },
153
+ { title: 'Manage keys', command: 'dexbot key', notes: 'Set up the master password and keyring.' },
154
+ { title: 'Edit bot config', command: 'dexbot bot', notes: 'Interactive bots.json editor.' },
155
+ { title: 'Start bots with PM2', command: 'dexbot pm2', notes: 'Generate the ecosystem config and start PM2.' },
156
+ { title: 'Update DEXBot2', command: 'dexbot update', notes: 'Pull, install, and restart active bots.' },
157
+ { title: 'Export bot trades', command: 'dexbot export <bot>', notes: 'Write trades and settings to CSV/JSON.' },
158
+ { title: 'Analyze order grids', command: 'dexbot order', notes: 'Spread, increment, and funds; --export for HTML.' },
159
+ { title: 'Show live credit positions', command: 'dexbot credit', notes: 'Summed MPA + borrowed-credit positions per bot.' },
160
+ { title: 'Chart a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'OHLC chart; --feed charts MPA price-feed history.' },
161
+ { title: 'PnL report', command: 'dexbot pnl <bot|account> --month 3 [--pair BASE/QUOTE]', notes: 'Self-contained HTML PnL report for the resolved bot or chain account.' }
168
162
  ];
169
163
  const STARTUP_COLORS = {
170
164
  reset: CLI_COLORS.reset,
@@ -194,40 +188,40 @@ function printCLIUsage() {
194
188
  // and the description column is derived, so alignment never drifts.
195
189
  const groups = [
196
190
  ['Runtime', [
197
- ['start [bot]', 'Start the monolithic runtime (--foreground, --isolated, --dryrun, --headless, claw-only, credit).'],
198
- ['stop', 'Stop the monolithic runtime.'],
199
- ['reload', 'Reload the monolithic runtime (leaves credential daemon untouched).'],
200
- ['restart', 'Restart the monolithic runtime (re-unlocks credential daemon).'],
201
- ['delete', 'Stop/delete all runtime processes.'],
202
- ['status', 'Show bot runtime status (unlock monolithic/isolated or PM2).'],
203
- ['pm2 [<sub>]', 'Start all active bots via PM2; also stop/restart/reload/delete (dexbot pm2 help).'],
191
+ ['start [bot]', 'Start the bot runtime (flags below).'],
192
+ ['stop', 'Stop the runtime.'],
193
+ ['reload', 'Reload the runtime without re-unlocking keys.'],
194
+ ['restart', 'Restart the runtime and re-unlock keys.'],
195
+ ['delete', 'Stop and delete all runtime processes.'],
196
+ ['status', 'Show runtime status.'],
197
+ ['pm2 [<sub>]', 'Manage PM2 bots (see: dexbot pm2 help).'],
204
198
  ]],
205
199
  ['Trading', [
206
- ['test <bot>', 'Run the named bot live once (not a dry run).'],
207
- ['drystart <bot>', 'Same as test but forced dry-run.'],
208
- ['reset {all|<bot>}', 'Trigger grid reset(s); auto-reloads if running, else applies on next start.'],
200
+ ['test <bot>', 'Run a bot live once.'],
201
+ ['drystart <bot>', 'Run a bot without broadcasting.'],
202
+ ['reset {all|<bot>}', 'Reset grid state (applies now or on next start).'],
209
203
  ]],
210
204
  ['Config', [
211
- ['bot', 'Interactive bot configurator (bots.json).'],
212
- ['key', 'Set up master password and keyring.'],
205
+ ['bot', 'Interactive bots.json configurator.'],
206
+ ['key', 'Set up the master password and keyring.'],
213
207
  ['enable {all|<bot>}', 'Mark bot(s) active in config.'],
214
208
  ['disable {all|<bot>}', 'Mark bot(s) inactive in config.'],
215
- ['default', 'Reset settings to defaults (deletes generated settings files).'],
216
- ['update', 'Update DEXBot2 from the repository and restart active bots.'],
209
+ ['default', 'Reset generated settings to defaults.'],
210
+ ['update', 'Update DEXBot2 and restart active bots.'],
217
211
  ]],
218
212
  ['Analysis', [
219
- ['order [<bot>]', 'Analyze order grids (spread, increment, funds); --export for HTML.'],
220
- ['export <bot>', 'Export bot trades/settings to CSV/JSON for local analysis.'],
221
- ['credit [<bot>]', 'Live summed MPA + borrowed-credit positions per asset per bot.'],
222
- ['tv <target>', 'TradingView chart: 1h candles for <bot|pool-id|AssetA/AssetB> over --month N (default 3).'],
223
- ['dw <target>', 'Dynamic-weight research chart: same targets/flags as tv (see analysis/).'],
224
- ['pnl <account>', 'PnL HTML report for a bot/account over --month N, optional --pair BASE/QUOTE filter.'],
213
+ ['order [<bot>]', 'Analyze persisted order grids; --export for HTML.'],
214
+ ['export <bot>', 'Export bot trades/settings to CSV/JSON.'],
215
+ ['credit [<bot>]', 'Show live MPA and borrowed-credit positions.'],
216
+ ['tv <target>', 'OHLC chart for <bot|pool-id|AssetA/AssetB>; --month N (default 3), --feed for MPA price-feed history.'],
217
+ ['dw <target>', 'Dynamic-weight research chart; same targets and flags as tv.'],
218
+ ['pnl <account>', 'HTML PnL report for a bot or account; --month N, optional --pair BASE/QUOTE filter.'],
225
219
  ]],
226
220
  ['Files', [
227
- ['clear', 'Delete <profiles>/logs/*.log, *.log.N and *.jsonl* (audit trail included). Stop the runtime first.'],
228
- ['clear-orders', 'Delete persisted grid state in <profiles>/orders (regenerated on next start).'],
229
- ['clear-market-adapter', 'Delete market adapter data, state, lock, and adapter logs.'],
230
- ['clear-all', 'All of the above, plus claw data. Stop the runtime first.'],
221
+ ['clear', 'Delete log files. Stop the runtime first.'],
222
+ ['clear-orders', 'Delete persisted grid state (regenerated on start).'],
223
+ ['clear-market-adapter', 'Delete market adapter data and state.'],
224
+ ['clear-all', 'Delete orders, logs, adapter, and claw data.'],
231
225
  ]],
232
226
  ];
233
227
  const width = Math.max(...groups.flatMap(([, entries]) => entries.map(([cmd]) => cmd.length))) + 2;
@@ -238,6 +232,11 @@ function printCLIUsage() {
238
232
  console.log(` ${cmd.padEnd(width)}${desc}`);
239
233
  }
240
234
  }
235
+ console.log('Runtime flags (dexbot start):');
236
+ console.log(` ${'--foreground'.padEnd(width)}Watch in the terminal (no auto-restart).`);
237
+ console.log(` ${'--isolated'.padEnd(width)}One process per bot.`);
238
+ console.log(` ${'--dryrun'.padEnd(width)}Run without broadcasting.`);
239
+ console.log(` ${'--headless'.padEnd(width)}Non-interactive unlock (--password-file <path> or DEXBOT_MASTER_PASSWORD).`);
241
240
  console.log('Help & options:');
242
241
  console.log(` ${'help, -h, --help'.padEnd(width)}Show this help.`);
243
242
  console.log(` ${'--cli-examples'.padEnd(width)}Print curated CLI snippets.`);
@@ -569,7 +568,7 @@ async function runBotInstances(botEntries, { forceDryRun = false, sourceName = '
569
568
  if (entry.debtPolicy?.lending && (entry.preferredAccount && accountGroups[entry.preferredAccount]?.length > 1)) {
570
569
  for (const item of entry.debtPolicy.lending) {
571
570
  if (item.collateralAsset)
572
- allCollateralRefs.add(item.collateralAsset);
571
+ allCollateralRefs.add(String(item.collateralAsset));
573
572
  }
574
573
  }
575
574
  }
@@ -584,7 +583,7 @@ async function runBotInstances(botEntries, { forceDryRun = false, sourceName = '
584
583
  for (const side of sides) {
585
584
  const pct = entry.botFunds[side];
586
585
  if (pct !== undefined && pct !== null) {
587
- await fundRegistry.registerAllocation(account, botName, side, pct);
586
+ await fundRegistry.registerAllocation(account, botName, side, Number(pct));
588
587
  }
589
588
  }
590
589
  }
@@ -592,7 +591,7 @@ async function runBotInstances(botEntries, { forceDryRun = false, sourceName = '
592
591
  if (botName && entry.debtPolicy?.lending) {
593
592
  const dp = entry.debtPolicy;
594
593
  const globalPct = dp.maxCollateralAmount ?? '100%';
595
- for (const item of dp.lending) {
594
+ for (const item of dp.lending || []) {
596
595
  const collateralRef = item.collateralAsset;
597
596
  if (!collateralRef)
598
597
  continue;
@@ -692,7 +691,7 @@ async function startBotByName(botName, { dryRun = false } = {}) {
692
691
  }
693
692
  const match = entries.find((b) => isSameBotName(b.name, botName));
694
693
  if (!match) {
695
- console.error(startupError(`Could not find any bot named '${botName}' in the tracked settings.`));
694
+ console.error(startupError(`No bot named '${botName}' was found in the tracked settings.`));
696
695
  process.exit(1);
697
696
  }
698
697
  const entryCopy = JSON.parse(JSON.stringify(match));
@@ -738,7 +737,7 @@ async function setBotActiveState(botName, active) {
738
737
  }
739
738
  const match = entries.find((b) => isSameBotName(b.name, botName));
740
739
  if (!match) {
741
- console.error(startupError(`Could not find any bot named '${botName}' to ${action}.`));
740
+ console.error(startupError(`No bot named '${botName}' was found to ${action}.`));
742
741
  process.exit(1);
743
742
  }
744
743
  if ((match.active !== false) === active) {
@@ -772,7 +771,7 @@ async function resetBotByName(botName) {
772
771
  // Filter targets
773
772
  const targets = botName ? entries.filter((b) => isSameBotName(b.name, botName)) : entries.filter((b) => b.active);
774
773
  if (botName && targets.length === 0) {
775
- console.error(startupError(`Could not find any bot named '${botName}' to reset.`));
774
+ console.error(startupError(`No bot named '${botName}' was found to reset.`));
776
775
  process.exit(1);
777
776
  }
778
777
  console.log(`Setting regeneration trigger for ${targets.length} ${targets.length === 1 ? 'bot' : 'bots'}...`);
@@ -1009,6 +1008,26 @@ async function handleCLICommands() {
1009
1008
  process.exit(result.status ?? 0);
1010
1009
  return true;
1011
1010
  }
1011
+ case 'git': {
1012
+ // Repository statistics analyzer (scripts/analyze-git.ts): parses
1013
+ // git history and writes analysis/charts/repo-stats.html. Git-only;
1014
+ // it requires a source checkout (.git present).
1015
+ const { spawnSync } = require('child_process');
1016
+ const scriptArgs = buildRuntimeScriptArgs({
1017
+ codeRoot: __dirname,
1018
+ scriptSegments: ['scripts', 'analyze-git'],
1019
+ });
1020
+ const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1021
+ cwd: PATHS.PROJECT_ROOT,
1022
+ stdio: 'inherit',
1023
+ });
1024
+ if (result.error) {
1025
+ console.error(`git: ${result.error.message}`);
1026
+ process.exit(1);
1027
+ }
1028
+ process.exit(result.status ?? 0);
1029
+ return true;
1030
+ }
1012
1031
  case 'tv':
1013
1032
  case 'dw':
1014
1033
  case 'pnl': {
@@ -1140,11 +1159,11 @@ async function handleCLICommands() {
1140
1159
  unlockRunning = true;
1141
1160
  }
1142
1161
  catch (err) {
1143
- if (err.code === 'EACCES') {
1162
+ if (getErrorCode(err) === 'EACCES') {
1144
1163
  console.warn('[dexbot]', `process.kill(${pid}, 0) EACCES — process exists but permission denied`);
1145
1164
  unlockRunning = true;
1146
1165
  }
1147
- else if (err.code !== 'ESRCH') {
1166
+ else if (getErrorCode(err) !== 'ESRCH') {
1148
1167
  console.warn('[dexbot]', `process.kill(${pid}, 0) unexpected error: ${getErrorMessage(err)}`);
1149
1168
  }
1150
1169
  }
@@ -1168,7 +1187,7 @@ async function handleCLICommands() {
1168
1187
  unlockRunning = true;
1169
1188
  }
1170
1189
  catch (err) {
1171
- if (err.code === 'EACCES')
1190
+ if (getErrorCode(err) === 'EACCES')
1172
1191
  unlockRunning = true;
1173
1192
  }
1174
1193
  }
@@ -1330,7 +1349,7 @@ async function bootstrap() {
1330
1349
  isNewSetup = ensureProfilesDirectory(PROFILES_DIR);
1331
1350
  }
1332
1351
  catch (err) {
1333
- if (err && (err.code === 'EACCES' || err.code === 'EPERM' || err.code === 'EROFS')) {
1352
+ if (err && (getErrorCode(err) === 'EACCES' || getErrorCode(err) === 'EPERM' || getErrorCode(err) === 'EROFS')) {
1334
1353
  const { spawnSync: respawn } = require('child_process');
1335
1354
  const fallbackDir = getHomeProfilesDir();
1336
1355
  console.log(`Config directory not writable at: ${PROFILES_DIR}`);
@@ -15,6 +15,7 @@ import { Config } from '../modules/config.js';
15
15
  * node dist/market_adapter/ama_signal_runner.js --bot <bot> --compact
16
16
  */
17
17
  import { runOnceForAma } from './market_adapter.js';
18
+ import { walkCliArgs } from './cli_args.js';
18
19
  function printHelp() {
19
20
  console.log('AMA signal runner (one cycle): updates candles and returns latest AMA values.');
20
21
  console.log('');
@@ -41,60 +42,26 @@ function parseArgs() {
41
42
  compact: false,
42
43
  overrides: {},
43
44
  };
44
- for (let i = 0; i < args.length; i++) {
45
- const a = args[i];
46
- const v = args[i + 1];
47
- switch (a) {
48
- case '--bot':
49
- out.bot = v;
50
- i++;
51
- break;
52
- case '--deltaPercent':
53
- out.overrides.deltaThresholdPercent = Number(v);
54
- i++;
55
- break;
56
- case '--gridResetFactor':
57
- throw new Error('--gridResetFactor is no longer supported; use --deltaPercent <percent>');
58
- case '--bootstrapHours':
59
- out.overrides.bootstrapLookbackHours = Number(v);
60
- i++;
61
- break;
62
- case '--nativeBackfillHours':
63
- out.overrides.nativeBackfillHours = Number(v);
64
- i++;
65
- break;
66
- case '--maxStaleHours':
67
- out.overrides.maxStaleHours = Number(v);
68
- i++;
69
- break;
70
- case '--sourceRetries':
71
- out.overrides.sourceRetries = Number(v);
72
- i++;
73
- break;
74
- case '--retryDelayMs':
75
- out.overrides.retryDelayMs = Number(v);
76
- i++;
77
- break;
78
- case '--maxPages':
79
- out.overrides.maxPages = Number(v);
80
- i++;
81
- break;
82
- case '--pageLimit':
83
- out.overrides.pageLimit = Number(v);
84
- i++;
85
- break;
86
- case '--compact':
87
- out.compact = true;
88
- break;
89
- case '--help':
90
- case '-h':
91
- printHelp();
92
- process.exit(0);
93
- break;
94
- default:
95
- throw new Error(`Unknown argument: ${a}`);
96
- }
97
- }
45
+ walkCliArgs(args, {
46
+ onHelp: () => {
47
+ printHelp();
48
+ process.exit(0);
49
+ },
50
+ flag: {
51
+ '--compact': () => { out.compact = true; },
52
+ },
53
+ value: {
54
+ '--bot': (v) => { out.bot = v ?? null; },
55
+ '--deltaPercent': (v) => { out.overrides.deltaThresholdPercent = Number(v); },
56
+ '--bootstrapHours': (v) => { out.overrides.bootstrapLookbackHours = Number(v); },
57
+ '--nativeBackfillHours': (v) => { out.overrides.nativeBackfillHours = Number(v); },
58
+ '--maxStaleHours': (v) => { out.overrides.maxStaleHours = Number(v); },
59
+ '--sourceRetries': (v) => { out.overrides.sourceRetries = Number(v); },
60
+ '--retryDelayMs': (v) => { out.overrides.retryDelayMs = Number(v); },
61
+ '--maxPages': (v) => { out.overrides.maxPages = Number(v); },
62
+ '--pageLimit': (v) => { out.overrides.pageLimit = Number(v); },
63
+ },
64
+ });
98
65
  return out;
99
66
  }
100
67
  function isFiniteOrNull(v) {
@@ -1,22 +1,22 @@
1
- /**
2
- * Candle field accessors and transforms — canonical implementations shared by
3
- * the production market adapter and the analysis tooling (via
4
- * analysis/math_utils.ts). Keeps every consumer on one accessor path.
5
- */
6
- declare function getCandleClose(candle: any): any;
7
- declare function getCandleTimestamp(candle: any): any;
8
- declare function normalizeCandle(candle: any): {
1
+ interface AssetRef {
2
+ id?: string | null;
3
+ precision?: unknown;
4
+ }
5
+ interface NormalizedCandle {
9
6
  time: number;
10
7
  open: number;
11
8
  high: number;
12
9
  low: number;
13
10
  close: number;
14
11
  volume: number;
15
- } | null;
16
- declare function tradesToCandles(trades: any, assetA: any, assetB: any, intervalSeconds?: number): any[][];
17
- declare function detectMissingCandleTimestamps(candles: any, intervalSeconds?: number): {
12
+ }
13
+ declare function getCandleClose(candle: unknown): number | null;
14
+ declare function getCandleTimestamp(candle: unknown): number | null;
15
+ declare function normalizeCandle(candle: unknown): NormalizedCandle | null;
16
+ declare function tradesToCandles(trades: unknown[], assetA: AssetRef, assetB: AssetRef, intervalSeconds?: number): number[][];
17
+ declare function detectMissingCandleTimestamps(candles: unknown, intervalSeconds?: number): {
18
18
  gapCount: number;
19
- missingTimestamps: any[];
19
+ missingTimestamps: number[];
20
20
  };
21
21
  /**
22
22
  * Fills gaps in a candle series by carrying forward the last known close price.
@@ -36,7 +36,9 @@ declare function detectMissingCandleTimestamps(candles: any, intervalSeconds?: n
36
36
  * @param {number} [options.baselinePrice] - optional price to use for leading gaps before the first candle
37
37
  * @returns {Array} Filled candle array with no gaps
38
38
  */
39
- declare function fillCandleGaps(candles: any, intervalSeconds: any, startTs?: any, endTs?: any, options?: any): any[];
39
+ declare function fillCandleGaps(candles: unknown, intervalSeconds: unknown, startTs?: number | null, endTs?: number | null, options?: {
40
+ baselinePrice?: number | null;
41
+ }): number[][];
40
42
  /**
41
43
  * Detect a stale trailing run of consecutive zero-volume candles with the
42
44
  * same close price. Returns the tail range so callers can verify with
@@ -49,10 +51,10 @@ declare function fillCandleGaps(candles: any, intervalSeconds: any, startTs?: an
49
51
  * the run length, and the tail close price so the caller can
50
52
  * decide whether to slice.
51
53
  */
52
- declare function detectStaleTail(candles: any, threshold: any): {
53
- sorted: any[];
54
+ declare function detectStaleTail(candles: unknown, threshold: number): {
55
+ sorted: number[][];
54
56
  runLength: number;
55
- lastClose: any;
57
+ lastClose: number;
56
58
  } | null;
57
59
  /**
58
60
  * Prune trailing candles that appear stale — i.e. zero-volume candles carrying
@@ -64,7 +66,15 @@ declare function detectStaleTail(candles: any, threshold: any): {
64
66
  * @param {number} threshold - min consecutive identical closes to prune
65
67
  * @returns {Array} candles with stale tail removed
66
68
  */
67
- declare function pruneStaleTail(candles: any, threshold: any): any;
68
- declare function mergeCandles(a: any, b: any, { onCollision }?: any): any[];
69
- export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles };
69
+ declare function pruneStaleTail(candles: unknown, threshold: number): unknown;
70
+ /**
71
+ * Collision resolver for `mergeCandles`: on a duplicate timestamp keep the
72
+ * candle with the higher volume (index 5). Shared by the window cache and
73
+ * the data-discovery loader so both pick the same winner.
74
+ */
75
+ declare function higherVolumeWins(existing: unknown, incoming: unknown): unknown;
76
+ declare function mergeCandles(a: unknown, b: unknown, { onCollision }?: {
77
+ onCollision?: (existing: unknown, incoming: unknown) => unknown;
78
+ }): number[][];
79
+ export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles, higherVolumeWins };
70
80
  //# sourceMappingURL=candle_utils.d.ts.map
@@ -1,18 +1,17 @@
1
1
  'use strict';
2
- /**
3
- * Candle field accessors and transforms — canonical implementations shared by
4
- * the production market adapter and the analysis tooling (via
5
- * analysis/math_utils.ts). Keeps every consumer on one accessor path.
6
- */
7
2
  function getCandleClose(candle) {
8
3
  if (!candle)
9
4
  return null;
10
- return Array.isArray(candle) ? candle[4] : candle.close;
5
+ if (Array.isArray(candle))
6
+ return candle[4];
7
+ return candle.close;
11
8
  }
12
9
  function getCandleTimestamp(candle) {
13
10
  if (!candle)
14
11
  return null;
15
- return Array.isArray(candle) ? candle[0] : candle.timestamp;
12
+ if (Array.isArray(candle))
13
+ return candle[0];
14
+ return candle.timestamp;
16
15
  }
17
16
  function normalizeCandle(candle) {
18
17
  if (!candle)
@@ -28,12 +27,13 @@ function normalizeCandle(candle) {
28
27
  return null;
29
28
  return { time: Math.floor(ts / 1000), open, high, low, close, volume: Number.isFinite(volume) ? volume : 0 };
30
29
  }
31
- const ts = Number(candle.timestamp ?? candle.ts ?? candle.time);
32
- const open = Number(candle.open);
33
- const high = Number(candle.high);
34
- const low = Number(candle.low);
35
- const close = Number(candle.close);
36
- const volume = Number(candle.volume ?? candle.volumeA ?? 0);
30
+ const c = candle;
31
+ const ts = Number(c.timestamp ?? c.ts ?? c.time);
32
+ const open = Number(c.open);
33
+ const high = Number(c.high);
34
+ const low = Number(c.low);
35
+ const close = Number(c.close);
36
+ const volume = Number(c.volume ?? c.volumeA ?? 0);
37
37
  if (![ts, open, high, low, close].every(Number.isFinite))
38
38
  return null;
39
39
  return { time: Math.floor(ts / 1000), open, high, low, close, volume: Number.isFinite(volume) ? volume : 0 };
@@ -45,8 +45,9 @@ function rawToHuman(rawAmount, precision) {
45
45
  return Number(rawAmount || 0) / Math.pow(10, Number(precision));
46
46
  }
47
47
  function tradeToBPerA(trade, assetA, assetB) {
48
- const sell = trade.sell || {};
49
- const recv = trade.received || {};
48
+ const t = trade;
49
+ const sell = t.sell || {};
50
+ const recv = t.received || {};
50
51
  const sellId = sell.asset_id;
51
52
  const recvId = recv.asset_id;
52
53
  if (!sellId || !recvId)
@@ -70,23 +71,26 @@ function tradeToBPerA(trade, assetA, assetB) {
70
71
  function tradesToCandles(trades, assetA, assetB, intervalSeconds = 3600) {
71
72
  const bucketMs = intervalSeconds * 1000;
72
73
  const sorted = trades.slice().sort((a, b) => {
73
- const tsDelta = a.tsMs - b.tsMs;
74
+ const ta = a;
75
+ const tb = b;
76
+ const tsDelta = ta.tsMs - tb.tsMs;
74
77
  if (tsDelta !== 0)
75
78
  return tsDelta;
76
- const aSeq = Number(a.sequence);
77
- const bSeq = Number(b.sequence);
79
+ const aSeq = Number(ta.sequence);
80
+ const bSeq = Number(tb.sequence);
78
81
  if (Number.isFinite(aSeq) && Number.isFinite(bSeq))
79
82
  return aSeq - bSeq;
80
83
  return 0;
81
84
  });
82
85
  const map = new Map();
83
86
  for (const t of sorted) {
84
- if (!Number.isFinite(t.tsMs))
87
+ const trade = t;
88
+ if (!Number.isFinite(trade.tsMs))
85
89
  continue;
86
90
  const converted = tradeToBPerA(t, assetA, assetB);
87
91
  if (!converted)
88
92
  continue;
89
- const key = Math.floor(t.tsMs / bucketMs) * bucketMs;
93
+ const key = Math.floor(trade.tsMs / bucketMs) * bucketMs;
90
94
  const p = converted.price;
91
95
  const vA = converted.volumeA;
92
96
  const cur = map.get(key);
@@ -268,6 +272,16 @@ function pruneStaleTail(candles, threshold) {
268
272
  const keepCount = sorted.length - runLength;
269
273
  return keepCount > 0 ? sorted.slice(0, keepCount) : [];
270
274
  }
275
+ /**
276
+ * Collision resolver for `mergeCandles`: on a duplicate timestamp keep the
277
+ * candle with the higher volume (index 5). Shared by the window cache and
278
+ * the data-discovery loader so both pick the same winner.
279
+ */
280
+ function higherVolumeWins(existing, incoming) {
281
+ const a = existing;
282
+ const b = incoming;
283
+ return Number(b?.[5] || 0) > Number(a?.[5] || 0) ? incoming : existing;
284
+ }
271
285
  function mergeCandles(a, b, { onCollision } = {}) {
272
286
  const map = new Map();
273
287
  for (const c of [...(a || []), ...(b || [])]) {
@@ -286,5 +300,5 @@ function mergeCandles(a, b, { onCollision } = {}) {
286
300
  }
287
301
  return [...map.values()].sort((x, y) => x[0] - y[0]);
288
302
  }
289
- export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles };
303
+ export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles, higherVolumeWins };
290
304
  //# sourceMappingURL=candle_utils.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Shared argument walker for the market_adapter CLI entry points.
3
+ *
4
+ * The runners expose an overlapping set of source/window tuning flags that
5
+ * must behave identically everywhere (`--bootstrapHours`, `--sourceRetries`,
6
+ * `--maxPages`, the unsupported `--gridResetFactor` guard, ...). Callers
7
+ * register handlers instead of re-listing the same switch cases; the walker
8
+ * owns value consumption, `--help`/`-h`, and the unknown-flag error.
9
+ *
10
+ * Deliberately free of Node globals: callers pass in their own argv and own
11
+ * the `process.exit` policy via `onHelp`, so this module stays browser-safe.
12
+ */
13
+ export interface CliArgHandlers {
14
+ /** Flags that take a value; receives the raw next argv token (never missing or flag-shaped). */
15
+ value?: Record<string, (raw: string) => void>;
16
+ /** Flags that take no value. */
17
+ flag?: Record<string, () => void>;
18
+ /** Invoked for `--help` / `-h`; the caller decides whether to exit. */
19
+ onHelp: () => void;
20
+ }
21
+ export declare function walkCliArgs(args: readonly string[], handlers: CliArgHandlers): void;
22
+ //# sourceMappingURL=cli_args.d.ts.map
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+ export function walkCliArgs(args, handlers) {
3
+ for (let i = 0; i < args.length; i++) {
4
+ const a = args[i];
5
+ if (a === '--gridResetFactor') {
6
+ throw new Error('--gridResetFactor is no longer supported; use --deltaPercent <percent>');
7
+ }
8
+ if (a === '--help' || a === '-h') {
9
+ handlers.onHelp();
10
+ continue;
11
+ }
12
+ const valueHandler = handlers.value?.[a];
13
+ if (valueHandler) {
14
+ const raw = args[i + 1];
15
+ if (raw === undefined || raw.startsWith('--')) {
16
+ throw new Error(`Flag ${a} expects a value; got ${raw === undefined ? 'nothing' : raw}`);
17
+ }
18
+ valueHandler(raw);
19
+ i++;
20
+ continue;
21
+ }
22
+ const flagHandler = handlers.flag?.[a];
23
+ if (flagHandler) {
24
+ flagHandler();
25
+ continue;
26
+ }
27
+ throw new Error(`Unknown argument: ${a}`);
28
+ }
29
+ }
30
+ //# sourceMappingURL=cli_args.js.map