dexbot 1.6.4 → 1.6.6

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 (240) hide show
  1. package/CHANGELOG.md +75 -3
  2. package/README.md +109 -40
  3. package/analysis/README.md +19 -17
  4. package/analysis/account_resolver.ts +1 -11
  5. package/analysis/analyze_dynamic_weight.ts +9 -3
  6. package/analysis/bot_usage/kibana_bot_queries.ts +1 -1
  7. package/analysis/chain_pool.ts +1 -1
  8. package/analysis/fills_source.ts +0 -6
  9. package/analysis/grid_correction_check.ts +20 -26
  10. package/analysis/resolve_source.ts +1 -1
  11. package/analysis/trade_profitability.ts +2 -5
  12. package/analysis/tradingview/analyze_tradingview.ts +5 -0
  13. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +2 -2
  14. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +35 -2
  15. package/analysis/trend_detection/README.md +1 -3
  16. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +82 -10
  17. package/analysis/trend_detection/package.json +1 -1
  18. package/claw/modules/dexbot_profiles.ts +4 -3
  19. package/claw/package.json +1 -1
  20. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  21. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  22. package/claw/tests/test_claw_mcp_transport.ts +2 -2
  23. package/claw/tests/test_dexbot_profiles.ts +18 -1
  24. package/dist/analysis/account_resolver.d.ts +1 -4
  25. package/dist/analysis/account_resolver.d.ts.map +1 -1
  26. package/dist/analysis/account_resolver.js +1 -1
  27. package/dist/analysis/account_resolver.js.map +1 -1
  28. package/dist/analysis/analyze_dynamic_weight.js +9 -3
  29. package/dist/analysis/analyze_dynamic_weight.js.map +1 -1
  30. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -2
  31. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +1 -1
  32. package/dist/analysis/bot_usage/kibana_bot_queries.js +1 -1
  33. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +1 -1
  34. package/dist/analysis/chain_pool.d.ts +1 -3
  35. package/dist/analysis/chain_pool.d.ts.map +1 -1
  36. package/dist/analysis/chain_pool.js +1 -1
  37. package/dist/analysis/chain_pool.js.map +1 -1
  38. package/dist/analysis/fills_source.d.ts +1 -51
  39. package/dist/analysis/fills_source.d.ts.map +1 -1
  40. package/dist/analysis/fills_source.js +1 -1
  41. package/dist/analysis/fills_source.js.map +1 -1
  42. package/dist/analysis/grid_correction_check.d.ts +2 -3
  43. package/dist/analysis/grid_correction_check.d.ts.map +1 -1
  44. package/dist/analysis/grid_correction_check.js +18 -26
  45. package/dist/analysis/grid_correction_check.js.map +1 -1
  46. package/dist/analysis/resolve_source.d.ts +1 -1
  47. package/dist/analysis/resolve_source.d.ts.map +1 -1
  48. package/dist/analysis/trade_profitability.d.ts.map +1 -1
  49. package/dist/analysis/trade_profitability.js +2 -7
  50. package/dist/analysis/trade_profitability.js.map +1 -1
  51. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +1 -1
  52. package/dist/analysis/tradingview/analyze_tradingview.js +5 -0
  53. package/dist/analysis/tradingview/analyze_tradingview.js.map +1 -1
  54. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -2
  55. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -1
  56. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +82 -10
  57. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -1
  58. package/dist/dexbot.d.ts.map +1 -1
  59. package/dist/dexbot.js +85 -140
  60. package/dist/dexbot.js.map +1 -1
  61. package/dist/market_adapter/core/asymmetric_bounds.d.ts +2 -2
  62. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +1 -1
  63. package/dist/market_adapter/core/asymmetric_bounds.js +15 -12
  64. package/dist/market_adapter/core/asymmetric_bounds.js.map +1 -1
  65. package/dist/market_adapter/core/kibana_candles.d.ts +1 -15
  66. package/dist/market_adapter/core/kibana_candles.d.ts.map +1 -1
  67. package/dist/market_adapter/core/kibana_candles.js +1 -1
  68. package/dist/market_adapter/core/kibana_candles.js.map +1 -1
  69. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +1 -35
  70. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +1 -1
  71. package/dist/market_adapter/inputs/fetch_lp_data.js +10 -54
  72. package/dist/market_adapter/inputs/fetch_lp_data.js.map +1 -1
  73. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +1 -8
  74. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +1 -1
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +1 -1
  76. package/dist/market_adapter/inputs/kibana_feed_source.js.map +1 -1
  77. package/dist/market_adapter/inputs/window_cache.d.ts +2 -63
  78. package/dist/market_adapter/inputs/window_cache.d.ts.map +1 -1
  79. package/dist/market_adapter/inputs/window_cache.js +22 -102
  80. package/dist/market_adapter/inputs/window_cache.js.map +1 -1
  81. package/dist/market_adapter/interval_utils.d.ts +1 -1
  82. package/dist/market_adapter/interval_utils.js +1 -1
  83. package/dist/modules/account_bots.d.ts +70 -6
  84. package/dist/modules/account_bots.d.ts.map +1 -1
  85. package/dist/modules/account_bots.js +353 -149
  86. package/dist/modules/account_bots.js.map +1 -1
  87. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +1 -1
  88. package/dist/modules/bitshares-native/crypto/ecc.browser.js +0 -31
  89. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +1 -1
  90. package/dist/modules/bot_defaults.d.ts +98 -0
  91. package/dist/modules/bot_defaults.d.ts.map +1 -0
  92. package/dist/modules/bot_defaults.js +169 -0
  93. package/dist/modules/bot_defaults.js.map +1 -0
  94. package/dist/modules/bot_settings.d.ts.map +1 -1
  95. package/dist/modules/bot_settings.js +4 -1
  96. package/dist/modules/bot_settings.js.map +1 -1
  97. package/dist/modules/config.d.ts +1 -0
  98. package/dist/modules/config.d.ts.map +1 -1
  99. package/dist/modules/config.js +1 -0
  100. package/dist/modules/config.js.map +1 -1
  101. package/dist/modules/constants.d.ts +11 -2
  102. package/dist/modules/constants.d.ts.map +1 -1
  103. package/dist/modules/constants.js +40 -27
  104. package/dist/modules/constants.js.map +1 -1
  105. package/dist/modules/credit_runtime.d.ts +0 -2
  106. package/dist/modules/credit_runtime.d.ts.map +1 -1
  107. package/dist/modules/credit_runtime.js +1 -10
  108. package/dist/modules/credit_runtime.js.map +1 -1
  109. package/dist/modules/dexbot_class.d.ts +13 -10
  110. package/dist/modules/dexbot_class.d.ts.map +1 -1
  111. package/dist/modules/dexbot_class.js +0 -9
  112. package/dist/modules/dexbot_class.js.map +1 -1
  113. package/dist/modules/dexbot_cow_runtime.d.ts +13 -0
  114. package/dist/modules/dexbot_cow_runtime.d.ts.map +1 -1
  115. package/dist/modules/dexbot_cow_runtime.js +13 -1
  116. package/dist/modules/dexbot_cow_runtime.js.map +1 -1
  117. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  118. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -1
  119. package/dist/modules/dexbot_maintenance_runtime.js +9 -4
  120. package/dist/modules/dexbot_maintenance_runtime.js.map +1 -1
  121. package/dist/modules/launcher/adapter_requirement.js +1 -1
  122. package/dist/modules/launcher/launch_modes.d.ts +17 -1
  123. package/dist/modules/launcher/launch_modes.d.ts.map +1 -1
  124. package/dist/modules/launcher/launch_modes.js +18 -1
  125. package/dist/modules/launcher/launch_modes.js.map +1 -1
  126. package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -1
  127. package/dist/modules/launcher/monolithic_runtime.js +8 -1
  128. package/dist/modules/launcher/monolithic_runtime.js.map +1 -1
  129. package/dist/modules/market_adapter_whitelist.d.ts +40 -1
  130. package/dist/modules/market_adapter_whitelist.d.ts.map +1 -1
  131. package/dist/modules/market_adapter_whitelist.js +161 -11
  132. package/dist/modules/market_adapter_whitelist.js.map +1 -1
  133. package/dist/modules/order/accounting.d.ts +4 -18
  134. package/dist/modules/order/accounting.d.ts.map +1 -1
  135. package/dist/modules/order/accounting.js +4 -34
  136. package/dist/modules/order/accounting.js.map +1 -1
  137. package/dist/modules/order/export.d.ts +9 -12
  138. package/dist/modules/order/export.d.ts.map +1 -1
  139. package/dist/modules/order/export.js +9 -12
  140. package/dist/modules/order/export.js.map +1 -1
  141. package/dist/modules/order/grid.d.ts +44 -40
  142. package/dist/modules/order/grid.d.ts.map +1 -1
  143. package/dist/modules/order/grid.js +66 -48
  144. package/dist/modules/order/grid.js.map +1 -1
  145. package/dist/modules/order/grid_reconcile.d.ts.map +1 -1
  146. package/dist/modules/order/grid_reconcile.js +111 -20
  147. package/dist/modules/order/grid_reconcile.js.map +1 -1
  148. package/dist/modules/order/grid_reconcile_internal.d.ts +5 -3
  149. package/dist/modules/order/grid_reconcile_internal.d.ts.map +1 -1
  150. package/dist/modules/order/grid_reconcile_internal.js +18 -3
  151. package/dist/modules/order/grid_reconcile_internal.js.map +1 -1
  152. package/dist/modules/order/manager.d.ts +0 -8
  153. package/dist/modules/order/manager.d.ts.map +1 -1
  154. package/dist/modules/order/manager.js +3 -12
  155. package/dist/modules/order/manager.js.map +1 -1
  156. package/dist/modules/order/utils/order.d.ts +22 -7
  157. package/dist/modules/order/utils/order.d.ts.map +1 -1
  158. package/dist/modules/order/utils/order.js +103 -21
  159. package/dist/modules/order/utils/order.js.map +1 -1
  160. package/dist/modules/order/utils/system.d.ts +5 -1
  161. package/dist/modules/order/utils/system.d.ts.map +1 -1
  162. package/dist/modules/order/utils/system.js +5 -2
  163. package/dist/modules/order/utils/system.js.map +1 -1
  164. package/dist/modules/order/utils/withPoolRef.d.ts +12 -0
  165. package/dist/modules/order/utils/withPoolRef.d.ts.map +1 -1
  166. package/dist/modules/order/utils/withPoolRef.js +17 -0
  167. package/dist/modules/order/utils/withPoolRef.js.map +1 -1
  168. package/dist/modules/order/working_grid.d.ts +8 -13
  169. package/dist/modules/order/working_grid.d.ts.map +1 -1
  170. package/dist/modules/order/working_grid.js +8 -29
  171. package/dist/modules/order/working_grid.js.map +1 -1
  172. package/dist/modules/settings_merge.d.ts +10 -1
  173. package/dist/modules/settings_merge.d.ts.map +1 -1
  174. package/dist/modules/settings_merge.js +27 -17
  175. package/dist/modules/settings_merge.js.map +1 -1
  176. package/dist/modules/validate_profiles.d.ts.map +1 -1
  177. package/dist/modules/validate_profiles.js +4 -3
  178. package/dist/modules/validate_profiles.js.map +1 -1
  179. package/dist/scripts/chart_command.d.ts +48 -0
  180. package/dist/scripts/chart_command.d.ts.map +1 -0
  181. package/dist/scripts/chart_command.js +504 -0
  182. package/dist/scripts/chart_command.js.map +1 -0
  183. package/dist/scripts/dw.d.ts +3 -0
  184. package/dist/scripts/dw.d.ts.map +1 -0
  185. package/dist/scripts/dw.js +30 -0
  186. package/dist/scripts/dw.js.map +1 -0
  187. package/dist/scripts/sync-version.js +0 -22
  188. package/dist/scripts/sync-version.js.map +1 -1
  189. package/dist/scripts/tv.d.ts +1 -31
  190. package/dist/scripts/tv.d.ts.map +1 -1
  191. package/dist/scripts/tv.js +10 -463
  192. package/dist/scripts/tv.js.map +1 -1
  193. package/dist/scripts/update.js +99 -62
  194. package/dist/scripts/update.js.map +1 -1
  195. package/dist/scripts/update_dist_freshness.d.ts +58 -0
  196. package/dist/scripts/update_dist_freshness.d.ts.map +1 -0
  197. package/dist/scripts/update_dist_freshness.js +144 -0
  198. package/dist/scripts/update_dist_freshness.js.map +1 -0
  199. package/dist/unlock.js +1 -1
  200. package/dist/unlock.js.map +1 -1
  201. package/docs/BITSHARES_ONBOARDING.md +16 -10
  202. package/docs/COW_INVARIANTS.md +1 -0
  203. package/docs/DEXBOT_COMPARISON.md +11 -11
  204. package/docs/EVOLUTION.md +9 -7
  205. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +4 -4
  206. package/docs/GRID_PRICE_INVARIANT.md +518 -0
  207. package/docs/GRID_RECALCULATION.md +20 -24
  208. package/docs/GRID_RECONCILE.md +62 -41
  209. package/docs/LOGGING.md +1 -0
  210. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +556 -0
  211. package/docs/README.md +18 -18
  212. package/docs/WORKFLOW.md +13 -8
  213. package/docs/architecture.md +42 -40
  214. package/docs/developer_guide.md +5 -8
  215. package/market_adapter/README.md +45 -65
  216. package/modules/README.md +3 -2
  217. package/package.json +7 -4
  218. package/scripts/README.md +18 -34
  219. package/scripts/reset-settings.sh +1 -1
  220. package/analysis/ama_fitting/package.json +0 -12
  221. package/analysis/analyze_derivatives.ts +0 -320
  222. package/analysis/derivative_chart_generator.ts +0 -874
  223. package/analysis/trend_detection/SIGNAL_DOCUMENTATION.md +0 -403
  224. package/analysis/trend_detection/derivative_analyzer.ts +0 -1059
  225. package/dist/analysis/analyze_derivatives.d.ts +0 -68
  226. package/dist/analysis/analyze_derivatives.d.ts.map +0 -1
  227. package/dist/analysis/analyze_derivatives.js +0 -287
  228. package/dist/analysis/analyze_derivatives.js.map +0 -1
  229. package/dist/analysis/derivative_chart_generator.d.ts +0 -12
  230. package/dist/analysis/derivative_chart_generator.d.ts.map +0 -1
  231. package/dist/analysis/derivative_chart_generator.js +0 -891
  232. package/dist/analysis/derivative_chart_generator.js.map +0 -1
  233. package/dist/analysis/trend_detection/derivative_analyzer.d.ts +0 -248
  234. package/dist/analysis/trend_detection/derivative_analyzer.d.ts.map +0 -1
  235. package/dist/analysis/trend_detection/derivative_analyzer.js +0 -910
  236. package/dist/analysis/trend_detection/derivative_analyzer.js.map +0 -1
  237. package/dist/scripts/generate_market_adapter_whitelist.d.ts +0 -15
  238. package/dist/scripts/generate_market_adapter_whitelist.d.ts.map +0 -1
  239. package/dist/scripts/generate_market_adapter_whitelist.js +0 -191
  240. package/dist/scripts/generate_market_adapter_whitelist.js.map +0 -1
