dexbot 1.6.11 → 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 (354) hide show
  1. package/CHANGELOG.md +35 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +2 -0
  4. package/analysis/tradingview/README.md +1 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  7. package/claw/modules/chain_broadcast.ts +7 -1
  8. package/claw/modules/claw_launcher.ts +1 -1
  9. package/claw/modules/launcher_mode_detector.ts +9 -2
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.d.ts +1 -1
  14. package/dist/analysis/account_resolver.js +2 -1
  15. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  16. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  17. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  18. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  19. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  20. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  21. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  22. package/dist/analysis/analyze_args.d.ts +31 -0
  23. package/dist/analysis/analyze_args.js +41 -0
  24. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  25. package/dist/analysis/analyze_kalman.js +7 -17
  26. package/dist/analysis/analyze_regime.js +7 -17
  27. package/dist/analysis/analyze_regime_windows.js +8 -18
  28. package/dist/analysis/analyze_risk_profile.js +8 -18
  29. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  30. package/dist/analysis/analyze_volatility.js +7 -17
  31. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  32. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
  33. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  34. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
  35. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  36. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  37. package/dist/analysis/bot_key_utils.d.ts +18 -10
  38. package/dist/analysis/bot_key_utils.js +7 -4
  39. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  40. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  41. package/dist/analysis/chain_pool.d.ts +3 -1
  42. package/dist/analysis/chart_ui.d.ts +5 -2
  43. package/dist/analysis/chart_ui.js +6 -3
  44. package/dist/analysis/chart_utils.d.ts +5 -5
  45. package/dist/analysis/chart_utils.js +9 -0
  46. package/dist/analysis/fills_cache.d.ts +1 -1
  47. package/dist/analysis/fills_source.d.ts +2 -2
  48. package/dist/analysis/fills_source.js +14 -12
  49. package/dist/analysis/grid_correction_check.d.ts +1 -1
  50. package/dist/analysis/grid_correction_check.js +12 -11
  51. package/dist/analysis/math_utils.d.ts +7 -6
  52. package/dist/analysis/math_utils.js +5 -8
  53. package/dist/analysis/pnl_report.js +29 -29
  54. package/dist/analysis/price_sources.d.ts +8 -8
  55. package/dist/analysis/price_sources.js +5 -4
  56. package/dist/analysis/resolve_bot_accounts.js +2 -2
  57. package/dist/analysis/resolve_source.d.ts +1 -1
  58. package/dist/analysis/trade_profitability.d.ts +23 -2
  59. package/dist/analysis/trade_profitability.js +50 -50
  60. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  61. package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
  62. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  63. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  64. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  65. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  66. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  67. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
  68. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
  69. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
  70. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  71. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
  72. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  73. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  74. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  75. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  76. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  77. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  78. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  79. package/dist/credential-daemon.js +34 -20
  80. package/dist/dexbot.js +11 -11
  81. package/dist/market_adapter/candle_utils.d.ts +22 -18
  82. package/dist/market_adapter/candle_utils.js +24 -20
  83. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  84. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  85. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  86. package/dist/market_adapter/core/kibana_candles.js +9 -7
  87. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  88. package/dist/market_adapter/core/kibana_client.js +8 -7
  89. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  90. package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
  91. package/dist/market_adapter/core/market_adapter_service.js +137 -113
  92. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  93. package/dist/market_adapter/core/strategies/ama.js +2 -4
  94. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  95. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  96. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  97. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  98. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  99. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  100. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  101. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  102. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  103. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  104. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  106. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  107. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  108. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  109. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  110. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  111. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  112. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
  113. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  114. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  115. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  116. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  117. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  118. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  119. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  120. package/dist/market_adapter/inputs/window_cache.js +8 -8
  121. package/dist/market_adapter/interval_utils.d.ts +4 -4
  122. package/dist/market_adapter/log_format.d.ts +6 -6
  123. package/dist/market_adapter/log_format.js +28 -21
  124. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  125. package/dist/market_adapter/lp_chart_core.js +26 -192
  126. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  127. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  128. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  129. package/dist/market_adapter/market_adapter.d.ts +94 -32
  130. package/dist/market_adapter/market_adapter.js +67 -48
  131. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  132. package/dist/market_adapter/utils/adapter_client.js +2 -2
  133. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  134. package/dist/market_adapter/utils/chain.d.ts +50 -41
  135. package/dist/market_adapter/utils/chain.js +40 -46
  136. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  137. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  138. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  139. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  140. package/dist/market_adapter/utils/file_lock.js +36 -32
  141. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  142. package/dist/market_adapter/utils/native_history.js +35 -28
  143. package/dist/modules/account_bots.d.ts +577 -21
  144. package/dist/modules/account_bots.js +182 -158
  145. package/dist/modules/account_orders.d.ts +66 -30
  146. package/dist/modules/account_orders.js +22 -20
  147. package/dist/modules/authority_resolver.d.ts +12 -2
  148. package/dist/modules/authority_resolver.js +15 -8
  149. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  150. package/dist/modules/bitshares-native/chain_client.js +45 -46
  151. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  152. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  153. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  154. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  155. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  156. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  157. package/dist/modules/bitshares-native/index.d.ts +1 -1
  158. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  159. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  160. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  161. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  162. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  163. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  164. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  165. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  166. package/dist/modules/bitshares-native/serial/types.js +55 -62
  167. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  168. package/dist/modules/bitshares-native/signing_client.js +19 -14
  169. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  170. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  171. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  172. package/dist/modules/bitshares-native/transport.js +5 -4
  173. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  174. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  175. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  176. package/dist/modules/bitshares_client.d.ts +45 -13
  177. package/dist/modules/bitshares_client.js +28 -19
  178. package/dist/modules/bot_defaults.d.ts +6 -15
  179. package/dist/modules/bot_defaults.js +1 -5
  180. package/dist/modules/bot_settings.d.ts +44 -10
  181. package/dist/modules/bot_settings.js +11 -8
  182. package/dist/modules/bots_file_lock.d.ts +6 -6
  183. package/dist/modules/bots_file_lock.js +16 -12
  184. package/dist/modules/broadcast_failure.d.ts +2 -2
  185. package/dist/modules/broadcast_failure.js +5 -4
  186. package/dist/modules/chain_keys.d.ts +42 -40
  187. package/dist/modules/chain_keys.js +53 -45
  188. package/dist/modules/chain_orders.d.ts +93 -59
  189. package/dist/modules/chain_orders.js +31 -23
  190. package/dist/modules/constants.d.ts +527 -31
  191. package/dist/modules/constants.js +15 -47
  192. package/dist/modules/cr_planner.d.ts +40 -2
  193. package/dist/modules/credential_policy.d.ts +68 -8
  194. package/dist/modules/credential_policy.js +37 -31
  195. package/dist/modules/credential_session_cache.d.ts +2 -2
  196. package/dist/modules/credit_pricing.d.ts +42 -6
  197. package/dist/modules/credit_pricing.js +44 -30
  198. package/dist/modules/credit_runtime.d.ts +276 -118
  199. package/dist/modules/credit_runtime.js +462 -165
  200. package/dist/modules/crypto/browser_provider.js +6 -4
  201. package/dist/modules/crypto/node_provider.js +1 -1
  202. package/dist/modules/crypto/pure_scrypt.js +35 -4
  203. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  204. package/dist/modules/crypto/sync.d.ts +9 -9
  205. package/dist/modules/crypto/sync.js +16 -9
  206. package/dist/modules/dexbot_class.d.ts +195 -139
  207. package/dist/modules/dexbot_class.js +78 -28
  208. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  209. package/dist/modules/dexbot_cow_runtime.js +248 -206
  210. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  211. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  212. package/dist/modules/dexbot_fill_runtime.js +48 -41
  213. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  214. package/dist/modules/dexbot_maintenance_runtime.js +108 -83
  215. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  216. package/dist/modules/dexbot_startup_runtime.js +43 -43
  217. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  218. package/dist/modules/dexbot_state_recovery.js +18 -13
  219. package/dist/modules/fund_registry.d.ts +4 -2
  220. package/dist/modules/fund_registry.js +10 -10
  221. package/dist/modules/general_settings.d.ts +30 -4
  222. package/dist/modules/graceful_shutdown.d.ts +3 -3
  223. package/dist/modules/graceful_shutdown.js +2 -2
  224. package/dist/modules/grid_price_source.d.ts +1 -1
  225. package/dist/modules/key_store.d.ts +14 -8
  226. package/dist/modules/key_store.js +7 -6
  227. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  228. package/dist/modules/launcher/adapter_requirement.js +5 -5
  229. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  230. package/dist/modules/launcher/bot_supervisor.js +12 -11
  231. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  232. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  233. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  234. package/dist/modules/launcher/credential_daemon.js +2 -2
  235. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  236. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  237. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  238. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  239. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  240. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  241. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  242. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  243. package/dist/modules/launcher/supervisor_control.js +4 -2
  244. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  245. package/dist/modules/market_adapter_whitelist.js +15 -3
  246. package/dist/modules/node_manager.d.ts +41 -11
  247. package/dist/modules/node_manager.js +5 -4
  248. package/dist/modules/order/accounting.d.ts +53 -24
  249. package/dist/modules/order/accounting.js +16 -15
  250. package/dist/modules/order/async_lock.d.ts +5 -2
  251. package/dist/modules/order/async_lock.js +1 -1
  252. package/dist/modules/order/export.d.ts +7 -6
  253. package/dist/modules/order/export.js +1 -7
  254. package/dist/modules/order/format.d.ts +4 -4
  255. package/dist/modules/order/genesis_policy.d.ts +21 -18
  256. package/dist/modules/order/genesis_policy.js +12 -8
  257. package/dist/modules/order/grid.d.ts +142 -36
  258. package/dist/modules/order/grid.js +148 -123
  259. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  260. package/dist/modules/order/grid_reconcile.js +13 -12
  261. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  262. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  263. package/dist/modules/order/index.d.ts +263 -1
  264. package/dist/modules/order/logger.d.ts +45 -11
  265. package/dist/modules/order/logger.js +38 -40
  266. package/dist/modules/order/logger_state.d.ts +4 -4
  267. package/dist/modules/order/manager.d.ts +225 -180
  268. package/dist/modules/order/manager.js +80 -83
  269. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  270. package/dist/modules/order/processed_fill_store.js +16 -27
  271. package/dist/modules/order/strategy.d.ts +21 -13
  272. package/dist/modules/order/strategy.js +5 -6
  273. package/dist/modules/order/sync_engine.d.ts +91 -33
  274. package/dist/modules/order/sync_engine.js +84 -53
  275. package/dist/modules/order/utils/math.d.ts +157 -102
  276. package/dist/modules/order/utils/math.js +77 -38
  277. package/dist/modules/order/utils/order.d.ts +310 -110
  278. package/dist/modules/order/utils/order.js +122 -99
  279. package/dist/modules/order/utils/slot.d.ts +1 -1
  280. package/dist/modules/order/utils/system.d.ts +176 -26
  281. package/dist/modules/order/utils/system.js +86 -69
  282. package/dist/modules/order/utils/validate.d.ts +89 -41
  283. package/dist/modules/order/utils/validate.js +24 -22
  284. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  285. package/dist/modules/order/utils/withPoolRef.js +18 -12
  286. package/dist/modules/order/working_grid.d.ts +14 -13
  287. package/dist/modules/paths.d.ts +1 -4
  288. package/dist/modules/paths.js +1 -27
  289. package/dist/modules/process_discovery.d.ts +1 -1
  290. package/dist/modules/process_discovery.js +2 -1
  291. package/dist/modules/runtime.d.ts +7 -3
  292. package/dist/modules/runtime.js +4 -3
  293. package/dist/modules/runtime_settings.d.ts +15 -10
  294. package/dist/modules/runtime_settings.js +30 -24
  295. package/dist/modules/settings_merge.d.ts +29 -3
  296. package/dist/modules/settings_merge.js +56 -78
  297. package/dist/modules/socket_json_client.d.ts +7 -4
  298. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  299. package/dist/modules/storage/browser_adapter.js +7 -30
  300. package/dist/modules/storage/index.d.ts +1 -1
  301. package/dist/modules/storage/node_adapter.d.ts +45 -27
  302. package/dist/modules/storage/node_adapter.js +9 -9
  303. package/dist/modules/storage/types.d.ts +5 -4
  304. package/dist/modules/types.d.ts +1071 -2
  305. package/dist/modules/types.js +4 -1
  306. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  307. package/dist/modules/utils/asset_symbols.js +2 -1
  308. package/dist/modules/utils/errors.d.ts +9 -0
  309. package/dist/modules/utils/errors.js +23 -1
  310. package/dist/modules/utils/time_range.d.ts +1 -12
  311. package/dist/modules/utils/time_range.js +1 -1
  312. package/dist/modules/validate_profiles.js +53 -43
  313. package/dist/modules/version_notice.d.ts +14 -3
  314. package/dist/modules/version_notice.js +6 -4
  315. package/dist/pm2.d.ts +29 -27
  316. package/dist/pm2.js +5 -5
  317. package/dist/scripts/analyze-credit.d.ts +2 -1
  318. package/dist/scripts/analyze-credit.js +23 -24
  319. package/dist/scripts/analyze-orders.d.ts +77 -9
  320. package/dist/scripts/analyze-orders.js +65 -40
  321. package/dist/scripts/chart_command.d.ts +27 -18
  322. package/dist/scripts/chart_command.js +13 -11
  323. package/dist/scripts/check_any.d.ts +18 -0
  324. package/dist/scripts/check_any.js +126 -0
  325. package/dist/scripts/diagnose-pool-history.js +12 -7
  326. package/dist/scripts/print_grid.js +0 -1
  327. package/dist/scripts/run-tests.js +39 -7
  328. package/dist/scripts/runner.js +1 -1
  329. package/dist/scripts/test-credit-renewal.js +30 -21
  330. package/dist/scripts/update.d.ts +10 -5
  331. package/dist/scripts/update.js +168 -103
  332. package/dist/scripts/update_dist_freshness.js +1 -0
  333. package/dist/scripts/update_layout.d.ts +61 -0
  334. package/dist/scripts/update_layout.js +180 -0
  335. package/dist/scripts/validate_bots.js +2 -1
  336. package/dist/scripts/verify-browser-bundle.js +8 -0
  337. package/dist/unlock.d.ts +28 -3
  338. package/dist/unlock.js +63 -35
  339. package/docs/BITSHARES_ONBOARDING.md +2 -0
  340. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  341. package/docs/COW_INVARIANTS.md +13 -6
  342. package/docs/DEXBOT_COMPARISON.md +8 -8
  343. package/docs/EVOLUTION.md +10 -9
  344. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  345. package/docs/GRID_RECALCULATION.md +4 -2
  346. package/docs/GRID_RECONCILE.md +14 -3
  347. package/docs/LIFECYCLE.md +11 -11
  348. package/docs/MPA_CREDIT_USAGE.md +22 -3
  349. package/docs/README.md +14 -3
  350. package/docs/architecture.md +12 -9
  351. package/docs/developer_guide.md +6 -6
  352. package/market_adapter/README.md +6 -1
  353. package/modules/README.md +4 -1
  354. package/package.json +4 -1
