dexbot 1.6.11 → 1.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -1,16 +1,82 @@
1
+ /**
2
+ * Grid-reset simulation for the TradingView exporter.
3
+ *
4
+ * Replays the market adapter's two grid-recentering triggers over the chart's
5
+ * AMA series, exactly as `market_adapter/core/market_adapter_service.ts`
6
+ * decides them per cycle (see docs/GRID_RECALCULATION.md §3 and §4):
7
+ *
8
+ * A — AMA price delta (`market_adapter_delta_threshold`): the accepted
9
+ * center ratchets only when the AMA moves
10
+ * `|AMA − gridCenterPrice| / gridCenterPrice × 100 >= deltaThresholdPercent`
11
+ * (`deltaThresholdPercent` in the resolved adapter cfg).
12
+ *
13
+ * B — AMA slope delta (`market_adapter_ama_slope_delta_threshold`): gated
14
+ * behind the per-bot `asymmetricBounds` whitelist, fires when
15
+ * `|slopePct − gridRangeScalingAmaSlope.slopePct| >= amaSlopeThresholdPercent`
16
+ * (per-bar %, see `buildAmaSlopeResetDetails`).
17
+ *
18
+ * Ratchet semantics (both triggers): on a reset the accepted center moves to
19
+ * the current AMA **and** the accepted slope baseline is re-seeded to the
20
+ * current slope — the `advanceTriggeredBotState` chain in the service. The
21
+ * price trigger is evaluated first and the slope trigger only runs when no
22
+ * price trigger fired in the same bar, matching the service's if/if-else
23
+ * ordering. This is the same model the OHLC backtest uses
24
+ * (analysis/bot_fitting/backtest_bot_fitting.ts, `simulateForParams`).
25
+ *
26
+ * Deliberate scope limits (the chart replays the *decision*, not the runtime):
27
+ * - one evaluation per 1h bar, no staleness/gap/candle-count suppression
28
+ * gates (fresh closed candles are the norm in a candle file);
29
+ * - the accepted center is the value the grid would be built around, so the
30
+ * simulated range band is frozen between resets and re-tilts from the
31
+ * accepted slope at every reset;
32
+ * - the band is a faithful replay of the grid-build *bounds pipeline*
33
+ * (applyAsymmetricBounds → applyNarrowingSideGuard), but the narrowing
34
+ * guard is centered on the accepted AMA center rather than the live
35
+ * market/start price the runtime uses; the gap is bounded by the reset
36
+ * threshold and only shifts the tightening side by its slot floor;
37
+ * - RMS divergence, available-funds resizes and manual triggers are not
38
+ * simulated (out of scope for a candle chart).
39
+ *
40
+ * The functions below are embedded verbatim into the generated HTML via
41
+ * `embedFunctionSources`, so they may only reference module imports that are
42
+ * embedded alongside them (`computeAverageAmaSlopePct`,
43
+ * `createAmaSlopeClipTracker`, `percentileFromSorted`, `clamp`).
44
+ */
45
+ import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
1
46
  declare const GRID_RESET_NONE = 0;
2
47
  declare const GRID_RESET_BOOTSTRAP = 1;
48
+ interface GridResetEvent {
49
+ index: number;
50
+ reason?: unknown;
51
+ [key: string]: unknown;
52
+ }
53
+ interface GridSimCfg {
54
+ clampMin?: number | null;
55
+ clampMax?: number | null;
56
+ clipPercentile?: number | null;
57
+ erPeriod?: number;
58
+ lookbackBars?: number;
59
+ maxSlopeOffset?: number;
60
+ maxSlopePct?: number;
61
+ neutralZonePct?: number;
62
+ priceDeltaThresholdPercent?: number;
63
+ slopeDeltaThresholdPercent?: number;
64
+ slopeEnabled?: boolean;
65
+ slopePersistBars?: number;
66
+ warmupBars?: number;
67
+ slopeEstimator?: ((amaValues: unknown, index: number, lookbackBars: unknown) => number | null) | null;
68
+ }
3
69
  declare const GRID_RESET_PRICE = 2;
4
70
  declare const GRID_RESET_SLOPE = 3;
5
- declare function gridSimPositiveNumber(value: any, fallback: any): any;
6
- declare function gridSimNonNegativeInt(value: any, fallback: any): any;
71
+ declare function gridSimPositiveNumber(value: unknown, fallback: number): number;
72
+ declare function gridSimNonNegativeInt(value: unknown, fallback: number): number;
7
73
  /**
8
74
  * Average AMA slope in %/bar plus the trend/offset the grid build would use
9
75
  * for that bar, mirroring `computeAmaSlopeWeights` steps 2b–3 (percentile clip
10
76
  * → neutral zone → trend → slopeOffset). The delta trigger itself compares the
11
77
  * UNCLIPPED `slopePct`; the clipped value only feeds the range tilt.
12
78
  */