@@ -12,63 +12,58 @@
12
12
  * - Detects and flags out-of-spread conditions
13
13
  *
14
14
  * ===============================================================================
15
- * TABLE OF CONTENTS - Grid Functions (27 exported functions)
15
+ * TABLE OF CONTENTS - Grid Functions (22 exported functions)
16
16
  * ===============================================================================
17
17
  *
18
- * CONFIGURATION & CALCULATION (1 method)
19
- * 1. calculateGapSlots(incrementPercent, targetSpreadPercent) - Calculate spread gap size
18
+ * CONFIGURATION & CALCULATION (2 functions)
19
+ * 1. resolveRmsThresholdPct(manager) - Resolve the structural-divergence threshold
20
+ * 2. calculateGapSlots(incrementPercent, targetSpreadPercent) - Calculate spread gap size
20
21
  *
21
- * GRID SIZING & CONTEXT (1 method)
22
- * 3. _getSizingContext(manager, side) - Get budget and sizing parameters (internal)
23
- * Determines budget from allocated funds, deducts BTS fees if needed
22
+ * GRID SIZING & CONTEXT (1 function)
23
+ * 3. _getSizingContext(manager, side, options) - Get budget and sizing parameters
24
+ * Determines budget from allocated funds and optionally deducts BTS fees
24
25
  *
