dexbot 1.3.3 → 1.4.1

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 (736) hide show
  1. package/dist/analysis/chart_utils.d.ts +11 -9
  2. package/dist/analysis/chart_utils.d.ts.map +1 -1
  3. package/dist/analysis/chart_utils.js +21 -16
  4. package/dist/analysis/chart_utils.js.map +1 -1
  5. package/dist/analysis/math_utils.d.ts +4 -13
  6. package/dist/analysis/math_utils.d.ts.map +1 -1
  7. package/dist/analysis/math_utils.js +16 -18
  8. package/dist/analysis/math_utils.js.map +1 -1
  9. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +3 -7
  10. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +1 -1
  11. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +38 -34
  12. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +1 -1
  13. package/dist/analysis/trend_detection/hurst_analyzer.d.ts +1 -4
  14. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +1 -1
  15. package/dist/analysis/trend_detection/hurst_analyzer.js +10 -7
  16. package/dist/analysis/trend_detection/hurst_analyzer.js.map +1 -1
  17. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts +6 -6
  18. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +1 -1
  19. package/dist/analysis/trend_detection/kalman_trend_analyzer.js +23 -15
  20. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +1 -1
  21. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts +12 -13
  22. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +1 -1
  23. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js +16 -16
  24. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +1 -1
  25. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts +1 -4
  26. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +1 -1
  27. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js +10 -7
  28. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +1 -1
  29. package/dist/bot.d.ts.map +1 -1
  30. package/dist/bot.js +6 -13
  31. package/dist/bot.js.map +1 -1
  32. package/dist/credential-daemon.d.ts.map +1 -1
  33. package/dist/credential-daemon.js +21 -22
  34. package/dist/credential-daemon.js.map +1 -1
  35. package/dist/dexbot.d.ts.map +1 -1
  36. package/dist/dexbot.js +16 -15
  37. package/dist/dexbot.js.map +1 -1
  38. package/dist/market_adapter/ama_signal_runner.d.ts +1 -1
  39. package/dist/market_adapter/ama_signal_runner.d.ts.map +1 -1
  40. package/dist/market_adapter/ama_signal_runner.js +8 -20
  41. package/dist/market_adapter/ama_signal_runner.js.map +1 -1
  42. package/dist/market_adapter/candle_utils.d.ts +2 -10
  43. package/dist/market_adapter/candle_utils.d.ts.map +1 -1
  44. package/dist/market_adapter/candle_utils.js +7 -8
  45. package/dist/market_adapter/candle_utils.js.map +1 -1
  46. package/dist/market_adapter/core/asymmetric_bounds.d.ts +12 -7
  47. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +1 -1
  48. package/dist/market_adapter/core/asymmetric_bounds.js +4 -5
  49. package/dist/market_adapter/core/asymmetric_bounds.js.map +1 -1
  50. package/dist/market_adapter/core/config_normalizers.d.ts +4 -9
  51. package/dist/market_adapter/core/config_normalizers.d.ts.map +1 -1
  52. package/dist/market_adapter/core/config_normalizers.js +9 -9
  53. package/dist/market_adapter/core/config_normalizers.js.map +1 -1
  54. package/dist/market_adapter/core/kibana_candles.d.ts +16 -20
  55. package/dist/market_adapter/core/kibana_candles.d.ts.map +1 -1
  56. package/dist/market_adapter/core/kibana_candles.js +16 -15
  57. package/dist/market_adapter/core/kibana_candles.js.map +1 -1
  58. package/dist/market_adapter/core/kibana_client.d.ts +8 -11
  59. package/dist/market_adapter/core/kibana_client.d.ts.map +1 -1
  60. package/dist/market_adapter/core/kibana_client.js +13 -11
  61. package/dist/market_adapter/core/kibana_client.js.map +1 -1
  62. package/dist/market_adapter/core/kibana_market_candles.d.ts +5 -12
  63. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +1 -1
  64. package/dist/market_adapter/core/kibana_market_candles.js +12 -21
  65. package/dist/market_adapter/core/kibana_market_candles.js.map +1 -1
  66. package/dist/market_adapter/core/market_adapter_service.d.ts +75 -53
  67. package/dist/market_adapter/core/market_adapter_service.d.ts.map +1 -1
  68. package/dist/market_adapter/core/market_adapter_service.js +102 -98
  69. package/dist/market_adapter/core/market_adapter_service.js.map +1 -1
  70. package/dist/market_adapter/core/strategies/ama.d.ts +21 -1
  71. package/dist/market_adapter/core/strategies/ama.d.ts.map +1 -1
  72. package/dist/market_adapter/core/strategies/ama.js +10 -10
  73. package/dist/market_adapter/core/strategies/ama.js.map +1 -1
  74. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +7 -11
  75. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +1 -1
  76. package/dist/market_adapter/core/strategies/ama_slope_model.js +23 -30
  77. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +1 -1
  78. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +5 -4
  79. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +1 -1
  80. package/dist/market_adapter/core/strategies/atr/calculator.js +5 -3
  81. package/dist/market_adapter/core/strategies/atr/calculator.js.map +1 -1
  82. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +4 -7
  83. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +1 -1
  84. package/dist/market_adapter/core/strategies/collateral_manager.js +5 -4
  85. package/dist/market_adapter/core/strategies/collateral_manager.js.map +1 -1
  86. package/dist/market_adapter/core/strategies/regime_gate.d.ts +11 -19
  87. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +1 -1
  88. package/dist/market_adapter/core/strategies/regime_gate.js +22 -22
  89. package/dist/market_adapter/core/strategies/regime_gate.js.map +1 -1
  90. package/dist/market_adapter/index.d.ts +24 -2
  91. package/dist/market_adapter/index.d.ts.map +1 -1
  92. package/dist/market_adapter/index.js +82 -56
  93. package/dist/market_adapter/index.js.map +1 -1
  94. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +26 -37
  95. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +1 -1
  96. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +4 -12
  97. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +1 -1
  98. package/dist/market_adapter/inputs/fetch_lp_data.js +100 -66
  99. package/dist/market_adapter/inputs/fetch_lp_data.js.map +1 -1
  100. package/dist/market_adapter/inputs/kibana_source.d.ts +4 -9
  101. package/dist/market_adapter/inputs/kibana_source.d.ts.map +1 -1
  102. package/dist/market_adapter/inputs/kibana_source.js +17 -18
  103. package/dist/market_adapter/inputs/kibana_source.js.map +1 -1
  104. package/dist/market_adapter/interval_utils.d.ts +1 -4
  105. package/dist/market_adapter/interval_utils.d.ts.map +1 -1
  106. package/dist/market_adapter/interval_utils.js +2 -3
  107. package/dist/market_adapter/interval_utils.js.map +1 -1
  108. package/dist/market_adapter/log_format.d.ts +1 -9
  109. package/dist/market_adapter/log_format.d.ts.map +1 -1
  110. package/dist/market_adapter/log_format.js +7 -8
  111. package/dist/market_adapter/log_format.js.map +1 -1
  112. package/dist/market_adapter/lp_chart_core.d.ts +1 -4
  113. package/dist/market_adapter/lp_chart_core.d.ts.map +1 -1
  114. package/dist/market_adapter/lp_chart_core.js +22 -20
  115. package/dist/market_adapter/lp_chart_core.js.map +1 -1
  116. package/dist/market_adapter/lp_chart_runner.d.ts +13 -24
  117. package/dist/market_adapter/lp_chart_runner.d.ts.map +1 -1
  118. package/dist/market_adapter/lp_chart_runner.js +58 -56
  119. package/dist/market_adapter/lp_chart_runner.js.map +1 -1
  120. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +4 -17
  121. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +1 -1
  122. package/dist/market_adapter/lp_chart_strategy_loader.js +36 -36
  123. package/dist/market_adapter/lp_chart_strategy_loader.js.map +1 -1
  124. package/dist/market_adapter/market_adapter.d.ts +51 -72
  125. package/dist/market_adapter/market_adapter.d.ts.map +1 -1
  126. package/dist/market_adapter/market_adapter.js +227 -192
  127. package/dist/market_adapter/market_adapter.js.map +1 -1
  128. package/dist/market_adapter/merge_lp_data.js +17 -16
  129. package/dist/market_adapter/merge_lp_data.js.map +1 -1
  130. package/dist/market_adapter/test_helpers.d.ts +9 -13
  131. package/dist/market_adapter/test_helpers.d.ts.map +1 -1
  132. package/dist/market_adapter/test_helpers.js +14 -14
  133. package/dist/market_adapter/test_helpers.js.map +1 -1
  134. package/dist/market_adapter/utils/adapter_client.d.ts +6 -14
  135. package/dist/market_adapter/utils/adapter_client.d.ts.map +1 -1
  136. package/dist/market_adapter/utils/adapter_client.js +16 -15
  137. package/dist/market_adapter/utils/adapter_client.js.map +1 -1
  138. package/dist/market_adapter/utils/atomic_write.d.ts +2 -5
  139. package/dist/market_adapter/utils/atomic_write.d.ts.map +1 -1
  140. package/dist/market_adapter/utils/atomic_write.js +5 -5
  141. package/dist/market_adapter/utils/atomic_write.js.map +1 -1
  142. package/dist/market_adapter/utils/chain.d.ts +19 -21
  143. package/dist/market_adapter/utils/chain.d.ts.map +1 -1
  144. package/dist/market_adapter/utils/chain.js +15 -16
  145. package/dist/market_adapter/utils/chain.js.map +1 -1
  146. package/dist/market_adapter/utils/data_discovery.d.ts +1 -4
  147. package/dist/market_adapter/utils/data_discovery.d.ts.map +1 -1
  148. package/dist/market_adapter/utils/data_discovery.js +10 -10
  149. package/dist/market_adapter/utils/data_discovery.js.map +1 -1
  150. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +1 -6
  151. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +1 -1
  152. package/dist/market_adapter/utils/dynamic_grid_snapshot.js +14 -14
  153. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +1 -1
  154. package/dist/market_adapter/utils/file_lock.d.ts +1 -7
  155. package/dist/market_adapter/utils/file_lock.d.ts.map +1 -1
  156. package/dist/market_adapter/utils/file_lock.js +21 -25
  157. package/dist/market_adapter/utils/file_lock.js.map +1 -1
  158. package/dist/market_adapter/utils/native_history.d.ts +12 -12
  159. package/dist/market_adapter/utils/native_history.d.ts.map +1 -1
  160. package/dist/market_adapter/utils/native_history.js +15 -15
  161. package/dist/market_adapter/utils/native_history.js.map +1 -1
  162. package/dist/market_adapter/utils/paths.d.ts +2 -4
  163. package/dist/market_adapter/utils/paths.d.ts.map +1 -1
  164. package/dist/market_adapter/utils/paths.js +6 -5
  165. package/dist/market_adapter/utils/paths.js.map +1 -1
  166. package/dist/modules/account_bots.d.ts +7 -8
  167. package/dist/modules/account_bots.d.ts.map +1 -1
  168. package/dist/modules/account_bots.js +92 -114
  169. package/dist/modules/account_bots.js.map +1 -1
  170. package/dist/modules/account_orders.d.ts +5 -9
  171. package/dist/modules/account_orders.d.ts.map +1 -1
  172. package/dist/modules/account_orders.js +69 -32
  173. package/dist/modules/account_orders.js.map +1 -1
  174. package/dist/modules/authority_resolver.d.ts +32 -1
  175. package/dist/modules/authority_resolver.d.ts.map +1 -1
  176. package/dist/modules/authority_resolver.js +18 -12
  177. package/dist/modules/authority_resolver.js.map +1 -1
  178. package/dist/modules/bitshares-native/chain_client.d.ts +3 -8
  179. package/dist/modules/bitshares-native/chain_client.d.ts.map +1 -1
  180. package/dist/modules/bitshares-native/chain_client.js +21 -16
  181. package/dist/modules/bitshares-native/chain_client.js.map +1 -1
  182. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts +21 -29
  183. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +1 -1
  184. package/dist/modules/bitshares-native/crypto/ecc.browser.js +72 -38
  185. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +1 -1
  186. package/dist/modules/bitshares-native/crypto/ecc.d.ts +9 -36
  187. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +1 -1
  188. package/dist/modules/bitshares-native/crypto/ecc.js +40 -83
  189. package/dist/modules/bitshares-native/crypto/ecc.js.map +1 -1
  190. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +14 -1
  191. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +1 -1
  192. package/dist/modules/bitshares-native/crypto/ecc_selector.js +5 -3
  193. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +1 -1
  194. package/dist/modules/bitshares-native/index.d.ts +10 -2
  195. package/dist/modules/bitshares-native/index.d.ts.map +1 -1
  196. package/dist/modules/bitshares-native/index.js +68 -31
  197. package/dist/modules/bitshares-native/index.js.map +1 -1
  198. package/dist/modules/bitshares-native/lru_cache.d.ts +1 -4
  199. package/dist/modules/bitshares-native/lru_cache.d.ts.map +1 -1
  200. package/dist/modules/bitshares-native/lru_cache.js +6 -3
  201. package/dist/modules/bitshares-native/lru_cache.js.map +1 -1
  202. package/dist/modules/bitshares-native/resolvers.d.ts +3 -6
  203. package/dist/modules/bitshares-native/resolvers.d.ts.map +1 -1
  204. package/dist/modules/bitshares-native/resolvers.js +11 -9
  205. package/dist/modules/bitshares-native/resolvers.js.map +1 -1
  206. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +53 -55
  207. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +1 -1
  208. package/dist/modules/bitshares-native/serial/chain_constants.js +28 -27
  209. package/dist/modules/bitshares-native/serial/chain_constants.js.map +1 -1
  210. package/dist/modules/bitshares-native/serial/index.d.ts +5 -9
  211. package/dist/modules/bitshares-native/serial/index.d.ts.map +1 -1
  212. package/dist/modules/bitshares-native/serial/index.js +46 -12
  213. package/dist/modules/bitshares-native/serial/index.js.map +1 -1
  214. package/dist/modules/bitshares-native/serial/operations.d.ts +102 -100
  215. package/dist/modules/bitshares-native/serial/operations.d.ts.map +1 -1
  216. package/dist/modules/bitshares-native/serial/operations.js +473 -471
  217. package/dist/modules/bitshares-native/serial/operations.js.map +1 -1
  218. package/dist/modules/bitshares-native/serial/serializer.d.ts +2 -7
  219. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +1 -1
  220. package/dist/modules/bitshares-native/serial/serializer.js +8 -3
  221. package/dist/modules/bitshares-native/serial/serializer.js.map +1 -1
  222. package/dist/modules/bitshares-native/serial/types.d.ts +26 -41
  223. package/dist/modules/bitshares-native/serial/types.d.ts.map +1 -1
  224. package/dist/modules/bitshares-native/serial/types.js +76 -42
  225. package/dist/modules/bitshares-native/serial/types.js.map +1 -1
  226. package/dist/modules/bitshares-native/signing_client.d.ts +1 -5
  227. package/dist/modules/bitshares-native/signing_client.d.ts.map +1 -1
  228. package/dist/modules/bitshares-native/signing_client.js +49 -11
  229. package/dist/modules/bitshares-native/signing_client.js.map +1 -1
  230. package/dist/modules/bitshares-native/subscriptions.d.ts +1 -4
  231. package/dist/modules/bitshares-native/subscriptions.d.ts.map +1 -1
  232. package/dist/modules/bitshares-native/subscriptions.js +47 -84
  233. package/dist/modules/bitshares-native/subscriptions.js.map +1 -1
  234. package/dist/modules/bitshares-native/transport.d.ts +1 -8
  235. package/dist/modules/bitshares-native/transport.d.ts.map +1 -1
  236. package/dist/modules/bitshares-native/transport.js +22 -15
  237. package/dist/modules/bitshares-native/transport.js.map +1 -1
  238. package/dist/modules/bitshares-native/tx/builder.d.ts +3 -8
  239. package/dist/modules/bitshares-native/tx/builder.d.ts.map +1 -1
  240. package/dist/modules/bitshares-native/tx/builder.js +61 -23
  241. package/dist/modules/bitshares-native/tx/builder.js.map +1 -1
  242. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +1 -8
  243. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +1 -1
  244. package/dist/modules/bitshares-native/tx/tx_cache.js +21 -17
  245. package/dist/modules/bitshares-native/tx/tx_cache.js.map +1 -1
  246. package/dist/modules/bitshares_client.d.ts +12 -23
  247. package/dist/modules/bitshares_client.d.ts.map +1 -1
  248. package/dist/modules/bitshares_client.js +109 -56
  249. package/dist/modules/bitshares_client.js.map +1 -1
  250. package/dist/modules/bot_settings.d.ts +1 -13
  251. package/dist/modules/bot_settings.d.ts.map +1 -1
  252. package/dist/modules/bot_settings.js +34 -34
  253. package/dist/modules/bot_settings.js.map +1 -1
  254. package/dist/modules/bots_file_lock.d.ts +3 -9
  255. package/dist/modules/bots_file_lock.d.ts.map +1 -1
  256. package/dist/modules/bots_file_lock.js +8 -9
  257. package/dist/modules/bots_file_lock.js.map +1 -1
  258. package/dist/modules/chain_keys.d.ts +7 -39
  259. package/dist/modules/chain_keys.d.ts.map +1 -1
  260. package/dist/modules/chain_keys.js +126 -90
  261. package/dist/modules/chain_keys.js.map +1 -1
  262. package/dist/modules/chain_orders.d.ts +46 -52
  263. package/dist/modules/chain_orders.d.ts.map +1 -1
  264. package/dist/modules/chain_orders.js +152 -104
  265. package/dist/modules/chain_orders.js.map +1 -1
  266. package/dist/modules/config.d.ts +50 -57
  267. package/dist/modules/config.d.ts.map +1 -1
  268. package/dist/modules/config.js +28 -24
  269. package/dist/modules/config.js.map +1 -1
  270. package/dist/modules/constants.d.ts +492 -494
  271. package/dist/modules/constants.d.ts.map +1 -1
  272. package/dist/modules/constants.js +69 -39
  273. package/dist/modules/constants.js.map +1 -1
  274. package/dist/modules/cr_planner.d.ts +1 -13
  275. package/dist/modules/cr_planner.d.ts.map +1 -1
  276. package/dist/modules/cr_planner.js +28 -28
  277. package/dist/modules/cr_planner.js.map +1 -1
  278. package/dist/modules/credential_policy.d.ts +18 -33
  279. package/dist/modules/credential_policy.d.ts.map +1 -1
  280. package/dist/modules/credential_policy.js +114 -87
  281. package/dist/modules/credential_policy.js.map +1 -1
  282. package/dist/modules/credential_runtime.d.ts +11 -21
  283. package/dist/modules/credential_runtime.d.ts.map +1 -1
  284. package/dist/modules/credential_runtime.js +40 -40
  285. package/dist/modules/credential_runtime.js.map +1 -1
  286. package/dist/modules/credential_session_cache.d.ts +8 -8
  287. package/dist/modules/credential_session_cache.d.ts.map +1 -1
  288. package/dist/modules/credential_session_cache.js +41 -8
  289. package/dist/modules/credential_session_cache.js.map +1 -1
  290. package/dist/modules/credit_runtime.d.ts +51 -316
  291. package/dist/modules/credit_runtime.d.ts.map +1 -1
  292. package/dist/modules/credit_runtime.js +257 -183
  293. package/dist/modules/credit_runtime.js.map +1 -1
  294. package/dist/modules/crypto/browser_provider.js +6 -6
  295. package/dist/modules/crypto/browser_provider.js.map +1 -1
  296. package/dist/modules/crypto/index.d.ts.map +1 -1
  297. package/dist/modules/crypto/index.js +2 -0
  298. package/dist/modules/crypto/index.js.map +1 -1
  299. package/dist/modules/crypto/sync.js +3 -3
  300. package/dist/modules/crypto/sync.js.map +1 -1
  301. package/dist/modules/dexbot_class.d.ts +262 -81
  302. package/dist/modules/dexbot_class.d.ts.map +1 -1
  303. package/dist/modules/dexbot_class.js +156 -123
  304. package/dist/modules/dexbot_class.js.map +1 -1
  305. package/dist/modules/dexbot_cow_runtime.d.ts +12 -9
  306. package/dist/modules/dexbot_cow_runtime.d.ts.map +1 -1
  307. package/dist/modules/dexbot_cow_runtime.js +144 -63
  308. package/dist/modules/dexbot_cow_runtime.js.map +1 -1
  309. package/dist/modules/dexbot_credential_client.d.ts +5 -11
  310. package/dist/modules/dexbot_credential_client.d.ts.map +1 -1
  311. package/dist/modules/dexbot_credential_client.js +32 -30
  312. package/dist/modules/dexbot_credential_client.js.map +1 -1
  313. package/dist/modules/dexbot_fill_runtime.d.ts +5 -20
  314. package/dist/modules/dexbot_fill_runtime.d.ts.map +1 -1
  315. package/dist/modules/dexbot_fill_runtime.js +55 -116
  316. package/dist/modules/dexbot_fill_runtime.js.map +1 -1
  317. package/dist/modules/dexbot_maintenance_runtime.d.ts +12 -12
  318. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -1
  319. package/dist/modules/dexbot_maintenance_runtime.js +55 -45
  320. package/dist/modules/dexbot_maintenance_runtime.js.map +1 -1
  321. package/dist/modules/dexbot_startup_runtime.d.ts +2 -6
  322. package/dist/modules/dexbot_startup_runtime.d.ts.map +1 -1
  323. package/dist/modules/dexbot_startup_runtime.js +122 -91
  324. package/dist/modules/dexbot_startup_runtime.js.map +1 -1
  325. package/dist/modules/dexbot_state_recovery.d.ts +11 -24
  326. package/dist/modules/dexbot_state_recovery.d.ts.map +1 -1
  327. package/dist/modules/dexbot_state_recovery.js +62 -28
  328. package/dist/modules/dexbot_state_recovery.js.map +1 -1
  329. package/dist/modules/fund_registry.d.ts +1 -13
  330. package/dist/modules/fund_registry.d.ts.map +1 -1
  331. package/dist/modules/fund_registry.js +23 -21
  332. package/dist/modules/fund_registry.js.map +1 -1
  333. package/dist/modules/general_settings.d.ts +3 -7
  334. package/dist/modules/general_settings.d.ts.map +1 -1
  335. package/dist/modules/general_settings.js +15 -14
  336. package/dist/modules/general_settings.js.map +1 -1
  337. package/dist/modules/graceful_shutdown.d.ts +1 -6
  338. package/dist/modules/graceful_shutdown.d.ts.map +1 -1
  339. package/dist/modules/graceful_shutdown.js +19 -16
  340. package/dist/modules/graceful_shutdown.js.map +1 -1
  341. package/dist/modules/key_store.d.ts.map +1 -1
  342. package/dist/modules/key_store.js +53 -19
  343. package/dist/modules/key_store.js.map +1 -1
  344. package/dist/modules/launcher/bot_supervisor.d.ts +23 -66
  345. package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -1
  346. package/dist/modules/launcher/bot_supervisor.js +115 -107
  347. package/dist/modules/launcher/bot_supervisor.js.map +1 -1
  348. package/dist/modules/launcher/child_env.d.ts +2 -5
  349. package/dist/modules/launcher/child_env.d.ts.map +1 -1
  350. package/dist/modules/launcher/child_env.js +4 -4
  351. package/dist/modules/launcher/child_env.js.map +1 -1
  352. package/dist/modules/launcher/credential_bootstrap.d.ts +4 -8
  353. package/dist/modules/launcher/credential_bootstrap.d.ts.map +1 -1
  354. package/dist/modules/launcher/credential_bootstrap.js +30 -26
  355. package/dist/modules/launcher/credential_bootstrap.js.map +1 -1
  356. package/dist/modules/launcher/credential_daemon.d.ts +8 -15
  357. package/dist/modules/launcher/credential_daemon.d.ts.map +1 -1
  358. package/dist/modules/launcher/credential_daemon.js +72 -41
  359. package/dist/modules/launcher/credential_daemon.js.map +1 -1
  360. package/dist/modules/launcher/credential_secret.d.ts +1 -4
  361. package/dist/modules/launcher/credential_secret.d.ts.map +1 -1
  362. package/dist/modules/launcher/credential_secret.js +36 -4
  363. package/dist/modules/launcher/credential_secret.js.map +1 -1
  364. package/dist/modules/launcher/foreign_cred_daemon.d.ts +32 -1
  365. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -1
  366. package/dist/modules/launcher/foreign_cred_daemon.js +25 -28
  367. package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -1
  368. package/dist/modules/launcher/headless_password.d.ts +1 -4
  369. package/dist/modules/launcher/headless_password.d.ts.map +1 -1
  370. package/dist/modules/launcher/headless_password.js +11 -11
  371. package/dist/modules/launcher/headless_password.js.map +1 -1
  372. package/dist/modules/launcher/launch_modes.d.ts +15 -14
  373. package/dist/modules/launcher/launch_modes.d.ts.map +1 -1
  374. package/dist/modules/launcher/launch_modes.js +8 -8
  375. package/dist/modules/launcher/launch_modes.js.map +1 -1
  376. package/dist/modules/launcher/market_adapter_runtime.d.ts +10 -19
  377. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -1
  378. package/dist/modules/launcher/market_adapter_runtime.js +33 -33
  379. package/dist/modules/launcher/market_adapter_runtime.js.map +1 -1
  380. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -17
  381. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +1 -1
  382. package/dist/modules/launcher/market_adapter_watchdog.js +42 -38
  383. package/dist/modules/launcher/market_adapter_watchdog.js.map +1 -1
  384. package/dist/modules/launcher/monolithic_runtime.d.ts +28 -57
  385. package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -1
  386. package/dist/modules/launcher/monolithic_runtime.js +135 -108
  387. package/dist/modules/launcher/monolithic_runtime.js.map +1 -1
  388. package/dist/modules/launcher/runtime_entry.d.ts +5 -10
  389. package/dist/modules/launcher/runtime_entry.d.ts.map +1 -1
  390. package/dist/modules/launcher/runtime_entry.js +14 -14
  391. package/dist/modules/launcher/runtime_entry.js.map +1 -1
  392. package/dist/modules/launcher/status_reporting.d.ts +17 -37
  393. package/dist/modules/launcher/status_reporting.d.ts.map +1 -1
  394. package/dist/modules/launcher/status_reporting.js +35 -34
  395. package/dist/modules/launcher/status_reporting.js.map +1 -1
  396. package/dist/modules/launcher/supervisor_control.d.ts +1 -4
  397. package/dist/modules/launcher/supervisor_control.d.ts.map +1 -1
  398. package/dist/modules/launcher/supervisor_control.js +9 -4
  399. package/dist/modules/launcher/supervisor_control.js.map +1 -1
  400. package/dist/modules/logger.d.ts +3 -1
  401. package/dist/modules/logger.d.ts.map +1 -1
  402. package/dist/modules/logger.js +38 -28
  403. package/dist/modules/logger.js.map +1 -1
  404. package/dist/modules/market_adapter_whitelist.d.ts +2 -10
  405. package/dist/modules/market_adapter_whitelist.d.ts.map +1 -1
  406. package/dist/modules/market_adapter_whitelist.js +18 -16
  407. package/dist/modules/market_adapter_whitelist.js.map +1 -1
  408. package/dist/modules/node_health_cache.d.ts +2 -12
  409. package/dist/modules/node_health_cache.d.ts.map +1 -1
  410. package/dist/modules/node_health_cache.js +24 -24
  411. package/dist/modules/node_health_cache.js.map +1 -1
  412. package/dist/modules/node_manager.d.ts +1 -1
  413. package/dist/modules/node_manager.d.ts.map +1 -1
  414. package/dist/modules/node_manager.js +44 -38
  415. package/dist/modules/node_manager.js.map +1 -1
  416. package/dist/modules/order/accounting.d.ts +12 -12
  417. package/dist/modules/order/accounting.d.ts.map +1 -1
  418. package/dist/modules/order/accounting.js +111 -76
  419. package/dist/modules/order/accounting.js.map +1 -1
  420. package/dist/modules/order/async_lock.d.ts +1 -2
  421. package/dist/modules/order/async_lock.d.ts.map +1 -1
  422. package/dist/modules/order/async_lock.js +4 -4
  423. package/dist/modules/order/async_lock.js.map +1 -1
  424. package/dist/modules/order/export.d.ts +8 -14
  425. package/dist/modules/order/export.d.ts.map +1 -1
  426. package/dist/modules/order/export.js +77 -42
  427. package/dist/modules/order/export.js.map +1 -1
  428. package/dist/modules/order/format.d.ts +17 -22
  429. package/dist/modules/order/format.d.ts.map +1 -1
  430. package/dist/modules/order/format.js +25 -31
  431. package/dist/modules/order/format.js.map +1 -1
  432. package/dist/modules/order/grid.d.ts +18 -104
  433. package/dist/modules/order/grid.d.ts.map +1 -1
  434. package/dist/modules/order/grid.js +346 -212
  435. package/dist/modules/order/grid.js.map +1 -1
  436. package/dist/modules/order/grid_reconcile.d.ts +8 -8
  437. package/dist/modules/order/grid_reconcile.d.ts.map +1 -1
  438. package/dist/modules/order/grid_reconcile.js +80 -23
  439. package/dist/modules/order/grid_reconcile.js.map +1 -1
  440. package/dist/modules/order/grid_reconcile_internal.d.ts +224 -1
  441. package/dist/modules/order/grid_reconcile_internal.d.ts.map +1 -1
  442. package/dist/modules/order/grid_reconcile_internal.js +159 -73
  443. package/dist/modules/order/grid_reconcile_internal.js.map +1 -1
  444. package/dist/modules/order/index.d.ts +1 -1
  445. package/dist/modules/order/index.d.ts.map +1 -1
  446. package/dist/modules/order/index.js +42 -7
  447. package/dist/modules/order/index.js.map +1 -1
  448. package/dist/modules/order/logger.d.ts +6 -16
  449. package/dist/modules/order/logger.d.ts.map +1 -1
  450. package/dist/modules/order/logger.js +76 -53
  451. package/dist/modules/order/logger.js.map +1 -1
  452. package/dist/modules/order/logger_state.d.ts +4 -4
  453. package/dist/modules/order/logger_state.d.ts.map +1 -1
  454. package/dist/modules/order/logger_state.js +3 -1
  455. package/dist/modules/order/logger_state.js.map +1 -1
  456. package/dist/modules/order/manager.d.ts +160 -37
  457. package/dist/modules/order/manager.d.ts.map +1 -1
  458. package/dist/modules/order/manager.js +166 -128
  459. package/dist/modules/order/manager.js.map +1 -1
  460. package/dist/modules/order/processed_fill_store.d.ts +6 -10
  461. package/dist/modules/order/processed_fill_store.d.ts.map +1 -1
  462. package/dist/modules/order/processed_fill_store.js +10 -9
  463. package/dist/modules/order/processed_fill_store.js.map +1 -1
  464. package/dist/modules/order/strategy.d.ts +3 -3
  465. package/dist/modules/order/strategy.d.ts.map +1 -1
  466. package/dist/modules/order/strategy.js +29 -27
  467. package/dist/modules/order/strategy.js.map +1 -1
  468. package/dist/modules/order/sync_engine.d.ts +9 -19
  469. package/dist/modules/order/sync_engine.d.ts.map +1 -1
  470. package/dist/modules/order/sync_engine.js +176 -126
  471. package/dist/modules/order/sync_engine.js.map +1 -1
  472. package/dist/modules/order/utils/math.d.ts +55 -85
  473. package/dist/modules/order/utils/math.d.ts.map +1 -1
  474. package/dist/modules/order/utils/math.js +155 -88
  475. package/dist/modules/order/utils/math.js.map +1 -1
  476. package/dist/modules/order/utils/order.d.ts +27 -72
  477. package/dist/modules/order/utils/order.d.ts.map +1 -1
  478. package/dist/modules/order/utils/order.js +144 -105
  479. package/dist/modules/order/utils/order.js.map +1 -1
  480. package/dist/modules/order/utils/system.d.ts +103 -45
  481. package/dist/modules/order/utils/system.d.ts.map +1 -1
  482. package/dist/modules/order/utils/system.js +271 -150
  483. package/dist/modules/order/utils/system.js.map +1 -1
  484. package/dist/modules/order/utils/validate.d.ts +35 -47
  485. package/dist/modules/order/utils/validate.d.ts.map +1 -1
  486. package/dist/modules/order/utils/validate.js +233 -116
  487. package/dist/modules/order/utils/validate.js.map +1 -1
  488. package/dist/modules/order/working_grid.d.ts +1 -4
  489. package/dist/modules/order/working_grid.d.ts.map +1 -1
  490. package/dist/modules/order/working_grid.js +9 -7
  491. package/dist/modules/order/working_grid.js.map +1 -1
  492. package/dist/modules/path_api.js +2 -2
  493. package/dist/modules/path_api.js.map +1 -1
  494. package/dist/modules/paths.d.ts +50 -56
  495. package/dist/modules/paths.d.ts.map +1 -1
  496. package/dist/modules/paths.js +66 -57
  497. package/dist/modules/paths.js.map +1 -1
  498. package/dist/modules/process_discovery.d.ts +1 -1
  499. package/dist/modules/process_discovery.d.ts.map +1 -1
  500. package/dist/modules/process_discovery.js +7 -7
  501. package/dist/modules/process_discovery.js.map +1 -1
  502. package/dist/modules/runtime.d.ts +1 -1
  503. package/dist/modules/runtime.d.ts.map +1 -1
  504. package/dist/modules/runtime.js +4 -4
  505. package/dist/modules/runtime.js.map +1 -1
  506. package/dist/modules/runtime_settings.d.ts +1 -0
  507. package/dist/modules/runtime_settings.d.ts.map +1 -1
  508. package/dist/modules/runtime_settings.js +15 -10
  509. package/dist/modules/runtime_settings.js.map +1 -1
  510. package/dist/modules/settings_merge.d.ts +1 -4
  511. package/dist/modules/settings_merge.d.ts.map +1 -1
  512. package/dist/modules/settings_merge.js +2 -1
  513. package/dist/modules/settings_merge.js.map +1 -1
  514. package/dist/modules/storage/browser_adapter.d.ts +7 -3
  515. package/dist/modules/storage/browser_adapter.d.ts.map +1 -1
  516. package/dist/modules/storage/browser_adapter.js +2 -0
  517. package/dist/modules/storage/browser_adapter.js.map +1 -1
  518. package/dist/modules/storage/index.d.ts +2 -2
  519. package/dist/modules/storage/index.d.ts.map +1 -1
  520. package/dist/modules/storage/index.js +2 -5
  521. package/dist/modules/storage/index.js.map +1 -1
  522. package/dist/modules/storage/node_adapter.d.ts +3 -3
  523. package/dist/modules/storage/node_adapter.d.ts.map +1 -1
  524. package/dist/modules/storage/node_adapter.js +9 -7
  525. package/dist/modules/storage/node_adapter.js.map +1 -1
  526. package/dist/modules/storage/types.d.ts +13 -10
  527. package/dist/modules/storage/types.d.ts.map +1 -1
  528. package/dist/modules/types.d.ts +0 -2
  529. package/dist/modules/types.d.ts.map +1 -1
  530. package/dist/modules/utils/base58check.d.ts +1 -9
  531. package/dist/modules/utils/base58check.d.ts.map +1 -1
  532. package/dist/modules/utils/base58check.js +14 -16
  533. package/dist/modules/utils/base58check.js.map +1 -1
  534. package/dist/modules/utils/build_dir.d.ts +2 -5
  535. package/dist/modules/utils/build_dir.d.ts.map +1 -1
  536. package/dist/modules/utils/build_dir.js +6 -3
  537. package/dist/modules/utils/build_dir.js.map +1 -1
  538. package/dist/modules/utils/errors.d.ts +2 -0
  539. package/dist/modules/utils/errors.d.ts.map +1 -0
  540. package/dist/modules/utils/errors.js +12 -0
  541. package/dist/modules/utils/errors.js.map +1 -0
  542. package/dist/modules/utils/fs_utils.d.ts +1 -8
  543. package/dist/modules/utils/fs_utils.d.ts.map +1 -1
  544. package/dist/modules/utils/fs_utils.js +8 -3
  545. package/dist/modules/utils/fs_utils.js.map +1 -1
  546. package/dist/modules/utils/math_utils.d.ts +2 -6
  547. package/dist/modules/utils/math_utils.d.ts.map +1 -1
  548. package/dist/modules/utils/math_utils.js +6 -2
  549. package/dist/modules/utils/math_utils.js.map +1 -1
  550. package/dist/modules/validate_profiles.d.ts +1 -11
  551. package/dist/modules/validate_profiles.d.ts.map +1 -1
  552. package/dist/modules/validate_profiles.js +25 -27
  553. package/dist/modules/validate_profiles.js.map +1 -1
  554. package/dist/pm2.d.ts +7 -6
  555. package/dist/pm2.d.ts.map +1 -1
  556. package/dist/pm2.js +132 -106
  557. package/dist/pm2.js.map +1 -1
  558. package/dist/scripts/analyze-git.d.ts.map +1 -1
  559. package/dist/scripts/analyze-git.js +15 -11
  560. package/dist/scripts/analyze-git.js.map +1 -1
  561. package/dist/scripts/analyze-orders.d.ts +146 -1
  562. package/dist/scripts/analyze-orders.d.ts.map +1 -1
  563. package/dist/scripts/analyze-orders.js +81 -105
  564. package/dist/scripts/analyze-orders.js.map +1 -1
  565. package/dist/scripts/diagnose-pool-history.d.ts.map +1 -1
  566. package/dist/scripts/diagnose-pool-history.js +9 -8
  567. package/dist/scripts/diagnose-pool-history.js.map +1 -1
  568. package/dist/scripts/divergence-calc.d.ts.map +1 -1
  569. package/dist/scripts/divergence-calc.js +11 -8
  570. package/dist/scripts/divergence-calc.js.map +1 -1
  571. package/dist/scripts/fix-err-message.d.ts +3 -0
  572. package/dist/scripts/fix-err-message.d.ts.map +1 -0
  573. package/dist/scripts/fix-err-message.js +198 -0
  574. package/dist/scripts/fix-err-message.js.map +1 -0
  575. package/dist/scripts/generate_lp_chart.d.ts +2 -9
  576. package/dist/scripts/generate_lp_chart.d.ts.map +1 -1
  577. package/dist/scripts/generate_lp_chart.js +14 -10
  578. package/dist/scripts/generate_lp_chart.js.map +1 -1
  579. package/dist/scripts/generate_mainnet_corpus_report.js +4 -4
  580. package/dist/scripts/generate_mainnet_corpus_report.js.map +1 -1
  581. package/dist/scripts/generate_market_adapter_whitelist.d.ts +17 -1
  582. package/dist/scripts/generate_market_adapter_whitelist.d.ts.map +1 -1
  583. package/dist/scripts/generate_market_adapter_whitelist.js +23 -20
  584. package/dist/scripts/generate_market_adapter_whitelist.js.map +1 -1
  585. package/dist/scripts/migrate_bot_keys.d.ts +1 -4
  586. package/dist/scripts/migrate_bot_keys.d.ts.map +1 -1
  587. package/dist/scripts/migrate_bot_keys.js +48 -124
  588. package/dist/scripts/migrate_bot_keys.js.map +1 -1
  589. package/dist/scripts/native_release_gates.d.ts.map +1 -1
  590. package/dist/scripts/native_release_gates.js +18 -14
  591. package/dist/scripts/native_release_gates.js.map +1 -1
  592. package/dist/scripts/print_grid.js +1 -1
  593. package/dist/scripts/print_grid.js.map +1 -1
  594. package/dist/scripts/run-tests.js +1 -0
  595. package/dist/scripts/run-tests.js.map +1 -1
  596. package/dist/scripts/runner.d.ts +1 -11
  597. package/dist/scripts/runner.d.ts.map +1 -1
  598. package/dist/scripts/runner.js +21 -19
  599. package/dist/scripts/runner.js.map +1 -1
  600. package/dist/scripts/test-credit-renewal.d.ts.map +1 -1
  601. package/dist/scripts/test-credit-renewal.js +2 -1
  602. package/dist/scripts/test-credit-renewal.js.map +1 -1
  603. package/dist/scripts/update.d.ts.map +1 -1
  604. package/dist/scripts/update.js +85 -79
  605. package/dist/scripts/update.js.map +1 -1
  606. package/dist/scripts/validate_bots.js +2 -2
  607. package/dist/scripts/validate_bots.js.map +1 -1
  608. package/dist/unlock.d.ts +4 -17
  609. package/dist/unlock.d.ts.map +1 -1
  610. package/dist/unlock.js +141 -108
  611. package/dist/unlock.js.map +1 -1
  612. package/package.json +1 -1
  613. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts +0 -3
  614. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  615. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +0 -149
  616. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  617. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts +0 -3
  618. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  619. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +0 -387
  620. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  621. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts +0 -3
  622. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  623. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -200
  624. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  625. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts +0 -3
  626. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  627. package/dist/analysis/ama_fitting/fetch_lp_candles.js +0 -212
  628. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  629. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +0 -31
  630. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  631. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +0 -249
  632. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  633. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +0 -2
  634. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  635. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +0 -782
  636. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  637. package/dist/analysis/analyze_derivatives.d.ts +0 -95
  638. package/dist/analysis/analyze_derivatives.d.ts.map +0 -1
  639. package/dist/analysis/analyze_derivatives.js +0 -295
  640. package/dist/analysis/analyze_derivatives.js.map +0 -1
  641. package/dist/analysis/analyze_dynamic_weight.d.ts +0 -14
  642. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  643. package/dist/analysis/analyze_dynamic_weight.js +0 -207
  644. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  645. package/dist/analysis/analyze_kalman.d.ts +0 -13
  646. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  647. package/dist/analysis/analyze_kalman.js +0 -123
  648. package/dist/analysis/analyze_kalman.js.map +0 -1
  649. package/dist/analysis/analyze_regime.d.ts +0 -20
  650. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  651. package/dist/analysis/analyze_regime.js +0 -139
  652. package/dist/analysis/analyze_regime.js.map +0 -1
  653. package/dist/analysis/analyze_regime_windows.d.ts +0 -19
  654. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  655. package/dist/analysis/analyze_regime_windows.js +0 -413
  656. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  657. package/dist/analysis/analyze_risk_profile.d.ts +0 -3
  658. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  659. package/dist/analysis/analyze_risk_profile.js +0 -159
  660. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  661. package/dist/analysis/analyze_trade_heatmap.d.ts +0 -3
  662. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  663. package/dist/analysis/analyze_trade_heatmap.js +0 -367
  664. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  665. package/dist/analysis/analyze_volatility.d.ts +0 -22
  666. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  667. package/dist/analysis/analyze_volatility.js +0 -172
  668. package/dist/analysis/analyze_volatility.js.map +0 -1
  669. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +0 -99
  670. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  671. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +0 -804
  672. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  673. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +0 -2
  674. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  675. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +0 -347
  676. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  677. package/dist/analysis/bot_fitting/shared_utils.d.ts +0 -15
  678. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  679. package/dist/analysis/bot_fitting/shared_utils.js +0 -48
  680. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  681. package/dist/analysis/bot_key_utils.d.ts +0 -22
  682. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  683. package/dist/analysis/bot_key_utils.js +0 -162
  684. package/dist/analysis/bot_key_utils.js.map +0 -1
  685. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts +0 -3
  686. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  687. package/dist/analysis/bot_usage/discover_bot_accounts.js +0 -498
  688. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  689. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +0 -546
  690. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  691. package/dist/analysis/bot_usage/kibana_bot_queries.js +0 -427
  692. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  693. package/dist/analysis/derivative_chart_generator.d.ts +0 -18
  694. package/dist/analysis/derivative_chart_generator.d.ts.map +0 -1
  695. package/dist/analysis/derivative_chart_generator.js +0 -896
  696. package/dist/analysis/derivative_chart_generator.js.map +0 -1
  697. package/dist/analysis/price_sources.d.ts +0 -34
  698. package/dist/analysis/price_sources.d.ts.map +0 -1
  699. package/dist/analysis/price_sources.js +0 -103
  700. package/dist/analysis/price_sources.js.map +0 -1
  701. package/dist/analysis/trade_profitability.d.ts +0 -115
  702. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  703. package/dist/analysis/trade_profitability.js +0 -1247
  704. package/dist/analysis/trade_profitability.js.map +0 -1
  705. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -36
  706. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  707. package/dist/analysis/tradingview/analyze_tradingview.js +0 -172
  708. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  709. package/dist/analysis/trend_detection/derivative_analyzer.d.ts +0 -250
  710. package/dist/analysis/trend_detection/derivative_analyzer.d.ts.map +0 -1
  711. package/dist/analysis/trend_detection/derivative_analyzer.js +0 -903
  712. package/dist/analysis/trend_detection/derivative_analyzer.js.map +0 -1
  713. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +0 -6
  714. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  715. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +0 -1450
  716. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  717. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +0 -6
  718. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  719. package/dist/analysis/trend_detection/kalman_chart_generator.js +0 -408
  720. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  721. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +0 -6
  722. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  723. package/dist/analysis/trend_detection/regime_chart_generator.js +0 -345
  724. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  725. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  726. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  727. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -130
  728. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  729. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  730. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  731. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -38
  732. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  733. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +0 -6
  734. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  735. package/dist/analysis/trend_detection/volatility_chart_generator.js +0 -732
  736. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
