dexbot 1.6.7 → 1.6.9

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 (626) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/README.md +3 -3
  3. package/analysis/README.md +2 -3
  4. package/analysis/tradingview/README.md +78 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
  10. package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
  11. package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
  12. package/dist/analysis/tradingview/grid_reset_config.js +235 -0
  13. package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
  14. package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
  16. package/dist/dexbot.js +55 -16
  17. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  18. package/dist/market_adapter/core/market_adapter_service.js +239 -20
  19. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  20. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  21. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  22. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  23. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
  24. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
  25. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  26. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  27. package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
  28. package/dist/market_adapter/inputs/window_cache.js +302 -48
  29. package/dist/market_adapter/interval_utils.d.ts +18 -1
  30. package/dist/market_adapter/interval_utils.js +31 -1
  31. package/dist/market_adapter/market_adapter.d.ts +158 -2
  32. package/dist/market_adapter/market_adapter.js +399 -65
  33. package/dist/market_adapter/test_helpers.d.ts +2 -2
  34. package/dist/market_adapter/test_helpers.js +2 -2
  35. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  36. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  37. package/dist/modules/account_bots.js +10 -0
  38. package/dist/modules/account_orders.d.ts +24 -2
  39. package/dist/modules/account_orders.js +41 -4
  40. package/dist/modules/bot_settings.js +10 -1
  41. package/dist/modules/config.d.ts +7 -0
  42. package/dist/modules/config.js +2 -0
  43. package/dist/modules/constants.d.ts +16 -4
  44. package/dist/modules/constants.js +144 -38
  45. package/dist/modules/dexbot_class.d.ts +6 -76
  46. package/dist/modules/dexbot_class.js +0 -32
  47. package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
  48. package/dist/modules/dexbot_cow_runtime.js +4 -87
  49. package/dist/modules/dexbot_maintenance_runtime.d.ts +15 -1
  50. package/dist/modules/dexbot_maintenance_runtime.js +59 -11
  51. package/dist/modules/dexbot_startup_runtime.js +73 -20
  52. package/dist/modules/dexbot_state_recovery.d.ts +6 -0
  53. package/dist/modules/dexbot_state_recovery.js +21 -0
  54. package/dist/modules/order/async_lock.d.ts +8 -0
  55. package/dist/modules/order/async_lock.js +15 -0
  56. package/dist/modules/order/genesis_policy.d.ts +162 -0
  57. package/dist/modules/order/genesis_policy.js +267 -0
  58. package/dist/modules/order/grid.js +172 -160
  59. package/dist/modules/order/grid_reconcile.d.ts +9 -0
  60. package/dist/modules/order/grid_reconcile.js +13 -4
  61. package/dist/modules/order/grid_reconcile_internal.js +2 -2
  62. package/dist/modules/order/manager.d.ts +4 -0
  63. package/dist/modules/order/manager.js +14 -1
  64. package/dist/modules/order/sync_engine.d.ts +19 -0
  65. package/dist/modules/order/sync_engine.js +284 -344
  66. package/dist/modules/order/utils/math.d.ts +22 -1
  67. package/dist/modules/order/utils/math.js +64 -1
  68. package/dist/modules/order/utils/order.d.ts +43 -58
  69. package/dist/modules/order/utils/order.js +220 -197
  70. package/dist/modules/order/utils/system.js +8 -1
  71. package/dist/modules/paths.d.ts +1 -0
  72. package/dist/modules/paths.js +1 -0
  73. package/dist/modules/version_notice.d.ts +311 -0
  74. package/dist/modules/version_notice.js +709 -0
  75. package/dist/pm2.js +16 -0
  76. package/dist/unlock.js +28 -0
  77. package/docs/BITSHARES_ONBOARDING.md +8 -1
  78. package/docs/COW_INVARIANTS.md +3 -2
  79. package/docs/DEXBOT_COMPARISON.md +4 -4
  80. package/docs/EVOLUTION.md +22 -20
  81. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  82. package/docs/GRID_PRICE_INVARIANT.md +149 -31
  83. package/docs/GRID_RECALCULATION.md +18 -2
  84. package/docs/README.md +3 -1
  85. package/docs/WORKFLOW.md +16 -5
  86. package/market_adapter/README.md +29 -1
  87. package/modules/README.md +18 -1
  88. package/package.json +13 -5
  89. package/scripts/README.md +28 -2
  90. package/scripts/clear-all.sh +13 -4
  91. package/scripts/clear-logs.sh +13 -4
  92. package/scripts/clear-market-adapter.sh +6 -0
  93. package/scripts/clear-orders.sh +5 -0
  94. package/scripts/lib/dexbot-paths.sh +108 -0
  95. package/tests/README.md +11 -3
  96. package/analysis/account_resolver.ts +0 -161
  97. package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
  98. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
  99. package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
  100. package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
  101. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
  102. package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
  103. package/analysis/analyze_dynamic_weight.ts +0 -243
  104. package/analysis/analyze_kalman.ts +0 -157
  105. package/analysis/analyze_regime.ts +0 -158
  106. package/analysis/analyze_regime_windows.ts +0 -470
  107. package/analysis/analyze_risk_profile.ts +0 -199
  108. package/analysis/analyze_trade_heatmap.ts +0 -362
  109. package/analysis/analyze_volatility.ts +0 -182
  110. package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
  111. package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
  112. package/analysis/bot_fitting/shared_utils.ts +0 -52
  113. package/analysis/bot_key_utils.ts +0 -426
  114. package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
  115. package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
  116. package/analysis/chain_pool.ts +0 -47
  117. package/analysis/chart_css.ts +0 -62
  118. package/analysis/chart_ui.ts +0 -105
  119. package/analysis/chart_utils.ts +0 -210
  120. package/analysis/fills_source.ts +0 -228
  121. package/analysis/grid_correction_check.ts +0 -786
  122. package/analysis/math_utils.ts +0 -53
  123. package/analysis/price_sources.ts +0 -136
  124. package/analysis/resolve_bot_accounts.ts +0 -199
  125. package/analysis/resolve_source.ts +0 -99
  126. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
  127. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
  128. package/analysis/trade_profitability.ts +0 -1335
  129. package/analysis/tradingview/analyze_tradingview.ts +0 -280
  130. package/analysis/tradingview/h-bts_tradingview.html +0 -1570
  131. package/analysis/tradingview/t-bts_tradingview.html +0 -1570
  132. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
  133. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
  134. package/analysis/trend_detection/hurst_analyzer.ts +0 -7
  135. package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
  136. package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
  137. package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
  138. package/analysis/trend_detection/package.json +0 -23
  139. package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
  140. package/analysis/trend_detection/regime_chart_generator.ts +0 -338
  141. package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
  142. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
  143. package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
  144. package/analysis/tsconfig.json +0 -29
  145. package/claw/tests/package.json +0 -3
  146. package/claw/tests/test_claw_bridge.ts +0 -570
  147. package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
  148. package/claw/tests/test_claw_chain_layer.ts +0 -739
  149. package/claw/tests/test_claw_data_flow.ts +0 -525
  150. package/claw/tests/test_claw_domain_logic.ts +0 -471
  151. package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
  152. package/claw/tests/test_claw_mcp_transport.ts +0 -243
  153. package/claw/tests/test_claw_regressions.ts +0 -711
  154. package/claw/tests/test_claw_skill_generation.ts +0 -103
  155. package/claw/tests/test_claw_state_store.ts +0 -44
  156. package/claw/tests/test_dexbot_profiles.ts +0 -654
  157. package/claw/tests/test_memu_bridge.ts +0 -189
  158. package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
  159. package/claw/tests/test_position_health.ts +0 -343
  160. package/claw/tests/test_position_manager.ts +0 -429
  161. package/claw/tests/test_position_manager_watch_health.ts +0 -100
  162. package/claw/tests/test_short_mpa_strategy.ts +0 -232
  163. package/dist/analysis/account_resolver.d.ts.map +0 -1
  164. package/dist/analysis/account_resolver.js.map +0 -1
  165. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  166. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  167. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  168. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  169. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  170. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  171. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  172. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  173. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  174. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  175. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  176. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  177. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  178. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  179. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  180. package/dist/analysis/analyze_kalman.js.map +0 -1
  181. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  182. package/dist/analysis/analyze_regime.js.map +0 -1
  183. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  184. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  185. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  186. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  187. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  188. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  189. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  190. package/dist/analysis/analyze_volatility.js.map +0 -1
  191. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  192. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  193. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  194. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  195. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  196. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  197. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  198. package/dist/analysis/bot_key_utils.js.map +0 -1
  199. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  200. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  201. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  202. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  203. package/dist/analysis/chain_pool.d.ts.map +0 -1
  204. package/dist/analysis/chain_pool.js.map +0 -1
  205. package/dist/analysis/chart_css.d.ts.map +0 -1
  206. package/dist/analysis/chart_css.js.map +0 -1
  207. package/dist/analysis/chart_ui.d.ts.map +0 -1
  208. package/dist/analysis/chart_ui.js.map +0 -1
  209. package/dist/analysis/chart_utils.d.ts.map +0 -1
  210. package/dist/analysis/chart_utils.js.map +0 -1
  211. package/dist/analysis/fills_source.d.ts.map +0 -1
  212. package/dist/analysis/fills_source.js.map +0 -1
  213. package/dist/analysis/grid_correction_check.d.ts.map +0 -1
  214. package/dist/analysis/grid_correction_check.js.map +0 -1
  215. package/dist/analysis/math_utils.d.ts.map +0 -1
  216. package/dist/analysis/math_utils.js.map +0 -1
  217. package/dist/analysis/price_sources.d.ts.map +0 -1
  218. package/dist/analysis/price_sources.js.map +0 -1
  219. package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
  220. package/dist/analysis/resolve_bot_accounts.js.map +0 -1
  221. package/dist/analysis/resolve_source.d.ts.map +0 -1
  222. package/dist/analysis/resolve_source.js.map +0 -1
  223. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  224. package/dist/analysis/trade_profitability.js.map +0 -1
  225. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  226. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  227. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
  228. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
  229. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  230. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  231. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
  232. package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
  233. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  234. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  235. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
  236. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
  237. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
  238. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
  239. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
  240. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
  241. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  242. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  243. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  244. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  245. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
  246. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  247. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  248. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  249. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
  250. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  251. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  252. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
  253. package/dist/bot.d.ts.map +0 -1
  254. package/dist/bot.js.map +0 -1
  255. package/dist/credential-daemon.d.ts.map +0 -1
  256. package/dist/credential-daemon.js.map +0 -1
  257. package/dist/dexbot.d.ts.map +0 -1
  258. package/dist/dexbot.js.map +0 -1
  259. package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
  260. package/dist/market_adapter/ama_signal_runner.js.map +0 -1
  261. package/dist/market_adapter/candle_utils.d.ts.map +0 -1
  262. package/dist/market_adapter/candle_utils.js.map +0 -1
  263. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
  264. package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
  265. package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
  266. package/dist/market_adapter/core/config_normalizers.js.map +0 -1
  267. package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
  268. package/dist/market_adapter/core/kibana_candles.js.map +0 -1
  269. package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
  270. package/dist/market_adapter/core/kibana_client.js.map +0 -1
  271. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
  272. package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
  273. package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
  274. package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
  275. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
  276. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
  277. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
  278. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
  279. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
  280. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
  281. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
  282. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
  283. package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
  284. package/dist/market_adapter/core/strategies/ama.js.map +0 -1
  285. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
  286. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
  287. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
  288. package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
  289. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
  290. package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
  291. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
  292. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
  293. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
  294. package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
  295. package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
  296. package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
  297. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
  298. package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
  299. package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
  300. package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
  301. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
  302. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
  303. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
  304. package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
  305. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
  306. package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
  307. package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
  308. package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
  309. package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
  310. package/dist/market_adapter/inputs/window_cache.js.map +0 -1
  311. package/dist/market_adapter/interval_utils.d.ts.map +0 -1
  312. package/dist/market_adapter/interval_utils.js.map +0 -1
  313. package/dist/market_adapter/log_format.d.ts.map +0 -1
  314. package/dist/market_adapter/log_format.js.map +0 -1
  315. package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
  316. package/dist/market_adapter/lp_chart_core.js.map +0 -1
  317. package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
  318. package/dist/market_adapter/lp_chart_runner.js.map +0 -1
  319. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
  320. package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
  321. package/dist/market_adapter/market_adapter.d.ts.map +0 -1
  322. package/dist/market_adapter/market_adapter.js.map +0 -1
  323. package/dist/market_adapter/test_helpers.d.ts.map +0 -1
  324. package/dist/market_adapter/test_helpers.js.map +0 -1
  325. package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
  326. package/dist/market_adapter/utils/adapter_client.js.map +0 -1
  327. package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
  328. package/dist/market_adapter/utils/atomic_write.js.map +0 -1
  329. package/dist/market_adapter/utils/chain.d.ts.map +0 -1
  330. package/dist/market_adapter/utils/chain.js.map +0 -1
  331. package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
  332. package/dist/market_adapter/utils/data_discovery.js.map +0 -1
  333. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
  334. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
  335. package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
  336. package/dist/market_adapter/utils/file_lock.js.map +0 -1
  337. package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
  338. package/dist/market_adapter/utils/native_history.js.map +0 -1
  339. package/dist/modules/account_bots.d.ts.map +0 -1
  340. package/dist/modules/account_bots.js.map +0 -1
  341. package/dist/modules/account_orders.d.ts.map +0 -1
  342. package/dist/modules/account_orders.js.map +0 -1
  343. package/dist/modules/authority_resolver.d.ts.map +0 -1
  344. package/dist/modules/authority_resolver.js.map +0 -1
  345. package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
  346. package/dist/modules/bitshares-native/chain_client.js.map +0 -1
  347. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
  348. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
  349. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
  350. package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
  351. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
  352. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
  353. package/dist/modules/bitshares-native/index.d.ts.map +0 -1
  354. package/dist/modules/bitshares-native/index.js.map +0 -1
  355. package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
  356. package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
  357. package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
  358. package/dist/modules/bitshares-native/resolvers.js.map +0 -1
  359. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
  360. package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
  361. package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
  362. package/dist/modules/bitshares-native/serial/index.js.map +0 -1
  363. package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
  364. package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
  365. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
  366. package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
  367. package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
  368. package/dist/modules/bitshares-native/serial/types.js.map +0 -1
  369. package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
  370. package/dist/modules/bitshares-native/signing_client.js.map +0 -1
  371. package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
  372. package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
  373. package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
  374. package/dist/modules/bitshares-native/transport.js.map +0 -1
  375. package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
  376. package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
  377. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
  378. package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
  379. package/dist/modules/bitshares_client.d.ts.map +0 -1
  380. package/dist/modules/bitshares_client.js.map +0 -1
  381. package/dist/modules/bot_defaults.d.ts.map +0 -1
  382. package/dist/modules/bot_defaults.js.map +0 -1
  383. package/dist/modules/bot_settings.d.ts.map +0 -1
  384. package/dist/modules/bot_settings.js.map +0 -1
  385. package/dist/modules/bots_file_lock.d.ts.map +0 -1
  386. package/dist/modules/bots_file_lock.js.map +0 -1
  387. package/dist/modules/broadcast_failure.d.ts.map +0 -1
  388. package/dist/modules/broadcast_failure.js.map +0 -1
  389. package/dist/modules/chain_keys.d.ts.map +0 -1
  390. package/dist/modules/chain_keys.js.map +0 -1
  391. package/dist/modules/chain_orders.d.ts.map +0 -1
  392. package/dist/modules/chain_orders.js.map +0 -1
  393. package/dist/modules/cli_colors.d.ts.map +0 -1
  394. package/dist/modules/cli_colors.js.map +0 -1
  395. package/dist/modules/cli_start_onboarding.d.ts.map +0 -1
  396. package/dist/modules/cli_start_onboarding.js.map +0 -1
  397. package/dist/modules/cli_start_output.d.ts.map +0 -1
  398. package/dist/modules/cli_start_output.js.map +0 -1
  399. package/dist/modules/config.d.ts.map +0 -1
  400. package/dist/modules/config.js.map +0 -1
  401. package/dist/modules/constants.d.ts.map +0 -1
  402. package/dist/modules/constants.js.map +0 -1
  403. package/dist/modules/cr_planner.d.ts.map +0 -1
  404. package/dist/modules/cr_planner.js.map +0 -1
  405. package/dist/modules/credential_policy.d.ts.map +0 -1
  406. package/dist/modules/credential_policy.js.map +0 -1
  407. package/dist/modules/credential_runtime.d.ts.map +0 -1
  408. package/dist/modules/credential_runtime.js.map +0 -1
  409. package/dist/modules/credential_session_cache.d.ts.map +0 -1
  410. package/dist/modules/credential_session_cache.js.map +0 -1
  411. package/dist/modules/credit_pricing.d.ts.map +0 -1
  412. package/dist/modules/credit_pricing.js.map +0 -1
  413. package/dist/modules/credit_runtime.d.ts.map +0 -1
  414. package/dist/modules/credit_runtime.js.map +0 -1
  415. package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
  416. package/dist/modules/crypto/browser_provider.js.map +0 -1
  417. package/dist/modules/crypto/index.d.ts.map +0 -1
  418. package/dist/modules/crypto/index.js.map +0 -1
  419. package/dist/modules/crypto/node_provider.d.ts.map +0 -1
  420. package/dist/modules/crypto/node_provider.js.map +0 -1
  421. package/dist/modules/crypto/provider.d.ts.map +0 -1
  422. package/dist/modules/crypto/provider.js.map +0 -1
  423. package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
  424. package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
  425. package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
  426. package/dist/modules/crypto/pure_scrypt.js.map +0 -1
  427. package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
  428. package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
  429. package/dist/modules/crypto/sync.d.ts.map +0 -1
  430. package/dist/modules/crypto/sync.js.map +0 -1
  431. package/dist/modules/daemon_node_health.d.ts.map +0 -1
  432. package/dist/modules/daemon_node_health.js.map +0 -1
  433. package/dist/modules/dexbot_class.d.ts.map +0 -1
  434. package/dist/modules/dexbot_class.js.map +0 -1
  435. package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
  436. package/dist/modules/dexbot_cow_runtime.js.map +0 -1
  437. package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
  438. package/dist/modules/dexbot_credential_client.js.map +0 -1
  439. package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
  440. package/dist/modules/dexbot_fill_runtime.js.map +0 -1
  441. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
  442. package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
  443. package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
  444. package/dist/modules/dexbot_startup_runtime.js.map +0 -1
  445. package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
  446. package/dist/modules/dexbot_state_recovery.js.map +0 -1
  447. package/dist/modules/env.d.ts.map +0 -1
  448. package/dist/modules/env.js.map +0 -1
  449. package/dist/modules/fund_registry.d.ts.map +0 -1
  450. package/dist/modules/fund_registry.js.map +0 -1
  451. package/dist/modules/general_settings.d.ts.map +0 -1
  452. package/dist/modules/general_settings.js.map +0 -1
  453. package/dist/modules/graceful_shutdown.d.ts.map +0 -1
  454. package/dist/modules/graceful_shutdown.js.map +0 -1
  455. package/dist/modules/grid_price_source.d.ts.map +0 -1
  456. package/dist/modules/grid_price_source.js.map +0 -1
  457. package/dist/modules/key_store.d.ts.map +0 -1
  458. package/dist/modules/key_store.js.map +0 -1
  459. package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
  460. package/dist/modules/launcher/adapter_requirement.js.map +0 -1
  461. package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
  462. package/dist/modules/launcher/bot_supervisor.js.map +0 -1
  463. package/dist/modules/launcher/child_env.d.ts.map +0 -1
  464. package/dist/modules/launcher/child_env.js.map +0 -1
  465. package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
  466. package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
  467. package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
  468. package/dist/modules/launcher/credential_daemon.js.map +0 -1
  469. package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
  470. package/dist/modules/launcher/credential_secret.js.map +0 -1
  471. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
  472. package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
  473. package/dist/modules/launcher/headless_password.d.ts.map +0 -1
  474. package/dist/modules/launcher/headless_password.js.map +0 -1
  475. package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
  476. package/dist/modules/launcher/launch_modes.js.map +0 -1
  477. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
  478. package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
  479. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
  480. package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
  481. package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
  482. package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
  483. package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
  484. package/dist/modules/launcher/runtime_entry.js.map +0 -1
  485. package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
  486. package/dist/modules/launcher/status_reporting.js.map +0 -1
  487. package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
  488. package/dist/modules/launcher/supervisor_control.js.map +0 -1
  489. package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
  490. package/dist/modules/market_adapter_whitelist.js.map +0 -1
  491. package/dist/modules/node_connect_policy.d.ts.map +0 -1
  492. package/dist/modules/node_connect_policy.js.map +0 -1
  493. package/dist/modules/node_failure_ledger.d.ts.map +0 -1
  494. package/dist/modules/node_failure_ledger.js.map +0 -1
  495. package/dist/modules/node_health_cache.d.ts.map +0 -1
  496. package/dist/modules/node_health_cache.js.map +0 -1
  497. package/dist/modules/node_manager.d.ts.map +0 -1
  498. package/dist/modules/node_manager.js.map +0 -1
  499. package/dist/modules/order/accounting.d.ts.map +0 -1
  500. package/dist/modules/order/accounting.js.map +0 -1
  501. package/dist/modules/order/async_lock.d.ts.map +0 -1
  502. package/dist/modules/order/async_lock.js.map +0 -1
  503. package/dist/modules/order/export.d.ts.map +0 -1
  504. package/dist/modules/order/export.js.map +0 -1
  505. package/dist/modules/order/format.d.ts.map +0 -1
  506. package/dist/modules/order/format.js.map +0 -1
  507. package/dist/modules/order/grid.d.ts.map +0 -1
  508. package/dist/modules/order/grid.js.map +0 -1
  509. package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
  510. package/dist/modules/order/grid_reconcile.js.map +0 -1
  511. package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
  512. package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
  513. package/dist/modules/order/index.d.ts.map +0 -1
  514. package/dist/modules/order/index.js.map +0 -1
  515. package/dist/modules/order/logger.d.ts.map +0 -1
  516. package/dist/modules/order/logger.js.map +0 -1
  517. package/dist/modules/order/logger_state.d.ts.map +0 -1
  518. package/dist/modules/order/logger_state.js.map +0 -1
  519. package/dist/modules/order/manager.d.ts.map +0 -1
  520. package/dist/modules/order/manager.js.map +0 -1
  521. package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
  522. package/dist/modules/order/processed_fill_store.js.map +0 -1
  523. package/dist/modules/order/strategy.d.ts.map +0 -1
  524. package/dist/modules/order/strategy.js.map +0 -1
  525. package/dist/modules/order/sync_engine.d.ts.map +0 -1
  526. package/dist/modules/order/sync_engine.js.map +0 -1
  527. package/dist/modules/order/utils/math.d.ts.map +0 -1
  528. package/dist/modules/order/utils/math.js.map +0 -1
  529. package/dist/modules/order/utils/order.d.ts.map +0 -1
  530. package/dist/modules/order/utils/order.js.map +0 -1
  531. package/dist/modules/order/utils/slot.d.ts.map +0 -1
  532. package/dist/modules/order/utils/slot.js.map +0 -1
  533. package/dist/modules/order/utils/system.d.ts.map +0 -1
  534. package/dist/modules/order/utils/system.js.map +0 -1
  535. package/dist/modules/order/utils/timeout.d.ts.map +0 -1
  536. package/dist/modules/order/utils/timeout.js.map +0 -1
  537. package/dist/modules/order/utils/validate.d.ts.map +0 -1
  538. package/dist/modules/order/utils/validate.js.map +0 -1
  539. package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
  540. package/dist/modules/order/utils/withPoolRef.js.map +0 -1
  541. package/dist/modules/order/working_grid.d.ts.map +0 -1
  542. package/dist/modules/order/working_grid.js.map +0 -1
  543. package/dist/modules/path_api.d.ts.map +0 -1
  544. package/dist/modules/path_api.js.map +0 -1
  545. package/dist/modules/paths.d.ts.map +0 -1
  546. package/dist/modules/paths.js.map +0 -1
  547. package/dist/modules/process_discovery.d.ts.map +0 -1
  548. package/dist/modules/process_discovery.js.map +0 -1
  549. package/dist/modules/runtime.d.ts.map +0 -1
  550. package/dist/modules/runtime.js.map +0 -1
  551. package/dist/modules/runtime_settings.d.ts.map +0 -1
  552. package/dist/modules/runtime_settings.js.map +0 -1
  553. package/dist/modules/settings_merge.d.ts.map +0 -1
  554. package/dist/modules/settings_merge.js.map +0 -1
  555. package/dist/modules/socket_json_client.d.ts.map +0 -1
  556. package/dist/modules/socket_json_client.js.map +0 -1
  557. package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
  558. package/dist/modules/storage/browser_adapter.js.map +0 -1
  559. package/dist/modules/storage/index.d.ts.map +0 -1
  560. package/dist/modules/storage/index.js.map +0 -1
  561. package/dist/modules/storage/node_adapter.d.ts.map +0 -1
  562. package/dist/modules/storage/node_adapter.js.map +0 -1
  563. package/dist/modules/storage/types.d.ts.map +0 -1
  564. package/dist/modules/storage/types.js.map +0 -1
  565. package/dist/modules/types.d.ts.map +0 -1
  566. package/dist/modules/types.js.map +0 -1
  567. package/dist/modules/utils/base58check.d.ts.map +0 -1
  568. package/dist/modules/utils/base58check.js.map +0 -1
  569. package/dist/modules/utils/build_dir.d.ts.map +0 -1
  570. package/dist/modules/utils/build_dir.js.map +0 -1
  571. package/dist/modules/utils/chain_logs.d.ts.map +0 -1
  572. package/dist/modules/utils/chain_logs.js.map +0 -1
  573. package/dist/modules/utils/errors.d.ts.map +0 -1
  574. package/dist/modules/utils/errors.js.map +0 -1
  575. package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
  576. package/dist/modules/utils/sanitize_key.js.map +0 -1
  577. package/dist/modules/utils/text_width.d.ts.map +0 -1
  578. package/dist/modules/utils/text_width.js.map +0 -1
  579. package/dist/modules/validate_profiles.d.ts.map +0 -1
  580. package/dist/modules/validate_profiles.js.map +0 -1
  581. package/dist/pm2.d.ts.map +0 -1
  582. package/dist/pm2.js.map +0 -1
  583. package/dist/scripts/analyze-credit.d.ts.map +0 -1
  584. package/dist/scripts/analyze-credit.js.map +0 -1
  585. package/dist/scripts/analyze-git.d.ts.map +0 -1
  586. package/dist/scripts/analyze-git.js.map +0 -1
  587. package/dist/scripts/analyze-orders.d.ts.map +0 -1
  588. package/dist/scripts/analyze-orders.js.map +0 -1
  589. package/dist/scripts/chart_command.d.ts.map +0 -1
  590. package/dist/scripts/chart_command.js.map +0 -1
  591. package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
  592. package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
  593. package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
  594. package/dist/scripts/diagnose-pool-history.js.map +0 -1
  595. package/dist/scripts/divergence-calc.d.ts.map +0 -1
  596. package/dist/scripts/divergence-calc.js.map +0 -1
  597. package/dist/scripts/dw.d.ts.map +0 -1
  598. package/dist/scripts/dw.js.map +0 -1
  599. package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
  600. package/dist/scripts/generate_lp_chart.js.map +0 -1
  601. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
  602. package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
  603. package/dist/scripts/native_release_gates.d.ts.map +0 -1
  604. package/dist/scripts/native_release_gates.js.map +0 -1
  605. package/dist/scripts/print_grid.d.ts.map +0 -1
  606. package/dist/scripts/print_grid.js.map +0 -1
  607. package/dist/scripts/run-tests.d.ts.map +0 -1
  608. package/dist/scripts/run-tests.js.map +0 -1
  609. package/dist/scripts/runner.d.ts.map +0 -1
  610. package/dist/scripts/runner.js.map +0 -1
  611. package/dist/scripts/sync-version.d.ts.map +0 -1
  612. package/dist/scripts/sync-version.js.map +0 -1
  613. package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
  614. package/dist/scripts/test-credit-renewal.js.map +0 -1
  615. package/dist/scripts/tv.d.ts.map +0 -1
  616. package/dist/scripts/tv.js.map +0 -1
  617. package/dist/scripts/update.d.ts.map +0 -1
  618. package/dist/scripts/update.js.map +0 -1
  619. package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
  620. package/dist/scripts/update_dist_freshness.js.map +0 -1
  621. package/dist/scripts/validate_bots.d.ts.map +0 -1
  622. package/dist/scripts/validate_bots.js.map +0 -1
  623. package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
  624. package/dist/scripts/verify-browser-bundle.js.map +0 -1
  625. package/dist/unlock.d.ts.map +0 -1
  626. package/dist/unlock.js.map +0 -1