25
- * GRID CREATION (1 method)
26
+ * GRID CREATION (1 function)
26
27
  * 4. createOrderGrid(config) - Create geometric price grid
27
28
  * Returns price levels from minPrice to maxPrice with increment spacing
28
29
  *
29
- * ORDER CACHE MANAGEMENT (1 method - internal)
30
- * 5. _clearOrderCachesLogic(manager) - Clear order caches (_ordersByType, _ordersByState)
30
+ * GRID LOADING & INITIALIZATION (2 functions - async)
31
+ * 5. loadGrid(manager, grid, boundaryIdx, genesisInput, options) - Load grid into manager orders
32
+ * 6. initializeGrid(manager) - Full grid initialization from config
31
33
  *
32
- * GRID LOADING & INITIALIZATION (2 methods - async)
33
- * 6. loadGrid(manager, grid, boundaryIdx) - Load grid into manager orders
34
- * 7. initializeGrid(manager) - Full grid initialization from config
34
+ * GRID RECALCULATION (1 function - async)
35
+ * 7. recalculateGrid(manager, opts) - Recalculate grid based on current state
35
36
  *
36
- * GRID RECALCULATION (1 method - async)
37
- * 8. recalculateGrid(manager, opts) - Recalculate grid based on current state
37
+ * GRID STATE CHECKING (1 function)
38
+ * 8. checkAndUpdateGridIfNeeded(manager) - Check if grid needs update
38
39
  *
