dexbot 1.6.10 → 1.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/CHANGELOG.md +50 -3
  2. package/README.md +3 -1
  3. package/analysis/README.md +51 -11
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +3 -3
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  9. package/claw/modules/chain_broadcast.ts +7 -1
  10. package/claw/modules/claw_launcher.ts +1 -1
  11. package/claw/modules/launcher_mode_detector.ts +9 -2
  12. package/claw/package.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  14. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  15. package/dist/analysis/account_resolver.d.ts +1 -1
  16. package/dist/analysis/account_resolver.js +15 -2
  17. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  18. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  19. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  24. package/dist/analysis/analyze_args.d.ts +31 -0
  25. package/dist/analysis/analyze_args.js +41 -0
  26. package/dist/analysis/analyze_dynamic_weight.js +7 -20
  27. package/dist/analysis/analyze_kalman.js +7 -17
  28. package/dist/analysis/analyze_regime.js +7 -17
  29. package/dist/analysis/analyze_regime_windows.js +8 -18
  30. package/dist/analysis/analyze_risk_profile.js +8 -18
  31. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  32. package/dist/analysis/analyze_volatility.js +7 -17
  33. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  34. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
  35. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  36. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
  37. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  38. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  39. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  40. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  41. package/dist/analysis/bot_key_utils.d.ts +18 -10
  42. package/dist/analysis/bot_key_utils.js +10 -17
  43. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  44. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  45. package/dist/analysis/chain_pool.d.ts +3 -1
  46. package/dist/analysis/chart_ui.d.ts +5 -2
  47. package/dist/analysis/chart_ui.js +6 -3
  48. package/dist/analysis/chart_utils.d.ts +5 -5
  49. package/dist/analysis/chart_utils.js +9 -0
  50. package/dist/analysis/fills_cache.d.ts +64 -0
  51. package/dist/analysis/fills_cache.js +254 -0
  52. package/dist/analysis/fills_source.d.ts +2 -2
  53. package/dist/analysis/fills_source.js +19 -14
  54. package/dist/analysis/grid_correction_check.d.ts +1 -1
  55. package/dist/analysis/grid_correction_check.js +12 -11
  56. package/dist/analysis/math_utils.d.ts +7 -6
  57. package/dist/analysis/math_utils.js +5 -8
  58. package/dist/analysis/pnl_report.d.ts +39 -0
  59. package/dist/analysis/pnl_report.js +325 -0
  60. package/dist/analysis/price_sources.d.ts +8 -8
  61. package/dist/analysis/price_sources.js +5 -4
  62. package/dist/analysis/resolve_bot_accounts.js +2 -2
  63. package/dist/analysis/resolve_source.d.ts +1 -2
  64. package/dist/analysis/trade_profitability.d.ts +32 -2
  65. package/dist/analysis/trade_profitability.js +232 -106
  66. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  67. package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
  68. package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
  69. package/dist/analysis/tradingview/grid_reset_config.js +35 -6
  70. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
  71. package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
  72. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  73. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
  74. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  75. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  76. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  77. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
  78. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
  79. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  80. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  81. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  82. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  83. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  84. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  85. package/dist/credential-daemon.js +34 -20
  86. package/dist/dexbot.js +17 -14
  87. package/dist/market_adapter/candle_utils.d.ts +22 -18
  88. package/dist/market_adapter/candle_utils.js +24 -20
  89. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  90. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  91. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  92. package/dist/market_adapter/core/kibana_candles.js +9 -7
  93. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  94. package/dist/market_adapter/core/kibana_client.js +8 -7
  95. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  96. package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
  97. package/dist/market_adapter/core/market_adapter_service.js +184 -101
  98. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  99. package/dist/market_adapter/core/strategies/ama.js +7 -32
  100. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  101. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  102. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  103. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  104. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  106. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
  107. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
  108. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  109. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  110. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  111. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  112. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  113. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  114. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  115. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  116. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  117. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  118. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
  119. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  120. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  121. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  122. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  123. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  124. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  125. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  126. package/dist/market_adapter/inputs/window_cache.js +8 -8
  127. package/dist/market_adapter/interval_utils.d.ts +4 -4
  128. package/dist/market_adapter/log_format.d.ts +6 -6
  129. package/dist/market_adapter/log_format.js +28 -22
  130. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  131. package/dist/market_adapter/lp_chart_core.js +26 -192
  132. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  133. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  134. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  135. package/dist/market_adapter/market_adapter.d.ts +94 -33
  136. package/dist/market_adapter/market_adapter.js +69 -75
  137. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  138. package/dist/market_adapter/utils/adapter_client.js +2 -2
  139. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  140. package/dist/market_adapter/utils/chain.d.ts +50 -41
  141. package/dist/market_adapter/utils/chain.js +40 -46
  142. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  143. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  144. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  145. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  146. package/dist/market_adapter/utils/file_lock.js +36 -32
  147. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  148. package/dist/market_adapter/utils/native_history.js +35 -28
  149. package/dist/modules/account_bots.d.ts +577 -21
  150. package/dist/modules/account_bots.js +182 -158
  151. package/dist/modules/account_orders.d.ts +66 -30
  152. package/dist/modules/account_orders.js +22 -20
  153. package/dist/modules/authority_resolver.d.ts +12 -2
  154. package/dist/modules/authority_resolver.js +15 -8
  155. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  156. package/dist/modules/bitshares-native/chain_client.js +45 -46
  157. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  158. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  159. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  160. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  161. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  162. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  163. package/dist/modules/bitshares-native/index.d.ts +1 -1
  164. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  165. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  166. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  167. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  168. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  169. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  170. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  171. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  172. package/dist/modules/bitshares-native/serial/types.js +55 -62
  173. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  174. package/dist/modules/bitshares-native/signing_client.js +19 -14
  175. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  176. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  177. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  178. package/dist/modules/bitshares-native/transport.js +5 -4
  179. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  180. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  181. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  182. package/dist/modules/bitshares_client.d.ts +45 -13
  183. package/dist/modules/bitshares_client.js +28 -19
  184. package/dist/modules/bot_defaults.d.ts +6 -15
  185. package/dist/modules/bot_defaults.js +1 -5
  186. package/dist/modules/bot_settings.d.ts +44 -10
  187. package/dist/modules/bot_settings.js +11 -8
  188. package/dist/modules/bots_file_lock.d.ts +6 -6
  189. package/dist/modules/bots_file_lock.js +16 -12
  190. package/dist/modules/broadcast_failure.d.ts +2 -2
  191. package/dist/modules/broadcast_failure.js +5 -4
  192. package/dist/modules/chain_keys.d.ts +42 -40
  193. package/dist/modules/chain_keys.js +53 -45
  194. package/dist/modules/chain_orders.d.ts +93 -59
  195. package/dist/modules/chain_orders.js +31 -23
  196. package/dist/modules/constants.d.ts +530 -32
  197. package/dist/modules/constants.js +52 -60
  198. package/dist/modules/cr_planner.d.ts +40 -2
  199. package/dist/modules/credential_policy.d.ts +68 -8
  200. package/dist/modules/credential_policy.js +37 -31
  201. package/dist/modules/credential_session_cache.d.ts +2 -2
  202. package/dist/modules/credit_pricing.d.ts +42 -6
  203. package/dist/modules/credit_pricing.js +44 -30
  204. package/dist/modules/credit_runtime.d.ts +276 -118
  205. package/dist/modules/credit_runtime.js +462 -165
  206. package/dist/modules/crypto/browser_provider.js +6 -4
  207. package/dist/modules/crypto/node_provider.js +1 -1
  208. package/dist/modules/crypto/pure_scrypt.js +35 -4
  209. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  210. package/dist/modules/crypto/sync.d.ts +9 -9
  211. package/dist/modules/crypto/sync.js +16 -9
  212. package/dist/modules/dexbot_class.d.ts +195 -139
  213. package/dist/modules/dexbot_class.js +78 -28
  214. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  215. package/dist/modules/dexbot_cow_runtime.js +248 -206
  216. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  217. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  218. package/dist/modules/dexbot_fill_runtime.js +48 -41
  219. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  220. package/dist/modules/dexbot_maintenance_runtime.js +117 -80
  221. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  222. package/dist/modules/dexbot_startup_runtime.js +43 -43
  223. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  224. package/dist/modules/dexbot_state_recovery.js +18 -13
  225. package/dist/modules/fund_registry.d.ts +4 -2
  226. package/dist/modules/fund_registry.js +10 -10
  227. package/dist/modules/general_settings.d.ts +30 -4
  228. package/dist/modules/graceful_shutdown.d.ts +3 -3
  229. package/dist/modules/graceful_shutdown.js +2 -2
  230. package/dist/modules/grid_price_source.d.ts +1 -1
  231. package/dist/modules/key_store.d.ts +14 -8
  232. package/dist/modules/key_store.js +7 -6
  233. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  234. package/dist/modules/launcher/adapter_requirement.js +5 -5
  235. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  236. package/dist/modules/launcher/bot_supervisor.js +12 -11
  237. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  238. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  239. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  240. package/dist/modules/launcher/credential_daemon.js +2 -2
  241. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  242. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  243. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  244. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  245. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  246. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  247. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  248. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  249. package/dist/modules/launcher/supervisor_control.js +4 -2
  250. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  251. package/dist/modules/market_adapter_whitelist.js +15 -3
  252. package/dist/modules/node_manager.d.ts +41 -11
  253. package/dist/modules/node_manager.js +5 -4
  254. package/dist/modules/order/accounting.d.ts +53 -24
  255. package/dist/modules/order/accounting.js +40 -14
  256. package/dist/modules/order/async_lock.d.ts +5 -2
  257. package/dist/modules/order/async_lock.js +1 -1
  258. package/dist/modules/order/export.d.ts +7 -6
  259. package/dist/modules/order/export.js +1 -7
  260. package/dist/modules/order/format.d.ts +39 -19
  261. package/dist/modules/order/format.js +62 -16
  262. package/dist/modules/order/genesis_policy.d.ts +21 -18
  263. package/dist/modules/order/genesis_policy.js +12 -8
  264. package/dist/modules/order/grid.d.ts +142 -36
  265. package/dist/modules/order/grid.js +148 -123
  266. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  267. package/dist/modules/order/grid_reconcile.js +13 -12
  268. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  269. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  270. package/dist/modules/order/index.d.ts +263 -1
  271. package/dist/modules/order/logger.d.ts +45 -11
  272. package/dist/modules/order/logger.js +38 -40
  273. package/dist/modules/order/logger_state.d.ts +4 -4
  274. package/dist/modules/order/manager.d.ts +226 -180
  275. package/dist/modules/order/manager.js +101 -83
  276. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  277. package/dist/modules/order/processed_fill_store.js +16 -27
  278. package/dist/modules/order/strategy.d.ts +21 -13
  279. package/dist/modules/order/strategy.js +5 -6
  280. package/dist/modules/order/sync_engine.d.ts +91 -33
  281. package/dist/modules/order/sync_engine.js +99 -54
  282. package/dist/modules/order/utils/math.d.ts +157 -102
  283. package/dist/modules/order/utils/math.js +77 -38
  284. package/dist/modules/order/utils/order.d.ts +326 -106
  285. package/dist/modules/order/utils/order.js +200 -99
  286. package/dist/modules/order/utils/slot.d.ts +1 -1
  287. package/dist/modules/order/utils/system.d.ts +176 -26
  288. package/dist/modules/order/utils/system.js +86 -69
  289. package/dist/modules/order/utils/validate.d.ts +89 -41
  290. package/dist/modules/order/utils/validate.js +24 -22
  291. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  292. package/dist/modules/order/utils/withPoolRef.js +18 -12
  293. package/dist/modules/order/working_grid.d.ts +14 -13
  294. package/dist/modules/paths.d.ts +3 -4
  295. package/dist/modules/paths.js +3 -27
  296. package/dist/modules/process_discovery.d.ts +1 -1
  297. package/dist/modules/process_discovery.js +2 -1
  298. package/dist/modules/runtime.d.ts +7 -3
  299. package/dist/modules/runtime.js +4 -3
  300. package/dist/modules/runtime_settings.d.ts +15 -10
  301. package/dist/modules/runtime_settings.js +30 -24
  302. package/dist/modules/settings_merge.d.ts +29 -3
  303. package/dist/modules/settings_merge.js +56 -78
  304. package/dist/modules/socket_json_client.d.ts +7 -4
  305. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  306. package/dist/modules/storage/browser_adapter.js +7 -30
  307. package/dist/modules/storage/index.d.ts +1 -1
  308. package/dist/modules/storage/node_adapter.d.ts +45 -27
  309. package/dist/modules/storage/node_adapter.js +9 -9
  310. package/dist/modules/storage/types.d.ts +5 -4
  311. package/dist/modules/types.d.ts +1071 -2
  312. package/dist/modules/types.js +4 -1
  313. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  314. package/dist/modules/utils/asset_symbols.js +2 -1
  315. package/dist/modules/utils/errors.d.ts +9 -0
  316. package/dist/modules/utils/errors.js +23 -1
  317. package/dist/modules/utils/time_range.d.ts +4 -0
  318. package/dist/modules/utils/time_range.js +18 -0
  319. package/dist/modules/validate_profiles.js +53 -43
  320. package/dist/modules/version_notice.d.ts +14 -3
  321. package/dist/modules/version_notice.js +6 -4
  322. package/dist/pm2.d.ts +29 -27
  323. package/dist/pm2.js +5 -5
  324. package/dist/scripts/analyze-credit.d.ts +2 -1
  325. package/dist/scripts/analyze-credit.js +23 -24
  326. package/dist/scripts/analyze-orders.d.ts +77 -9
  327. package/dist/scripts/analyze-orders.js +66 -84
  328. package/dist/scripts/chart_command.d.ts +27 -18
  329. package/dist/scripts/chart_command.js +16 -15
  330. package/dist/scripts/check_any.d.ts +18 -0
  331. package/dist/scripts/check_any.js +126 -0
  332. package/dist/scripts/diagnose-pool-history.js +12 -7
  333. package/dist/scripts/pnl.d.ts +3 -0
  334. package/dist/scripts/pnl.js +40 -0
  335. package/dist/scripts/print_grid.js +0 -1
  336. package/dist/scripts/run-tests.js +39 -7
  337. package/dist/scripts/runner.js +1 -1
  338. package/dist/scripts/test-credit-renewal.js +30 -21
  339. package/dist/scripts/update.d.ts +10 -5
  340. package/dist/scripts/update.js +168 -103
  341. package/dist/scripts/update_dist_freshness.js +1 -0
  342. package/dist/scripts/update_layout.d.ts +61 -0
  343. package/dist/scripts/update_layout.js +180 -0
  344. package/dist/scripts/validate_bots.js +2 -1
  345. package/dist/scripts/verify-browser-bundle.js +8 -0
  346. package/dist/unlock.d.ts +28 -3
  347. package/dist/unlock.js +72 -10
  348. package/docs/BITSHARES_ONBOARDING.md +2 -0
  349. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  350. package/docs/COW_INVARIANTS.md +13 -6
  351. package/docs/DEXBOT_COMPARISON.md +8 -8
  352. package/docs/EVOLUTION.md +12 -10
  353. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  354. package/docs/GRID_RECALCULATION.md +15 -16
  355. package/docs/GRID_RECONCILE.md +14 -3
  356. package/docs/LIFECYCLE.md +11 -11
  357. package/docs/MPA_CREDIT_USAGE.md +22 -3
  358. package/docs/README.md +15 -4
  359. package/docs/WORKFLOW.md +1 -0
  360. package/docs/architecture.md +12 -9
  361. package/docs/developer_guide.md +6 -6
  362. package/market_adapter/README.md +9 -26
  363. package/modules/README.md +4 -1
  364. package/package.json +4 -1
  365. package/scripts/README.md +14 -0
