dexbot 1.1.14 → 1.2.0

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 (116) hide show
  1. package/README.md +1 -0
  2. package/dist/market_adapter/market_adapter.js +1 -1
  3. package/dist/market_adapter/market_adapter.js.map +1 -1
  4. package/dist/modules/bitshares-native/lru_cache.d.ts +20 -0
  5. package/dist/modules/bitshares-native/lru_cache.d.ts.map +1 -0
  6. package/dist/modules/bitshares-native/lru_cache.js +45 -0
  7. package/dist/modules/bitshares-native/lru_cache.js.map +1 -0
  8. package/dist/modules/bitshares-native/resolvers.d.ts +2 -18
  9. package/dist/modules/bitshares-native/resolvers.d.ts.map +1 -1
  10. package/dist/modules/bitshares-native/resolvers.js +2 -41
  11. package/dist/modules/bitshares-native/resolvers.js.map +1 -1
  12. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -0
  13. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +1 -1
  14. package/dist/modules/bitshares-native/serial/chain_constants.js +3 -0
  15. package/dist/modules/bitshares-native/serial/chain_constants.js.map +1 -1
  16. package/dist/modules/bitshares-native/signing_client.d.ts.map +1 -1
  17. package/dist/modules/bitshares-native/signing_client.js +12 -1
  18. package/dist/modules/bitshares-native/signing_client.js.map +1 -1
  19. package/dist/modules/bitshares-native/subscriptions.d.ts.map +1 -1
  20. package/dist/modules/bitshares-native/subscriptions.js +42 -3
  21. package/dist/modules/bitshares-native/subscriptions.js.map +1 -1
  22. package/dist/modules/bitshares-native/transport.d.ts.map +1 -1
  23. package/dist/modules/bitshares-native/transport.js +77 -27
  24. package/dist/modules/bitshares-native/transport.js.map +1 -1
  25. package/dist/modules/bitshares-native/tx/builder.d.ts.map +1 -1
  26. package/dist/modules/bitshares-native/tx/builder.js +26 -16
  27. package/dist/modules/bitshares-native/tx/builder.js.map +1 -1
  28. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +17 -0
  29. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +1 -0
  30. package/dist/modules/bitshares-native/tx/tx_cache.js +62 -0
  31. package/dist/modules/bitshares-native/tx/tx_cache.js.map +1 -0
  32. package/dist/modules/bot_settings.d.ts.map +1 -1
  33. package/dist/modules/bot_settings.js +2 -1
  34. package/dist/modules/bot_settings.js.map +1 -1
  35. package/dist/modules/chain_orders.d.ts +4 -1
  36. package/dist/modules/chain_orders.d.ts.map +1 -1
  37. package/dist/modules/chain_orders.js +30 -1
  38. package/dist/modules/chain_orders.js.map +1 -1
  39. package/dist/modules/config.d.ts +6 -0
  40. package/dist/modules/config.d.ts.map +1 -1
  41. package/dist/modules/config.js +11 -0
  42. package/dist/modules/config.js.map +1 -1
  43. package/dist/modules/constants.d.ts +14 -1
  44. package/dist/modules/constants.d.ts.map +1 -1
  45. package/dist/modules/constants.js +64 -6
  46. package/dist/modules/constants.js.map +1 -1
  47. package/dist/modules/credit_runtime.d.ts.map +1 -1
  48. package/dist/modules/credit_runtime.js +40 -29
  49. package/dist/modules/credit_runtime.js.map +1 -1
  50. package/dist/modules/dexbot_class.d.ts +6 -12
  51. package/dist/modules/dexbot_class.d.ts.map +1 -1
  52. package/dist/modules/dexbot_class.js +117 -75
  53. package/dist/modules/dexbot_class.js.map +1 -1
  54. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -5
  55. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -1
  56. package/dist/modules/dexbot_maintenance_runtime.js +19 -48
  57. package/dist/modules/dexbot_maintenance_runtime.js.map +1 -1
  58. package/dist/modules/launcher/child_env.d.ts.map +1 -1
  59. package/dist/modules/launcher/child_env.js +1 -0
  60. package/dist/modules/launcher/child_env.js.map +1 -1
  61. package/dist/modules/launcher/launch_modes.d.ts +2 -0
  62. package/dist/modules/launcher/launch_modes.d.ts.map +1 -1
  63. package/dist/modules/launcher/launch_modes.js +7 -6
  64. package/dist/modules/launcher/launch_modes.js.map +1 -1
  65. package/dist/modules/order/accounting.d.ts.map +1 -1
  66. package/dist/modules/order/accounting.js +40 -12
  67. package/dist/modules/order/accounting.js.map +1 -1
  68. package/dist/modules/order/async_lock.d.ts +12 -4
  69. package/dist/modules/order/async_lock.d.ts.map +1 -1
  70. package/dist/modules/order/async_lock.js +27 -5
  71. package/dist/modules/order/async_lock.js.map +1 -1
  72. package/dist/modules/order/grid.d.ts +434 -475
  73. package/dist/modules/order/grid.d.ts.map +1 -1
  74. package/dist/modules/order/grid.js +1612 -1592
  75. package/dist/modules/order/grid.js.map +1 -1
  76. package/dist/modules/order/grid_reconcile.d.ts +3 -73
  77. package/dist/modules/order/grid_reconcile.d.ts.map +1 -1
  78. package/dist/modules/order/grid_reconcile.js +11 -843
  79. package/dist/modules/order/grid_reconcile.js.map +1 -1
  80. package/dist/modules/order/grid_reconcile_internal.d.ts +8 -0
  81. package/dist/modules/order/grid_reconcile_internal.d.ts.map +1 -0
  82. package/dist/modules/order/grid_reconcile_internal.js +771 -0
  83. package/dist/modules/order/grid_reconcile_internal.js.map +1 -0
  84. package/dist/modules/order/logger.d.ts +1 -1
  85. package/dist/modules/order/logger.d.ts.map +1 -1
  86. package/dist/modules/order/logger.js +26 -2
  87. package/dist/modules/order/logger.js.map +1 -1
  88. package/dist/modules/order/manager.d.ts +40 -3
  89. package/dist/modules/order/manager.d.ts.map +1 -1
  90. package/dist/modules/order/manager.js +91 -12
  91. package/dist/modules/order/manager.js.map +1 -1
  92. package/dist/modules/order/runner.js +2 -2
  93. package/dist/modules/order/runner.js.map +1 -1
  94. package/dist/modules/order/strategy.js +3 -3
  95. package/dist/modules/order/strategy.js.map +1 -1
  96. package/dist/modules/order/sync_engine.d.ts +1 -1
  97. package/dist/modules/order/sync_engine.d.ts.map +1 -1
  98. package/dist/modules/order/sync_engine.js +72 -29
  99. package/dist/modules/order/sync_engine.js.map +1 -1
  100. package/dist/modules/order/utils/order.d.ts +17 -0
  101. package/dist/modules/order/utils/order.d.ts.map +1 -1
  102. package/dist/modules/order/utils/order.js +39 -18
  103. package/dist/modules/order/utils/order.js.map +1 -1
  104. package/dist/modules/order/utils/system.js +4 -4
  105. package/dist/modules/order/utils/system.js.map +1 -1
  106. package/dist/modules/order/utils/validate.d.ts.map +1 -1
  107. package/dist/modules/order/utils/validate.js +6 -8
  108. package/dist/modules/order/utils/validate.js.map +1 -1
  109. package/dist/scripts/print_grid.js +3 -3
  110. package/dist/scripts/print_grid.js.map +1 -1
  111. package/dist/scripts/test-credit-renewal.js +1 -1
  112. package/dist/scripts/test-credit-renewal.js.map +1 -1
  113. package/dist/unlock.d.ts.map +1 -1
  114. package/dist/unlock.js +26 -12
  115. package/dist/unlock.js.map +1 -1
  116. package/package.json +1 -1
