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