dexbot 1.6.10 → 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 (365) hide show
  1. package/CHANGELOG.md +50 -3
  2. package/README.md +3 -1
  3. package/analysis/README.md +51 -11
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +3 -3
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  9. package/claw/modules/chain_broadcast.ts +7 -1
  10. package/claw/modules/claw_launcher.ts +1 -1
  11. package/claw/modules/launcher_mode_detector.ts +9 -2
  12. package/claw/package.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  14. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  15. package/dist/analysis/account_resolver.d.ts +1 -1
  16. package/dist/analysis/account_resolver.js +15 -2
  17. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  18. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  19. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  24. package/dist/analysis/analyze_args.d.ts +31 -0
  25. package/dist/analysis/analyze_args.js +41 -0
  26. package/dist/analysis/analyze_dynamic_weight.js +7 -20
  27. package/dist/analysis/analyze_kalman.js +7 -17
  28. package/dist/analysis/analyze_regime.js +7 -17
  29. package/dist/analysis/analyze_regime_windows.js +8 -18
  30. package/dist/analysis/analyze_risk_profile.js +8 -18
  31. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  32. package/dist/analysis/analyze_volatility.js +7 -17
  33. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  34. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
  35. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  36. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
  37. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  38. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  39. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  40. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  41. package/dist/analysis/bot_key_utils.d.ts +18 -10
  42. package/dist/analysis/bot_key_utils.js +10 -17
  43. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  44. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  45. package/dist/analysis/chain_pool.d.ts +3 -1
  46. package/dist/analysis/chart_ui.d.ts +5 -2
  47. package/dist/analysis/chart_ui.js +6 -3
  48. package/dist/analysis/chart_utils.d.ts +5 -5
  49. package/dist/analysis/chart_utils.js +9 -0
  50. package/dist/analysis/fills_cache.d.ts +64 -0
  51. package/dist/analysis/fills_cache.js +254 -0
  52. package/dist/analysis/fills_source.d.ts +2 -2
  53. package/dist/analysis/fills_source.js +19 -14
  54. package/dist/analysis/grid_correction_check.d.ts +1 -1
  55. package/dist/analysis/grid_correction_check.js +12 -11
  56. package/dist/analysis/math_utils.d.ts +7 -6
  57. package/dist/analysis/math_utils.js +5 -8
  58. package/dist/analysis/pnl_report.d.ts +39 -0
  59. package/dist/analysis/pnl_report.js +325 -0
  60. package/dist/analysis/price_sources.d.ts +8 -8
  61. package/dist/analysis/price_sources.js +5 -4
  62. package/dist/analysis/resolve_bot_accounts.js +2 -2
  63. package/dist/analysis/resolve_source.d.ts +1 -2
  64. package/dist/analysis/trade_profitability.d.ts +32 -2
  65. package/dist/analysis/trade_profitability.js +232 -106
  66. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  67. package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
  68. package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
  69. package/dist/analysis/tradingview/grid_reset_config.js +35 -6
  70. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
  71. package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
  72. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  73. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
  74. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  75. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  76. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  77. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
  78. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
  79. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  80. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  81. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  82. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  83. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  84. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  85. package/dist/credential-daemon.js +34 -20
  86. package/dist/dexbot.js +17 -14
  87. package/dist/market_adapter/candle_utils.d.ts +22 -18
  88. package/dist/market_adapter/candle_utils.js +24 -20
  89. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  90. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  91. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  92. package/dist/market_adapter/core/kibana_candles.js +9 -7
  93. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  94. package/dist/market_adapter/core/kibana_client.js +8 -7
  95. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  96. package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
  97. package/dist/market_adapter/core/market_adapter_service.js +184 -101
  98. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  99. package/dist/market_adapter/core/strategies/ama.js +7 -32
  100. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  101. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  102. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  103. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  104. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  106. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
  107. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
  108. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  109. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  110. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  111. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  112. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  113. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  114. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  115. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  116. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  117. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  118. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
  119. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  120. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  121. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  122. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  123. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  124. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  125. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  126. package/dist/market_adapter/inputs/window_cache.js +8 -8
  127. package/dist/market_adapter/interval_utils.d.ts +4 -4
  128. package/dist/market_adapter/log_format.d.ts +6 -6
  129. package/dist/market_adapter/log_format.js +28 -22
  130. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  131. package/dist/market_adapter/lp_chart_core.js +26 -192
  132. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  133. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  134. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  135. package/dist/market_adapter/market_adapter.d.ts +94 -33
  136. package/dist/market_adapter/market_adapter.js +69 -75
  137. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  138. package/dist/market_adapter/utils/adapter_client.js +2 -2
  139. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  140. package/dist/market_adapter/utils/chain.d.ts +50 -41
  141. package/dist/market_adapter/utils/chain.js +40 -46
  142. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  143. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  144. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  145. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  146. package/dist/market_adapter/utils/file_lock.js +36 -32
  147. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  148. package/dist/market_adapter/utils/native_history.js +35 -28
  149. package/dist/modules/account_bots.d.ts +577 -21
  150. package/dist/modules/account_bots.js +182 -158
  151. package/dist/modules/account_orders.d.ts +66 -30
  152. package/dist/modules/account_orders.js +22 -20
  153. package/dist/modules/authority_resolver.d.ts +12 -2
  154. package/dist/modules/authority_resolver.js +15 -8
  155. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  156. package/dist/modules/bitshares-native/chain_client.js +45 -46
  157. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  158. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  159. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  160. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  161. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  162. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  163. package/dist/modules/bitshares-native/index.d.ts +1 -1
  164. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  165. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  166. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  167. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  168. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  169. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  170. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  171. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  172. package/dist/modules/bitshares-native/serial/types.js +55 -62
  173. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  174. package/dist/modules/bitshares-native/signing_client.js +19 -14
  175. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  176. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  177. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  178. package/dist/modules/bitshares-native/transport.js +5 -4
  179. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  180. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  181. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  182. package/dist/modules/bitshares_client.d.ts +45 -13
  183. package/dist/modules/bitshares_client.js +28 -19
  184. package/dist/modules/bot_defaults.d.ts +6 -15
  185. package/dist/modules/bot_defaults.js +1 -5
  186. package/dist/modules/bot_settings.d.ts +44 -10
  187. package/dist/modules/bot_settings.js +11 -8
  188. package/dist/modules/bots_file_lock.d.ts +6 -6
  189. package/dist/modules/bots_file_lock.js +16 -12
  190. package/dist/modules/broadcast_failure.d.ts +2 -2
  191. package/dist/modules/broadcast_failure.js +5 -4
  192. package/dist/modules/chain_keys.d.ts +42 -40
  193. package/dist/modules/chain_keys.js +53 -45
  194. package/dist/modules/chain_orders.d.ts +93 -59
  195. package/dist/modules/chain_orders.js +31 -23
  196. package/dist/modules/constants.d.ts +530 -32
  197. package/dist/modules/constants.js +52 -60
  198. package/dist/modules/cr_planner.d.ts +40 -2
  199. package/dist/modules/credential_policy.d.ts +68 -8
  200. package/dist/modules/credential_policy.js +37 -31
  201. package/dist/modules/credential_session_cache.d.ts +2 -2
  202. package/dist/modules/credit_pricing.d.ts +42 -6
  203. package/dist/modules/credit_pricing.js +44 -30
  204. package/dist/modules/credit_runtime.d.ts +276 -118
  205. package/dist/modules/credit_runtime.js +462 -165
  206. package/dist/modules/crypto/browser_provider.js +6 -4
  207. package/dist/modules/crypto/node_provider.js +1 -1
  208. package/dist/modules/crypto/pure_scrypt.js +35 -4
  209. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  210. package/dist/modules/crypto/sync.d.ts +9 -9
  211. package/dist/modules/crypto/sync.js +16 -9
  212. package/dist/modules/dexbot_class.d.ts +195 -139
  213. package/dist/modules/dexbot_class.js +78 -28
  214. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  215. package/dist/modules/dexbot_cow_runtime.js +248 -206
  216. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  217. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  218. package/dist/modules/dexbot_fill_runtime.js +48 -41
  219. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  220. package/dist/modules/dexbot_maintenance_runtime.js +117 -80
  221. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  222. package/dist/modules/dexbot_startup_runtime.js +43 -43
  223. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  224. package/dist/modules/dexbot_state_recovery.js +18 -13
  225. package/dist/modules/fund_registry.d.ts +4 -2
  226. package/dist/modules/fund_registry.js +10 -10
  227. package/dist/modules/general_settings.d.ts +30 -4
  228. package/dist/modules/graceful_shutdown.d.ts +3 -3
  229. package/dist/modules/graceful_shutdown.js +2 -2
  230. package/dist/modules/grid_price_source.d.ts +1 -1
  231. package/dist/modules/key_store.d.ts +14 -8
  232. package/dist/modules/key_store.js +7 -6
  233. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  234. package/dist/modules/launcher/adapter_requirement.js +5 -5
  235. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  236. package/dist/modules/launcher/bot_supervisor.js +12 -11
  237. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  238. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  239. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  240. package/dist/modules/launcher/credential_daemon.js +2 -2
  241. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  242. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  243. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  244. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  245. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  246. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  247. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  248. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  249. package/dist/modules/launcher/supervisor_control.js +4 -2
  250. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  251. package/dist/modules/market_adapter_whitelist.js +15 -3
  252. package/dist/modules/node_manager.d.ts +41 -11
  253. package/dist/modules/node_manager.js +5 -4
  254. package/dist/modules/order/accounting.d.ts +53 -24
  255. package/dist/modules/order/accounting.js +40 -14
  256. package/dist/modules/order/async_lock.d.ts +5 -2
  257. package/dist/modules/order/async_lock.js +1 -1
  258. package/dist/modules/order/export.d.ts +7 -6
  259. package/dist/modules/order/export.js +1 -7
  260. package/dist/modules/order/format.d.ts +39 -19
  261. package/dist/modules/order/format.js +62 -16
  262. package/dist/modules/order/genesis_policy.d.ts +21 -18
  263. package/dist/modules/order/genesis_policy.js +12 -8
  264. package/dist/modules/order/grid.d.ts +142 -36
  265. package/dist/modules/order/grid.js +148 -123
  266. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  267. package/dist/modules/order/grid_reconcile.js +13 -12
  268. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  269. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  270. package/dist/modules/order/index.d.ts +263 -1
  271. package/dist/modules/order/logger.d.ts +45 -11
  272. package/dist/modules/order/logger.js +38 -40
  273. package/dist/modules/order/logger_state.d.ts +4 -4
  274. package/dist/modules/order/manager.d.ts +226 -180
  275. package/dist/modules/order/manager.js +101 -83
  276. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  277. package/dist/modules/order/processed_fill_store.js +16 -27
  278. package/dist/modules/order/strategy.d.ts +21 -13
  279. package/dist/modules/order/strategy.js +5 -6
  280. package/dist/modules/order/sync_engine.d.ts +91 -33
  281. package/dist/modules/order/sync_engine.js +99 -54
  282. package/dist/modules/order/utils/math.d.ts +157 -102
  283. package/dist/modules/order/utils/math.js +77 -38
  284. package/dist/modules/order/utils/order.d.ts +326 -106
  285. package/dist/modules/order/utils/order.js +200 -99
  286. package/dist/modules/order/utils/slot.d.ts +1 -1
  287. package/dist/modules/order/utils/system.d.ts +176 -26
  288. package/dist/modules/order/utils/system.js +86 -69
  289. package/dist/modules/order/utils/validate.d.ts +89 -41
  290. package/dist/modules/order/utils/validate.js +24 -22
  291. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  292. package/dist/modules/order/utils/withPoolRef.js +18 -12
  293. package/dist/modules/order/working_grid.d.ts +14 -13
  294. package/dist/modules/paths.d.ts +3 -4
  295. package/dist/modules/paths.js +3 -27
  296. package/dist/modules/process_discovery.d.ts +1 -1
  297. package/dist/modules/process_discovery.js +2 -1
  298. package/dist/modules/runtime.d.ts +7 -3
  299. package/dist/modules/runtime.js +4 -3
  300. package/dist/modules/runtime_settings.d.ts +15 -10
  301. package/dist/modules/runtime_settings.js +30 -24
  302. package/dist/modules/settings_merge.d.ts +29 -3
  303. package/dist/modules/settings_merge.js +56 -78
  304. package/dist/modules/socket_json_client.d.ts +7 -4
  305. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  306. package/dist/modules/storage/browser_adapter.js +7 -30
  307. package/dist/modules/storage/index.d.ts +1 -1
  308. package/dist/modules/storage/node_adapter.d.ts +45 -27
  309. package/dist/modules/storage/node_adapter.js +9 -9
  310. package/dist/modules/storage/types.d.ts +5 -4
  311. package/dist/modules/types.d.ts +1071 -2
  312. package/dist/modules/types.js +4 -1
  313. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  314. package/dist/modules/utils/asset_symbols.js +2 -1
  315. package/dist/modules/utils/errors.d.ts +9 -0
  316. package/dist/modules/utils/errors.js +23 -1
  317. package/dist/modules/utils/time_range.d.ts +4 -0
  318. package/dist/modules/utils/time_range.js +18 -0
  319. package/dist/modules/validate_profiles.js +53 -43
  320. package/dist/modules/version_notice.d.ts +14 -3
  321. package/dist/modules/version_notice.js +6 -4
  322. package/dist/pm2.d.ts +29 -27
  323. package/dist/pm2.js +5 -5
  324. package/dist/scripts/analyze-credit.d.ts +2 -1
  325. package/dist/scripts/analyze-credit.js +23 -24
  326. package/dist/scripts/analyze-orders.d.ts +77 -9
  327. package/dist/scripts/analyze-orders.js +66 -84
  328. package/dist/scripts/chart_command.d.ts +27 -18
  329. package/dist/scripts/chart_command.js +16 -15
  330. package/dist/scripts/check_any.d.ts +18 -0
  331. package/dist/scripts/check_any.js +126 -0
  332. package/dist/scripts/diagnose-pool-history.js +12 -7
  333. package/dist/scripts/pnl.d.ts +3 -0
  334. package/dist/scripts/pnl.js +40 -0
  335. package/dist/scripts/print_grid.js +0 -1
  336. package/dist/scripts/run-tests.js +39 -7
  337. package/dist/scripts/runner.js +1 -1
  338. package/dist/scripts/test-credit-renewal.js +30 -21
  339. package/dist/scripts/update.d.ts +10 -5
  340. package/dist/scripts/update.js +168 -103
  341. package/dist/scripts/update_dist_freshness.js +1 -0
  342. package/dist/scripts/update_layout.d.ts +61 -0
  343. package/dist/scripts/update_layout.js +180 -0
  344. package/dist/scripts/validate_bots.js +2 -1
  345. package/dist/scripts/verify-browser-bundle.js +8 -0
  346. package/dist/unlock.d.ts +28 -3
  347. package/dist/unlock.js +72 -10
  348. package/docs/BITSHARES_ONBOARDING.md +2 -0
  349. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  350. package/docs/COW_INVARIANTS.md +13 -6
  351. package/docs/DEXBOT_COMPARISON.md +8 -8
  352. package/docs/EVOLUTION.md +12 -10
  353. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  354. package/docs/GRID_RECALCULATION.md +15 -16
  355. package/docs/GRID_RECONCILE.md +14 -3
  356. package/docs/LIFECYCLE.md +11 -11
  357. package/docs/MPA_CREDIT_USAGE.md +22 -3
  358. package/docs/README.md +15 -4
  359. package/docs/WORKFLOW.md +1 -0
  360. package/docs/architecture.md +12 -9
  361. package/docs/developer_guide.md +6 -6
  362. package/market_adapter/README.md +9 -26
  363. package/modules/README.md +4 -1
  364. package/package.json +4 -1
  365. package/scripts/README.md +14 -0