@@ -2,7 +2,7 @@
2
2
  * modules/order/grid.ts - Grid Engine
3
3
  *
4
4
  * Order grid creation, synchronization, and health management.
5
- * Exports a single Grid class with static methods for grid operations.
5
+ * Exports plain functions for grid operations.
6
6
  *
7
7
  * Manages the complete lifecycle of the order grid:
8
8
  * - Creates geometric price grids with configurable spacing (increments)
@@ -12,7 +12,7 @@
12
12
  * - Detects and flags out-of-spread conditions
13
13
  *
14
14
  * ===============================================================================
15
- * TABLE OF CONTENTS - Grid Class (25 static methods)
15
+ * TABLE OF CONTENTS - Grid Functions (28 exported functions)
16
16
  * ===============================================================================
17
17
  *
18
18
  * CONFIGURATION & CALCULATION (2 methods)
@@ -94,482 +94,441 @@
94
94
  *
95
95
  * ===============================================================================
96
96
  */
97
- declare class Grid {
98
- /**
99
- * Calculate the spread gap size (number of empty slots between BUY and SELL rails).
100
- * Delegates to utils/math for pure calculation logic.
101
- *
102
- * @param {number} incrementPercent
103
- * @param {number} targetSpreadPercent
104
- * @returns {number}
105
- */
106
- static calculateGapSlots(incrementPercent: any, targetSpreadPercent: any, gridLimitsOverride?: Record<string, any>): any;
107
- /**
108
- * Detect grid bloat: compares total grid size to expected maximum based on
109
- * actual placed orders (ACTIVE/PARTIAL with orderId) plus gap slots plus 1
110
- * tolerance slot. Accepts either an array (from persisted grid load) or a
111
- * Map (from manager.orders at runtime).
112
- *
113
- * Formula: maxAllowed = placedCount + gapSlots + 1
114
- *
115
- * @param {Object} manager - OrderManager instance (provides config).
116
- * @param {Array|Map} orders - Grid orders as array or Map.
117
- * @returns {{bloated: boolean, details?: {gridSize: number, placedCount: number, numBuyActive: number, numSellActive: number, gapSlots: number, maxAllowed: number}}}
118
- */
119
- static isGridBloated(manager: any, orders: any): {
120
- bloated: boolean;
121
- details?: undefined;
122
- } | {
123
- bloated: boolean;
124
- details: {
125
- gridSize: any;
126
- placedCount: number;
127
- numBuyActive: number;
128
- numSellActive: number;
129
- gapSlots: any;
130
- maxAllowed: any;
131
- };
97
+ export declare function calculateGapSlots(incrementPercent: any, targetSpreadPercent: any, gridLimitsOverride?: Record<string, any>): any;
98
+ export declare function isGridBloated(manager: any, orders: any): {
99
+ bloated: boolean;
100
+ details?: undefined;
101
+ } | {
102
+ bloated: boolean;
103
+ details: {
104
+ gridSize: any;
105
+ placedCount: number;
106
+ numBuyActive: number;
107
+ numSellActive: number;
108
+ gapSlots: any;
109
+ maxAllowed: any;
132
110
  };
133
- /**
134
- * Public wrapper for side sizing context.
135
- * Keeps StrategyEngine decoupled from Grid private internals.
136
- *
137
- * @param {import('./types').OrderManager} manager
138
- * @param {'buy'|'sell'} side
139
- * @returns {Promise<import('./types').SizingContext|null>}
140
- */
141
- static getSizingContext(manager: any, side: any): Promise<{
142
- budget: any;
143
- precision: any;
144
- config: any;
145
- }>;
146
- /**
147
- * Unifies budget calculation and fee deduction for all grid sizing scenarios.
148
- * Ensures consistent fund context (Allocated vs Total) across the bot.
149
- *
150
- * @param {import('./types').OrderManager} manager - OrderManager instance
151
- * @param {string} side - 'buy' or 'sell'
152
- * @returns {Promise<import('./types').SizingContext|null>}
153
- * @private
154
- */
155
- static _getSizingContext(manager: any, side: any, { skipRecalc }?: {
156
- skipRecalc?: boolean;
157
- }): Promise<{
158
- budget: any;
159
- precision: any;
160
- config: any;
161
- }>;
162
- /**
163
- * Create the initial order grid structure based on configuration.
164
- *
165
- * ALGORITHM: Geometric Grid Creation with Fixed Spread Gap
166
- * =========================================================
167
- * This method generates a unified "Master Rail" of price levels with geometric spacing.
168
- * The grid is centered around startPrice with a fixed-size spread gap.
169
- *
170
- * KEY CONCEPTS:
171
- * - Geometric Spacing: Each price level is incrementPercent% away from neighbors
172
- * - Master Rail: Single unified array (not separate buy/sell rails)
173
- * - Spread Gap: Fixed-size buffer between best buy and best sell
174
- * - Role Assignment: BUY / SPREAD / SELL based on position relative to startPrice
175
- *
176
- * SPREAD GAP FORMULA:
177
- * ===================
178
- * The spread gap size is calculated to match the target spread percentage:
179
- *
180
- * 1. Step Factor (s): s = 1 + (incrementPercent / 100)
181
- * Example: If incrementPercent = 0.5%, then s = 1.005
182
- *
183
- * 2. Minimum Spread: minSpread = incrementPercent × MIN_SPREAD_FACTOR
184
- * This ensures spread is at least 2× the increment (prevents too-narrow spread)
185
- *
186
- * 3. Target Steps (n): Number of price levels needed to achieve target spread
187
- * Formula: n = ceil(ln(1 + targetSpread/100) / ln(s))
188
- *
189
- * Derivation: If we want price to grow by targetSpread% over n steps:
190
- * - Final price = startPrice × s^n
191
- * - Growth factor = (1 + targetSpread/100)
192
- * - Therefore: s^n = (1 + targetSpread/100)
193
- * - Taking ln: n × ln(s) = ln(1 + targetSpread/100)
194
- * - Solving: n = ln(1 + targetSpread/100) / ln(s)
195
- *
196
- * 4. Gap Slots (G): G = max(MIN_SPREAD_ORDERS, n)
197
- * Ensures at least MIN_SPREAD_ORDERS slots even if target spread is small
198
- *
199
- * EXAMPLE:
200
- * --------
201
- * incrementPercent = 0.5%, targetSpread = 2%
202
- * - s = 1.005
203
- * - minSpread = 0.5% × 2 = 1%
204
- * - targetSpread = max(2%, 1%) = 2%
205
- * - n = ceil(ln(1.02) / ln(1.005)) = ceil(3.98) = 4 steps
206
- * - G = max(2, 4) = 4 slots
207
- *
208
- * @param {import('./types').GridConfig} config - Grid configuration
209
- * @returns {import('./types').GridCreationResult}
210
- */
211
- static createOrderGrid(config: any): {
212
- orders: any;
213
- boundaryIdx: any;
214
- initialSpreadCount: {
215
- buy: number;
216
- sell: number;
217
- };
111
+ };
112
+ /**
113
+ * Check whether the grid-bloat grace period is still active, i.e. a
114
+ * bloat detection happened recently enough that a structural resync
115
+ * has not had time to resolve it.
116
+ *
117
+ * Used by both Grid.loadGrid (to suppress redundant resync requests)
118
+ * and the maintenance runtime (to decide when to re-check after the
119
+ * grace window expires) so the two policies share one definition of
120
+ * the grace window.
121
+ *
122
+ * @param {Object} manager - OrderManager instance.
123
+ * @returns {{active: boolean, elapsed: number, graceMs: number}}
124
+ */
125
+ export declare function isGridBloatGraceActive(manager: any): {
126
+ active: boolean;
127
+ elapsed: number;
128
+ graceMs: any;
129
+ };
130
+ /**
131
+ * Clear the grid-bloat detection timestamp once the grid size has
132
+ * returned to normal. Shared so both call sites use the same key.
133
+ * @param {Object} manager - OrderManager instance.
134
+ */
135
+ export declare function clearGridBloatFlag(manager: any): void;
136
+ /**
137
+ * Public wrapper for side sizing context.
138
+ * Keeps StrategyEngine decoupled from Grid private internals.
139
+ *
140
+ * @param {import('./types').OrderManager} manager
141
+ * @param {'buy'|'sell'} side
142
+ * @returns {Promise<import('./types').SizingContext|null>}
143
+ */
144
+ export declare function getSizingContext(manager: any, side: any): Promise<{
145
+ budget: any;
146
+ precision: any;
147
+ config: any;
148
+ }>;
149
+ /**
150
+ * Unifies budget calculation and fee deduction for all grid sizing scenarios.
151
+ * Ensures consistent fund context (Allocated vs Total) across the bot.
152
+ *
153
+ * @param {import('./types').OrderManager} manager - OrderManager instance
154
+ * @param {string} side - 'buy' or 'sell'
155
+ * @returns {Promise<import('./types').SizingContext|null>}
156
+ * @private
157
+ */
158
+ export declare function _getSizingContext(manager: any, side: any, { skipRecalc }?: {
159
+ skipRecalc?: boolean;
160
+ }): Promise<{
161
+ budget: any;
162
+ precision: any;
163
+ config: any;
164
+ }>;
165
+ /**
166
+ * Create the initial order grid structure based on configuration.
167
+ *
168
+ * ALGORITHM: Geometric Grid Creation with Fixed Spread Gap
169
+ * =========================================================
170
+ * This method generates a unified "Master Rail" of price levels with geometric spacing.
171
+ * The grid is centered around startPrice with a fixed-size spread gap.
172
+ *
173
+ * KEY CONCEPTS:
174
+ * - Geometric Spacing: Each price level is incrementPercent% away from neighbors
175
+ * - Master Rail: Single unified array (not separate buy/sell rails)
176
+ * - Spread Gap: Fixed-size buffer between best buy and best sell
177
+ * - Role Assignment: BUY / SPREAD / SELL based on position relative to startPrice
178
+ *
179
+ * SPREAD GAP FORMULA:
180
+ * ===================
181
+ * The spread gap size is calculated to match the target spread percentage:
182
+ *
183
+ * 1. Step Factor (s): s = 1 + (incrementPercent / 100)
184
+ * Example: If incrementPercent = 0.5%, then s = 1.005
185
+ *
186
+ * 2. Minimum Spread: minSpread = incrementPercent × MIN_SPREAD_FACTOR
187
+ * This ensures spread is at least 2× the increment (prevents too-narrow spread)
188
+ *
189
+ * 3. Target Steps (n): Number of price levels needed to achieve target spread
190
+ * Formula: n = ceil(ln(1 + targetSpread/100) / ln(s))
191
+ *
192
+ * Derivation: If we want price to grow by targetSpread% over n steps:
193
+ * - Final price = startPrice × s^n
194
+ * - Growth factor = (1 + targetSpread/100)
195
+ * - Therefore: s^n = (1 + targetSpread/100)
196
+ * - Taking ln: n × ln(s) = ln(1 + targetSpread/100)
197
+ * - Solving: n = ln(1 + targetSpread/100) / ln(s)
198
+ *
199
+ * 4. Gap Slots (G): G = max(MIN_SPREAD_ORDERS, n)
200
+ * Ensures at least MIN_SPREAD_ORDERS slots even if target spread is small
201
+ *
202
+ * EXAMPLE:
203
+ * --------
204
+ * incrementPercent = 0.5%, targetSpread = 2%
205
+ * - s = 1.005
206
+ * - minSpread = 0.5% × 2 = 1%
207
+ * - targetSpread = max(2%, 1%) = 2%
208
+ * - n = ceil(ln(1.02) / ln(1.005)) = ceil(3.98) = 4 steps
209
+ * - G = max(2, 4) = 4 slots
210
+ *
211
+ * @param {import('./types').GridConfig} config - Grid configuration
212
+ * @returns {import('./types').GridCreationResult}
213
+ */
214
+ export declare function createOrderGrid(config: any): {
215
+ orders: any;
216
+ boundaryIdx: any;
217
+ initialSpreadCount: {
218
+ buy: number;
219
+ sell: number;
220
+ };
221
+ };
222
+ /**
223
+ * Restore a persisted grid snapshot onto a manager instance.
224
+ * @param {import('./types').OrderManager} manager - The manager instance.
225
+ * @param {Array<import('./types').GridOrderSlot>} grid - The persisted grid array.
226
+ * @param {number|null} [boundaryIdx=null] - The master boundary index.
227
+ * @returns {Promise<void>}
228
+ */
229
+ export declare function loadGrid(manager: any, grid: any, boundaryIdx?: any): Promise<any>;
230
+ /**
231
+ * Initialize the order grid with blockchain-aware sizing.
232
+ * @param {import('./types').OrderManager} manager - The manager instance.
233
+ * @returns {Promise<void>}
234
+ * @throws {Error} If initialization fails or account totals are missing.
235
+ */
236
+ export declare function initializeGrid(manager: any): Promise<void>;
237
+ /**
238
+ * Full grid resynchronization from blockchain state.
239
+ * @param {import('./types').OrderManager} manager - The manager instance.
240
+ * @param {Object} opts - Options for resynchronization.
241
+ * @param {Function} opts.readOpenOrdersFn - Function to read open orders.
242
+ * @param {Object} opts.chainOrders - Chain orders module.
243
+ * @param {string} opts.account - Account name.
244
+ * @param {string} opts.privateKey - Private key.
245
+ * @returns {Promise<void>}
246
+ */
247
+ export declare function recalculateGrid(manager: any, opts: any): Promise<void>;
248
+ /**
249
+ * Check for grid divergence and trigger update if threshold is met.
250
+ *
251
+ * @param {import('./types').OrderManager} manager - Manager instance with order state
252
+ * @returns {import('./types').SideUpdateFlags}
253
+ */
254
+ export declare function checkAndUpdateGridIfNeeded(manager: any): {
255
+ buyUpdated: boolean;
256
+ sellUpdated: boolean;
257
+ };
258
+ /**
259
+ * Standardize grid sizes using blockchain total context.
260
+ *
261
+ * FUND CAPPING STRATEGY:
262
+ * =====================
263
+ * During grid regeneration (e.g., after fills increase available funds),
264
+ * this method recalculates all order sizes using geometric weighting.
265
+ * However, ACTIVE/PARTIAL orders must not grow larger than currently available funds.
266
+ *
267
+ * Rationale for capping:
268
+ * 1. POST-FILL EXPANSION PREVENTION: After a large fill, funds become available.
269
+ * A naive size recalculation might expand orders, consuming all new capital.
270
+ * Capping prevents this "resize explosion" by limiting growth to available free balance.
271
+ * 2. VIRTUAL ORDER PROTECTION: Virtual orders (not yet placed) are uncapped,
272
+ * allowing natural expansion when their slot comes up for placement.
273
+ * 3. BLOCKCHAIN-BACKED CONSTRAINT: sideFreeAvailable tracks exactly what we can spend,
274
+ * decreasing as commitments grow (proportional to realized delta).
275
+ *
276
+ * Fund Capping Algorithm:
277
+ * ========================
278
+ * For each ACTIVE/PARTIAL order slot:
279
+ * 1. Calculate new size from geometric series
280
+ * 2. If delta > 0 (growth):
281
+ * - affordableDelta = min(delta, sideFreeAvailable)
282
+ * - Cap growth to what we actually have: newSize = currentSize + affordableDelta
283
+ * - Deduct from sideFreeAvailable (this spending is now committed)
284
+ * 3. If delta < 0 (shrinkage):
285
+ * - Release the freed capital back to sideFreeAvailable
286
+ * - Allows later slots to grow into this freed capacity
287
+ * 4. For VIRTUAL orders (not on-chain):
288
+ * - Apply new size directly (no capping)
289
+ * - They will be constrained when actually placed
290
+ *
291
+ * Example (2 slots, buy side, budget=1000, simplify to linear):
292
+ * ========================================================
293
+ * Initial: slot[0]=400 (ACTIVE), slot[1]=0 (VIRTUAL), sideFree=600
294
+ * Recalc: newSizes=[500, 500]
295
+ *
296
+ * Process slot[0]:
297
+ * - Type: ACTIVE, current=400, new=500, delta=+100
298
+ * - affordableDelta = min(100, 600) = 100
299
+ * - Apply: size=500 (full growth), sideFree=500
300
+ *
301
+ * Process slot[1]:
302
+ * - Type: VIRTUAL (not capped), current=0, new=500, delta=+500
303
+ * - Apply: size=500 (no cap check)
304
+ * - Result: slot[1] ready for placement, will consume from sideFree when placed
305
+ *
306
+ * @param {import('./types').OrderManager} manager - OrderManager instance
307
+ * @param {string} orderType - ORDER_TYPES.BUY or ORDER_TYPES.SELL
308
+ * @param {Object} [options] - Options object
309
+ * @param {import('./working_grid')} [options.workingGrid] - Working grid for COW pattern
310
+ * @returns {Promise<{actions: Array, changed: boolean}|undefined>} - COW result or undefined
311
+ * @private
312
+ */
313
+ export declare function _recalculateGridOrderSizesFromBlockchain(manager: any, orderType: any, options?: {
314
+ workingGrid?: any;
315
+ }): Promise<{
316
+ actions: any[];
317
+ changed: boolean;
318
+ }>;
319
+ /**
320
+ * High-level entry for resizing grid from snapshot using COW pattern.
321
+ * Creates working grid, calculates new sizes, generates UPDATE actions.
322
+ * Master grid is only updated after successful blockchain confirmation.
323
+ *
324
+ * @param {import('./types').OrderManager} manager - Manager instance
325
+ * @param {string} orderType - 'buy', 'sell', or 'both' - which sides to update
326
+ * @param {boolean} [fromBlockchainTimer=false] - If true, skip refetch of account totals (already current)
327
+ * @param {number|null} [overrideBoundaryIdx=null] - Optional override for boundary index
328
+ * @returns {Promise<{actions: Array, workingGrid: import('./working_grid'), workingIndexes: Object, workingBoundary: number, hasWorkingChanges: boolean, aborted: boolean}|null>}
329
+ */
330
+ export declare function updateGridFromBlockchainSnapshot(manager: any, orderType?: string, fromBlockchainTimer?: boolean, overrideBoundaryIdx?: any): Promise<{
331
+ actions: any[];
332
+ workingGrid: any;
333
+ workingIndexes: any;
334
+ workingBoundary: any;
335
+ hasWorkingChanges: boolean;
336
+ aborted: boolean;
337
+ }>;
338
+ /**
339
+ * Compare ideal grid vs persisted grid to detect divergence.
340
+ * INDEPENDENT SIDE CHECKING: Buy and sell sides are evaluated independently.
341
+ * Each side's RMS divergence is compared against its own threshold.
342
+ * Only sides exceeding the threshold are marked for update.
343
+ *
344
+ * PURPOSE: Detect if the calculated in-memory grid has diverged significantly from the
345
+ * persisted grid state. High divergence indicates that order fills/rotations have caused
346
+ * size distributions to deviate, potentially requiring grid size recalculation.
347
+ *
348
+ * METRIC: RMS (Root Mean Square) percentage of relative size differences
349
+ * Formula: RMS% = sqrt(mean((calculated - persisted) / persisted)²) × 100
350
+ * This measures the typical relative error across all orders on each side.
351
+ *
352
+ * SIDE INDEPENDENCE:
353
+ * - Buy side RMS is checked against GRID_COMPARISON.RMS_PERCENTAGE independently
354
+ * - Sell side RMS is checked against GRID_COMPARISON.RMS_PERCENTAGE independently
355
+ * - One side can diverge while the other remains stable (no update for stable side)
356
+ *
357
+ * RC-4: Atomic snapshot taking prevents stale data from concurrent fill operations
358
+ * - Grids are snapshotted atomically before comparison
359
+ * - Prevents mixing old and new grid state
360
+ * - Ensures consistent RMS metrics across both sides
361
+ *
362
+ * @param {Array<import('./types').GridOrderSlot>} calculatedGrid - Ideal calculated grid
363
+ * @param {Array<import('./types').GridOrderSlot>} persistedGrid - Persisted grid state
364
+ * @param {import('./types').OrderManager|null} [manager=null] - Manager instance (for grid lock access)
365
+ * @returns {Promise<import('./types').GridComparisonResult>}
366
+ */
367
+ export declare function compareGrids(calculatedGrid: any, persistedGrid: any, manager?: any): Promise<{
368
+ buy: {
369
+ metric: number;
370
+ updated: boolean;
371
+ };
372
+ sell: {
373
+ metric: number;
374
+ updated: boolean;
218
375
  };
219
- /**
220
- * Internal utility to clear all order-related manager caches.
221
- * Prevents stale references during grid reinitialization.
222
- * RC-2: Synchronized to prevent concurrent modifications during clear
223
- *
224
- * Note: Uses explicit assignment instead of .clear() to enforce COW semantics:
225
- * - Replace the master grid atomically with a fresh Map instance
226
- * - Avoid mutating any previously referenced Map object
227
- * @param {import('./types').OrderManager} manager - OrderManager instance
228
- * @private
229
- */
230
- static _clearOrderCachesLogic(manager: any): void;
231
- /**
232
- * Restore a persisted grid snapshot onto a manager instance.
233
- * @param {import('./types').OrderManager} manager - The manager instance.
234
- * @param {Array<import('./types').GridOrderSlot>} grid - The persisted grid array.
235
- * @param {number|null} [boundaryIdx=null] - The master boundary index.
236
- * @returns {Promise<void>}
237
- */
238
- static loadGrid(manager: any, grid: any, boundaryIdx?: any): Promise<any>;
239
- /**
240
- * Initialize the order grid with blockchain-aware sizing.
241
- * @param {import('./types').OrderManager} manager - The manager instance.
242
- * @returns {Promise<void>}
243
- * @throws {Error} If initialization fails or account totals are missing.
244
- */
245
- static initializeGrid(manager: any): Promise<void>;
246
- /**
247
- * Full grid resynchronization from blockchain state.
248
- * @param {import('./types').OrderManager} manager - The manager instance.
249
- * @param {Object} opts - Options for resynchronization.
250
- * @param {Function} opts.readOpenOrdersFn - Function to read open orders.
251
- * @param {Object} opts.chainOrders - Chain orders module.
252
- * @param {string} opts.account - Account name.
253
- * @param {string} opts.privateKey - Private key.
254
- * @returns {Promise<void>}
255
- */
256
- static recalculateGrid(manager: any, opts: any): Promise<void>;
257
- /**
258
- * Check for grid divergence and trigger update if threshold is met.
259
- *
260
- * @param {import('./types').OrderManager} manager - Manager instance with order state
261
- * @returns {import('./types').SideUpdateFlags}
262
- */
263
- static checkAndUpdateGridIfNeeded(manager: any): {
264
- buyUpdated: boolean;
265
- sellUpdated: boolean;
376
+ totalMetric?: undefined;
377
+ } | {
378
+ buy: {
379
+ metric: any;
380
+ updated: boolean;
266
381
  };
267
- /**
268
- * Standardize grid sizes using blockchain total context.
269
- *
270
- * FUND CAPPING STRATEGY:
271
- * =====================
272
- * During grid regeneration (e.g., after fills increase available funds),
273
- * this method recalculates all order sizes using geometric weighting.
274
- * However, ACTIVE/PARTIAL orders must not grow larger than currently available funds.
275
- *
276
- * Rationale for capping:
277
- * 1. POST-FILL EXPANSION PREVENTION: After a large fill, funds become available.
278
- * A naive size recalculation might expand orders, consuming all new capital.
279
- * Capping prevents this "resize explosion" by limiting growth to available free balance.
280
- * 2. VIRTUAL ORDER PROTECTION: Virtual orders (not yet placed) are uncapped,
281
- * allowing natural expansion when their slot comes up for placement.
282
- * 3. BLOCKCHAIN-BACKED CONSTRAINT: sideFreeAvailable tracks exactly what we can spend,
283
- * decreasing as commitments grow (proportional to realized delta).
284
- *
285
- * Fund Capping Algorithm:
286
- * ========================
287
- * For each ACTIVE/PARTIAL order slot:
288
- * 1. Calculate new size from geometric series
289
- * 2. If delta > 0 (growth):
290
- * - affordableDelta = min(delta, sideFreeAvailable)
291
- * - Cap growth to what we actually have: newSize = currentSize + affordableDelta
292
- * - Deduct from sideFreeAvailable (this spending is now committed)
293
- * 3. If delta < 0 (shrinkage):
294
- * - Release the freed capital back to sideFreeAvailable
295
- * - Allows later slots to grow into this freed capacity
296
- * 4. For VIRTUAL orders (not on-chain):
297
- * - Apply new size directly (no capping)
298
- * - They will be constrained when actually placed
299
- *
300
- * Example (2 slots, buy side, budget=1000, simplify to linear):
301
- * ========================================================
302
- * Initial: slot[0]=400 (ACTIVE), slot[1]=0 (VIRTUAL), sideFree=600
303
- * Recalc: newSizes=[500, 500]
304
- *
305
- * Process slot[0]:
306
- * - Type: ACTIVE, current=400, new=500, delta=+100
307
- * - affordableDelta = min(100, 600) = 100
308
- * - Apply: size=500 (full growth), sideFree=500
309
- *
310
- * Process slot[1]:
311
- * - Type: VIRTUAL (not capped), current=0, new=500, delta=+500
312
- * - Apply: size=500 (no cap check)
313
- * - Result: slot[1] ready for placement, will consume from sideFree when placed
314
- *
315
- * @param {import('./types').OrderManager} manager - OrderManager instance
316
- * @param {string} orderType - ORDER_TYPES.BUY or ORDER_TYPES.SELL
317
- * @param {Object} [options] - Options object
318
- * @param {import('./working_grid')} [options.workingGrid] - Working grid for COW pattern
319
- * @returns {Promise<{actions: Array, changed: boolean}|undefined>} - COW result or undefined
320
- * @private
321
- */
322
- static _recalculateGridOrderSizesFromBlockchain(manager: any, orderType: any, options?: {
323
- workingGrid?: any;
324
- }): Promise<{
325
- actions: any[];
326
- changed: boolean;
327
- }>;
328
- /**
329
- * High-level entry for resizing grid from snapshot using COW pattern.
330
- * Creates working grid, calculates new sizes, generates UPDATE actions.
331
- * Master grid is only updated after successful blockchain confirmation.
332
- *
333
- * @param {import('./types').OrderManager} manager - Manager instance
334
- * @param {string} orderType - 'buy', 'sell', or 'both' - which sides to update
335
- * @param {boolean} [fromBlockchainTimer=false] - If true, skip refetch of account totals (already current)
336
- * @param {number|null} [overrideBoundaryIdx=null] - Optional override for boundary index
337
- * @returns {Promise<{actions: Array, workingGrid: import('./working_grid'), workingIndexes: Object, workingBoundary: number, hasWorkingChanges: boolean, aborted: boolean}|null>}
338
- */
339
- static updateGridFromBlockchainSnapshot(manager: any, orderType?: string, fromBlockchainTimer?: boolean, overrideBoundaryIdx?: any): Promise<{
340
- actions: any[];
341
- workingGrid: any;
342
- workingIndexes: any;
343
- workingBoundary: any;
344
- hasWorkingChanges: boolean;
345
- aborted: boolean;
346
- }>;
347
- /**
348
- * Compare ideal grid vs persisted grid to detect divergence.
349
- * INDEPENDENT SIDE CHECKING: Buy and sell sides are evaluated independently.
350
- * Each side's RMS divergence is compared against its own threshold.
351
- * Only sides exceeding the threshold are marked for update.
352
- *
353
- * PURPOSE: Detect if the calculated in-memory grid has diverged significantly from the
354
- * persisted grid state. High divergence indicates that order fills/rotations have caused
355
- * size distributions to deviate, potentially requiring grid size recalculation.
356
- *
357
- * METRIC: RMS (Root Mean Square) percentage of relative size differences
358
- * Formula: RMS% = sqrt(mean((calculated - persisted) / persisted)²) × 100
359
- * This measures the typical relative error across all orders on each side.
360
- *
361
- * SIDE INDEPENDENCE:
362
- * - Buy side RMS is checked against GRID_COMPARISON.RMS_PERCENTAGE independently
363
- * - Sell side RMS is checked against GRID_COMPARISON.RMS_PERCENTAGE independently
364
- * - One side can diverge while the other remains stable (no update for stable side)
365
- *
366
- * RC-4: Atomic snapshot taking prevents stale data from concurrent fill operations
367
- * - Grids are snapshotted atomically before comparison
368
- * - Prevents mixing old and new grid state
369
- * - Ensures consistent RMS metrics across both sides
370
- *
371
- * @param {Array<import('./types').GridOrderSlot>} calculatedGrid - Ideal calculated grid
372
- * @param {Array<import('./types').GridOrderSlot>} persistedGrid - Persisted grid state
373
- * @param {import('./types').OrderManager|null} [manager=null] - Manager instance (for grid lock access)
374
- * @returns {Promise<import('./types').GridComparisonResult>}
375
- */
376
- static compareGrids(calculatedGrid: any, persistedGrid: any, manager?: any): Promise<{
377
- buy: {
378
- metric: number;
379
- updated: boolean;
380
- };
381
- sell: {
382
- metric: number;
383
- updated: boolean;
384
- };
385
- totalMetric?: undefined;
386
- } | {
387
- buy: {
388
- metric: any;
389
- updated: boolean;
390
- };
391
- sell: {
392
- metric: any;
393
- updated: boolean;
394
- };
395
- totalMetric: number;
396
- }>;
397
- /**
398
- * Unified divergence monitoring.
399
- * Performs both Ratio-based and RMS-based divergence checks.
400
- *
401
- * @param {import('./types').OrderManager} manager - Manager instance
402
- * @param {Array<import('./types').GridOrderSlot>} calculatedGrid - Ideal/calculated grid
403
- * @param {Array<import('./types').GridOrderSlot>} persistedGrid - Current/persisted grid
404
- * @returns {Promise<import('./types').DivergenceResult>}
405
- */
406
- static monitorDivergence(manager: any, calculatedGrid: any, persistedGrid: any): Promise<{
407
- needsUpdate: boolean;
408
- buy: {
409
- updated: boolean;
410
- ratio: boolean;
411
- rms: boolean;
412
- metric: any;
413
- };
414
- sell: {
415
- updated: boolean;
416
- ratio: boolean;
417
- rms: boolean;
418
- metric: any;
419
- };
420
- orderType: any;
421
- }>;
422
- /**
423
- * Collect on-chain buy and sell orders from the manager.
424
- * Filters to orders with valid orderId and positive size.
425
- * @param {import('./types').OrderManager} manager - The manager instance.
426
- * @returns {{onChainBuys: Array<import('./types').Order>, onChainSells: Array<import('./types').Order>}}
427
- */
428
- static _getOnChainOrders(manager: any): {
429
- onChainBuys: any[];
430
- onChainSells: any[];
382
+ sell: {
383
+ metric: any;
384
+ updated: boolean;
431
385
  };
432
- /**
433
- * Calculate current market spread using on-chain orders.
434
- * @param {import('./types').OrderManager} manager - The manager instance.
435
- * @returns {number} The calculated spread percentage.
436
- */
437
- static calculateCurrentSpread(manager: any): any;
438
- /**
439
- * Proactive spread correction check.
440
- *
441
- * CRITICAL: Uses AsyncLock to prevent race conditions with fill processing.
442
- * Without the lock, a TOCTOU (Time-Of-Check-To-Use) vulnerability exists where:
443
- * - Fund snapshot is taken (check phase)
444
- * - Fill processor modifies funds in another thread
445
- * - Order is placed based on stale funds (use phase)
446
- * Result: Orders placed beyond available liquidity, fund accounting errors
447
- *
448
- * DESIGN DECISION: Lock is released before blockchain operations for performance
449
- * - Lock held: Fund verification and correction decision (synchronized)
450
- * - Lock released: Blockchain submission (async, potentially slow)
451
- * - RACE CONDITION WINDOW: Between lock release and blockchain submission
452
- * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
453
- *
454
- * See RACE_CONDITION_ANALYSIS.md for detailed vulnerability documentation.
455
- *
456
- * @param {import('./types').OrderManager} manager - Manager instance
457
- * @param {Object} BitShares - BitShares API client
458
- * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
459
- * @returns {Promise<import('./types').SpreadCheckResult>}
460
- */
461
- static checkSpreadCondition(manager: any, BitShares: any, updateOrdersOnChainBatch?: any): Promise<{
462
- ordersPlaced: any;
463
- partialsMoved: any;
464
- }>;
465
- /**
466
- * Grid health check for structural violations.
467
- * Monitors for "Dust Partials" that are too small to be traded on-chain,
468
- * scoped to the active buy/sell window.
469
- *
470
- * NOTE: Internal gaps (virtual slots between active ones) are no longer
471
- * flagged as violations. The "Edge-First" placement strategy intentionally
472
- * creates these gaps to maximize grid coverage during fund expansion.
473
- *
474
- * @param {import('./types').OrderManager} manager - The manager instance.
475
- * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function.
476
- * @returns {Promise<import('./types').DustCheckResult>}
477
- */
478
- static checkGridHealth(manager: any, updateOrdersOnChainBatch?: any): Promise<{
479
- buyDust: boolean;
480
- sellDust: boolean;
481
- buyDustOrders: any;
482
- sellDustOrders: any;
483
- }>;
484
- /**
485
- * Dust check covering all partial orders, with interior-only guard.
486
- *
487
- * The top-of-window partial (closest to market) is always eligible for dust
488
- * detection since cancelling it is just the grid edge moving inward.
489
- *
490
- * Interior partials (further from market) are only eligible if they have a
491
- * duplicate price level — another active order at essentially the same price.
492
- * Cancelling such an interior partial won't leave a gap in the grid because
493
- * the sibling active order already covers that price level.
494
- *
495
- * Returns boolean flags plus the actual dust order objects so callers can act
496
- * on individual orders (e.g. DUST_CANCEL_DELAY_SEC auto-cancel).
497
- *
498
- * @param {import('./types').OrderManager} manager
499
- * @returns {Promise<import('./types').DustCheckResult>}
500
- */
501
- static checkWindowDust(manager: any): Promise<{
502
- buyDust: boolean;
503
- sellDust: boolean;
504
- buyDustOrders: any;
505
- sellDustOrders: any;
506
- }>;
507
- /**
508
- * Return the subset of partial orders that qualify as dust on a given side.
509
- * Shares the same sizing context as _hasAnyDust but returns the actual order
510
- * objects so callers can act on them (e.g. auto-cancel).
511
- * @private
512
- * @param {import('./types').OrderManager} manager
513
- * @param {Array<import('./types').GridOrderSlot>} partials - Candidate partial orders to test.
514
- * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
515
- * @returns {Promise<Array<import('./types').GridOrderSlot>>} Orders whose size is below the dust threshold.
516
- */
517
- static _getDustOrders(manager: any, partials: any, type: any): Promise<any>;
518
- /**
519
- * Check if any partial orders on a side represent "dust" that should be cleaned.
520
- * @param {import('./types').OrderManager} manager - Manager instance
521
- * @param {Array<import('./types').GridOrderSlot>} partials - Partial orders to check
522
- * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
523
- * @returns {Promise<boolean>} true if dust partials exist
524
- * @private
525
- */
526
- static _hasAnyDust(manager: any, partials: any, type: any): Promise<boolean>;
527
- /**
528
- * Public dust helper shared by StrategyEngine and Grid health checks.
529
- * @param {import('./types').OrderManager} manager
530
- * @param {Array<import('./types').GridOrderSlot>} partials
531
- * @param {'buy'|'sell'} side
532
- * @returns {Promise<boolean>}
533
- */
534
- static hasAnyDust(manager: any, partials: any, side: any): Promise<boolean>;
535
- /**
536
- * Public dust helper that returns the subset of candidate partials currently below
537
- * the configured dust threshold for the requested side.
538
- * @param {import('./types').OrderManager} manager
539
- * @param {Array<import('./types').GridOrderSlot>} partials
540
- * @param {'buy'|'sell'} side
541
- * @returns {Promise<Array<import('./types').GridOrderSlot>>}
542
- */
543
- static getDustOrders(manager: any, partials: any, side: any): Promise<any>;
544
- /**
545
- * Determine which side has more available funds for spread correction.
546
- * @param {import('./types').OrderManager} manager - The manager instance.
547
- * @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
548
- * normalize sell-side funds into buy-side units for a fair cross-asset comparison.
549
- * @returns {{ side: import('./types').OrderType|null, reason: string }} The side to correct on, or null if insufficient funds.
550
- */
551
- static determineOrderSideByFunds(manager: any, currentMarketPrice: any): {
552
- side: any;
553
- reason: string;
386
+ totalMetric: number;
387
+ }>;
388
+ /**
389
+ * Unified divergence monitoring.
390
+ * Performs both Ratio-based and RMS-based divergence checks.
391
+ *
392
+ * @param {import('./types').OrderManager} manager - Manager instance
393
+ * @param {Array<import('./types').GridOrderSlot>} calculatedGrid - Ideal/calculated grid
394
+ * @param {Array<import('./types').GridOrderSlot>} persistedGrid - Current/persisted grid
395
+ * @returns {Promise<import('./types').DivergenceResult>}
396
+ */
397
+ export declare function monitorDivergence(manager: any, calculatedGrid: any, persistedGrid: any): Promise<{
398
+ needsUpdate: boolean;
399
+ buy: {
400
+ updated: boolean;
401
+ ratio: boolean;
402
+ rms: boolean;
403
+ metric: any;
554
404
  };
555
- /**
556
- * Calculate the geometric ideal size for a new order being placed during spread correction.
557
- * @param {import('./types').OrderManager} manager - The manager instance.
558
- * @param {import('./types').OrderType} targetType - The type of order being placed (ORDER_TYPES.BUY or ORDER_TYPES.SELL).
559
- * @returns {Promise<number|null>} The calculated geometric size.
560
- */
561
- static calculateGeometricSizeForSpreadCorrection(manager: any, targetType: any): Promise<any>;
562
- /**
563
- * Prepares one or more orders to correct a wide spread.
564
- * @param {import('./types').OrderManager} manager - The OrderManager instance.
565
- * @param {string} preferredSide - The side to place the correction on (ORDER_TYPES.BUY/SELL).
566
- * @returns {Promise<import('./types').SpreadCorrectionResult>}
567
- * @throws {Error} If preferredSide is invalid.
568
- */
569
- static prepareSpreadCorrectionOrders(manager: any, preferredSide: any): Promise<{
570
- ordersToPlace: any[];
571
- ordersToUpdate: any[];
572
- }>;
573
- }
574
- export = Grid;
405
+ sell: {
406
+ updated: boolean;
407
+ ratio: boolean;
408
+ rms: boolean;
409
+ metric: any;
410
+ };
411
+ orderType: any;
412
+ }>;
413
+ /**
414
+ * Calculate current market spread using on-chain orders.
415
+ * @param {import('./types').OrderManager} manager - The manager instance.
416
+ * @returns {number} The calculated spread percentage.
417
+ */
418
+ export declare function calculateCurrentSpread(manager: any): any;
419
+ /**
420
+ * Proactive spread correction check.
421
+ *
422
+ * CRITICAL: Uses AsyncLock to prevent race conditions with fill processing.
423
+ * Without the lock, a TOCTOU (Time-Of-Check-To-Use) vulnerability exists where:
424
+ * - Fund snapshot is taken (check phase)
425
+ * - Fill processor modifies funds in another thread
426
+ * - Order is placed based on stale funds (use phase)
427
+ * Result: Orders placed beyond available liquidity, fund accounting errors
428
+ *
429
+ * DESIGN DECISION: Lock is released before blockchain operations for performance
430
+ * - Lock held: Fund verification and correction decision (synchronized)
431
+ * - Lock released: Blockchain submission (async, potentially slow)
432
+ * - RACE CONDITION WINDOW: Between lock release and blockchain submission
433
+ * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
434
+ *
435
+ * See RACE_CONDITION_ANALYSIS.md for detailed vulnerability documentation.
436
+ *
437
+ * @param {import('./types').OrderManager} manager - Manager instance
438
+ * @param {Object} BitShares - BitShares API client
439
+ * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
440
+ * @returns {Promise<import('./types').SpreadCheckResult>}
441
+ */
442
+ export declare function checkSpreadCondition(manager: any, BitShares: any, updateOrdersOnChainBatch?: any): Promise<{
443
+ ordersPlaced: any;
444
+ partialsMoved: any;
445
+ }>;
446
+ /**
447
+ * Grid health check for structural violations.
448
+ * Monitors for "Dust Partials" that are too small to be traded on-chain,
449
+ * scoped to the active buy/sell window.
450
+ *
451
+ * NOTE: Internal gaps (virtual slots between active ones) are no longer
452
+ * flagged as violations. The "Edge-First" placement strategy intentionally
453
+ * creates these gaps to maximize grid coverage during fund expansion.
454
+ *
455
+ * @param {import('./types').OrderManager} manager - The manager instance.
456
+ * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function.
457
+ * @returns {Promise<import('./types').DustCheckResult>}
458
+ */
459
+ export declare function checkGridHealth(manager: any, updateOrdersOnChainBatch?: any): Promise<{
460
+ buyDust: boolean;
461
+ sellDust: boolean;
462
+ buyDustOrders: any;
463
+ sellDustOrders: any;
464
+ }>;
465
+ /**
466
+ * Dust check covering all partial orders, with interior-only guard.
467
+ *
468
+ * The top-of-window partial (closest to market) is always eligible for dust
469
+ * detection since cancelling it is just the grid edge moving inward.
470
+ *
471
+ * Interior partials (further from market) are only eligible if they have a
472
+ * duplicate price level — another active order at essentially the same price.
473
+ * Cancelling such an interior partial won't leave a gap in the grid because
474
+ * the sibling active order already covers that price level.
475
+ *
476
+ * Returns boolean flags plus the actual dust order objects so callers can act
477
+ * on individual orders (e.g. DUST_CANCEL_DELAY_SEC auto-cancel).
478
+ *
479
+ * @param {import('./types').OrderManager} manager
480
+ * @returns {Promise<import('./types').DustCheckResult>}
481
+ */
482
+ export declare function checkWindowDust(manager: any): Promise<{
483
+ buyDust: boolean;
484
+ sellDust: boolean;
485
+ buyDustOrders: any;
486
+ sellDustOrders: any;
487
+ }>;
488
+ /**
489
+ * Public dust helper shared by StrategyEngine and Grid health checks.
490
+ * @param {import('./types').OrderManager} manager
491
+ * @param {Array<import('./types').GridOrderSlot>} partials
492
+ * @param {'buy'|'sell'} side
493
+ * @returns {Promise<boolean>}
494
+ */
495
+ export declare function hasAnyDust(manager: any, partials: any, side: any): Promise<boolean>;
496
+ /**
497
+ * Public dust helper that returns the subset of candidate partials currently below
498
+ * the configured dust threshold for the requested side.
499
+ * @param {import('./types').OrderManager} manager
500
+ * @param {Array<import('./types').GridOrderSlot>} partials
501
+ * @param {'buy'|'sell'} side
502
+ * @returns {Promise<Array<import('./types').GridOrderSlot>>}
503
+ */
504
+ export declare function getDustOrders(manager: any, partials: any, side: any): Promise<any>;
505
+ /**
506
+ * Determine which side has more available funds for spread correction.
507
+ * @param {import('./types').OrderManager} manager - The manager instance.
508
+ * @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
509
+ * normalize sell-side funds into buy-side units for a fair cross-asset comparison.
510
+ * @returns {{ side: import('./types').OrderType|null, reason: string }} The side to correct on, or null if insufficient funds.
511
+ */
512
+ export declare function determineOrderSideByFunds(manager: any, currentMarketPrice: any): {
513
+ side: any;
514
+ reason: string;
515
+ };
516
+ /**
517
+ * Calculate the geometric ideal size for a new order being placed during spread correction.
518
+ * @param {import('./types').OrderManager} manager - The manager instance.
519
+ * @param {import('./types').OrderType} targetType - The type of order being placed (ORDER_TYPES.BUY or ORDER_TYPES.SELL).
520
+ * @returns {Promise<number|null>} The calculated geometric size.
521
+ */
522
+ export declare function calculateGeometricSizeForSpreadCorrection(manager: any, targetType: any): Promise<any>;
523
+ /**
524
+ * Prepares one or more orders to correct a wide spread.
525
+ * @param {import('./types').OrderManager} manager - The OrderManager instance.
526
+ * @param {string} preferredSide - The side to place the correction on (ORDER_TYPES.BUY/SELL).
527
+ * @returns {Promise<import('./types').SpreadCorrectionResult>}
528
+ * @throws {Error} If preferredSide is invalid.
529
+ */
530
+ export declare function prepareSpreadCorrectionOrders(manager: any, preferredSide: any): Promise<{
531
+ ordersToPlace: any[];
532
+ ordersToUpdate: any[];
533
+ }>;
575
534
  //# sourceMappingURL=grid.d.ts.map