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
@@ -5,7 +5,7 @@
5
5
  * Manages multi-bot configuration and metadata.
6
6
  *
7
7
  * ===============================================================================
8
- * EXPORTS (5 functions)
8
+ * EXPORTS (10 functions)
9
9
  * ===============================================================================
10
10
  *
11
11
  * MAIN ENTRY POINT:
@@ -16,11 +16,12 @@
16
16
  * normalizeBotDraft(base) - Normalize a bot configuration draft
17
17
  * Applies defaults and validation to raw bot config entries
18
18
  *
19
- * parseJsonWithComments(raw) - Parse JSON with comment stripping
20
- * (re-exported from ./order/utils/system.js)
19
+ * loadGeneralSettings() - Load profiles/general.settings.json
21
20
  *
22
- * parseCronToDelta(cronString) - Parse a cron expression to { days, time }
23
- * deltaToCron(days, time) - Convert { days, time } back to a cron expression
21
+ * SUPPORTING EXPORTS:
22
+ * ensureBotAccountId, parseJsonWithComments, parseBooleanInput,
23
+ * colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice,
24
+ * isPoolRefClearInput
24
25
  *
25
26
  * INTERNAL HELPERS (not exported):
26
27
  * ask* prompt family (askString, askNumberWithBounds, askIntegerInRange,
@@ -29,11 +30,12 @@
29
30
  * askMaxPrice, askWeightDistribution, askWeightDistributionNoLegend,
30
31
  * askLogLevel, askUpdaterBranch, askCronSchedule, askBoolean),
31
32
  * loadBotsConfig, saveBotsConfig, listBots, selectBotIndex,
32
- * loadGeneralSettings, saveGeneralSettings, isMultiplierString,
33
+ * saveGeneralSettings, isMultiplierString,
33
34
  * colorPriceRangeValue, colorMultiplierInput,
34
35
  * isPercentageString, colorPercentageInput,
35
- * isDynamicPriceSource, colorStartPriceValue, colorGridPriceValue,
36
+ * isDynamicPriceSource, colorStartPriceValue,
36
37
  * colorBooleanFlag,
38
+ * parseCronToDelta, deltaToCron,
37
39
  * normalizePercentageInput, promptBotData, promptGeneralSettings
38
40
  *
39
41
  * ===============================================================================
@@ -95,10 +97,10 @@ import { PATHS } from './paths.js';
95
97
  import { SETTINGS_FILE, readGeneralSettings, writeGeneralSettings } from './general_settings.js';
96
98
  import { parseJsonWithComments } from './order/utils/system.js';
97
99
  import { assertNoDuplicateBotKeys, loadSettingsFile, normalizeBotEntry } from './bot_settings.js';
98
- import { getWhitelistFlags, setWhitelistFlags, renameWhitelistEntry, removeWhitelistEntry, whitelistFile } from './market_adapter_whitelist.js';
100
+ import { getWhitelistFlags, hasWhitelistEntry, setWhitelistFlags, renameWhitelistEntry, removeWhitelistEntry, whitelistFile, AMA_ONLY_WHITELIST_FLAGS } from './market_adapter_whitelist.js';
99
101
  import { BOT_LIVE_CONFIG_KEYS } from './runtime_settings.js';
100
102
  import { mergeSettings } from './settings_merge.js';
101
- import { getErrorMessage } from './utils/errors.js';
103
+ import { getErrorMessage, getErrorCode } from './utils/errors.js';
102
104
  import { normalizeAssetSymbol } from './utils/asset_symbols.js';
103
105
  import { roundToDecimals, parseRelativeMultiplier } from './order/utils/math.js';
104
106
  import { CLI_COLORS } from './cli_colors.js';
@@ -134,7 +136,7 @@ function loadBotsConfig() {
134
136
  return { config: { bots: [] }, filePath };
135
137
  if (!Array.isArray(config.bots))
136
138
  config.bots = [];
137
- return { config, filePath };
139
+ return { config: config, filePath };
138
140
  }
