dexbot 1.6.6 → 1.6.8

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 (632) hide show
  1. package/CHANGELOG.md +89 -1
  2. package/README.md +8 -5
  3. package/analysis/README.md +2 -3
  4. package/analysis/tradingview/README.md +78 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
  10. package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
  11. package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
  12. package/dist/analysis/tradingview/grid_reset_config.js +235 -0
  13. package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
  14. package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
  16. package/dist/dexbot.js +44 -15
  17. package/dist/market_adapter/core/market_adapter_service.js +14 -2
  18. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
  20. package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
  21. package/dist/market_adapter/inputs/window_cache.js +302 -48
  22. package/dist/market_adapter/market_adapter.d.ts +8 -1
  23. package/dist/market_adapter/market_adapter.js +22 -4
  24. package/dist/modules/account_bots.js +20 -9
  25. package/dist/modules/account_orders.d.ts +44 -4
  26. package/dist/modules/account_orders.js +104 -7
  27. package/dist/modules/bitshares-native/chain_client.d.ts +10 -0
  28. package/dist/modules/bitshares-native/chain_client.js +197 -28
  29. package/dist/modules/bitshares-native/subscriptions.js +312 -10
  30. package/dist/modules/bitshares-native/transport.d.ts +1 -0
  31. package/dist/modules/bitshares-native/transport.js +97 -3
  32. package/dist/modules/bitshares_client.d.ts +20 -0
  33. package/dist/modules/bitshares_client.js +29 -0
  34. package/dist/modules/bot_settings.js +10 -1
  35. package/dist/modules/chain_keys.d.ts +37 -22
  36. package/dist/modules/chain_keys.js +145 -44
  37. package/dist/modules/cli_start_onboarding.d.ts +10 -0
  38. package/dist/modules/cli_start_onboarding.js +15 -0
  39. package/dist/modules/cli_start_output.d.ts +6 -0
  40. package/dist/modules/cli_start_output.js +8 -0
  41. package/dist/modules/config.d.ts +1 -0
  42. package/dist/modules/config.js +1 -0
  43. package/dist/modules/constants.d.ts +23 -2
  44. package/dist/modules/constants.js +196 -15
  45. package/dist/modules/dexbot_class.d.ts +6 -76
  46. package/dist/modules/dexbot_class.js +0 -32
  47. package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
  48. package/dist/modules/dexbot_cow_runtime.js +53 -96
  49. package/dist/modules/dexbot_fill_runtime.d.ts +6 -1
  50. package/dist/modules/dexbot_fill_runtime.js +22 -3
  51. package/dist/modules/dexbot_maintenance_runtime.d.ts +38 -1
  52. package/dist/modules/dexbot_maintenance_runtime.js +103 -11
  53. package/dist/modules/dexbot_startup_runtime.js +73 -20
  54. package/dist/modules/dexbot_state_recovery.d.ts +6 -0
  55. package/dist/modules/dexbot_state_recovery.js +34 -1
  56. package/dist/modules/order/async_lock.d.ts +8 -0
  57. package/dist/modules/order/async_lock.js +15 -0
  58. package/dist/modules/order/genesis_policy.d.ts +162 -0
  59. package/dist/modules/order/genesis_policy.js +267 -0
  60. package/dist/modules/order/grid.js +109 -135
  61. package/dist/modules/order/grid_reconcile.d.ts +9 -0
  62. package/dist/modules/order/grid_reconcile.js +13 -4
  63. package/dist/modules/order/grid_reconcile_internal.js +13 -2
  64. package/dist/modules/order/logger.d.ts +12 -2
  65. package/dist/modules/order/logger.js +29 -7
  66. package/dist/modules/order/manager.d.ts +53 -0
  67. package/dist/modules/order/manager.js +86 -25
  68. package/dist/modules/order/sync_engine.d.ts +19 -0
  69. package/dist/modules/order/sync_engine.js +284 -344
  70. package/dist/modules/order/utils/math.d.ts +22 -1
  71. package/dist/modules/order/utils/math.js +64 -1
  72. package/dist/modules/order/utils/order.d.ts +43 -58
  73. package/dist/modules/order/utils/order.js +302 -194
  74. package/dist/modules/order/utils/system.d.ts +97 -0
  75. package/dist/modules/order/utils/system.js +282 -3
  76. package/dist/modules/paths.d.ts +8 -1
  77. package/dist/modules/paths.js +11 -3
  78. package/dist/modules/utils/text_width.d.ts +19 -0
  79. package/dist/modules/utils/text_width.js +97 -0
  80. package/dist/modules/version_notice.d.ts +165 -0
  81. package/dist/modules/version_notice.js +364 -0
  82. package/dist/pm2.js +104 -18
  83. package/dist/scripts/update.js +62 -13
  84. package/dist/unlock.d.ts +14 -2
  85. package/dist/unlock.js +101 -4
  86. package/docs/BITSHARES_ONBOARDING.md +8 -1
  87. package/docs/COW_INVARIANTS.md +11 -2
  88. package/docs/CREDENTIAL_SECURITY.md +26 -0
  89. package/docs/DEXBOT_COMPARISON.md +4 -4
  90. package/docs/EVOLUTION.md +20 -18
  91. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  92. package/docs/GRID_PRICE_INVARIANT.md +204 -31
  93. package/docs/GRID_RECALCULATION.md +12 -0
  94. package/docs/LOGGING.md +17 -2
  95. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +6 -7
  96. package/docs/README.md +3 -1
  97. package/docs/WORKFLOW.md +16 -5
  98. package/market_adapter/README.md +1 -1
  99. package/modules/README.md +18 -1
  100. package/package.json +14 -6
  101. package/scripts/README.md +28 -2
  102. package/scripts/clear-all.sh +13 -4
  103. package/scripts/clear-logs.sh +13 -4
  104. package/scripts/clear-market-adapter.sh +6 -0
  105. package/scripts/clear-orders.sh +5 -0
  106. package/scripts/lib/dexbot-paths.sh +108 -0
  107. package/tests/README.md +11 -3
  108. package/analysis/account_resolver.ts +0 -161
  109. package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
  110. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
  111. package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
  112. package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
  113. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
  114. package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
  115. package/analysis/analyze_dynamic_weight.ts +0 -243
  116. package/analysis/analyze_kalman.ts +0 -157
  117. package/analysis/analyze_regime.ts +0 -158
  118. package/analysis/analyze_regime_windows.ts +0 -470
  119. package/analysis/analyze_risk_profile.ts +0 -199
  120. package/analysis/analyze_trade_heatmap.ts +0 -362
  121. package/analysis/analyze_volatility.ts +0 -182
  122. package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
  123. package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
  124. package/analysis/bot_fitting/shared_utils.ts +0 -52
  125. package/analysis/bot_key_utils.ts +0 -426
  126. package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
  127. package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
  128. package/analysis/chain_pool.ts +0 -47
  129. package/analysis/chart_css.ts +0 -62
  130. package/analysis/chart_ui.ts +0 -105
  131. package/analysis/chart_utils.ts +0 -210
  132. package/analysis/fills_source.ts +0 -228
  133. package/analysis/grid_correction_check.ts +0 -786
  134. package/analysis/math_utils.ts +0 -53
  135. package/analysis/price_sources.ts +0 -136
  136. package/analysis/resolve_bot_accounts.ts +0 -199
  137. package/analysis/resolve_source.ts +0 -99
  138. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
  139. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
  140. package/analysis/trade_profitability.ts +0 -1335
  141. package/analysis/tradingview/analyze_tradingview.ts +0 -280
  142. package/analysis/tradingview/h-bts_tradingview.html +0 -1570
  143. package/analysis/tradingview/t-bts_tradingview.html +0 -1570
  144. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
  145. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
  146. package/analysis/trend_detection/hurst_analyzer.ts +0 -7
  147. package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
  148. package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
  149. package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
  150. package/analysis/trend_detection/package.json +0 -23
  151. package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
  152. package/analysis/trend_detection/regime_chart_generator.ts +0 -338
  153. package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
  154. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
  155. package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
  156. package/analysis/tsconfig.json +0 -29
  157. package/claw/tests/package.json +0 -3
  158. package/claw/tests/test_claw_bridge.ts +0 -570
  159. package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
  160. package/claw/tests/test_claw_chain_layer.ts +0 -739
  161. package/claw/tests/test_claw_data_flow.ts +0 -525
  162. package/claw/tests/test_claw_domain_logic.ts +0 -471
  163. package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
  164. package/claw/tests/test_claw_mcp_transport.ts +0 -243
  165. package/claw/tests/test_claw_regressions.ts +0 -711
  166. package/claw/tests/test_claw_skill_generation.ts +0 -103
  167. package/claw/tests/test_claw_state_store.ts +0 -44
  168. package/claw/tests/test_dexbot_profiles.ts +0 -654
  169. package/claw/tests/test_memu_bridge.ts +0 -189
  170. package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
  171. package/claw/tests/test_position_health.ts +0 -343
  172. package/claw/tests/test_position_manager.ts +0 -429
  173. package/claw/tests/test_position_manager_watch_health.ts +0 -100
  174. package/claw/tests/test_short_mpa_strategy.ts +0 -232
  175. package/dist/analysis/account_resolver.d.ts.map +0 -1
  176. package/dist/analysis/account_resolver.js.map +0 -1
  177. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  178. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  179. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  180. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  181. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  182. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  183. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  184. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  185. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  186. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  187. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  188. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  189. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  190. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  191. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  192. package/dist/analysis/analyze_kalman.js.map +0 -1
  193. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  194. package/dist/analysis/analyze_regime.js.map +0 -1
  195. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  196. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  197. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  198. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  199. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  200. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  201. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  202. package/dist/analysis/analyze_volatility.js.map +0 -1
  203. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  204. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  205. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  206. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  207. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  208. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  209. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  210. package/dist/analysis/bot_key_utils.js.map +0 -1
  211. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  212. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  213. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  214. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  215. package/dist/analysis/chain_pool.d.ts.map +0 -1
  216. package/dist/analysis/chain_pool.js.map +0 -1
  217. package/dist/analysis/chart_css.d.ts.map +0 -1
  218. package/dist/analysis/chart_css.js.map +0 -1
  219. package/dist/analysis/chart_ui.d.ts.map +0 -1
  220. package/dist/analysis/chart_ui.js.map +0 -1
  221. package/dist/analysis/chart_utils.d.ts.map +0 -1
  222. package/dist/analysis/chart_utils.js.map +0 -1
  223. package/dist/analysis/fills_source.d.ts.map +0 -1
  224. package/dist/analysis/fills_source.js.map +0 -1
  225. package/dist/analysis/grid_correction_check.d.ts.map +0 -1
  226. package/dist/analysis/grid_correction_check.js.map +0 -1
  227. package/dist/analysis/math_utils.d.ts.map +0 -1
  228. package/dist/analysis/math_utils.js.map +0 -1
  229. package/dist/analysis/price_sources.d.ts.map +0 -1
  230. package/dist/analysis/price_sources.js.map +0 -1
  231. package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
  232. package/dist/analysis/resolve_bot_accounts.js.map +0 -1
  233. package/dist/analysis/resolve_source.d.ts.map +0 -1
  234. package/dist/analysis/resolve_source.js.map +0 -1
  235. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  236. package/dist/analysis/trade_profitability.js.map +0 -1
  237. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  238. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  239. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
  240. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
  241. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  242. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  243. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
  244. package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
  245. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  246. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  247. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
  248. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
  249. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
  250. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
  251. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
  252. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
  253. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  254. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  255. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  256. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  257. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
  258. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  259. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  260. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  261. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
  262. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  263. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  264. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
  265. package/dist/bot.d.ts.map +0 -1
  266. package/dist/bot.js.map +0 -1
  267. package/dist/credential-daemon.d.ts.map +0 -1
  268. package/dist/credential-daemon.js.map +0 -1
  269. package/dist/dexbot.d.ts.map +0 -1
  270. package/dist/dexbot.js.map +0 -1
  271. package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
  272. package/dist/market_adapter/ama_signal_runner.js.map +0 -1
  273. package/dist/market_adapter/candle_utils.d.ts.map +0 -1
  274. package/dist/market_adapter/candle_utils.js.map +0 -1
  275. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
  276. package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
  277. package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
  278. package/dist/market_adapter/core/config_normalizers.js.map +0 -1
  279. package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
  280. package/dist/market_adapter/core/kibana_candles.js.map +0 -1
  281. package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
  282. package/dist/market_adapter/core/kibana_client.js.map +0 -1
  283. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
  284. package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
  285. package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
  286. package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
  287. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
  288. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
  289. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
  290. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
  291. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
  292. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
  293. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
  294. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
  295. package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
  296. package/dist/market_adapter/core/strategies/ama.js.map +0 -1
  297. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
  298. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
  299. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
  300. package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
  301. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
  302. package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
  303. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
  304. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
  305. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
  306. package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
  307. package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
  308. package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
  309. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
  310. package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
  311. package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
  312. package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
  313. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
  314. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
  315. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
  316. package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
  317. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
  318. package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
  319. package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
  320. package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
  321. package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
  322. package/dist/market_adapter/inputs/window_cache.js.map +0 -1
  323. package/dist/market_adapter/interval_utils.d.ts.map +0 -1
  324. package/dist/market_adapter/interval_utils.js.map +0 -1
  325. package/dist/market_adapter/log_format.d.ts.map +0 -1
  326. package/dist/market_adapter/log_format.js.map +0 -1
  327. package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
  328. package/dist/market_adapter/lp_chart_core.js.map +0 -1
  329. package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
  330. package/dist/market_adapter/lp_chart_runner.js.map +0 -1
  331. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
  332. package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
  333. package/dist/market_adapter/market_adapter.d.ts.map +0 -1
  334. package/dist/market_adapter/market_adapter.js.map +0 -1
  335. package/dist/market_adapter/test_helpers.d.ts.map +0 -1
  336. package/dist/market_adapter/test_helpers.js.map +0 -1
  337. package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
  338. package/dist/market_adapter/utils/adapter_client.js.map +0 -1
  339. package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
  340. package/dist/market_adapter/utils/atomic_write.js.map +0 -1
  341. package/dist/market_adapter/utils/chain.d.ts.map +0 -1
  342. package/dist/market_adapter/utils/chain.js.map +0 -1
  343. package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
  344. package/dist/market_adapter/utils/data_discovery.js.map +0 -1
  345. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
  346. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
  347. package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
  348. package/dist/market_adapter/utils/file_lock.js.map +0 -1
  349. package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
  350. package/dist/market_adapter/utils/native_history.js.map +0 -1
  351. package/dist/modules/account_bots.d.ts.map +0 -1
  352. package/dist/modules/account_bots.js.map +0 -1
  353. package/dist/modules/account_orders.d.ts.map +0 -1
  354. package/dist/modules/account_orders.js.map +0 -1
  355. package/dist/modules/authority_resolver.d.ts.map +0 -1
  356. package/dist/modules/authority_resolver.js.map +0 -1
  357. package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
  358. package/dist/modules/bitshares-native/chain_client.js.map +0 -1
  359. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
  360. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
  361. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
  362. package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
  363. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
  364. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
  365. package/dist/modules/bitshares-native/index.d.ts.map +0 -1
  366. package/dist/modules/bitshares-native/index.js.map +0 -1
  367. package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
  368. package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
  369. package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
  370. package/dist/modules/bitshares-native/resolvers.js.map +0 -1
  371. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
  372. package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
  373. package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
  374. package/dist/modules/bitshares-native/serial/index.js.map +0 -1
  375. package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
  376. package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
  377. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
  378. package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
  379. package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
  380. package/dist/modules/bitshares-native/serial/types.js.map +0 -1
  381. package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
  382. package/dist/modules/bitshares-native/signing_client.js.map +0 -1
  383. package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
  384. package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
  385. package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
  386. package/dist/modules/bitshares-native/transport.js.map +0 -1
  387. package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
  388. package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
  389. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
  390. package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
  391. package/dist/modules/bitshares_client.d.ts.map +0 -1
  392. package/dist/modules/bitshares_client.js.map +0 -1
  393. package/dist/modules/bot_defaults.d.ts.map +0 -1
  394. package/dist/modules/bot_defaults.js.map +0 -1
  395. package/dist/modules/bot_settings.d.ts.map +0 -1
  396. package/dist/modules/bot_settings.js.map +0 -1
  397. package/dist/modules/bots_file_lock.d.ts.map +0 -1
  398. package/dist/modules/bots_file_lock.js.map +0 -1
  399. package/dist/modules/broadcast_failure.d.ts.map +0 -1
  400. package/dist/modules/broadcast_failure.js.map +0 -1
  401. package/dist/modules/chain_keys.d.ts.map +0 -1
  402. package/dist/modules/chain_keys.js.map +0 -1
  403. package/dist/modules/chain_orders.d.ts.map +0 -1
  404. package/dist/modules/chain_orders.js.map +0 -1
  405. package/dist/modules/cli_colors.d.ts.map +0 -1
  406. package/dist/modules/cli_colors.js.map +0 -1
  407. package/dist/modules/config.d.ts.map +0 -1
  408. package/dist/modules/config.js.map +0 -1
  409. package/dist/modules/constants.d.ts.map +0 -1
  410. package/dist/modules/constants.js.map +0 -1
  411. package/dist/modules/cr_planner.d.ts.map +0 -1
  412. package/dist/modules/cr_planner.js.map +0 -1
  413. package/dist/modules/credential_policy.d.ts.map +0 -1
  414. package/dist/modules/credential_policy.js.map +0 -1
  415. package/dist/modules/credential_runtime.d.ts.map +0 -1
  416. package/dist/modules/credential_runtime.js.map +0 -1
  417. package/dist/modules/credential_session_cache.d.ts.map +0 -1
  418. package/dist/modules/credential_session_cache.js.map +0 -1
  419. package/dist/modules/credit_pricing.d.ts.map +0 -1
  420. package/dist/modules/credit_pricing.js.map +0 -1
  421. package/dist/modules/credit_runtime.d.ts.map +0 -1
  422. package/dist/modules/credit_runtime.js.map +0 -1
  423. package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
  424. package/dist/modules/crypto/browser_provider.js.map +0 -1
  425. package/dist/modules/crypto/index.d.ts.map +0 -1
  426. package/dist/modules/crypto/index.js.map +0 -1
  427. package/dist/modules/crypto/node_provider.d.ts.map +0 -1
  428. package/dist/modules/crypto/node_provider.js.map +0 -1
  429. package/dist/modules/crypto/provider.d.ts.map +0 -1
  430. package/dist/modules/crypto/provider.js.map +0 -1
  431. package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
  432. package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
  433. package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
  434. package/dist/modules/crypto/pure_scrypt.js.map +0 -1
  435. package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
  436. package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
  437. package/dist/modules/crypto/sync.d.ts.map +0 -1
  438. package/dist/modules/crypto/sync.js.map +0 -1
  439. package/dist/modules/daemon_node_health.d.ts.map +0 -1
  440. package/dist/modules/daemon_node_health.js.map +0 -1
  441. package/dist/modules/dexbot_class.d.ts.map +0 -1
  442. package/dist/modules/dexbot_class.js.map +0 -1
  443. package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
  444. package/dist/modules/dexbot_cow_runtime.js.map +0 -1
  445. package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
  446. package/dist/modules/dexbot_credential_client.js.map +0 -1
  447. package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
  448. package/dist/modules/dexbot_fill_runtime.js.map +0 -1
  449. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
  450. package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
  451. package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
  452. package/dist/modules/dexbot_startup_runtime.js.map +0 -1
  453. package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
  454. package/dist/modules/dexbot_state_recovery.js.map +0 -1
  455. package/dist/modules/env.d.ts.map +0 -1
  456. package/dist/modules/env.js.map +0 -1
  457. package/dist/modules/fund_registry.d.ts.map +0 -1
  458. package/dist/modules/fund_registry.js.map +0 -1
  459. package/dist/modules/general_settings.d.ts.map +0 -1
  460. package/dist/modules/general_settings.js.map +0 -1
  461. package/dist/modules/graceful_shutdown.d.ts.map +0 -1
  462. package/dist/modules/graceful_shutdown.js.map +0 -1
  463. package/dist/modules/grid_price_source.d.ts.map +0 -1
  464. package/dist/modules/grid_price_source.js.map +0 -1
  465. package/dist/modules/key_store.d.ts.map +0 -1
  466. package/dist/modules/key_store.js.map +0 -1
  467. package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
  468. package/dist/modules/launcher/adapter_requirement.js.map +0 -1
  469. package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
  470. package/dist/modules/launcher/bot_supervisor.js.map +0 -1
  471. package/dist/modules/launcher/child_env.d.ts.map +0 -1
  472. package/dist/modules/launcher/child_env.js.map +0 -1
  473. package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
  474. package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
  475. package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
  476. package/dist/modules/launcher/credential_daemon.js.map +0 -1
  477. package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
  478. package/dist/modules/launcher/credential_secret.js.map +0 -1
  479. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
  480. package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
  481. package/dist/modules/launcher/headless_password.d.ts.map +0 -1
  482. package/dist/modules/launcher/headless_password.js.map +0 -1
  483. package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
  484. package/dist/modules/launcher/launch_modes.js.map +0 -1
  485. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
  486. package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
  487. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
  488. package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
  489. package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
  490. package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
  491. package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
  492. package/dist/modules/launcher/runtime_entry.js.map +0 -1
  493. package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
  494. package/dist/modules/launcher/status_reporting.js.map +0 -1
  495. package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
  496. package/dist/modules/launcher/supervisor_control.js.map +0 -1
  497. package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
  498. package/dist/modules/market_adapter_whitelist.js.map +0 -1
  499. package/dist/modules/node_connect_policy.d.ts.map +0 -1
  500. package/dist/modules/node_connect_policy.js.map +0 -1
  501. package/dist/modules/node_failure_ledger.d.ts.map +0 -1
  502. package/dist/modules/node_failure_ledger.js.map +0 -1
  503. package/dist/modules/node_health_cache.d.ts.map +0 -1
  504. package/dist/modules/node_health_cache.js.map +0 -1
  505. package/dist/modules/node_manager.d.ts.map +0 -1
  506. package/dist/modules/node_manager.js.map +0 -1
  507. package/dist/modules/order/accounting.d.ts.map +0 -1
  508. package/dist/modules/order/accounting.js.map +0 -1
  509. package/dist/modules/order/async_lock.d.ts.map +0 -1
  510. package/dist/modules/order/async_lock.js.map +0 -1
  511. package/dist/modules/order/export.d.ts.map +0 -1
  512. package/dist/modules/order/export.js.map +0 -1
  513. package/dist/modules/order/format.d.ts.map +0 -1
  514. package/dist/modules/order/format.js.map +0 -1
  515. package/dist/modules/order/grid.d.ts.map +0 -1
  516. package/dist/modules/order/grid.js.map +0 -1
  517. package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
  518. package/dist/modules/order/grid_reconcile.js.map +0 -1
  519. package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
  520. package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
  521. package/dist/modules/order/index.d.ts.map +0 -1
  522. package/dist/modules/order/index.js.map +0 -1
  523. package/dist/modules/order/logger.d.ts.map +0 -1
  524. package/dist/modules/order/logger.js.map +0 -1
  525. package/dist/modules/order/logger_state.d.ts.map +0 -1
  526. package/dist/modules/order/logger_state.js.map +0 -1
  527. package/dist/modules/order/manager.d.ts.map +0 -1
  528. package/dist/modules/order/manager.js.map +0 -1
  529. package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
  530. package/dist/modules/order/processed_fill_store.js.map +0 -1
  531. package/dist/modules/order/strategy.d.ts.map +0 -1
  532. package/dist/modules/order/strategy.js.map +0 -1
  533. package/dist/modules/order/sync_engine.d.ts.map +0 -1
  534. package/dist/modules/order/sync_engine.js.map +0 -1
  535. package/dist/modules/order/utils/math.d.ts.map +0 -1
  536. package/dist/modules/order/utils/math.js.map +0 -1
  537. package/dist/modules/order/utils/order.d.ts.map +0 -1
  538. package/dist/modules/order/utils/order.js.map +0 -1
  539. package/dist/modules/order/utils/slot.d.ts.map +0 -1
  540. package/dist/modules/order/utils/slot.js.map +0 -1
  541. package/dist/modules/order/utils/system.d.ts.map +0 -1
  542. package/dist/modules/order/utils/system.js.map +0 -1
  543. package/dist/modules/order/utils/timeout.d.ts.map +0 -1
  544. package/dist/modules/order/utils/timeout.js.map +0 -1
  545. package/dist/modules/order/utils/validate.d.ts.map +0 -1
  546. package/dist/modules/order/utils/validate.js.map +0 -1
  547. package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
  548. package/dist/modules/order/utils/withPoolRef.js.map +0 -1
  549. package/dist/modules/order/working_grid.d.ts.map +0 -1
  550. package/dist/modules/order/working_grid.js.map +0 -1
  551. package/dist/modules/path_api.d.ts.map +0 -1
  552. package/dist/modules/path_api.js.map +0 -1
  553. package/dist/modules/paths.d.ts.map +0 -1
  554. package/dist/modules/paths.js.map +0 -1
  555. package/dist/modules/process_discovery.d.ts.map +0 -1
  556. package/dist/modules/process_discovery.js.map +0 -1
  557. package/dist/modules/runtime.d.ts.map +0 -1
  558. package/dist/modules/runtime.js.map +0 -1
  559. package/dist/modules/runtime_settings.d.ts.map +0 -1
  560. package/dist/modules/runtime_settings.js.map +0 -1
  561. package/dist/modules/settings_merge.d.ts.map +0 -1
  562. package/dist/modules/settings_merge.js.map +0 -1
  563. package/dist/modules/socket_json_client.d.ts.map +0 -1
  564. package/dist/modules/socket_json_client.js.map +0 -1
  565. package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
  566. package/dist/modules/storage/browser_adapter.js.map +0 -1
  567. package/dist/modules/storage/index.d.ts.map +0 -1
  568. package/dist/modules/storage/index.js.map +0 -1
  569. package/dist/modules/storage/node_adapter.d.ts.map +0 -1
  570. package/dist/modules/storage/node_adapter.js.map +0 -1
  571. package/dist/modules/storage/types.d.ts.map +0 -1
  572. package/dist/modules/storage/types.js.map +0 -1
  573. package/dist/modules/types.d.ts.map +0 -1
  574. package/dist/modules/types.js.map +0 -1
  575. package/dist/modules/utils/base58check.d.ts.map +0 -1
  576. package/dist/modules/utils/base58check.js.map +0 -1
  577. package/dist/modules/utils/build_dir.d.ts.map +0 -1
  578. package/dist/modules/utils/build_dir.js.map +0 -1
  579. package/dist/modules/utils/chain_logs.d.ts.map +0 -1
  580. package/dist/modules/utils/chain_logs.js.map +0 -1
  581. package/dist/modules/utils/errors.d.ts.map +0 -1
  582. package/dist/modules/utils/errors.js.map +0 -1
  583. package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
  584. package/dist/modules/utils/sanitize_key.js.map +0 -1
  585. package/dist/modules/validate_profiles.d.ts.map +0 -1
  586. package/dist/modules/validate_profiles.js.map +0 -1
  587. package/dist/pm2.d.ts.map +0 -1
  588. package/dist/pm2.js.map +0 -1
  589. package/dist/scripts/analyze-credit.d.ts.map +0 -1
  590. package/dist/scripts/analyze-credit.js.map +0 -1
  591. package/dist/scripts/analyze-git.d.ts.map +0 -1
  592. package/dist/scripts/analyze-git.js.map +0 -1
  593. package/dist/scripts/analyze-orders.d.ts.map +0 -1
  594. package/dist/scripts/analyze-orders.js.map +0 -1
  595. package/dist/scripts/chart_command.d.ts.map +0 -1
  596. package/dist/scripts/chart_command.js.map +0 -1
  597. package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
  598. package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
  599. package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
  600. package/dist/scripts/diagnose-pool-history.js.map +0 -1
  601. package/dist/scripts/divergence-calc.d.ts.map +0 -1
  602. package/dist/scripts/divergence-calc.js.map +0 -1
  603. package/dist/scripts/dw.d.ts.map +0 -1
  604. package/dist/scripts/dw.js.map +0 -1
  605. package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
  606. package/dist/scripts/generate_lp_chart.js.map +0 -1
  607. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
  608. package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
  609. package/dist/scripts/native_release_gates.d.ts.map +0 -1
  610. package/dist/scripts/native_release_gates.js.map +0 -1
  611. package/dist/scripts/print_grid.d.ts.map +0 -1
  612. package/dist/scripts/print_grid.js.map +0 -1
  613. package/dist/scripts/run-tests.d.ts.map +0 -1
  614. package/dist/scripts/run-tests.js.map +0 -1
  615. package/dist/scripts/runner.d.ts.map +0 -1
  616. package/dist/scripts/runner.js.map +0 -1
  617. package/dist/scripts/sync-version.d.ts.map +0 -1
  618. package/dist/scripts/sync-version.js.map +0 -1
  619. package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
  620. package/dist/scripts/test-credit-renewal.js.map +0 -1
  621. package/dist/scripts/tv.d.ts.map +0 -1
  622. package/dist/scripts/tv.js.map +0 -1
  623. package/dist/scripts/update.d.ts.map +0 -1
  624. package/dist/scripts/update.js.map +0 -1
  625. package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
  626. package/dist/scripts/update_dist_freshness.js.map +0 -1
  627. package/dist/scripts/validate_bots.d.ts.map +0 -1
  628. package/dist/scripts/validate_bots.js.map +0 -1
  629. package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
  630. package/dist/scripts/verify-browser-bundle.js.map +0 -1
  631. package/dist/unlock.d.ts.map +0 -1
  632. package/dist/unlock.js.map +0 -1