@@ -9,11 +9,10 @@ import { parseJsonWithComments, sleep, ensureDir } from '../modules/order/utils/
9
9
  import { readGeneralSettings } from '../modules/general_settings.js';
10
10
  import { DEFAULT_CONFIG, MARKET_ADAPTER, NATIVE_CLIENT, API_LIMITS, TIMING } from '../modules/constants.js';
11
11
  import { normalizeBotEntry } from '../modules/bot_settings.js';
12
- import { calculateAMA } from './core/strategies/ama.js';
13
12
  import * as kibanaSource from './inputs/kibana_source.js';
14
13
  import * as kibanaMarketSource from './core/kibana_market_candles.js';
15
14
  import { tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles } from './candle_utils.js';
16
- import { toIntervalLabel } from './interval_utils.js';
15
+ import { toIntervalLabel, bucketStartMs, latestClosedBucketStartMs } from './interval_utils.js';
17
16
  import { loadMarketProfiles } from '../analysis/tradingview/tradingview_uplot_chart_generator.js';
18
17
  import { candleFileForBot as candleFilePathForLabel } from '../analysis/bot_key_utils.js';
19
18
  import { writeJsonAtomic } from './utils/atomic_write.js';
@@ -273,7 +272,6 @@ const DEFAULT_AMA_KEY = String(MARKET_ADAPTER.DEFAULT_AMA_KEY).toUpperCase();
273
272
  const BUILTIN_AMAS = MARKET_ADAPTER.AMAS;