39
- * GRID STATE CHECKING (1 method)
40
- * 9. checkAndUpdateGridIfNeeded(manager) - Check if grid needs update
40
+ * BLOCKCHAIN SYNCHRONIZATION (2 functions - async)
41
+ * 9. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
42
+ * 10. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer, overrideBoundaryIdx) - Update grid from blockchain
41
43
  *
42
- * BLOCKCHAIN SYNCHRONIZATION (2 methods - async)
43
- * 10. _recalculateGridOrderSizesFromBlockchain(manager, orderType) - Recalculate sizes from blockchain
44
- * 11. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer) - Update grid from blockchain
45
- *
46
- * GRID COMPARISON (2 methods - async)
47
- * 12. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
44
+ * GRID COMPARISON (2 functions - async)
45
+ * 11. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
48
46
  * Validates grid structure and reports divergence metrics
49
- * 13. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
47
+ * 12. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
50
48
  * Runs ratio-based + RMS-based checks and returns combined result
51
49
  *
52
- * ON-CHAIN ORDER FETCHING (1 method - async)
53
- * 14. _getOnChainOrders(manager) - Collect on-chain buy/sell orders from manager
54
- *
55
- * SPREAD MANAGEMENT (2 methods - async)
56
- * 15. calculateCurrentSpread(manager) - Calculate current bid-ask spread
57
- * 16. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
50
+ * SPREAD MANAGEMENT (2 functions)
51
+ * 13. calculateCurrentSpread(manager) - Calculate current bid-ask spread
52
+ * 14. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
58
53
  *