@@ -30,44 +30,9 @@ import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELIN
30
30
  import { seedBotRuntimeConfig } from '../bot_defaults.js';
31
31
  import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
32
32
  import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
33
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement } from './utils/order.js';
34
- import { getErrorMessage } from '../utils/errors.js';
33
+ import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
34
+ import { getErrorMessage, getErrorCode } from '../utils/errors.js';
35
35
  const { toFiniteNumber } = Format;
36
- // ===============================================================================
37
- // SECTION 2: COW REBALANCE ENGINE
38
- // ===============================================================================
39
- /**
40
- * Stale-placement veto: whether a placement action crosses the plan's own
41
- * boundary and would fill immediately on stale market data.
42
- * - BUY create/update targeting a slot ABOVE the boundary is dropped; SELL
43
- * create/update targeting a slot BELOW the boundary is dropped. Strict
44
- * comparison: a placement AT the boundary is kept (the boundary slot is
45
- * the spread, which reconcile never targets).
46
- * - The reference is the PLAN'S OWN targetBoundary — and ONLY that: the
47
- * plan's slots derive from the same target grid, so a stale plan's
48
- * placements cross its own boundary while legitimate re-placements never
49
- * do (the boundary is capped, the fills are not). Fill-based veto lines
50
- * are deliberately NOT used — after a burst the fills sit beyond the
51
- * plan's legitimate re-place levels (e.g. SELL fills 5,6,7 with cap=1
52
- * moves the boundary only to slot 6), so ANY fill comparison can veto
53
- * valid placements, including the strategy's own rotations (a partial
54
- * SELL rotated into a slot below the last BUY fill after the boundary
55
- * crawled left). The guard is therefore "inert" for boundary-consistent
56
- * engine output by construction.
57
- * - Slot ids are compared within the plan's own grid generation
58
- * (targetBoundary and target slots are both from the current plan), so a
59
- * recenter between the fill capture and the plan cannot skew the
60
- * comparison. Both CREATE and UPDATE actions are guarded: the
61
- * cancel/create optimization can convert the same logical placement into
62
- * an UPDATE op (target slot = newGridId), which the CREATE-only check
63
- * would have missed.
64
- * - When no plan boundary is available (hand-built plans), nothing is
65
- * vetoed — fill evidence is not a reliable veto line. Non-placement
66
- * actions and non-grid-slot targets are never vetoed.
67
- * @param {Object} action - COW action
68
- * @param {number} planBoundary - The plan's target boundary slot index
69
- * @returns {string|null} Drop reason for the log, or null to keep the action
70
- */
71
36
  function stalePlacementDropReason(action, planBoundary) {
72
37
  const isPlacement = action?.type === COW_ACTIONS.CREATE || action?.type === COW_ACTIONS.UPDATE;
73
38
  if (!isPlacement)
@@ -134,7 +99,7 @@ class COWRebalanceEngine {
134
99
  this.assets = deps.assets;
135
100
  this.config = deps.config;
136
101
  }
137
- async execute({ masterGrid, gridVersion, boundaryIdx, funds, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, reserveEdgeAnchors = null }) {
102
+ async execute({ masterGrid, gridVersion, boundaryIdx, funds, manager = null, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, reserveEdgeAnchors = null }) {
138
103
  const startTime = Date.now();
139
104
  const workingGrid = new WorkingGrid(masterGrid, { baseVersion: gridVersion });
140
105
  const strategyParams = {
@@ -172,15 +137,15 @@ class COWRebalanceEngine {
172
137
  const reconcileResult = reconcileGrid(masterGrid, targetGrid, targetBoundary, {
173
138
  logger: (msg, level) => this.logger?.log(msg, level),
174
139
  dustThresholdPercent,
175
- gapSlots,
176
- evacStreaks,
140
+ gapSlots: gapSlots ?? undefined,
141
+ evacStreaks: evacStreaks ?? undefined,
177
142
  assets: this.assets
178
143
  });
179
144
  // Gap-evacuation telemetry: evacReady is the streak-tick output of
180
145
  // reconcileGrid (stuck in-band candidates). It must survive both
181
146
  // abort and success so the manager can act on it even when the
182
147
  // rebalance plan itself aborts for an unrelated reason.
183
- const evacReady = Array.isArray(reconcileResult?.evacReady)
148
+ const evacReady = Array.isArray(reconcileResult.evacReady)
184
149
  ? reconcileResult.evacReady
185
150
  : [];
186
151
  if (reconcileResult.aborted) {
@@ -188,10 +153,40 @@ class COWRebalanceEngine {
188
153
  aborted.evacReady = evacReady;
189
154
  return aborted;
190
155
  }
191
- const optimizedActions = optimizeRebalanceActions(reconcileResult.actions, masterGrid, {
156
+ // Fresh-placement cancel guard. Reconcile runs on a target snapshot
157
+ // that can be a beat behind a just-placed order; cancelling it burns
158
+ // fees, empties a level and re-places the same thing next cycle. Hold
159
+ // the whole slot's action group (a type-mismatch CANCEL is paired with
160
+ // a CREATE on the same id) for the grace window. The surplus is
161
+ // re-derived next cycle once the order has had time to prove itself.
162
+ const deferredFreshCancelSlots = new Set();
163
+ for (const action of reconcileResult.actions) {
164
+ if (action.type !== COW_ACTIONS.CANCEL || !action.orderId)
165
+ continue;
166
+ if (!manager || !isFreshlyPlacedOrder(manager, action.orderId))
167
+ continue;
168
+ const slotId = String(action.id);
169
+ if (deferredFreshCancelSlots.has(slotId))
170
+ continue;
171
+ deferredFreshCancelSlots.add(slotId);
172
+ this.logger?.log(`[COW] Deferring cancel of freshly placed ${action.orderId} (${slotId}) — inside grace window`, 'info');
173
+ }
174
+ // Id-group drop is deliberate: dropping only the CANCEL would let
175
+ // optimizeRebalanceActions below fold the paired CREATE back into an
176
+ // UPDATE (cancelAction.id + newGridId) and re-materialize the
177
+ // placement. Safe because reconcile emits per slot either a CANCEL
178
+ // group or an UPDATE, never both ("no duplicate UPDATE+CANCEL for the
179
+ // same order" invariant), and an unpaired-surplus CANCEL by
180
+ // construction has no remaining same-type hole to fold into — so no
181
+ // needed repricing is discarded here. If a generator ever emits both,
182
+ // the symptom is only a one-cycle repricing deferral.
183
+ const plannedActions = deferredFreshCancelSlots.size > 0
184
+ ? reconcileResult.actions.filter((action) => !deferredFreshCancelSlots.has(String(action.id)))
185
+ : reconcileResult.actions;
186
+ const optimizedActions = optimizeRebalanceActions(plannedActions, masterGrid, {
192
187
  logger: (msg, level) => this.logger?.log(msg, level),
193
- boundaryIdx: targetBoundary,
194
- gapSlots,
188
+ boundaryIdx: targetBoundary ?? undefined,
189
+ gapSlots: gapSlots ?? undefined,
195
190
  assets: this.assets
196
191
  });
197
192
  // Stale-placement guard: drop placements crossing the plan's own
@@ -245,6 +240,13 @@ class COWRebalanceEngine {
245
240
  manager: this
246
241
  });
247
242
  projectTargetToWorkingGrid(workingGrid, targetGrid, { actions: optimizedActions });
243
+ // The projection above virtually applied every target-grid change,
244
+ // including the cancellations we just held back. Restore the freshly
245
+ // placed slots from master so committing the working grid does not
246
+ // virtualize a live order whose cancel was deferred.
247
+ for (const slotId of deferredFreshCancelSlots) {
248
+ workingGrid.syncFromMaster(masterGrid, slotId, gridVersion);
249
+ }
248
250
  const precisions = {
249
251
  buyPrecision: this.assets?.assetB?.precision,
250
252
  sellPrecision: this.assets?.assetA?.precision
@@ -439,6 +441,7 @@ class OrderManager {
439
441
  _deferredRebalanceAt;
440
442
  _lastHeldPlanSignature;
441
443
  _heldPlanSuppressionCount;
444
+ _onBroadcastRegionEnd;
442
445
  _onBroadcastRegionEndListeners;
443
446
  _lastBoundaryHoldResyncAt;
444
447
  _gapEvacStreaks;
@@ -577,6 +580,11 @@ class OrderManager {
577
580
  this._gapEvacStreaks = new Map();
578
581
  this._gapEvacCancelQueued = new Set();
579
582
  this._metrics = {
583
+ fillsProcessed: 0,
584
+ batchesExecuted: 0,
585
+ fillProcessingTimeMs: 0,
586
+ lockContentionEvents: 0,
587
+ maxQueueDepth: 0,
580
588
  fundRecalcCount: 0,
581
589
  lockAcquisitions: 0,
582
590
  lockContentionSkips: 0,
@@ -735,7 +743,7 @@ class OrderManager {
735
743
  this._bootstrapping++;
736
744
  }
737
745
  /**
738
- * @returns {any}
746
+ * @returns {unknown}
739
747
  */
740
748
  finishBootstrap() {
741
749
  const result = { hadDrift: false, driftInfo: null };
@@ -804,10 +812,10 @@ class OrderManager {
804
812
  */
805
813
  _fireBroadcastRegionEnd() {
806
814
  try {
807
- this._onBroadcastRegionEnd?.();
815
+ (this._onBroadcastRegionEnd)?.();
808
816
  }
809
817
  catch (err) {
810
- this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${err?.message || err}`, 'warn');
818
+ this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${getErrorMessage(err)}`, 'warn');
811
819
  }
812
820
  const listeners = this._onBroadcastRegionEndListeners;
813
821
  if (Array.isArray(listeners)) {
@@ -816,7 +824,7 @@ class OrderManager {
816
824
  listener?.();
817
825
  }
818
826
  catch (err) {
819
- this.logger?.log?.(`[BROADCAST] Region-end listener failed: ${err?.message || err}`, 'warn');
827
+ this.logger?.log?.(`[BROADCAST] Region-end listener failed: ${getErrorMessage(err)}`, 'warn');
820
828
  }
821
829
  }
822
830
  }
@@ -857,7 +865,7 @@ class OrderManager {
857
865
  * value can lag behind the actual orders state (virtualized orders
858
866
  * release committed capital via updateOptimisticFreeBalance without
859
867
  * triggering a recalc). Reading from the orders map avoids that race.
860
- * @returns {any}
868
+ * @returns {unknown}
861
869
  */
862
870
  getChainFundsSnapshot() {
863
871
  let committedBuy = 0, committedSell = 0;
@@ -1000,7 +1008,7 @@ class OrderManager {
1000
1008
  return await this.sync.fetchAccountBalancesAndSetTotals();
1001
1009
  }
1002
1010
  /**
1003
- * @param {any} totals - Account balance totals
1011
+ * @param {unknown} totals - Account balance totals
1004
1012
  * @returns {Promise<void>}
1005
1013
  */
1006
1014
  async setAccountTotals(totals = { buy: null, sell: null, buyFree: null, sellFree: null }) {
@@ -1170,7 +1178,7 @@ class OrderManager {
1170
1178
  * @param {Object} info
1171
1179
  * @returns {Promise<any>}
1172
1180
  */
1173
- syncFromOpenOrders(orders, info) {
1181
+ syncFromOpenOrders(orders, info = {}) {
1174
1182
  return this.sync.syncFromOpenOrders(orders, info);
1175
1183
  }
1176
1184
  /**
@@ -1178,7 +1186,7 @@ class OrderManager {
1178
1186
  * @param {Object} [options]
1179
1187
  * @returns {Promise<any>}
1180
1188
  */
1181
- syncFromFillHistory(fill, options) {
1189
+ syncFromFillHistory(fill, options = {}) {
1182
1190
  return this.sync.syncFromFillHistory(fill, options);
1183
1191
  }
1184
1192
  /**
@@ -1186,7 +1194,7 @@ class OrderManager {
1186
1194
  * @param {Object} [options]
1187
1195
  * @returns {Promise<any>}
1188
1196
  */
1189
- syncFromFillHistoryBatch(fills, options) {
1197
+ syncFromFillHistoryBatch(fills, options = {}) {
1190
1198
  return this.sync.syncFromFillHistoryBatch(fills, options);
1191
1199
  }
1192
1200
  /**
@@ -1305,7 +1313,7 @@ class OrderManager {
1305
1313
  this.logger.log(warning.message, 'warn');
1306
1314
  }
1307
1315
  if (!validation.isValid && validation.errors.length > 0) {
1308
- const fatalError = validation.errors.find((e) => e.isFatal || e.code === 'ILLEGAL_SPREAD_STATE');
1316
+ const fatalError = validation.errors.find((e) => e.isFatal === true || getErrorCode(e) === 'ILLEGAL_SPREAD_STATE');
1309
1317
  if (fatalError) {
1310
1318
  this.logger.log(fatalError.message, 'error');
1311
1319
  this._lastIllegalState = {
@@ -1324,9 +1332,9 @@ class OrderManager {
1324
1332
  // Ensure a mutable copy before passing to updateOptimisticFreeBalance.
1325
1333
  // validation.normalizedOrder may reference a frozen master-grid order,
1326
1334
  // and _resolveBtsFeeLifecycle mutates btsFeeState on the order object.
1327
- let nextOrder = { ...validation.normalizedOrder };
1335
+ let nextOrder = { ...(validation.normalizedOrder ?? {}) };
1328
1336
  // Apply phantom order auto-correction to the normalized order
1329
- const phantomError = validation.errors.find((e) => e.code === 'PHANTOM_ORDER');
1337
+ const phantomError = validation.errors.find((e) => getErrorCode(e) === 'PHANTOM_ORDER');
1330
1338
  let accountingSkip = skipAccounting;
1331
1339
  if (phantomError && phantomError.autoCorrect) {
1332
1340
  nextOrder = { ...nextOrder, ...phantomError.autoCorrect };
@@ -1387,18 +1395,6 @@ class OrderManager {
1387
1395
  this._markGridDirty();
1388
1396
  return true;
1389
1397
  }
1390
- /**
1391
- * Backward-compatible accessor for _currentWorkingGrid.
1392
- * Returns the top of the working grid stack (null if empty).
1393
- */
1394
- get _currentWorkingGrid() {
1395
- return this._peekWorkingGrid();
1396
- }
1397
- set _currentWorkingGrid(val) {
1398
- if (val !== null) {
1399
- this._currentWorkingGridStack.push(val);
1400
- }
1401
- }
1402
1398
  _peekWorkingGrid() {
1403
1399
  const stack = this._currentWorkingGridStack;
1404
1400
  return stack.length > 0 ? stack[stack.length - 1] : null;
@@ -1420,7 +1416,7 @@ class OrderManager {
1420
1416
  /**
1421
1417
  * @param {Array<import('./types').Order>} updates - Order updates to apply
1422
1418
  * @param {string} [context] - Update context label
1423
- * @param {any} [options]
1419
+ * @param {unknown} [options]
1424
1420
  * @returns {Promise<boolean>}
1425
1421
  */
1426
1422
  async applyGridUpdateBatch(updates, context = 'batch-update', options = {}) {
@@ -1493,7 +1489,7 @@ class OrderManager {
1493
1489
  return { skipped: true, suspended: true, reason: this._gridPersistenceSuspendedReason };
1494
1490
  }
1495
1491
  const result = await this.persistGrid(undefined);
1496
- if (result && result.skipped === true) {
1492
+ if (result && 'skipped' in result && result.skipped === true) {
1497
1493
  // Persistence was deferred (suspension, validation, etc.) — keep
1498
1494
  // the dirty flag so a later tick can retry.
1499
1495
  return result;
@@ -1724,22 +1720,21 @@ class OrderManager {
1724
1720
  */
1725
1721
  _logBoundaryDebug(source, newIdx) {
1726
1722
  try {
1727
- const self = this;
1728
- const boundary = newIdx == null ? self.boundaryIdx : newIdx;
1723
+ const boundary = newIdx == null ? this.boundaryIdx : newIdx;
1729
1724
  if (boundary == null)
1730
1725
  return;
1731
- const gapSlots = typeof self._gapSlots === 'number' ? self._gapSlots : 0;
1726
+ const gapSlots = typeof this._gapSlots === 'number' ? this._gapSlots : 0;
1732
1727
  const sellStart = boundary + 1 + gapSlots;
1733
1728
  const countActive = (type) => {
1734
1729
  let n = 0;
1735
- for (const o of (self.orders?.values?.() || [])) {
1730
+ for (const o of this.orders.values()) {
1736
1731
  if (o && o.type === type && o.orderId)
1737
1732
  n++;
1738
1733
  }
1739
1734
  return n;
1740
1735
  };
1741
1736
  this.logger?.log?.(`[BOUNDARY] ${source} boundary=${boundary} sellStart=${sellStart} gapSlots=${gapSlots} ` +
1742
- `spreadCount=${self.currentSpreadCount ?? self.initialSpreadCount ?? '?'} ` +
1737
+ `spreadCount=${this.currentSpreadCount ?? this.initialSpreadCount ?? '?'} ` +
1743
1738
  `activeBuy=${countActive(ORDER_TYPES.BUY)} activeSell=${countActive(ORDER_TYPES.SELL)}`, 'debug');
1744
1739
  }
1745
1740
  catch {
@@ -1821,7 +1816,7 @@ class OrderManager {
1821
1816
  let priceSrc = 'direct';
1822
1817
  if (!Number.isFinite(price) || price <= 0) {
1823
1818
  try {
1824
- const slot = f.id ? this.orders?.get?.(f.id) : null;
1819
+ const slot = f.id ? this.orders.get(f.id) : null;
1825
1820
  price = slot ? Number(slot.price) : null;
1826
1821
  if (Number.isFinite(price) && price > 0)
1827
1822
  priceSrc = 'slot-fallback';
@@ -1834,7 +1829,7 @@ class OrderManager {
1834
1829
  continue;
1835
1830
  this._setLastFillPivot(f.type, price, 'fill');
1836
1831
  recorded++;
1837
- lastKind = f?.isPartial === true ? 'partial' : (f?.isPartial === false ? 'full' : 'unknown');
1832
+ lastKind = f.isPartial === true ? 'partial' : (f.isPartial === false ? 'full' : 'unknown');
1838
1833
  lastPriceSrc = priceSrc;
1839
1834
  }
1840
1835
  // One line per fill batch (chunk): the pivot mutations above are otherwise
@@ -1954,14 +1949,14 @@ class OrderManager {
1954
1949
  * @param {Function} batchCb - Batch callback
1955
1950
  * @returns {Promise<Object>}
1956
1951
  */
1957
- async checkSpreadCondition(BitShares, batchCb) {
1952
+ async checkSpreadCondition(BitShares, batchCb = null) {
1958
1953
  return await checkSpreadCondition(this, BitShares, batchCb);
1959
1954
  }
1960
1955
  /**
1961
1956
  * @param {Function} batchCb - Batch callback
1962
1957
  * @returns {Promise<Object>}
1963
1958
  */
1964
- async checkGridHealth(batchCb) {
1959
+ async checkGridHealth(batchCb = null) {
1965
1960
  return await checkGridHealth(this, batchCb);
1966
1961
  }
1967
1962
  /**
@@ -1971,7 +1966,7 @@ class OrderManager {
1971
1966
  return calculateCurrentSpread(this);
1972
1967
  }
1973
1968
  /**
1974
- * @returns {any}
1969
+ * @returns {unknown}
1975
1970
  */
1976
1971
  checkFundDriftAfterFills() {
1977
1972
  if (!this.assets || !hasValidAccountTotals(this.accountTotals)) {
@@ -1981,7 +1976,7 @@ class OrderManager {
1981
1976
  }
1982
1977
  /**
1983
1978
  * @param {Object|number} [pipelineSignals] - Pipeline state signals or queue length
1984
- * @returns {any}
1979
+ * @returns {unknown}
1985
1980
  */
1986
1981
  isPipelineEmpty(pipelineSignals = 0) {
1987
1982
  const normalizedSignals = (typeof pipelineSignals === 'number')
@@ -2100,7 +2095,8 @@ class OrderManager {
2100
2095
  const boundary = this.boundaryIdx;
2101
2096
  const gapSlots = this._gapSlots;
2102
2097
  let queued = 0;
2103
- for (const candidate of candidates) {
2098
+ for (const raw of candidates) {
2099
+ const candidate = raw;
2104
2100
  const slotId = candidate?.id;
2105
2101
  const chainOrderId = candidate?.orderId;
2106
2102
  if (!slotId || !chainOrderId)
@@ -2276,6 +2272,7 @@ class OrderManager {
2276
2272
  gridVersion: this._gridVersion,
2277
2273
  boundaryIdx: this.boundaryIdx,
2278
2274
  funds: this.getChainFundsSnapshot(),
2275
+ manager: this,
2279
2276
  fills,
2280
2277
  excludeIds,
2281
2278
  gapSlots: this._gapSlots,
@@ -2487,7 +2484,7 @@ class OrderManager {
2487
2484
  /**
2488
2485
  * @param {Object} [options]
2489
2486
  * @param {boolean} [options.allowBootstrapTransient]
2490
- * @returns {any}
2487
+ * @returns {unknown}
2491
2488
  */
2492
2489
  validateGridStateForPersistence(options = {}) {
2493
2490
  const result = validateGridForPersistence(this.orders, this.accountTotals);
@@ -1,3 +1,7 @@
1
+ /**
2
+ * @enum {string}
3
+ */
4
+ import type { AccountOrdersLike } from '../types.js';
1
5
  declare const PROCESSED_FILL_PERSISTENCE_MODES: {
2
6
  readonly IMMEDIATE: string;
3
7
  readonly BATCHED: string;
@@ -23,11 +27,11 @@ declare class ProcessedFillStore {
23
27
  _warn: (msg: string) => void;
24
28
  _persistTimer: ReturnType<typeof setTimeout> | null;
25
29
  _flushPromise: Promise<void>;
26
- _accountOrders: any | null;
30
+ _accountOrders: AccountOrdersLike | null;
27
31
  _shuttingDown: boolean;
28
32
  /**
29
33
  * Create a ProcessedFillStore instance.
30
- * @param {any} [options] - Configuration
34
+ * @param {unknown} [options] - Configuration
31
35
  * @param {number} [options.batchMs] - Batch interval in ms for coalesced writes
32
36
  * @param {number} [options.batchSize] - Max batch size before auto-flush
33
37
  * @param {Function} [options.warn] - Warning logger function
@@ -43,7 +47,7 @@ declare class ProcessedFillStore {
43
47
  * @param {Object} [options.accountOrders] - AccountOrders instance for persistence
44
48
  */
45
49
  configure({ accountOrders }?: {
46
- accountOrders?: any;
50
+ accountOrders?: AccountOrdersLike;
47
51
  }): void;
48
52
  /**
49
53
  * Set the shutting down flag to prevent delayed writes during shutdown.
@@ -105,6 +109,17 @@ declare class ProcessedFillStore {
105
109
  flushKeys(fillKeys: string[] | Set<string>, reason?: string, { throwOnError }?: {
106
110
  throwOnError?: boolean;
107
111
  }): Promise<void>;
112
+ /**
113
+ * Persist a batch of already-dequeued fills, re-queuing entries when the
114
+ * write fails. Shared by flush() and flushKeys() so the retry/back-off
115
+ * path cannot drift apart.
116
+ * @param {Map<string, number>} batch - Dequeued fill keys to persist
117
+ * @param {string} reason - Reason label for logging
118
+ * @param {boolean} throwOnError - Re-throw on flush failure
119
+ * @param {string} descriptor - Noun describing the batch in the failure log
120
+ * @returns {Promise<void>}
121
+ */
122
+ _flushBatch(batch: Map<string, number>, reason: string, throwOnError: boolean, descriptor: string): Promise<void>;
108
123
  /**
109
124
  * Queue a fill key for batched persistence.
110
125
  * @param {string} fillKey - Fill deduplication key
@@ -1,6 +1,3 @@
1
- /**
2
- * @enum {string}
3
- */
4
1
  import { getErrorMessage } from '../utils/errors.js';
5
2
  const PROCESSED_FILL_PERSISTENCE_MODES = Object.freeze({
6
3
  IMMEDIATE: 'immediate',
@@ -40,7 +37,7 @@ class ProcessedFillStore {
40
37
  _shuttingDown;
41
38
  /**
42
39
  * Create a ProcessedFillStore instance.
43
- * @param {any} [options] - Configuration
40
+ * @param {unknown} [options] - Configuration
44
41
  * @param {number} [options.batchMs] - Batch interval in ms for coalesced writes
45
42
  * @param {number} [options.batchSize] - Max batch size before auto-flush
46
43
  * @param {Function} [options.warn] - Warning logger function
@@ -163,28 +160,7 @@ class ProcessedFillStore {
163
160
  }
164
161
  const batch = new Map(this.pendingWrites);
165
162
  this.pendingWrites.clear();
166
- let flushError = null;
167
- const flushWork = async () => {
168
- try {
169
- await this._accountOrders.updateProcessedFillsBatch(batch);
170
- }
171
- catch (err) {
172
- flushError = err;
173
- for (const [fillKey, timestamp] of batch) {
174
- const queuedTimestamp = this.pendingWrites.get(fillKey);
175
- if (queuedTimestamp === undefined || timestamp > queuedTimestamp) {
176
- this.pendingWrites.set(fillKey, timestamp);
177
- }
178
- }
179
- this._warn(`[FILL-DEDUP] Failed to flush ${batch.size} processed fill record(s) (${reason}): ${getErrorMessage(err)}`);
180
- this._schedule();
181
- }
182
- };
183
- this._flushPromise = this._flushPromise.then(flushWork, flushWork);
184
- await this._flushPromise;
185
- if (flushError && throwOnError) {
186
- throw flushError;
187
- }
163
+ await this._flushBatch(batch, reason, throwOnError, 'processed');
188
164
  }
189
165
  /**
190
166
  * Flush pending writes for specific fill keys.
@@ -208,6 +184,19 @@ class ProcessedFillStore {
208
184
  batch.set(fillKey, this.pendingWrites.get(fillKey));
209
185
  this.pendingWrites.delete(fillKey);
210
186
  }
187
+ await this._flushBatch(batch, reason, throwOnError, 'selected processed');
188
+ }
189
+ /**
190
+ * Persist a batch of already-dequeued fills, re-queuing entries when the
191
+ * write fails. Shared by flush() and flushKeys() so the retry/back-off
192
+ * path cannot drift apart.
193
+ * @param {Map<string, number>} batch - Dequeued fill keys to persist
194
+ * @param {string} reason - Reason label for logging
195
+ * @param {boolean} throwOnError - Re-throw on flush failure
196
+ * @param {string} descriptor - Noun describing the batch in the failure log
197
+ * @returns {Promise<void>}
198
+ */
199
+ async _flushBatch(batch, reason, throwOnError, descriptor) {
211
200
  if (batch.size === 0) {
212
201
  await this._flushPromise;
213
202
  return;
@@ -225,7 +214,7 @@ class ProcessedFillStore {
225
214
  this.pendingWrites.set(fillKey, timestamp);
226
215
  }
227
216
  }
228
- this._warn(`[FILL-DEDUP] Failed to flush ${batch.size} selected processed fill record(s) (${reason}): ${getErrorMessage(err)}`);
217
+ this._warn(`[FILL-DEDUP] Failed to flush ${batch.size} ${descriptor} fill record(s) (${reason}): ${getErrorMessage(err)}`);
229
218
  this._schedule();
230
219
  }
231
220
  };
@@ -46,12 +46,23 @@
46
46
  *
47
47
  * ===============================================================================
48
48
  */
49
+ import type { OrderManagerLike, ManagedOrder, GridConfig, AssetPair, ProjectedFunds } from "../types.js";
50
+ interface FillInput {
51
+ id?: string;
52
+ type?: string;
53
+ price?: number;
54
+ size?: number;
55
+ isPartial?: boolean;
56
+ isDelayedRotationTrigger?: boolean;
57
+ orderId?: string | null;
58
+ [key: string]: unknown;
59
+ }
49
60
  declare class StrategyEngine {
50
- manager: any;
61
+ manager: OrderManagerLike;
51
62
  /**
52
63
  * @param {Object} manager - OrderManager instance
53
64
  */
54
- constructor(manager: any);
65
+ constructor(manager: OrderManagerLike);
55
66
  /**
56
67
  * Process filled orders: handle fills and consolidate partials.
57
68
  * Does NOT trigger rebalancing (now decoupled from rebalance logic).
@@ -84,7 +95,7 @@ declare class StrategyEngine {
84
95
  * @returns {Promise<boolean>} True if processing completed successfully
85
96
  * @async
86
97
  */
87
- processFillsOnly(filledOrders: any, excludeOrderIds?: any): Promise<boolean>;
98
+ processFillsOnly(filledOrders: FillInput[], excludeOrderIds?: Set<string>): Promise<boolean>;
88
99
  /**
89
100
  * UNIFIED TARGET CALCULATION
90
101
  * Calculates the "Ideal State" grid based on current fills and market conditions.
@@ -136,18 +147,15 @@ declare class StrategyEngine {
136
147
  * - boundaryIdx {number}: New boundary index
137
148
  */
138
149
  calculateTargetGrid(params: {
139
- frozenMasterGrid: Map<string, any>;
140
- config: any;
141
- accountAssets: any;
142
- funds: any;
143
- fills: any[];
144
- currentBoundaryIdx: number;
150
+ frozenMasterGrid: Map<string, ManagedOrder>;
151
+ config: GridConfig;
152
+ accountAssets: AssetPair | null;
153
+ funds: ProjectedFunds | null;
154
+ fills: FillInput[];
155
+ currentBoundaryIdx: number | null;
145
156
  }): {
146
157
  targetGrid: Map<any, any>;
147
- boundaryIdx: number;
148
- } | {
149
- targetGrid: Map<any, any>;
150
- boundaryIdx: null;
158
+ boundaryIdx: number | null;
151
159
  };
152
160
  }
153
161
  export default StrategyEngine;
@@ -98,7 +98,7 @@ class StrategyEngine {
98
98
  return true;
99
99
  mgr.logger.log(`[STRATEGY] Processing batch of ${filledOrders.length} filled orders...`, 'info');
100
100
  for (const filledOrder of filledOrders) {
101
- if (excludeOrderIds?.has?.(filledOrder.id)) {
101
+ if (filledOrder.id != null && excludeOrderIds?.has?.(filledOrder.id)) {
102
102
  mgr.logger.log(`[STRATEGY] Skipping excluded fill for order ${filledOrder.id}`, 'debug');
103
103
  continue;
104
104
  }
@@ -141,7 +141,7 @@ class StrategyEngine {
141
141
  }
142
142
  }
143
143
  if (!isPartial || filledOrder.isDelayedRotationTrigger) {
144
- const currentSlot = mgr.orders.get(filledOrder.id);
144
+ const currentSlot = filledOrder.id != null ? mgr.orders.get(filledOrder.id) : undefined;
145
145
  const slotReused = currentSlot && hasOnChainId(currentSlot) && filledOrder.orderId && currentSlot.orderId !== filledOrder.orderId;
146
146
  if (currentSlot && !slotReused && isOrderPlaced(currentSlot) && currentSlot.size > 0) {
147
147
  mgr.logger.log(`[STRATEGY] Virtualizing filled slot ${filledOrder.id}`, 'debug');
@@ -152,7 +152,7 @@ class StrategyEngine {
152
152
  // never the stored type.
153
153
  let filledHole = null;
154
154
  try {
155
- const filledGeoType = geometryTypeForSlotIndex(parseSlotIndex(currentSlot?.id), mgr?.boundaryIdx, mgr?._gapSlots);
155
+ const filledGeoType = geometryTypeForSlotIndex(parseSlotIndex(currentSlot?.id), mgr.boundaryIdx, mgr._gapSlots);
156
156
  filledHole = (filledGeoType === ORDER_TYPES.BUY || filledGeoType === ORDER_TYPES.SELL)
157
157
  ? toRailHolePlaceholder(currentSlot, filledGeoType, 0)
158
158
  : convertToSpreadPlaceholder(currentSlot);
@@ -246,7 +246,7 @@ class StrategyEngine {
246
246
  // but not position, and an unanchored recovery fabricates a rail-edge
247
247
  // boundary (the slot-77→slot-192 teleport). The numeric config center
248
248
  // still wins when present.
249
- const genesisStart = Number(this.manager?._genesis?.startPrice);
249
+ const genesisStart = Number(this.manager._genesis?.startPrice);
250
250
  const boundaryConfig = (!Number.isFinite(Number(config?.startPrice)) && Number.isFinite(genesisStart))
251
251
  ? { ...config, genesisStartPrice: genesisStart }
252
252
  : config;
@@ -259,7 +259,7 @@ class StrategyEngine {
259
259
  buy: resolveLiveReserveEdgeAnchorPrice(this.manager, 'buy'),
260
260
  sell: resolveLiveReserveEdgeAnchorPrice(this.manager, 'sell'),
261
261
  };
262
- const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager?._pendingFillCrawls, reserveEdgeAnchors);
262
+ const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager._pendingFillCrawls, reserveEdgeAnchors);
263
263
  if (crossChunkBudget != null) {
264
264
  this.manager._boundaryShiftBudget = remainingBudget;
265
265
  }
@@ -354,7 +354,6 @@ class StrategyEngine {
354
354
  type: slot.type,
355
355
  size: size,
356
356
  idealSize: size,
357
- // If size > 0, we WANT it active. If size 0, we want it VIRTUAL/SPREAD
358
357
  state: size > 0 ? ORDER_STATES.ACTIVE : ORDER_STATES.VIRTUAL,
359
358
  committedSide: (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)
360
359
  ? slot.type