274
273
  const DEFAULT_AMA = MARKET_ADAPTER.AMAS.AMA3;
275
274
  const AMA_KEYWORDS = new Set(['ama', 'ama1', 'ama2', 'ama3', 'ama4']);
276
- const AMA_PRESET_KEYS = ['AMA1', 'AMA2', 'AMA3', 'AMA4'];
277
275
  function normalizeAmaPreset(raw) {
278
276
  const erPeriod = Number(raw?.erPeriod);
279
277
  const fastPeriod = Number(raw?.fastPeriod);
@@ -355,26 +353,29 @@ function resolveErSmoothPeriodForBot(bot) {
355
353
  }
356
354
  return globalErSmoothPeriod;
357
355
  }
358
- function buildAmaComparisonPresets(bot, ctx) {
359
- const profile = findAmaProfileForBot(bot, ctx);
360
- const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
361
- return AMA_PRESET_KEYS
362
- .map((key) => {
363
- const preset = getAmaPresetForKey(key, profile);
364
- if (!preset)
365
- return null;
366
- return {
367
- name: key,
368
- erPeriod: preset.erPeriod,
369
- fastPeriod: preset.fastPeriod,
370
- slowPeriod: preset.slowPeriod,
371
- erSmoothPeriod,
372
- };
373
- })
374
- .filter(Boolean);
375
- }
376
356
  function getAmaFromProfilesForBot(bot, ctx, cfg) {
357
+ const selected = resolveAmaPresetForBot(bot, ctx, cfg);
358
+ if (!selected)
359
+ return null;
360
+ return {
361
+ enabled: true,
362
+ name: selected.name,
363
+ erPeriod: selected.erPeriod,
364
+ fastPeriod: selected.fastPeriod,
365
+ slowPeriod: selected.slowPeriod,
366
+ erSmoothPeriod: selected.erSmoothPeriod,
367
+ };
368
+ }
369
+ /**
370
+ * Resolve which AMA preset key a bot actually trades on, and with what
371
+ * parameters. Returns null when no preset/profile entry applies.
372
+ *
373
+ * The chosen key rides along as `name` on the returned config so the cycle log
374
+ * and the state snapshot can say "this bot runs AMA2" without re-deriving it.
375
+ */
376
+ function resolveAmaPresetForBot(bot, ctx, cfg) {
377
377
  const profile = findAmaProfileForBot(bot, ctx);
378
+ const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
378
379
  if (!profile)
379
380
  return null;
380
381
  const rawGridPrice = String(bot?.gridPrice || '').trim().toLowerCase();
@@ -384,26 +385,223 @@ function getAmaFromProfilesForBot(bot, ctx, cfg) {
384
385
  : (isAmaKeyword(rawGridPrice)
385
386
  ? normalizeAmaKey(rawGridPrice)
386
387
  : (overrideDefaultAmaKey || normalizeAmaKey(profile?.defaultAma)));
387
- const selected = normalizeAmaPreset(profile?.amas?.[requestedKey])
388
- || normalizeAmaPreset(profile?.amas?.[overrideDefaultAmaKey || DEFAULT_AMA_KEY])
389
- || getAmaPresetForKey(requestedKey, profile)
390
- || getAmaPresetForKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, profile);
388
+ // Keep the (key, preset) pair so the effective preset name is the one that
389
+ // actually won the fallback chain, not merely the one that was requested.
390
+ const selected = pairAmaKey(requestedKey, normalizeAmaPreset(profile?.amas?.[requestedKey]))
391
+ || pairAmaKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, normalizeAmaPreset(profile?.amas?.[overrideDefaultAmaKey || DEFAULT_AMA_KEY]))
392
+ || pairAmaKey(requestedKey, getAmaPresetForKey(requestedKey, profile))
393
+ || pairAmaKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, getAmaPresetForKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, profile));
391
394
  if (!selected)