59
- * GRID HEALTH MONITORING (6 methods)
60
- * 17. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health (async)
61
- * 18. checkWindowDust(manager) - Dust check scoped to the active buy/sell window (async)
62
- * 19. _hasAnyDust(manager, partials, type) - Check for dust orders (internal)
63
- * 20. hasAnyDust(manager, partials, side) - Check for dust orders (public)
64
- * 21. getDustOrders(manager, partials, side) - Get all dust order IDs (public)
65
- * 22. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
54
+ * GRID HEALTH MONITORING (4 functions)
55
+ * 15. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health
56
+ * 16. checkWindowDust(manager) - Dust check scoped to the active buy/sell window
57
+ * 17. hasAnyDust(manager, partials, side) - Check for dust orders
58
+ * 18. getDustOrders(manager, partials, side) - Get dust order IDs
66
59
  *
67
- * SPREAD CORRECTION (1 method)
68
- * 23. prepareSpreadCorrectionOrders(manager, preferredSide) - Prepare correction orders
60
+ * SIDE SELECTION (1 function)
61
+ * 19. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
69
62
  *
70
- * DUST DETECTION (1 method - internal)
71
- * 25. _getDustOrders(manager, partials, type) - Internal dust detection helper
63
+ * BLOAT STATUS (3 functions)
64
+ * 20. isGridBloated(manager, orders) - Check whether the grid is bloated
65
+ * 21. isGridBloatGraceActive(manager) - Check the bloat grace state
66
+ * 22. clearGridBloatFlag(manager) - Clear the bloat state
72
67
  *