139
141
  /**
140
142
  * Saves the bots configuration to the specified file path.
@@ -145,7 +147,8 @@ function loadBotsConfig() {
145
147
  function saveBotsConfig(config, filePath) {
146
148
  try {
147
149
  ensureProfilesDirectory(PROFILES_DIR);
148
- const entries = Array.isArray(config?.bots) ? config.bots : Array.isArray(config) ? config : [];
150
+ const c = config;
151
+ const entries = Array.isArray(c?.bots) ? c.bots : Array.isArray(config) ? config : [];
149
152
  if (entries.length >= 2)
150
153
  assertNoDuplicateBotKeys(entries, 'account_bots');
151
154
  writeJSON(filePath, config);
@@ -300,7 +303,7 @@ async function askCronSchedule(_promptText, defaultValue) {
300
303
  const current = parseCronToDelta(defaultValue);
301
304
  // Interval Prompt
302
305
  const days = await askNumberWithBounds(' Interval (days)', current.days, 1, 31);
303
- if (days === '\x1b')
306
+ if (days === '\x1b' || typeof days !== 'number')
304
307
  return '\x1b';
305
308
  // Time Prompt
306
309
  let time = current.time;
@@ -308,7 +311,7 @@ async function askCronSchedule(_promptText, defaultValue) {
308
311
  const rawTime = await askString(' Time (HH:mm)', current.time);
309
312
  if (rawTime === '\x1b')
310
313
  return '\x1b';
311
- if (/^([01]\d|2[0-3]):([0-5]\d)$/.test(rawTime)) {
314
+ if (rawTime && /^([01]\d|2[0-3]):([0-5]\d)$/.test(rawTime)) {
312
315
  time = rawTime;
313
316
  break;
314
317
  }
@@ -328,7 +331,7 @@ async function askUpdaterBranch(promptText, defaultValue) {
328
331
  const value = await askString(promptText, defaultValue);
329
332
  if (value === '\x1b')
330
333
  return '\x1b';
331
- const lowered = value.toLowerCase().trim();
334
+ const lowered = (value ?? '').toLowerCase().trim();
332
335
  if (validBranches.includes(lowered))
333
336
  return lowered;
334
337
  console.log(`Invalid branch. Please choose from: ${validBranches.join(', ')}`);
@@ -347,19 +350,18 @@ async function askLogLevel(promptText, defaultValue) {
347
350
  const value = await askString(promptText, defaultValue);
348
351
  if (value === '\x1b')
349
352
  return '\x1b';
350
- const lowered = value.toLowerCase().trim();
353
+ const lowered = (value ?? '').toLowerCase().trim();
351
354
  if (validLevels.includes(lowered))
352
355
  return lowered;
353
356
  console.log(`Invalid log level. Please choose from: ${validLevels.join(', ')}`);
354
357
  }
355
358
  }
356
359
  /**
357
- * Prompts the user for an asset symbol.
358
- * @param {string} promptText - The prompt text to display.
359
- * @param {string} [defaultValue] - The default value to use if input is empty.
360
- * @returns {Promise<string>} The asset symbol in uppercase.
360
+ * Shared asset-symbol input loop: handles ESC, the empty-input default, and
361
+ * normalizeAssetSymbol. An optional `validate` callback may reject a
362
+ * normalized symbol by returning a message to print.
361
363
  */