392
395
  return null;
393
396
  return {
394
397
  enabled: true,
395
- erPeriod: selected.erPeriod,
396
- fastPeriod: selected.fastPeriod,
397
- slowPeriod: selected.slowPeriod,
398
+ name: selected.key,
399
+ erPeriod: selected.preset.erPeriod,
400
+ fastPeriod: selected.preset.fastPeriod,
401
+ slowPeriod: selected.preset.slowPeriod,
402
+ erSmoothPeriod,
398
403
  };
399
404
  }
405
+ function pairAmaKey(key, preset) {
406
+ if (!preset)
407
+ return null;
408
+ return { key: String(key), preset };
409
+ }
400
410
  function sleepUntilAlignedBoundary(pollSeconds, referenceNowMs = Date.now(), nowMs = Date.now()) {
401
- const intervalMs = Math.max(1, Math.floor(Number(pollSeconds) || 0)) * 1000;
411
+ const normalizedPollSeconds = Math.max(1, Math.floor(Number(pollSeconds) || 0));
412
+ const intervalMs = normalizedPollSeconds * 1000;
402
413
  const bufferMs = 1000;
403
- const targetBoundaryMs = Math.floor(Number(referenceNowMs) / intervalMs) * intervalMs + intervalMs;
414
+ // The bucket containing the reference instant; its immediate successor is
415
+ // the boundary to align to. Shared bucket helper keeps this on the same
416
+ // grid as the closed-candle gate and the startup sleep.
417
+ const referenceBucketMs = bucketStartMs(referenceNowMs, normalizedPollSeconds);
418
+ // null (unusable reference clock/interval) means "do not wait": treat the
419
+ // reference as the first boundary, so the delay collapses to the buffer
420
+ // floor below. Never interpret it as an extra period, which would postpone
421
+ // a cycle instead of running it.
422
+ const targetBoundaryMs = (referenceBucketMs === null ? 0 : referenceBucketMs) + intervalMs;
404
423
  const delayMs = targetBoundaryMs - Number(nowMs) + bufferMs;
405
424
  return Math.max(bufferMs, delayMs);
406
425
  }