73
68
  * ===============================================================================
74
69
  *
@@ -95,13 +90,24 @@
95
90
  import { createRequire } from 'node:module';
96
91
  const require = createRequire(import.meta.url);
97
92
  import { ORDER_TYPES, ORDER_STATES, COW_ACTIONS, DEFAULT_CONFIG, GRID_LIMITS, TIMING, PIPELINE_TIMING, MARKET_ADAPTER, INCREMENT_BOUNDS } from '../constants.js';
98
- const { GRID_COMPARISON } = GRID_LIMITS;
99
93
  import * as Format from './format.js';
100
94
  import { resolveMaxAsymmetryFactor, applyAsymmetricBounds, applyNarrowingSideGuard, } from '../../market_adapter/core/asymmetric_bounds.js';
101
95
  // FIX: Extract magic numbers to named constants for maintainability
102
96
  const GRID_CONSTANTS = {
103
97
  RMS_PERCENTAGE_SCALE: 100, // Convert RMS percentage threshold from percent to decimal
104
98
  };
99
+ /**
100
+ * Central resolution for the RMS structural-divergence threshold (percent).
101
+ * Single source of truth: per-bot override wins, global GRID_COMPARISON default
102
+ * is the fallback. Used by compareGrids() and re-exported for the maintenance
103
+ * runtime so the reset log always shows the level that actually fired.
104
+ * @param {any} manager - OrderManager instance (may be null)
105
+ * @returns {number} Threshold in percent (0 = disabled)
106
+ */
107
+ export function resolveRmsThresholdPct(manager) {
108
+ return manager?.config?.gridLimits?.GRID_COMPARISON?.RMS_PERCENTAGE
109
+ ?? GRID_LIMITS.GRID_COMPARISON.RMS_PERCENTAGE;
110
+ }
105
111
  function _snapshotFundState(manager) {
106
112
  return {
107
113
  buyFree: Number(manager.accountTotals?.buyFree || 0),
@@ -114,7 +120,7 @@ import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager,
114
120
  import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveReserveCount, reserveEdgeIdSet, resolveLiveReserveEdgeAnchorPrice } from './utils/order.js';
115
121
  import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry } from './utils/system.js';
116
122
  import * as MathUtils from './utils/math.js';
117
- import { derivePriceWithPoolRef } from './utils/withPoolRef.js';
123
+ import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
118
124
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
119
125
  import { getErrorMessage } from '../utils/errors.js';
120
126
  const calculateGapSlots = _mathGapSlots;