362
- async function askAsset(promptText, defaultValue) {
364
+ async function askAssetSymbol(promptText, defaultValue, validate) {
363
365
  while (true) {
364
366
  const displayDefault = defaultValue ? normalizeAssetSymbol(defaultValue) : undefined;
365
367
  const suffix = displayDefault !== undefined && displayDefault !== null ? ` [${displayDefault}]` : '';
@@ -372,9 +374,24 @@ async function askAsset(promptText, defaultValue) {
372
374
  console.log('Asset name is required.');
373
375
  continue;
374
376
  }
375
- return normalizeAssetSymbol(answer);
377
+ const asset = normalizeAssetSymbol(answer);
378
+ const reason = validate ? validate(asset) : null;
379
+ if (reason) {
380
+ console.log(reason);
381
+ continue;
382
+ }
383
+ return asset;
376
384
  }
377
385
  }
386
+ /**
387
+ * Prompts the user for an asset symbol.
388
+ * @param {string} promptText - The prompt text to display.
389
+ * @param {string} [defaultValue] - The default value to use if input is empty.
390
+ * @returns {Promise<string>} The asset symbol in uppercase.
391
+ */
392
+ async function askAsset(promptText, defaultValue) {
393
+ return askAssetSymbol(promptText, defaultValue);
394
+ }
378
395
  /**
379
396
  * Prompts the user for Asset B, ensuring it's different from Asset A.
380
397
  * @param {string} promptText - The prompt text to display.
@@ -383,26 +400,7 @@ async function askAsset(promptText, defaultValue) {
383
400
  * @returns {Promise<string>} The asset symbol in uppercase.
384
401
  */
385
402
  async function askAssetB(promptText, defaultValue, assetA) {
386
- while (true) {
387
- const displayDefault = defaultValue ? normalizeAssetSymbol(defaultValue) : undefined;
388
- const suffix = displayDefault !== undefined && displayDefault !== null ? ` [${displayDefault}]` : '';
389
- const answer = await readInput(`${promptText}${suffix}: `);
390
- if (answer === '\x1b')
391
- return '\x1b';
392
- if (!answer) {
393
- if (displayDefault)
394
- return displayDefault;
395
- console.log('Asset name is required.');
396
- continue;
397
- }
398
- const assetB = normalizeAssetSymbol(answer);
399
- // Validate that Asset B is different from Asset A
400
- if (assetB === assetA) {
401
- console.log(`Invalid: Asset B cannot be the same as Asset A (${assetA})`);
402
- continue;
403
- }
404
- return assetB;
405
- }
403
+ return askAssetSymbol(promptText, defaultValue, (assetB) => assetB === assetA ? `Invalid: Asset B cannot be the same as Asset A (${assetA})` : null);
406
404
  }
407
405
  /**
408
406
  * Prompts the user for a weight distribution value with a legend.
@@ -410,10 +408,12 @@ async function askAssetB(promptText, defaultValue, assetA) {
410
408
  * @param {number} [defaultValue] - The default value to use if input is empty.
411
409
  * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
412
410
  */
413
- async function askWeightDistribution(promptText, defaultValue) {
411
+ async function askWeightDistributionValue(promptText, defaultValue, showLegend) {
414
412
  const MIN_WEIGHT = -1;
415
413
  const MAX_WEIGHT = 2;
416
- console.log(` ${COLORS.cyan}-1=SuperValley${COLORS.reset} ←→ ${COLORS.blue}0=Valley${COLORS.reset} ←→ ${COLORS.gray}0.5=Neutral${COLORS.reset} ←→ ${COLORS.bold}${COLORS.orange}1=Mountain${COLORS.reset} ←→ ${COLORS.redStrong}2=SuperMountain${COLORS.reset}`);
414
+ if (showLegend) {
415
+ console.log(` ${COLORS.cyan}-1=SuperValley${COLORS.reset} ←→ ${COLORS.blue}0=Valley${COLORS.reset} ←→ ${COLORS.gray}0.5=Neutral${COLORS.reset} ←→ ${COLORS.bold}${COLORS.orange}1=Mountain${COLORS.reset} ←→ ${COLORS.redStrong}2=SuperMountain${COLORS.reset}`);
416
+ }
417
417
  const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
418
418
  const raw = (await readInput(`${promptText}${suffix}: `)).trim();
419
419
  if (raw === '\x1b')
@@ -423,14 +423,23 @@ async function askWeightDistribution(promptText, defaultValue) {
423
423
  const parsed = Number(raw);
424
424
  if (Number.isNaN(parsed)) {
425
425
  console.log('Please enter a valid number.');
426
- return askWeightDistribution(promptText, defaultValue);
426
+ return askWeightDistributionValue(promptText, defaultValue, showLegend);
427
427
  }
428
428
  if (parsed < MIN_WEIGHT || parsed > MAX_WEIGHT) {
429
429
  console.log(`Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.`);
430
- return askWeightDistribution(promptText, defaultValue);
430
+ return askWeightDistributionValue(promptText, defaultValue, showLegend);
431
431
  }
432
432
  return parsed;
433
433
  }
434
+ /**
435
+ * Prompts the user for a weight distribution value with a legend.
436
+ * @param {string} promptText - The prompt text to display.
437
+ * @param {number} [defaultValue] - The default value to use if input is empty.
438
+ * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
439
+ */
440
+ async function askWeightDistribution(promptText, defaultValue) {
441
+ return askWeightDistributionValue(promptText, defaultValue, true);
442
+ }
434
443
  /**
435
444
  * Prompts the user for a weight distribution value without a legend.
436
445
  * @param {string} promptText - The prompt text to display.
@@ -438,24 +447,7 @@ async function askWeightDistribution(promptText, defaultValue) {
438
447
  * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
439
448
  */
440
449
  async function askWeightDistributionNoLegend(promptText, defaultValue) {
441
- const MIN_WEIGHT = -1;
442
- const MAX_WEIGHT = 2;
443
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
444
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
445
- if (raw === '\x1b')
446
- return '\x1b';
447
- if (raw === '')
448
- return defaultValue;
449
- const parsed = Number(raw);
450
- if (Number.isNaN(parsed)) {
451
- console.log('Please enter a valid number.');
452
- return askWeightDistributionNoLegend(promptText, defaultValue);
453
- }
454
- if (parsed < MIN_WEIGHT || parsed > MAX_WEIGHT) {
455
- console.log(`Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.`);
456
- return askWeightDistributionNoLegend(promptText, defaultValue);
457
- }
458
- return parsed;
450
+ return askWeightDistributionValue(promptText, defaultValue, false);
459
451
  }
460
452
  /**
461
453
  * Checks if a value is a multiplier string (e.g. "3x").
@@ -708,14 +700,11 @@ function deltaToCron(days, time) {
708
700
  return `${min} ${hour} ${dayPart} * *`;
709
701
  }
710
702
  /**
711
- * Prompts the user for a number within specified bounds.
712
- * @param {string} promptText - The prompt text to display.
713
- * @param {number} [defaultValue] - The default value to use if input is empty.
714
- * @param {number} minVal - The minimum allowed value.
715
- * @param {number} maxVal - The maximum allowed value.
716
- * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
703
+ * Shared numeric-input loop: handles ESC and the empty-input default, then
704
+ * delegates domain validation to `validate`. `validate` returns an error
705
+ * message to print and retry, or null to accept the parsed value.
717
706
  */
718
- async function askNumberWithBounds(promptText, defaultValue, minVal = 0, maxVal = 100) {
707
+ async function askNumeric(promptText, defaultValue, validate) {
719
708
  const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
720
709
  const raw = (await readInput(`${promptText}${suffix}: `)).trim();
721
710
  if (raw === '\x1b')
@@ -725,24 +714,36 @@ async function askNumberWithBounds(promptText, defaultValue, minVal = 0, maxVal
725
714
  const parsed = Number(raw);
726
715
  if (Number.isNaN(parsed)) {
727
716
  console.log('Please enter a valid number.');
728
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
729
- }
730
- // Validate that number is finite (not Infinity, -Infinity, or NaN)
731
- if (!Number.isFinite(parsed)) {
732
- console.log('Please enter a valid finite number.');
733
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
734
- }
735
- // Validate bounds
736
- if (parsed < minVal) {
737
- console.log(`Invalid ${promptText}: ${parsed}. Must be >= ${minVal}`);
738
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
717
+ return askNumeric(promptText, defaultValue, validate);
739
718
  }
740
- if (parsed > maxVal) {
741
- console.log(`Invalid ${promptText}: ${parsed}. Must be <= ${maxVal}`);
742
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
719
+ const reason = validate(parsed);
720
+ if (reason) {
721
+ console.log(reason);
722
+ return askNumeric(promptText, defaultValue, validate);
743
723
  }
744
724
  return parsed;
745
725
  }
726
+ /**
727
+ * Prompts the user for a number within specified bounds.
728
+ * @param {string} promptText - The prompt text to display.
729
+ * @param {number} [defaultValue] - The default value to use if input is empty.
730
+ * @param {number} minVal - The minimum allowed value.
731
+ * @param {number} maxVal - The maximum allowed value.
732
+ * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
733
+ */
734
+ async function askNumberWithBounds(promptText, defaultValue, minVal = 0, maxVal = 100) {
735
+ return askNumeric(promptText, defaultValue, (parsed) => {
736
+ // Validate that number is finite (not Infinity, -Infinity, or NaN)
737
+ if (!Number.isFinite(parsed))
738
+ return 'Please enter a valid finite number.';
739
+ // Validate bounds
740
+ if (parsed < minVal)
741
+ return `Invalid ${promptText}: ${parsed}. Must be >= ${minVal}`;
742
+ if (parsed > maxVal)
743
+ return `Invalid ${promptText}: ${parsed}. Must be <= ${maxVal}`;
744
+ return null;
745
+ });
746
+ }
746
747
  /**
747
748
  * Prompts the user for the target spread percentage.
748
749
  * Values are rounded to two decimal places: the displayed minimum, the
@@ -758,7 +759,7 @@ async function askTargetSpreadPercent(promptText, defaultValue, incrementPercent
758
759
  const safeMinSpreadFactor = Number.isFinite(minSpreadFactor) ? minSpreadFactor : GRID_LIMITS.MIN_SPREAD_FACTOR;
759
760
  const minRequired = roundToDecimals(safeIncrement * safeMinSpreadFactor, 2);
760
761
  const minRequiredLabel = minRequired.toFixed(2);
761
- const effectiveDefault = Number.isFinite(defaultValue) ? Math.max(roundToDecimals(defaultValue, 2), minRequired) : defaultValue;
762
+ const effectiveDefault = typeof defaultValue === 'number' && Number.isFinite(defaultValue) ? Math.max(roundToDecimals(defaultValue, 2), minRequired) : defaultValue;
762
763
  const suffix = effectiveDefault !== undefined && effectiveDefault !== null ? ` [${effectiveDefault.toFixed(2)}]` : '';
763
764
  const raw = (await readInput(`${promptText} (>= ${minRequiredLabel})${suffix}: `)).trim();
764
765
  if (raw === '\x1b')
@@ -796,28 +797,36 @@ async function askTargetSpreadPercent(promptText, defaultValue, incrementPercent
796
797
  * @returns {Promise<number|string>} The integer or '\x1b' if ESC.
797
798
  */
798
799
  async function askIntegerInRange(promptText, defaultValue, minVal = 0, maxVal = 100) {
799
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
800
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
801
- if (raw === '\x1b')
802
- return '\x1b';
803
- if (raw === '')
804
- return defaultValue;
805
- const parsed = Number(raw);
806
- if (Number.isNaN(parsed)) {
807
- console.log('Please enter a valid number.');
808
- return askIntegerInRange(promptText, defaultValue, minVal, maxVal);
809
- }
810
- // Validate that number is integer (not float)
811
- if (!Number.isInteger(parsed)) {
812
- console.log(`Invalid ${promptText}: ${parsed}. Must be an integer (no decimals)`);
813
- return askIntegerInRange(promptText, defaultValue, minVal, maxVal);
800
+ return askNumeric(promptText, defaultValue, (parsed) => {
801
+ // Validate that number is integer (not float)
802
+ if (!Number.isInteger(parsed))
803
+ return `Invalid ${promptText}: ${parsed}. Must be an integer (no decimals)`;
804
+ // Validate bounds
805
+ if (parsed < minVal || parsed > maxVal)
806
+ return `Invalid ${promptText}: ${parsed}. Must be between ${minVal} and ${maxVal}`;
807
+ return null;
808
+ });
809
+ }
810
+ /**
811
+ * Validate a relative-multiplier input ("1.5x") for the price-bound prompts.
812
+ * Returns the trimmed multiplier string when accepted, or the error message to
813
+ * print when rejected. Single source of truth for the min/max direction rule.
814
+ */
815
+ function validateMultiplierInput(promptText, raw) {
816
+ const trimmed = raw.trim();
817
+ const multiplier = parseFloat(trimmed);
818
+ if (multiplier <= 0) {
819
+ return { error: `Invalid ${promptText}: "${trimmed}". Multiplier must be > 0. No "0x" or negative values` };
814
820
  }
815
- // Validate bounds
816
- if (parsed < minVal || parsed > maxVal) {
817
- console.log(`Invalid ${promptText}: ${parsed}. Must be between ${minVal} and ${maxVal}`);
818
- return askIntegerInRange(promptText, defaultValue, minVal, maxVal);
821
+ if (multiplier < 1) {
822
+ // A sub-1x bound multiplier ("0.7x") resolves to the wrong side of the
823
+ // grid. Reject so the rail can't land across the book (issue #15).
824
+ const directionNote = /max/i.test(promptText)
825
+ ? 'For maxPrice, "Nx" means center*N, so a multiplier < 1 places the bound BELOW the center. Use a value > 1.'
826
+ : 'For minPrice, "Nx" means center/N, so a multiplier < 1 places the bound ABOVE the center. Use a value > 1 (e.g. "1.43x" for 70% of center).';
827
+ return { error: `Invalid ${promptText}: "${trimmed}". ${directionNote}` };
819
828
  }
820
- return parsed;
829
+ return { value: trimmed };
821
830
  }
822
831
  /**
823
832
  * Prompts the user for a numeric value or a multiplier. Used for price
@@ -838,22 +847,12 @@ async function askNumberOrMultiplier(promptText, defaultValue) {
838
847
  if (raw === '')
839
848
  return defaultValue;
840
849
  if (isMultiplierString(raw)) {
841
- const trimmed = raw.trim();
842
- const multiplier = parseFloat(trimmed);
843
- if (multiplier <= 0) {
844
- console.log(`Invalid ${promptText}: "${trimmed}". Multiplier must be > 0. No "0x" or negative values`);
850
+ const result = validateMultiplierInput(promptText, raw);
851
+ if ('error' in result) {
852
+ console.log(result.error);
845
853
  return askNumberOrMultiplier(promptText, defaultValue);
846
854
  }
847
- // A sub-1x bound multiplier ("0.7x") resolves to the wrong side of
848
- // the grid. Reject so the rail can't land across the book (issue #15).
849
- const directionNote = /max/i.test(promptText)
850
- ? 'For maxPrice, "Nx" means center*N, so a multiplier < 1 places the bound BELOW the center. Use a value > 1.'
851
- : 'For minPrice, "Nx" means center/N, so a multiplier < 1 places the bound ABOVE the center. Use a value > 1 (e.g. "1.43x" for 70% of center).';
852
- if (multiplier < 1) {
853
- console.log(`Invalid ${promptText}: "${trimmed}". ${directionNote}`);
854
- return askNumberOrMultiplier(promptText, defaultValue);
855
- }
856
- return trimmed;
855
+ return result.value;
857
856
  }
858
857
  const parsed = Number(raw);
859
858
  if (Number.isNaN(parsed)) {
@@ -883,19 +882,12 @@ async function askMaxPrice(promptText, defaultValue, minPrice) {
883
882
  if (raw === '')
884
883
  return defaultValue;
885
884
  if (isMultiplierString(raw)) {
886
- const trimmed = raw.trim();
887
- const multiplier = parseFloat(trimmed);
888
- if (multiplier <= 0) {
889
- console.log(`Invalid ${promptText}: "${trimmed}". Multiplier must be > 0. No "0x" or negative values`);
890
- return askMaxPrice(promptText, defaultValue, minPrice);
891
- }
892
- // For maxPrice a multiplier < 1 ("0.7x") resolves to center*0.7 — a
893
- // bound BELOW the center. Reject so the rail can't land across the book.
894
- if (multiplier < 1) {
895
- console.log(`Invalid ${promptText}: "${trimmed}". For maxPrice, "Nx" means center*N, so a multiplier < 1 places the bound BELOW the center. Use a value > 1.`);
885
+ const result = validateMultiplierInput(promptText, raw);
886
+ if ('error' in result) {
887
+ console.log(result.error);
896
888
  return askMaxPrice(promptText, defaultValue, minPrice);
897
889
  }
898
- return trimmed;
890
+ return result.value;
899
891
  }
900
892
  const parsed = Number(raw);
901
893
  if (Number.isNaN(parsed)) {
@@ -913,7 +905,7 @@ async function askMaxPrice(promptText, defaultValue, minPrice) {
913
905
  // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
914
906
  if (!isMultiplierString(minPrice)) {
915
907
  const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
916
- if (parsed <= minPriceValue) {
908
+ if (minPriceValue != null && parsed <= minPriceValue) {
917
909
  console.log(`Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})`);
918
910
  return askMaxPrice(promptText, defaultValue, minPrice);
919
911
  }
@@ -1129,12 +1121,6 @@ async function askGridPriceMode(promptText, defaultValue) {
1129
1121
  console.log(`${COLORS.red}Please enter: ama1, ama2, ama3 or ama4 — also allowed: pool, book, ama, a positive number, or none (s/start, n/no/false/0/f).${COLORS.reset}`);
1130
1122
  }
1131
1123
  }
1132
- /**
1133
- * Normalizes a bot draft for editing or saving.
1134
- * Preserves existing fields and strips unsupported runtime-managed fields.
1135
- * @param {Object} [base={}] - The initial bot data to edit.
1136
- * @returns {Object} A normalized bot draft.
1137
- */
1138
1124
  function normalizeBotDraft(base = {}) {
1139
1125
  // Seeding rules live in modules/bot_defaults.ts (single defaults source).
1140
1126
  // Return type stays `any`: the editor prompt-flow treats drafts as dynamic
@@ -1214,7 +1200,7 @@ async function ensureBotAccountId(data, timeoutMs = 15000, quiet = false, force
1214
1200
  ]);
1215
1201
  }
1216
1202
  catch (err) {
1217
- const reason = err && err.code === 'ACCOUNT_LOOKUP_TIMEOUT' ? 'timeout' : 'error';
1203
+ const reason = err && getErrorCode(err) === 'ACCOUNT_LOOKUP_TIMEOUT' ? 'timeout' : 'error';
1218
1204
  if (!quiet) {
1219
1205
  const hint = reason === 'timeout'
1220
1206
  ? `nodes unreachable (timed out after ${timeoutMs}ms). Continuing without accountId — it will be stored automatically once a lookup succeeds.`
@@ -1282,10 +1268,21 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1282
1268
  // together with the rest of the draft.
1283
1269
  const baseEntry = base && typeof base === 'object' && Object.keys(base).length > 0 ? base : null;
1284
1270
  const baseBotKey = baseEntry ? String(normalizeBotEntry(baseEntry, baseIndex).botKey || '') : '';
1271
+ const isNewBot = !baseEntry;
1285
1272
  let adapterStaged = null;
1286
1273
  const isAmaGridPriceDraft = () => /^ama(?:[1-4])?$/.test(String(data.gridPrice ?? '').trim().toLowerCase());
1287
- const adapterFlags = () => adapterStaged
1288
- || getWhitelistFlags(baseBotKey || String(normalizeBotEntry(data, index).botKey || ''));
1274
+ // Staged menu-6 edits win. Otherwise an existing bot uses its stored entry;
1275
+ // a brand-new bot uses that entry too if one already exists for its key,
1276
+ // and only falls back to AMA pricing ON when there is no record at all — so
1277
+ // re-creating a previously configured key never silently flips its flags.
1278
+ const adapterFlags = () => {
1279
+ if (adapterStaged)
1280
+ return adapterStaged;
1281
+ const key = baseBotKey || String(normalizeBotEntry(data, index).botKey || '');
1282
+ if (!isNewBot)
1283
+ return getWhitelistFlags(key);
1284
+ return hasWhitelistEntry(key) ? getWhitelistFlags(key) : { ...AMA_ONLY_WHITELIST_FLAGS };
1285
+ };
1289
1286
  let finished = false;
1290
1287
  let cancelled = false;
1291
1288
  let showMenu = true;
@@ -1367,10 +1364,10 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1367
1364
  data.accountId = draft.accountId;
1368
1365
  }
1369
1366
  const active = await askBoolean('Active', data.active);
1370
- if (active === '\x1b')
1367
+ if (typeof active !== 'boolean')
1371
1368
  break;
1372
1369
  const dryRun = await askBoolean('Dry run', data.dryRun);
1373
- if (dryRun === '\x1b')
1370
+ if (typeof dryRun !== 'boolean')
1374
1371
  break;
1375
1372
  data.name = name;
1376
1373
  data.preferredAccount = prefAcc;
@@ -1417,11 +1414,15 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1417
1414
  const incrP = await askNumberWithBounds('incrementPercent', data.incrementPercent, INCREMENT_BOUNDS.MIN_PERCENT, INCREMENT_BOUNDS.MAX_PERCENT);
1418
1415
  if (incrP === '\x1b')
1419
1416
  break;
1417
+ if (typeof incrP !== 'number')
1418
+ break;
1420
1419
  const defaultSpread = data.targetSpreadPercent || incrP * 4;
1421
1420
  // Use current general settings for the validation limit
1422
1421
  const currentSettings = loadGeneralSettings();
1423
1422
  const targetS = await askTargetSpreadPercent('targetSpread %', defaultSpread, incrP, currentSettings.GRID_LIMITS.MIN_SPREAD_FACTOR);
1424
- if (targetS === '\x1b')
1423
+ if (typeof targetS !== 'number')
1424
+ break;
1425
+ if (typeof wSell !== 'number' || typeof wBuy !== 'number')
1425
1426
  break;
1426
1427
  data.weightDistribution.sell = wSell;
1427
1428
  data.weightDistribution.buy = wBuy;
@@ -1431,22 +1432,22 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1431
1432
  break;
1432
1433
  case '5':
1433
1434
  const fSell = await askNumberOrPercentage('botFunds sell amount', data.botFunds.sell);
1434
- if (fSell === '\x1b')
1435
+ if (fSell === undefined || fSell === '\x1b')
1435
1436
  break;
1436
1437
  const fBuy = await askNumberOrPercentage('botFunds buy amount', data.botFunds.buy);
1437
- if (fBuy === '\x1b')
1438
+ if (fBuy === undefined || fBuy === '\x1b')
1438
1439
  break;
1439
1440
  const oSell = await askIntegerInRange('activeOrders sell count', data.activeOrders.sell, 1, 100);
1440
- if (oSell === '\x1b')
1441
+ if (typeof oSell !== 'number')
1441
1442
  break;
1442
1443
  const oBuy = await askIntegerInRange('activeOrders buy count', data.activeOrders.buy, 1, 100);
1443
- if (oBuy === '\x1b')
1444
+ if (typeof oBuy !== 'number')
1444
1445
  break;
1445
1446
  const rBuy = await askIntegerInRange('reserveOrders buy floor count (0 disables)', data.reserveOrders?.buy ?? 0, 0, 100);
1446
- if (rBuy === '\x1b')
1447
+ if (typeof rBuy !== 'number')
1447
1448
  break;
1448
1449
  const rSell = await askIntegerInRange('reserveOrders sell ceiling count (0 disables)', data.reserveOrders?.sell ?? 0, 0, 100);
1449
- if (rSell === '\x1b')
1450
+ if (typeof rSell !== 'number')
1450
1451
  break;
1451
1452
  data.botFunds.sell = fSell;
1452
1453
  data.botFunds.buy = fBuy;
@@ -1465,12 +1466,18 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1465
1466
  const price = await askBoolean('AMA pricing (Price)', flags.ama);
1466
1467
  if (price === '\x1b')
1467
1468
  break;
1469
+ if (typeof price !== 'boolean')
1470
+ break;
1468
1471
  const weight = await askBoolean('Dynamic weights (Weight)', flags.dynamicWeight);
1469
1472
  if (weight === '\x1b')
1470
1473
  break;
1474
+ if (typeof weight !== 'boolean')
1475
+ break;
1471
1476
  const range = await askBoolean('Range scaling (Range)', flags.asymmetricBounds);
1472
1477
  if (range === '\x1b')
1473
1478
  break;
1479
+ if (typeof range !== 'boolean')
1480
+ break;
1474
1481
  adapterStaged = { ama: price, dynamicWeight: weight, asymmetricBounds: range };
1475
1482
  if (!price && (weight || range)) {
1476
1483
  console.log(`${COLORS.yellow}Note: Weight/Range only take effect while Price (AMA) is enabled.${COLORS.reset}`);
@@ -1489,8 +1496,8 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1489
1496
  const spreadFactor = Number.isFinite(currentSettings.GRID_LIMITS.MIN_SPREAD_FACTOR)
1490
1497
  ? currentSettings.GRID_LIMITS.MIN_SPREAD_FACTOR
1491
1498
  : GRID_LIMITS.MIN_SPREAD_FACTOR;
1492
- const minRequiredSpread = roundToDecimals(data.incrementPercent * spreadFactor, 2);
1493
- if (data.targetSpreadPercent + Number.EPSILON < minRequiredSpread) {
1499
+ const minRequiredSpread = roundToDecimals((data.incrementPercent ?? 0) * spreadFactor, 2);
1500
+ if ((data.targetSpreadPercent ?? 0) + Number.EPSILON < minRequiredSpread) {
1494
1501
  console.log(`${COLORS.red}Error: targetSpreadPercent (${data.targetSpreadPercent}) must be >= ${spreadFactor}x incrementPercent (${minRequiredSpread.toFixed(2)}).${COLORS.reset}`);
1495
1502
  break;
1496
1503
  }
@@ -1517,13 +1524,18 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1517
1524
  // flags already match what is stored — an unchanged save never creates a
1518
1525
  // placeholder entry.
1519
1526
  const stagedFlags = adapterStaged;
1520
- const commitAdapter = stagedFlags ? () => {
1527
+ // A new bot also commits without an explicit menu-6 edit: its resolved
1528
+ // default (record if present, else AMA-on) must be persisted so the market
1529
+ // adapter sees the same value the editor displayed. An unchanged save still
1530
+ // writes nothing.
1531
+ const commitAdapter = (stagedFlags || isNewBot) ? () => {
1521
1532
  const newKey = String(normalizeBotEntry(data, index).botKey || '');
1522
1533
  const needRename = !!(baseBotKey && newKey && baseBotKey !== newKey);
1534
+ const desired = stagedFlags || adapterFlags();
1523
1535
  const current = getWhitelistFlags(baseBotKey || newKey);
1524
- const unchanged = stagedFlags.ama === current.ama
1525
- && stagedFlags.dynamicWeight === current.dynamicWeight
1526
- && stagedFlags.asymmetricBounds === current.asymmetricBounds;
1536
+ const unchanged = desired.ama === current.ama
1537
+ && desired.dynamicWeight === current.dynamicWeight
1538
+ && desired.asymmetricBounds === current.asymmetricBounds;
1527
1539
  if (needRename && !renameWhitelistEntry(baseBotKey, newKey)) {
1528
1540
  console.log(`${COLORS.yellow}Adapter flags not saved — see the warning above.${COLORS.reset}`);
1529
1541
  return;
@@ -1532,7 +1544,7 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1532
1544
  // migrated the entry under the new key.
1533
1545
  if (unchanged)
1534
1546
  return;
1535
- if (!setWhitelistFlags(newKey, stagedFlags)) {
1547
+ if (!setWhitelistFlags(newKey, desired)) {
1536
1548
  console.log(`${COLORS.yellow}Warning: adapter flags not saved — could not write ${whitelistFile()}.${COLORS.reset}`);
1537
1549
  }
1538
1550
  else {
@@ -1590,6 +1602,8 @@ async function promptGeneralSettings() {
1590
1602
  const amaSlopeDelta = await askNumberWithBounds('AMA-Slope Δ', settings.MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT, 0.1, 100.0);
1591
1603
  if (amaSlopeDelta === '\x1b')
1592
1604
  break;
1605
+ if (typeof gRegen !== 'number' || typeof rms !== 'number' || typeof amaDelta !== 'number' || typeof amaSlopeDelta !== 'number')
1606
+ break;
1593
1607
  settings.GRID_LIMITS.GRID_REGENERATION_PERCENTAGE = gRegen;
1594
1608
  settings.GRID_LIMITS.GRID_COMPARISON.RMS_PERCENTAGE = rms;
1595
1609
  settings.MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT = amaDelta;
@@ -1599,10 +1613,14 @@ async function promptGeneralSettings() {
1599
1613
  const dust = await askNumberWithBounds('Partial Dust Threshold %', settings.GRID_LIMITS.PARTIAL_DUST_THRESHOLD_PERCENTAGE, 0.1, 50);
1600
1614
  if (dust === '\x1b')
1601
1615
  break;
1616
+ if (typeof dust !== 'number')
1617
+ break;
1602
1618
  settings.GRID_LIMITS.PARTIAL_DUST_THRESHOLD_PERCENTAGE = dust;
1603
1619
  const hcInterval = await askIntegerInRange('Health Check Interval (min)', (settings.NODES.healthCheck?.intervalMs || NODE_MANAGEMENT.HEALTH_CHECK_INTERVAL_MS) / 60000, 1, 43200);
1604
1620
  if (hcInterval === '\x1b')
1605
1621
  break;
1622
+ if (typeof hcInterval !== 'number')
1623
+ break;
1606
1624
  if (!settings.NODES.healthCheck)
1607
1625
  settings.NODES.healthCheck = {};
1608
1626
  settings.NODES.healthCheck.intervalMs = hcInterval * 60000;
@@ -1645,6 +1663,8 @@ async function promptGeneralSettings() {
1645
1663
  const removeIdx = await askIntegerInRange(' Enter node number to remove', 1, 1, nodeList.length);
1646
1664
  if (removeIdx === '\x1b')
1647
1665
  continue;
1666
+ if (typeof removeIdx !== 'number')
1667
+ continue;
1648
1668
  const removed = nodeList.splice(removeIdx - 1, 1)[0];
1649
1669
  console.log(` ${COLORS.green}Removed:${COLORS.reset} ${removed}`);
1650
1670
  }
@@ -1661,7 +1681,7 @@ async function promptGeneralSettings() {
1661
1681
  break;
1662
1682
  if (!settings.NODES.selection)
1663
1683
  settings.NODES.selection = {};
1664
- settings.NODES.selection.preferredNode = prefNode.trim() || null;
1684
+ settings.NODES.selection.preferredNode = (prefNode ?? '').trim() || null;
1665
1685
  break;
1666
1686
  case '4':
1667
1687
  const newLevel = await askLogLevel('Enter log level', settings.LOG_LEVEL);
@@ -1673,6 +1693,8 @@ async function promptGeneralSettings() {
1673
1693
  const upActive = await askBoolean('Enable Automated Updater', settings.UPDATER.ACTIVE !== false);
1674
1694
  if (upActive === '\x1b')
1675
1695
  break;
1696
+ if (typeof upActive !== 'boolean')
1697
+ break;
1676
1698
  settings.UPDATER.ACTIVE = upActive;
1677
1699
  console.log(` ${COLORS.gray}Branch:${COLORS.reset} ${COLORS.green}main${COLORS.reset}, ${COLORS.orange}dev${COLORS.reset}, ${COLORS.red}test${COLORS.reset}, or ${COLORS.blue}auto${COLORS.reset} (detected current)`);
1678
1700
  const branch = await askUpdaterBranch('Branch', settings.UPDATER.BRANCH);
@@ -1690,6 +1712,8 @@ async function promptGeneralSettings() {
1690
1712
  const noticeOn = await askBoolean('Show "new version available" notice on startup', settings.UPDATER.NOTICE_ENABLED !== false);
1691
1713
  if (noticeOn === '\x1b')
1692
1714
  break;
1715
+ if (typeof noticeOn !== 'boolean')
1716
+ break;
1693
1717
  settings.UPDATER.NOTICE_ENABLED = noticeOn;
1694
1718
  break;
1695
1719
  case 's':
@@ -1833,5 +1857,5 @@ async function main() {
1833
1857
  }
1834
1858
  console.log('Botmanager closed!');
1835
1859
  }
1836
- export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings, saveGeneralSettings };
1860
+ export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings };
1837
1861
  //# sourceMappingURL=account_bots.js.map