@@ -95,6 +95,39 @@
95
95
  *
96
96
  * ===============================================================================
97
97
  */
98
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
99
+ if (k2 === undefined) k2 = k;
100
+ var desc = Object.getOwnPropertyDescriptor(m, k);
101
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
102
+ desc = { enumerable: true, get: function() { return m[k]; } };
103
+ }
104
+ Object.defineProperty(o, k2, desc);
105
+ }) : (function(o, m, k, k2) {
106
+ if (k2 === undefined) k2 = k;
107
+ o[k2] = m[k];
108
+ }));
109
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
110
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
111
+ }) : function(o, v) {
112
+ o["default"] = v;
113
+ });
114
+ var __importStar = (this && this.__importStar) || (function () {
115
+ var ownKeys = function(o) {
116
+ ownKeys = Object.getOwnPropertyNames || function (o) {
117
+ var ar = [];
118
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
119
+ return ar;
120
+ };
121
+ return ownKeys(o);
122
+ };
123
+ return function (mod) {
124
+ if (mod && mod.__esModule) return mod;
125
+ var result = {};
126
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
127
+ __setModuleDefault(result, mod);
128
+ return result;
129
+ };
130
+ })();
98
131
  Object.defineProperty(exports, "__esModule", { value: true });
99
132
  exports.calculateGapSlots = calculateGapSlots;