@@ -0,0 +1,725 @@
1
+ 'use strict';
2
+ /**
3
+ * AMA-SLOPE-HUBER LOOKBACK BACKTEST
4
+ *
5
+ * Sweeps the Huber slope lookback window (MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS,
6
+ * exposed as `lb` in the dynamic-weight research chart) from a low bound to a
7
+ * high bound and reports the metrics that actually differ between windows:
8
+ *
9
+ * LAG — how late the causal slope signal confirms a regime change,
10
+ * measured two ways:
11
+ * priceLag cross-correlation peak vs a centred slope of close
12
+ * (total pipeline lag: AMA smoothing + slope window)
13
+ * amaLag cross-correlation peak vs a centred slope of AMA
14
+ * (slope-window group delay only)
15
+ * revLag median bars from a sign flip in the centred AMA
16
+ * slope until the causal slope confirms the new sign
17
+ * RESETS — the market adapter's two grid-recentering triggers (drift ratchet
18
+ * + slope-delta, whitelist-gated), replayed bar-by-bar through the
19
+ * canonical `simulateGridResetSeries`: count, reason split, rate,
20
+ * gap distribution and whipsaw (back-to-back) resets
21
+ * NOISE — slope standard deviation, bar-to-bar wobble (mean |Δslope|),
22
+ * second-difference energy, zero-crossing rate, saturation and
23
+ * neutral-zone occupancy, average absolute range tilt
24
+ *
25
+ * The reset replay uses the UNCLIPPED slope (clip only feeds the range tilt, it
26
+ * never moves reset timing — see grid_reset_sim.ts), so `clipPercentile` is
27
+ * passed as 0 for speed and the tilt metric is derived from the batch clip
28
+ * threshold instead. Everything else is the production decision path.
29
+ *
30
+ * Data may be a single LP candle JSON or a directory of month shards
31
+ * (market_adapter/data/lp/<pair>/) — shards are concatenated and de-duplicated
32
+ * by timestamp, so overlapping chunk files are harmless.
33
+ *
34
+ * Usage:
35
+ * node dist/analysis/trend_detection/backtest_ama_slope_huber.js \
36
+ * --data market_adapter/data/lp/<market-pair> [--lookback 8:28:2]
37
+ */
38
+ import fs from 'node:fs';
39
+ import path from 'node:path';
40
+ import { pathToFileURL } from 'node:url';
41
+ import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
42
+ import { computeAmaSlopeClipThreshold } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
43
+ import { createHuberEstimator } from './huber_scale_variants.js';
44
+ import { simulateGridResetSeries, GRID_RESET_BOOTSTRAP } from '../tradingview/grid_reset_sim.js';
45
+ import { normalizeCandle, range } from '../math_utils.js';
46
+ import { parseListOrRange } from '../bot_fitting/shared_utils.js';
47
+ import { getStorage } from '../../modules/storage/index.js';
48
+ import { PATHS } from '../../modules/paths.js';
49
+ import { MARKET_ADAPTER } from '../../modules/constants.js';
50
+ const { readJSON, writeJSON } = getStorage();
51
+ const MA = MARKET_ADAPTER;
52
+ // ─── CLI ─────────────────────────────────────────────────────────────────────
53
+ /**
54
+ * Parse a lookback spec. Accepts the shared `a:b:s` / comma syntax but also
55
+ * tolerates a DESCENDING range like `28:8:2` (which parseListOrRange rejects),
56
+ * so both "8h..28h" and "28h..8h" phrasings work.
57
+ */
58
+ function parseLookbacks(spec, fallback) {
59
+ const m = spec.match(/^(\d+):(\d+):([\d.]+)$/);
60
+ if (m) {
61
+ const a = Number(m[1]);
62
+ const b = Number(m[2]);
63
+ const step = Number(m[3]);
64
+ if (Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(step) && step > 0 && a > b) {
65
+ spec = `${b}:${a}:${step}`;
66
+ }
67
+ }
68
+ return parseListOrRange(spec, fallback).map((v) => Math.round(v));
69
+ }
70
+ function parseArgs() {
71
+ const args = process.argv.slice(2);
72
+ const out = {
73
+ dataPath: '',
74
+ amaName: MA.DEFAULT_AMA_KEY,
75
+ er: null,
76
+ fast: null,
77
+ slow: null,
78
+ lookbacks: [...range(8, 28, 2, 0)].map((v) => Math.round(v)).reverse(),
79
+ priceThresholdPct: MA.AMA_DELTA_THRESHOLD_PERCENT,
80
+ slopeThresholdFactor: MA.AMA_SLOPE_DELTA_THRESHOLD_PERCENT,
81
+ slopeEnabled: true,
82
+ slopePersistBars: MA.AMA_SLOPE_PERSIST_BARS,
83
+ confirmFraction: 0.25,
84
+ whipsawBars: 3,
85
+ scaleMode: 'none',
86
+ truthWindowBars: null,
87
+ forwardWindowBars: null,
88
+ outPath: null,
89
+ };
90
+ for (let i = 0; i < args.length; i++) {
91
+ const arg = args[i];
92
+ if (arg === '--help' || arg === '-h') {
93
+ printHelp();
94
+ process.exit(0);
95
+ }
96
+ if (arg === '--no-slope') {
97
+ out.slopeEnabled = false;
98
+ continue;
99
+ }
100
+ const val = args[i + 1];
101
+ if (!val)
102
+ continue;
103
+ switch (arg) {
104
+ case '--data':
105
+ out.dataPath = val;
106
+ i++;
107
+ break;
108
+ case '--ama':
109
+ out.amaName = val;
110
+ i++;
111
+ break;
112
+ case '--er':
113
+ out.er = Number(val);
114
+ i++;
115
+ break;
116
+ case '--fast':
117
+ out.fast = Number(val);
118
+ i++;
119
+ break;
120
+ case '--slow':
121
+ out.slow = Number(val);
122
+ i++;
123
+ break;
124
+ case '--lookback':
125
+ out.lookbacks = parseLookbacks(val, out.lookbacks);
126
+ i++;
127
+ break;
128
+ case '--price-threshold':
129
+ out.priceThresholdPct = Number(val);
130
+ i++;
131
+ break;
132
+ case '--slope-threshold-factor':
133
+ out.slopeThresholdFactor = Number(val);
134
+ i++;
135
+ break;
136
+ case '--slope-persist':
137
+ out.slopePersistBars = Math.max(1, Math.round(Number(val)));
138
+ i++;
139
+ break;
140
+ case '--confirm':
141
+ out.confirmFraction = Number(val);
142
+ i++;
143
+ break;
144
+ case '--scale-mode':
145
+ if (val !== 'none' && val !== 'df' && val !== 'mscale')
146
+ throw new Error(`--scale-mode must be none|df|mscale (got '${val}')`);
147
+ out.scaleMode = val;
148
+ i++;
149
+ break;
150
+ case '--whipsaw':
151
+ out.whipsawBars = Number(val);
152
+ i++;
153
+ break;
154
+ case '--truth-window':
155
+ out.truthWindowBars = Number(val);
156
+ i++;
157
+ break;
158
+ case '--forward-window':
159
+ out.forwardWindowBars = Number(val);
160
+ i++;
161
+ break;
162
+ case '--out':
163
+ out.outPath = path.resolve(val);
164
+ i++;
165
+ break;
166
+ }
167
+ }
168
+ if (!out.dataPath)
169
+ throw new Error('--data <path-to-lp-candles.json|dir> is required');
170
+ if (!Array.isArray(out.lookbacks) || out.lookbacks.length === 0 || out.lookbacks.some((v) => !Number.isFinite(v) || v < 2)) {
171
+ throw new Error('--lookback must resolve to a non-empty list of bars >= 2');
172
+ }
173
+ // De-duplicate and present high -> low so the table reads 28h..8h.
174
+ out.lookbacks = [...new Set(out.lookbacks)].sort((a, b) => b - a);
175
+ return out;
176
+ }
177
+ 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');
197
+ }
198
+ function resolveAma(cfg) {
199
+ if (cfg.er != null || cfg.fast != null || cfg.slow != null) {
200
+ const er = cfg.er ?? 781;
201
+ const fast = cfg.fast ?? 5.2;
202
+ const slow = cfg.slow ?? 83.6;
203
+ return { name: `custom(er=${er},f=${fast},s=${slow})`, er, fast, slow };
204
+ }
205
+ const presets = MA.AMAS;
206
+ const preset = presets[cfg.amaName];
207
+ if (!preset)
208
+ throw new Error(`Unknown AMA preset '${cfg.amaName}' (expected ${Object.keys(presets).join(', ')})`);
209
+ return { name: cfg.amaName, er: preset.erPeriod, fast: preset.fastPeriod, slow: preset.slowPeriod };
210
+ }
211
+ // ─── 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 = null;
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
+ }
267
+ // ─── Lag estimators ──────────────────────────────────────────────────────────
268
+ /**
269
+ * Cross-correlation peak lag between the causal signal and a reference.
270
+ * Returns the smallest non-negative k maximising corr(sig[t], ref[t-k]).
271
+ * A positive lag means `sig` trails `ref` by k bars (the smoother's group delay).
272
+ */
273
+ function crossCorrelationLag(sig, ref, maxLag) {
274
+ let bestLag = 0;
275
+ let bestCorr = -Infinity;
276
+ for (let k = 0; k <= maxLag; k++) {
277
+ let n = 0, sx = 0, sy = 0, sxy = 0, sxx = 0, syy = 0;
278
+ for (let t = k; t < sig.length; t++) {
279
+ const x = sig[t];
280
+ const y = ref[t - k];
281
+ if (x == null || y == null || !Number.isFinite(x) || !Number.isFinite(y))
282
+ continue;
283
+ n++;
284
+ sx += x;
285
+ sy += y;
286
+ sxy += x * y;
287
+ sxx += x * x;
288
+ syy += y * y;
289
+ }
290
+ if (n < 100)
291
+ continue;
292
+ const mx = sx / n, my = sy / n;
293
+ const vx = sxx / n - mx * mx;
294
+ const vy = syy / n - my * my;
295
+ const cov = sxy / n - mx * my;
296
+ const corr = vx > 0 && vy > 0 ? cov / Math.sqrt(vx * vy) : -Infinity;
297
+ if (corr > bestCorr) {
298
+ bestCorr = corr;
299
+ bestLag = k;
300
+ }
301
+ }
302
+ return { lagBars: bestLag, corr: Number.isFinite(bestCorr) ? bestCorr : null };
303
+ }
304
+ /**
305
+ * Median bars between a sign flip in the centred reference slope and the first
306
+ * bar the causal slope confirms the new direction at or above `confirmPct`.
307
+ * `misses` counts flips the causal slope never confirmed inside the window.
308
+ */
309
+ function reversalLag(sig, ref, maxLag, confirmPct) {
310
+ const lags = [];
311
+ let flips = 0;
312
+ let misses = 0;
313
+ let prevSign = 0;
314
+ for (let t = 1; t < ref.length; t++) {
315
+ const v = ref[t];
316
+ if (v == null || !Number.isFinite(v))
317
+ continue;
318
+ const s = Math.sign(v);
319
+ if (s !== 0 && prevSign !== 0 && s !== prevSign) {
320
+ flips++;
321
+ const end = Math.min(t + maxLag, sig.length - 1);
322
+ let found = -1;
323
+ for (let u = t + 1; u <= end; u++) {
324
+ const x = sig[u];
325
+ if (x != null && Number.isFinite(x) && Math.sign(x) === s && Math.abs(x) >= confirmPct) {
326
+ found = u - t;
327
+ break;
328
+ }
329
+ }
330
+ if (found >= 0)
331
+ lags.push(found);
332
+ else
333
+ misses++;
334
+ }
335
+ prevSign = s;
336
+ }
337
+ return { lagBars: median(lags), flips, misses, samples: lags.length };
338
+ }
339
+ // ─── Per-lookback computation ────────────────────────────────────────────────
340
+ function analyzeLookback(closes, amaValues, lookbackBars, amaDef, cfg, truthArr, priceTruthArr, truthHalf, estimator = createHuberEstimator('none')) {
341
+ const n = closes.length;
342
+ const warmupBars = getAmaWarmupBars(amaDef.er, amaDef.slow, 0, amaDef.fast);
343
+ const maxSlopePct = MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
344
+ const neutralZonePct = MA.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
345
+ const maxSlopeOffset = MA.DYNAMIC_WEIGHT_ASYMMETRIC_OFFSET_CLAMP;
346
+ const slopeDeltaThresholdPct = (cfg.slopeThresholdFactor / 100) * maxSlopePct;
347
+ // Canonical production reset decision (clip-independent for timing).
348
+ const sim = simulateGridResetSeries(amaValues, {
349
+ priceDeltaThresholdPercent: cfg.priceThresholdPct,
350
+ slopeDeltaThresholdPercent: slopeDeltaThresholdPct,
351
+ slopeEnabled: cfg.slopeEnabled,
352
+ erPeriod: amaDef.er,
353
+ lookbackBars,
354
+ warmupBars,
355
+ maxSlopePct,
356
+ neutralZonePct,
357
+ maxSlopeOffset,
358
+ clipPercentile: 0,
359
+ slopePersistBars: cfg.slopePersistBars,
360
+ slopeEstimator: estimator,
361
+ });
362
+ const slopeSeries = sim.slopePct;
363
+ const estStats = estimator.stats;
364
+ const meanOutlierFraction = estStats.calls > 0 ? estStats.outlierFractionSum / estStats.calls : null;
365
+ const meanHuberScale = estStats.calls > 0 ? estStats.scaleSum / estStats.calls : null;
366
+ const liveBars = Math.max(1, n - warmupBars);
367
+ // ── Noise / signal-quality metrics ──────────────────────────────────────
368
+ let finite = 0, sumSigned = 0, sumAbs = 0, sumSq = 0;
369
+ let prev = null;
370
+ let deltaCount = 0, sumAbsDelta = 0;
371
+ let prevDelta = null;
372
+ let secondCount = 0, secondSq = 0;
373
+ let zeroCross = 0, lastSign = 0;
374
+ let saturated = 0, neutral = 0;
375
+ for (let i = 0; i < n; i++) {
376
+ const s = slopeSeries[i];
377
+ if (s == null || !Number.isFinite(s)) {
378
+ prev = null;
379
+ prevDelta = null;
380
+ continue;
381
+ }
382
+ finite++;
383
+ sumSigned += s;
384
+ sumAbs += Math.abs(s);
385
+ sumSq += s * s;
386
+ if (Math.abs(s) >= maxSlopePct)
387
+ saturated++;
388
+ if (Math.abs(s) <= neutralZonePct)
389
+ neutral++;
390
+ const sign = Math.sign(s);
391
+ if (sign !== 0) {
392
+ if (lastSign !== 0 && sign !== lastSign)
393
+ zeroCross++;
394
+ lastSign = sign;
395
+ }
396
+ if (prev != null) {
397
+ const d = s - prev;
398
+ sumAbsDelta += Math.abs(d);
399
+ deltaCount++;
400
+ if (prevDelta != null) {
401
+ secondSq += (d - prevDelta) ** 2;
402
+ secondCount++;
403
+ }
404
+ prevDelta = d;
405
+ }
406
+ else {
407
+ prevDelta = null;
408
+ }
409
+ prev = s;
410
+ }
411
+ const meanAbsSlope = finite > 0 ? sumAbs / finite : 0;
412
+ const meanSlope = finite > 0 ? sumSigned / finite : 0;
413
+ const variance = finite > 0 ? Math.max(0, sumSq / finite - meanSlope * meanSlope) : 0;
414
+ // ── Range tilt (batch clip threshold; only affects offset, not timing) ──
415
+ const clipThreshold = computeAmaSlopeClipThreshold(amaValues, amaDef.er, lookbackBars, MA.DYNAMIC_WEIGHT_CLIP_PERCENTILE);
416
+ let offsetCount = 0, offsetAbsSum = 0;
417
+ for (let i = 0; i < n; i++) {
418
+ const s = slopeSeries[i];
419
+ if (s == null || !Number.isFinite(s))
420
+ continue;
421
+ const clipped = Math.max(-clipThreshold, Math.min(clipThreshold, s));
422
+ if (Math.abs(clipped) <= neutralZonePct)
423
+ continue;
424
+ offsetAbsSum += Math.abs(clipped / maxSlopePct) * maxSlopeOffset;
425
+ offsetCount++;
426
+ }
427
+ // ── Lag metrics ─────────────────────────────────────────────────────────
428
+ const maxLag = Math.max(1, lookbackBars * 2);
429
+ const priceLag = crossCorrelationLag(slopeSeries, priceTruthArr, maxLag);
430
+ const amaLag = crossCorrelationLag(slopeSeries, truthArr, maxLag);
431
+ // The reversal search window is wider than the xcorr window: a slow AMA can
432
+ // take well over one slope window to actually cross into a new regime.
433
+ const revMaxLag = Math.max(maxLag, truthHalf * 3);
434
+ const confirmPct = cfg.confirmFraction * meanAbsSlope;
435
+ const rev = reversalLag(slopeSeries, truthArr, revMaxLag, confirmPct);
436
+ // ── Reset metrics ───────────────────────────────────────────────────────
437
+ const resetEvents = sim.events.filter((e) => e.reason !== GRID_RESET_BOOTSTRAP);
438
+ const resetIdx = resetEvents.map((e) => Number(e.index));
439
+ const gaps = [];
440
+ for (let k = 1; k < resetIdx.length; k++)
441
+ gaps.push(resetIdx[k] - resetIdx[k - 1]);
442
+ const whipsaws = gaps.filter((g) => g <= cfg.whipsawBars).length;
443
+ const resetsPerDay = (sim.stats.resets / liveBars) * 24;
444
+ const lastResetIndex = sim.stats.lastResetIndex;
445
+ // ── Range-tilt wrong-way (applied tilt vs realized forward move) ────────
446
+ // The band tilt only refreshes at resets, so the applied direction at bar t
447
+ // is the sign of the slope sampled at the most recent reset. Wrong-way =
448
+ // that applied direction points against the realized forward AMA move over
449
+ // `forwardWindowBars`. Geometry-independent: the tilt sign is sign(slope).
450
+ const forwardWindowCfg = Number(cfg.forwardWindowBars);
451
+ const forwardWindowBars = Number.isFinite(forwardWindowCfg) && forwardWindowCfg > 0
452
+ ? Math.round(forwardWindowCfg)
453
+ : Math.max(1, lookbackBars);
454
+ const eventIdx = new Set(sim.events.map((e) => Number(e.index)));
455
+ let curAppliedDir = 0;
456
+ let evaluatedBars = 0, tiltActiveBars = 0, wrongWayBars = 0;
457
+ let curWrongStreak = 0;
458
+ const wrongStreaks = [];
459
+ const adverseMoves = [];
460
+ const closeStreak = () => { if (curWrongStreak > 0) {
461
+ wrongStreaks.push(curWrongStreak);
462
+ curWrongStreak = 0;
463
+ } };
464
+ for (let i = 0; i < n; i++) {
465
+ if (eventIdx.has(i)) {
466
+ const s = slopeSeries[i];
467
+ curAppliedDir = (s != null && Number.isFinite(s) && Math.abs(s) > neutralZonePct) ? Math.sign(s) : 0;
468
+ }
469
+ const fwdEnd = i + forwardWindowBars;
470
+ if (i < warmupBars || fwdEnd >= n) {
471
+ closeStreak();
472
+ continue;
473
+ }
474
+ const a0 = amaValues[i], a1 = amaValues[fwdEnd];
475
+ if (!Number.isFinite(a0) || a0 <= 0 || !Number.isFinite(a1)) {
476
+ closeStreak();
477
+ continue;
478
+ }
479
+ const fwdPct = ((a1 - a0) / a0) * 100;
480
+ const fwdDir = Math.sign(fwdPct);
481
+ if (fwdDir === 0) {
482
+ closeStreak();
483
+ continue;
484
+ }
485
+ evaluatedBars++;
486
+ if (curAppliedDir !== 0) {
487
+ tiltActiveBars++;
488
+ if (fwdDir !== curAppliedDir) {
489
+ wrongWayBars++;
490
+ curWrongStreak++;
491
+ adverseMoves.push(Math.abs(fwdPct));
492
+ }
493
+ else
494
+ closeStreak();
495
+ }
496
+ else {
497
+ closeStreak();
498
+ }
499
+ }
500
+ closeStreak();
501
+ return {
502
+ lookbackBars,
503
+ huberScaleMode: cfg.scaleMode,
504
+ meanOutlierFractionPct: meanOutlierFraction == null ? null : meanOutlierFraction * 100,
505
+ meanHuberScale,
506
+ // lag
507
+ priceLagBars: priceLag.lagBars,
508
+ priceLagCorr: priceLag.corr,
509
+ amaLagBars: amaLag.lagBars,
510
+ amaLagCorr: amaLag.corr,
511
+ reversalLagBars: rev.lagBars,
512
+ reversalFlips: rev.flips,
513
+ reversalMisses: rev.misses,
514
+ // resets
515
+ resets: sim.stats.resets,
516
+ resetsTotal: sim.stats.resetsTotal,
517
+ priceResets: sim.stats.priceResets,
518
+ slopeResets: sim.stats.slopeResets,
519
+ resetsPerDay,
520
+ avgBarsBetweenResets: gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : null,
521
+ medianBarsBetweenResets: median(gaps),
522
+ p90BarsBetweenResets: percentile(gaps, 90),
523
+ minBarsBetweenResets: gaps.length > 0 ? Math.min(...gaps) : null,
524
+ whipsawResets: whipsaws,
525
+ whipsawPct: gaps.length > 0 ? (whipsaws / gaps.length) * 100 : 0,
526
+ gridAgeSinceLastResetBars: lastResetIndex == null ? null : n - 1 - lastResetIndex,
527
+ // noise / quality
528
+ meanAbsSlopePct: meanAbsSlope,
529
+ slopeStdPct: Math.sqrt(variance),
530
+ slopeWobblePct: deltaCount > 0 ? sumAbsDelta / deltaCount : 0,
531
+ secondDiffEnergy: secondCount > 0 ? secondSq / secondCount : 0,
532
+ zeroCrossPer1k: finite > 0 ? (zeroCross / finite) * 1000 : 0,
533
+ saturationPct: finite > 0 ? (saturated / finite) * 100 : 0,
534
+ neutralPct: finite > 0 ? (neutral / finite) * 100 : 0,
535
+ avgAbsRangeOffset: offsetCount > 0 ? offsetAbsSum / offsetCount : 0,
536
+ offsetActivePct: finite > 0 ? (offsetCount / finite) * 100 : 0,
537
+ // range-tilt wrong-way
538
+ forwardWindowBars,
539
+ rangeWrongWayPct: tiltActiveBars > 0 ? (wrongWayBars / tiltActiveBars) * 100 : null,
540
+ rangeTiltActivePct: evaluatedBars > 0 ? (tiltActiveBars / evaluatedBars) * 100 : null,
541
+ meanWrongStreakBars: wrongStreaks.length > 0 ? wrongStreaks.reduce((a, b) => a + b, 0) / wrongStreaks.length : null,
542
+ medianAdverseMoveWhileWrongPct: median(adverseMoves),
543
+ p90AdverseMoveWhileWrongPct: percentile(adverseMoves, 90),
544
+ // context
545
+ warmupBars,
546
+ finiteSlopeBars: finite,
547
+ };
548
+ }
549
+ // ─── Composite recommendation ────────────────────────────────────────────────
550
+ function normalize(values) {
551
+ const finite = values.filter((v) => Number.isFinite(v));
552
+ const lo = Math.min(...finite);
553
+ const hi = Math.max(...finite);
554
+ return (v) => (hi > lo ? (v - lo) / (hi - lo) : 0);
555
+ }
556
+ function addCompositeScore(results) {
557
+ const lagVals = results.map((r) => (r.reversalLagBars ?? r.amaLagBars));
558
+ const resetVals = results.map((r) => r.resetsPerDay);
559
+ const wobbleVals = results.map((r) => r.slopeWobblePct);
560
+ const nLag = normalize(lagVals);
561
+ const nReset = normalize(resetVals);
562
+ const nWobble = normalize(wobbleVals);
563
+ for (const r of results) {
564
+ const lag = (r.reversalLagBars ?? r.amaLagBars);
565
+ const freshness = 1 - nLag(lag);
566
+ const stability = 1 - nReset(r.resetsPerDay);
567
+ const smoothness = 1 - nWobble(r.slopeWobblePct);
568
+ r.compositeScore = (freshness + stability + smoothness) / 3;
569
+ }
570
+ }
571
+ // ─── Main ────────────────────────────────────────────────────────────────────
572
+ function run() {
573
+ const cfg = parseArgs();
574
+ const amaDef = resolveAma(cfg);
575
+ const { candles, meta, files } = loadCandles(cfg.dataPath);
576
+ const closes = candles.map((c) => c.close);
577
+ const n = closes.length;
578
+ const amaValues = calculateAMA(closes, { erPeriod: amaDef.er, fastPeriod: amaDef.fast, slowPeriod: amaDef.slow });
579
+ const warmupBars = getAmaWarmupBars(amaDef.er, amaDef.slow, 0, amaDef.fast);
580
+ const maxLookback = Math.max(...cfg.lookbacks);
581
+ const truthHalf = cfg.truthWindowBars ?? maxLookback;
582
+ // Centred Huber slope (uses future bars) — the zero-lag reference the causal
583
+ // slope is correlated against. Half-window is shared across lookbacks so
584
+ // lag differences come from the causal window, not the reference.
585
+ const amaTruth = new Array(n).fill(null);
586
+ const priceTruth = new Array(n).fill(null);
587
+ const truthEstimator = createHuberEstimator(cfg.scaleMode);
588
+ for (let t = truthHalf; t <= n - 1 - truthHalf; t++) {
589
+ const a = truthEstimator(amaValues, t + truthHalf, truthHalf * 2);
590
+ if (a != null && Number.isFinite(a))
591
+ amaTruth[t] = a;
592
+ const p = truthEstimator(closes, t + truthHalf, truthHalf * 2);
593
+ if (p != null && Number.isFinite(p))
594
+ priceTruth[t] = p;
595
+ }
596
+ console.log('================================================================================');
597
+ console.log(' AMA-SLOPE-HUBER LOOKBACK BACKTEST');
598
+ console.log('================================================================================');
599
+ console.log(` Data: ${path.resolve(cfg.dataPath)}`);
600
+ console.log(` ${files} file(s), ${n} candles, ${((n * Number(meta?.intervalSeconds ?? 3600)) / 86400).toFixed(0)} days`);
601
+ console.log(` AMA: ${amaDef.name} (er=${amaDef.er}, fast=${amaDef.fast}, slow=${amaDef.slow}), warmup ${warmupBars} bars`);
602
+ console.log(` Lookbacks: ${cfg.lookbacks.join(', ')} bars (${cfg.lookbacks.length} windows)`);
603
+ console.log(` Resets: drift >= ${cfg.priceThresholdPct}% | slope delta >= ${fmt((cfg.slopeThresholdFactor / 100) * MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT, 4)}%/bar` +
604
+ ` (${cfg.slopeThresholdFactor}% of max ${MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT})${cfg.slopeEnabled ? '' : ' [OFF]'} | persist K=${cfg.slopePersistBars}`);
605
+ console.log(` Reference: centred Huber slope, half-window ${truthHalf} bars`);
606
+ console.log(` Huber: scale mode = ${cfg.scaleMode}`);
607
+ console.log(` Confirm: |slope| >= ${cfg.confirmFraction} x each window's mean |slope| (per-window gate)`);
608
+ console.log('');
609
+ const results = [];
610
+ for (const lb of cfg.lookbacks) {
611
+ const estimator = createHuberEstimator(cfg.scaleMode);
612
+ const r = analyzeLookback(closes, amaValues, lb, amaDef, cfg, amaTruth, priceTruth, truthHalf, estimator);
613
+ results.push(r);
614
+ process.stdout.write(` lb=${String(lb).padStart(2)} resets=${String(r.resets).padStart(4)} ` +
615
+ `lag(ama)=${fmt(r.amaLagBars, 0).padStart(3)} rev=${fmt(r.reversalLagBars, 1).padStart(5)} ` +
616
+ `wobble=${fmt(r.slopeWobblePct, 4)} zc/1k=${fmt(r.zeroCrossPer1k, 1)}\n`);
617
+ }
618
+ addCompositeScore(results);
619
+ // ── Metric table ────────────────────────────────────────────────────────
620
+ console.log('\n================================================================================');
621
+ console.log(' PER-LOOKBACK METRICS');
622
+ console.log('================================================================================');
623
+ console.log(' lb | resets rs/day | price slope | medGap p90 | whip% | lagP lagA | revLag | std wobble zc/1k | sat% | comp');
624
+ console.log('----+--------------+-------------+------------+-------+---------+--------+-----------------------+------+-----');
625
+ for (const r of results) {
626
+ console.log(` ${String(r.lookbackBars).padStart(2)} | ` +
627
+ `${String(r.resets).padStart(6)} ${fmt(r.resetsPerDay, 1).padStart(6)} | ` +
628
+ `${String(r.priceResets).padStart(5)} ${String(r.slopeResets).padStart(5)} | ` +
629
+ `${fmt(r.medianBarsBetweenResets, 0).padStart(6)} ${fmt(r.p90BarsBetweenResets, 0).padStart(4)} | ` +
630
+ `${fmt(r.whipsawPct, 0).padStart(5)} | ` +
631
+ `${fmt(r.priceLagBars, 0).padStart(4)} ${fmt(r.amaLagBars, 0).padStart(4)} | ` +
632
+ `${fmt(r.reversalLagBars, 1).padStart(6)} | ` +
633
+ `${fmt(r.slopeStdPct, 4).padStart(6)} ${fmt(r.slopeWobblePct, 4).padStart(7)} ${fmt(r.zeroCrossPer1k, 1).padStart(6)} | ` +
634
+ `${fmt(r.saturationPct, 0).padStart(4)} | ` +
635
+ `${fmt(r.compositeScore, 3)}`);
636
+ }
637
+ console.log('\n Correlation strength at the peak (higher = more reliable lag estimate):');
638
+ console.log(' lb | priceCorr | amaCorr | reversalFlips | reversalMisses | offsetActive% | avg|offset|');
639
+ console.log(' ---+-----------+---------+---------------+----------------+---------------+------------');
640
+ for (const r of results) {
641
+ console.log(` ${String(r.lookbackBars).padStart(2)} | ` +
642
+ `${fmt(r.priceLagCorr, 3).padStart(9)} | ` +
643
+ `${fmt(r.amaLagCorr, 3).padStart(7)} | ` +
644
+ `${String(r.reversalFlips).padStart(13)} | ` +
645
+ `${String(r.reversalMisses).padStart(14)} | ` +
646
+ `${fmt(r.offsetActivePct, 1).padStart(13)} | ` +
647
+ `${fmt(r.avgAbsRangeOffset, 4).padStart(12)}`);
648
+ }
649
+ console.log(`\n Huber scale mode: ${cfg.scaleMode} (outlier = |residual| > C x scale)`);
650
+ console.log(' lb | mean outlier% | mean scale (log units)');
651
+ console.log(' ---+---------------+----------------------');
652
+ for (const r of results) {
653
+ console.log(` ${String(r.lookbackBars).padStart(2)} | ` +
654
+ `${fmt(r.meanOutlierFractionPct, 2).padStart(13)} | ` +
655
+ `${fmt(r.meanHuberScale, 5).padStart(20)}`);
656
+ }
657
+ console.log('\n Range-tilt wrong-way (applied tilt vs realized forward AMA move):');
658
+ console.log(' var | tiltActive% | wrongWay% | meanWrongRun | medAdverse | p90Adverse');
659
+ console.log(' -------+-------------+-----------+--------------+------------+-----------');
660
+ for (const r of results) {
661
+ console.log(` ${String(r.lookbackBars).padStart(5)} | ` +
662
+ `${fmt(r.rangeTiltActivePct, 1).padStart(11)} | ` +
663
+ `${fmt(r.rangeWrongWayPct, 1).padStart(9)} | ` +
664
+ `${fmt(r.meanWrongStreakBars, 1).padStart(12)} | ` +
665
+ `${fmt(r.medianAdverseMoveWhileWrongPct, 2).padStart(10)} | ` +
666
+ `${fmt(r.p90AdverseMoveWhileWrongPct, 2).padStart(10)}`);
667
+ }
668
+ // ── Sweet spot (heuristic) ──────────────────────────────────────────────
669
+ const ranked = results.slice().sort((a, b) => (b.compositeScore ?? 0) - (a.compositeScore ?? 0));
670
+ const winner = ranked[0];
671
+ console.log('\n================================================================================');
672
+ console.log(' HEURISTIC SWEET SPOT');
673
+ console.log('================================================================================');
674
+ console.log(' Composite = equal-weight mean of (low reversal lag, low reset rate, low wobble),');
675
+ console.log(' each min-max normalised across the swept lookbacks. Not a P&L objective —');
676
+ console.log(' use the per-metric table to trade lag against reset churn for your own fill model.');
677
+ console.log(`\n lb=${winner.lookbackBars}: lagA=${fmt(winner.amaLagBars, 0)} revLag=${fmt(winner.reversalLagBars, 1)} ` +
678
+ `resets/day=${fmt(winner.resetsPerDay, 1)} wobble=${fmt(winner.slopeWobblePct, 4)} score=${fmt(winner.compositeScore, 3)}`);
679
+ // ── Persist ─────────────────────────────────────────────────────────────
680
+ const base = path.basename(path.resolve(cfg.dataPath)).replace(/\.json$/i, '');
681
+ const outPath = cfg.outPath ?? path.join(PATHS.ANALYSIS.RESULTS_DIR, `ama_slope_huber_lookback_${base}.json`);
682
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
683
+ writeJSON(outPath, {
684
+ meta: {
685
+ generatedAt: new Date().toISOString(),
686
+ dataPath: path.relative(process.cwd(), path.resolve(cfg.dataPath)),
687
+ files,
688
+ candles: n,
689
+ ama: amaDef,
690
+ warmupBars,
691
+ lookbacks: cfg.lookbacks,
692
+ slopePersistBars: cfg.slopePersistBars,
693
+ huberScaleMode: cfg.scaleMode,
694
+ resetConfig: {
695
+ priceDeltaThresholdPercent: cfg.priceThresholdPct,
696
+ slopeDeltaThresholdPercent: (cfg.slopeThresholdFactor / 100) * MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
697
+ slopeThresholdFactor: cfg.slopeThresholdFactor,
698
+ slopeEnabled: cfg.slopeEnabled,
699
+ maxSlopePct: MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
700
+ neutralZonePct: MA.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT,
701
+ clipPercentile: MA.DYNAMIC_WEIGHT_CLIP_PERCENTILE,
702
+ },
703
+ lagConfig: {
704
+ reference: `centred Huber slope, half-window ${truthHalf} bars`,
705
+ confirmPct: `${cfg.confirmFraction} x each window's mean |slope|`,
706
+ },
707
+ whipsawBars: cfg.whipsawBars,
708
+ notes: 'Reset replay uses the canonical simulateGridResetSeries decision path (unclipped slope — clip only affects range tilt). Lag is a cross-correlation group-delay estimate; reversalLag is the median bars from a sign flip in the centred AMA slope to causal confirmation.',
709
+ },
710
+ results,
711
+ sweetSpot: winner,
712
+ });
713
+ console.log(`\nSaved: ${path.relative(process.cwd(), outPath)}`);
714
+ }
715
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
716
+ try {
717
+ run();
718
+ }
719
+ catch (err) {
720
+ console.error(err);
721
+ process.exit(1);
722
+ }
723
+ }
724
+ export { loadCandles, crossCorrelationLag, reversalLag, analyzeLookback };
725
+ //# sourceMappingURL=backtest_ama_slope_huber.js.map