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
@@ -48,8 +48,9 @@ function convertSlopePercentToPerBar(value, lookbackBars, mode) {
48
48
  function normalizePersistedAmaSlopeSnapshot(snapshot, lookbackBars, mode) {
49
49
  if (!snapshot || typeof snapshot !== 'object')
50
50
  return null;
51
- const normalized = { ...snapshot };
52
- const slopePct = convertSlopePercentToPerBar(snapshot.slopePct, lookbackBars, mode);
51
+ const s = snapshot;
52
+ const normalized = { ...s };
53
+ const slopePct = convertSlopePercentToPerBar(s.slopePct, lookbackBars, mode);
53
54
  if (Number.isFinite(slopePct)) {
54
55
  normalized.slopePct = slopePct;
55
56
  }
@@ -58,34 +59,37 @@ function normalizePersistedAmaSlopeSnapshot(snapshot, lookbackBars, mode) {
58
59
  function normalizePersistedAmaSlopeDiagnostics(data, lookbackBars) {
59
60
  if (!data || typeof data !== 'object')
60
61
  return data;
61
- const mode = normalizeAmaSlopePercentMode(data.amaSlopePercentMode) || AMA_SLOPE_PERCENT_MODE_WINDOW;
62
- const normalized = { ...data };
62
+ const d = data;
63
+ const mode = normalizeAmaSlopePercentMode(d.amaSlopePercentMode) || AMA_SLOPE_PERCENT_MODE_WINDOW;
64
+ const normalized = { ...d };
63
65
  normalized.amaSlopePercentMode = AMA_SLOPE_PERCENT_MODE_PER_BAR;
64
- normalized.amaSlope = normalizePersistedAmaSlopeSnapshot(data.amaSlope, lookbackBars, mode);
65
- normalized.gridRangeScalingAmaSlope = normalizePersistedAmaSlopeSnapshot(data.gridRangeScalingAmaSlope, lookbackBars, mode);
66
- const deltaPercent = convertSlopePercentToPerBar(data.amaSlopeDeltaPercent, lookbackBars, mode);
67
- const thresholdPercent = convertSlopePercentToPerBar(data.amaSlopeThresholdPercent, lookbackBars, mode);
66
+ normalized.amaSlope = normalizePersistedAmaSlopeSnapshot(d.amaSlope, lookbackBars, mode);
67
+ normalized.gridRangeScalingAmaSlope = normalizePersistedAmaSlopeSnapshot(d.gridRangeScalingAmaSlope, lookbackBars, mode);
68
+ const deltaPercent = convertSlopePercentToPerBar(d.amaSlopeDeltaPercent, lookbackBars, mode);
69
+ const thresholdPercent = convertSlopePercentToPerBar(d.amaSlopeThresholdPercent, lookbackBars, mode);
68
70
  normalized.amaSlopeDeltaPercent = Number.isFinite(deltaPercent) ? deltaPercent : null;
69
71
  normalized.amaSlopeThresholdPercent = Number.isFinite(thresholdPercent) ? thresholdPercent : null;
70
72
  // Persistence-gate state carried across restarts (see advanceAmaSlopePersistence).
71
- const persistCount = Number(data.amaSlopePersistCount);
73
+ const persistCount = Number(d.amaSlopePersistCount);
72
74
  normalized.amaSlopePersistCount = Number.isFinite(persistCount) && persistCount > 0 ? Math.floor(persistCount) : 0;
73
- const persistDir = Number(data.amaSlopePersistDir);
75
+ const persistDir = Number(d.amaSlopePersistDir);
74
76
  normalized.amaSlopePersistDir = persistDir === 1 ? 1 : (persistDir === -1 ? -1 : 0);
75
77
  return normalized;
76
78
  }
77
79
  function computeGridPriceOffsetPlan(bot, amaSlope) {
78
- const targetSpreadPercentRaw = Number(bot?.targetSpreadPercent);
80
+ const b = bot;
81
+ const a = amaSlope;
82
+ const targetSpreadPercentRaw = Number(b?.targetSpreadPercent);
79
83
  const targetSpreadPercent = Number.isFinite(targetSpreadPercentRaw) && targetSpreadPercentRaw > 0
80
84
  ? targetSpreadPercentRaw
81
85
  : Number(DEFAULT_CONFIG.targetSpreadPercent);
82
86
  const maxGridPriceOffsetPct = targetSpreadPercent / 2;
83
- const trend = amaSlope?.trend;
84
- const rawSlopeOffset = Number(amaSlope?.rawSlopeOffset);
85
- const maxSlopeOffset = Number(amaSlope?.maxSlopeOffset);
87
+ const trend = a?.trend;
88
+ const rawSlopeOffset = Number(a?.rawSlopeOffset);
89
+ const maxSlopeOffset = Number(a?.maxSlopeOffset);
86
90
  const directionalSlope = Number.isFinite(rawSlopeOffset)
87
91
  ? Math.abs(rawSlopeOffset)
88
- : Math.abs(Number(amaSlope?.slopeOffset));
92
+ : Math.abs(Number(a?.slopeOffset));
89
93
  const slopeRatio = Number.isFinite(directionalSlope) && Number.isFinite(maxSlopeOffset) && maxSlopeOffset > 0
90
94
  ? Math.min(directionalSlope / maxSlopeOffset, 1)
91
95
  : 0;
@@ -254,7 +258,8 @@ class MarketAdapterService {
254
258
  * shortfall) is evaluateStateRepairVeto above; keep the two in step.
255
259
  */
256
260
  candleFileCoversClosedBucket(candles, meta, marketSource, closedBucketStartMs, requiredCount = 0) {
257
- if (!Number.isFinite(closedBucketStartMs) || closedBucketStartMs <= 0)
261
+ const closedBucketMs = Number(closedBucketStartMs);
262
+ if (!Number.isFinite(closedBucketMs) || closedBucketMs <= 0)
258
263
  return false;
259
264
  if (this.isCandleSourceMismatch(meta, marketSource))
260
265
  return false;
@@ -269,7 +274,7 @@ class MarketAdapterService {
269
274
  const newestTs = Number(candles[candles.length - 1]?.[0]);
270
275
  if (!Number.isFinite(newestTs))
271
276
  return false;
272
- return newestTs >= closedBucketStartMs;
277
+ return newestTs >= closedBucketMs;
273
278
  }
274
279
  selectClosedCandles(candles, intervalSeconds, nowMs = this.getNowMs()) {
275
280
  const currentBucketStart = bucketStartMs(nowMs, intervalSeconds);
@@ -313,8 +318,8 @@ class MarketAdapterService {
313
318
  getMissingTimestampsWithinTimeRange(missingTimestamps, timeRange) {
314
319
  if (!Array.isArray(missingTimestamps) || missingTimestamps.length === 0 || !timeRange)
315
320
  return [];
316
- const gteMs = Date.parse(timeRange.gte);
317
- const lteMs = Date.parse(timeRange.lte);
321
+ const gteMs = Date.parse(String(timeRange.gte));
322
+ const lteMs = Date.parse(String(timeRange.lte));
318
323
  if (!Number.isFinite(gteMs) || !Number.isFinite(lteMs) || lteMs < gteMs)
319
324
  return [];
320
325
  return missingTimestamps.filter((ts) => Number.isFinite(ts) && ts >= gteMs && ts <= lteMs);
@@ -325,7 +330,7 @@ class MarketAdapterService {
325
330
  ? intervalSeconds / 3600
326
331
  : 1;
327
332
  const maxCandles = Number.isFinite(cfg?.maxNativeGapFillCandles)
328
- ? cfg.maxNativeGapFillCandles
333
+ ? Number(Number(cfg.maxNativeGapFillCandles))
329
334
  : MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
330
335
  // Include the candle before and after the missing run so Kibana repair
331
336
  // does not truncate a valid threshold-sized gap while still respecting
@@ -334,7 +339,7 @@ class MarketAdapterService {
334
339
  }
335
340
  getTrustedNoTradeGapThresholdCandles(cfg) {
336
341
  return Number.isFinite(cfg?.maxNativeGapFillCandles)
337
- ? cfg.maxNativeGapFillCandles
342
+ ? Number(Number(cfg.maxNativeGapFillCandles))
338
343
  : MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
339
344
  }
340
345
  fillNativeIncrementalClosedGaps(candles, previousLastTs, intervalSeconds, nowMs = this.getNowMs()) {
@@ -385,12 +390,12 @@ class MarketAdapterService {
385
390
  const deps = this.deps;
386
391
  const bucketMs = Number(intervalSeconds) * 1000;
387
392
  if (!Array.isArray(candles) || candles.length === 0 || !Array.isArray(missingTimestamps) || missingTimestamps.length === 0) {
388
- return { candles, filledTimestamps: [] };
393
+ return { candles: candles, filledTimestamps: [] };
389
394
  }
390
395
  if (!Number.isFinite(bucketMs) || bucketMs <= 0)
391
- return { candles, filledTimestamps: [] };
396
+ return { candles: candles, filledTimestamps: [] };
392
397
  if (!Number.isFinite(maxGapCandles) || maxGapCandles <= 0)
393
- return { candles, filledTimestamps: [] };
398
+ return { candles: candles, filledTimestamps: [] };
394
399
  const sortedCandles = candles
395
400
  .filter((c) => Array.isArray(c) && Number.isFinite(c[0]))
396
401
  .slice()
@@ -495,7 +500,7 @@ class MarketAdapterService {
495
500
  const base = Number(centerPrice);
496
501
  const ref = Number(referencePrice);
497
502
  if (!Number.isFinite(base) || base <= 0)
498
- return centerPrice;
503
+ return base;
499
504
  try {
500
505
  const startPrice = Number.isFinite(ref) && ref > 0 ? ref : base;
501
506
  const minP = resolveConfiguredPriceBound(bot?.minPrice, DEFAULT_CONFIG.minPrice, startPrice, 'min') ?? 0;
@@ -672,12 +677,25 @@ class MarketAdapterService {
672
677
  * (legacy fire-on-first-crossing).
673
678
  */
674
679
  resolveAmaSlopePersistBars(cfg) {
675
- const explicit = Number(cfg?.amaSlope?.persistBars ?? cfg?.amaSlopePersistBars);
676
- if (Number.isFinite(explicit) && explicit >= 1)
677
- return Math.round(explicit);
678
- const enabled = cfg?.amaSlope?.persistEnabled === true
679
- || cfg?.amaSlopePersistEnabled === true
680
- || MARKET_ADAPTER.AMA_SLOPE_PERSIST_ENABLED === true;
680
+ // Per-bot/market `persistBars`: >= 1 sets the gate length, exactly 0
681
+ // disables it (legacy 1). Negative/NaN fall through to the enable flags.
682
+ const rawBars = cfg?.amaSlope?.persistBars ?? cfg?.amaSlopePersistBars;
683
+ const explicit = (rawBars === null || rawBars === undefined) ? NaN : Number(rawBars);
684
+ if (Number.isFinite(explicit)) {
685
+ if (explicit >= 1)
686
+ return Math.round(explicit);
687
+ if (explicit === 0)
688
+ return 1;
689
+ }
690
+ // `persistEnabled` is a tri-state override: an explicit false disables
691
+ // the gate even when the global default is on; undefined falls back to
692
+ // the global flag; explicit true enables it. Must be an explicit
693
+ // tri-state check — a `||` chain lets the global `true` mask a per-bot
694
+ // `false`, silently killing the documented per-bot rollback.
695
+ const override = cfg?.amaSlope?.persistEnabled ?? cfg?.amaSlopePersistEnabled;
696
+ const enabled = override === false ? false
697
+ : override === true ? true
698
+ : MARKET_ADAPTER.AMA_SLOPE_PERSIST_ENABLED === true;
681
699
  if (!enabled)
682
700
  return 1;
683
701
  const bars = Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS);
@@ -716,7 +734,7 @@ class MarketAdapterService {
716
734
  normalizePersistedBotState(botState, lookbackBars) {
717
735
  if (!botState || typeof botState !== 'object')
718
736
  return {};
719
- return normalizePersistedAmaSlopeDiagnostics(botState, lookbackBars);
737
+ return (normalizePersistedAmaSlopeDiagnostics(botState, lookbackBars) ?? {});
720
738
  }
721
739
  extractPersistedDynamicGridState(snapshot, lookbackBars) {
722
740
  if (!snapshot || typeof snapshot !== 'object')
@@ -819,7 +837,7 @@ class MarketAdapterService {
819
837
  // The gate still recomputes from scratch whenever the cached
820
838
  // closes are not a prefix of the incoming window (gap repair,
821
839
  // rewritten bar, shortened window) or a parameter changed.
822
- cacheKey: `${bot?.botKey ?? 'bot'}:${cfg.intervalSeconds}`,
840
+ cacheKey: `${bot?.botKey ?? 'bot'}:${Number(cfg.intervalSeconds)}`,
823
841
  });
824
842
  regimeMultiplier = regimeResult.isReady && Math.abs(regimeResult.multiplier - 1.0) >= absoluteThreshold
825
843
  ? regimeResult.multiplier
@@ -958,8 +976,8 @@ class MarketAdapterService {
958
976
  kalmanSmoothSpanPct,
959
977
  signalConfirmBars,
960
978
  };
961
- const staticSell = bot.weightDistribution.sell;
962
- const staticBuy = bot.weightDistribution.buy;
979
+ const staticSell = bot.weightDistribution?.sell ?? 0;
980
+ const staticBuy = bot.weightDistribution?.buy ?? 0;
963
981
  const MIN_W = MARKET_ADAPTER.DYNAMIC_WEIGHT_MIN_WEIGHT;
964
982
  const MAX_W = MARKET_ADAPTER.DYNAMIC_WEIGHT_MAX_WEIGHT;
965
983
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
@@ -1109,7 +1127,7 @@ class MarketAdapterService {
1109
1127
  const thresholdPercent = typeof deps.calculateBotThreshold === 'function'
1110
1128
  ? deps.calculateBotThreshold(cfg)
1111
1129
  : null;
1112
- state.bots[bot.botKey] = this.buildDefaultBotState(bot, {
1130
+ state.bots[String(bot.botKey)] = this.buildDefaultBotState(bot, {
1113
1131
  startPrice: bot.startPrice,
1114
1132
  priceMode: 'fixed',
1115
1133
  lastCycleSource: 'fixed-start-price',
@@ -1124,13 +1142,13 @@ class MarketAdapterService {
1124
1142
  });
1125
1143
  }
1126
1144
  const contextSignature = this.buildBotContextSignature(bot);
1127
- const cached = contextCache.get(bot.botKey);
1128
- const cachedCtx = cached && typeof cached === 'object' && cached.ctx ? cached.ctx : cached;
1145
+ const cached = contextCache.get(String(bot.botKey));
1146
+ const cachedCtx = (cached && typeof cached === 'object' && cached.ctx ? cached.ctx : cached);
1129
1147
  const cachedSignature = cached && typeof cached === 'object' && cached.signature ? cached.signature : null;
1130
- let ctx = cachedCtx;
1131
- if (!ctx || cachedSignature !== contextSignature) {
1132
- ctx = await deps.resolveBotContext(bot);
1133
- contextCache.set(bot.botKey, {
1148
+ let ctx = cachedCtx ?? {};
1149
+ if (!cachedCtx || cachedSignature !== contextSignature) {
1150
+ ctx = (await deps.resolveBotContext(bot)) ?? {};
1151
+ contextCache.set(String(bot.botKey), {
1134
1152
  signature: contextSignature,
1135
1153
  ctx,
1136
1154
  });
@@ -1145,7 +1163,7 @@ class MarketAdapterService {
1145
1163
  return { ok: false, reason: 'ama disabled' };
1146
1164
  }
1147
1165
  const lookbackBars = normalizeAmaSlopeLookbackBars(cfg.amaSlope?.lookbackBars);
1148
- const filePath = deps.candleFileForBot(bot.botKey, cfg.intervalSeconds);
1166
+ const filePath = deps.candleFileForBot(bot.botKey, Number(cfg.intervalSeconds));
1149
1167
  // mtime-validated read cache: the previous cycle serialized this very
1150
1168
  // file, so re-parsing ~250 KiB of JSON per bot per hour is pure waste.
1151
1169
  // The cache decides on the file's stat alone — an unstattable file (or a
@@ -1161,7 +1179,7 @@ class MarketAdapterService {
1161
1179
  // Retention targets, derived from the bot's own AMA parameters. Pure and
1162
1180
  // local, so they are computed before the off-hour gate below (which
1163
1181
  // needs the warmup target) and reused by the full path unchanged.
1164
- const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod);
1182
+ const amaWarmupBars = getAmaWarmupBars(Number(botAma.erPeriod), Number(botAma.slowPeriod), lookbackBars, Number(botAma.fastPeriod));
1165
1183
  const analysisKeepCount = amaWarmupBars + 1;
1166
1184
  // Retain one extra raw candle so the closed-candle analysis window still keeps a
1167
1185
  // full warmup/history set when the newest bucket is the current in-progress bar.
@@ -1184,9 +1202,9 @@ class MarketAdapterService {
1184
1202
  // change — must still run. Only a bot that has demonstrably consumed
1185
1203
  // that bucket and holds the data for it is skipped.
1186
1204
  const persistedBotState = (state?.bots && typeof state.bots === 'object')
1187
- ? state.bots[bot.botKey]
1205
+ ? state.bots[String(bot.botKey)]
1188
1206
  : null;
1189
- const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, cfg.intervalSeconds, undefined, cfg);
1207
+ const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, Number(cfg.intervalSeconds), undefined, cfg);
1190
1208
  const offHourSkipCovered = !!offHourSkip && this.candleFileCoversClosedBucket(existingCandles, existingMeta, marketSource, offHourSkip.latestClosedBucketStartMs, rawKeepCount);
1191
1209
  if (offHourSkip && offHourSkipCovered) {
1192
1210
  const skipNowIso = new Date().toISOString();
@@ -1202,7 +1220,7 @@ class MarketAdapterService {
1202
1220
  pendingClosedCandle: true,
1203
1221
  lastTriggerSuppressedReason: 'waiting_for_new_closed_candle',
1204
1222
  };
1205
- state.bots[bot.botKey] = skippedState;
1223
+ state.bots[String(bot.botKey)] = skippedState;
1206
1224
  return this.buildDefaultResult(bot, {
1207
1225
  dryRunMessages,
1208
1226
  source: 'off-hour-skip',
@@ -1214,8 +1232,8 @@ class MarketAdapterService {
1214
1232
  pendingClosedCandle: true,
1215
1233
  });
1216
1234
  }
1217
- const kibanaRequestTimeoutMs = Number.isFinite(cfg.kibanaRequestTimeoutMs) && cfg.kibanaRequestTimeoutMs > 0
1218
- ? cfg.kibanaRequestTimeoutMs
1235
+ const kibanaRequestTimeoutMs = Number.isFinite(Number(cfg.kibanaRequestTimeoutMs)) && Number(cfg.kibanaRequestTimeoutMs) > 0
1236
+ ? Number(cfg.kibanaRequestTimeoutMs)
1219
1237
  : MARKET_ADAPTER.KIBANA_REQUEST_TIMEOUT_MS;
1220
1238
  const fetchKibanaCandles = async (options = {}) => {
1221
1239
  const kibanaOptions = {
@@ -1264,7 +1282,8 @@ class MarketAdapterService {
1264
1282
  const tailEndTs = detected.sorted[detected.sorted.length - 1][0];
1265
1283
  // Skip Kibana verification if this tail range was already confirmed flat
1266
1284
  // on a previous cycle (the current tail is contained within a verified range).
1267
- const { startTs: vStart, endTs: vEnd } = verifiedRange;
1285
+ const vStart = Number(verifiedRange.startTs);
1286
+ const vEnd = Number(verifiedRange.endTs);
1268
1287
  if (Number.isFinite(vStart) && Number.isFinite(vEnd)
1269
1288
  && tailStartTs >= vStart && tailEndTs <= vEnd) {
1270
1289
  return { candles, keptStaleTailStartTs: tailStartTs, keptStaleTailEndTs: tailEndTs };
@@ -1272,7 +1291,7 @@ class MarketAdapterService {
1272
1291
  // Verify with Kibana: did the market actually trade during this period?
1273
1292
  try {
1274
1293
  const kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
1275
- intervalSeconds: cfg.intervalSeconds,
1294
+ intervalSeconds: Number(cfg.intervalSeconds),
1276
1295
  fillGapsToRequestedRange: false,
1277
1296
  apiKey: null,
1278
1297
  timeRange: {
@@ -1365,7 +1384,7 @@ class MarketAdapterService {
1365
1384
  ? deps.kibanaMarketSource && typeof deps.kibanaMarketSource.getMarketCandles === 'function'
1366
1385
  : deps.kibanaSource && typeof deps.kibanaSource.getLpCandlesForPool === 'function';
1367
1386
  const verifyAndFillLongSilence = async (candles, lastTs, latestClosedBucketTs, sourceLabel, incomingCandles = []) => {
1368
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1387
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1369
1388
  const silenceStartTs = Number(lastTs) + bucketMs;
1370
1389
  const earliestIncomingTs = (Array.isArray(incomingCandles) ? incomingCandles : [])
1371
1390
  .filter((c) => Array.isArray(c) && Number.isFinite(c[0]) && c[0] > lastTs)
@@ -1381,7 +1400,7 @@ class MarketAdapterService {
1381
1400
  }
1382
1401
  try {
1383
1402
  const kibanaSilenceCandles = await deps.withRetries(() => fetchKibanaCandles({
1384
- intervalSeconds: cfg.intervalSeconds,
1403
+ intervalSeconds: Number(cfg.intervalSeconds),
1385
1404
  fillGapsToRequestedRange: false,
1386
1405
  apiKey: null,
1387
1406
  timeRange: {
@@ -1402,7 +1421,7 @@ class MarketAdapterService {
1402
1421
  .filter((c) => Array.isArray(c) && c[0] === lastTs)
1403
1422
  .slice(-1)[0];
1404
1423
  const filledSilence = previousCandle
1405
- ? deps.fillCandleGaps([previousCandle, ...(Array.isArray(incomingCandles) ? incomingCandles : [])], cfg.intervalSeconds, lastTs, silenceEndTs)
1424
+ ? deps.fillCandleGaps([previousCandle, ...(Array.isArray(incomingCandles) ? incomingCandles : [])], Number(cfg.intervalSeconds), lastTs, silenceEndTs)
1406
1425
  .filter((c) => Array.isArray(c) && c[0] > lastTs)
1407
1426
  : [];
1408
1427
  if (filledSilence.length === 0)
@@ -1431,26 +1450,26 @@ class MarketAdapterService {
1431
1450
  }
1432
1451
  };
1433
1452
  const fillBoundedTrailingClosedGap = (candles, latestClosedBucketTs, nowMs, maxNativeGapFill) => {
1434
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1453
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1435
1454
  const latestKnownTs = Array.isArray(candles) && candles.length > 0
1436
1455
  ? candles[candles.length - 1]?.[0]
1437
1456
  : null;
1438
1457
  const trailingGapBuckets = Number.isFinite(bucketMs) && bucketMs > 0
1439
- && Number.isFinite(latestClosedBucketTs) && Number.isFinite(latestKnownTs)
1458
+ && Number.isFinite(latestClosedBucketTs) && latestKnownTs != null && Number.isFinite(latestKnownTs)
1440
1459
  && latestClosedBucketTs > latestKnownTs
1441
1460
  ? Math.round((latestClosedBucketTs - latestKnownTs) / bucketMs)
1442
1461
  : 0;
1443
1462
  if (trailingGapBuckets <= 0 || trailingGapBuckets > maxNativeGapFill) {
1444
1463
  return candles;
1445
1464
  }
1446
- return this.fillNativeIncrementalClosedGaps(candles, latestKnownTs, cfg.intervalSeconds, nowMs);
1465
+ return this.fillNativeIncrementalClosedGaps(candles, latestKnownTs, Number(cfg.intervalSeconds), nowMs);
1447
1466
  };
1448
1467
  if (isBookSource) {
1449
1468
  nativeRecentTradeSequences = [];
1450
1469
  nativeLastTradeTs = null;
1451
1470
  nativeOverlapCount = null;
1452
1471
  nativePagesFetched = null;
1453
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1472
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1454
1473
  const nowMs = this.getNowMs();
1455
1474
  if (needBootstrap) {
1456
1475
  // Bootstrap: Kibana first (deep history), native as fallback
@@ -1458,7 +1477,7 @@ class MarketAdapterService {
1458
1477
  let kibanaCandles = null;
1459
1478
  try {
1460
1479
  kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
1461
- intervalSeconds: cfg.intervalSeconds,
1480
+ intervalSeconds: Number(cfg.intervalSeconds),
1462
1481
  lookbackHours: kibanaLookbackHours,
1463
1482
  fillGapsToRequestedRange: false,
1464
1483
  apiKey: null,
@@ -1474,12 +1493,12 @@ class MarketAdapterService {
1474
1493
  }
1475
1494
  else {
1476
1495
  // Fall back to native
1477
- const nativeLookbackHours = Math.max(Number(cfg.bootstrapLookbackHours) || 0, Number(cfg.nativeBackfillHours) || 0, (analysisKeepCount * Math.max(Number(cfg.intervalSeconds) || 3600, 3600)) / 3600);
1496
+ const nativeLookbackHours = Math.max(Number(cfg.bootstrapLookbackHours) || 0, Number(Number(cfg.nativeBackfillHours)) || 0, (analysisKeepCount * Math.max(Number(Number(cfg.intervalSeconds)) || 3600, 3600)) / 3600);
1478
1497
  const nativeStartMs = Math.max(0, nowMs - (nativeLookbackHours * 3600 * 1000));
1479
1498
  let nativeCandles = [];
1480
1499
  try {
1481
1500
  if (typeof deps.fetchNativeMarketHistorySince === 'function') {
1482
- nativeCandles = await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, nativeStartMs, nowMs, cfg.intervalSeconds, { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, 'native market history bootstrap failed');
1501
+ nativeCandles = await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, nativeStartMs, nowMs, Number(cfg.intervalSeconds), { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, 'native market history bootstrap failed');
1483
1502
  }
1484
1503
  }
1485
1504
  catch (_) {
@@ -1502,7 +1521,7 @@ class MarketAdapterService {
1502
1521
  let nativeCandles = [];
1503
1522
  try {
1504
1523
  if (typeof deps.fetchNativeMarketHistorySince === 'function') {
1505
- nativeCandles = await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, nativeStartMs, nowMs, cfg.intervalSeconds, { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, 'native market history fetch failed');
1524
+ nativeCandles = await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, nativeStartMs, nowMs, Number(cfg.intervalSeconds), { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, 'native market history fetch failed');
1506
1525
  }
1507
1526
  }
1508
1527
  catch (_) {
@@ -1519,14 +1538,14 @@ class MarketAdapterService {
1519
1538
  const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
1520
1539
  const latestClosedBucketTs = currentBucketStartMs - bucketMs;
1521
1540
  const earliestIncomingTs = nativeCandles.length > 0 ? nativeCandles[0][0] : null;
1522
- const gapEndTs = Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
1541
+ const gapEndTs = earliestIncomingTs != null && Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
1523
1542
  ? earliestIncomingTs
1524
1543
  : latestClosedBucketTs + bucketMs;
1525
1544
  const gapBuckets = gapEndTs !== null && gapEndTs > lastTs
1526
1545
  ? Math.round((gapEndTs - lastTs) / bucketMs) - 1
1527
1546
  : 0;
1528
- const maxNativeGapFill = Number.isFinite(cfg.maxNativeGapFillCandles)
1529
- ? cfg.maxNativeGapFillCandles
1547
+ const maxNativeGapFill = Number.isFinite(Number(cfg.maxNativeGapFillCandles))
1548
+ ? Number(cfg.maxNativeGapFillCandles)
1530
1549
  : MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
1531
1550
  if (gapBuckets > maxNativeGapFill) {
1532
1551
  const verifiedSilence = await verifyAndFillLongSilence(nextCandles, lastTs, latestClosedBucketTs, sourceLabel, nativeCandles);
@@ -1553,7 +1572,7 @@ class MarketAdapterService {
1553
1572
  let kibanaCandles = null;
1554
1573
  try {
1555
1574
  kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
1556
- intervalSeconds: cfg.intervalSeconds,
1575
+ intervalSeconds: Number(cfg.intervalSeconds),
1557
1576
  lookbackHours,
1558
1577
  fillGapsToRequestedRange: false,
1559
1578
  apiKey: null,
@@ -1582,11 +1601,11 @@ class MarketAdapterService {
1582
1601
  if (Number.isFinite(latestTradeTs))
1583
1602
  nativeLastTradeTs = latestTradeTs;
1584
1603
  }
1585
- nativeCandles = deps.tradesToCandles(trades, ctx.assetA, ctx.assetB, cfg.intervalSeconds);
1604
+ nativeCandles = deps.tradesToCandles(trades, ctx.assetA, ctx.assetB, Number(cfg.intervalSeconds));
1586
1605
  if (nativeCandles.length > 0 && typeof deps.fillCandleGaps === 'function') {
1587
1606
  const eTs = nativeCandles[0][0];
1588
1607
  const lTs = nativeCandles[nativeCandles.length - 1][0];
1589
- nativeCandles = deps.fillCandleGaps(nativeCandles, cfg.intervalSeconds, eTs, lTs);
1608
+ nativeCandles = deps.fillCandleGaps(nativeCandles, Number(cfg.intervalSeconds), eTs, lTs);
1590
1609
  }
1591
1610
  }
1592
1611
  catch (_) {
@@ -1602,7 +1621,7 @@ class MarketAdapterService {
1602
1621
  if (stitched.length > 1 && typeof deps.fillCandleGaps === 'function') {
1603
1622
  const sTs = stitched[0][0];
1604
1623
  const eTs = stitched[stitched.length - 1][0];
1605
- nextCandles = deps.fillCandleGaps(stitched, cfg.intervalSeconds, sTs, eTs);
1624
+ nextCandles = deps.fillCandleGaps(stitched, Number(cfg.intervalSeconds), sTs, eTs);
1606
1625
  }
1607
1626
  else {
1608
1627
  nextCandles = stitched;
@@ -1660,13 +1679,13 @@ class MarketAdapterService {
1660
1679
  }
1661
1680
  }
1662
1681
  if (!overlapUsed) {
1663
- const sinceMs = lastTs - (cfg.nativeBackfillHours * 3600 * 1000);
1682
+ const sinceMs = lastTs - (Number(cfg.nativeBackfillHours) * 3600 * 1000);
1664
1683
  const fetchResult = await deps.withRetries(() => deps.fetchNativeTradesSince(ctx.poolId, sinceMs, cfg.pageLimit, cfg.maxPages), cfg.sourceRetries, cfg.retryDelayMs, 'native incremental fetch failed');
1665
1684
  fetchedTrades = Array.isArray(fetchResult?.trades) ? fetchResult.trades : [];
1666
1685
  if (fetchResult?.truncated && typeof deps.logger?.warn === 'function') {
1667
1686
  deps.logger.warn(`[market_adapter] ${bot.botKey}: native incremental history truncated (exhausted ${cfg.maxPages} pages)`);
1668
1687
  }
1669
- newTrades = this.filterTimeBasedNativeNewTrades(fetchedTrades, knownSequences, nativeLastTradeTs, lastTs, cfg.intervalSeconds);
1688
+ newTrades = this.filterTimeBasedNativeNewTrades(fetchedTrades, knownSequences, nativeLastTradeTs, lastTs, Number(cfg.intervalSeconds));
1670
1689
  sourceLabel = 'native-incremental-time';
1671
1690
  nativeOverlapCount = null;
1672
1691
  nativePagesFetched = fetchResult?.pages || null;
@@ -1677,26 +1696,26 @@ class MarketAdapterService {
1677
1696
  if (Number.isFinite(latestTradeTs))
1678
1697
  nativeLastTradeTs = latestTradeTs;
1679
1698
  }
1680
- const incomingCandles = deps.tradesToCandles(newTrades, ctx.assetA, ctx.assetB, cfg.intervalSeconds);
1699
+ const incomingCandles = deps.tradesToCandles(newTrades, ctx.assetA, ctx.assetB, Number(cfg.intervalSeconds));
1681
1700
  nextCandles = deps.mergeCandles(existingCandles, incomingCandles, {
1682
1701
  onCollision: (existingCandle, incomingCandle) => this.buildIncrementalCandleCollision(existingCandle, incomingCandle),
1683
1702
  });
1684
1703
  // Fill bounded no-trade gaps from native incremental fetch. Ordinary LP
1685
1704
  // inactivity should remain a continuous flat 1h series; very large gaps stay
1686
1705
  // visible for Kibana repair/stale-tail handling instead of carrying stale prices.
1687
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1706
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1688
1707
  const nowMs = this.getNowMs();
1689
1708
  const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
1690
1709
  const latestClosedBucketTs = currentBucketStartMs - bucketMs;
1691
- const earliestIncomingTs = incomingCandles.length > 0 ? incomingCandles[0][0] : null;
1692
- const gapEndTs = Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
1710
+ const earliestIncomingTs = incomingCandles.length > 0 ? Number(incomingCandles[0][0]) : null;
1711
+ const gapEndTs = (earliestIncomingTs != null && Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs)
1693
1712
  ? earliestIncomingTs
1694
1713
  : latestClosedBucketTs + bucketMs;
1695
1714
  const gapBuckets = Number.isFinite(gapEndTs) && gapEndTs > lastTs
1696
1715
  ? Math.round((gapEndTs - lastTs) / bucketMs) - 1
1697
1716
  : 0;
1698
1717
  if (gapBuckets <= trustedNoTradeGapThresholdCandles) {
1699
- nextCandles = this.fillNativeIncrementalClosedGaps(nextCandles, lastTs, cfg.intervalSeconds);
1718
+ nextCandles = this.fillNativeIncrementalClosedGaps(nextCandles, lastTs, Number(cfg.intervalSeconds));
1700
1719
  }
1701
1720
  else {
1702
1721
  const verifiedSilence = await verifyAndFillLongSilence(nextCandles, lastTs, latestClosedBucketTs, sourceLabel, incomingCandles);
@@ -1727,34 +1746,34 @@ class MarketAdapterService {
1727
1746
  let kibanaGapRepairTimestamps = [];
1728
1747
  let kibanaGapRepairAttempted = false;
1729
1748
  let gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1730
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1749
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1731
1750
  : { gapCount: 0, missingTimestamps: [] };
1732
1751
  // Step 1: Fill gaps within the trusted no-trade threshold directly (no Kibana needed).
1733
1752
  // The native incremental fetch already confirmed no trades for these timestamps.
1734
1753
  if (gapAnalysis.gapCount > 0) {
1735
- const filledNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, gapAnalysis.missingTimestamps, cfg.intervalSeconds, trustedNoTradeGapThresholdCandles);
1754
+ const filledNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, gapAnalysis.missingTimestamps, Number(Number(cfg.intervalSeconds)), trustedNoTradeGapThresholdCandles);
1736
1755
  if (filledNoTrade.filledTimestamps.length > 0) {
1737
1756
  nextCandles = filledNoTrade.candles;
1738
1757
  kibanaGapRepairTimestamps = filledNoTrade.filledTimestamps.slice();
1739
1758
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: synthesized ${filledNoTrade.filledTimestamps.length} no-trade candle(s) within trusted threshold `
1740
- + `[${filledNoTrade.filledTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
1759
+ + `[${filledNoTrade.filledTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
1741
1760
  }
1742
1761
  // Re-detect gaps — only beyond-threshold gaps remain
1743
1762
  gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1744
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1763
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1745
1764
  : { gapCount: 0, missingTimestamps: [] };
1746
1765
  }
1747
1766
  // Step 2: Only query Kibana for gaps beyond the trusted threshold
1748
1767
  if (gapAnalysis.gapCount > 0 && hasKibanaSource) {
1749
- const timeRange = this.buildGapRepairTimeRange(gapAnalysis.missingTimestamps, cfg.intervalSeconds, this.getGapRepairMaxHours(cfg));
1768
+ const timeRange = this.buildGapRepairTimeRange(gapAnalysis.missingTimestamps, Number(cfg.intervalSeconds), this.getGapRepairMaxHours(cfg));
1750
1769
  if (timeRange) {
1751
1770
  kibanaGapRepairAttempted = true;
1752
1771
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: ${gapAnalysis.gapCount} candle gap(s) beyond trusted threshold; `
1753
1772
  + `requesting Kibana repair for ${timeRange.gte} -> ${timeRange.lte} `
1754
- + `missing=[${gapAnalysis.missingTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
1773
+ + `missing=[${gapAnalysis.missingTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
1755
1774
  try {
1756
1775
  const kibanaGapCandles = await deps.withRetries(() => fetchKibanaCandles({
1757
- intervalSeconds: cfg.intervalSeconds,
1776
+ intervalSeconds: Number(cfg.intervalSeconds),
1758
1777
  fillGapsToRequestedRange: false,
1759
1778
  apiKey: null,
1760
1779
  timeRange,
@@ -1770,19 +1789,19 @@ class MarketAdapterService {
1770
1789
  kibanaGapRepairTimestamps = [...kibanaGapRepairTimestamps, ...kibanaPatchedTs];
1771
1790
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: Kibana gap repair patched ${kibanaPatchedTs.length}/${gapAnalysis.gapCount} gap(s)`
1772
1791
  + (kibanaPatchedTs.length > 0
1773
- ? ` [${kibanaPatchedTs.map((ts) => new Date(ts).toISOString()).join(', ')}]`
1792
+ ? ` [${kibanaPatchedTs.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`
1774
1793
  : ''));
1775
1794
  }
1776
1795
  else {
1777
1796
  // Kibana returned no data — that IS verification: no trades happened.
1778
1797
  // Synthesize no-trade candles for all gaps within the queried window.
1779
1798
  const verifiedGapTimestamps = this.getMissingTimestampsWithinTimeRange(gapAnalysis.missingTimestamps, timeRange);
1780
- const verifiedNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, verifiedGapTimestamps, cfg.intervalSeconds, verifiedGapTimestamps.length);
1799
+ const verifiedNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, verifiedGapTimestamps, Number(cfg.intervalSeconds), verifiedGapTimestamps.length);
1781
1800
  if (verifiedNoTrade.filledTimestamps.length > 0) {
1782
1801
  nextCandles = verifiedNoTrade.candles;
1783
1802
  kibanaGapRepairTimestamps = [...kibanaGapRepairTimestamps, ...verifiedNoTrade.filledTimestamps];
1784
1803
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: synthesized ${verifiedNoTrade.filledTimestamps.length} no-trade candle(s) after empty Kibana repair `
1785
- + `[${verifiedNoTrade.filledTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
1804
+ + `[${verifiedNoTrade.filledTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
1786
1805
  }
1787
1806
  else {
1788
1807
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: Kibana empty but could not synthesize gaps (missing neighbors)`, 'warn');
@@ -1794,11 +1813,11 @@ class MarketAdapterService {
1794
1813
  }
1795
1814
  }
1796
1815
  gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1797
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1816
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1798
1817
  : { gapCount: 0, missingTimestamps: [] };
1799
1818
  if (gapAnalysis.gapCount > 0) {
1800
1819
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: ${gapAnalysis.gapCount} candle gap(s) still unresolved after Kibana repair `
1801
- + `[${gapAnalysis.missingTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`, 'warn');
1820
+ + `[${gapAnalysis.missingTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`, 'warn');
1802
1821
  }
1803
1822
  }
1804
1823
  // ── Historical backfill: if candle count is still insufficient for AMA warmup,
@@ -1809,13 +1828,13 @@ class MarketAdapterService {
1809
1828
  const needsHistoricalBackfill = !kibanaGapRepairAttempted || gapAnalysis.gapCount > 0;
1810
1829
  if (!kibanaBootstrapEmpty && needsHistoricalBackfill && candleShortfall > 0 && nextCandles.length > 0 && hasKibanaSource) {
1811
1830
  const oldestTs = nextCandles[0][0];
1812
- const shortfallMs = candleShortfall * cfg.intervalSeconds * 1000;
1831
+ const shortfallMs = candleShortfall * Number(cfg.intervalSeconds) * 1000;
1813
1832
  const bufferMs = 24 * 3600 * 1000; // 24h buffer
1814
1833
  const backfillStartMs = Math.max(0, oldestTs - shortfallMs - bufferMs);
1815
- const backfillEndMs = oldestTs + cfg.intervalSeconds * 1000;
1834
+ const backfillEndMs = oldestTs + Number(cfg.intervalSeconds) * 1000;
1816
1835
  try {
1817
1836
  const historicalCandles = await deps.withRetries(() => fetchKibanaCandles({
1818
- intervalSeconds: cfg.intervalSeconds,
1837
+ intervalSeconds: Number(cfg.intervalSeconds),
1819
1838
  fillGapsToRequestedRange: false,
1820
1839
  apiKey: null,
1821
1840
  timeRange: {
@@ -1838,7 +1857,7 @@ class MarketAdapterService {
1838
1857
  const retainedTimestamps = new Set(nextCandles.map((c) => c[0]));
1839
1858
  const kibanaGapRepairCount = kibanaGapRepairTimestamps.filter((ts) => retainedTimestamps.has(ts)).length;
1840
1859
  const retainedGapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1841
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1860
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1842
1861
  : { gapCount: 0, missingTimestamps: [] };
1843
1862
  return {
1844
1863
  nextCandles,
@@ -1878,16 +1897,16 @@ class MarketAdapterService {
1878
1897
  kibanaBackfillCount = loadResult.kibanaBackfillCount || 0;
1879
1898
  unresolvedGapCount = loadResult.unresolvedGapCount;
1880
1899
  nativeRecentTradeSequences = Array.isArray(loadResult.nativeRecentTradeSequences) ? loadResult.nativeRecentTradeSequences : [];
1881
- nativeLastTradeTs = Number.isFinite(loadResult.nativeLastTradeTs) ? loadResult.nativeLastTradeTs : null;
1882
- nativeOverlapCount = Number.isFinite(loadResult.nativeOverlapCount) ? loadResult.nativeOverlapCount : null;
1883
- nativePagesFetched = Number.isFinite(loadResult.nativePagesFetched) ? loadResult.nativePagesFetched : null;
1900
+ nativeLastTradeTs = Number.isFinite(loadResult.nativeLastTradeTs) ? Number(loadResult.nativeLastTradeTs) : null;
1901
+ nativeOverlapCount = Number.isFinite(loadResult.nativeOverlapCount) ? Number(loadResult.nativeOverlapCount) : null;
1902
+ nativePagesFetched = Number.isFinite(loadResult.nativePagesFetched) ? Number(loadResult.nativePagesFetched) : null;
1884
1903
  const nowMs = this.getNowMs();
1885
- ({ closedCandles, currentBucketStartMs } = this.selectClosedCandles(nextCandles, cfg.intervalSeconds, nowMs));
1904
+ ({ closedCandles, currentBucketStartMs } = this.selectClosedCandles(nextCandles, Number(cfg.intervalSeconds), nowMs));
1886
1905
  rawLastCandle = nextCandles[nextCandles.length - 1] || [0, 0, 0, 0, 0];
1887
1906
  rawLastCandleTs = rawLastCandle[0] || null;
1888
1907
  latestClosedCandle = closedCandles[closedCandles.length - 1] || null;
1889
1908
  lastClosedCandleTs = latestClosedCandle ? latestClosedCandle[0] : null;
1890
- botState = this.normalizePersistedBotState(state.bots[bot.botKey], lookbackBars);
1909
+ botState = this.normalizePersistedBotState(state.bots[String(bot.botKey)], lookbackBars);
1891
1910
  if (sourceMismatch) {
1892
1911
  botState = {};
1893
1912
  }
@@ -1949,7 +1968,7 @@ class MarketAdapterService {
1949
1968
  marketSource,
1950
1969
  assetA: ctx.assetA,
1951
1970
  assetB: ctx.assetB,
1952
- intervalSeconds: cfg.intervalSeconds,
1971
+ intervalSeconds: Number(cfg.intervalSeconds),
1953
1972
  candleCount: nextCandles.length,
1954
1973
  analysisCandleCount: closedCandles.length,
1955
1974
  rawKeepCount,
@@ -1983,7 +2002,7 @@ class MarketAdapterService {
1983
2002
  const triggerSuppressedReason = staleData
1984
2003
  ? 'stale_candle_data'
1985
2004
  : 'waiting_for_new_closed_candle';
1986
- state.bots[bot.botKey] = {
2005
+ state.bots[String(bot.botKey)] = {
1987
2006
  ...botState,
1988
2007
  botName: bot.name,
1989
2008
  botKey: bot.botKey,
@@ -2105,10 +2124,10 @@ class MarketAdapterService {
2105
2124
  closes,
2106
2125
  amaValues,
2107
2126
  lookbackBars,
2108
- botAma,
2127
+ botAma: botAma,
2109
2128
  weightVariance,
2110
2129
  nowIso,
2111
- cfg,
2130
+ cfg: cfg,
2112
2131
  bot,
2113
2132
  atrPeriod,
2114
2133
  });
@@ -2117,7 +2136,7 @@ class MarketAdapterService {
2117
2136
  weights = dwResult.weights;
2118
2137
  dynamicWeightsPayload = dwResult.dynamicWeightsPayload;
2119
2138
  }
2120
- const amaSlopeResetDetails = this.buildAmaSlopeResetDetails(amaSlope, previousGridResetAmaSlope, cfg);
2139
+ const amaSlopeResetDetails = this.buildAmaSlopeResetDetails(amaSlope ?? {}, previousGridResetAmaSlope, cfg);
2121
2140
  const amaSlopeDeltaPercent = amaSlopeResetDetails.deltaPercent;
2122
2141
  const amaSlopeThresholdPercent = amaSlopeResetDetails.thresholdPercent;
2123
2142
  // 4. Advisory collateral-ratio hint only; execution is owned by the debt runtime.
@@ -2172,13 +2191,6 @@ class MarketAdapterService {
2172
2191
  // trigger/snapshot write happened on a stale-but-new cycle.
2173
2192
  triggerSuppressedReason = 'stale_candle_data';
2174
2193
  }
2175
- // Slope-delta persistence gate (trigger B). Advances only on actionable
2176
- // cycles; any successful reset clears it via advanceTriggeredBotState.
2177
- const amaSlopePersistence = (!staleData && !hasUnresolvedCandleGaps)
2178
- ? this.advanceAmaSlopePersistence(amaSlopeResetDetails, cfg, botState)
2179
- : { shouldTrigger: false, persistBars: this.resolveAmaSlopePersistBars(cfg) };
2180
- const amaSlopeShouldTrigger = amaSlopePersistence.shouldTrigger;
2181
- const amaSlopePersistBars = amaSlopePersistence.persistBars;
2182
2194
  const buildDynamicGridOptions = (options = {}) => {
2183
2195
  const payload = {
2184
2196
  gridCenterPrice: options.gridCenterPrice ?? null, // explicit baseline if provided
@@ -2356,7 +2368,19 @@ class MarketAdapterService {
2356
2368
  }
2357
2369
  }
2358
2370
  }
2359
- if (!triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted && amaSlopeShouldTrigger) {
2371
+ // Slope-delta persistence gate (trigger B). Advance only when this
2372
+ // cycle can actually act on it — after trigger A (price/Drift) and
2373
+ // bootstrap have had their chance, and only for whitelisted bots.
2374
+ // Mirrors grid_reset_sim, where the slope candidate is evaluated
2375
+ // only in the price trigger's `else` branch, and stops the counter
2376
+ // accumulating for bots that never use the slope trigger.
2377
+ const amaSlopeGateActive = !triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted;
2378
+ const amaSlopePersistence = amaSlopeGateActive
2379
+ ? this.advanceAmaSlopePersistence(amaSlopeResetDetails, cfg, botState)
2380
+ : { shouldTrigger: false, persistBars: this.resolveAmaSlopePersistBars(cfg) };
2381
+ const amaSlopeShouldTrigger = amaSlopePersistence.shouldTrigger;
2382
+ const amaSlopePersistBars = amaSlopePersistence.persistBars;
2383
+ if (amaSlopeGateActive && amaSlopeShouldTrigger) {
2360
2384
  const amaSlopePersisted = persistDynamicGridSnapshot(centerPrice);
2361
2385
  if (!amaSlopePersisted) {
2362
2386
  triggerSuppressedReason = 'ama_slope_persist_failed';
@@ -2453,7 +2477,7 @@ class MarketAdapterService {
2453
2477
  ? (botState.amaSlopeThresholdPercent ?? amaSlopeThresholdPercent ?? null)
2454
2478
  : (amaSlopeThresholdPercent ?? botState.amaSlopeThresholdPercent ?? null);
2455
2479
  const stateGridRangeScalingAmaSlope = botState.gridRangeScalingAmaSlope || previousGridResetAmaSlope || null;
2456
- state.bots[bot.botKey] = {
2480
+ state.bots[String(bot.botKey)] = {
2457
2481
  ...botState,
2458
2482
  botName: bot.name,
2459
2483
  botKey: bot.botKey,
@@ -2528,7 +2552,7 @@ class MarketAdapterService {
2528
2552
  dryRunMessages,
2529
2553
  source: sourceLabel,
2530
2554
  marketSource,
2531
- intervalSeconds: cfg.intervalSeconds,
2555
+ intervalSeconds: Number(cfg.intervalSeconds),
2532
2556
  candleCount: nextCandles.length,
2533
2557
  analysisCandleCount: analysisCandles.length,
2534
2558
  rawKeepCount,
@@ -2555,7 +2579,7 @@ class MarketAdapterService {
2555
2579
  triggerSuppressedReason,
2556
2580
  weights: canExposeDynamicWeights ? weights : null,
2557
2581
  collateralRecommendation,
2558
- amaSlope: amaSlope || botState.amaSlope || null,
2582
+ amaSlope: (amaSlope || botState.amaSlope || null),
2559
2583
  amaSlopeDeltaPercent: Number.isFinite(amaSlopeDeltaPercent)
2560
2584
  ? amaSlopeDeltaPercent
2561
2585
  : botState.amaSlopeDeltaPercent ?? null,