100
133
  exports.isGridBloated = isGridBloated;
@@ -120,10 +153,10 @@ exports.getDustOrders = getDustOrders;
120
153
  exports.determineOrderSideByFunds = determineOrderSideByFunds;
121
154
  exports.calculateGeometricSizeForSpreadCorrection = calculateGeometricSizeForSpreadCorrection;
122
155
  exports.prepareSpreadCorrectionOrders = prepareSpreadCorrectionOrders;
123
- const { ORDER_TYPES, ORDER_STATES, COW_ACTIONS, DEFAULT_CONFIG, GRID_LIMITS, TIMING, MARKET_ADAPTER } = require('../constants');
124
- const { GRID_COMPARISON } = GRID_LIMITS;
125
- const Format = require('./format');
126
- const { resolveMaxAsymmetryFactor, applyAsymmetricBounds, } = require('../../market_adapter/core/asymmetric_bounds');
156
+ const constants_1 = require("../constants");
157
+ const { GRID_COMPARISON } = constants_1.GRID_LIMITS;
158
+ const Format = __importStar(require("./format"));
159
+ const asymmetric_bounds_1 = require("../../market_adapter/core/asymmetric_bounds");
127
160
  // FIX: Extract magic numbers to named constants for maintainability
128
161
  const GRID_CONSTANTS = {
129
162
  RMS_PERCENTAGE_SCALE: 100, // Convert RMS percentage threshold from percent to decimal
@@ -136,12 +169,13 @@ function _snapshotFundState(manager) {
136
169
  sellLocked: Number(manager.accountTotals?.sellLocked || 0),
137
170
  };
138
171
  }
139
- const { floatToBlockchainInt, blockchainToFloat, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinAbsoluteOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots: _mathGapSlots, calculatePriceTolerance } = require('./utils/math');
140
- const { adjustBudgetForBtsFees, filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, hasOnChainId, calculateIdealBoundary, assignGridRoles } = require('./utils/order');
141
- const { derivePrice, loadAmaCenterPrice, loadAmaCenterSnapshot } = require('./utils/system');
142
- const { getWhitelistFlags } = require('../market_adapter_whitelist');
172
+ const math_1 = require("./utils/math");
173
+ const order_1 = require("./utils/order");
174
+ const system_1 = require("./utils/system");
175
+ const market_adapter_whitelist_1 = require("../market_adapter_whitelist");
176
+ const errors_1 = require("../utils/errors");
143
177
  function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimitsOverride) {
144
- return _mathGapSlots(incrementPercent, targetSpreadPercent, gridLimitsOverride ?? GRID_LIMITS);
178
+ return (0, math_1.calculateGapSlots)(incrementPercent, targetSpreadPercent, gridLimitsOverride ?? constants_1.GRID_LIMITS);
145
179
  }