426
+ /**
427
+ * Sleep-first startup decision for the daemon.
428
+ *
429
+ * Returns `{ delayMs, veto }`: `delayMs` is how long to wait before the first
430
+ * cycle (0 = run a catch-up cycle now); `veto` is null when the adapter may
431
+ * sleep, otherwise `{ reason, botKeys }` saying why not. The wait uses the
432
+ * SAME poll boundary the loop aligns to (sleepUntilAlignedBoundary with
433
+ * cfg.pollSeconds, default 3600s), so the timing setting is honoured, not
434
+ * hardcoded.
435
+ *
436
+ * `veto` is non-null — and `delayMs` 0 — when:
437
+ * - state is fresh/empty (first run, cleared state — bootstrap lives in the
438
+ * cycle),
439
+ * - no in-scope bot has a consumed closed-candle marker yet,
440
+ * - ANY in-scope bot's consumed marker is not exactly the newest closed bucket
441
+ * (older = that bot still owes a cycle; newer = the clocks disagree, so do
442
+ * not trust the marker). Evaluated per bot, never aggregated: one lagging
443
+ * bot is invisible behind a max() over the others, and that bot is exactly
444
+ * what a catch-up cycle is for.
445
+ * - the candle interval is not the poll cadence, or the clock cannot be
446
+ * evaluated,
447
+ * - an active bot's last cycle left repair work still outstanding
448
+ * (unresolved gaps, or a cache shorter than its own warmup target),
449
+ * - an active bot has never been processed (no state row, or no consumed
450
+ * marker) — its bootstrap is still owed,
451
+ * - the active bot list cannot be read (then every state entry counts).
452
+ *
453
+ * The interval guard matters: the newest closed bucket is computed on the
454
+ * poll grid, while the markers in state are candle-bucket starts. With a
455
+ * mismatch (e.g. 2h candles polled hourly) the two grids only coincide by
456
+ * accident, and "coincide" here would delay a real cycle by up to one poll
457
+ * period. Refuse to sleep unless the grids are identical, i.e. unless one
458
+ * cycle per poll actually is one cycle per candle.
459
+ *
460
+ * One grid for every bot is correct because `intervalSeconds` is not in the
461
+ * per-pair/per-bot override whitelist, so all bots in a cycle share a bucket
462
+ * size. If that ever changes, the comparison has to become per bot.
463
+ *
464
+ * Otherwise it returns the wait until the next poll boundary. Mid-hour
465
+ * respawns (the common case: wrapper restart, crash recovery) therefore sleep
466
+ * instead of running a full cycle that the closed-candle gate would discard
467
+ * anyway. That wait is always shorter than one poll period, so at most one
468
+ * boundary is ever passed over: a candle that closes during the sleep is
469
+ * picked up by the very next cycle, never skipped.
470
+ *
471
+ * Only entries for bots the adapter would actually process are considered
472
+ * (activeBotKeys). A removed bot's leftover row, or a fixed-price bot, must
473
+ * not be able to defeat the sleep for everyone else — such an entry either
474
+ * has no marker at all or a marker that is months old. An active bot with NO
475
+ * row is treated exactly like an active bot with a row but no marker: both owe
476
+ * a bootstrap, so both veto the sleep and that bot goes live on the next cycle
477
+ * rather than up to a poll period later.
478
+ *
479
+ * Repair work is judged from the state entry, which records how the previous
480
+ * cycle ended. Two of its fields are deliberately distinguished:
481
+ *
482
+ * - `unresolvedGapCount` is a STANDING condition — it is measured on the final
483
+ * candle set, so a non-zero value means gaps are still missing right now.
484
+ * - `candleCount < rawKeepCount` is standing too: the cache has not reached
485
+ * the bot's own warmup target.
486
+ *
487
+ * `kibanaBackfillCount` is deliberately NOT consulted. It is an action count —
488
+ * how many candles the last completed cycle happened to fetch — and that cycle
489
+ * already applied them. A non-zero value means "repair was needed and was
490
+ * done", not "repair is owed". Because a skip carries the persisted entry
491
+ * forward, treating it as outstanding would keep vetoing the sleep after every
492
+ * backfill until some full cycle happened to rewrite the field with a zero.
493
+ * Cache shortness is the real signal, and it is checked directly above. The
494
+ * standing verdict is computed by evaluateStateRepairVeto in
495
+ * market_adapter_service.ts, immediately before the candle-file mirror
496
+ * (candleFileCoversClosedBucket), so a new standing signal is added once.
497
+ *
498
+ * None of this can see a config change made after that cycle (a grown AMA
499
+ * window, for instance): the backfill for that is then deferred to the next
500
+ * boundary, bounded by one poll period. Reading the state entry costs no extra
501
+ * I/O — no candle file is re-read and no connection is opened (the startup
502
+ * decision reads bots.json to build the active list, and each cycle reads it
503
+ * again).
504
+ *
505
+ * Known consequence of the "active bot with no row vetoes" rule: an active bot
506
+ * that can never reach a state write (unresolvable market, persistent
507
+ * pre-persist failure) keeps the sleep disabled for the whole daemon. That is
508
+ * intentional and fail-safe — healthy bots still take the in-cycle off-hour
509
+ * skip, so only the startup sleep is lost — and the veto is reported with its
510
+ * reason and bot keys so the situation is visible instead of silent.
511
+ */
512
+ function evaluateStartupSleep(cfg, state, nowMs = Date.now(), activeBotKeys = null) {
513
+ const vetoes = {};
514
+ const veto = (reason, key) => {
515
+ if (key == null)
516
+ return;
517
+ if (!vetoes[reason])
518
+ vetoes[reason] = [];
519
+ vetoes[reason].push(key);
520
+ };
521
+ // Whole-fleet refusals: the condition is about the configuration or the
522
+ // inputs, not about a particular bot, so there is nothing to attribute and
523
+ // botKeys stays empty. Per-bot refusals are collected in `vetoes` by the
524
+ // loop below and returned with their bot list. Deliberately NOT reading
525
+ // `vetoes[reason]` here — that would silently return another bot's keys if
526
+ // a denied() call were ever made after the loop has populated it.
527
+ const denied = (reason) => ({ delayMs: 0, veto: { reason, botKeys: [] } });
528
+ // Deliberate normalization asymmetry: pollSeconds is clamped to >=1 because
529
+ // it is the grid the sleep aligns to, while intervalSeconds is left as a
530
+ // bare floor so an invalid interval (0, negative, NaN) can NEVER equal the
531
+ // clamped poll value and therefore always takes interval_mismatch below —
532
+ // i.e. runs a catch-up cycle. Do not "simplify" by clamping both: that
533
+ // would let an unconfigured interval match and authorize a sleep on a grid
534
+ // the persisted markers were not written on.
535
+ const pollSeconds = Math.max(1, Math.floor(Number(cfg?.pollSeconds) || 0));
536
+ const intervalSeconds = Math.floor(Number(cfg?.intervalSeconds) || 0);
537
+ if (intervalSeconds !== pollSeconds)
538
+ return denied('interval_mismatch');
539
+ const now = Number(nowMs);
540
+ if (!Number.isFinite(now) || now <= 0)
541
+ return denied('clock_unusable');
542
+ const bots = state?.bots;
543
+ if (!bots || typeof bots !== 'object')
544
+ return denied('state_unusable');
545
+ // An empty active-bot list means the adapter has nothing to do; do not
546
+ // interpret it as "unknown scope" and fall back to scanning every row.
547
+ if (Array.isArray(activeBotKeys) && activeBotKeys.length === 0)
548
+ return denied('no_active_bots');
549
+ // Newest fully closed bucket: its start. A cycle that consumed it has
550
+ // done all the work available until the next bucket closes. Shared helper
551
+ // so the startup sleep and the in-cycle gate agree by construction.
552
+ const latestClosed = latestClosedBucketStartMs(now, pollSeconds);
553
+ if (latestClosed === null)
554
+ return denied('clock_unusable');
555
+ // With a known active set, every one of those bots is judged on its own.
556
+ // Unknown set (bot list unreadable) falls back to the state rows present.
557
+ const scope = Array.isArray(activeBotKeys) ? activeBotKeys : Object.keys(bots);
558
+ if (scope.length === 0)
559
+ return denied('no_state_rows');
560
+ for (const key of scope) {
561
+ const entry = bots[key];
562
+ // An active bot with no state row at all still owes its first cycle.
563
+ if (!entry || typeof entry !== 'object') {
564
+ veto('no_state_row', key);
565
+ continue;
566
+ }
567
+ const consumed = Number(entry.lastClosedCandleTs || 0);
568
+ // No consumed marker yet: this bot still owes a bootstrap/warmup cycle.
569
+ if (!Number.isFinite(consumed) || consumed <= 0) {
570
+ veto('no_consumed_marker', key);
571
+ continue;
572
+ }
573
+ // Per bot, never aggregated across bots: one lagging bot is exactly the
574
+ // reason a catch-up cycle is needed, and a max() would hide it.
575
+ if (consumed !== latestClosed) {
576
+ veto(consumed < latestClosed ? 'behind_latest_closed_candle' : 'marker_ahead_of_clock', key);
577
+ continue;
578
+ }
579
+ // Standing repair conditions, as measured by the previous cycle. Shared
580
+ // with candleFileCoversClosedBucket's state-side mirror so the two gates
581
+ // cannot drift apart.
582
+ const repairReason = evaluateStateRepairVeto(entry);
583
+ if (repairReason) {
584
+ veto(repairReason, key);
585
+ continue;
586
+ }
587
+ }
588
+ if (Object.keys(vetoes).length > 0) {
589
+ // Every distinct reason is reported, so a permanent veto (an active bot
590
+ // that can never be persisted) is diagnosable from the log alone.
591
+ const reason = Object.keys(vetoes).sort().join('+');
592
+ return { delayMs: 0, veto: { reason, botKeys: [...new Set(Object.values(vetoes).flat())] } };
593
+ }
594
+ return { delayMs: sleepUntilAlignedBoundary(pollSeconds, now, now), veto: null };
595
+ }
596
+ /**
597
+ * Numeric form of evaluateStartupSleep: the wait before the daemon's first
598
+ * cycle, or 0 to run a catch-up cycle now. The decision rules — and the reasons
599
+ * it can refuse — are documented there; this wrapper exists so callers that
600
+ * only need the wait do not have to unpack a verdict object.
601
+ */
602
+ function computeStartupDelayMs(cfg, state, nowMs = Date.now(), activeBotKeys = null) {
603
+ return evaluateStartupSleep(cfg, state, nowMs, activeBotKeys).delayMs;
604
+ }
407
605
  function withRetries(fn, attempts, baseDelayMs, label) {
408
606
  return (async () => {
409
607
  let lastErr;
@@ -536,17 +734,35 @@ function resolveDeltaThresholdPercentFromGeneralSettings(settings) {
536
734
  return explicit;
537
735
  return null;
538
736
  }
737
+ /**
738
+ * Slope-trigger factor from general settings (`(value/100) × maxSlopePct`).
739
+ * Mirrors the price resolver above; the bot editor writes this knob under
740
+ * `MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT`, so the runtime must read
741
+ * it back or the user-facing `AMA-Slope Δ` setting would be inert.
742
+ */
743
+ function resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings(settings) {
744
+ const explicit = Number(settings?.MARKET_ADAPTER?.AMA_SLOPE_DELTA_THRESHOLD_PERCENT);
745
+ if (Number.isFinite(explicit) && explicit > 0)
746
+ return explicit;
747
+ return null;
748
+ }
539
749
  function applyRuntimeDefaultsFromGeneralSettings(cfg, provided = {}, settingsOverride) {
540
750
  const out = { ...cfg };
751
+ const settings = settingsOverride === undefined
752
+ ? readGeneralSettings({ fallback: null })
753
+ : settingsOverride;
541
754
  if (!provided?.deltaThresholdPercent) {
542
- const settings = settingsOverride === undefined
543
- ? readGeneralSettings({ fallback: null })
544
- : settingsOverride;
545
755
  const fromSettings = resolveDeltaThresholdPercentFromGeneralSettings(settings);
546
756
  if (fromSettings != null) {
547
757
  out.deltaThresholdPercent = fromSettings;
548
758
  }
549
759
  }
760
+ const slopeFromSettings = resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings(settings);
761
+ if (slopeFromSettings != null) {
762
+ // Rebuild amaSlope instead of mutating it: `cfg` may be the shared
763
+ // DEFAULTS object and must not be poisoned for later calls.
764
+ out.amaSlope = { ...(out.amaSlope || {}), deltaThresholdPct: slopeFromSettings };
765
+ }
550
766
  return out;
551
767
  }
552
768
  const marketAdapterLogFile = path.join(PATHS.LOGS_DIR, 'market_adapter.log');
@@ -626,23 +842,53 @@ function computeCandleStaleness(lastCandleTs, maxStaleHours) {
626
842
  const staleAgeHours = Number.isFinite(staleAgeMs) ? (staleAgeMs / 3600000) : null;
627
843
  return { staleData, staleAgeHours };
628
844
  }
845
+ /**
846
+ * Resolve the AMA configuration a bot trades on.
847
+ *
848
+ * Precedence, as implemented: when a market profile applies for the pair, the
849
+ * preset is chosen from the profile by the bot's `gridPrice` keyword, else the
850
+ * profile/`AMA3` default (a profile entry always wins over the bot's numeric
851
+ * `ama` block). Without a profile, the bot's own `ama` numbers are used, with
852
+ * the `gridPrice` keyword preset filling any missing period and AMA3 as the last
853
+ * resort.
854
+ *
855
+ * The winning preset key — or 'custom' when the numbers came from the bot's own
856
+ * `ama` block — rides along as `name`, so the cycle log and the state snapshot
857
+ * can state which AMA this bot runs without re-deriving it.
858
+ *
859
+ * `enabled` is a derived invariant, always true here. `gridPrice` is the single
860
+ * switch that decides whether a bot is AMA-driven — `usesAmaGridPrice()` reads
861
+ * it in the bot runtime, the maintenance runtime and the launcher — so an
862
+ * `ama.enabled` flag could only ever disagree with them. It used to: this
863
+ * function honoured it on the profile-less path and hardcoded `true` on the
864
+ * profile path, and because the bot side ignores the flag, honouring it froze
865
+ * the published center while the bot kept trading on it. Callers must gate AMA
866
+ * work on `usesAmaGridPrice(bot)`.
867
+ */
629
868
  function resolveAmaForBot(bot, ctx = null, cfg = null) {
630
869
  const raw = (bot && typeof bot.ama === 'object' && bot.ama !== null) ? bot.ama : {};
631
870
  const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
632
871
  const fromProfiles = getAmaFromProfilesForBot(bot, ctx, cfg);
633
- if (fromProfiles) {
634
- fromProfiles.erSmoothPeriod = erSmoothPeriod;
872
+ if (fromProfiles)
635
873
  return fromProfiles;
636
- }
637
874
  const amaCfg = {
638
875
  erPeriod: Number(raw.erPeriod),
639
876
  fastPeriod: Number(raw.fastPeriod),
640
877
  slowPeriod: Number(raw.slowPeriod),
641
878
  erSmoothPeriod,
642
- enabled: raw.enabled !== false,
879
+ enabled: true,
880
+ name: 'custom',
643
881
  };
882
+ // Which preset the periods came from — tracked so the reported name
883
+ // describes the SOURCE, not merely the values (a bot that hand-writes the
884
+ // AMA3 numbers is still its own configuration, not "AMA3").
885
+ const botSuppliedPeriod = Number.isFinite(Number(raw.erPeriod))
886
+ || Number.isFinite(Number(raw.fastPeriod))
887
+ || Number.isFinite(Number(raw.slowPeriod));
888
+ let presetKey = null;
644
889
  if (isAmaKeyword(bot?.gridPrice)) {
645
- const preset = getAmaPresetForKey(normalizeAmaKey(bot.gridPrice), null);
890
+ const key = normalizeAmaKey(bot.gridPrice);
891
+ const preset = getAmaPresetForKey(key, null);
646
892
  if (preset) {
647
893
  if (!Number.isFinite(amaCfg.erPeriod))
648
894
  amaCfg.erPeriod = preset.erPeriod;
@@ -650,6 +896,7 @@ function resolveAmaForBot(bot, ctx = null, cfg = null) {
650
896
  amaCfg.fastPeriod = preset.fastPeriod;
651
897
  if (!Number.isFinite(amaCfg.slowPeriod))
652
898
  amaCfg.slowPeriod = preset.slowPeriod;
899
+ presetKey = key;
653
900
  }
654
901
  }
655
902
  if (!Number.isFinite(amaCfg.erPeriod) || amaCfg.erPeriod < 1)
@@ -658,6 +905,9 @@ function resolveAmaForBot(bot, ctx = null, cfg = null) {
658
905
  amaCfg.fastPeriod = DEFAULT_AMA.fastPeriod;
659
906
  if (!Number.isFinite(amaCfg.slowPeriod) || amaCfg.slowPeriod < 1)
660
907
  amaCfg.slowPeriod = DEFAULT_AMA.slowPeriod;
908
+ // Periods the bot supplied itself win, so the config is 'custom'; otherwise
909
+ // the name is the preset the periods came from (keyword, else the default).
910
+ amaCfg.name = botSuppliedPeriod ? 'custom' : (presetKey || DEFAULT_AMA_KEY);
661
911
  if (amaCfg.fastPeriod > amaCfg.slowPeriod) {
662
912
  const t = amaCfg.fastPeriod;
663
913
  amaCfg.fastPeriod = amaCfg.slowPeriod;
@@ -672,26 +922,39 @@ function pruneCandles(candles, keepCount) {
672
922
  return candles;
673
923
  return candles.slice(candles.length - keepCount);
674
924
  }
675
- function calcAmaComparison(candles, bot = null, ctx = null) {
676
- const closes = (candles || []).map((c) => Number(c?.[4])).filter((v) => Number.isFinite(v) && v > 0);
677
- const out = [];
678
- const presets = buildAmaComparisonPresets(bot, ctx);
679
- for (const p of presets) {
680
- const minNeeded = p.erPeriod + 1;
681
- if (closes.length < minNeeded) {
682
- out.push({ ...p, value: null, ok: false });
683
- continue;
684
- }
685
- const values = calculateAMA(closes, {
686
- erPeriod: p.erPeriod,
687
- fastPeriod: p.fastPeriod,
688
- slowPeriod: p.slowPeriod,
689
- erSmoothPeriod: p.erSmoothPeriod,
690
- });
691
- const value = values[values.length - 1];
692
- out.push({ ...p, value: Number.isFinite(value) ? value : null, ok: Number.isFinite(value) });
925
+ /**
926
+ * Build the per-bot AMA record that is logged and persisted in the state file.
927
+ *
928
+ * It reports the ONE AMA the bot actually trades on — the value the cycle has
929
+ * already computed as `amaValues` — instead of re-running `calculateAMA` for the
930
+ * AMA1..AMA4 preset sweep. Those four extra passes cost ~0.3 ms each per bot per
931
+ * hour and fed nothing but the old "AMA compare:" log line: the presets are
932
+ * research knobs, not a signal, and the bot's price always came from its own
933
+ * configured parameters. So the comparison was 4 duplications of work whose
934
+ * result no decision, log consumer or dashboard ever read.
935
+ *
936
+ * The array shape (one entry, same fields) is kept so the state schema and the
937
+ * cycle log stay stable; the field is still called `amaComparison` in the
938
+ * persisted state for backwards compatibility with existing snapshots.
939
+ */
940
+ function buildAmaRecord(botAma, amaPrice) {
941
+ const erPeriod = Number(botAma?.erPeriod);
942
+ const fastPeriod = Number(botAma?.fastPeriod);
943
+ const slowPeriod = Number(botAma?.slowPeriod);
944
+ const erSmoothPeriod = Number(botAma?.erSmoothPeriod);
945
+ if (!Number.isFinite(erPeriod) || !Number.isFinite(fastPeriod) || !Number.isFinite(slowPeriod)) {
946
+ return [];
693
947
  }
694
- return out;
948
+ const value = Number(amaPrice);
949
+ return [{
950
+ name: String(botAma?.name || 'active'),
951
+ erPeriod,
952
+ fastPeriod,
953
+ slowPeriod,
954
+ erSmoothPeriod: Number.isFinite(erSmoothPeriod) ? erSmoothPeriod : 0,
955
+ value: Number.isFinite(value) ? value : null,
956
+ ok: Number.isFinite(value),
957
+ }];
695
958
  }
696
959
  async function fetchNativeTradesSince(poolId, sinceMs, pageLimit, maxPages) {
697
960
  const { BitShares } = getBitsharesClient();
@@ -938,7 +1201,7 @@ function writeBotDynamicGrid(botKey, gridCenterPrice, options = {}) {
938
1201
  return false;
939
1202
  }
940
1203
  }
941
- import { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar, } from './core/market_adapter_service.js';
1204
+ import { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar, evaluateStateRepairVeto, } from './core/market_adapter_service.js';
942
1205
  import { getErrorMessage } from '../modules/utils/errors.js';
943
1206
  const adapterService = new MarketAdapterService({
944
1207
  resolveBotContext,
@@ -961,7 +1224,7 @@ const adapterService = new MarketAdapterService({
961
1224
  pruneStaleTail,
962
1225
  mergeCandles,
963
1226
  pruneCandles,
964
- calcAmaComparison,
1227
+ buildAmaRecord,
965
1228
  writeGridResetTrigger,
966
1229
  writeBotDynamicGrid,
967
1230
  isBotWhitelisted,
@@ -1067,6 +1330,18 @@ async function runOnce(cfg, state, contextCache) {
1067
1330
  });
1068
1331
  continue;
1069
1332
  }
1333
+ // Off-hour skip: nothing to compute, so log one compact line
1334
+ // instead of the full signal block (which would print n/a for
1335
+ // every field and bury the hourly cycle in noise).
1336
+ if (r.source === 'off-hour-skip') {
1337
+ log(cfg, `skip (no new closed candle, last processed ${Number.isFinite(r.lastClosedCandleTs) ? new Date(r.lastClosedCandleTs).toISOString() : 'n/a'})`);
1338
+ results.push({
1339
+ botName: bot.name,
1340
+ botKey: bot.botKey,
1341
+ ...r,
1342
+ });
1343
+ continue;
1344
+ }
1070
1345
  const amaText = Number.isFinite(r.amaPrice) ? r.amaPrice.toFixed(8) : 'n/a';
1071
1346
  const prevCenterText = Number.isFinite(r.previousCenterPrice) ? r.previousCenterPrice.toFixed(8) : 'n/a';
1072
1347
  const deltaText = Number.isFinite(r.deltaPercent) ? `${r.deltaPercent.toFixed(3)}%` : 'n/a';
@@ -1130,7 +1405,7 @@ async function runOnce(cfg, state, contextCache) {
1130
1405
  const erSmoothText = Number.isFinite(Number(a.erSmoothPeriod)) ? `/es${fixedTo(a.erSmoothPeriod, 0)}` : '';
1131
1406
  return `${a.name}[${a.erPeriod}/${a.fastPeriod}/${a.slowPeriod}${erSmoothText}]=${val}`;
1132
1407
  });
1133
- log(cfg, ` AMA compare: ${parts.join(' | ')}`);
1408
+ log(cfg, ` AMA active: ${parts.join(' | ')}`);
1134
1409
  }
1135
1410
  results.push({
1136
1411
  botName: bot.name,
@@ -1238,6 +1513,53 @@ async function main() {
1238
1513
  log(cfg, 'Dry run: config validation + lock acquisition OK (no network, no writes).');
1239
1514
  return 0;
1240
1515
  }
1516
+ // Read state before the sleep: the lock guarantees no other adapter can
1517
+ // rewrite it in the meantime, and the same object is then used by the
1518
+ // first cycle, so the file is parsed exactly once per start.
1519
+ const state = loadJson(STATE_FILE, { meta: {}, bots: {} });
1520
+ const contextCache = new Map();
1521
+ // Sleep-first startup, decided BEFORE the first connection: a respawned
1522
+ // daemon (wrapper restart, crash recovery, manual start) must not run a
1523
+ // full cycle immediately — mid-hour that cycle can only hit the
1524
+ // closed-candle gate after paying the chain handshake + per-bot native
1525
+ // fetch. Instead, align to the SAME boundary the loop uses
1526
+ // (pollSeconds, default 3600s) and only run early when some active bot
1527
+ // still owes a cycle.
1528
+ //
1529
+ // Ordering matters: connecting first and sleeping afterwards would hold
1530
+ // an idle socket for the whole hour, which is exactly what the
1531
+ // per-cycle connect/disconnect below exists to avoid. The lock is
1532
+ // already held (and its heartbeat is unref'd but armed), so a sleeping
1533
+ // adapter still looks alive to the watchdog, which decides staleness by
1534
+ // holder liveness rather than by lock age.
1535
+ if (!cfg.once) {
1536
+ // Only bots the adapter would actually process may veto the sleep:
1537
+ // a removed bot's leftover state row (or a fixed-price bot) must
1538
+ // not force a full cycle on every restart. If the bot list cannot be
1539
+ // read, every state row is judged instead (conservative).
1540
+ let activeAmaBotKeys = null;
1541
+ try {
1542
+ activeAmaBotKeys = loadActiveBots()
1543
+ .filter((bot) => usesAmaGridPrice(bot))
1544
+ .map((bot) => bot.botKey);
1545
+ }
1546
+ catch (_) {
1547
+ activeAmaBotKeys = null;
1548
+ }
1549
+ const verdict = evaluateStartupSleep(cfg, state, Date.now(), activeAmaBotKeys);
1550
+ if (verdict.delayMs > 0) {
1551
+ log(cfg, `Startup: every active bot consumed the newest closed candle and no repair is outstanding — sleeping ${(verdict.delayMs / 1000).toFixed(0)}s until the next ${cfg.pollSeconds}s boundary (no connection held).`);
1552
+ await sleep(verdict.delayMs);
1553
+ }
1554
+ else {
1555
+ // Name the reason and the bots: a veto caused by one
1556
+ // unprocessable bot would otherwise look like "the adapter just
1557
+ // never sleeps" with nothing in the log to explain it.
1558
+ const v = verdict.veto || { reason: 'unknown', botKeys: [] };
1559
+ const who = v.botKeys.length > 0 ? ` [${v.botKeys.join(', ')}]` : '';
1560
+ log(cfg, `Startup: running a catch-up cycle now — ${v.reason}${who}.`);
1561
+ }
1562
+ }
1241
1563
  {
1242
1564
  const maxRetries = 5;
1243
1565
  let lastErr = null;
@@ -1263,8 +1585,6 @@ async function main() {
1263
1585
  }
1264
1586
  }
1265
1587
  log(cfg, 'Connected to BitShares');
1266
- const state = loadJson(STATE_FILE, { meta: {}, bots: {} });
1267
- const contextCache = new Map();
1268
1588
  if (cfg.once) {
1269
1589
  const run = await runOnce(cfg, state, contextCache);
1270
1590
  const allProcessedFailed = run.metrics.processedBots > 0 && run.metrics.successBots === 0;
@@ -1273,8 +1593,12 @@ async function main() {
1273
1593
  while (true) {
1274
1594
  const started = Date.now();
1275
1595
  log(cfg, `\n[cycle ${new Date(started).toISOString()}]`);
1276
- // Connect for this cycle using the lightweight native read-only client.
1277
- // Tear down after runOnce so the connection never sits idle.
1596
+ // Connect for this cycle using the lightweight native read-only
1597
+ // client, and tear it down after runOnce so the connection never
1598
+ // sits idle. A socket that outlives its cycle can be half-open when
1599
+ // the next one starts (the peer drops it with no close frame, so
1600
+ // readyState stays 1 and nothing notices); the per-cycle handshake
1601
+ // re-validates chain id and api id before any RPC goes out on it.
1278
1602
  try {
1279
1603
  const { connectClient } = getBitsharesClient();
1280
1604
  await connectClient();
@@ -1289,6 +1613,16 @@ async function main() {
1289
1613
  disconnectClient();
1290
1614
  }
1291
1615
  catch (_) { }
1616
+ const cycleMs = Date.now() - started;
1617
+ const pollMs = Math.max(1, Number(cfg.pollSeconds) || 0) * 1000;
1618
+ if (cycleMs >= pollMs) {
1619
+ // The cadence is slipping: this cycle alone consumed a full
1620
+ // period, so the next one starts immediately (1000ms floor) and
1621
+ // the backlog drains one cycle at a time. Surfaced explicitly,
1622
+ // because a silent backlog is indistinguishable from an adapter
1623
+ // that "runs every hour" in the log.
1624
+ logger.warn(`Cycle took ${(cycleMs / 1000).toFixed(0)}s, at or beyond the ${cfg.pollSeconds}s poll period — running the next cycle immediately to catch up.`);
1625
+ }
1292
1626
  const sleepMs = sleepUntilAlignedBoundary(cfg.pollSeconds, started, Date.now());
1293
1627
  await sleep(sleepMs);
1294
1628
  }
@@ -1305,5 +1639,5 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
1305
1639
  process.exit(1);
1306
1640
  });
1307
1641
  }
1308
- export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, calcAmaComparison, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, resolveAmaForBot, resolveDeltaThresholdPercentFromGeneralSettings, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, _resetCycleCache, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, mergeGridResetMetadataFromDynamicGrid, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, setBitsharesClientForTests as _setBitsharesClientForTests, loadMarketAdapterSettings, findPairForBot };
1642
+ export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, buildAmaRecord, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveAmaForBot, resolveDeltaThresholdPercentFromGeneralSettings, resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, _resetCycleCache, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, mergeGridResetMetadataFromDynamicGrid, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, setBitsharesClientForTests as _setBitsharesClientForTests, loadMarketAdapterSettings, findPairForBot };
1309
1643
  //# sourceMappingURL=market_adapter.js.map
@@ -4,7 +4,7 @@
4
4
  * Canonical import point for tests that need internal market-adapter helpers.
5
5
  * Keeps test dependencies centralized and explicit.
6
6
  */
7
- import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary } from './market_adapter.js';
7
+ import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep } from './market_adapter.js';
8
8
  import { resolveAsset, resolveBotContext, resolveMarketSourceForBot } from './utils/chain.js';
9
- export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
9
+ export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
10
10
  //# sourceMappingURL=test_helpers.d.ts.map
@@ -5,7 +5,7 @@
5
5
  * Canonical import point for tests that need internal market-adapter helpers.
6
6
  * Keeps test dependencies centralized and explicit.
7
7
  */
8
- import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, } from './market_adapter.js';
8
+ import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, } from './market_adapter.js';
9
9
  import { resolveAsset, resolveBotContext, resolveMarketSourceForBot, } from './utils/chain.js';
10
- export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
10
+ export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
11
11
  //# sourceMappingURL=test_helpers.js.map