13
- declare function gridSimSlopeSignal(slopePct: any, clipThreshold: any, cfg: any): {
79
+ declare function gridSimSlopeSignal(slopePct: unknown, clipThreshold: unknown, cfg: GridSimCfg): {
14
80
  slopePct: null;
15
81
  clippedSlopePct: null;
16
82
  trend: null;
@@ -35,7 +101,7 @@ declare function gridSimSlopeSignal(slopePct: any, clipThreshold: any, cfg: any)
35
101
  * model without touching this module — it takes the whole series plus the index
36
102
  * because windowed estimators need the window, not just the two endpoints.
37
103
  */
38
- declare function gridSimResolveSlopeEstimator(cfg: any): any;
104
+ declare function gridSimResolveSlopeEstimator(cfg: GridSimCfg): typeof computeHuberWindowSlopePct;
39
105
  /**
40
106
  * Replay the two market-adapter grid-recentering triggers over `amaSeries`
41
107
  * (the chart's 1h AMA series, already in display orientation).
@@ -47,7 +113,7 @@ declare function gridSimResolveSlopeEstimator(cfg: any): any;
47
113
  * maxSlopeOffset, clipPercentile, clampMin, clampMax.
48
114
  * @returns per-bar series (same length as `amaSeries`) + `events` + `stats`.
49
115
  */
50
- declare function simulateGridResetSeries(amaSeries: any, cfg: any): {
116
+ declare function simulateGridResetSeries(amaSeries: unknown, cfg: GridSimCfg): {
51
117
  center: any[];
52
118
  reason: any[];
53
119
  driftPct: any[];
@@ -56,21 +122,21 @@ declare function simulateGridResetSeries(amaSeries: any, cfg: any): {
56
122
  acceptedSlopePct: any[];
57
123
  acceptedSlopeOffset: any[];
58
124
  acceptedTrend: any[];
59
- events: any[];
125
+ events: GridResetEvent[];
60
126
  stats: {
61
127
  bars: number;
62
128
  resets: number;
63
129
  resetsTotal: number;
64
130
  priceResets: number;
65
131
  slopeResets: number;
66
- bootstrapIndex: any;
132
+ bootstrapIndex: number | null;
67
133
  lastResetIndex: number | null;
68
134
  barsSinceLastReset: number | null;
69
135
  avgBarsBetweenResets: number | null;
70
- warmupBars: any;
136
+ warmupBars: number;
71
137
  priceDeltaThresholdPercent: number | null;
72
138
  slopeDeltaThresholdPercent: number | null;
73
- slopePersistBars: any;
139
+ slopePersistBars: number;
74
140
  slopeTriggerArmed: boolean;
75
141
  };
76
142
  };
@@ -120,7 +120,8 @@ function gridSimResolveSlopeEstimator(cfg) {
120
120
  * @returns per-bar series (same length as `amaSeries`) + `events` + `stats`.
121
121
  */
122
122
  function simulateGridResetSeries(amaSeries, cfg) {
123
- const n = Array.isArray(amaSeries) ? amaSeries.length : 0;
123
+ const amaArr = Array.isArray(amaSeries) ? amaSeries : [];
124
+ const n = amaArr.length;
124
125
  const priceThreshold = Number(cfg?.priceDeltaThresholdPercent);
125
126
  const priceTriggerArmed = Number.isFinite(priceThreshold) && priceThreshold > 0;
126
127
  const slopeThreshold = Number(cfg?.slopeDeltaThresholdPercent);
@@ -198,7 +199,7 @@ function simulateGridResetSeries(amaSeries, cfg) {
198
199
  let slopePersistCount = 0;
199
200
  let slopePersistDir = 0;
200
201
  for (let i = 0; i < n; i++) {
201
- const ama = Number(amaSeries[i]);
202
+ const ama = Number(amaArr[i]);
202
203
  const hasAma = Number.isFinite(ama) && ama > 0;
203
204
  // Feed the clip tracker every bar (non-finite values keep their slot,
204
205
  // exactly like the batch threshold). The chart's AMA is computed over
@@ -210,7 +211,7 @@ function simulateGridResetSeries(amaSeries, cfg) {
210
211
  const clipThreshold = clipTracker.push(hasAma ? ama : NaN);
211
212
  let slopePct = null;
212
213
  if (hasAma && i >= readyBars) {
213
- const s = estimateSlope(amaSeries, i, lookbackBars);
214
+ const s = estimateSlope(amaArr, i, lookbackBars);
214
215
  if (Number.isFinite(s))
215
216
  slopePct = s;
216
217
  }
@@ -1,9 +1,74 @@
1
1
  import { normalizeCandle } from '../math_utils.js';
2
- declare function loadMarketProfiles(filePath?: any): any;
2
+ interface MarketMeta {
3
+ intervalSeconds?: unknown;
4
+ pool?: unknown;
5
+ poolId?: unknown;
6
+ feed?: unknown;
7
+ assetA?: {
8
+ symbol?: string;
9
+ id?: string;
10
+ };
11
+ assetB?: {
12
+ symbol?: string;
13
+ id?: string;
14
+ };
15
+ }
16
+ interface AmaDefaultsInput {
17
+ amaDefaults?: {
18
+ erPeriod?: unknown;
19
+ fastPeriod?: unknown;
20
+ slowPeriod?: unknown;
21
+ } | null;
22
+ amaErPeriod?: unknown;
23
+ amaFastPeriod?: unknown;
24
+ amaSlowPeriod?: unknown;
25
+ }
26
+ declare function loadMarketProfiles(filePath?: string | null | undefined): {
27
+ profiles?: Array<Record<string, unknown>>;
28
+ } | null;
3
29
  declare const TRADINGVIEW_PREFS_KEY_PREFIX = "dexbot2-tradingview-uplot-v3";
4
30
  declare const TRADINGVIEW_SYNC_KEY = "dexbot2-tradingview-sync";
5
- declare function sanitizeStorageComponent(value: any, fallback: string): string;
6
- declare function resolveChartStorageKey(meta?: any, baseIntervalSeconds?: any): string;
7
- declare function generateHTML(data: any, title?: any): string;
31
+ declare function sanitizeStorageComponent(value: unknown, fallback: string): string;
32
+ declare function resolveChartStorageKey(meta?: MarketMeta, baseIntervalSeconds?: number): string;
33
+ interface TvChartInput extends AmaDefaultsInput {
34
+ candles?: unknown[];
35
+ meta?: MarketMeta;
36
+ defaultTimeframe?: string;
37
+ marketProfiles?: unknown;
38
+ smaPeriod?: number;
39
+ smaEnabled?: boolean;
40
+ amaEnabled?: boolean;
41
+ vwapEnabled?: boolean;
42
+ vwapBars?: number;
43
+ priceScale?: string;
44
+ rangeWidthPct?: number;
45
+ rangeSpan?: number;
46
+ grid?: {
47
+ minPrice?: unknown;
48
+ maxPrice?: unknown;
49
+ incrementPercent?: number | null;
50
+ maxAsymmetryFactor?: number | null;
51
+ minScaleSlots?: number | null;
52
+ [key: string]: unknown;
53
+ } | null;
54
+ gridSim?: {
55
+ enabled?: boolean;
56
+ [key: string]: unknown;
57
+ } | null;
58
+ gridBounds?: {
59
+ low?: unknown;
60
+ high?: unknown;
61
+ };
62
+ orders?: {
63
+ buys?: unknown[];
64
+ sells?: unknown[];
65
+ };
66
+ storageKey?: string;
67
+ defaultPairMode?: string;
68
+ updateMarkerTsSec?: number | null;
69
+ updateMarkerNewBars?: number | null;
70
+ [key: string]: unknown;
71
+ }
72
+ declare function generateHTML(data: TvChartInput, title?: string): string;
8
73
  export { generateHTML, normalizeCandle, loadMarketProfiles, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
9
74
  //# sourceMappingURL=tradingview_uplot_chart_generator.d.ts.map
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import { MARKET_ADAPTER } from '../../modules/constants.js';
4
4
  import { escapeHtml, serializeJsonForScript, UPLOT_SHARED_SCRIPT, embedFunctionSources, uplotInlineTags } from '../chart_utils.js';
5
5
  import { cursorCSS, uplotBgCSS } from '../chart_css.js';
6
- import { zoomResetScript } from '../chart_ui.js';
6
+ import { zoomResetScript, formatTimeLabelFn } from '../chart_ui.js';
7
7
  import { normalizeCandle } from '../math_utils.js';
8
8
  import { PATHS } from '../../modules/paths.js';
9
9
  import { getStorage } from '../../modules/storage/index.js';
@@ -23,10 +23,11 @@ const RANGE_SPAN_DEFAULT = 1.55;
23
23
  function inferBaseIntervalSeconds(candles, fallback = 3600) {
24
24
  if (!Array.isArray(candles) || candles.length < 2)
25
25
  return fallback;
26
+ const rows = candles;
26
27
  const deltas = [];
27
- for (let i = 1; i < candles.length; i++) {
28
- const prev = Number(candles[i - 1]?.time);
29
- const curr = Number(candles[i]?.time);
28
+ for (let i = 1; i < rows.length; i++) {
29
+ const prev = Number(rows[i - 1]?.time);
30
+ const curr = Number(rows[i]?.time);
30
31
  if (!Number.isFinite(prev) || !Number.isFinite(curr))
31
32
  continue;
32
33
  const d = curr - prev;
@@ -52,29 +53,31 @@ function loadMarketProfiles(filePath = PATHS.PROFILES.MARKET_PROFILES_JSON) {
52
53
  }
53
54
  }
54
55
  function findMarketProfile(profiles, meta = {}) {
55
- const entries = Array.isArray(profiles?.profiles) ? profiles.profiles : [];
56
+ const container = profiles;
57
+ const entries = Array.isArray(container?.profiles) ? container.profiles : [];
56
58
  if (!entries.length)
57
59
  return null;
58
60
  const assetA = meta.assetA?.symbol || meta.assetA?.id || meta.assetA;
59
61
  const assetB = meta.assetB?.symbol || meta.assetB?.id || meta.assetB;
60
62
  const intervalSeconds = Number(meta.intervalSeconds);
61
- return entries.find((entry) => {
63
+ return (entries.find((entry) => {
62
64
  if (!entry || typeof entry !== 'object')
63
65
  return false;
66
+ const e = entry;
64
67
  if (assetA && assetB) {
65
- const matchesPair = (String(entry.assetA) === String(assetA) || String(entry.assetAId) === String(assetA))
66
- && (String(entry.assetB) === String(assetB) || String(entry.assetBId) === String(assetB));
68
+ const matchesPair = (String(e.assetA) === String(assetA) || String(e.assetAId) === String(assetA))
69
+ && (String(e.assetB) === String(assetB) || String(e.assetBId) === String(assetB));
67
70
  if (!matchesPair)
68
71
  return false;
69
72
  }
70
73
  else {
71
74
  return false;
72
75
  }
73
- if (Number.isFinite(intervalSeconds) && intervalSeconds > 0 && Number(entry.intervalSeconds) !== intervalSeconds) {
76
+ if (Number.isFinite(intervalSeconds) && intervalSeconds > 0 && Number(e.intervalSeconds) !== intervalSeconds) {
74
77
  return false;
75
78
  }
76
79
  return true;
77
- }) || null;
80
+ }) || null);
78
81
  }
79
82
  function resolveAmaDefaults({ meta, data, marketProfiles } = {}) {
80
83
  const amaDefaultsSource = MARKET_ADAPTER.AMAS.AMA3;
@@ -82,15 +85,15 @@ function resolveAmaDefaults({ meta, data, marketProfiles } = {}) {
82
85
  const profileAmaKey = profile?.defaultAma && profile.amas && profile.amas[profile.defaultAma]
83
86
  ? profile.defaultAma
84
87
  : null;
85
- const profileAma = profileAmaKey ? profile.amas[profileAmaKey] : null;
88
+ const profileAma = profileAmaKey && profile?.amas ? profile.amas[profileAmaKey] : null;
86
89
  const source = data?.amaDefaults || profileAma || amaDefaultsSource;
87
90
  return {
88
91
  erPeriod: Math.max(1, Math.round(Number(data?.amaErPeriod ?? source.erPeriod))),
89
92
  fastPeriod: Number.isFinite(Number(data?.amaFastPeriod))
90
- ? Number(data.amaFastPeriod)
93
+ ? Number(data?.amaFastPeriod)
91
94
  : Number(source.fastPeriod),
92
95
  slowPeriod: Number.isFinite(Number(data?.amaSlowPeriod))
93
- ? Number(data.amaSlowPeriod)
96
+ ? Number(data?.amaSlowPeriod)
94
97
  : Number(source.slowPeriod),
95
98
  };
96
99
  }
@@ -123,7 +126,6 @@ function generateHTML(data, title = 'TradingView Style Research') {
123
126
  ? Number(meta.intervalSeconds)
124
127
  : inferBaseIntervalSeconds(candles, 3600);
125
128
  const timeframes = [
126
- { label: '1h', seconds: 3600 },
127
129
  { label: '4h', seconds: 14400 },
128
130
  { label: '1d', seconds: 86400 },
129
131
  { label: '1w', seconds: 604800 },
@@ -230,8 +232,8 @@ function generateHTML(data, title = 'TradingView Style Research') {
230
232
  orderBuys: Array.isArray(data.orders?.buys) ? data.orders.buys.map(Number).filter(Number.isFinite) : [],
231
233
  orderSells: Array.isArray(data.orders?.sells) ? data.orders.sells.map(Number).filter(Number.isFinite) : [],
232
234
  gridBounds: {
233
- low: Number.isFinite(Number(data.gridBounds?.low)) && Number(data.gridBounds.low) > 0 ? Number(data.gridBounds.low) : null,
234
- high: Number.isFinite(Number(data.gridBounds?.high)) && Number(data.gridBounds.high) > 0 ? Number(data.gridBounds.high) : null,
235
+ low: Number.isFinite(Number(data.gridBounds?.low)) && Number(data.gridBounds?.low) > 0 ? Number(data.gridBounds?.low) : null,
236
+ high: Number.isFinite(Number(data.gridBounds?.high)) && Number(data.gridBounds?.high) > 0 ? Number(data.gridBounds?.high) : null,
235
237
  },
236
238
  updateMarkerTsSec: Number(data.updateMarkerTsSec) > 0 ? Number(data.updateMarkerTsSec) : null,
237
239
  updateMarkerNewBars: Number(data.updateMarkerNewBars) || null,
@@ -246,7 +248,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
246
248
  poolLabel,
247
249
  intervalLabel,
248
250
  amaDefaultsSource: marketProfiles ? 'market_profiles' : 'constants',
249
- volumeIsCount: !!(meta?.feed),
251
+ volumeIsCount: !!meta?.feed,
250
252
  };
251
253
  return `<!doctype html>
252
254
  <html lang="en">
@@ -1002,23 +1004,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
1002
1004
  const d = new Date(ts * 1000);
1003
1005
  return d.toLocaleString(undefined, { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
1004
1006
  }
1005
- function pad2(n) {
1006
- return String(n).padStart(2, '0');
1007
- }
1008
- function formatTimeLabel(tsSec, spanSec) {
1009
- const d = new Date(tsSec * 1000);
1010
- if (!Number.isFinite(spanSec)) spanSec = 0;
1011
- if (spanSec >= 365 * 24 * 3600 * 2) {
1012
- return String(d.getUTCFullYear());
1013
- }
1014
- if (spanSec >= 90 * 24 * 3600) {
1015
- return d.toLocaleString(undefined, { month: 'short', year: 'numeric', timeZone: 'UTC' });
1016
- }
1017
- if (spanSec >= 14 * 24 * 3600) {
1018
- return d.toLocaleString(undefined, { month: 'short', day: '2-digit', timeZone: 'UTC' });
1019
- }
1020
- return d.toLocaleString(undefined, { month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' });
1021
- }
1007
+ ${formatTimeLabelFn({ dateTimeSep: ', ', padDay: true })}
1022
1008
  function makeTimeAxis(showLabels) {
1023
1009
  return {
1024
1010
  show: true,
@@ -1,102 +1,2 @@
1
- import { type HuberScaleMode, type HuberEstimator } from './huber_scale_variants.js';
2
- type Candle = {
3
- time: number;
4
- open: number;
5
- high: number;
6
- low: number;
7
- close: number;
8
- volume: number;
9
- };
10
- type AmaDef = {
11
- name: string;
12
- er: number;
13
- fast: number;
14
- slow: number;
15
- };
16
- declare function parseArgs(): {
17
- dataPath: string;
18
- amaName: string;
19
- er: number | null;
20
- fast: number | null;
21
- slow: number | null;
22
- lookbacks: number[];
23
- priceThresholdPct: number;
24
- slopeThresholdFactor: number;
25
- slopeEnabled: boolean;
26
- slopePersistBars: number;
27
- confirmFraction: number;
28
- whipsawBars: number;
29
- scaleMode: HuberScaleMode;
30
- truthWindowBars: number | null;
31
- forwardWindowBars: number | null;
32
- outPath: string | null;
33
- };
34
- declare function loadCandles(input: string): {
35
- candles: Candle[];
36
- meta: any;
37
- files: number;
38
- };
39
- /**
40
- * Cross-correlation peak lag between the causal signal and a reference.
41
- * Returns the smallest non-negative k maximising corr(sig[t], ref[t-k]).
42
- * A positive lag means `sig` trails `ref` by k bars (the smoother's group delay).
43
- */
44
- declare function crossCorrelationLag(sig: (number | null)[], ref: (number | null)[], maxLag: number): {
45
- lagBars: number;
46
- corr: number | null;
47
- };
48
- /**
49
- * Median bars between a sign flip in the centred reference slope and the first
50
- * bar the causal slope confirms the new direction at or above `confirmPct`.
51
- * `misses` counts flips the causal slope never confirmed inside the window.
52
- */
53
- declare function reversalLag(sig: (number | null)[], ref: (number | null)[], maxLag: number, confirmPct: number): {
54
- lagBars: number | null;
55
- flips: number;
56
- misses: number;
57
- samples: number;
58
- };
59
- declare function analyzeLookback(closes: number[], amaValues: number[], lookbackBars: number, amaDef: AmaDef, cfg: ReturnType<typeof parseArgs>, truthArr: (number | null)[], priceTruthArr: (number | null)[], truthHalf: number, estimator?: HuberEstimator): {
60
- lookbackBars: number;
61
- huberScaleMode: HuberScaleMode;
62
- meanOutlierFractionPct: number | null;
63
- meanHuberScale: number | null;
64
- priceLagBars: number;
65
- priceLagCorr: number | null;
66
- amaLagBars: number;
67
- amaLagCorr: number | null;
68
- reversalLagBars: number | null;
69
- reversalFlips: number;
70
- reversalMisses: number;
71
- resets: number;
72
- resetsTotal: number;
73
- priceResets: number;
74
- slopeResets: number;
75
- resetsPerDay: number;
76
- avgBarsBetweenResets: number | null;
77
- medianBarsBetweenResets: number | null;
78
- p90BarsBetweenResets: number | null;
79
- minBarsBetweenResets: number | null;
80
- whipsawResets: number;
81
- whipsawPct: number;
82
- gridAgeSinceLastResetBars: number | null;
83
- meanAbsSlopePct: number;
84
- slopeStdPct: number;
85
- slopeWobblePct: number;
86
- secondDiffEnergy: number;
87
- zeroCrossPer1k: number;
88
- saturationPct: number;
89
- neutralPct: number;
90
- avgAbsRangeOffset: number;
91
- offsetActivePct: number;
92
- forwardWindowBars: number;
93
- rangeWrongWayPct: number | null;
94
- rangeTiltActivePct: number | null;
95
- meanWrongStreakBars: number | null;
96
- medianAdverseMoveWhileWrongPct: number | null;
97
- p90AdverseMoveWhileWrongPct: number | null;
98
- warmupBars: number;
99
- finiteSlopeBars: number;
100
- };
101
- export { loadCandles, crossCorrelationLag, reversalLag, analyzeLookback };
1
+ export {};
102
2
  //# sourceMappingURL=backtest_ama_slope_huber.d.ts.map
@@ -42,12 +42,13 @@ import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strate
42
42
  import { computeAmaSlopeClipThreshold } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
43
43
  import { createHuberEstimator } from './huber_scale_variants.js';
44
44
  import { simulateGridResetSeries, GRID_RESET_BOOTSTRAP } from '../tradingview/grid_reset_sim.js';
45
- import { normalizeCandle, range } from '../math_utils.js';
45
+ import { range, median, percentile, fmtNum as fmt, loadCandleSeries } from '../math_utils.js';
46
46
  import { parseListOrRange } from '../bot_fitting/shared_utils.js';
47
+ import { printHelpHeader, helpRow } from '../analyze_args.js';
47
48
  import { getStorage } from '../../modules/storage/index.js';
48
49
  import { PATHS } from '../../modules/paths.js';
49
50
  import { MARKET_ADAPTER } from '../../modules/constants.js';
50
- const { readJSON, writeJSON } = getStorage();
51
+ const { writeJSON } = getStorage();
51
52
  const MA = MARKET_ADAPTER;
52
53
  // ─── CLI ─────────────────────────────────────────────────────────────────────
53
54
  /**
@@ -175,25 +176,21 @@ function parseArgs() {
175
176
  return out;
176
177
  }
177
178
  function printHelp() {
178
- console.log('AMA-Slope-Huber lookback backtest');
179
- console.log('');
180
- console.log('Usage: node dist/analysis/trend_detection/backtest_ama_slope_huber.js [options]');
181
- console.log('');
182
- console.log('Options:');
183
- console.log(' --data <path> LP candle file or shard directory (required)');
184
- console.log(` --ama <AMA1..AMA4> Built-in AMA preset (default: ${MA.DEFAULT_AMA_KEY})`);
185
- console.log(' --er/--fast/--slow <n> Override AMA periods (override --ama)');
186
- console.log(' --lookback <spec> Lookback sweep in bars (default: 28h,26h,...,8h; also accepts 28:8:2 or 8:28:2)');
187
- console.log(` --price-threshold <pct> Drift reset threshold (default: ${MA.AMA_DELTA_THRESHOLD_PERCENT})`);
188
- console.log(` --slope-threshold-factor <n> % of max slope for the slope reset (default: ${MA.AMA_SLOPE_DELTA_THRESHOLD_PERCENT})`);
189
- console.log(` --slope-persist <bars> Bars the slope delta must persist before resetting (default: ${MA.AMA_SLOPE_PERSIST_BARS})`);
190
- console.log(' --no-slope Disable the slope-delta reset (drift only)');
191
- console.log(' --confirm <frac> Slope confirmation size as a fraction of max slope (default: 0.25)');
192
- console.log(' --scale-mode <mode> Huber scale estimate: none (production) | df | mscale (default: none)');
193
- console.log(' --whipsaw <bars> Back-to-back reset gap counted as a whipsaw (default: 3)');
194
- console.log(' --truth-window <bars> Centred reference half-window (default: max lookback)');
195
- console.log(' --forward-window <bars> Realized forward horizon for range tilt direction (default: lookback)');
196
- console.log(' --out <path> JSON output path');
179
+ printHelpHeader('AMA-Slope-Huber lookback backtest', 'trend_detection/backtest_ama_slope_huber.js');
180
+ console.log(helpRow('--data <path>', 'LP candle file or shard directory (required)', 29));
181
+ console.log(helpRow('--ama <AMA1..AMA4>', `Built-in AMA preset (default: ${MA.DEFAULT_AMA_KEY})`, 29));
182
+ console.log(helpRow('--er/--fast/--slow <n>', 'Override AMA periods (override --ama)', 29));
183
+ console.log(helpRow('--lookback <spec>', 'Lookback sweep in bars (default: 28h,26h,...,8h; also accepts 28:8:2 or 8:28:2)', 29));
184
+ console.log(helpRow('--price-threshold <pct>', `Drift reset threshold (default: ${MA.AMA_DELTA_THRESHOLD_PERCENT})`, 29));
185
+ console.log(helpRow('--slope-threshold-factor <n>', `% of max slope for the slope reset (default: ${MA.AMA_SLOPE_DELTA_THRESHOLD_PERCENT})`, 29));
186
+ console.log(helpRow('--slope-persist <bars>', `Bars the slope delta must persist before resetting (default: ${MA.AMA_SLOPE_PERSIST_BARS})`, 29));
187
+ console.log(helpRow('--no-slope', 'Disable the slope-delta reset (drift only)', 29));
188
+ console.log(helpRow('--confirm <frac>', 'Slope confirmation size as a fraction of max slope (default: 0.25)', 29));
189
+ console.log(helpRow('--scale-mode <mode>', 'Huber scale estimate: none (production) | df | mscale (default: none)', 29));
190
+ console.log(helpRow('--whipsaw <bars>', 'Back-to-back reset gap counted as a whipsaw (default: 3)', 29));
191
+ console.log(helpRow('--truth-window <bars>', 'Centred reference half-window (default: max lookback)', 29));
192
+ console.log(helpRow('--forward-window <bars>', 'Realized forward horizon for range tilt direction (default: lookback)', 29));
193
+ console.log(helpRow('--out <path>', 'JSON output path', 29));
197
194
  }
198
195
  function resolveAma(cfg) {
199
196
  if (cfg.er != null || cfg.fast != null || cfg.slow != null) {
@@ -209,61 +206,7 @@ function resolveAma(cfg) {
209
206
  return { name: cfg.amaName, er: preset.erPeriod, fast: preset.fastPeriod, slow: preset.slowPeriod };
210
207
  }
211
208
  // ─── Data loading ────────────────────────────────────────────────────────────
212
- function loadCandles(input) {
213
- const resolved = path.resolve(input);
214
- if (!fs.existsSync(resolved))
215
- throw new Error(`Data path not found: ${resolved}`);
216
- const stat = fs.statSync(resolved);
217
- const files = stat.isDirectory()
218
- ? fs.readdirSync(resolved)
219
- .filter((name) => /\.json$/i.test(name) && !/manifest/i.test(name))
220
- .map((name) => path.join(resolved, name))
221
- .sort()
222
- : [resolved];
223
- const byTime = new Map();
224
- let meta = null;
225
- for (const file of files) {
226
- let raw;
227
- try {
228
- raw = readJSON(file);
229
- }
230
- catch {
231
- continue;
232
- }
233
- const arr = Array.isArray(raw?.candles) ? raw.candles : (Array.isArray(raw) ? raw : null);
234
- if (!arr || arr.length === 0)
235
- continue;
236
- if (!meta && raw?.meta)
237
- meta = raw.meta;
238
- for (const c of arr) {
239
- const n = normalizeCandle(c);
240
- if (n)
241
- byTime.set(n.time, { time: n.time, open: n.open, high: n.high, low: n.low, close: n.close, volume: n.volume });
242
- }
243
- }
244
- const candles = [...byTime.values()].sort((a, b) => a.time - b.time);
245
- if (candles.length === 0)
246
- throw new Error(`No candles found under ${resolved}`);
247
- return { candles, meta, files: files.length };
248
- }
249
- // ─── Small stats helpers ─────────────────────────────────────────────────────
250
- function median(values) {
251
- if (values.length === 0)
252
- return null;
253
- const s = values.slice().sort((a, b) => a - b);
254
- const mid = s.length >> 1;
255
- return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
256
- }
257
- function percentile(values, pct) {
258
- if (values.length === 0)
259
- return null;
260
- const s = values.slice().sort((a, b) => a - b);
261
- const idx = Math.min(s.length - 1, Math.max(0, Math.round((pct / 100) * (s.length - 1))));
262
- return s[idx];
263
- }
264
- function fmt(x, d = 2) {
265
- return Number.isFinite(Number(x)) ? Number(x).toFixed(d) : 'n/a';
266
- }
209
+ // File/directory shard loading lives in math_utils.loadCandleSeries.
267
210
  // ─── Lag estimators ──────────────────────────────────────────────────────────
268
211
  /**
269
212
  * Cross-correlation peak lag between the causal signal and a reference.
@@ -435,7 +378,7 @@ function analyzeLookback(closes, amaValues, lookbackBars, amaDef, cfg, truthArr,
435
378
  const rev = reversalLag(slopeSeries, truthArr, revMaxLag, confirmPct);
436
379
  // ── Reset metrics ───────────────────────────────────────────────────────
437
380
  const resetEvents = sim.events.filter((e) => e.reason !== GRID_RESET_BOOTSTRAP);
438
- const resetIdx = resetEvents.map((e) => e.index);
381
+ const resetIdx = resetEvents.map((e) => Number(e.index));
439
382
  const gaps = [];
440
383
  for (let k = 1; k < resetIdx.length; k++)
441
384
  gaps.push(resetIdx[k] - resetIdx[k - 1]);
@@ -451,7 +394,7 @@ function analyzeLookback(closes, amaValues, lookbackBars, amaDef, cfg, truthArr,
451
394
  const forwardWindowBars = Number.isFinite(forwardWindowCfg) && forwardWindowCfg > 0
452
395
  ? Math.round(forwardWindowCfg)
453
396
  : Math.max(1, lookbackBars);
454
- const eventIdx = new Set(sim.events.map((e) => e.index));
397
+ const eventIdx = new Set(sim.events.map((e) => Number(e.index)));
455
398
  let curAppliedDir = 0;
456
399
  let evaluatedBars = 0, tiltActiveBars = 0, wrongWayBars = 0;
457
400
  let curWrongStreak = 0;
@@ -519,7 +462,7 @@ function analyzeLookback(closes, amaValues, lookbackBars, amaDef, cfg, truthArr,
519
462
  resetsPerDay,
520
463
  avgBarsBetweenResets: gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : null,
521
464
  medianBarsBetweenResets: median(gaps),
522
- p90BarsBetweenResets: percentile(gaps, 90),
465
+ p90BarsBetweenResets: percentile(gaps, 90, { interpolation: 'nearest' }),
523
466
  minBarsBetweenResets: gaps.length > 0 ? Math.min(...gaps) : null,
524
467
  whipsawResets: whipsaws,
525
468
  whipsawPct: gaps.length > 0 ? (whipsaws / gaps.length) * 100 : 0,
@@ -540,7 +483,7 @@ function analyzeLookback(closes, amaValues, lookbackBars, amaDef, cfg, truthArr,
540
483
  rangeTiltActivePct: evaluatedBars > 0 ? (tiltActiveBars / evaluatedBars) * 100 : null,
541
484
  meanWrongStreakBars: wrongStreaks.length > 0 ? wrongStreaks.reduce((a, b) => a + b, 0) / wrongStreaks.length : null,
542
485
  medianAdverseMoveWhileWrongPct: median(adverseMoves),
543
- p90AdverseMoveWhileWrongPct: percentile(adverseMoves, 90),
486
+ p90AdverseMoveWhileWrongPct: percentile(adverseMoves, 90, { interpolation: 'nearest' }),
544
487
  // context
545
488
  warmupBars,
546
489
  finiteSlopeBars: finite,
@@ -572,7 +515,7 @@ function addCompositeScore(results) {
572
515
  function run() {
573
516
  const cfg = parseArgs();
574
517
  const amaDef = resolveAma(cfg);
575
- const { candles, meta, files } = loadCandles(cfg.dataPath);
518
+ const { candles, meta, files } = loadCandleSeries(cfg.dataPath);
576
519
  const closes = candles.map((c) => c.close);
577
520
  const n = closes.length;
578
521
  const amaValues = calculateAMA(closes, { erPeriod: amaDef.er, fastPeriod: amaDef.fast, slowPeriod: amaDef.slow });
@@ -597,7 +540,7 @@ function run() {
597
540
  console.log(' AMA-SLOPE-HUBER LOOKBACK BACKTEST');
598
541
  console.log('================================================================================');
599
542
  console.log(` Data: ${path.resolve(cfg.dataPath)}`);
600
- console.log(` ${files} file(s), ${n} candles, ${((n * (meta?.intervalSeconds ?? 3600)) / 86400).toFixed(0)} days`);
543
+ console.log(` ${files} file(s), ${n} candles, ${((n * Number(meta?.intervalSeconds ?? 3600)) / 86400).toFixed(0)} days`);
601
544
  console.log(` AMA: ${amaDef.name} (er=${amaDef.er}, fast=${amaDef.fast}, slow=${amaDef.slow}), warmup ${warmupBars} bars`);
602
545
  console.log(` Lookbacks: ${cfg.lookbacks.join(', ')} bars (${cfg.lookbacks.length} windows)`);
603
546
  console.log(` Resets: drift >= ${cfg.priceThresholdPct}% | slope delta >= ${fmt((cfg.slopeThresholdFactor / 100) * MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT, 4)}%/bar` +
@@ -666,7 +609,7 @@ function run() {
666
609
  `${fmt(r.p90AdverseMoveWhileWrongPct, 2).padStart(10)}`);
667
610
  }
668
611
  // ── Sweet spot (heuristic) ──────────────────────────────────────────────
669
- const ranked = results.slice().sort((a, b) => b.compositeScore - a.compositeScore);
612
+ const ranked = results.slice().sort((a, b) => (b.compositeScore ?? 0) - (a.compositeScore ?? 0));
670
613
  const winner = ranked[0];
671
614
  console.log('\n================================================================================');
672
615
  console.log(' HEURISTIC SWEET SPOT');
@@ -721,5 +664,4 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
721
664
  process.exit(1);
722
665
  }
723
666
  }
724
- export { loadCandles, crossCorrelationLag, reversalLag, analyzeLookback };
725
667
  //# sourceMappingURL=backtest_ama_slope_huber.js.map