146
180
  function isGridBloated(manager, orders) {
147
181
  const gridSize = Array.isArray(orders) ? orders.length : orders.size;
@@ -153,11 +187,11 @@ function isGridBloated(manager, orders) {
153
187
  return { bloated: false };
154
188
  const targetSpreadPct = config.targetSpreadPercent || incPct * 2;
155
189
  const orderList = Array.isArray(orders) ? orders : Array.from(orders.values());
156
- const numBuyActive = orderList.filter((o) => o.type === ORDER_TYPES.BUY &&
157
- (o.state === ORDER_STATES.ACTIVE || o.state === ORDER_STATES.PARTIAL) &&
190
+ const numBuyActive = orderList.filter((o) => o.type === constants_1.ORDER_TYPES.BUY &&
191
+ (o.state === constants_1.ORDER_STATES.ACTIVE || o.state === constants_1.ORDER_STATES.PARTIAL) &&
158
192
  o.orderId).length;
159
- const numSellActive = orderList.filter((o) => o.type === ORDER_TYPES.SELL &&
160
- (o.state === ORDER_STATES.ACTIVE || o.state === ORDER_STATES.PARTIAL) &&
193
+ const numSellActive = orderList.filter((o) => o.type === constants_1.ORDER_TYPES.SELL &&
194
+ (o.state === constants_1.ORDER_STATES.ACTIVE || o.state === constants_1.ORDER_STATES.PARTIAL) &&
161
195
  o.orderId).length;
162
196
  const placedCount = numBuyActive + numSellActive;
163
197
  if (!placedCount)
@@ -188,7 +222,7 @@ function isGridBloated(manager, orders) {
188
222
  }
189
223
  }
190
224
  const railEstimate = Math.max(expectedTotal, placedCount);
191
- const buffer = (config.gridLimits?.MIN_SPREAD_ORDERS ?? GRID_LIMITS.MIN_SPREAD_ORDERS);
225
+ const buffer = (config.gridLimits?.MIN_SPREAD_ORDERS ?? constants_1.GRID_LIMITS.MIN_SPREAD_ORDERS);
192
226
  const maxAllowed = railEstimate + gapSlots + buffer;
193
227
  return {
194
228
  bloated: gridSize > maxAllowed,
@@ -209,7 +243,7 @@ function isGridBloated(manager, orders) {
209
243
  * @returns {{active: boolean, elapsed: number, graceMs: number}}
210
244
  */
211
245
  function isGridBloatGraceActive(manager) {
212
- const graceMs = Number(TIMING?.GRID_BLOAT_RESYNC_GRACE_MS) || TIMING.GRID_BLOAT_RESYNC_GRACE_MS;
246
+ const graceMs = Number(constants_1.TIMING?.GRID_BLOAT_RESYNC_GRACE_MS) || constants_1.TIMING.GRID_BLOAT_RESYNC_GRACE_MS;
213
247
  if (!manager._gridBloatDetectedAt) {
214
248
  return { active: false, elapsed: 0, graceMs };
215
249
  }
@@ -253,7 +287,7 @@ async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
253
287
  }
254
288
  const snap = manager.getChainFundsSnapshot ? manager.getChainFundsSnapshot() : {};
255
289
  const isBuy = side === 'buy';
256
- const type = isBuy ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
290
+ const type = isBuy ? constants_1.ORDER_TYPES.BUY : constants_1.ORDER_TYPES.SELL;
257
291
  // 2. Determine base budget: Always use ALLOCATED funds (respects botFunds %)
258
292
  // This ensures the bot only "thinks" about the capital it is allowed to use.
259
293
  let budget = isBuy ? (snap.allocatedBuy || 0) : (snap.allocatedSell || 0);
@@ -265,13 +299,13 @@ async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
265
299
  const targetSell = Math.max(0, manager.config.activeOrders?.sell ?? 1);
266
300
  const totalTarget = targetBuy + targetSell;
267
301
  const isBtsSide = (isBuy && manager.config.assetB === 'BTS') || (!isBuy && manager.config.assetA === 'BTS');
268
- const formulaBudget = calculateOrderCreationFees(manager.config.assetA, manager.config.assetB, totalTarget, manager.config?.feeParams?.BTS_RESERVATION_MULTIPLIER);
269
- budget = adjustBudgetForBtsFees(budget, isBtsSide, formulaBudget, manager.config.min_BTS_value || 0, Format.toFiniteNumber(manager.funds?.btsBalance?.free, 0), Format.toFiniteNumber(isBuy ? (snap.allocatedBuy || 0) : (snap.allocatedSell || 0)), Format.toFiniteNumber(snap.allocatedBuy || 0)
302
+ const formulaBudget = (0, math_1.calculateOrderCreationFees)(manager.config.assetA, manager.config.assetB, totalTarget, manager.config?.feeParams?.BTS_RESERVATION_MULTIPLIER);
303
+ budget = (0, order_1.adjustBudgetForBtsFees)(budget, isBtsSide, formulaBudget, manager.config.min_BTS_value || 0, Format.toFiniteNumber(manager.funds?.btsBalance?.free, 0), Format.toFiniteNumber(isBuy ? (snap.allocatedBuy || 0) : (snap.allocatedSell || 0)), Format.toFiniteNumber(snap.allocatedBuy || 0)
270
304
  + Format.toFiniteNumber(snap.allocatedSell || 0));
271
305
  }
272
306
  return {
273
307
  budget,
274
- precision: getPrecisionByOrderType(manager.assets, type),
308
+ precision: (0, math_1.getPrecisionByOrderType)(manager.assets, type),
275
309
  config: manager.config
276
310
  };
277
311
  }
@@ -401,7 +435,7 @@ function createOrderGrid(config) {
401
435
  // Determine the boundary and assign roles (BUY/SPREAD/SELL) to each slot.
402
436
  //
403
437
  // STRATEGY: Center the spread gap around startPrice
404
- const boundaryIdx = calculateIdealBoundary(priceLevels.map(p => ({ price: p })), startPrice, gapSlots);
438
+ const boundaryIdx = (0, order_1.calculateIdealBoundary)(priceLevels.map((p) => ({ price: p })), startPrice, gapSlots);
405
439
  // ================================================================================
406
440
  // STEP 4: CREATE ORDER OBJECTS
407
441
  // ================================================================================
@@ -410,12 +444,12 @@ function createOrderGrid(config) {
410
444
  id: `slot-${i}`,
411
445
  price,
412
446
  type: null, // assigned below
413
- state: ORDER_STATES.VIRTUAL,
447
+ state: constants_1.ORDER_STATES.VIRTUAL,
414
448
  size: 0
415
449
  }));
416
- const updatedOrders = assignGridRoles(orders, boundaryIdx, gapSlots, ORDER_TYPES, ORDER_STATES);
417
- const buyCount = updatedOrders.filter(o => o.type === ORDER_TYPES.BUY).length;
418
- const sellCount = updatedOrders.filter(o => o.type === ORDER_TYPES.SELL).length;
450
+ const updatedOrders = (0, order_1.assignGridRoles)(orders, boundaryIdx, gapSlots, constants_1.ORDER_TYPES, constants_1.ORDER_STATES);
451
+ const buyCount = updatedOrders.filter((o) => o.type === constants_1.ORDER_TYPES.BUY).length;
452
+ const sellCount = updatedOrders.filter((o) => o.type === constants_1.ORDER_TYPES.SELL).length;
419
453
  if (buyCount === 0 || sellCount === 0) {
420
454
  throw new Error(`Grid generation produced an imbalanced rail (buy=${buyCount}, sell=${sellCount}) for ` +
421
455
  `startPrice=${startPrice}, bounds=[${minPrice}, ${maxPrice}], incrementPercent=${incrementPercent}, ` +
@@ -468,7 +502,7 @@ async function loadGrid(manager, grid, boundaryIdx = null) {
468
502
  await manager._initializeAssets();
469
503
  }
470
504
  catch (e) {
471
- manager.logger?.log?.(`Asset initialization failed during grid load: ${e.message}`, 'warn');
505
+ manager.logger?.log?.(`Asset initialization failed during grid load: ${(0, errors_1.getErrorMessage)(e)}`, 'warn');
472
506
  }
473
507
  // RC-2: Use logic helper
474
508
  _clearOrderCachesLogic(manager);
@@ -491,12 +525,12 @@ async function loadGrid(manager, grid, boundaryIdx = null) {
491
525
  const sellStartIdx = boundaryIdx + gapSlots + 1;
492
526
  let reassignCount = 0;
493
527
  grid = grid.map((slot, i) => {
494
- if (slot.state === ORDER_STATES.VIRTUAL && !slot.orderId) {
528
+ if (slot.state === constants_1.ORDER_STATES.VIRTUAL && !slot.orderId) {
495
529
  const correctType = (i <= buyEndIdx)
496
- ? ORDER_TYPES.BUY
530
+ ? constants_1.ORDER_TYPES.BUY
497
531
  : (i >= sellStartIdx)
498
- ? ORDER_TYPES.SELL
499
- : ORDER_TYPES.SPREAD;
532
+ ? constants_1.ORDER_TYPES.SELL
533
+ : constants_1.ORDER_TYPES.SPREAD;
500
534
  if (slot.type !== correctType) {
501
535
  reassignCount++;
502
536
  return { ...slot, type: correctType };
@@ -525,7 +559,7 @@ async function loadGrid(manager, grid, boundaryIdx = null) {
525
559
  manager._gridBloatDetectedAt = Date.now();
526
560
  if (typeof manager.requestStructuralGridResync === 'function') {
527
561
  manager.requestStructuralGridResync('grid-bloat-detected', { reason: `Grid size ${d.gridSize} exceeds maximum ${d.maxAllowed}` }).catch((err) => {
528
- manager.logger?.log?.(`[GRID-BLOAT] Structural resync request failed: ${err.message}`, 'error');
562
+ manager.logger?.log?.(`[GRID-BLOAT] Structural resync request failed: ${(0, errors_1.getErrorMessage)(err)}`, 'error');
529
563
  });
530
564
  }
531
565
  }
@@ -536,13 +570,13 @@ async function loadGrid(manager, grid, boundaryIdx = null) {
536
570
  // RC-2: Use applyOrderUpdate (PRIVATE/UNLOCKED)
537
571
  for (const order of grid) {
538
572
  let currentOrder = order;
539
- if (isPhantomOrder(order)) {
573
+ if ((0, order_1.isPhantomOrder)(order)) {
540
574
  manager.logger?.log?.(`Sanitizing corrupted order ${order.id}: ACTIVE/PARTIAL without orderId -> VIRTUAL`, 'warn');
541
- currentOrder = { ...order, state: ORDER_STATES.VIRTUAL };
575
+ currentOrder = { ...order, state: constants_1.ORDER_STATES.VIRTUAL };
542
576
  }
543
577
  await manager._applyOrderUpdate(currentOrder, 'grid-load', { skipAccounting: true });
544
578
  }
545
- const spreadCount = grid.filter(o => o.type === ORDER_TYPES.SPREAD).length;
579
+ const spreadCount = grid.filter((o) => o.type === constants_1.ORDER_TYPES.SPREAD).length;
546
580
  manager.targetSpreadCount = spreadCount;
547
581
  manager.currentSpreadCount = spreadCount;
548
582
  }
@@ -576,7 +610,7 @@ async function initializeGrid(manager) {
576
610
  if (typeof mpRaw !== 'number' || isNaN(mpRaw)) {
577
611
  try {
578
612
  const { BitShares } = require('../bitshares_client');
579
- const derived = await derivePrice(BitShares, manager.config.assetA, manager.config.assetB, manager.config.priceMode || 'auto');
613
+ const derived = await (0, system_1.derivePrice)(BitShares, manager.config.assetA, manager.config.assetB, manager.config.priceMode || 'auto');
580
614
  if (derived) {
581
615
  manager.logger?.log?.(`[DIAGNOSTIC] initializeGrid: Derived new startPrice=${derived.toFixed(8)} (mode=${manager.config.priceMode || 'auto'})`, 'info');
582
616
  manager.config.startPrice = Number(derived);
@@ -586,11 +620,10 @@ async function initializeGrid(manager) {
586
620
  }
587
621
  }
588
622
  catch (err) {
589
- manager.logger?.log?.(`Failed to derive market price: ${err.message}`, 'warn');
623
+ manager.logger?.log?.(`Failed to derive market price: ${(0, errors_1.getErrorMessage)(err)}`, 'warn');
590
624
  throw err; // Re-throw to prevent "pool" string reaching numeric math
591
625
  }
592
626
  }
593
- const configuredStartPrice = manager.config.startPrice;
594
627
  const configuredMinPrice = manager.config.minPrice;
595
628
  const configuredMaxPrice = manager.config.maxPrice;
596
629
  const mp = Number(manager.config.startPrice);
@@ -603,7 +636,7 @@ async function initializeGrid(manager) {
603
636
  let gp = mp;
604
637
  let gpSource = 'startPrice';
605
638
  let amaSnapshot = null;
606
- const whitelistFlags = getWhitelistFlags(manager.config.botKey);
639
+ const whitelistFlags = (0, market_adapter_whitelist_1.getWhitelistFlags)(manager.config.botKey);
607
640
  const isGridRangeScalingWhitelisted = whitelistFlags.asymmetricBounds === true;
608
641
  let gridPriceOffsetPct = 0;
609
642
  const gpRaw = manager.config.gridPrice;
@@ -616,7 +649,7 @@ async function initializeGrid(manager) {
616
649
  else if (gpMode === 'pool' || gpMode === 'book') {
617
650
  try {
618
651
  const { BitShares } = require('../bitshares_client');
619
- const derived = await derivePrice(BitShares, manager.config.assetA, manager.config.assetB, gpMode);
652
+ const derived = await (0, system_1.derivePrice)(BitShares, manager.config.assetA, manager.config.assetB, gpMode);
620
653
  if (derived) {
621
654
  gp = Number(derived);
622
655
  gpSource = gpMode;
@@ -627,12 +660,12 @@ async function initializeGrid(manager) {
627
660
  }
628
661
  }
629
662
  catch (err) {
630
- manager.logger?.log?.(`initializeGrid: ${gpMode} gridPrice derivation failed: ${err.message}`, 'warn');
663
+ manager.logger?.log?.(`initializeGrid: ${gpMode} gridPrice derivation failed: ${(0, errors_1.getErrorMessage)(err)}`, 'warn');
631
664
  }
632
665
  }
633
666
  else if (/^ama(?:[1-4])?$/.test(gpMode || '')) {
634
- amaSnapshot = loadAmaCenterSnapshot(manager.config.botKey);
635
- const amaCenter = amaSnapshot?.gridCenterPrice ?? loadAmaCenterPrice(manager.config.botKey);
667
+ amaSnapshot = (0, system_1.loadAmaCenterSnapshot)(manager.config.botKey);
668
+ const amaCenter = amaSnapshot?.gridCenterPrice ?? (0, system_1.loadAmaCenterPrice)(manager.config.botKey);
636
669
  if (Number.isFinite(amaCenter) && amaCenter > 0) {
637
670
  gp = amaCenter;
638
671
  gpSource = 'ama';
@@ -647,8 +680,8 @@ async function initializeGrid(manager) {
647
680
  manager.logger?.log?.(`initializeGrid: AMA center unavailable for gridPrice, falling back to startPrice`, 'warn');
648
681
  }
649
682
  }
650
- const minP = resolveConfiguredPriceBound(manager.config.minPrice, DEFAULT_CONFIG.minPrice, gp, 'min');
651
- const maxP = resolveConfiguredPriceBound(manager.config.maxPrice, DEFAULT_CONFIG.maxPrice, gp, 'max');
683
+ const minP = (0, order_1.resolveConfiguredPriceBound)(manager.config.minPrice, constants_1.DEFAULT_CONFIG.minPrice, gp, 'min');
684
+ const maxP = (0, order_1.resolveConfiguredPriceBound)(manager.config.maxPrice, constants_1.DEFAULT_CONFIG.maxPrice, gp, 'max');
652
685
  // Asymmetric bound adjustment: widen the bound in the AMA trend direction
653
686
  // and tighten the opposite side, giving the grid more room when the center
654
687
  // trails price. Uses slope data from the dynamicgrid.json snapshot.
@@ -665,8 +698,8 @@ async function initializeGrid(manager) {
665
698
  ? amaSnapshot.asymmetricBounds
666
699
  : null;
667
700
  if (dw) {
668
- const maxAsymmetryFactor = resolveMaxAsymmetryFactor(manager.config.asymmetricBounds?.maxAsymmetryFactor, dw?.maxAsymmetryFactor, MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MAX_ASYMMETRY_FACTOR);
669
- const adjustment = applyAsymmetricBounds({
701
+ const maxAsymmetryFactor = (0, asymmetric_bounds_1.resolveMaxAsymmetryFactor)(manager.config.asymmetricBounds?.maxAsymmetryFactor, dw?.maxAsymmetryFactor, constants_1.MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MAX_ASYMMETRY_FACTOR);
702
+ const adjustment = (0, asymmetric_bounds_1.applyAsymmetricBounds)({
670
703
  centerPrice: gp,
671
704
  minPrice: minP,
672
705
  maxPrice: maxP,
@@ -680,11 +713,11 @@ async function initializeGrid(manager) {
680
713
  resolvedMaxP = adjustment.resolvedMaxPrice;
681
714
  rangeScalingFactor = Number(adjustment.appliedAsymmetryFactor);
682
715
  manager.logger?.log?.(`[BOUND-ASYMMETRY] trend=${dw.trend} slopeOffset=${dw.slopeOffset.toFixed(4)} `
683
- + `raw=${(adjustment.rawAsymmetryFactor * 100).toFixed(1)}% `
684
- + `cap=${(maxAsymmetryFactor * 100).toFixed(0)}% `
685
- + `asymmetry=${(adjustment.appliedAsymmetryFactor * 100).toFixed(1)}% `
686
- + `min ${minP.toFixed(8)}→${resolvedMinP.toFixed(8)} `
687
- + `max ${maxP.toFixed(8)}→${resolvedMaxP.toFixed(8)}`, 'info');
716
+ + `raw=${((adjustment.rawAsymmetryFactor ?? 0) * 100).toFixed(1)}% `
717
+ + `cap=${((maxAsymmetryFactor ?? 0) * 100).toFixed(0)}% `
718
+ + `asymmetry=${((adjustment.appliedAsymmetryFactor ?? 0) * 100).toFixed(1)}% `
719
+ + `min ${(minP ?? 0).toFixed(8)}→${(resolvedMinP ?? 0).toFixed(8)} `
720
+ + `max ${(maxP ?? 0).toFixed(8)}→${(resolvedMaxP ?? 0).toFixed(8)}`, 'info');
688
721
  }
689
722
  }
690
723
  else if (rootBounds && Number.isFinite(rootBounds.appliedAsymmetryFactor)
@@ -702,8 +735,8 @@ async function initializeGrid(manager) {
702
735
  rangeScalingFactor = asymmetry;
703
736
  manager.logger?.log?.(`[BOUND-ASYMMETRY] trend=${rootTrend} `
704
737
  + `asymmetry=${(asymmetry * 100).toFixed(1)}% `
705
- + `(root-level) min ${minP.toFixed(8)}→${resolvedMinP.toFixed(8)} `
706
- + `max ${maxP.toFixed(8)}→${resolvedMaxP.toFixed(8)}`, 'info');
738
+ + `(root-level) min ${(minP ?? 0).toFixed(8)}→${(resolvedMinP ?? 0).toFixed(8)} `
739
+ + `max ${(maxP ?? 0).toFixed(8)}→${(resolvedMaxP ?? 0).toFixed(8)}`, 'info');
707
740
  }
708
741
  }
709
742
  let gridStartPrice = mp;
@@ -715,14 +748,16 @@ async function initializeGrid(manager) {
715
748
  gridStartPrice = adjustedMarketPrice;
716
749
  offsetAdjustedStartPrice = adjustedMarketPrice;
717
750
  }
718
- if (!(gridStartPrice >= resolvedMinP && gridStartPrice <= resolvedMaxP)) {
719
- if (Number.isFinite(gp) && gp > 0 && gp >= resolvedMinP && gp <= resolvedMaxP) {
751
+ const rMinP = resolvedMinP ?? 0;
752
+ const rMaxP = resolvedMaxP ?? 0;
753
+ if (!(gridStartPrice >= rMinP && gridStartPrice <= rMaxP)) {
754
+ if (Number.isFinite(gp) && gp > 0 && gp >= rMinP && gp <= rMaxP) {
720
755
  gridStartPrice = gp;
721
- manager.logger?.log?.(`initializeGrid: startPrice (${mp}) outside bounds [${resolvedMinP}, ${resolvedMaxP}]; using gridPrice center ${gp}`, 'warn');
756
+ manager.logger?.log?.(`initializeGrid: startPrice (${mp}) outside bounds [${rMinP}, ${rMaxP}]; using gridPrice center ${gp}`, 'warn');
722
757
  }
723
758
  else {
724
- const clamped = Math.min(resolvedMaxP, Math.max(resolvedMinP, gridStartPrice));
725
- manager.logger?.log?.(`initializeGrid: startPrice (${mp}) outside bounds [${resolvedMinP}, ${resolvedMaxP}]; clamping to ${clamped}`, 'warn');
759
+ const clamped = Math.min(rMaxP, Math.max(rMinP, gridStartPrice));
760
+ manager.logger?.log?.(`initializeGrid: startPrice (${mp}) outside bounds [${rMinP}, ${rMaxP}]; clamping to ${clamped}`, 'warn');
726
761
  gridStartPrice = clamped;
727
762
  }
728
763
  }
@@ -740,14 +775,14 @@ async function initializeGrid(manager) {
740
775
  // Ensure percentage-based funds are resolved before sizing
741
776
  try {
742
777
  if (manager.accountId && !manager.accountTotals) {
743
- await manager.waitForAccountTotals(TIMING.ACCOUNT_TOTALS_TIMEOUT_MS);
778
+ await manager.waitForAccountTotals(constants_1.TIMING.ACCOUNT_TOTALS_TIMEOUT_MS);
744
779
  }
745
780
  }
746
781
  catch (e) {
747
- manager.logger?.log?.(`Failed to load account totals: ${e.message}`, 'warn');
782
+ manager.logger?.log?.(`Failed to load account totals: ${(0, errors_1.getErrorMessage)(e)}`, 'warn');
748
783
  // FIX: Add error handling - cannot proceed with grid initialization without account totals
749
784
  // Continuing would create grid with 0 fund allocation, rendering it non-functional
750
- throw new Error(`Cannot initialize grid without account totals: ${e.message}`);
785
+ throw new Error(`Cannot initialize grid without account totals: ${(0, errors_1.getErrorMessage)(e)}`);
751
786
  }
752
787
  const { orders, boundaryIdx, initialSpreadCount } = createOrderGrid({
753
788
  ...manager.config,
@@ -765,13 +800,13 @@ async function initializeGrid(manager) {
765
800
  manager.notifyBoundaryUpdate(boundaryIdx);
766
801
  }
767
802
  catch (err) {
768
- manager.logger?.log?.(`Error notifying boundary update: ${err.message}`, 'warn');
803
+ manager.logger?.log?.(`Error notifying boundary update: ${(0, errors_1.getErrorMessage)(err)}`, 'warn');
769
804
  }
770
805
  }
771
806
  }
772
- const minSellSize = getMinAbsoluteOrderSize(ORDER_TYPES.SELL, manager.assets);
773
- const minBuySize = getMinAbsoluteOrderSize(ORDER_TYPES.BUY, manager.assets);
774
- const { A: precA, B: precB } = getPrecisionsForManager(manager.assets);
807
+ const minSellSize = (0, math_1.getMinAbsoluteOrderSize)(constants_1.ORDER_TYPES.SELL, manager.assets);
808
+ const minBuySize = (0, math_1.getMinAbsoluteOrderSize)(constants_1.ORDER_TYPES.BUY, manager.assets);
809
+ const { A: precA, B: precB } = (0, math_1.getPrecisionsForManager)(manager.assets);
775
810
  // Use centralized sizing context for both sides.
776
811
  // Resolve funds once upfront so both contexts share the same snapshot,
777
812
  // avoiding a redundant recalculateFunds inside the second _getSizingContext call.
@@ -780,17 +815,17 @@ async function initializeGrid(manager) {
780
815
  const buyCtx = await _getSizingContext(manager, 'buy', { skipRecalc: true });
781
816
  if (!sellCtx || !buyCtx)
782
817
  throw new Error('Failed to retrieve sizing context for grid initialization');
783
- let sizedOrders = calculateOrderSizes(orders, manager.config, sellCtx.budget, buyCtx.budget, minSellSize, minBuySize, precA, precB);
818
+ let sizedOrders = (0, math_1.calculateOrderSizes)(orders, manager.config, sellCtx.budget, buyCtx.budget, minSellSize, minBuySize, precA, precB);
784
819
  // Verification of sizes
785
- const sells = filterOrdersByType(sizedOrders, ORDER_TYPES.SELL).map(o => Number(o.size || 0));
786
- const buys = filterOrdersByType(sizedOrders, ORDER_TYPES.BUY).map(o => Number(o.size || 0));
787
- if (checkSizesBeforeMinimum(sells, minSellSize, precA) || checkSizesBeforeMinimum(buys, minBuySize, precB)) {
820
+ const sells = (0, order_1.filterOrdersByType)(sizedOrders, constants_1.ORDER_TYPES.SELL).map((o) => Number(o.size || 0));
821
+ const buys = (0, order_1.filterOrdersByType)(sizedOrders, constants_1.ORDER_TYPES.BUY).map((o) => Number(o.size || 0));
822
+ if ((0, order_1.checkSizesBeforeMinimum)(sells, minSellSize, precA) || (0, order_1.checkSizesBeforeMinimum)(buys, minBuySize, precB)) {
788
823
  throw new Error('Calculated orders fall below minimum allowable size.');
789
824
  }
790
825
  // Check for warning if orders are near minimal size (regression fix)
791
- const warningSellSize = minSellSize > 0 ? getMinAbsoluteOrderSize(ORDER_TYPES.SELL, manager.assets, 100) : 0;
792
- const warningBuySize = minBuySize > 0 ? getMinAbsoluteOrderSize(ORDER_TYPES.BUY, manager.assets, 100) : 0;
793
- if (checkSizeThreshold(sells, warningSellSize, precA, false) || checkSizeThreshold(buys, warningBuySize, precB, false)) {
826
+ const warningSellSize = minSellSize > 0 ? (0, math_1.getMinAbsoluteOrderSize)(constants_1.ORDER_TYPES.SELL, manager.assets, 100) : 0;
827
+ const warningBuySize = minBuySize > 0 ? (0, math_1.getMinAbsoluteOrderSize)(constants_1.ORDER_TYPES.BUY, manager.assets, 100) : 0;
828
+ if ((0, order_1.checkSizeThreshold)(sells, warningSellSize, precA, false) || (0, order_1.checkSizeThreshold)(buys, warningBuySize, precB, false)) {
794
829
  manager.logger?.log?.("WARNING: Order grid contains orders near minimum size. To ensure the bot runs properly, consider increasing the funds of your bot.", "warn");
795
830
  }
796
831
  // RC-2: Wrap atomic changes in grid lock
@@ -832,32 +867,48 @@ async function recalculateGrid(manager, opts) {
832
867
  const { readOpenOrdersFn, chainOrders, account, privateKey } = opts;
833
868
  // Suppress invariant warnings during full resync
834
869
  manager.startBootstrap();
835
- try {
836
- // FIX: Use consistent optional chaining pattern for logger calls
870
+ // Total timeout across all steps — prevents indefinite hang even if
871
+ // an individual withBlockchainRetry step pins the event loop.
872
+ const totalTimeoutMs = constants_1.PIPELINE_TIMING.TIMEOUT_MS * 2; // 10 min
873
+ const work = (async () => {
837
874
  manager.logger?.log?.('Starting full resync...', 'info');
875
+ // #1: Initialize assets (returns immediately if already loaded)
838
876
  await manager._initializeAssets();
839
- await manager.fetchAccountTotals();
840
- const chainOpenOrders = await readOpenOrdersFn();
877
+ // #2: Fetch account totals with timeout + retry + node failover
878
+ await (0, system_1.withBlockchainRetry)(() => manager.fetchAccountTotals(), 'fetchAccountTotals', { logger: manager.logger });
879
+ // #3: Read open orders with timeout + retry + node failover
880
+ const chainOpenOrders = await (0, system_1.withBlockchainRetry)(() => readOpenOrdersFn(), 'readOpenOrders', { logger: manager.logger });
841
881
  if (!Array.isArray(chainOpenOrders))
842
882
  return;
843
- // CRITICAL: Filter out PARTIAL orders before synchronizing - they're from old grid
844
- // and shouldn't be part of the fresh regenerated grid structure
845
- const activeOrders = chainOpenOrders.filter(o => o.state !== ORDER_STATES.PARTIAL);
846
- await manager.syncFromOpenOrders(activeOrders, { skipAccounting: true });
883
+ await (0, system_1.withBlockchainRetry)(() => manager.syncFromOpenOrders(chainOpenOrders, { skipAccounting: true }), 'syncFromOpenOrders', { logger: manager.logger });
847
884
  manager.resetFunds();
848
885
  await manager.persistGrid();
849
886
  await initializeGrid(manager);
850
887
  const { reconcileGridOrders } = require('./grid_reconcile');
851
- // FIX: Add error context for debugging grid recalculation issues
888
+ // #5: Reconcile grid orders with timeout + retry + node failover
852
889
  try {
853
- await reconcileGridOrders({ manager, config: manager.config, account, privateKey, chainOrders, chainOpenOrders });
890
+ await (0, system_1.withBlockchainRetry)(() => reconcileGridOrders({ manager, config: manager.config, account, privateKey, chainOrders, chainOpenOrders }), 'reconcileGridOrders',
891
+ // 5 min: Phase 2 of reconcile does sequential creates (~3s each);
892
+ // the default 30s timeout would kill mid-batch and cause duplicate-
893
+ // accumulation death spirals. PIPELINE_TIMING.TIMEOUT_MS gives enough
894
+ // headroom for all pending creates+updates to finish in one shot.
895
+ { logger: manager.logger, timeoutMs: constants_1.PIPELINE_TIMING.TIMEOUT_MS });
854
896
  }
855
897
  catch (err) {
856
- manager.logger?.log?.(`Error during startup order reconciliation: ${err.message}`, 'error');
857
- throw new Error(`Grid recalculation failed during order reconciliation: ${err.message}`);
898
+ manager.logger?.log?.(`Error during startup order reconciliation: ${(0, errors_1.getErrorMessage)(err)}`, 'error');
899
+ throw new Error(`Grid recalculation failed during order reconciliation: ${(0, errors_1.getErrorMessage)(err)}`);
858
900
  }
859
- // FIX: Use consistent optional chaining pattern for logger calls
860
901
  manager.logger?.log?.('Full resync complete.', 'info');
902
+ })();
903
+ try {
904
+ // Swallow late rejection if timeout wins the race
905
+ Promise.resolve(work).catch(() => { });
906
+ return await Promise.race([
907
+ work,
908
+ new Promise((_, reject) => {
909
+ setTimeout(() => reject(new Error(`recalculateGrid timed out after ${totalTimeoutMs}ms`)), totalTimeoutMs);
910
+ })
911
+ ]);
861
912
  }
862
913
  finally {
863
914
  manager.finishBootstrap();
@@ -876,13 +927,13 @@ function checkAndUpdateGridIfNeeded(manager) {
876
927
  const gridSell = Number(manager.funds?.total?.grid?.sell || 0);
877
928
  const result = { buyUpdated: false, sellUpdated: false };
878
929
  const sides = [
879
- { name: 'buy', grid: gridBuy, orderType: ORDER_TYPES.BUY },
880
- { name: 'sell', grid: gridSell, orderType: ORDER_TYPES.SELL }
930
+ { name: 'buy', grid: gridBuy, orderType: constants_1.ORDER_TYPES.BUY },
931
+ { name: 'sell', grid: gridSell, orderType: constants_1.ORDER_TYPES.SELL }
881
932
  ];
882
933
  for (const s of sides) {
883
934
  if (s.grid <= 0)
884
935
  continue;
885
- const availableFunds = calculateAvailableFundsValue(s.name, manager.accountTotals, manager.funds, manager.config.assetA, manager.config.assetB, manager.config.activeOrders, manager.config.min_BTS_value, manager.config.feeParams ?? null);
936
+ const availableFunds = (0, math_1.calculateAvailableFundsValue)(s.name, manager.accountTotals, manager.funds, manager.config.assetA, manager.config.assetB, manager.config.activeOrders, manager.config.min_BTS_value, manager.config.feeParams ?? null);
886
937
  // Denominator: side's allocated capital (or chain total fallback).
887
938
  const allocated = s.name === 'buy' ? chainSnap.allocatedBuy : chainSnap.allocatedSell;
888
939
  const denominator = (allocated > 0) ? allocated : (s.grid + availableFunds);
@@ -961,7 +1012,7 @@ async function _recalculateGridOrderSizesFromBlockchain(manager, orderType, opti
961
1012
  return options?.workingGrid ? { actions: [], changed: false } : undefined;
962
1013
  const workingGrid = options?.workingGrid || null;
963
1014
  const collectActions = !!workingGrid;
964
- const isBuy = orderType === ORDER_TYPES.BUY;
1015
+ const isBuy = orderType === constants_1.ORDER_TYPES.BUY;
965
1016
  const sideName = isBuy ? 'buy' : 'sell';
966
1017
  // Use centralized sizing context (respects botFunds % allocation)
967
1018
  const ctx = await _getSizingContext(manager, sideName);
@@ -971,12 +1022,12 @@ async function _recalculateGridOrderSizesFromBlockchain(manager, orderType, opti
971
1022
  // SELL: sorted ASC (Market to Edge)
972
1023
  // BUY: sorted ASC (Edge to Market)
973
1024
  const allSideSlots = Array.from(manager.orders.values())
974
- .filter(o => o.type === orderType)
1025
+ .filter((o) => o.type === orderType)
975
1026
  .sort((a, b) => a.price - b.price);
976
1027
  if (allSideSlots.length === 0)
977
1028
  return collectActions ? { actions: [], changed: false } : undefined;
978
1029
  // Calculate geometric sizes for the ENTIRE rail
979
- const newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, orderType, manager.config, 0, ctx.precision);
1030
+ const newSizes = (0, math_1.calculateRotationOrderSizes)(ctx.budget, 0, allSideSlots.length, orderType, manager.config, 0, ctx.precision);
980
1031
  const actions = [];
981
1032
  let changed = false;
982
1033
  const freeKey = isBuy ? 'buyFree' : 'sellFree';
@@ -995,7 +1046,7 @@ async function _recalculateGridOrderSizesFromBlockchain(manager, orderType, opti
995
1046
  // NOTE: BTS update fees are paid from BTS balance (separate from asset balance),
996
1047
  // so they don't affect this asset-side size cap. Fee budgets are tracked in
997
1048
  // funds.btsFeesOwed and reserved separately via btsFeesReservation.
998
- const isCommitted = isOrderOnChain(slot);
1049
+ const isCommitted = (0, order_1.isOrderOnChain)(slot);
999
1050
  if (isCommitted) {
1000
1051
  const currentSize = Number(slot.size || 0);
1001
1052
  const delta = newSize - currentSize;
@@ -1015,8 +1066,8 @@ async function _recalculateGridOrderSizesFromBlockchain(manager, orderType, opti
1015
1066
  }
1016
1067
  }
1017
1068
  // Use integer comparison to avoid redundant updates from float noise
1018
- const currentSizeInt = floatToBlockchainInt(slot.size || 0, ctx.precision);
1019
- const newSizeInt = floatToBlockchainInt(newSize, ctx.precision);
1069
+ const currentSizeInt = (0, math_1.floatToBlockchainInt)(slot.size || 0, ctx.precision);
1070
+ const newSizeInt = (0, math_1.floatToBlockchainInt)(newSize, ctx.precision);
1020
1071
  if (slot.size === undefined || currentSizeInt !== newSizeInt) {
1021
1072
  changed = true;
1022
1073
  if (collectActions) {
@@ -1024,9 +1075,9 @@ async function _recalculateGridOrderSizesFromBlockchain(manager, orderType, opti
1024
1075
  ...slot,
1025
1076
  size: newSize
1026
1077
  });
1027
- if (isCommitted && hasOnChainId(slot)) {
1078
+ if (isCommitted && (0, order_1.hasOnChainId)(slot)) {
1028
1079
  actions.push({
1029
- type: COW_ACTIONS.UPDATE,
1080
+ type: constants_1.COW_ACTIONS.UPDATE,
1030
1081
  id: slot.id,
1031
1082
  orderId: slot.orderId,
1032
1083
  newGridId: slot.id,
@@ -1083,13 +1134,13 @@ async function updateGridFromBlockchainSnapshot(manager, orderType = 'both', fro
1083
1134
  const allActions = [];
1084
1135
  let hasWorkingChanges = false;
1085
1136
  // Calculate size updates for each side (via existing sizing function in COW mode)
1086
- if (orderType === ORDER_TYPES.BUY || orderType === 'both') {
1087
- const buyResult = await _recalculateGridOrderSizesFromBlockchain(manager, ORDER_TYPES.BUY, { workingGrid });
1137
+ if (orderType === constants_1.ORDER_TYPES.BUY || orderType === 'both') {
1138
+ const buyResult = await _recalculateGridOrderSizesFromBlockchain(manager, constants_1.ORDER_TYPES.BUY, { workingGrid });
1088
1139
  allActions.push(...buyResult.actions);
1089
1140
  hasWorkingChanges = hasWorkingChanges || buyResult.changed;
1090
1141
  }
1091
- if (orderType === ORDER_TYPES.SELL || orderType === 'both') {
1092
- const sellResult = await _recalculateGridOrderSizesFromBlockchain(manager, ORDER_TYPES.SELL, { workingGrid });
1142
+ if (orderType === constants_1.ORDER_TYPES.SELL || orderType === 'both') {
1143
+ const sellResult = await _recalculateGridOrderSizesFromBlockchain(manager, constants_1.ORDER_TYPES.SELL, { workingGrid });
1093
1144
  allActions.push(...sellResult.actions);
1094
1145
  hasWorkingChanges = hasWorkingChanges || sellResult.changed;
1095
1146
  }
@@ -1100,9 +1151,9 @@ async function updateGridFromBlockchainSnapshot(manager, orderType = 'both', fro
1100
1151
  if (overrideBoundaryIdx !== null && overrideBoundaryIdx !== manager.boundaryIdx) {
1101
1152
  const gapSlots = calculateGapSlots(manager.config.incrementPercent, manager.config.targetSpreadPercent, manager.config.gridLimits);
1102
1153
  const allSlots = Array.from(workingGrid.values())
1103
- .filter(s => s.price != null)
1154
+ .filter((s) => s.price != null)
1104
1155
  .sort((a, b) => a.price - b.price);
1105
- const updatedSlots = assignGridRoles(allSlots, newBoundary, gapSlots, ORDER_TYPES, ORDER_STATES);
1156
+ const updatedSlots = (0, order_1.assignGridRoles)(allSlots, newBoundary, gapSlots, constants_1.ORDER_TYPES, constants_1.ORDER_STATES);
1106
1157
  for (const slot of updatedSlots) {
1107
1158
  workingGrid.set(slot.id, slot);
1108
1159
  }
@@ -1173,14 +1224,14 @@ async function compareGrids(calculatedGrid, persistedGrid, manager = null) {
1173
1224
  // they are instead handled by the available-funds ratio check or follow-up correction.
1174
1225
  // Must be sorted ASC for calculateRotationOrderSizes to match geometric weight distribution
1175
1226
  const filterForRms = (orders, type) => {
1176
- const result = Array.isArray(orders) ? orders.filter(o => o && o.type === type && o.state === ORDER_STATES.ACTIVE) : [];
1227
+ const result = Array.isArray(orders) ? orders.filter((o) => o && o.type === type && o.state === constants_1.ORDER_STATES.ACTIVE) : [];
1177
1228
  return result
1178
1229
  .sort((a, b) => (a.price ?? 0) - (b.price ?? 0));
1179
1230
  };
1180
- const calculatedBuys = filterForRms(calculatedSnap, ORDER_TYPES.BUY);
1181
- const calculatedSells = filterForRms(calculatedSnap, ORDER_TYPES.SELL);
1182
- const persistedBuys = filterForRms(persistedSnap, ORDER_TYPES.BUY);
1183
- const persistedSells = filterForRms(persistedSnap, ORDER_TYPES.SELL);
1231
+ const calculatedBuys = filterForRms(calculatedSnap, constants_1.ORDER_TYPES.BUY);
1232
+ const calculatedSells = filterForRms(calculatedSnap, constants_1.ORDER_TYPES.SELL);
1233
+ const persistedBuys = filterForRms(persistedSnap, constants_1.ORDER_TYPES.BUY);
1234
+ const persistedSells = filterForRms(persistedSnap, constants_1.ORDER_TYPES.SELL);
1184
1235
  // Calculate ideal sizes for each order based on current available budget.
1185
1236
  // The sizing context (which includes recalculateFunds) is resolved once per side up front
1186
1237
  // so both buy and sell metrics share a single fund snapshot. This avoids the previous
@@ -1192,18 +1243,18 @@ async function compareGrids(calculatedGrid, persistedGrid, manager = null) {
1192
1243
  // Identify ALL slots currently assigned to this side.
1193
1244
  // Ideal sizing must use the full slot count to determine geometric share per slot.
1194
1245
  const sideSlots = Array.from(manager.orders.values())
1195
- .filter(o => o.type === type)
1246
+ .filter((o) => o.type === type)
1196
1247
  .sort((a, b) => (a.price ?? 0) - (b.price ?? 0));
1197
1248
  if (sideSlots.length === 0)
1198
1249
  return activeOrders;
1199
1250
  // Calculate geometric ideals for the ENTIRE side (all slots)
1200
1251
  try {
1201
- const allIdealSizes = calculateRotationOrderSizes(ctx.budget, 0, sideSlots.length, type, manager.config, 0, ctx.precision);
1252
+ const allIdealSizes = (0, math_1.calculateRotationOrderSizes)(ctx.budget, 0, sideSlots.length, type, manager.config, 0, ctx.precision);
1202
1253
  // Map Ideal sizes to IDs for quick lookup
1203
1254
  const idealMap = new Map();
1204
1255
  sideSlots.forEach((slot, i) => idealMap.set(slot.id, allIdealSizes[i]));
1205
1256
  // Return the activeOrders subset with their true geometric ideal sizes
1206
- return activeOrders.map(o => ({ ...o, size: idealMap.get(o.id) ?? 0 }));
1257
+ return activeOrders.map((o) => ({ ...o, size: idealMap.get(o.id) ?? 0 }));
1207
1258
  }
1208
1259
  catch (e) {
1209
1260
  return activeOrders;
@@ -1220,11 +1271,11 @@ async function compareGrids(calculatedGrid, persistedGrid, manager = null) {
1220
1271
  const sellCtx = needsSell
1221
1272
  ? await _getSizingContext(manager, 'sell', { skipRecalc: true })
1222
1273
  : null;
1223
- const buyIdeals = computeSideIdeals(calculatedBuys, ORDER_TYPES.BUY, buyCtx);
1224
- const sellIdeals = computeSideIdeals(calculatedSells, ORDER_TYPES.SELL, sellCtx);
1274
+ const buyIdeals = computeSideIdeals(calculatedBuys, constants_1.ORDER_TYPES.BUY, buyCtx);
1275
+ const sellIdeals = computeSideIdeals(calculatedSells, constants_1.ORDER_TYPES.SELL, sellCtx);
1225
1276
  // Calculate RMS divergence metric for each side
1226
- const buyMetric = calculateGridSideDivergenceMetric(buyIdeals, persistedBuys, 'buy');
1227
- const sellMetric = calculateGridSideDivergenceMetric(sellIdeals, persistedSells, 'sell');
1277
+ const buyMetric = (0, math_1.calculateGridSideDivergenceMetric)(buyIdeals, persistedBuys, 'buy');
1278
+ const sellMetric = (0, math_1.calculateGridSideDivergenceMetric)(sellIdeals, persistedSells, 'sell');
1228
1279
  // Check if metrics exceed threshold and flag sides for regeneration
1229
1280
  // Set RMS_PERCENTAGE to 0 to disable RMS divergence checks
1230
1281
  let buyUpdated = false, sellUpdated = false;
@@ -1234,14 +1285,14 @@ async function compareGrids(calculatedGrid, persistedGrid, manager = null) {
1234
1285
  // RC-3: Use Set for automatic duplicate prevention
1235
1286
  if (!(manager._gridSidesUpdated instanceof Set))
1236
1287
  manager._gridSidesUpdated = new Set();
1237
- manager._gridSidesUpdated.add(ORDER_TYPES.BUY);
1288
+ manager._gridSidesUpdated.add(constants_1.ORDER_TYPES.BUY);
1238
1289
  buyUpdated = true;
1239
1290
  }
1240
1291
  if (sellMetric > limit) {
1241
1292
  // RC-3: Use Set for automatic duplicate prevention
1242
1293
  if (!(manager._gridSidesUpdated instanceof Set))
1243
1294
  manager._gridSidesUpdated = new Set();
1244
- manager._gridSidesUpdated.add(ORDER_TYPES.SELL);
1295
+ manager._gridSidesUpdated.add(constants_1.ORDER_TYPES.SELL);
1245
1296
  sellUpdated = true;
1246
1297
  }
1247
1298
  }
@@ -1292,13 +1343,13 @@ async function monitorDivergence(manager, calculatedGrid, persistedGrid) {
1292
1343
  */
1293
1344
  function _getOnChainOrders(manager) {
1294
1345
  const onChainBuys = [
1295
- ...manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.ACTIVE),
1296
- ...manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.PARTIAL)
1297
- ].filter(o => o?.orderId && Number(o?.size || 0) > 0);
1346
+ ...manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.BUY, constants_1.ORDER_STATES.ACTIVE),
1347
+ ...manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.BUY, constants_1.ORDER_STATES.PARTIAL)
1348
+ ].filter((o) => o?.orderId && Number(o?.size || 0) > 0);
1298
1349
  const onChainSells = [
1299
- ...manager.getOrdersByTypeAndState(ORDER_TYPES.SELL, ORDER_STATES.ACTIVE),
1300
- ...manager.getOrdersByTypeAndState(ORDER_TYPES.SELL, ORDER_STATES.PARTIAL)
1301
- ].filter(o => o?.orderId && Number(o?.size || 0) > 0);
1350
+ ...manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.SELL, constants_1.ORDER_STATES.ACTIVE),
1351
+ ...manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.SELL, constants_1.ORDER_STATES.PARTIAL)
1352
+ ].filter((o) => o?.orderId && Number(o?.size || 0) > 0);
1302
1353
  return { onChainBuys, onChainSells };
1303
1354
  }
1304
1355
  /**
@@ -1308,7 +1359,7 @@ function _getOnChainOrders(manager) {
1308
1359
  */
1309
1360
  function calculateCurrentSpread(manager) {
1310
1361
  const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
1311
- return calculateSpreadFromOrders(onChainBuys, onChainSells);
1362
+ return (0, math_1.calculateSpreadFromOrders)(onChainBuys, onChainSells);
1312
1363
  }
1313
1364
  /**
1314
1365
  * Proactive spread correction check.
@@ -1333,7 +1384,7 @@ function calculateCurrentSpread(manager) {
1333
1384
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
1334
1385
  * @returns {Promise<import('./types').SpreadCheckResult>}
1335
1386
  */
1336
- async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch = null) {
1387
+ async function checkSpreadCondition(manager, _BitShares, updateOrdersOnChainBatch = null) {
1337
1388
  // CRITICAL: Acquire corrections lock to serialize spread correction operations
1338
1389
  // This prevents concurrent fill processing from modifying funds while we're making decisions
1339
1390
  let correction = null;
@@ -1343,7 +1394,7 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1343
1394
  // Mid between best bid and best ask is the most current price the bot has.
1344
1395
  // Falls back to config.startPrice when either side is empty (e.g. at startup).
1345
1396
  const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
1346
- const { bestBuy, bestSell } = getGridBestPrices(onChainBuys, onChainSells);
1397
+ const { bestBuy, bestSell } = (0, math_1.getGridBestPrices)(onChainBuys, onChainSells);
1347
1398
  const lastPrice = (bestBuy !== null && bestSell !== null)
1348
1399
  ? (bestBuy + bestSell) / 2
1349
1400
  : Number(manager.config.startPrice) || 0;
@@ -1361,18 +1412,18 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1361
1412
  const currentSpread = calculateCurrentSpread(manager);
1362
1413
  // Nominal spread is the configured target spread percentage.
1363
1414
  // Keep this fixed: doubled-side flags are fill/replacement mechanics only.
1364
- const nominalSpread = manager.config.targetSpreadPercent ?? DEFAULT_CONFIG.targetSpreadPercent;
1415
+ const nominalSpread = manager.config.targetSpreadPercent ?? constants_1.DEFAULT_CONFIG.targetSpreadPercent;
1365
1416
  // Fixed tolerance: 0.5 steps = half increment (tighter spread check).
1366
1417
  const toleranceSteps = 0.5;
1367
- const buyCount = manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.ACTIVE)
1368
- .concat(manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.PARTIAL))
1369
- .filter(o => o?.orderId && Number(o?.size || 0) > 0)
1418
+ const buyCount = manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.BUY, constants_1.ORDER_STATES.ACTIVE)
1419
+ .concat(manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.BUY, constants_1.ORDER_STATES.PARTIAL))
1420
+ .filter((o) => o?.orderId && Number(o?.size || 0) > 0)
1370
1421
  .length;
1371
- const sellCount = manager.getOrdersByTypeAndState(ORDER_TYPES.SELL, ORDER_STATES.ACTIVE)
1372
- .concat(manager.getOrdersByTypeAndState(ORDER_TYPES.SELL, ORDER_STATES.PARTIAL))
1373
- .filter(o => o?.orderId && Number(o?.size || 0) > 0)
1422
+ const sellCount = manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.SELL, constants_1.ORDER_STATES.ACTIVE)
1423
+ .concat(manager.getOrdersByTypeAndState(constants_1.ORDER_TYPES.SELL, constants_1.ORDER_STATES.PARTIAL))
1424
+ .filter((o) => o?.orderId && Number(o?.size || 0) > 0)
1374
1425
  .length;
1375
- manager.outOfSpread = shouldFlagOutOfSpread(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
1426
+ manager.outOfSpread = (0, order_1.shouldFlagOutOfSpread)(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
1376
1427
  if (manager.outOfSpread === 0)
1377
1428
  return false;
1378
1429
  // Check whether the empty side is caused by boundary-at-rail-edge.
@@ -1402,7 +1453,7 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1402
1453
  `Requesting structural grid resync to re-center.`, 'warn');
1403
1454
  if (typeof manager.requestStructuralGridResync === 'function') {
1404
1455
  manager.requestStructuralGridResync('boundary-at-rail-edge', { reason: `Boundary ${manager.boundaryIdx} leaves ${buySideCount} buy / ${sellSideCount} sell slots` }).catch((err) => {
1405
- manager.logger?.log?.(`[SPREAD] Structural resync request failed: ${err.message}`, 'error');
1456
+ manager.logger?.log?.(`[SPREAD] Structural resync request failed: ${(0, errors_1.getErrorMessage)(err)}`, 'error');
1406
1457
  });
1407
1458
  }
1408
1459
  }
@@ -1427,7 +1478,7 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1427
1478
  shouldApplyCorrection = await manager._gridLock.acquire(executeSpreadCheck);
1428
1479
  }
1429
1480
  catch (err) {
1430
- manager.logger?.log?.(`Error checking spread condition: ${err.message}`, 'warn');
1481
+ manager.logger?.log?.(`Error checking spread condition: ${(0, errors_1.getErrorMessage)(err)}`, 'warn');
1431
1482
  return { ordersPlaced: 0, partialsMoved: 0 };
1432
1483
  }
1433
1484
  // FIX: Apply blockchain operations OUTSIDE the lock to reduce lock contention
@@ -1444,22 +1495,32 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1444
1495
  // Instead of silently aborting, re-plan with fresh funds so the
1445
1496
  // correction still applies on this cycle. The pre-flight check
1446
1497
  // still guards against placing orders based on stale fund snapshots.
1447
- const decision = determineOrderSideByFunds(manager, lastPrice);
1448
- if (decision.side) {
1449
- correction = await prepareSpreadCorrectionOrders(manager, decision.side);
1450
- if (correction && ((correction.ordersToPlace?.length || 0) + (correction.ordersToUpdate?.length || 0) > 0)) {
1451
- fundSnapshot = currentFunds;
1452
- manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
1453
- `re-planned with updated funds: ${correction.ordersToPlace?.length || 0} creates, ` +
1454
- `${correction.ordersToUpdate?.length || 0} updates`, 'info');
1455
- }
1456
- else {
1457
- manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
1458
- return { ordersPlaced: 0, partialsMoved: 0 };
1459
- }
1498
+ // Re-acquire _gridLock for the re-plan to ensure consistent grid
1499
+ // state (the lock is re-entrant for this call chain — the outer
1500
+ // acquire's callback completed before we reach here, so there is
1501
+ // no nested lock to recurse into). If determineOrderSideByFunds
1502
+ // or prepareSpreadCorrectionOrders grow to hold the lock for
1503
+ // heavy work, hoist the result to avoid serial re-execution.
1504
+ const rePlanResult = await manager._gridLock.acquire(async () => {
1505
+ const decision = determineOrderSideByFunds(manager, lastPrice);
1506
+ if (!decision.side)
1507
+ return { side: false };
1508
+ const c = await prepareSpreadCorrectionOrders(manager, decision.side);
1509
+ return { side: true, correction: c };
1510
+ });
1511
+ if (!rePlanResult.side) {
1512
+ manager.logger?.log?.(`[SPREAD] Fund state changed; no side has sufficient funds for re-plan. Skipping cycle.`, 'warn');
1513
+ return { ordersPlaced: 0, partialsMoved: 0 };
1514
+ }
1515
+ correction = rePlanResult.correction;
1516
+ if (correction && ((correction.ordersToPlace?.length || 0) + (correction.ordersToUpdate?.length || 0) > 0)) {
1517
+ fundSnapshot = currentFunds;
1518
+ manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
1519
+ `re-planned with updated funds: ${correction.ordersToPlace?.length || 0} creates, ` +
1520
+ `${correction.ordersToUpdate?.length || 0} updates`, 'info');
1460
1521
  }
1461
1522
  else {
1462
- manager.logger?.log?.(`[SPREAD] Fund state changed; no side has sufficient funds for re-plan. Skipping cycle.`, 'warn');
1523
+ manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
1463
1524
  return { ordersPlaced: 0, partialsMoved: 0 };
1464
1525
  }
1465
1526
  }
@@ -1475,7 +1536,7 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1475
1536
  return { ordersPlaced: placed + updated, partialsMoved: updated };
1476
1537
  }
1477
1538
  catch (err) {
1478
- manager.logger?.log?.(`Error applying spread correction on-chain: ${err.message}`, 'warn');
1539
+ manager.logger?.log?.(`Error applying spread correction on-chain: ${(0, errors_1.getErrorMessage)(err)}`, 'warn');
1479
1540
  return { ordersPlaced: 0, partialsMoved: 0 };
1480
1541
  }
1481
1542
  }
@@ -1494,7 +1555,7 @@ async function checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch
1494
1555
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function.
1495
1556
  * @returns {Promise<import('./types').DustCheckResult>}
1496
1557
  */
1497
- async function checkGridHealth(manager, updateOrdersOnChainBatch = null) {
1558
+ async function checkGridHealth(manager, _updateOrdersOnChainBatch = null) {
1498
1559
  if (!manager)
1499
1560
  return { buyDust: false, sellDust: false, buyDustOrders: [], sellDustOrders: [] };
1500
1561
  // Skip health checks during bootstrap to prevent spamming warnings
@@ -1529,16 +1590,16 @@ async function checkWindowDust(manager) {
1529
1590
  if (!manager)
1530
1591
  return { buyDust: false, sellDust: false, buyDustOrders: [], sellDustOrders: [] };
1531
1592
  const allOrders = Array.from(manager.orders.values());
1532
- const isLiveOrder = order => order &&
1593
+ const isLiveOrder = (order) => order &&
1533
1594
  order.orderId &&
1534
1595
  order.price != null &&
1535
- (order.state === ORDER_STATES.ACTIVE || order.state === ORDER_STATES.PARTIAL);
1596
+ (order.state === constants_1.ORDER_STATES.ACTIVE || order.state === constants_1.ORDER_STATES.PARTIAL);
1536
1597
  // Identify top-of-window orders (closest to market per side).
1537
1598
  const topBuyOrder = allOrders
1538
- .filter(o => o.type === ORDER_TYPES.BUY && isLiveOrder(o))
1599
+ .filter((o) => o.type === constants_1.ORDER_TYPES.BUY && isLiveOrder(o))
1539
1600
  .sort((a, b) => b.price - a.price)[0];
1540
1601
  const topSellOrder = allOrders
1541
- .filter(o => o.type === ORDER_TYPES.SELL && isLiveOrder(o))
1602
+ .filter((o) => o.type === constants_1.ORDER_TYPES.SELL && isLiveOrder(o))
1542
1603
  .sort((a, b) => a.price - b.price)[0];
1543
1604
  // Check if an order has a duplicate price level — an active sibling at the
1544
1605
  // same price within tolerance. If so, cancelling won't create a grid gap.
@@ -1546,25 +1607,17 @@ async function checkWindowDust(manager) {
1546
1607
  // sibling, neither qualifies and the gap is left to the rebalancer.
1547
1608
  // Uses the LARGER size of the two orders for tolerance calculation to prevent
1548
1609
  // a tiny dust order from inflating the tolerance window.
1549
- const hasDuplicatePriceLevel = (order, assets) => allOrders.some(o => {
1550
- if (o.id === order.id || o.type !== order.type)
1551
- return false;
1552
- if (o.state !== ORDER_STATES.ACTIVE || !o.orderId || o.price == null)
1553
- return false;
1554
- const toleranceSize = Math.max(order.size, o.size);
1555
- const tolerance = calculatePriceTolerance(Math.min(order.price, o.price), toleranceSize, order.type, assets);
1556
- return tolerance != null && Math.abs(o.price - order.price) <= tolerance;
1557
- });
1610
+ const hasDuplicatePriceLevel = (order, assets) => (0, math_1.findPriceCollision)(allOrders, order.id, order.price, order.size, order.type, assets, (o) => o.type === order.type && o.state === constants_1.ORDER_STATES.ACTIVE && !!o.orderId && o.price != null) != null;
1558
1611
  const assets = manager.assets;
1559
- const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === ORDER_STATES.PARTIAL);
1612
+ const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === constants_1.ORDER_STATES.PARTIAL);
1560
1613
  const isTopBuy = (o) => topBuyOrder && o.id === topBuyOrder.id;
1561
1614
  const isTopSell = (o) => topSellOrder && o.id === topSellOrder.id;
1562
1615
  // Safety filter: top-of-window partials always qualify; interior partials
1563
1616
  // only qualify if they have a duplicate price level (no gap risk).
1564
- const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o, assets)));
1565
- const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o, assets)));
1566
- const buyDustOrders = await _getDustOrders(manager, eligibleBuyPartials, ORDER_TYPES.BUY);
1567
- const sellDustOrders = await _getDustOrders(manager, eligibleSellPartials, ORDER_TYPES.SELL);
1617
+ const eligibleBuyPartials = allPartials.filter((o) => o.type === constants_1.ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o, assets)));
1618
+ const eligibleSellPartials = allPartials.filter((o) => o.type === constants_1.ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o, assets)));
1619
+ const buyDustOrders = await _getDustOrders(manager, eligibleBuyPartials, constants_1.ORDER_TYPES.BUY);
1620
+ const sellDustOrders = await _getDustOrders(manager, eligibleSellPartials, constants_1.ORDER_TYPES.SELL);
1568
1621
  return {
1569
1622
  buyDust: buyDustOrders.length > 0,
1570
1623
  sellDust: sellDustOrders.length > 0,
@@ -1585,27 +1638,27 @@ async function checkWindowDust(manager) {
1585
1638
  async function _getDustOrders(manager, partials, type) {
1586
1639
  if (!partials || partials.length === 0)
1587
1640
  return [];
1588
- const side = type === ORDER_TYPES.BUY ? 'buy' : 'sell';
1641
+ const side = type === constants_1.ORDER_TYPES.BUY ? 'buy' : 'sell';
1589
1642
  const ctx = await _getSizingContext(manager, side);
1590
1643
  const dustThresholdPercent = manager.config?.gridLimits?.PARTIAL_DUST_THRESHOLD_PERCENTAGE;
1591
1644
  const sideSlots = Array.from(manager.orders.values())
1592
- .filter(o => o.type === type)
1645
+ .filter((o) => o.type === type)
1593
1646
  .sort((a, b) => a.price - b.price);
1594
1647
  if (sideSlots.length === 0)
1595
1648
  return [];
1596
1649
  const idealSizes = ctx && ctx.budget > 0
1597
- ? allocateFundsByWeights(ctx.budget, sideSlots.length, manager.config.weightDistribution[side], manager.config.incrementPercent / 100, type === ORDER_TYPES.BUY, 0, ctx.precision)
1650
+ ? (0, math_1.allocateFundsByWeights)(ctx.budget, sideSlots.length, manager.config.weightDistribution[side], manager.config.incrementPercent / 100, type === constants_1.ORDER_TYPES.BUY, 0, ctx.precision)
1598
1651
  : [];
1599
1652
  // When no budget is available, idealSizes becomes [] so every
1600
1653
  // partial's threshold collapses to 0 — no order qualifies as dust.
1601
1654
  // We still run the filter for uniformity so the threshold logic
1602
1655
  // stays consistent regardless of budget state.
1603
- return partials.filter(p => {
1604
- const idx = sideSlots.findIndex(s => s.id === p.id);
1656
+ return partials.filter((p) => {
1657
+ const idx = sideSlots.findIndex((s) => s.id === p.id);
1605
1658
  if (idx === -1)
1606
1659
  return false;
1607
1660
  const threshold = idealSizes.length > idx && idealSizes[idx] > 0
1608
- ? getSingleDustThreshold(idealSizes[idx], dustThresholdPercent)
1661
+ ? (0, math_1.getSingleDustThreshold)(idealSizes[idx], dustThresholdPercent)
1609
1662
  : 0;
1610
1663
  return p.size < threshold;
1611
1664
  });
@@ -1629,7 +1682,7 @@ async function _hasAnyDust(manager, partials, type) {
1629
1682
  * @returns {Promise<boolean>}
1630
1683
  */
1631
1684
  async function hasAnyDust(manager, partials, side) {
1632
- const type = side === 'buy' ? ORDER_TYPES.BUY : side === 'sell' ? ORDER_TYPES.SELL : null;
1685
+ const type = side === 'buy' ? constants_1.ORDER_TYPES.BUY : side === 'sell' ? constants_1.ORDER_TYPES.SELL : null;
1633
1686
  if (!type)
1634
1687
  return false;
1635
1688
  return await _hasAnyDust(manager, partials, type);
@@ -1643,7 +1696,7 @@ async function hasAnyDust(manager, partials, side) {
1643
1696
  * @returns {Promise<Array<import('./types').GridOrderSlot>>}
1644
1697
  */
1645
1698
  async function getDustOrders(manager, partials, side) {
1646
- const type = side === 'buy' ? ORDER_TYPES.BUY : side === 'sell' ? ORDER_TYPES.SELL : null;
1699
+ const type = side === 'buy' ? constants_1.ORDER_TYPES.BUY : side === 'sell' ? constants_1.ORDER_TYPES.SELL : null;
1647
1700
  if (!type)
1648
1701
  return [];
1649
1702
  return await _getDustOrders(manager, partials, type);
@@ -1677,13 +1730,35 @@ function determineOrderSideByFunds(manager, currentMarketPrice) {
1677
1730
  const sellInBuyUnits = (Number.isFinite(marketPrice) && marketPrice > 0)
1678
1731
  ? sellAvailable * marketPrice
1679
1732
  : sellAvailable;
1680
- side = buyAvailable >= sellInBuyUnits ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
1733
+ // Determine market direction from current price vs grid center price.
1734
+ // When the market is below the grid center, the bot should prefer SELL
1735
+ // (to narrow the spread from above — sells are too high). When the market
1736
+ // is above the grid center, prefer BUY (buys are too low). This prevents
1737
+ // spread correction from placing orders on the retreating side, which would
1738
+ // compound inventory in the wrong direction after a batch of fill-induced
1739
+ // boundary shifts.
1740
+ const centerPrice = manager._lastGridPricingContext?.startPrice
1741
+ ?? Number(manager.config.startPrice)
1742
+ ?? null;
1743
+ const hasDirection = Number.isFinite(marketPrice)
1744
+ && marketPrice > 0
1745
+ && Number.isFinite(centerPrice)
1746
+ && centerPrice > 0;
1747
+ if (hasDirection && marketPrice < centerPrice) {
1748
+ side = constants_1.ORDER_TYPES.SELL;
1749
+ }
1750
+ else if (hasDirection && marketPrice > centerPrice) {
1751
+ side = constants_1.ORDER_TYPES.BUY;
1752
+ }
1753
+ else {
1754
+ side = buyAvailable >= sellInBuyUnits ? constants_1.ORDER_TYPES.BUY : constants_1.ORDER_TYPES.SELL;
1755
+ }
1681
1756
  }
1682
1757
  else if (buyViable) {
1683
- side = ORDER_TYPES.BUY;
1758
+ side = constants_1.ORDER_TYPES.BUY;
1684
1759
  }
1685
1760
  else if (sellViable) {
1686
- side = ORDER_TYPES.SELL;
1761
+ side = constants_1.ORDER_TYPES.SELL;
1687
1762
  }
1688
1763
  if (!side) {
1689
1764
  const committedBuy = Math.max(0, Number(manager.funds?.committed?.chain?.buy || 0));
@@ -1694,17 +1769,17 @@ function determineOrderSideByFunds(manager, currentMarketPrice) {
1694
1769
  if (hasValidPrice) {
1695
1770
  const buyComparable = committedBuy;
1696
1771
  const sellComparable = committedSell * marketPrice;
1697
- side = buyComparable >= sellComparable ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
1772
+ side = buyComparable >= sellComparable ? constants_1.ORDER_TYPES.BUY : constants_1.ORDER_TYPES.SELL;
1698
1773
  }
1699
1774
  else if (committedBuy > buyMinUnit && committedSell <= sellMinUnit) {
1700
- side = ORDER_TYPES.BUY;
1775
+ side = constants_1.ORDER_TYPES.BUY;
1701
1776
  }
1702
1777
  else if (committedSell > sellMinUnit && committedBuy <= buyMinUnit) {
1703
- side = ORDER_TYPES.SELL;
1778
+ side = constants_1.ORDER_TYPES.SELL;
1704
1779
  }
1705
1780
  else {
1706
1781
  // Deterministic fallback when both sides hold inventory but market valuation is unavailable.
1707
- side = ORDER_TYPES.BUY;
1782
+ side = constants_1.ORDER_TYPES.BUY;
1708
1783
  }
1709
1784
  manager.logger?.log?.(`Spread correction using redistribution fallback on ${side} ` +
1710
1785
  `(free buy=${Format.formatAmount8(buyAvailable)}, free sell=${Format.formatAmount8(sellAvailable)}, ` +
@@ -1724,13 +1799,13 @@ function determineOrderSideByFunds(manager, currentMarketPrice) {
1724
1799
  * @returns {Promise<number|null>} The calculated geometric size.
1725
1800
  */
1726
1801
  async function calculateGeometricSizeForSpreadCorrection(manager, targetType) {
1727
- const side = targetType === ORDER_TYPES.BUY ? 'buy' : 'sell';
1802
+ const side = targetType === constants_1.ORDER_TYPES.BUY ? 'buy' : 'sell';
1728
1803
  // Count only on-chain orders (ACTIVE+PARTIAL) to avoid diluting the
1729
1804
  // spread-correction order size across hundreds of virtual slots on a
1730
1805
  // full-rail grid. Virtual slots have their capital tracked separately
1731
1806
  // in funds.virtual and should not compete for the free budget.
1732
1807
  const slotsCount = Array.from(manager.orders.values())
1733
- .filter(o => o.type === targetType && (o.state === ORDER_STATES.ACTIVE || o.state === ORDER_STATES.PARTIAL))
1808
+ .filter((o) => o.type === targetType && (o.state === constants_1.ORDER_STATES.ACTIVE || o.state === constants_1.ORDER_STATES.PARTIAL))
1734
1809
  .length + 1;
1735
1810
  // Use centralized sizing context (respects botFunds % allocation)
1736
1811
  const ctx = await _getSizingContext(manager, side);
@@ -1739,7 +1814,7 @@ async function calculateGeometricSizeForSpreadCorrection(manager, targetType) {
1739
1814
  // ALLOW slotsCount === 1 to enable spread correction even if a side is completely missing
1740
1815
  const dummy = Array.from({ length: slotsCount }, () => ({ type: targetType }));
1741
1816
  try {
1742
- const sized = calculateOrderSizes(dummy, manager.config, side === 'sell' ? ctx.budget : 0, side === 'buy' ? ctx.budget : 0, 0, 0, ctx.precision, ctx.precision);
1817
+ const sized = (0, math_1.calculateOrderSizes)(dummy, manager.config, side === 'sell' ? ctx.budget : 0, side === 'buy' ? ctx.budget : 0, 0, 0, ctx.precision, ctx.precision);
1743
1818
  if (!Array.isArray(sized) || sized.length === 0) {
1744
1819
  manager.logger?.log?.(`calculateOrderSizes returned invalid result for spread correction`, 'warn');
1745
1820
  return null;
@@ -1747,7 +1822,7 @@ async function calculateGeometricSizeForSpreadCorrection(manager, targetType) {
1747
1822
  return side === 'sell' ? sized[0].size : sized[sized.length - 1].size;
1748
1823
  }
1749
1824
  catch (e) {
1750
- manager.logger?.log?.(`Error calculating geometric size for spread correction: ${e.message}`, 'warn');
1825
+ manager.logger?.log?.(`Error calculating geometric size for spread correction: ${(0, errors_1.getErrorMessage)(e)}`, 'warn');
1751
1826
  return null;
1752
1827
  }
1753
1828
  }
@@ -1760,13 +1835,13 @@ async function calculateGeometricSizeForSpreadCorrection(manager, targetType) {
1760
1835
  */
1761
1836
  async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1762
1837
  // FIX: Validate preferredSide parameter to prevent silent logic errors
1763
- if (preferredSide !== ORDER_TYPES.BUY && preferredSide !== ORDER_TYPES.SELL) {
1764
- throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${ORDER_TYPES.BUY}' or '${ORDER_TYPES.SELL}'.`);
1838
+ if (preferredSide !== constants_1.ORDER_TYPES.BUY && preferredSide !== constants_1.ORDER_TYPES.SELL) {
1839
+ throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${constants_1.ORDER_TYPES.BUY}' or '${constants_1.ORDER_TYPES.SELL}'.`);
1765
1840
  }
1766
1841
  const ordersToPlace = [];
1767
1842
  const ordersToUpdate = [];
1768
1843
  const railType = preferredSide;
1769
- const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
1844
+ const sideName = railType === constants_1.ORDER_TYPES.BUY ? 'buy' : 'sell';
1770
1845
  const configuredMissingSlots = Number(manager.outOfSpread || 0);
1771
1846
  const missingSlots = configuredMissingSlots > 0
1772
1847
  ? Math.floor(configuredMissingSlots)
@@ -1779,31 +1854,90 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1779
1854
  const allOrders = Array.from(manager.orders.values());
1780
1855
  let edgePartial = null;
1781
1856
  const partials = allOrders
1782
- .filter(o => o.type === railType && o.state === ORDER_STATES.PARTIAL)
1783
- .sort((a, b) => railType === ORDER_TYPES.BUY ? b.price - a.price : a.price - b.price);
1857
+ .filter((o) => o.type === railType && o.state === constants_1.ORDER_STATES.PARTIAL)
1858
+ .sort((a, b) => railType === constants_1.ORDER_TYPES.BUY ? b.price - a.price : a.price - b.price);
1784
1859
  if (partials.length > 0) {
1785
1860
  edgePartial = partials[0];
1786
1861
  manager.logger?.log?.(`[SPREAD-CORRECTION] Identified partial order at ${edgePartial.price} for update`, 'debug');
1787
1862
  }
1788
- // Primary candidates: SPREAD-type slots adjacent to the gap.
1863
+ // Boundary-correct type computation. Used by both candidate pools below to ensure
1864
+ // spread correction does not re-activate slots whose current boundary position
1865
+ // places them on the wrong side or in the spread zone — doing so would compound
1866
+ // inventory at prices where the bot already traded.
1867
+ //
1868
+ // The natural type of a slot is derived from its position in the price-sorted rail
1869
+ // relative to boundaryIdx + gapSlots: indices in [0, boundaryIdx] are BUY, indices
1870
+ // in [boundaryIdx + gapSlots + 1, N-1] are SELL, the middle band is SPREAD.
1871
+ const allSlotsByPrice = allOrders
1872
+ .filter((o) => o.price != null && Number.isFinite(o.price))
1873
+ .sort((a, b) => a.price - b.price);
1874
+ const slotIndexMap = new Map(allSlotsByPrice.map((o, i) => [o.id, i]));
1875
+ const gapSlots = calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
1876
+ const bIdx = manager.boundaryIdx ?? 0;
1877
+ const buyEndIdx = bIdx;
1878
+ const sellStartIdx = bIdx + Number(gapSlots) + 1;
1879
+ const getSlotCorrectType = (slot) => {
1880
+ const idx = slotIndexMap.get(slot.id);
1881
+ if (idx === undefined)
1882
+ return slot.type;
1883
+ if (idx <= buyEndIdx)
1884
+ return constants_1.ORDER_TYPES.BUY;
1885
+ if (idx >= sellStartIdx)
1886
+ return constants_1.ORDER_TYPES.SELL;
1887
+ return constants_1.ORDER_TYPES.SPREAD;
1888
+ };
1889
+ // Primary candidates: SPREAD-type slots adjacent to the gap. Filter by
1890
+ // boundary-correct type so a SPREAD slot that, after a boundary shift, now sits
1891
+ // in the BUY or SELL zone is excluded — it would otherwise be placed on the
1892
+ // correction side at a price the grid already considers the opposite side.
1789
1893
  const typedSpreadCandidates = allOrders
1790
- .filter(o => o.type === ORDER_TYPES.SPREAD && isSlotAvailable(o))
1791
- .sort((a, b) => railType === ORDER_TYPES.BUY ? a.price - b.price : b.price - a.price)
1894
+ .filter((o) => o.type === constants_1.ORDER_TYPES.SPREAD
1895
+ && (0, order_1.isSlotAvailable)(o)
1896
+ && getSlotCorrectType(o) === railType)
1897
+ .sort((a, b) => railType === constants_1.ORDER_TYPES.BUY ? a.price - b.price : b.price - a.price)
1792
1898
  .slice(0, missingSlots);
1793
1899
  // Secondary candidates: orphaned virtual slots of the correct side-type that have
1794
1900
  // lost their order (e.g. stale-cleaned after a race condition during a crash).
1795
1901
  // These sit inside the active window and are invisible to the SPREAD-type filter above.
1902
+ //
1903
+ // IMPORTANT: Filter by boundary-correct type so that filled-then-virtualized slots
1904
+ // whose boundary position has moved into the spread or opposite zone are NOT
1905
+ // re-activated on the stale side — doing so would compound inventory at prices
1906
+ // where the bot already traded. The boundary-correct type is computed from the
1907
+ // current boundary index and the slot's price position in the sorted rail.
1796
1908
  const orphanedVirtualCandidates = allOrders
1797
- .filter(o => o.type === railType && o.state === ORDER_STATES.VIRTUAL && !o.orderId && Number(o.size || 0) === 0)
1798
- .sort((a, b) => railType === ORDER_TYPES.BUY ? b.price - a.price : a.price - b.price)
1909
+ .filter((o) => o.type === railType
1910
+ && o.state === constants_1.ORDER_STATES.VIRTUAL
1911
+ && !o.orderId
1912
+ && Number(o.size || 0) === 0
1913
+ && getSlotCorrectType(o) === railType)
1914
+ .sort((a, b) => railType === constants_1.ORDER_TYPES.BUY ? b.price - a.price : a.price - b.price)
1799
1915
  .slice(0, missingSlots);
1800
1916
  // Merge: prefer orphaned virtuals (they already occupy correct grid positions) then
1801
1917
  // fall back to SPREAD slots for any remaining quota.
1802
1918
  const remainingQuota = Math.max(0, missingSlots - orphanedVirtualCandidates.length);
1803
- const spreadCandidates = [
1919
+ let spreadCandidates = [
1804
1920
  ...orphanedVirtualCandidates,
1805
1921
  ...typedSpreadCandidates.slice(0, remainingQuota)
1806
1922
  ];
1923
+ // P2: Filter out candidates whose price already has a placed order from any slot.
1924
+ // This prevents creating a duplicate order at the same price when a prior cycle's
1925
+ // order was not properly cleaned up (e.g. uncertain broadcast).
1926
+ if (spreadCandidates.length > 0) {
1927
+ const preFilter = spreadCandidates.length;
1928
+ spreadCandidates = spreadCandidates.filter((c) => {
1929
+ if (c.price == null)
1930
+ return false;
1931
+ // Resolve candidate size: if zero/missing, use minimum so tolerance
1932
+ // doesn't collapse to zero (calculatePriceTolerance returns null for size <= 0).
1933
+ const cs = (c.size && c.size > 0) ? c.size : (0, math_1.getMinAbsoluteOrderSize)(railType, manager.assets);
1934
+ return !(0, math_1.findPriceCollision)(allOrders, c.id, c.price, cs, railType, manager.assets, (o) => (0, order_1.isOrderPlaced)(o) && o.price != null);
1935
+ });
1936
+ const filteredCount = preFilter - spreadCandidates.length;
1937
+ if (filteredCount > 0) {
1938
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Filtered ${filteredCount}/${preFilter} candidate(s) with duplicate price levels`, 'warn');
1939
+ }
1940
+ }
1807
1941
  if (spreadCandidates.length > 0) {
1808
1942
  manager.logger?.log?.(`[SPREAD-CORRECTION] Identified ${spreadCandidates.length}/${missingSlots} slot(s) for activation on ${sideName} (orphaned=${orphanedVirtualCandidates.length}, spread=${spreadCandidates.length - orphanedVirtualCandidates.length})`, 'debug');
1809
1943
  }
@@ -1811,26 +1945,26 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1811
1945
  manager.logger?.log?.(`[SPREAD-CORRECTION] No suitable partials, orphaned virtual slots, or spread slots found. Skipping.`, 'warn');
1812
1946
  return { ordersToPlace: [], ordersToUpdate: [] };
1813
1947
  }
1814
- const orphanedIds = new Set(orphanedVirtualCandidates.map(o => o.id));
1948
+ const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
1815
1949
  const sideSlots = allOrders
1816
- .filter(o => o.type === railType && !orphanedIds.has(o.id))
1950
+ .filter((o) => o.type === railType && !orphanedIds.has(o.id))
1817
1951
  .sort((a, b) => a.price - b.price);
1818
1952
  const syntheticSideSlots = [
1819
1953
  ...sideSlots,
1820
- ...spreadCandidates.map(slot => ({ ...slot, type: railType }))
1954
+ ...spreadCandidates.map((slot) => ({ ...slot, type: railType }))
1821
1955
  ].sort((a, b) => a.price - b.price);
1822
1956
  const ctx = await _getSizingContext(manager, sideName);
1823
1957
  if (!ctx || ctx.budget <= 0 || syntheticSideSlots.length === 0) {
1824
1958
  return { ordersToPlace: [], ordersToUpdate: [] };
1825
1959
  }
1826
- const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
1827
- const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, manager.config.weightDistribution[sideName], manager.config.incrementPercent / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
1960
+ const precisionEpsilon = (0, math_1.getPrecisionSlack)(ctx.precision, 1);
1961
+ const idealSizes = (0, math_1.allocateFundsByWeights)(ctx.budget, syntheticSideSlots.length, manager.config.weightDistribution[sideName], manager.config.incrementPercent / 100, railType === constants_1.ORDER_TYPES.BUY, 0, ctx.precision);
1828
1962
  const idealById = new Map();
1829
1963
  syntheticSideSlots.forEach((slot, idx) => {
1830
1964
  idealById.set(slot.id, Number(idealSizes[idx] || 0));
1831
1965
  });
1832
1966
  const availableFund = Math.max(0, Math.min(Number(manager.funds?.available?.[sideName] || 0), Number(sideName === 'buy' ? manager.accountTotals?.buyFree : manager.accountTotals?.sellFree) || 0));
1833
- const minAbsoluteSize = getMinAbsoluteOrderSize(railType, manager.assets);
1967
+ const minAbsoluteSize = (0, math_1.getMinAbsoluteOrderSize)(railType, manager.assets);
1834
1968
  const prioritizedTargets = [];
1835
1969
  if (edgePartial && edgePartial.id) {
1836
1970
  const ideal = Number(idealById.get(edgePartial.id) || 0);
@@ -1866,9 +2000,9 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1866
2000
  if (totalNeeded > availableFund + precisionEpsilon) {
1867
2001
  let shortfall = totalNeeded - availableFund;
1868
2002
  const donors = sideSlots
1869
- .filter(o => hasOnChainId(o) && (o.state === ORDER_STATES.ACTIVE || o.state === ORDER_STATES.PARTIAL))
1870
- .filter(o => !edgePartial || o.id !== edgePartial.id)
1871
- .sort((a, b) => railType === ORDER_TYPES.BUY ? a.price - b.price : b.price - a.price);
2003
+ .filter((o) => (0, order_1.hasOnChainId)(o) && (o.state === constants_1.ORDER_STATES.ACTIVE || o.state === constants_1.ORDER_STATES.PARTIAL))
2004
+ .filter((o) => !edgePartial || o.id !== edgePartial.id)
2005
+ .sort((a, b) => railType === constants_1.ORDER_TYPES.BUY ? a.price - b.price : b.price - a.price);
1872
2006
  for (const donor of donors) {
1873
2007
  if (shortfall <= precisionEpsilon)
1874
2008
  break;
@@ -1882,7 +2016,7 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1882
2016
  const donorNext = donorCurrent - reduction;
1883
2017
  if (donorNext <= precisionEpsilon)
1884
2018
  continue;
1885
- if (!isOrderHealthy(donorNext, railType, manager.assets, donorIdeal || donorNext))
2019
+ if (!(0, order_1.isOrderHealthy)(donorNext, railType, manager.assets, donorIdeal || donorNext))
1886
2020
  continue;
1887
2021
  redistributionUpdates.push({ partialOrder: { ...donor }, newSize: donorNext });
1888
2022
  recoveredBudget += reduction;
@@ -1899,7 +2033,7 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1899
2033
  if (target.kind === 'partial-topup') {
1900
2034
  const topUp = Math.min(target.needed, remainingBudget);
1901
2035
  const newSize = target.current + topUp;
1902
- if (newSize > target.current + precisionEpsilon && isOrderHealthy(newSize, railType, manager.assets, target.ideal)) {
2036
+ if (newSize > target.current + precisionEpsilon && (0, order_1.isOrderHealthy)(newSize, railType, manager.assets, target.ideal)) {
1903
2037
  ordersToUpdate.push({ partialOrder: { ...target.order }, newSize });
1904
2038
  remainingBudget -= topUp;
1905
2039
  }
@@ -1908,13 +2042,13 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1908
2042
  const createSize = Math.min(target.ideal, remainingBudget);
1909
2043
  if (createSize <= precisionEpsilon)
1910
2044
  continue;
1911
- if (!isOrderHealthy(createSize, railType, manager.assets, target.ideal))
2045
+ if (!(0, order_1.isOrderHealthy)(createSize, railType, manager.assets, target.ideal))
1912
2046
  continue;
1913
2047
  ordersToPlace.push({
1914
2048
  ...target.order,
1915
2049
  type: railType,
1916
2050
  size: createSize,
1917
- state: ORDER_STATES.VIRTUAL
2051
+ state: constants_1.ORDER_STATES.VIRTUAL
1918
2052
  });
1919
2053
  remainingBudget -= createSize;
1920
2054
  }
@@ -1923,7 +2057,7 @@ async function prepareSpreadCorrectionOrders(manager, preferredSide) {
1923
2057
  const id = plannedUpdate?.partialOrder?.id || plannedUpdate?.id;
1924
2058
  if (!id)
1925
2059
  continue;
1926
- const existingIdx = combinedUpdates.findIndex(u => (u?.partialOrder?.id || u?.id) === id);
2060
+ const existingIdx = combinedUpdates.findIndex((u) => (u?.partialOrder?.id || u?.id) === id);
1927
2061
  if (existingIdx >= 0) {
1928
2062
  combinedUpdates[existingIdx] = plannedUpdate;
1929
2063
  }