@@ -1,861 +0,0 @@
1
- 'use strict';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
6
- import { computeAverageAmaSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
7
- import { range } from '../math_utils.js';
8
- import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
9
- import { getStorage } from '../../modules/storage/index.js';
10
- import { PATHS } from '../../modules/paths.js';
11
- import { GRID_LIMITS, MARKET_ADAPTER } from '../../modules/constants.js';
12
- const { ensureDir, readJSON, writeJSON } = getStorage();
13
-
14
-
15
- // Default mirrors production sizing: createOrderGrid sizes EVERY rail slot in
16
- // bounds (modules/order/grid.ts), it does not cap per side. Infinity = all
17
- // slots; --active-orders N restores a bounded run.
18
- const DEFAULT_ACTIVE_ORDERS = Infinity;
19
- const DEFAULT_FEE_ROUNDTRIP_PCT = 0.20;
20
-
21
- // BTS operation fees — same model as backtest_ama_sweep. Every placement
22
- // (initial grid, reset rebuild, per-cycle slot refill) pays a maker create
23
- // fee, every cancel pays a cancel fee. Fees are converted into percentage
24
- // points against --bts-fee-capital so they deduct from net capture in the
25
- // same units as the rest of the accounting.
26
- const DEFAULT_BTS_CREATE_FEE = 0.48260;
27
- const DEFAULT_BTS_CANCEL_FEE = 0.00482;
28
- const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.10;
29
- const DEFAULT_TX_FEE_PRICE = 1.0;
30
- const DEFAULT_BTS_FEE_CAPITAL = 10000;
31
-
32
- // ── Production grid-reset triggers (MARKET_ADAPTER, modules/constants.ts) ────
33
- //
34
- // Trigger A — AMA delta: the live adapter records the AMA center and writes a
35
- // recalculate.<botKey>.trigger when AMA moves ±AMA_DELTA_THRESHOLD_PERCENT
36
- // from that recorded center; the center re-records only when a trigger fires
37
- // (ratchet semantics — see analyze_ama_price_changes.trackRepositions).
38
- // --reposition-pct overrides the default.
39
- const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
40
- //
41
- // Trigger B — AMA slope delta, plus the grid price offset, are BOTH gated in
42
- // production behind the per-bot asymmetricBounds whitelist
43
- // (market_adapter_service.ts: isGridRangeScalingWhitelisted consumes both
44
- // shouldTrigger at the slope-reset write and computeGridPriceOffsetPlan via
45
- // README "asymmetricBounds whitelist also enables gridPriceOffsetPct").
46
- // The sim therefore exposes one switch, default OFF (typical non-whitelisted
47
- // bot): --asymmetric-bounds enables slope-delta resets AND slope-ratio offset.
48
- // Trigger B fires when |slopePct_now − baseline| reaches
49
- // (AMA_SLOPE_DELTA_THRESHOLD_PERCENT / 100) × DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
50
- // where slopePct is the average per-bar AMA change over
51
- // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeAverageAmaSlopePct) and the
52
- // baseline mirrors botState.gridRangeScalingAmaSlope (re-seeded every reset).
53
- const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
54
- const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
55
- const SLOPE_LOOKBACK_BARS = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
56
- const SLOPE_NEUTRAL_ZONE_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
57
-
58
- // Spread-gap floor knobs (GRID_LIMITS): the effective target spread is
59
- // clamped up to incrementPercent × MIN_SPREAD_FACTOR and the gap is never
60
- // narrower than MIN_SPREAD_ORDERS slots — mirrored from calculateGapSlots
61
- // (modules/order/utils/math.ts).
62
- const DEFAULT_MIN_SPREAD_FACTOR = GRID_LIMITS.MIN_SPREAD_FACTOR;
63
-
64
- // Inventory-risk penalty weights (in score points)
65
- const RISK_W_DURATION = 1.0; // avg open bars
66
- const RISK_W_PEAK_OPEN = 2.0; // peak simultaneous open orders
67
- const RISK_W_IMBALANCE = 1.2; // avg |openBuy-openSell|
68
- const RISK_W_CANCEL = 0.15; // canceled on reposition
69
-
70
- const DEFAULT_SPREAD_VALUES = range(0.4, 1.6, 0.1);
71
- const DEFAULT_INCREMENT_VALUES = range(0.2, 0.8, 0.1);
72
- const DEFAULT_RATIO_VALUES = [1.5, 1.75, 2, 2.5, 3, 4, 5, 8, 10];
73
-
74
- function parseArgs() {
75
- const args = process.argv.slice(2);
76
- const out: {
77
- dataPath: string | null;
78
- resultsPath: string | null;
79
- spreadValues: number[];
80
- incrementValues: number[];
81
- ratioValues: number[];
82
- activeOrders: number;
83
- feeRoundtripPct: number;
84
- minSpreadFactor: number;
85
- repositionPct: number;
86
- asymmetricBounds: boolean;
87
- btsCreateFee: number;
88
- btsCancelFee: number;
89
- makerCreateFactor: number;
90
- txFeePrice: number;
91
- btsFeeCapital: number;
92
- riskWDuration: number;
93
- riskWPeakOpen: number;
94
- riskWImbalance: number;
95
- riskWCancel: number;
96
- } = {
97
- dataPath: null,
98
- resultsPath: null,
99
- spreadValues: DEFAULT_SPREAD_VALUES,
100
- incrementValues: DEFAULT_INCREMENT_VALUES,
101
- ratioValues: DEFAULT_RATIO_VALUES,
102
- activeOrders: DEFAULT_ACTIVE_ORDERS,
103
- feeRoundtripPct: DEFAULT_FEE_ROUNDTRIP_PCT,
104
- minSpreadFactor: DEFAULT_MIN_SPREAD_FACTOR,
105
- repositionPct: DEFAULT_REPOSITION_PCT,
106
- asymmetricBounds: false,
107
- btsCreateFee: DEFAULT_BTS_CREATE_FEE,
108
- btsCancelFee: DEFAULT_BTS_CANCEL_FEE,
109
- makerCreateFactor: DEFAULT_BTS_MAKER_CREATE_FACTOR,
110
- txFeePrice: DEFAULT_TX_FEE_PRICE,
111
- btsFeeCapital: DEFAULT_BTS_FEE_CAPITAL,
112
- riskWDuration: RISK_W_DURATION,
113
- riskWPeakOpen: RISK_W_PEAK_OPEN,
114
- riskWImbalance: RISK_W_IMBALANCE,
115
- riskWCancel: RISK_W_CANCEL,
116
- };
117
-
118
- for (let i = 0; i < args.length; i++) {
119
- const arg = args[i];
120
- // Valueless boolean flag — must be handled before the value lookup
121
- // below (and before the trailing-arg `if (!val) continue` guard).
122
- if (arg === '--asymmetric-bounds') { out.asymmetricBounds = true; continue; }
123
- const val = args[i + 1];
124
- if (!val) continue;
125
- switch (arg) {
126
- case '--data':
127
- out.dataPath = path.resolve(val);
128
- i++;
129
- break;
130
- case '--results':
131
- out.resultsPath = path.resolve(val);
132
- i++;
133
- break;
134
- case '--spread':
135
- out.spreadValues = parseListOrRange(val, DEFAULT_SPREAD_VALUES);
136
- i++;
137
- break;
138
- case '--increment':
139
- out.incrementValues = parseListOrRange(val, DEFAULT_INCREMENT_VALUES);
140
- i++;
141
- break;
142
- case '--ratio':
143
- out.ratioValues = parseListOrRange(val, DEFAULT_RATIO_VALUES);
144
- i++;
145
- break;
146
- case '--active-orders':
147
- out.activeOrders = Number(val);
148
- i++;
149
- break;
150
- case '--fee':
151
- out.feeRoundtripPct = Number(val);
152
- i++;
153
- break;
154
- case '--min-spread-factor':
155
- out.minSpreadFactor = Number(val);
156
- i++;
157
- break;
158
- case '--reposition-pct':
159
- out.repositionPct = Number(val);
160
- i++;
161
- break;
162
- case '--bts-create-fee':
163
- out.btsCreateFee = Number(val);
164
- i++;
165
- break;
166
- case '--bts-cancel-fee':
167
- out.btsCancelFee = Number(val);
168
- i++;
169
- break;
170
- case '--maker-create-factor':
171
- out.makerCreateFactor = Number(val);
172
- i++;
173
- break;
174
- case '--tx-fee-price':
175
- out.txFeePrice = Number(val);
176
- i++;
177
- break;
178
- case '--bts-fee-capital':
179
- out.btsFeeCapital = Number(val);
180
- i++;
181
- break;
182
- case '--risk-duration':
183
- out.riskWDuration = Number(val);
184
- i++;
185
- break;
186
- case '--risk-peak-open':
187
- out.riskWPeakOpen = Number(val);
188
- i++;
189
- break;
190
- case '--risk-imbalance':
191
- out.riskWImbalance = Number(val);
192
- i++;
193
- break;
194
- case '--risk-cancel':
195
- out.riskWCancel = Number(val);
196
- i++;
197
- break;
198
- }
199
- }
200
-
201
- if (!out.dataPath) {
202
- throw new Error('--data <path-to-lp-candles.json> is required');
203
- }
204
-
205
- if (!out.resultsPath) {
206
- out.resultsPath = resolveAutoResultsPath(out.dataPath);
207
- }
208
-
209
- return out;
210
- }
211
-
212
- /**
213
- * Auto-derive the AMA optimizer results file for a given LP candle data file.
214
- *
215
- * The optimizer names results `optimization_results_<base>_w<λ1>_<λ2>_<λ3>_<λ4>.json`
216
- * (per-AMA distance weights appended as a `_w...` suffix). To stay robust against
217
- * weight overrides, pick the most recently written `optimization_results_<base>_w*.json`
218
- * in the analysis results dir (legacy ama_fitting location still scanned); fall
219
- * back to the legacy `optimization_results_<base>.json` name if no suffixed file exists.
220
- */
221
- function resolveAutoResultsPath(dataPath: string): string {
222
- const base = path.basename(dataPath, '.json');
223
- // Canonical results dir first, then the legacy ama_fitting location so
224
- // previously generated files are still discovered.
225
- const dirs = [PATHS.ANALYSIS.RESULTS_DIR, path.join(PATHS.PROJECT_ROOT, 'analysis', 'ama_fitting')];
226
- const prefix = `optimization_results_${base}_w`;
227
- let newest: { file: string; mtimeMs: number } | null = null;
228
- try {
229
- for (const dir of dirs) {
230
- for (const entry of fs.readdirSync(dir)) {
231
- if (!entry.startsWith(prefix) || !entry.endsWith('.json')) continue;
232
- const full = path.join(dir, entry);
233
- const stat = fs.statSync(full);
234
- if (!newest || stat.mtimeMs > newest.mtimeMs) {
235
- newest = { file: full, mtimeMs: stat.mtimeMs };
236
- }
237
- }
238
- }
239
- } catch {
240
- // dir unreadable — fall through to legacy name check
241
- }
242
- if (newest) return newest.file;
243
- return path.join(PATHS.ANALYSIS.RESULTS_DIR, `optimization_results_${base}.json`);
244
- }
245
-
246
- function loadAmaStrategies(resultsPath: string) {
247
- const json = readJSON(resultsPath);
248
- const amas = (json.meta?.amas ?? {}) as any;
249
- const labels = { AMA1: 'AMA1', AMA2: 'AMA2', AMA3: 'AMA3', AMA4: 'AMA4' as string };
250
-
251
- const out: any[] = [];
252
- for (const [key, val] of Object.entries(amas)) {
253
- const a = val as any;
254
- if (!a || !Number.isFinite(a.er) || !Number.isFinite(a.fast) || !Number.isFinite(a.slow)) continue;
255
- out.push({
256
- id: key,
257
- name: labels[key as keyof typeof labels] ?? key,
258
- er: a.er,
259
- fast: a.fast,
260
- slow: a.slow,
261
- });
262
- }
263
-
264
- if (out.length !== 4) {
265
- throw new Error(`Expected 4 AMA strategies in results meta.amas, found ${out.length}`);
266
- }
267
- return out;
268
- }
269
-
270
- /**
271
- * Spread-gap width in slots — direct port of calculateGapSlots
272
- * (modules/order/utils/math.ts:1228). The effective target spread is clamped
273
- * up to incrementPercent × MIN_SPREAD_FACTOR and the gap never drops below
274
- * MIN_SPREAD_ORDERS slots. `incrementPercent`/`targetSpreadPercent` in PERCENT
275
- * units, matching the production signature.
276
- */
277
- function computeGapSlots(incrementPercent: number, targetSpreadPercent: number) {
278
- const step = 1 + (incrementPercent / 100);
279
- const minSpreadPercent = incrementPercent * GRID_LIMITS.MIN_SPREAD_FACTOR;
280
- const effectiveTargetSpread = Math.max(targetSpreadPercent || 0, minSpreadPercent);
281
- const requiredSteps = Math.ceil(Math.log(1 + (effectiveTargetSpread / 100)) / Math.log(step));
282
- return Math.max(GRID_LIMITS.MIN_SPREAD_ORDERS, requiredSteps - 1);
283
- }
284
-
285
- /**
286
- * Slope-ratio grid price offset — port of computeGridPriceOffsetPlan
287
- * (market_adapter/core/market_adapter_service.ts:92-119) combined with the
288
- * trend/slopeRatio semantics of computeAmaSlopeWeights
289
- * (market_adapter/core/strategies/ama_slope_model.ts):
290
- *
291
- * maxGridPriceOffsetPct = targetSpreadPercent / 2
292
- * slopeRatio = min(|slopePct| / DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT, 1)
293
- * direction = sign(slopePct) (0 inside the neutral zone)
294
- * offsetPct = direction × slopeRatio × maxGridPriceOffsetPct
295
- *
296
- * Production applies this to startPrice (grid.ts:982: startPrice × (1 +
297
- * offset/100)) only for asymmetricBounds-whitelisted bots; the sim applies it
298
- * to the placement center on every grid build when asymmetricBounds is on.
299
- */
300
- function computeGridPriceOffsetPct(slopePct: number, targetSpreadPercent: number) {
301
- if (!Number.isFinite(slopePct)) return 0;
302
- if (Math.abs(slopePct) <= SLOPE_NEUTRAL_ZONE_PCT) return 0;
303
- const slopeRatio = Math.min(Math.abs(slopePct) / SLOPE_MAX_PCT, 1);
304
- const maxGridPriceOffsetPct = targetSpreadPercent / 2;
305
- const direction = slopePct > 0 ? 1 : -1;
306
- const offsetPct = direction * slopeRatio * maxGridPriceOffsetPct;
307
- return Math.round(offsetPct * 1e6) / 1e6;
308
- }
309
-
310
- /**
311
- * Build a persistent grid with FIXED chain prices from a master rail —
312
- * port of createOrderGrid (modules/order/grid.ts:374-505):
313
- *
314
- * - Master rail: geometric progression starting at √(1±inc) × center and
315
- * expanding by (1±inc) steps outward, bounded by
316
- * [center/maxMinRatio, center×maxMinRatio] (grid.ts:428-444).
317
- * - Spread gap: gapSlots empty slots centered on the center price
318
- * (calculateIdealBoundary: boundaryIdx = splitIdx − floor(gap/2) − 1;
319
- * sells start at boundaryIdx + gapSlots + 1).
320
- * - By default every rail slot in bounds is sized (activeOrders = Infinity,
321
- * matching production); an explicit cap keeps only the slots nearest the
322
- * gap on each side.
323
- *
324
- * Order prices are placement-time constants — exactly like on-chain orders,
325
- * they do NOT follow AMA after placement.
326
- */
327
- function buildProductionGrid(center: number, spreadPct: number, incrementPctFrac: number, maxMinRatio: number, activeOrders: number) {
328
- const stepUp = 1 + incrementPctFrac;
329
- const stepDown = 1 - incrementPctFrac;
330
- const minBound = center / maxMinRatio;
331
- const maxBound = center * maxMinRatio;
332
-
333
- const rail: number[] = [];
334
- let p = center * Math.sqrt(stepUp);
335
- while (p <= maxBound) { rail.push(p); p *= stepUp; }
336
- p = center * Math.sqrt(stepDown);
337
- while (p >= minBound) { rail.push(p); p *= stepDown; }
338
- rail.sort((a, b) => a - b);
339
- if (rail.length === 0) return { buys: [], sells: [], rail: [], buySliceStart: 0, sellStartIdx: 0 };
340
-
341
- const gapSlots = computeGapSlots(incrementPctFrac * 100, spreadPct);
342
- let splitIdx = rail.findIndex((v) => v >= center);
343
- if (splitIdx === -1) splitIdx = rail.length;
344
- const buySpread = Math.floor(gapSlots / 2);
345
- const boundaryIdx = Math.max(0, Math.min(rail.length - 1, splitIdx - buySpread - 1));
346
- const sellStartIdx = boundaryIdx + gapSlots + 1;
347
-
348
- // Buys closest to the gap = highest priced below boundary; sells closest =
349
- // lowest priced above sellStartIdx. Rail + slice offsets are returned so
350
- // callers can map each placed slot onto its MASTER-RAIL index (rotation
351
- // walks adjacent rail nodes, exactly like the live anchor-&-refill hop).
352
- const buySliceStart = Math.max(0, boundaryIdx - activeOrders + 1);
353
- const sellsArr = rail.slice(sellStartIdx, sellStartIdx + activeOrders);
354
- return {
355
- buys: rail.slice(buySliceStart, boundaryIdx + 1),
356
- sells: sellsArr,
357
- rail,
358
- buySliceStart,
359
- sellStartIdx,
360
- };
361
- }
362
-
363
- /**
364
- * Slot-rotation simulation with FIXED chain prices, mirroring production
365
- * anchor-&-refill (strategy.ts) on top of the createOrderGrid geometry:
366
- *
367
- * - Initial grid built once at the post-warmup AMA (createOrderGrid geometry
368
- * via buildProductionGrid); order prices never follow AMA afterwards. When
369
- * asymmetricBounds is enabled the placement center is shifted by the
370
- * slope-ratio offset (#3) exactly like the live startPrice offset.
371
- * - Rotation economics (#1/#2/#15): a FILLED BUY at rail node k instantly
372
- * re-offers that base at the ADJACENT MASTER-RAIL NODE k+1; when that
373
- * refill sells, the rotation books exactly one rail hop minus the
374
- * round-trip fee, and the freed quote re-bids the node k-1 below. Slots
375
- * cycle on small oscillations between resets — the earnings model of a
376
- * refilled live slot, not a cross-gap differential.
377
- * - Inventory-funded selling: an INITIAL (unlinked) sell can only execute
378
- * against held inventory — it books its proceeds against the weighted
379
- * average entry of the position (the live bot funds sells from real
380
- * balances; unfundable sells stay open and retry, never shorting). Base
381
- * bought in the SAME bar does not fund unlinked sales until the next bar
382
- * (live balance updates propagate on the next maintenance tick).
383
- * - Same-bar guard: newly armed/refill orders carry a one-bar cooldown, so
384
- * a slot that just cycled cannot fill again inside the completion bar.
385
- * - Grid reset fires on EITHER production trigger:
386
- * (A) |AMA − recordedCenter| / recordedCenter ≥ repositionThresholdPct
387
- * (ratchet: recordedCenter updates only when the trigger fires),
388
- * (B) slope-delta reset, ONLY when asymmetricBounds (whitelist gate):
389
- * |slopePct_now − slopeBaseline| ≥ slopeDeltaThresholdPct
390
- * (= AMA_SLOPE_DELTA_THRESHOLD_PERCENT/100 ×
391
- * DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT), where slopePct is the
392
- * DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS average-slope series and
393
- * slopeBaseline mirrors botState.gridRangeScalingAmaSlope — seeded
394
- * at start and re-seeded on every reset.
395
- * On reset ALL unfilled orders are canceled (counted); bought-and-held
396
- * base REMAINS as inventory (live resync never market-sells) and merges
397
- * into the weighted-average-entry pool; a fresh grid is placed at the
398
- * new center.
399
- * - Scoring uses REALIZED rotations and op fees ONLY. The end-of-run
400
- * inventory position (units × mark-vs-avg-entry) is reported as an
401
- * informational field — it is real carried risk, but including unrealized
402
- * bag marks in the ranking objective let trend-following combos dump
403
- * phantom paper profit into the score.
404
- * - BTS operation fees (#9): every order placement (initial grid + every
405
- * armed refill/rebid) pays makerCreateFee × btsCreateFee, every reset
406
- * cancel pays btsCancelFee; totals are converted to percentage points
407
- * against the --bts-fee-capital reference and deducted from net capture.
408
- *
409
- * Differences from production (by design, documented):
410
- * #6 bar-granularity triggers and reset-vs-fill ordering (OHLC sim);
411
- * #7 all-or-nothing fills on raw hi/lo touch (no partial fills/dust/queue);
412
- * #8 unit sizes / percentage-point accounting instead of capital-weighted
413
- * dynamic sizing;
414
- * #10 pool-price fills (no book depth/slippage);
415
- * #11 no consolidation/dust-cancel/COW/collision mechanics.
416
- */
417
- function simulateForParams(candles: any, amaValues: any, params: any) {
418
- const { spreadPct, incrementPct, maxMinRatio, activeOrders, feeRoundtripPct,
419
- repositionThresholdPct, asymmetricBounds, risk,
420
- btsCreateFee, btsCancelFee, makerCreateFactor, txFeePrice, btsFeeCapital } = params;
421
- // Warmup follows production AMA seeding/convergence (getAmaWarmupBars)
422
- // instead of an arbitrary fraction of the dataset, so simulations never
423
- // start on SMA-warmup values when the fitted ER period is large.
424
- const skip = Math.min(params.warmupBars, Math.max(0, candles.length - 2));
425
- const singleLegFeePct = feeRoundtripPct / 2;
426
- const slopeDeltaThresholdPct = (SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT;
427
- const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
428
- const stepUpFrac = 1 + incrementPct; // one-rail-step rotation distance
429
-
430
- // First tradable bar: need a finite positive AMA to anchor the chain.
431
- let startIdx = Math.min(skip, candles.length - 1);
432
- let gridCenter = Number.NaN;
433
- for (let j = startIdx; j < candles.length; j++) {
434
- const v = amaValues[j];
435
- if (Number.isFinite(v) && v > 0) { gridCenter = v; startIdx = j; break; }
436
- }
437
-
438
- // Production AMA slope series (%/bar averaged over the lookback window).
439
- // Evaluated over full history like the live adapter (only bar-index guards).
440
- const slopeAt: (number | null)[] = new Array(candles.length).fill(null);
441
- for (let j = SLOPE_LOOKBACK_BARS; j < candles.length; j++) {
442
- const s = computeAverageAmaSlopePct(amaValues[j], amaValues[j - SLOPE_LOOKBACK_BARS], SLOPE_LOOKBACK_BARS);
443
- if (s != null && Number.isFinite(s)) slopeAt[j] = s;
444
- }
445
-
446
- // Open orders keyed by running id: { side, price, linkedBuyPrice,
447
- // linkedEntryBar, cooldownUntil }. linkedBuyPrice != null marks an armed
448
- // refill sell created by a specific filled buy (one-increment rotation).
449
- const orders = new Map<number, any>();
450
- let nextOrderId = 0;
451
- // Bought-and-held base across the whole run (weighted-average entry
452
- // pool). Never negative — sells without inventory stay pending.
453
- const inv = { units: 0, cost: 0 };
454
-
455
- let btsFeesBts = 0;
456
- let offsetAppliedCount = 0;
457
- // Master rail of the CURRENT epoch — rotation hops read adjacent nodes.
458
- let activeRail: number[] = [];
459
-
460
- const placeInitialGrid = (center: number, slopePct: number | null) => {
461
- const offsetPct = (asymmetricBounds && slopePct != null)
462
- ? computeGridPriceOffsetPct(slopePct, spreadPct)
463
- : 0;
464
- if (offsetPct !== 0) offsetAppliedCount++;
465
- const effCenter = center * (1 + offsetPct / 100);
466
- const built = buildProductionGrid(effCenter, spreadPct, incrementPct, maxMinRatio, activeOrders);
467
- activeRail = built.rail;
468
- orders.clear();
469
- // Rail indices matter: rotation re-offers/re-bids walk ADJACENT
470
- // master-rail nodes (buy at node k arms a sell at node k+1; the freed
471
- // quote re-bids node k-1), preserving the exact production hop sizes.
472
- built.buys.forEach((price, i) => orders.set(nextOrderId++, {
473
- side: 'buy', price, railIdx: built.buySliceStart + i,
474
- linkedBuyPrice: null, linkedEntryBar: -1, cooldownUntil: -1,
475
- }));
476
- built.sells.forEach((price, i) => orders.set(nextOrderId++, {
477
- side: 'sell', price, railIdx: built.sellStartIdx + i,
478
- linkedBuyPrice: null, linkedEntryBar: -1, cooldownUntil: -1,
479
- }));
480
- btsFeesBts += (built.buys.length + built.sells.length) * makerCreateFeeBts;
481
- };
482
-
483
- let touchedOrders = 0;
484
- let cyclesTotal = 0;
485
- let rotationCount = 0; // linked ping-pong rotations (buy → refill sell)
486
- let inventorySaleCount = 0; // unlinked sells executed against held bags
487
- let canceledOnReposition = 0;
488
- let repositionCount = 0;
489
- let driftTriggerCount = 0;
490
- let slopeTriggerCount = 0;
491
- let totalGrossCapturePct = 0;
492
- let totalNetCapturePct = 0;
493
- let peakOpenOrders = 0;
494
- let imbalanceSum = 0;
495
- let imbalanceSamples = 0;
496
- let matchedOpenDurationBars = 0;
497
-
498
- const invAvgEntry = () => (inv.units > 0 ? inv.cost / inv.units : 0);
499
-
500
- if (Number.isFinite(gridCenter)) placeInitialGrid(gridCenter, slopeAt[startIdx]);
501
-
502
- // Slope-delta baseline: mirrors botState.gridRangeScalingAmaSlope —
503
- // seeded at bootstrap (first cycle) and re-seeded to the current slope on
504
- // EVERY grid reset (advanceTriggeredBotState), so trigger B measures how
505
- // far slope has moved SINCE THE LAST RESET, not bar-over-bar jitter.
506
- let slopeBaseline: number | null = null;
507
- for (let j = startIdx + 1; j < candles.length; j++) {
508
- if (slopeAt[j] != null) { slopeBaseline = slopeAt[j]; break; }
509
- }
510
-
511
- for (let i = startIdx + 1; i < candles.length; i++) {
512
- const ama = amaValues[i];
513
- const hi = candles[i].high;
514
- const lo = candles[i].low;
515
-
516
- // ── Grid-reset check: trigger A (AMA delta) always; trigger B
517
- // (slope delta) only under the asymmetricBounds whitelist gate.
518
- let shouldReset = false;
519
- if (Number.isFinite(ama) && ama > 0) {
520
- const driftPct = (Math.abs(ama - gridCenter) / gridCenter) * 100;
521
- if (driftPct >= repositionThresholdPct) { shouldReset = true; driftTriggerCount++; }
522
- }
523
- if (!shouldReset && asymmetricBounds && slopeBaseline != null && slopeAt[i] != null) {
524
- const slopeDeltaPct = Math.abs(slopeAt[i]! - slopeBaseline);
525
- if (slopeDeltaPct >= slopeDeltaThresholdPct) { shouldReset = true; slopeTriggerCount++; }
526
- }
527
-
528
- if (shouldReset && Number.isFinite(ama) && ama > 0) {
529
- canceledOnReposition += orders.size;
530
- btsFeesBts += orders.size * btsCancelFee;
531
- orders.clear(); // inventory survives — resync never market-sells
532
- repositionCount++;
533
- gridCenter = ama; // ratchet the recorded center to the current AMA
534
- // Re-seed the slope baseline with the current slope (falls back to
535
- // the previous baseline when slope is not ready — same as
536
- // advanceTriggeredBotState's `|| previous` chain).
537
- if (slopeAt[i] != null) slopeBaseline = slopeAt[i];
538
- placeInitialGrid(gridCenter, slopeAt[i]);
539
- }
540
-
541
- const currentOpen = orders.size;
542
- if (currentOpen > peakOpenOrders) peakOpenOrders = currentOpen;
543
- let buyCount = 0;
544
- for (const [, o] of orders) { if (o.side === 'buy') buyCount++; }
545
- imbalanceSum += Math.abs(buyCount - (orders.size - buyCount));
546
- imbalanceSamples++;
547
-
548
- // ── Fill detection against FIXED chain prices ───────────────────
549
- const filledBuys: { id: number; order: any }[] = [];
550
- const filledSells: { id: number; order: any }[] = [];
551
- for (const [id, o] of orders) {
552
- if (i < o.cooldownUntil) continue;
553
- if (o.side === 'buy' && lo <= o.price) filledBuys.push({ id, order: o });
554
- else if (o.side === 'sell' && hi >= o.price) filledSells.push({ id, order: o });
555
- }
556
- touchedOrders += filledBuys.length + filledSells.length;
557
- // Base held BEFORE this bar's intakes — an unlinked sell may only
558
- // dispose against pre-existing funds (live balance updates propagate
559
- // on the next maintenance tick; same-bar funding is not assumed).
560
- const invAtBarStart = inv.units;
561
-
562
- // ── Buy intakes first: base enters inventory, refill armed at the
563
- // ADJACENT MASTER-RAIL NODE above (anchor-&-refill hop; cooldown
564
- // blocks same-bar recycles).
565
- for (const f of filledBuys) {
566
- orders.delete(f.id);
567
- inv.units += 1;
568
- inv.cost += f.order.price;
569
- const upIdx = (f.order.railIdx ?? -1) + 1;
570
- const refillPrice = activeRail[upIdx] ?? f.order.price * stepUpFrac;
571
- orders.set(nextOrderId++, {
572
- side: 'sell',
573
- price: refillPrice,
574
- railIdx: upIdx,
575
- linkedBuyPrice: f.order.price,
576
- linkedEntryBar: i,
577
- cooldownUntil: i + 1,
578
- });
579
- btsFeesBts += makerCreateFeeBts;
580
- }
581
-
582
- // ── Sell disposals: linked refills book the one-rail-hop rotation;
583
- // unlinked (initial-grid) sells need held inventory — no shorting.
584
- // Linked refills resolve FIRST so same-bar cross-gap inventory
585
- // sales against a fresh bag cannot happen.
586
- filledSells.sort((a, b) => ((a.order.linkedBuyPrice != null ? 0 : 1) - (b.order.linkedBuyPrice != null ? 0 : 1)));
587
- let disposables = invAtBarStart;
588
- for (const f of filledSells) {
589
- const o = f.order;
590
- if (o.linkedBuyPrice != null) {
591
- const grossPct = (o.price / o.linkedBuyPrice - 1) * 100;
592
- totalGrossCapturePct += grossPct;
593
- totalNetCapturePct += grossPct - feeRoundtripPct;
594
- cyclesTotal++;
595
- rotationCount++;
596
- matchedOpenDurationBars += Math.abs(i - o.linkedEntryBar);
597
- // Dispose the unit its own rotation bought.
598
- const applied = Math.min(1, inv.units);
599
- inv.cost -= applied * invAvgEntry();
600
- inv.units -= applied;
601
- // Its disposal also drains the pre-bar funding budget —
602
- // otherwise later unlinked sales could overspend stock.
603
- disposables -= applied;
604
- // Freed quote re-bids the ADJACENT RAIL NODE below.
605
- const downIdx = (o.railIdx ?? 0) - 1;
606
- const rebidPrice = activeRail[downIdx] ?? o.price / stepUpFrac;
607
- orders.delete(f.id);
608
- orders.set(nextOrderId++, {
609
- side: 'buy',
610
- price: rebidPrice,
611
- railIdx: downIdx,
612
- linkedBuyPrice: null,
613
- linkedEntryBar: -1,
614
- cooldownUntil: i + 1,
615
- });
616
- btsFeesBts += makerCreateFeeBts;
617
- } else if (disposables >= 1) {
618
- const avgEntry = invAvgEntry();
619
- const grossPct = (o.price / avgEntry - 1) * 100;
620
- totalGrossCapturePct += grossPct;
621
- totalNetCapturePct += grossPct - feeRoundtripPct;
622
- cyclesTotal++;
623
- inventorySaleCount++;
624
- inv.cost -= avgEntry; // remove that unit at pool-average cost
625
- inv.units -= 1;
626
- disposables -= 1;
627
- orders.delete(f.id); // sold bag is gone; slot not re-armed
628
- } else {
629
- // Unfundable (no base to sell): stays open, retries next bar.
630
- o.cooldownUntil = i + 1;
631
- }
632
- }
633
- }
634
-
635
- // ── End-of-run inventory mark (informational, NOT in score) ────────
636
- // Bought-and-held base is real carried risk, but unrealized bag marks are
637
- // excluded from ranking so trend-following combos can't dump phantom
638
- // paper profit into the objective. Marked once at the final close with a
639
- // single-leg exit fee per unit.
640
- const lastClose = candles.length > 0 ? candles[candles.length - 1].close : NaN;
641
- const inventoryUnits = inv.units;
642
- const inventoryAvgEntry = invAvgEntry();
643
- const inventoryNetPts = inventoryUnits > 0 && Number.isFinite(lastClose) && lastClose > 0
644
- ? (((lastClose / inventoryAvgEntry) - 1) * 100 - singleLegFeePct) * inventoryUnits
645
- : 0;
646
-
647
- // BTS operation fees → percentage points against the reference capital.
648
- const btsFeePts = (btsFeesBts * txFeePrice) / Math.max(1, btsFeeCapital) * 100;
649
- const totalNetCaptureAfterFeesPct = totalNetCapturePct - btsFeePts;
650
-
651
- const fillEfficiency = touchedOrders > 0 ? (cyclesTotal / touchedOrders) * 100 : 0;
652
- const avgNetPerPair = cyclesTotal > 0 ? totalNetCapturePct / cyclesTotal : 0;
653
- const utilization = (touchedOrders / Math.max(1, candles.length - skip)) * 100;
654
- const avgOpenDurationBars = rotationCount > 0 ? (matchedOpenDurationBars / rotationCount) : 0;
655
- const avgImbalance = imbalanceSamples > 0 ? (imbalanceSum / imbalanceSamples) : 0;
656
- const riskPenalty =
657
- (avgOpenDurationBars * risk.duration) +
658
- (peakOpenOrders * risk.peakOpen) +
659
- (avgImbalance * risk.imbalance) +
660
- (canceledOnReposition * risk.cancel);
661
- const baseScore = totalNetCaptureAfterFeesPct * (fillEfficiency / 100);
662
- const score = baseScore - riskPenalty;
663
-
664
- return {
665
- spreadPct,
666
- incrementPct,
667
- maxMinRatio,
668
- touchedOrders,
669
- matchedPairs: cyclesTotal,
670
- cyclesTotal,
671
- rotationCount,
672
- inventorySaleCount,
673
- avgCyclesPerSlot: cyclesTotal / Math.max(1, peakOpenOrders),
674
- fillEfficiency,
675
- totalGrossCapturePct,
676
- totalNetCapturePct,
677
- btsFeePts,
678
- btsFeesBts,
679
- totalNetCaptureAfterFeesPct,
680
- avgNetPerPair,
681
- canceledOnReposition,
682
- repositionCount,
683
- driftTriggerCount,
684
- slopeTriggerCount,
685
- inventoryUnits,
686
- inventoryAvgEntry,
687
- inventoryNetPts,
688
- offsetAppliedCount,
689
- avgOpenDurationBars,
690
- peakOpenOrders,
691
- avgImbalance,
692
- riskPenalty,
693
- baseScore,
694
- utilization,
695
- score,
696
- };
697
- }
698
-
699
- function run() {
700
- const cfg = parseArgs();
701
- if (!Number.isFinite(cfg.minSpreadFactor) || cfg.minSpreadFactor <= 0) {
702
- throw new Error(`Invalid min spread factor: ${cfg.minSpreadFactor}`);
703
- }
704
- for (const [k, v] of Object.entries({
705
- riskDuration: cfg.riskWDuration,
706
- riskPeakOpen: cfg.riskWPeakOpen,
707
- riskImbalance: cfg.riskWImbalance,
708
- riskCancel: cfg.riskWCancel,
709
- })) {
710
- if (!Number.isFinite(v) || v < 0) throw new Error(`Invalid ${k}: ${v}`);
711
- }
712
- const loaded = loadLpData(cfg.dataPath!);
713
- const candles = loaded.candles;
714
- const closes = candles.map((c: any) => c.close);
715
- const strategies = loadAmaStrategies(cfg.resultsPath!);
716
-
717
- if (!Number.isFinite(cfg.repositionPct) || cfg.repositionPct <= 0) {
718
- throw new Error(`Invalid reposition threshold: ${cfg.repositionPct}`);
719
- }
720
-
721
- const totalCombos = cfg.spreadValues.length * cfg.incrementValues.length * cfg.ratioValues.length;
722
-
723
- console.log('================================================================================');
724
- console.log(' BOT FITTING BACKTEST (1h LP candles)');
725
- console.log('================================================================================');
726
- console.log(` Data: ${path.basename(cfg.dataPath!)} (${candles.length} candles)`);
727
- console.log(` Results file: ${path.basename(cfg.resultsPath!)}`);
728
- console.log(` Spread grid: ${cfg.spreadValues[0]}..${cfg.spreadValues[cfg.spreadValues.length - 1]}% (${cfg.spreadValues.length})`);
729
- console.log(` Increment: ${cfg.incrementValues[0]}..${cfg.incrementValues[cfg.incrementValues.length - 1]}% (${cfg.incrementValues.length})`);
730
- console.log(` Max/Min ratio:${cfg.ratioValues[0]}..${cfg.ratioValues[cfg.ratioValues.length - 1]} (${cfg.ratioValues.length})`);
731
- console.log(` Active orders:${Number.isFinite(cfg.activeOrders) ? cfg.activeOrders : 'all'} per side (Infinity = every rail slot, matching production)`);
732
- console.log(` Fee RT: ${cfg.feeRoundtripPct}%`);
733
- console.log(` Spread floor: spread >= ${cfg.minSpreadFactor} x increment`);
734
- console.log(` Reset (A): AMA drift >= ${cfg.repositionPct}% from recorded center${cfg.repositionPct === DEFAULT_REPOSITION_PCT ? ' (AMA_DELTA_THRESHOLD_PERCENT)' : ''}`);
735
- console.log(` Asym. bounds: ${cfg.asymmetricBounds ? 'ON — slope reset (B) + grid price offset enabled (whitelist semantics)' : 'OFF — typical non-whitelisted bot (production default)'}`);
736
- console.log(` Reset (B): |slope - slope@lastReset| >= ${(SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT}% (${SLOPE_TRIGGER_FACTOR}% x ${SLOPE_MAX_PCT}, lookback ${SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
737
- console.log(` Tx fees: create=${fmt(cfg.btsCreateFee * cfg.makerCreateFactor, 5)} BTS, cancel=${fmt(cfg.btsCancelFee, 5)} BTS, 1 BTS=${fmt(cfg.txFeePrice, 2)} units, capital=${fmt(cfg.btsFeeCapital, 0)}`);
738
- console.log(` Risk W: duration=${cfg.riskWDuration}, peakOpen=${cfg.riskWPeakOpen}, imbalance=${cfg.riskWImbalance}, cancel=${cfg.riskWCancel}`);
739
- console.log(` Combos/AMA: ${totalCombos}\n`);
740
-
741
- const byAma: any[] = [];
742
-
743
- for (const s of strategies) {
744
- const amaValues = calculateAMA(closes, { erPeriod: s.er, fastPeriod: s.fast, slowPeriod: s.slow });
745
- // Production-aligned warmup: ER window + convergence (getAmaWarmupBars).
746
- const warmupBars = getAmaWarmupBars(s.er, s.slow, 0, s.fast);
747
- let best: any = null;
748
-
749
- for (const spreadPct of cfg.spreadValues) {
750
- for (const incrementPct of cfg.incrementValues) {
751
- // Dedup guard only: computeGapSlots clamps the effective target
752
- // spread up to increment × MIN_SPREAD_FACTOR, so combos below the
753
- // floor would build an identical grid to the floored combo.
754
- if (spreadPct + Number.EPSILON < (cfg.minSpreadFactor * incrementPct)) continue;
755
- for (const maxMinRatio of cfg.ratioValues) {
756
- const sim = simulateForParams(candles, amaValues, {
757
- spreadPct,
758
- incrementPct: incrementPct / 100,
759
- maxMinRatio,
760
- activeOrders: cfg.activeOrders,
761
- feeRoundtripPct: cfg.feeRoundtripPct,
762
- repositionThresholdPct: cfg.repositionPct,
763
- asymmetricBounds: cfg.asymmetricBounds,
764
- btsCreateFee: cfg.btsCreateFee,
765
- btsCancelFee: cfg.btsCancelFee,
766
- makerCreateFactor: cfg.makerCreateFactor,
767
- txFeePrice: cfg.txFeePrice,
768
- btsFeeCapital: cfg.btsFeeCapital,
769
- warmupBars,
770
- risk: {
771
- duration: cfg.riskWDuration,
772
- peakOpen: cfg.riskWPeakOpen,
773
- imbalance: cfg.riskWImbalance,
774
- cancel: cfg.riskWCancel,
775
- },
776
- });
777
- if (!best || sim.score > best.score) best = sim;
778
- }
779
- }
780
- }
781
-
782
- byAma.push({ strategy: s, best });
783
- }
784
-
785
- console.log('BEST PARAMS PER AMA');
786
- console.log('--------------------------------------------------------------------------------');
787
- console.log('AMA | spread | incr | ratio | cyc | fill% | net% | risk | score | inv-units (info)');
788
- console.log('---------------------------------|--------|------|-------|-------|-------|--------|-------|-------|-----------------');
789
- for (const row of byAma) {
790
- const b = row.best;
791
- if (!b) continue;
792
- console.log(
793
- `${row.strategy.name.padEnd(33)}| ` +
794
- `${fmt(b.spreadPct, 2).padStart(6)} | ` +
795
- `${fmt(b.incrementPct * 100, 2).padStart(4)} | ` +
796
- `${fmt(b.maxMinRatio, 2).padStart(5)} | ` +
797
- `${String(b.matchedPairs).padStart(5)} | ` +
798
- `${fmt(b.fillEfficiency, 1).padStart(5)} | ` +
799
- `${fmt(b.totalNetCapturePct, 1).padStart(6)} | ` +
800
- `${fmt(b.riskPenalty, 1).padStart(5)} | ` +
801
- `${fmt(b.score, 1).padStart(5)} | ` +
802
- `${fmt(b.inventoryUnits, 0).padStart(8)} (${fmt(b.inventoryNetPts, 1)} pts)`
803
- );
804
- }
805
- console.log('(* end-of-run inventory mark: informational only — excluded from scoring)');
806
- console.log();
807
-
808
- const outName = `bot_fitting_results_${path.basename(cfg.dataPath!, '.json')}.json`;
809
- const outPath = path.join(PATHS.ANALYSIS.RESULTS_DIR, outName);
810
- ensureDir(PATHS.ANALYSIS.RESULTS_DIR);
811
- writeJSON(outPath, {
812
- meta: {
813
- generatedAt: new Date().toISOString(),
814
- dataPath: path.relative(process.cwd(), cfg.dataPath!),
815
- resultsPath: path.relative(process.cwd(), cfg.resultsPath!),
816
- candles: candles.length,
817
- activeOrders: Number.isFinite(cfg.activeOrders) ? cfg.activeOrders : 'all',
818
- feeRoundtripPct: cfg.feeRoundtripPct,
819
- btsCreateFee: cfg.btsCreateFee,
820
- btsCancelFee: cfg.btsCancelFee,
821
- makerCreateFactor: cfg.makerCreateFactor,
822
- txFeePrice: cfg.txFeePrice,
823
- btsFeeCapital: cfg.btsFeeCapital,
824
- search: {
825
- spreadValues: cfg.spreadValues,
826
- incrementValues: cfg.incrementValues,
827
- ratioValues: cfg.ratioValues,
828
- minSpreadFactor: cfg.minSpreadFactor,
829
- repositionPct: cfg.repositionPct,
830
- asymmetricBounds: cfg.asymmetricBounds,
831
- combosPerAma: totalCombos,
832
- },
833
- scoring: {
834
- baseScore: 'totalNetCaptureAfterFeesPct * (fillEfficiency / 100)',
835
- gridModel: 'persistent fixed chain prices (createOrderGrid port): master rail at sqrt(1±inc) offsets bounded by [center/ratio, center*ratio], gapSlots spread zone centered on center; prices never follow AMA after placement',
836
- spreadParam: 'targetSpreadPercent for calculateGapSlots (floored at increment * MIN_SPREAD_FACTOR)',
837
- resetTriggers: `(A) AMA drift >= ${cfg.repositionPct}% from recorded center (ratchet)${cfg.asymmetricBounds ? ` OR (B) |slope - slopeAtLastReset| >= ${(SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT}% over ${SLOPE_LOOKBACK_BARS}-bar average slope (baseline re-seeded on every reset)` : ' (trigger B gated off — asymmetricBounds whitelist)'}`,
838
- gridPriceOffset: cfg.asymmetricBounds ? 'slope-ratio offset applied to placement center (direction * min(|slope|/maxSlopePct,1) * targetSpread/2) on every grid build' : 'disabled (asymmetricBounds whitelist)',
839
- repositionAccounting: 'unfilled orders canceled + counted (incl armed refills/rebids); bought-and-held base carries across resets in a weighted-average-entry inventory pool (resync never market-sells); end-of-run inventory mark is informational and excluded from scoring',
840
- cycleEconomics: 'slot rotation: filled buy re-offers one rail step up; that refill selling books ~increment% minus round-trip fee and the freed quote re-bids one step down; unlinked initial-grid sells only execute against held inventory at weighted-average entry (no shorting)',
841
- totalGrossCapturePct: 'sum of realized per-rotation gross from actual fixed prices (linked rotations + inventory sales)',
842
- totalNetCapturePct: 'realized gross - roundtrip fee per completed disposition; excludes the end-of-run inventory mark',
843
- btsFees: `every order placement (initial grid + armed refills/rebids) pays maker create (${cfg.btsCreateFee}*${cfg.makerCreateFactor} BTS), every reset cancel pays ${cfg.btsCancelFee} BTS; btsFeePts = total BTS * txFeePrice / btsFeeCapital * 100 deducted from net before scoring`,
844
- warmup: 'getAmaWarmupBars(er, slow, 0, fast)',
845
- riskPenalty: `avgOpenDurationBars*${cfg.riskWDuration} + peakOpenOrders*${cfg.riskWPeakOpen} + avgImbalance*${cfg.riskWImbalance} + canceledOnReposition*${cfg.riskWCancel}`,
846
- finalScore: 'baseScore - riskPenalty',
847
- },
848
- },
849
- results: byAma,
850
- });
851
-
852
- console.log(`Saved: ${path.relative(process.cwd(), outPath)}`);
853
- }
854
-
855
- // Main-thread entry guard: importing this module (e.g. from the logic tests)
856
- // must not execute the CLI run.
857
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
858
- run();
859
- }
860
-
861
- export { computeGapSlots, computeGridPriceOffsetPct, buildProductionGrid, simulateForParams };