@@ -943,9 +949,14 @@ export async function initializeGrid(manager) {
943
949
  if (typeof mpRaw !== 'number' || isNaN(mpRaw)) {
944
950
  try {
945
951
  const { BitShares } = require('../bitshares_client');
946
- const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA, manager.config.assetB, manager.config.priceMode || 'auto', manager.config.poolRef);
952
+ // startPrice is the master price source: pass its own mode so a
953
+ // pinned poolRef only refines pool discovery. Without this,
954
+ // the old `priceMode || 'auto'` read (priceMode is never set in
955
+ // the runtime path) let a poolRef override startPrice:"book".
956
+ const startPriceMode = resolveStartPriceMode(mpRaw, manager.config.priceMode || 'auto');
957
+ const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA, manager.config.assetB, startPriceMode, manager.config.poolRef);
947
958
  if (derived) {
948
- manager.logger?.log?.(`[DIAGNOSTIC] initializeGrid: Derived new startPrice=${derived.toFixed(8)} (mode=${manager.config.priceMode || 'auto'})`, 'info');
959
+ manager.logger?.log?.(`[DIAGNOSTIC] initializeGrid: Derived new startPrice=${derived.toFixed(8)} (mode=${startPriceMode})`, 'info');
949
960
  manager.config.startPrice = Number(derived);
950
961
  }
951
962
  else {
@@ -1884,8 +1895,9 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
1884
1895
  // Check if metrics exceed threshold and flag sides for regeneration
1885
1896
  // Set RMS_PERCENTAGE to 0 to disable RMS divergence checks
1886
1897
  let buyUpdated = false, sellUpdated = false;
1887
- if (manager && (manager.config?.gridLimits?.GRID_COMPARISON?.RMS_PERCENTAGE ?? GRID_COMPARISON.RMS_PERCENTAGE) > 0) {
1888
- const limit = (manager.config?.gridLimits?.GRID_COMPARISON?.RMS_PERCENTAGE ?? GRID_COMPARISON.RMS_PERCENTAGE) / GRID_CONSTANTS.RMS_PERCENTAGE_SCALE;
1898
+ const rmsThresholdPct = resolveRmsThresholdPct(manager);
1899
+ if (manager && rmsThresholdPct > 0) {
1900
+ const limit = rmsThresholdPct / GRID_CONSTANTS.RMS_PERCENTAGE_SCALE;
1889
1901
  if (buyMetric > limit) {
1890
1902
  // RC-3: Use Set for automatic duplicate prevention
1891
1903
  if (!(manager._gridSidesUpdated instanceof Set))
@@ -1900,11 +1912,16 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
1900
1912
  manager._gridSidesUpdated.add(ORDER_TYPES.SELL);
1901
1913
  sellUpdated = true;
1902
1914
  }
1915
+ manager.logger?.log?.(`[RMS] BUY check: metric=${Format.formatPercent(buyMetric * 100, 2)}% (threshold=${rmsThresholdPct}%) → ${buyUpdated ? 'TRIGGER-RESYNC' : 'no trigger'} | SELL check: metric=${Format.formatPercent(sellMetric * 100, 2)}% (threshold=${rmsThresholdPct}%) → ${sellUpdated ? 'TRIGGER-RESYNC' : 'no trigger'}`, 'debug');
1916
+ }
1917
+ else if (manager) {
1918
+ manager.logger?.log?.(`[RMS] checks disabled (threshold=${rmsThresholdPct}%) — buy=${Format.formatPercent(buyMetric * 100, 2)}%, sell=${Format.formatPercent(sellMetric * 100, 2)}%`, 'debug');
1903
1919
  }
1904
1920
  return {
1905
1921
  buy: { metric: buyMetric, updated: buyUpdated },
1906
1922
  sell: { metric: sellMetric, updated: sellUpdated },
1907
- totalMetric: (buyMetric + sellMetric) / 2
1923
+ totalMetric: (buyMetric + sellMetric) / 2,
1924
+ thresholdPct: rmsThresholdPct
1908
1925
  };
1909
1926
  }
1910
1927
  /**
@@ -1937,7 +1954,8 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
1937
1954
  needsUpdate: buyUpdated || sellUpdated,
1938
1955
  buy: { updated: buyUpdated, ratio: ratioResult.buyUpdated, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: ratioResult.buyShrink === true },
1939
1956
  sell: { updated: sellUpdated, ratio: ratioResult.sellUpdated, rms: rmsResult.sell.updated, metric: rmsResult.sell.metric, shrink: ratioResult.sellShrink === true },
1940
- orderType: getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated)
1957
+ orderType: getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated),
1958
+ thresholdPct: rmsResult.thresholdPct
1941
1959
  };
1942
1960
  }
1943
1961
  /**