@@ -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,29 +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;
72
+ // Persistence-gate state carried across restarts (see advanceAmaSlopePersistence).
73
+ const persistCount = Number(d.amaSlopePersistCount);
74
+ normalized.amaSlopePersistCount = Number.isFinite(persistCount) && persistCount > 0 ? Math.floor(persistCount) : 0;
75
+ const persistDir = Number(d.amaSlopePersistDir);
76
+ normalized.amaSlopePersistDir = persistDir === 1 ? 1 : (persistDir === -1 ? -1 : 0);
70
77
  return normalized;
71
78
  }
72
79
  function computeGridPriceOffsetPlan(bot, amaSlope) {
73
- const targetSpreadPercentRaw = Number(bot?.targetSpreadPercent);
80
+ const b = bot;
81
+ const a = amaSlope;
82
+ const targetSpreadPercentRaw = Number(b?.targetSpreadPercent);
74
83
  const targetSpreadPercent = Number.isFinite(targetSpreadPercentRaw) && targetSpreadPercentRaw > 0
75
84
  ? targetSpreadPercentRaw
76
85
  : Number(DEFAULT_CONFIG.targetSpreadPercent);
77
86
  const maxGridPriceOffsetPct = targetSpreadPercent / 2;
78
- const trend = amaSlope?.trend;
79
- const rawSlopeOffset = Number(amaSlope?.rawSlopeOffset);
80
- const maxSlopeOffset = Number(amaSlope?.maxSlopeOffset);
87
+ const trend = a?.trend;
88
+ const rawSlopeOffset = Number(a?.rawSlopeOffset);
89
+ const maxSlopeOffset = Number(a?.maxSlopeOffset);
81
90
  const directionalSlope = Number.isFinite(rawSlopeOffset)
82
91
  ? Math.abs(rawSlopeOffset)
83
- : Math.abs(Number(amaSlope?.slopeOffset));
92
+ : Math.abs(Number(a?.slopeOffset));
84
93
  const slopeRatio = Number.isFinite(directionalSlope) && Number.isFinite(maxSlopeOffset) && maxSlopeOffset > 0
85
94
  ? Math.min(directionalSlope / maxSlopeOffset, 1)
86
95
  : 0;
@@ -249,7 +258,8 @@ class MarketAdapterService {
249
258
  * shortfall) is evaluateStateRepairVeto above; keep the two in step.
250
259
  */
251
260
  candleFileCoversClosedBucket(candles, meta, marketSource, closedBucketStartMs, requiredCount = 0) {
252
- if (!Number.isFinite(closedBucketStartMs) || closedBucketStartMs <= 0)
261
+ const closedBucketMs = Number(closedBucketStartMs);
262
+ if (!Number.isFinite(closedBucketMs) || closedBucketMs <= 0)
253
263
  return false;
254
264
  if (this.isCandleSourceMismatch(meta, marketSource))
255
265
  return false;
@@ -264,7 +274,7 @@ class MarketAdapterService {
264
274
  const newestTs = Number(candles[candles.length - 1]?.[0]);
265
275
  if (!Number.isFinite(newestTs))
266
276
  return false;
267
- return newestTs >= closedBucketStartMs;
277
+ return newestTs >= closedBucketMs;
268
278
  }
269
279
  selectClosedCandles(candles, intervalSeconds, nowMs = this.getNowMs()) {
270
280
  const currentBucketStart = bucketStartMs(nowMs, intervalSeconds);
@@ -308,8 +318,8 @@ class MarketAdapterService {
308
318
  getMissingTimestampsWithinTimeRange(missingTimestamps, timeRange) {
309
319
  if (!Array.isArray(missingTimestamps) || missingTimestamps.length === 0 || !timeRange)
310
320
  return [];
311
- const gteMs = Date.parse(timeRange.gte);
312
- const lteMs = Date.parse(timeRange.lte);
321
+ const gteMs = Date.parse(String(timeRange.gte));
322
+ const lteMs = Date.parse(String(timeRange.lte));
313
323
  if (!Number.isFinite(gteMs) || !Number.isFinite(lteMs) || lteMs < gteMs)
314
324
  return [];
315
325
  return missingTimestamps.filter((ts) => Number.isFinite(ts) && ts >= gteMs && ts <= lteMs);
@@ -320,7 +330,7 @@ class MarketAdapterService {
320
330
  ? intervalSeconds / 3600
321
331
  : 1;
322
332
  const maxCandles = Number.isFinite(cfg?.maxNativeGapFillCandles)
323
- ? cfg.maxNativeGapFillCandles
333
+ ? Number(Number(cfg.maxNativeGapFillCandles))
324
334
  : MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
325
335
  // Include the candle before and after the missing run so Kibana repair
326
336
  // does not truncate a valid threshold-sized gap while still respecting
@@ -329,7 +339,7 @@ class MarketAdapterService {
329
339
  }
330
340
  getTrustedNoTradeGapThresholdCandles(cfg) {
331
341
  return Number.isFinite(cfg?.maxNativeGapFillCandles)
332
- ? cfg.maxNativeGapFillCandles
342
+ ? Number(Number(cfg.maxNativeGapFillCandles))
333
343
  : MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
334
344
  }
335
345
  fillNativeIncrementalClosedGaps(candles, previousLastTs, intervalSeconds, nowMs = this.getNowMs()) {
@@ -380,12 +390,12 @@ class MarketAdapterService {
380
390
  const deps = this.deps;
381
391
  const bucketMs = Number(intervalSeconds) * 1000;
382
392
  if (!Array.isArray(candles) || candles.length === 0 || !Array.isArray(missingTimestamps) || missingTimestamps.length === 0) {
383
- return { candles, filledTimestamps: [] };
393
+ return { candles: candles, filledTimestamps: [] };
384
394
  }
385
395
  if (!Number.isFinite(bucketMs) || bucketMs <= 0)
386
- return { candles, filledTimestamps: [] };
396
+ return { candles: candles, filledTimestamps: [] };
387
397
  if (!Number.isFinite(maxGapCandles) || maxGapCandles <= 0)
388
- return { candles, filledTimestamps: [] };
398
+ return { candles: candles, filledTimestamps: [] };
389
399
  const sortedCandles = candles
390
400
  .filter((c) => Array.isArray(c) && Number.isFinite(c[0]))
391
401
  .slice()
@@ -490,7 +500,7 @@ class MarketAdapterService {
490
500
  const base = Number(centerPrice);
491
501
  const ref = Number(referencePrice);
492
502
  if (!Number.isFinite(base) || base <= 0)
493
- return centerPrice;
503
+ return base;
494
504
  try {
495
505
  const startPrice = Number.isFinite(ref) && ref > 0 ? ref : base;
496
506
  const minP = resolveConfiguredPriceBound(bot?.minPrice, DEFAULT_CONFIG.minPrice, startPrice, 'min') ?? 0;
@@ -661,10 +671,70 @@ class MarketAdapterService {
661
671
  shouldTrigger: thresholdCrossed,
662
672
  };
663
673
  }
674
+ /**
675
+ * Number of consecutive confirming bars the slope-delta trigger requires.
676
+ * Resolves per-bot/market override, else the global enable + value, else 1
677
+ * (legacy fire-on-first-crossing).
678
+ */
679
+ resolveAmaSlopePersistBars(cfg) {
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;
699
+ if (!enabled)
700
+ return 1;
701
+ const bars = Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS);
702
+ return Number.isFinite(bars) && bars >= 1 ? Math.round(bars) : 1;
703
+ }
704
+ /**
705
+ * Advance the slope-delta persistence counter on one actionable cycle and
706
+ * report whether the gate is satisfied. Mutates botState counters (persisted
707
+ * across restarts). Caller clears them on any successful reset.
708
+ */
709
+ advanceAmaSlopePersistence(details, cfg, botState) {
710
+ const persistBars = this.resolveAmaSlopePersistBars(cfg);
711
+ const crossed = !!details?.thresholdCrossed;
712
+ if (persistBars <= 1) {
713
+ botState.amaSlopePersistCount = 0;
714
+ botState.amaSlopePersistDir = 0;
715
+ return { shouldTrigger: crossed, persistBars };
716
+ }
717
+ if (!crossed) {
718
+ botState.amaSlopePersistCount = 0;
719
+ botState.amaSlopePersistDir = 0;
720
+ return { shouldTrigger: false, persistBars };
721
+ }
722
+ const current = Number(details?.currentSlopePct);
723
+ const previous = Number(details?.previousSlopePct);
724
+ const dir = Number.isFinite(current) && Number.isFinite(previous) ? Math.sign(current - previous) : 0;
725
+ const storedDirRaw = Number(botState.amaSlopePersistDir);
726
+ const storedDir = storedDirRaw === 1 ? 1 : (storedDirRaw === -1 ? -1 : 0);
727
+ const storedCountRaw = Number(botState.amaSlopePersistCount);
728
+ const storedCount = Number.isFinite(storedCountRaw) && storedCountRaw > 0 ? Math.floor(storedCountRaw) : 0;
729
+ const count = (dir !== 0 && dir === storedDir) ? storedCount + 1 : 1;
730
+ botState.amaSlopePersistDir = dir;
731
+ botState.amaSlopePersistCount = count;
732
+ return { shouldTrigger: count >= persistBars, persistBars };
733
+ }
664
734
  normalizePersistedBotState(botState, lookbackBars) {
665
735
  if (!botState || typeof botState !== 'object')
666
736
  return {};
667
- return normalizePersistedAmaSlopeDiagnostics(botState, lookbackBars);
737
+ return (normalizePersistedAmaSlopeDiagnostics(botState, lookbackBars) ?? {});
668
738
  }
669
739
  extractPersistedDynamicGridState(snapshot, lookbackBars) {
670
740
  if (!snapshot || typeof snapshot !== 'object')
@@ -767,7 +837,7 @@ class MarketAdapterService {
767
837
  // The gate still recomputes from scratch whenever the cached
768
838
  // closes are not a prefix of the incoming window (gap repair,
769
839
  // rewritten bar, shortened window) or a parameter changed.
770
- cacheKey: `${bot?.botKey ?? 'bot'}:${cfg.intervalSeconds}`,
840
+ cacheKey: `${bot?.botKey ?? 'bot'}:${Number(cfg.intervalSeconds)}`,
771
841
  });
772
842
  regimeMultiplier = regimeResult.isReady && Math.abs(regimeResult.multiplier - 1.0) >= absoluteThreshold
773
843
  ? regimeResult.multiplier
@@ -906,8 +976,8 @@ class MarketAdapterService {
906
976
  kalmanSmoothSpanPct,
907
977
  signalConfirmBars,
908
978
  };
909
- const staticSell = bot.weightDistribution.sell;
910
- const staticBuy = bot.weightDistribution.buy;
979
+ const staticSell = bot.weightDistribution?.sell ?? 0;
980
+ const staticBuy = bot.weightDistribution?.buy ?? 0;
911
981
  const MIN_W = MARKET_ADAPTER.DYNAMIC_WEIGHT_MIN_WEIGHT;
912
982
  const MAX_W = MARKET_ADAPTER.DYNAMIC_WEIGHT_MAX_WEIGHT;
913
983
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
@@ -1057,7 +1127,7 @@ class MarketAdapterService {
1057
1127
  const thresholdPercent = typeof deps.calculateBotThreshold === 'function'
1058
1128
  ? deps.calculateBotThreshold(cfg)
1059
1129
  : null;
1060
- state.bots[bot.botKey] = this.buildDefaultBotState(bot, {
1130
+ state.bots[String(bot.botKey)] = this.buildDefaultBotState(bot, {
1061
1131
  startPrice: bot.startPrice,
1062
1132
  priceMode: 'fixed',
1063
1133
  lastCycleSource: 'fixed-start-price',
@@ -1072,13 +1142,13 @@ class MarketAdapterService {
1072
1142
  });
1073
1143
  }
1074
1144
  const contextSignature = this.buildBotContextSignature(bot);
1075
- const cached = contextCache.get(bot.botKey);
1076
- 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);
1077
1147
  const cachedSignature = cached && typeof cached === 'object' && cached.signature ? cached.signature : null;
1078
- let ctx = cachedCtx;
1079
- if (!ctx || cachedSignature !== contextSignature) {
1080
- ctx = await deps.resolveBotContext(bot);
1081
- 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), {
1082
1152
  signature: contextSignature,
1083
1153
  ctx,
1084
1154
  });
@@ -1093,7 +1163,7 @@ class MarketAdapterService {
1093
1163
  return { ok: false, reason: 'ama disabled' };
1094
1164
  }
1095
1165
  const lookbackBars = normalizeAmaSlopeLookbackBars(cfg.amaSlope?.lookbackBars);
1096
- const filePath = deps.candleFileForBot(bot.botKey, cfg.intervalSeconds);
1166
+ const filePath = deps.candleFileForBot(bot.botKey, Number(cfg.intervalSeconds));
1097
1167
  // mtime-validated read cache: the previous cycle serialized this very
1098
1168
  // file, so re-parsing ~250 KiB of JSON per bot per hour is pure waste.
1099
1169
  // The cache decides on the file's stat alone — an unstattable file (or a
@@ -1109,7 +1179,7 @@ class MarketAdapterService {
1109
1179
  // Retention targets, derived from the bot's own AMA parameters. Pure and
1110
1180
  // local, so they are computed before the off-hour gate below (which
1111
1181
  // needs the warmup target) and reused by the full path unchanged.
1112
- const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod, botAma.erSmoothPeriod ?? 0);
1182
+ const amaWarmupBars = getAmaWarmupBars(Number(botAma.erPeriod), Number(botAma.slowPeriod), lookbackBars, Number(botAma.fastPeriod));
1113
1183
  const analysisKeepCount = amaWarmupBars + 1;
1114
1184
  // Retain one extra raw candle so the closed-candle analysis window still keeps a
1115
1185
  // full warmup/history set when the newest bucket is the current in-progress bar.
@@ -1132,9 +1202,9 @@ class MarketAdapterService {
1132
1202
  // change — must still run. Only a bot that has demonstrably consumed
1133
1203
  // that bucket and holds the data for it is skipped.
1134
1204
  const persistedBotState = (state?.bots && typeof state.bots === 'object')
1135
- ? state.bots[bot.botKey]
1205
+ ? state.bots[String(bot.botKey)]
1136
1206
  : null;
1137
- const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, cfg.intervalSeconds, undefined, cfg);
1207
+ const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, Number(cfg.intervalSeconds), undefined, cfg);
1138
1208
  const offHourSkipCovered = !!offHourSkip && this.candleFileCoversClosedBucket(existingCandles, existingMeta, marketSource, offHourSkip.latestClosedBucketStartMs, rawKeepCount);
1139
1209
  if (offHourSkip && offHourSkipCovered) {
1140
1210
  const skipNowIso = new Date().toISOString();
@@ -1150,7 +1220,7 @@ class MarketAdapterService {
1150
1220
  pendingClosedCandle: true,
1151
1221
  lastTriggerSuppressedReason: 'waiting_for_new_closed_candle',
1152
1222
  };
1153
- state.bots[bot.botKey] = skippedState;
1223
+ state.bots[String(bot.botKey)] = skippedState;
1154
1224
  return this.buildDefaultResult(bot, {
1155
1225
  dryRunMessages,
1156
1226
  source: 'off-hour-skip',
@@ -1162,8 +1232,8 @@ class MarketAdapterService {
1162
1232
  pendingClosedCandle: true,
1163
1233
  });
1164
1234
  }
1165
- const kibanaRequestTimeoutMs = Number.isFinite(cfg.kibanaRequestTimeoutMs) && cfg.kibanaRequestTimeoutMs > 0
1166
- ? cfg.kibanaRequestTimeoutMs
1235
+ const kibanaRequestTimeoutMs = Number.isFinite(Number(cfg.kibanaRequestTimeoutMs)) && Number(cfg.kibanaRequestTimeoutMs) > 0
1236
+ ? Number(cfg.kibanaRequestTimeoutMs)
1167
1237
  : MARKET_ADAPTER.KIBANA_REQUEST_TIMEOUT_MS;
1168
1238
  const fetchKibanaCandles = async (options = {}) => {
1169
1239
  const kibanaOptions = {
@@ -1212,7 +1282,8 @@ class MarketAdapterService {
1212
1282
  const tailEndTs = detected.sorted[detected.sorted.length - 1][0];
1213
1283
  // Skip Kibana verification if this tail range was already confirmed flat
1214
1284
  // on a previous cycle (the current tail is contained within a verified range).
1215
- const { startTs: vStart, endTs: vEnd } = verifiedRange;
1285
+ const vStart = Number(verifiedRange.startTs);
1286
+ const vEnd = Number(verifiedRange.endTs);
1216
1287
  if (Number.isFinite(vStart) && Number.isFinite(vEnd)
1217
1288
  && tailStartTs >= vStart && tailEndTs <= vEnd) {
1218
1289
  return { candles, keptStaleTailStartTs: tailStartTs, keptStaleTailEndTs: tailEndTs };
@@ -1220,7 +1291,7 @@ class MarketAdapterService {
1220
1291
  // Verify with Kibana: did the market actually trade during this period?
1221
1292
  try {
1222
1293
  const kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
1223
- intervalSeconds: cfg.intervalSeconds,
1294
+ intervalSeconds: Number(cfg.intervalSeconds),
1224
1295
  fillGapsToRequestedRange: false,
1225
1296
  apiKey: null,
1226
1297
  timeRange: {
@@ -1313,7 +1384,7 @@ class MarketAdapterService {
1313
1384
  ? deps.kibanaMarketSource && typeof deps.kibanaMarketSource.getMarketCandles === 'function'
1314
1385
  : deps.kibanaSource && typeof deps.kibanaSource.getLpCandlesForPool === 'function';
1315
1386
  const verifyAndFillLongSilence = async (candles, lastTs, latestClosedBucketTs, sourceLabel, incomingCandles = []) => {
1316
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1387
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1317
1388
  const silenceStartTs = Number(lastTs) + bucketMs;
1318
1389
  const earliestIncomingTs = (Array.isArray(incomingCandles) ? incomingCandles : [])
1319
1390
  .filter((c) => Array.isArray(c) && Number.isFinite(c[0]) && c[0] > lastTs)
@@ -1329,7 +1400,7 @@ class MarketAdapterService {
1329
1400
  }
1330
1401
  try {
1331
1402
  const kibanaSilenceCandles = await deps.withRetries(() => fetchKibanaCandles({
1332
- intervalSeconds: cfg.intervalSeconds,
1403
+ intervalSeconds: Number(cfg.intervalSeconds),
1333
1404
  fillGapsToRequestedRange: false,
1334
1405
  apiKey: null,
1335
1406
  timeRange: {
@@ -1350,7 +1421,7 @@ class MarketAdapterService {
1350
1421
  .filter((c) => Array.isArray(c) && c[0] === lastTs)
1351
1422
  .slice(-1)[0];
1352
1423
  const filledSilence = previousCandle
1353
- ? deps.fillCandleGaps([previousCandle, ...(Array.isArray(incomingCandles) ? incomingCandles : [])], cfg.intervalSeconds, lastTs, silenceEndTs)
1424
+ ? deps.fillCandleGaps([previousCandle, ...(Array.isArray(incomingCandles) ? incomingCandles : [])], Number(cfg.intervalSeconds), lastTs, silenceEndTs)
1354
1425
  .filter((c) => Array.isArray(c) && c[0] > lastTs)
1355
1426
  : [];
1356
1427
  if (filledSilence.length === 0)
@@ -1379,26 +1450,26 @@ class MarketAdapterService {
1379
1450
  }
1380
1451
  };
1381
1452
  const fillBoundedTrailingClosedGap = (candles, latestClosedBucketTs, nowMs, maxNativeGapFill) => {
1382
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1453
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1383
1454
  const latestKnownTs = Array.isArray(candles) && candles.length > 0
1384
1455
  ? candles[candles.length - 1]?.[0]
1385
1456
  : null;
1386
1457
  const trailingGapBuckets = Number.isFinite(bucketMs) && bucketMs > 0
1387
- && Number.isFinite(latestClosedBucketTs) && Number.isFinite(latestKnownTs)
1458
+ && Number.isFinite(latestClosedBucketTs) && latestKnownTs != null && Number.isFinite(latestKnownTs)
1388
1459
  && latestClosedBucketTs > latestKnownTs
1389
1460
  ? Math.round((latestClosedBucketTs - latestKnownTs) / bucketMs)
1390
1461
  : 0;
1391
1462
  if (trailingGapBuckets <= 0 || trailingGapBuckets > maxNativeGapFill) {
1392
1463
  return candles;
1393
1464
  }
1394
- return this.fillNativeIncrementalClosedGaps(candles, latestKnownTs, cfg.intervalSeconds, nowMs);
1465
+ return this.fillNativeIncrementalClosedGaps(candles, latestKnownTs, Number(cfg.intervalSeconds), nowMs);
1395
1466
  };
1396
1467
  if (isBookSource) {
1397
1468
  nativeRecentTradeSequences = [];
1398
1469
  nativeLastTradeTs = null;
1399
1470
  nativeOverlapCount = null;
1400
1471
  nativePagesFetched = null;
1401
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1472
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1402
1473
  const nowMs = this.getNowMs();
1403
1474
  if (needBootstrap) {
1404
1475
  // Bootstrap: Kibana first (deep history), native as fallback
@@ -1406,7 +1477,7 @@ class MarketAdapterService {
1406
1477
  let kibanaCandles = null;
1407
1478
  try {
1408
1479
  kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
1409
- intervalSeconds: cfg.intervalSeconds,
1480
+ intervalSeconds: Number(cfg.intervalSeconds),
1410
1481
  lookbackHours: kibanaLookbackHours,
1411
1482
  fillGapsToRequestedRange: false,
1412
1483
  apiKey: null,
@@ -1422,12 +1493,12 @@ class MarketAdapterService {
1422
1493
  }
1423
1494
  else {
1424
1495
  // Fall back to native
1425
- 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);
1426
1497
  const nativeStartMs = Math.max(0, nowMs - (nativeLookbackHours * 3600 * 1000));
1427
1498
  let nativeCandles = [];
1428
1499
  try {
1429
1500
  if (typeof deps.fetchNativeMarketHistorySince === 'function') {
1430
- 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');
1431
1502
  }
1432
1503
  }
1433
1504
  catch (_) {
@@ -1450,7 +1521,7 @@ class MarketAdapterService {
1450
1521
  let nativeCandles = [];
1451
1522
  try {
1452
1523
  if (typeof deps.fetchNativeMarketHistorySince === 'function') {
1453
- 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');
1454
1525
  }
1455
1526
  }
1456
1527
  catch (_) {
@@ -1467,14 +1538,14 @@ class MarketAdapterService {
1467
1538
  const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
1468
1539
  const latestClosedBucketTs = currentBucketStartMs - bucketMs;
1469
1540
  const earliestIncomingTs = nativeCandles.length > 0 ? nativeCandles[0][0] : null;
1470
- const gapEndTs = Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
1541
+ const gapEndTs = earliestIncomingTs != null && Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
1471
1542
  ? earliestIncomingTs
1472
1543
  : latestClosedBucketTs + bucketMs;
1473
1544
  const gapBuckets = gapEndTs !== null && gapEndTs > lastTs
1474
1545
  ? Math.round((gapEndTs - lastTs) / bucketMs) - 1
1475
1546
  : 0;
1476
- const maxNativeGapFill = Number.isFinite(cfg.maxNativeGapFillCandles)
1477
- ? cfg.maxNativeGapFillCandles
1547
+ const maxNativeGapFill = Number.isFinite(Number(cfg.maxNativeGapFillCandles))
1548
+ ? Number(cfg.maxNativeGapFillCandles)
1478
1549
  : MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
1479
1550
  if (gapBuckets > maxNativeGapFill) {
1480
1551
  const verifiedSilence = await verifyAndFillLongSilence(nextCandles, lastTs, latestClosedBucketTs, sourceLabel, nativeCandles);
@@ -1501,7 +1572,7 @@ class MarketAdapterService {
1501
1572
  let kibanaCandles = null;
1502
1573
  try {
1503
1574
  kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
1504
- intervalSeconds: cfg.intervalSeconds,
1575
+ intervalSeconds: Number(cfg.intervalSeconds),
1505
1576
  lookbackHours,
1506
1577
  fillGapsToRequestedRange: false,
1507
1578
  apiKey: null,
@@ -1530,11 +1601,11 @@ class MarketAdapterService {
1530
1601
  if (Number.isFinite(latestTradeTs))
1531
1602
  nativeLastTradeTs = latestTradeTs;
1532
1603
  }
1533
- nativeCandles = deps.tradesToCandles(trades, ctx.assetA, ctx.assetB, cfg.intervalSeconds);
1604
+ nativeCandles = deps.tradesToCandles(trades, ctx.assetA, ctx.assetB, Number(cfg.intervalSeconds));
1534
1605
  if (nativeCandles.length > 0 && typeof deps.fillCandleGaps === 'function') {
1535
1606
  const eTs = nativeCandles[0][0];
1536
1607
  const lTs = nativeCandles[nativeCandles.length - 1][0];
1537
- nativeCandles = deps.fillCandleGaps(nativeCandles, cfg.intervalSeconds, eTs, lTs);
1608
+ nativeCandles = deps.fillCandleGaps(nativeCandles, Number(cfg.intervalSeconds), eTs, lTs);
1538
1609
  }
1539
1610
  }
1540
1611
  catch (_) {
@@ -1550,7 +1621,7 @@ class MarketAdapterService {
1550
1621
  if (stitched.length > 1 && typeof deps.fillCandleGaps === 'function') {
1551
1622
  const sTs = stitched[0][0];
1552
1623
  const eTs = stitched[stitched.length - 1][0];
1553
- nextCandles = deps.fillCandleGaps(stitched, cfg.intervalSeconds, sTs, eTs);
1624
+ nextCandles = deps.fillCandleGaps(stitched, Number(cfg.intervalSeconds), sTs, eTs);
1554
1625
  }
1555
1626
  else {
1556
1627
  nextCandles = stitched;
@@ -1608,13 +1679,13 @@ class MarketAdapterService {
1608
1679
  }
1609
1680
  }
1610
1681
  if (!overlapUsed) {
1611
- const sinceMs = lastTs - (cfg.nativeBackfillHours * 3600 * 1000);
1682
+ const sinceMs = lastTs - (Number(cfg.nativeBackfillHours) * 3600 * 1000);
1612
1683
  const fetchResult = await deps.withRetries(() => deps.fetchNativeTradesSince(ctx.poolId, sinceMs, cfg.pageLimit, cfg.maxPages), cfg.sourceRetries, cfg.retryDelayMs, 'native incremental fetch failed');
1613
1684
  fetchedTrades = Array.isArray(fetchResult?.trades) ? fetchResult.trades : [];
1614
1685
  if (fetchResult?.truncated && typeof deps.logger?.warn === 'function') {
1615
1686
  deps.logger.warn(`[market_adapter] ${bot.botKey}: native incremental history truncated (exhausted ${cfg.maxPages} pages)`);
1616
1687
  }
1617
- newTrades = this.filterTimeBasedNativeNewTrades(fetchedTrades, knownSequences, nativeLastTradeTs, lastTs, cfg.intervalSeconds);
1688
+ newTrades = this.filterTimeBasedNativeNewTrades(fetchedTrades, knownSequences, nativeLastTradeTs, lastTs, Number(cfg.intervalSeconds));
1618
1689
  sourceLabel = 'native-incremental-time';
1619
1690
  nativeOverlapCount = null;
1620
1691
  nativePagesFetched = fetchResult?.pages || null;
@@ -1625,26 +1696,26 @@ class MarketAdapterService {
1625
1696
  if (Number.isFinite(latestTradeTs))
1626
1697
  nativeLastTradeTs = latestTradeTs;
1627
1698
  }
1628
- const incomingCandles = deps.tradesToCandles(newTrades, ctx.assetA, ctx.assetB, cfg.intervalSeconds);
1699
+ const incomingCandles = deps.tradesToCandles(newTrades, ctx.assetA, ctx.assetB, Number(cfg.intervalSeconds));
1629
1700
  nextCandles = deps.mergeCandles(existingCandles, incomingCandles, {
1630
1701
  onCollision: (existingCandle, incomingCandle) => this.buildIncrementalCandleCollision(existingCandle, incomingCandle),
1631
1702
  });
1632
1703
  // Fill bounded no-trade gaps from native incremental fetch. Ordinary LP
1633
1704
  // inactivity should remain a continuous flat 1h series; very large gaps stay
1634
1705
  // visible for Kibana repair/stale-tail handling instead of carrying stale prices.
1635
- const bucketMs = Number(cfg.intervalSeconds) * 1000;
1706
+ const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
1636
1707
  const nowMs = this.getNowMs();
1637
1708
  const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
1638
1709
  const latestClosedBucketTs = currentBucketStartMs - bucketMs;
1639
- const earliestIncomingTs = incomingCandles.length > 0 ? incomingCandles[0][0] : null;
1640
- 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)
1641
1712
  ? earliestIncomingTs
1642
1713
  : latestClosedBucketTs + bucketMs;
1643
1714
  const gapBuckets = Number.isFinite(gapEndTs) && gapEndTs > lastTs
1644
1715
  ? Math.round((gapEndTs - lastTs) / bucketMs) - 1
1645
1716
  : 0;
1646
1717
  if (gapBuckets <= trustedNoTradeGapThresholdCandles) {
1647
- nextCandles = this.fillNativeIncrementalClosedGaps(nextCandles, lastTs, cfg.intervalSeconds);
1718
+ nextCandles = this.fillNativeIncrementalClosedGaps(nextCandles, lastTs, Number(cfg.intervalSeconds));
1648
1719
  }
1649
1720
  else {
1650
1721
  const verifiedSilence = await verifyAndFillLongSilence(nextCandles, lastTs, latestClosedBucketTs, sourceLabel, incomingCandles);
@@ -1675,34 +1746,34 @@ class MarketAdapterService {
1675
1746
  let kibanaGapRepairTimestamps = [];
1676
1747
  let kibanaGapRepairAttempted = false;
1677
1748
  let gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1678
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1749
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1679
1750
  : { gapCount: 0, missingTimestamps: [] };
1680
1751
  // Step 1: Fill gaps within the trusted no-trade threshold directly (no Kibana needed).
1681
1752
  // The native incremental fetch already confirmed no trades for these timestamps.
1682
1753
  if (gapAnalysis.gapCount > 0) {
1683
- const filledNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, gapAnalysis.missingTimestamps, cfg.intervalSeconds, trustedNoTradeGapThresholdCandles);
1754
+ const filledNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, gapAnalysis.missingTimestamps, Number(Number(cfg.intervalSeconds)), trustedNoTradeGapThresholdCandles);
1684
1755
  if (filledNoTrade.filledTimestamps.length > 0) {
1685
1756
  nextCandles = filledNoTrade.candles;
1686
1757
  kibanaGapRepairTimestamps = filledNoTrade.filledTimestamps.slice();
1687
1758
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: synthesized ${filledNoTrade.filledTimestamps.length} no-trade candle(s) within trusted threshold `
1688
- + `[${filledNoTrade.filledTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
1759
+ + `[${filledNoTrade.filledTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
1689
1760
  }
1690
1761
  // Re-detect gaps — only beyond-threshold gaps remain
1691
1762
  gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1692
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1763
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1693
1764
  : { gapCount: 0, missingTimestamps: [] };
1694
1765
  }
1695
1766
  // Step 2: Only query Kibana for gaps beyond the trusted threshold
1696
1767
  if (gapAnalysis.gapCount > 0 && hasKibanaSource) {
1697
- const timeRange = this.buildGapRepairTimeRange(gapAnalysis.missingTimestamps, cfg.intervalSeconds, this.getGapRepairMaxHours(cfg));
1768
+ const timeRange = this.buildGapRepairTimeRange(gapAnalysis.missingTimestamps, Number(cfg.intervalSeconds), this.getGapRepairMaxHours(cfg));
1698
1769
  if (timeRange) {
1699
1770
  kibanaGapRepairAttempted = true;
1700
1771
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: ${gapAnalysis.gapCount} candle gap(s) beyond trusted threshold; `
1701
1772
  + `requesting Kibana repair for ${timeRange.gte} -> ${timeRange.lte} `
1702
- + `missing=[${gapAnalysis.missingTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
1773
+ + `missing=[${gapAnalysis.missingTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
1703
1774
  try {
1704
1775
  const kibanaGapCandles = await deps.withRetries(() => fetchKibanaCandles({
1705
- intervalSeconds: cfg.intervalSeconds,
1776
+ intervalSeconds: Number(cfg.intervalSeconds),
1706
1777
  fillGapsToRequestedRange: false,
1707
1778
  apiKey: null,
1708
1779
  timeRange,
@@ -1718,19 +1789,19 @@ class MarketAdapterService {
1718
1789
  kibanaGapRepairTimestamps = [...kibanaGapRepairTimestamps, ...kibanaPatchedTs];
1719
1790
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: Kibana gap repair patched ${kibanaPatchedTs.length}/${gapAnalysis.gapCount} gap(s)`
1720
1791
  + (kibanaPatchedTs.length > 0
1721
- ? ` [${kibanaPatchedTs.map((ts) => new Date(ts).toISOString()).join(', ')}]`
1792
+ ? ` [${kibanaPatchedTs.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`
1722
1793
  : ''));
1723
1794
  }
1724
1795
  else {
1725
1796
  // Kibana returned no data — that IS verification: no trades happened.
1726
1797
  // Synthesize no-trade candles for all gaps within the queried window.
1727
1798
  const verifiedGapTimestamps = this.getMissingTimestampsWithinTimeRange(gapAnalysis.missingTimestamps, timeRange);
1728
- const verifiedNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, verifiedGapTimestamps, cfg.intervalSeconds, verifiedGapTimestamps.length);
1799
+ const verifiedNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, verifiedGapTimestamps, Number(cfg.intervalSeconds), verifiedGapTimestamps.length);
1729
1800
  if (verifiedNoTrade.filledTimestamps.length > 0) {
1730
1801
  nextCandles = verifiedNoTrade.candles;
1731
1802
  kibanaGapRepairTimestamps = [...kibanaGapRepairTimestamps, ...verifiedNoTrade.filledTimestamps];
1732
1803
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: synthesized ${verifiedNoTrade.filledTimestamps.length} no-trade candle(s) after empty Kibana repair `
1733
- + `[${verifiedNoTrade.filledTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
1804
+ + `[${verifiedNoTrade.filledTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
1734
1805
  }
1735
1806
  else {
1736
1807
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: Kibana empty but could not synthesize gaps (missing neighbors)`, 'warn');
@@ -1742,11 +1813,11 @@ class MarketAdapterService {
1742
1813
  }
1743
1814
  }
1744
1815
  gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1745
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1816
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1746
1817
  : { gapCount: 0, missingTimestamps: [] };
1747
1818
  if (gapAnalysis.gapCount > 0) {
1748
1819
  logGapRepairEvent(`[market_adapter] ${bot.botKey}: ${gapAnalysis.gapCount} candle gap(s) still unresolved after Kibana repair `
1749
- + `[${gapAnalysis.missingTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`, 'warn');
1820
+ + `[${gapAnalysis.missingTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`, 'warn');
1750
1821
  }
1751
1822
  }
1752
1823
  // ── Historical backfill: if candle count is still insufficient for AMA warmup,
@@ -1757,13 +1828,13 @@ class MarketAdapterService {
1757
1828
  const needsHistoricalBackfill = !kibanaGapRepairAttempted || gapAnalysis.gapCount > 0;
1758
1829
  if (!kibanaBootstrapEmpty && needsHistoricalBackfill && candleShortfall > 0 && nextCandles.length > 0 && hasKibanaSource) {
1759
1830
  const oldestTs = nextCandles[0][0];
1760
- const shortfallMs = candleShortfall * cfg.intervalSeconds * 1000;
1831
+ const shortfallMs = candleShortfall * Number(cfg.intervalSeconds) * 1000;
1761
1832
  const bufferMs = 24 * 3600 * 1000; // 24h buffer
1762
1833
  const backfillStartMs = Math.max(0, oldestTs - shortfallMs - bufferMs);
1763
- const backfillEndMs = oldestTs + cfg.intervalSeconds * 1000;
1834
+ const backfillEndMs = oldestTs + Number(cfg.intervalSeconds) * 1000;
1764
1835
  try {
1765
1836
  const historicalCandles = await deps.withRetries(() => fetchKibanaCandles({
1766
- intervalSeconds: cfg.intervalSeconds,
1837
+ intervalSeconds: Number(cfg.intervalSeconds),
1767
1838
  fillGapsToRequestedRange: false,
1768
1839
  apiKey: null,
1769
1840
  timeRange: {
@@ -1786,7 +1857,7 @@ class MarketAdapterService {
1786
1857
  const retainedTimestamps = new Set(nextCandles.map((c) => c[0]));
1787
1858
  const kibanaGapRepairCount = kibanaGapRepairTimestamps.filter((ts) => retainedTimestamps.has(ts)).length;
1788
1859
  const retainedGapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
1789
- ? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
1860
+ ? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
1790
1861
  : { gapCount: 0, missingTimestamps: [] };
1791
1862
  return {
1792
1863
  nextCandles,
@@ -1826,16 +1897,16 @@ class MarketAdapterService {
1826
1897
  kibanaBackfillCount = loadResult.kibanaBackfillCount || 0;
1827
1898
  unresolvedGapCount = loadResult.unresolvedGapCount;
1828
1899
  nativeRecentTradeSequences = Array.isArray(loadResult.nativeRecentTradeSequences) ? loadResult.nativeRecentTradeSequences : [];
1829
- nativeLastTradeTs = Number.isFinite(loadResult.nativeLastTradeTs) ? loadResult.nativeLastTradeTs : null;
1830
- nativeOverlapCount = Number.isFinite(loadResult.nativeOverlapCount) ? loadResult.nativeOverlapCount : null;
1831
- 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;
1832
1903
  const nowMs = this.getNowMs();
1833
- ({ closedCandles, currentBucketStartMs } = this.selectClosedCandles(nextCandles, cfg.intervalSeconds, nowMs));
1904
+ ({ closedCandles, currentBucketStartMs } = this.selectClosedCandles(nextCandles, Number(cfg.intervalSeconds), nowMs));
1834
1905
  rawLastCandle = nextCandles[nextCandles.length - 1] || [0, 0, 0, 0, 0];
1835
1906
  rawLastCandleTs = rawLastCandle[0] || null;
1836
1907
  latestClosedCandle = closedCandles[closedCandles.length - 1] || null;
1837
1908
  lastClosedCandleTs = latestClosedCandle ? latestClosedCandle[0] : null;
1838
- botState = this.normalizePersistedBotState(state.bots[bot.botKey], lookbackBars);
1909
+ botState = this.normalizePersistedBotState(state.bots[String(bot.botKey)], lookbackBars);
1839
1910
  if (sourceMismatch) {
1840
1911
  botState = {};
1841
1912
  }
@@ -1897,7 +1968,7 @@ class MarketAdapterService {
1897
1968
  marketSource,
1898
1969
  assetA: ctx.assetA,
1899
1970
  assetB: ctx.assetB,
1900
- intervalSeconds: cfg.intervalSeconds,
1971
+ intervalSeconds: Number(cfg.intervalSeconds),
1901
1972
  candleCount: nextCandles.length,
1902
1973
  analysisCandleCount: closedCandles.length,
1903
1974
  rawKeepCount,
@@ -1931,7 +2002,7 @@ class MarketAdapterService {
1931
2002
  const triggerSuppressedReason = staleData
1932
2003
  ? 'stale_candle_data'
1933
2004
  : 'waiting_for_new_closed_candle';
1934
- state.bots[bot.botKey] = {
2005
+ state.bots[String(bot.botKey)] = {
1935
2006
  ...botState,
1936
2007
  botName: bot.name,
1937
2008
  botKey: bot.botKey,
@@ -1989,7 +2060,6 @@ class MarketAdapterService {
1989
2060
  erPeriod: botAma.erPeriod,
1990
2061
  fastPeriod: botAma.fastPeriod,
1991
2062
  slowPeriod: botAma.slowPeriod,
1992
- erSmoothPeriod: botAma.erSmoothPeriod ?? 0,
1993
2063
  },
1994
2064
  pendingClosedCandle,
1995
2065
  });
@@ -2054,10 +2124,10 @@ class MarketAdapterService {
2054
2124
  closes,
2055
2125
  amaValues,
2056
2126
  lookbackBars,
2057
- botAma,
2127
+ botAma: botAma,
2058
2128
  weightVariance,
2059
2129
  nowIso,
2060
- cfg,
2130
+ cfg: cfg,
2061
2131
  bot,
2062
2132
  atrPeriod,
2063
2133
  });
@@ -2066,7 +2136,7 @@ class MarketAdapterService {
2066
2136
  weights = dwResult.weights;
2067
2137
  dynamicWeightsPayload = dwResult.dynamicWeightsPayload;
2068
2138
  }
2069
- const amaSlopeResetDetails = this.buildAmaSlopeResetDetails(amaSlope, previousGridResetAmaSlope, cfg);
2139
+ const amaSlopeResetDetails = this.buildAmaSlopeResetDetails(amaSlope ?? {}, previousGridResetAmaSlope, cfg);
2070
2140
  const amaSlopeDeltaPercent = amaSlopeResetDetails.deltaPercent;
2071
2141
  const amaSlopeThresholdPercent = amaSlopeResetDetails.thresholdPercent;
2072
2142
  // 4. Advisory collateral-ratio hint only; execution is owned by the debt runtime.
@@ -2179,6 +2249,8 @@ class MarketAdapterService {
2179
2249
  : botState.amaSlopeDeltaPercent ?? null;
2180
2250
  botState.amaSlopeThresholdPercent = amaSlopeThresholdPercent;
2181
2251
  botState.amaSlopePercentMode = AMA_SLOPE_PERCENT_MODE_PER_BAR;
2252
+ botState.amaSlopePersistCount = 0;
2253
+ botState.amaSlopePersistDir = 0;
2182
2254
  botState.triggerCount = Number(botState.triggerCount || 0) + 1;
2183
2255
  if (canApplyDynamicWeights && dynamicWeightsPayload) {
2184
2256
  botState.effectiveWeights = dynamicWeightsPayload.effectiveWeights || null;
@@ -2296,7 +2368,19 @@ class MarketAdapterService {
2296
2368
  }
2297
2369
  }
2298
2370
  }
2299
- if (!triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted && amaSlopeResetDetails.shouldTrigger) {
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) {
2300
2384
  const amaSlopePersisted = persistDynamicGridSnapshot(centerPrice);
2301
2385
  if (!amaSlopePersisted) {
2302
2386
  triggerSuppressedReason = 'ama_slope_persist_failed';
@@ -2308,6 +2392,7 @@ class MarketAdapterService {
2308
2392
  reason: 'market_adapter_ama_slope_delta_threshold',
2309
2393
  thresholdPercent: amaSlopeThresholdPercent,
2310
2394
  deltaPercent: amaSlopeDeltaPercent,
2395
+ amaSlopePersistBars,
2311
2396
  previousAmaSlope,
2312
2397
  previousGridResetAmaSlope,
2313
2398
  amaSlope,
@@ -2392,7 +2477,7 @@ class MarketAdapterService {
2392
2477
  ? (botState.amaSlopeThresholdPercent ?? amaSlopeThresholdPercent ?? null)
2393
2478
  : (amaSlopeThresholdPercent ?? botState.amaSlopeThresholdPercent ?? null);
2394
2479
  const stateGridRangeScalingAmaSlope = botState.gridRangeScalingAmaSlope || previousGridResetAmaSlope || null;
2395
- state.bots[bot.botKey] = {
2480
+ state.bots[String(bot.botKey)] = {
2396
2481
  ...botState,
2397
2482
  botName: bot.name,
2398
2483
  botKey: bot.botKey,
@@ -2428,7 +2513,6 @@ class MarketAdapterService {
2428
2513
  erPeriod: botAma.erPeriod,
2429
2514
  fastPeriod: botAma.fastPeriod,
2430
2515
  slowPeriod: botAma.slowPeriod,
2431
- erSmoothPeriod: botAma.erSmoothPeriod ?? 0,
2432
2516
  },
2433
2517
  amaComparison,
2434
2518
  lastDeltaPercent: deltaPercent,
@@ -2468,7 +2552,7 @@ class MarketAdapterService {
2468
2552
  dryRunMessages,
2469
2553
  source: sourceLabel,
2470
2554
  marketSource,
2471
- intervalSeconds: cfg.intervalSeconds,
2555
+ intervalSeconds: Number(cfg.intervalSeconds),
2472
2556
  candleCount: nextCandles.length,
2473
2557
  analysisCandleCount: analysisCandles.length,
2474
2558
  rawKeepCount,
@@ -2495,7 +2579,7 @@ class MarketAdapterService {
2495
2579
  triggerSuppressedReason,
2496
2580
  weights: canExposeDynamicWeights ? weights : null,
2497
2581
  collateralRecommendation,
2498
- amaSlope: amaSlope || botState.amaSlope || null,
2582
+ amaSlope: (amaSlope || botState.amaSlope || null),
2499
2583
  amaSlopeDeltaPercent: Number.isFinite(amaSlopeDeltaPercent)
2500
2584
  ? amaSlopeDeltaPercent
2501
2585
  : botState.amaSlopeDeltaPercent ?? null,
@@ -2517,7 +2601,6 @@ class MarketAdapterService {
2517
2601
  erPeriod: botAma.erPeriod,
2518
2602
  fastPeriod: botAma.fastPeriod,
2519
2603
  slowPeriod: botAma.slowPeriod,
2520
- erSmoothPeriod: botAma.erSmoothPeriod ?? 0,
2521
2604
  },
2522
2605
  atr,
2523
2606
  weightVariance,