dexbot 1.6.14 → 1.6.16
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.
- package/CHANGELOG.md +60 -4
- package/README.md +4 -4
- package/analysis/README.md +6 -6
- package/analysis/tradingview/README.md +2 -1
- package/claw/README.md +7 -7
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
- package/claw/modules/chain_queries.ts +3 -3
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
- package/dist/analysis/bot_key_utils.js +9 -7
- package/dist/analysis/chart_utils.d.ts +9 -2
- package/dist/analysis/chart_utils.js +51 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
- package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
- package/dist/dexbot.js +112 -141
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
- package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
- package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
- package/dist/market_adapter/inputs/window_cache.js +53 -17
- package/dist/market_adapter/lp_chart_core.js +1 -0
- package/dist/market_adapter/utils/chain.js +4 -3
- package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
- package/dist/market_adapter/utils/pair_orientation.js +142 -0
- package/dist/modules/account_bots.d.ts +40 -3
- package/dist/modules/account_bots.js +80 -37
- package/dist/modules/account_orders.d.ts +4 -1
- package/dist/modules/account_orders.js +4 -1
- package/dist/modules/bitshares-native/resolvers.js +3 -3
- package/dist/modules/bitshares-native/subscriptions.js +1 -1
- package/dist/modules/bitshares_client.d.ts +12 -10
- package/dist/modules/bitshares_client.js +12 -10
- package/dist/modules/bot_defaults.d.ts +13 -2
- package/dist/modules/bot_defaults.js +31 -2
- package/dist/modules/bot_settings.js +6 -3
- package/dist/modules/chain_keys.d.ts +5 -1
- package/dist/modules/chain_keys.js +5 -1
- package/dist/modules/chain_orders.d.ts +6 -2
- package/dist/modules/chain_orders.js +6 -2
- package/dist/modules/constants.d.ts +11 -0
- package/dist/modules/constants.js +31 -1
- package/dist/modules/credit_runtime.d.ts +35 -5
- package/dist/modules/credit_runtime.js +219 -38
- package/dist/modules/dexbot_class.d.ts +22 -2
- package/dist/modules/dexbot_class.js +61 -21
- package/dist/modules/dexbot_cow_runtime.js +19 -18
- package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
- package/dist/modules/dexbot_fill_runtime.js +4 -7
- package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
- package/dist/modules/dexbot_maintenance_runtime.js +52 -7
- package/dist/modules/dexbot_startup_runtime.js +3 -2
- package/dist/modules/dexbot_state_recovery.js +1 -1
- package/dist/modules/graceful_shutdown.d.ts +6 -2
- package/dist/modules/graceful_shutdown.js +6 -2
- package/dist/modules/launcher/bot_supervisor.js +4 -0
- package/dist/modules/launcher/launch_modes.js +6 -3
- package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
- package/dist/modules/launcher/monolithic_runtime.js +60 -1
- package/dist/modules/launcher/runtime_mode.d.ts +79 -0
- package/dist/modules/launcher/runtime_mode.js +223 -0
- package/dist/modules/market_adapter_whitelist.d.ts +8 -0
- package/dist/modules/market_adapter_whitelist.js +8 -0
- package/dist/modules/order/accounting.d.ts +15 -1
- package/dist/modules/order/accounting.js +15 -1
- package/dist/modules/order/async_lock.d.ts +9 -3
- package/dist/modules/order/async_lock.js +9 -3
- package/dist/modules/order/export.d.ts +0 -5
- package/dist/modules/order/export.js +2 -7
- package/dist/modules/order/format.d.ts +6 -4
- package/dist/modules/order/format.js +6 -4
- package/dist/modules/order/grid.d.ts +147 -19
- package/dist/modules/order/grid.js +321 -68
- package/dist/modules/order/grid_reconcile.js +4 -3
- package/dist/modules/order/grid_reconcile_internal.js +13 -18
- package/dist/modules/order/index.d.ts +4 -2
- package/dist/modules/order/index.js +1 -1
- package/dist/modules/order/logger_state.d.ts +1 -1
- package/dist/modules/order/logger_state.js +1 -1
- package/dist/modules/order/manager.d.ts +1 -0
- package/dist/modules/order/manager.js +5 -14
- package/dist/modules/order/sync_engine.d.ts +26 -11
- package/dist/modules/order/sync_engine.js +44 -20
- package/dist/modules/order/utils/math.d.ts +157 -47
- package/dist/modules/order/utils/math.js +236 -78
- package/dist/modules/order/utils/order.d.ts +64 -20
- package/dist/modules/order/utils/order.js +80 -24
- package/dist/modules/order/utils/system.d.ts +41 -11
- package/dist/modules/order/utils/system.js +43 -13
- package/dist/modules/order/utils/validate.d.ts +6 -3
- package/dist/modules/order/utils/validate.js +53 -60
- package/dist/modules/types.d.ts +7 -0
- package/dist/modules/utils/asset_symbols.d.ts +5 -5
- package/dist/modules/utils/asset_symbols.js +5 -5
- package/dist/modules/utils/errors.d.ts +2 -1
- package/dist/modules/utils/errors.js +2 -1
- package/dist/scripts/analyze-credit.js +44 -27
- package/dist/scripts/diagnose-pool-history.js +35 -30
- package/dist/scripts/pnl.js +1 -1
- package/dist/scripts/rich_list.d.ts +50 -0
- package/dist/scripts/rich_list.js +469 -0
- package/dist/scripts/run-tests.js +80 -4
- package/dist/unlock.d.ts +2 -1
- package/dist/unlock.js +53 -21
- package/docs/BITSHARES_ONBOARDING.md +7 -0
- package/docs/COW_INVARIANTS.md +7 -1
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +11 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
- package/docs/GRID_RECALCULATION.md +18 -6
- package/docs/LIFECYCLE.md +8 -8
- package/docs/LOGGING.md +16 -1
- package/docs/MPA_CREDIT_USAGE.md +10 -5
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +6 -5
- package/docs/architecture.md +56 -2
- package/docs/developer_guide.md +5 -1
- package/market_adapter/README.md +14 -7
- package/modules/README.md +1 -1
- package/package.json +4 -1
- package/scripts/README.md +59 -32
- package/tests/README.md +40 -2
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* - Detects and flags out-of-spread conditions
|
|
13
13
|
*
|
|
14
14
|
* ===============================================================================
|
|
15
|
-
* TABLE OF CONTENTS - Grid Functions (
|
|
15
|
+
* TABLE OF CONTENTS - Grid Functions (34 exports)
|
|
16
16
|
* ===============================================================================
|
|
17
17
|
*
|
|
18
18
|
* CONFIGURATION & CALCULATION (2 functions)
|
|
@@ -37,36 +37,49 @@
|
|
|
37
37
|
* GRID STATE CHECKING (2 functions)
|
|
38
38
|
* 8. checkAndUpdateGridIfNeeded(manager) - Complete fund trigger: available-
|
|
39
39
|
* funds ratio + over-allocation + on-chain committed-drift legs
|
|
40
|
-
*
|
|
40
|
+
* 9. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
|
|
41
41
|
* (the drift core is folded into checkAndUpdateGridIfNeeded)
|
|
42
42
|
*
|
|
43
43
|
* BLOCKCHAIN SYNCHRONIZATION (2 functions - async)
|
|
44
|
-
*
|
|
45
|
-
*
|
|
44
|
+
* 10. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
|
|
45
|
+
* 11. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer, overrideBoundaryIdx) - Update grid from blockchain
|
|
46
46
|
*
|
|
47
47
|
* GRID COMPARISON (2 functions - async)
|
|
48
|
-
*
|
|
48
|
+
* 12. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
|
|
49
49
|
* Validates grid structure and reports divergence metrics
|
|
50
|
-
*
|
|
50
|
+
* 13. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
|
|
51
51
|
* Runs ratio-based + RMS-based checks and returns combined result
|
|
52
52
|
*
|
|
53
53
|
* SPREAD MANAGEMENT (2 functions)
|
|
54
|
-
*
|
|
55
|
-
*
|
|
54
|
+
* 14. calculateCurrentSpread(manager) - Calculate current bid-ask spread
|
|
55
|
+
* 15. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
|
|
56
56
|
*
|
|
57
57
|
* GRID HEALTH MONITORING (4 functions)
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
58
|
+
* 16. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health
|
|
59
|
+
* 17. checkWindowDust(manager) - Dust check scoped to the active buy/sell window
|
|
60
|
+
* 18. hasAnyDust(manager, partials, side) - Check for dust orders
|
|
61
|
+
* 19. getDustOrders(manager, partials, side) - Get dust order IDs
|
|
62
62
|
*
|
|
63
63
|
* SIDE SELECTION (1 function)
|
|
64
|
-
*
|
|
64
|
+
* 20. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
|
|
65
|
+
*
|
|
66
|
+
* SPREAD CORRECTION PLANNING (11 exports)
|
|
67
|
+
* 21. SPREAD_CORRECTION_REFUSAL - Refusal-cause vocabulary constant
|
|
68
|
+
* 22. SpreadCorrectionRefusalCause - Refusal-cause union type
|
|
69
|
+
* 23. isTransientSpreadRefusal(cause) - Whether a refusal cause is retryable
|
|
70
|
+
* 24. classifySpreadRefusalCause(...) - Classify why a correction batch did not land
|
|
71
|
+
* 25. recordSpreadCorrectionRefusal(...) - Record a refusal on the manager
|
|
72
|
+
* 26. recordSpreadCorrectionRetry(...) - Count a bounded re-plan retry
|
|
73
|
+
* 27. getOccupiedCorrectionSlots(...) - Planned CREATE destinations already occupied
|
|
74
|
+
* 28. replanSpreadCorrectionFromFreshMaster(...) - Re-plan from the current master
|
|
75
|
+
* 29. OccupiedCorrectionResolution - Outcome of plan-time collision resolution
|
|
76
|
+
* 30. resolveOccupiedCorrection(...) - Resolve a correction whose destination was taken
|
|
77
|
+
* 31. prepareSpreadCorrectionOrders(...) - Prepare orders to correct a wide spread
|
|
65
78
|
*
|
|
66
79
|
* BLOAT STATUS (3 functions)
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
80
|
+
* 32. isGridBloated(manager, orders) - Check whether the grid is bloated
|
|
81
|
+
* 33. isGridBloatGraceActive(manager) - Check the bloat grace state
|
|
82
|
+
* 34. clearGridBloatFlag(manager) - Clear the bloat state
|
|
70
83
|
*
|
|
71
84
|
* ===============================================================================
|
|
72
85
|
*
|
|
@@ -121,6 +134,193 @@ function classifySpreadStall(c) {
|
|
|
121
134
|
return hint;
|
|
122
135
|
return 'no-candidates';
|
|
123
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Spread-correction refusal causes — the single vocabulary shared by
|
|
139
|
+
* classifySpreadRefusalCause, the retry/transience decision and the
|
|
140
|
+
* spreadCorrectionRefusalCauses metric key. Keep every reader/writer keyed off
|
|
141
|
+
* this map so a new cause cannot leave classification and transience out of
|
|
142
|
+
* sync.
|
|
143
|
+
*/
|
|
144
|
+
export const SPREAD_CORRECTION_REFUSAL = Object.freeze({
|
|
145
|
+
/** Post-broadcast working-grid commit rejected (orders may already be on chain). */
|
|
146
|
+
COMMIT_REFUSED: 'commit-refused',
|
|
147
|
+
/** Plan went stale / skipped before broadcast (base-version mismatch). */
|
|
148
|
+
VERSION_MISMATCH: 'version-mismatch',
|
|
149
|
+
/** A tracked UPDATE target was gone on chain (COW pre-broadcast guard). */
|
|
150
|
+
UPDATE_TARGET_MISSING: 'update-target-missing',
|
|
151
|
+
/** Destination slot already held an active order (plan-time dedupe). */
|
|
152
|
+
CREATE_COLLISION: 'create-collision',
|
|
153
|
+
/** Unmatched chain orders blocked the CREATE batch. */
|
|
154
|
+
UNMATCHED_CHAIN_ORDERS: 'unmatched-chain-orders',
|
|
155
|
+
/** Shutdown began while the batch was in flight. */
|
|
156
|
+
SHUTDOWN: 'shutdown',
|
|
157
|
+
/** Unclassified non-execution (fallback). */
|
|
158
|
+
BATCH_NOT_EXECUTED: 'batch-not-executed'
|
|
159
|
+
});
|
|
160
|
+
/**
|
|
161
|
+
* Causes the bounded in-cycle re-plan can heal. `commit-refused` is deliberately
|
|
162
|
+
* EXCLUDED: the batch reached the chain (chain adoption runs), so it is not a
|
|
163
|
+
* clean pre-broadcast staleness a fresh-master re-plan repairs — it should count
|
|
164
|
+
* toward the persistent-stale watchdog instead.
|
|
165
|
+
*/
|
|
166
|
+
const TRANSIENT_SPREAD_CORRECTION_REFUSALS = new Set([
|
|
167
|
+
SPREAD_CORRECTION_REFUSAL.VERSION_MISMATCH,
|
|
168
|
+
SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION,
|
|
169
|
+
SPREAD_CORRECTION_REFUSAL.BATCH_NOT_EXECUTED
|
|
170
|
+
]);
|
|
171
|
+
/**
|
|
172
|
+
* Whether a refusal cause is retryable by the bounded spread-correction re-plan.
|
|
173
|
+
* @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
|
|
174
|
+
* @returns {boolean}
|
|
175
|
+
*/
|
|
176
|
+
export function isTransientSpreadRefusal(cause) {
|
|
177
|
+
return TRANSIENT_SPREAD_CORRECTION_REFUSALS.has(cause);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* P0 observability: classify WHY a spread-correction batch did not land
|
|
181
|
+
* (executed !== true) from the COW batch result. Counter-only — never gates
|
|
182
|
+
* placement. Returns a SPREAD_CORRECTION_REFUSAL value so the metric key, the
|
|
183
|
+
* retry decision and the log all share one vocabulary.
|
|
184
|
+
* @param {Object|null} batchResult - The COW batch result
|
|
185
|
+
* @returns {string} A SPREAD_CORRECTION_REFUSAL value
|
|
186
|
+
*/
|
|
187
|
+
export function classifySpreadRefusalCause(batchResult) {
|
|
188
|
+
const r = (batchResult ?? {});
|
|
189
|
+
const reason = String(r.reason ?? '').toUpperCase();
|
|
190
|
+
if (r.commitRefused === true)
|
|
191
|
+
return SPREAD_CORRECTION_REFUSAL.COMMIT_REFUSED;
|
|
192
|
+
if (reason === 'UPDATE_TARGET_MISSING')
|
|
193
|
+
return SPREAD_CORRECTION_REFUSAL.UPDATE_TARGET_MISSING;
|
|
194
|
+
if (reason === 'UNMATCHED_CHAIN_ORDERS')
|
|
195
|
+
return SPREAD_CORRECTION_REFUSAL.UNMATCHED_CHAIN_ORDERS;
|
|
196
|
+
if (reason === 'SHUTDOWN_IN_PROGRESS')
|
|
197
|
+
return SPREAD_CORRECTION_REFUSAL.SHUTDOWN;
|
|
198
|
+
if (r.skippedStalePlan === true || reason.includes('STALE') || reason.includes('MISMATCH') || reason.includes('BASE VERSION'))
|
|
199
|
+
return SPREAD_CORRECTION_REFUSAL.VERSION_MISMATCH;
|
|
200
|
+
if (reason.includes('COLLISION') || reason.includes('EXISTING') || reason.includes('DUPLICATE'))
|
|
201
|
+
return SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION;
|
|
202
|
+
return SPREAD_CORRECTION_REFUSAL.BATCH_NOT_EXECUTED;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* P0 observability: record a spread-correction refusal on the manager's
|
|
206
|
+
* metrics (the only object reachable from this planner; getMetrics overlays
|
|
207
|
+
* these onto the bot's counters). Counter-only; never throws, never gates.
|
|
208
|
+
* @param {Object} manager - OrderManager instance
|
|
209
|
+
* @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
|
|
210
|
+
*/
|
|
211
|
+
export function recordSpreadCorrectionRefusal(manager, cause) {
|
|
212
|
+
try {
|
|
213
|
+
const m = manager?._metrics;
|
|
214
|
+
if (!m)
|
|
215
|
+
return;
|
|
216
|
+
m.spreadCorrectionRefusedCount = (Number(m.spreadCorrectionRefusedCount) || 0) + 1;
|
|
217
|
+
const causes = (m.spreadCorrectionRefusalCauses && typeof m.spreadCorrectionRefusalCauses === 'object')
|
|
218
|
+
? m.spreadCorrectionRefusalCauses
|
|
219
|
+
: (m.spreadCorrectionRefusalCauses = {});
|
|
220
|
+
causes[cause] = (Number(causes[cause]) || 0) + 1;
|
|
221
|
+
}
|
|
222
|
+
catch { /* metrics are best-effort */ }
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* P5 observability: count a bounded spread-correction re-plan retry. Churn
|
|
226
|
+
* signal — a rising retry rate means concurrent commits are repeatedly
|
|
227
|
+
* invalidating corrections. Counter-only; never throws.
|
|
228
|
+
* @param {Object} manager - OrderManager instance
|
|
229
|
+
*/
|
|
230
|
+
export function recordSpreadCorrectionRetry(manager) {
|
|
231
|
+
try {
|
|
232
|
+
const m = manager?._metrics;
|
|
233
|
+
if (!m)
|
|
234
|
+
return;
|
|
235
|
+
m.spreadCorrectionRetryCount = (Number(m.spreadCorrectionRetryCount) || 0) + 1;
|
|
236
|
+
}
|
|
237
|
+
catch { /* metrics are best-effort */ }
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* P2 plan-time dedupe: which of a correction's planned CREATE destinations are
|
|
241
|
+
* now occupied by a live (ACTIVE/PARTIAL) order with a chain id?
|
|
242
|
+
*
|
|
243
|
+
* The correction is planned under _gridLock, then broadcast after the lock is
|
|
244
|
+
* released. A concurrent fill rebalance can commit an order onto one of the
|
|
245
|
+
* planned slots in that window; the COW build layer then rejects the whole
|
|
246
|
+
* batch (`Rejecting CREATE … existing orderId`). Detecting it here turns that
|
|
247
|
+
* into a cheap plan-time re-derive (see the retry loop in checkSpreadCondition)
|
|
248
|
+
* instead of a mid-broadcast refusal and structural resync.
|
|
249
|
+
*
|
|
250
|
+
* Pure and never throws. A missing/non-Map orders store selects the empty set.
|
|
251
|
+
* @param {Object} manager - OrderManager instance
|
|
252
|
+
* @param {Object|null} correction - Prepared spread correction
|
|
253
|
+
* @returns {string[]} Occupied planned slot ids
|
|
254
|
+
*/
|
|
255
|
+
export function getOccupiedCorrectionSlots(manager, correction) {
|
|
256
|
+
const occupied = [];
|
|
257
|
+
try {
|
|
258
|
+
const orders = manager.orders;
|
|
259
|
+
if (!(orders instanceof Map) || !correction)
|
|
260
|
+
return occupied;
|
|
261
|
+
for (const o of correction.ordersToPlace || []) {
|
|
262
|
+
const cur = orders.get(o.id);
|
|
263
|
+
if (!cur)
|
|
264
|
+
continue;
|
|
265
|
+
const liveState = cur.state === ORDER_STATES.ACTIVE || cur.state === ORDER_STATES.PARTIAL;
|
|
266
|
+
if (liveState && cur.orderId)
|
|
267
|
+
occupied.push(o.id);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
catch { /* best-effort detection */ }
|
|
271
|
+
return occupied;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* P1/P3 shared re-plan: derive a spread correction from the CURRENT master
|
|
275
|
+
* state (side chosen from fresh on-chain book, opposite-side starvation
|
|
276
|
+
* fallback). Used both for the plan-time collision dedupe and the bounded
|
|
277
|
+
* refusal retry. Read-only against the grid; no _gridLock needed (matches the
|
|
278
|
+
* existing TOCTOU fund re-plan contract).
|
|
279
|
+
* @param {Object} manager - OrderManager instance
|
|
280
|
+
* @returns {Promise<Object|null>} A correction with at least one create, or null
|
|
281
|
+
*/
|
|
282
|
+
export async function replanSpreadCorrectionFromFreshMaster(manager) {
|
|
283
|
+
const freshOnChain = _getOnChainOrders(manager);
|
|
284
|
+
const freshBest = getGridBestPrices(freshOnChain.onChainBuys, freshOnChain.onChainSells);
|
|
285
|
+
const freshPrice = (freshBest.bestBuy !== null && freshBest.bestSell !== null)
|
|
286
|
+
? (freshBest.bestBuy + freshBest.bestSell) / 2
|
|
287
|
+
: Number(manager.config.startPrice) || 0;
|
|
288
|
+
const decision = determineOrderSideByFunds(manager, freshPrice);
|
|
289
|
+
if (!decision.side)
|
|
290
|
+
return null;
|
|
291
|
+
let c = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
|
|
292
|
+
if ((c?.ordersToPlace?.length || 0) === 0) {
|
|
293
|
+
const opposite = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
|
|
294
|
+
const oc = await prepareSpreadCorrectionOrders(manager, opposite, manager.outOfSpread);
|
|
295
|
+
if ((oc?.ordersToPlace?.length || 0) > 0)
|
|
296
|
+
c = oc;
|
|
297
|
+
}
|
|
298
|
+
return c;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* P2: resolve a planned correction whose CREATE destination(s) were taken after
|
|
302
|
+
* planning. Detects the collision, re-derives once from fresh master, and
|
|
303
|
+
* reports whether the caller should broadcast, swap in the re-plan, or refuse.
|
|
304
|
+
*
|
|
305
|
+
* Extracted from checkSpreadCondition so the branch is a real, production-called
|
|
306
|
+
* unit that tests can drive directly (no test-only hook in the production path).
|
|
307
|
+
*
|
|
308
|
+
* @param {Object} manager - OrderManager instance
|
|
309
|
+
* @param {Object|null} correction - The plan about to broadcast
|
|
310
|
+
* @param {number} attempt - 1-based attempt index
|
|
311
|
+
* @param {number} maxAttempts - Total attempts allowed
|
|
312
|
+
* @returns {Promise<OccupiedCorrectionResolution>}
|
|
313
|
+
*/
|
|
314
|
+
export async function resolveOccupiedCorrection(manager, correction, attempt, maxAttempts) {
|
|
315
|
+
const occupied = getOccupiedCorrectionSlots(manager, correction);
|
|
316
|
+
if (!(occupied.length > 0 && attempt < maxAttempts))
|
|
317
|
+
return { action: 'broadcast' };
|
|
318
|
+
const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
|
|
319
|
+
if (replanned && (replanned.ordersToPlace?.length || 0) > 0) {
|
|
320
|
+
return { action: 'replanned', correction: replanned, occupied };
|
|
321
|
+
}
|
|
322
|
+
return { action: 'blocked', occupied };
|
|
323
|
+
}
|
|
124
324
|
/**
|
|
125
325
|
* Central resolution for the RMS structural-divergence threshold (percent).
|
|
126
326
|
* Single source of truth: per-bot override wins, global GRID_COMPARISON default
|
|
@@ -141,7 +341,7 @@ function _snapshotFundState(manager) {
|
|
|
141
341
|
sellLocked: Number(manager.accountTotals?.sellLocked || 0),
|
|
142
342
|
};
|
|
143
343
|
}
|
|
144
|
-
import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots,
|
|
344
|
+
import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, pricesOnSameLevel, sameGridLevel, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
|
|
145
345
|
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
|
|
146
346
|
import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice } from './utils/system.js';
|
|
147
347
|
import * as MathUtils from './utils/math.js';
|
|
@@ -660,7 +860,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
|
|
|
660
860
|
// band, GAP-EVAC already tracking it): keep the boundary so
|
|
661
861
|
// the heal path (rotation/teeth/sweeps) can run. Nuking it
|
|
662
862
|
// here would discard the evacuation state for exactly the
|
|
663
|
-
// condition evacuation exists to fix (
|
|
863
|
+
// condition evacuation exists to fix (<bot> 2026-09-13).
|
|
664
864
|
manager.logger?.log?.(`[GRID-LOAD] Persisted snapshot has transient in-band placement (${check.reason}): ${check.detail}. ` +
|
|
665
865
|
`Keeping boundary ${restoredBoundary}; GAP-EVAC/sync sweeps own cleanup.`, 'warn');
|
|
666
866
|
}
|
|
@@ -2191,8 +2391,6 @@ export function calculateCurrentSpread(manager) {
|
|
|
2191
2391
|
* - RACE CONDITION WINDOW: Between lock release and blockchain submission
|
|
2192
2392
|
* - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
|
|
2193
2393
|
*
|
|
2194
|
-
* See RACE_CONDITION_ANALYSIS.md for detailed vulnerability documentation.
|
|
2195
|
-
*
|
|
2196
2394
|
* @param {import('./types').OrderManager} manager - Manager instance
|
|
2197
2395
|
* @param {Object} BitShares - BitShares API client
|
|
2198
2396
|
* @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
|
|
@@ -2404,12 +2602,15 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2404
2602
|
// Pre-flight fund verification mitigates TOCTOU between lock release and broadcast.
|
|
2405
2603
|
if (shouldApplyCorrection && updateOrdersOnChainBatch && correction && fundSnapshot) {
|
|
2406
2604
|
let activeCorrection = correction;
|
|
2407
|
-
|
|
2605
|
+
// Explicit non-null alias: fundSnapshot is assigned inside the
|
|
2606
|
+
// executeSpreadCheck closure, so TS control-flow cannot prove it
|
|
2607
|
+
// non-null here even though the guard above checked it.
|
|
2608
|
+
const baseFundSnapshot = fundSnapshot;
|
|
2408
2609
|
const currentFunds = _snapshotFundState(manager);
|
|
2409
|
-
const fundChanged =
|
|
2410
|
-
||
|
|
2411
|
-
||
|
|
2412
|
-
||
|
|
2610
|
+
const fundChanged = baseFundSnapshot.buyFree !== currentFunds.buyFree
|
|
2611
|
+
|| baseFundSnapshot.sellFree !== currentFunds.sellFree
|
|
2612
|
+
|| baseFundSnapshot.buyLocked !== currentFunds.buyLocked
|
|
2613
|
+
|| baseFundSnapshot.sellLocked !== currentFunds.sellLocked;
|
|
2413
2614
|
if (fundChanged) {
|
|
2414
2615
|
// TOCTOU: fund state changed between lock release and broadcast.
|
|
2415
2616
|
// Lock-free re-plan — no _gridLock needed because the fund read
|
|
@@ -2436,7 +2637,6 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2436
2637
|
const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
|
|
2437
2638
|
if (rePlanCorrection && (rePlanCorrection.ordersToPlace?.length || 0) > 0) {
|
|
2438
2639
|
activeCorrection = rePlanCorrection;
|
|
2439
|
-
activeSnapshot = currentFunds;
|
|
2440
2640
|
manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
|
|
2441
2641
|
`re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates`, 'info');
|
|
2442
2642
|
}
|
|
@@ -2450,23 +2650,86 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2450
2650
|
return { ordersPlaced: 0, partialsMoved: 0, stall };
|
|
2451
2651
|
}
|
|
2452
2652
|
}
|
|
2653
|
+
// P1: hold the broadcast/placement region across the whole attempt
|
|
2654
|
+
// loop (re-plan + broadcast). A defer-if-broadcasting fill rebalance
|
|
2655
|
+
// yields while this region is held, and a waiting one parks on
|
|
2656
|
+
// _awaitBroadcastIdle, so a concurrent commit is far less likely to
|
|
2657
|
+
// bump master between this correction's plan and its broadcast — the
|
|
2658
|
+
// race that made the commit guard refuse the batch. This narrows the
|
|
2659
|
+
// window rather than closing it absolutely (the idle wait is bounded
|
|
2660
|
+
// and proceeds on timeout), so the commit guard stays the backstop
|
|
2661
|
+
// and the retry below re-plans from fresh master. The COW batch
|
|
2662
|
+
// refcounts the region internally; this is the outer holder.
|
|
2663
|
+
const MAX_SPREAD_ATTEMPTS = Number(TIMING?.SPREAD_CORRECTION_MAX_ATTEMPTS) > 0
|
|
2664
|
+
? Number(TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS)
|
|
2665
|
+
: 2;
|
|
2666
|
+
let attempts = 0;
|
|
2667
|
+
// Whether the most recent refusal is retryable — reported to the P4
|
|
2668
|
+
// watchdog so a non-transient cause (commit-refused /
|
|
2669
|
+
// update-target-missing) counts toward staleness instead of being
|
|
2670
|
+
// waved through as a retry. Defaults to transient for the P2
|
|
2671
|
+
// collision-blocked path, which has no batch result.
|
|
2672
|
+
let lastTransient = true;
|
|
2673
|
+
let lastResult = null;
|
|
2674
|
+
const canHoldRegion = typeof manager.startBroadcasting === 'function'
|
|
2675
|
+
&& typeof manager.stopBroadcasting === 'function';
|
|
2676
|
+
if (canHoldRegion)
|
|
2677
|
+
manager.startBroadcasting();
|
|
2453
2678
|
try {
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
//
|
|
2458
|
-
//
|
|
2459
|
-
|
|
2460
|
-
|
|
2679
|
+
while (attempts < MAX_SPREAD_ATTEMPTS) {
|
|
2680
|
+
attempts++;
|
|
2681
|
+
// P2: before broadcasting, detect a planned CREATE whose
|
|
2682
|
+
// destination was taken by a competing batch after planning,
|
|
2683
|
+
// and re-derive instead of shipping a known collision.
|
|
2684
|
+
const resolution = await resolveOccupiedCorrection(manager, activeCorrection, attempts, MAX_SPREAD_ATTEMPTS);
|
|
2685
|
+
if (resolution.action !== 'broadcast') {
|
|
2686
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Plan-time dedupe: ${resolution.occupied.length} planned slot(s) occupied since planning ` +
|
|
2687
|
+
`(${resolution.occupied.slice(0, 8).join(', ')}${resolution.occupied.length > 8 ? ', …' : ''}); ` +
|
|
2688
|
+
(resolution.action === 'replanned' ? 're-planning from fresh master' : 'no re-plan candidate — refusing this cycle'), 'warn');
|
|
2689
|
+
recordSpreadCorrectionRefusal(manager, SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION);
|
|
2690
|
+
if (resolution.action === 'replanned') {
|
|
2691
|
+
recordSpreadCorrectionRetry(manager);
|
|
2692
|
+
activeCorrection = resolution.correction;
|
|
2693
|
+
continue;
|
|
2694
|
+
}
|
|
2695
|
+
break;
|
|
2696
|
+
}
|
|
2697
|
+
const batchResult = await updateOrdersOnChainBatch(activeCorrection);
|
|
2698
|
+
lastResult = batchResult ?? null;
|
|
2699
|
+
if (batchResult && batchResult.executed === true) {
|
|
2700
|
+
await manager.recalculateFunds();
|
|
2701
|
+
const placed = activeCorrection.ordersToPlace?.length || 0;
|
|
2702
|
+
return { ordersPlaced: placed, partialsMoved: 0 };
|
|
2703
|
+
}
|
|
2704
|
+
const cause = classifySpreadRefusalCause(batchResult);
|
|
2705
|
+
recordSpreadCorrectionRefusal(manager, cause);
|
|
2706
|
+
const transient = isTransientSpreadRefusal(cause);
|
|
2707
|
+
lastTransient = transient;
|
|
2708
|
+
if (!transient || attempts >= MAX_SPREAD_ATTEMPTS)
|
|
2709
|
+
break;
|
|
2710
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Batch refused (${cause}); re-planning from fresh master ` +
|
|
2711
|
+
`(attempt ${attempts + 1}/${MAX_SPREAD_ATTEMPTS})`, 'warn');
|
|
2712
|
+
const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
|
|
2713
|
+
if (!replanned || (replanned.ordersToPlace?.length || 0) === 0)
|
|
2714
|
+
break;
|
|
2715
|
+
recordSpreadCorrectionRetry(manager);
|
|
2716
|
+
activeCorrection = replanned;
|
|
2461
2717
|
}
|
|
2462
|
-
await manager.recalculateFunds();
|
|
2463
|
-
const placed = activeCorrection.ordersToPlace?.length || 0;
|
|
2464
|
-
return { ordersPlaced: placed, partialsMoved: 0 };
|
|
2465
2718
|
}
|
|
2466
2719
|
catch (err) {
|
|
2467
2720
|
manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
|
|
2468
2721
|
return { ordersPlaced: 0, partialsMoved: 0, stall: 'apply-error' };
|
|
2469
2722
|
}
|
|
2723
|
+
finally {
|
|
2724
|
+
if (canHoldRegion)
|
|
2725
|
+
manager.stopBroadcasting();
|
|
2726
|
+
}
|
|
2727
|
+
manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.` +
|
|
2728
|
+
(lastResult ? ` (cause=${classifySpreadRefusalCause(lastResult)})` : ''), 'warn');
|
|
2729
|
+
// Retryable only when the last refusal cause was transient; a
|
|
2730
|
+
// commit-refused / update-target-missing / unmatched / shutdown
|
|
2731
|
+
// refusal counts toward the persistent-stale watchdog.
|
|
2732
|
+
return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed', transient: lastTransient };
|
|
2470
2733
|
}
|
|
2471
2734
|
return { ordersPlaced: 0, partialsMoved: 0, stall };
|
|
2472
2735
|
}
|
|
@@ -2533,26 +2796,24 @@ export async function checkWindowDust(manager) {
|
|
|
2533
2796
|
const topSellOrder = allOrders
|
|
2534
2797
|
.filter((o) => o.type === ORDER_TYPES.SELL && isLiveOrder(o))
|
|
2535
2798
|
.sort((a, b) => a.price - b.price)[0];
|
|
2536
|
-
// Check if an order has a duplicate
|
|
2537
|
-
|
|
2538
|
-
|
|
2799
|
+
// Check if an order has a duplicate price level — an active sibling at
|
|
2800
|
+
// the same ladder level. If so, cancelling won't create a grid gap.
|
|
2801
|
+
// Only checks ACTIVE siblings. If two PARTIALs share a price with no active
|
|
2802
|
+
// sibling, neither qualifies and the gap is left to the rebalancer.
|
|
2803
|
+
// Grid-vs-grid: resolve both prices to their frozen ladder level
|
|
2804
|
+
// (genesis-aware), NOT priceSlotEqual at the asset precision (collapses
|
|
2805
|
+
// adjacent levels for a low-precision asset).
|
|
2806
|
+
const hasDuplicatePriceLevel = (order) => {
|
|
2539
2807
|
for (const o of allOrders) {
|
|
2540
2808
|
if (o.id === order.id)
|
|
2541
2809
|
continue;
|
|
2542
2810
|
if (o.type !== order.type || o.state !== ORDER_STATES.ACTIVE || !o.orderId || o.price == null)
|
|
2543
2811
|
continue;
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
return true;
|
|
2547
|
-
}
|
|
2548
|
-
catch {
|
|
2549
|
-
if (o.price === order.price)
|
|
2550
|
-
return true;
|
|
2551
|
-
}
|
|
2812
|
+
if (sameGridLevel(o.price, order.price, manager._genesis))
|
|
2813
|
+
return true;
|
|
2552
2814
|
}
|
|
2553
2815
|
return false;
|
|
2554
2816
|
};
|
|
2555
|
-
const assets = manager.assets;
|
|
2556
2817
|
const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === ORDER_STATES.PARTIAL);
|
|
2557
2818
|
const isTopBuy = (o) => !!(topBuyOrder && o.id === topBuyOrder.id);
|
|
2558
2819
|
const isTopSell = (o) => !!(topSellOrder && o.id === topSellOrder.id);
|
|
@@ -2583,8 +2844,8 @@ export async function checkWindowDust(manager) {
|
|
|
2583
2844
|
// only cancels zero-value residuals, and an interior dust rarely has a
|
|
2584
2845
|
// duplicate price level. Cancelling it frees the slot for rotation to
|
|
2585
2846
|
// re-derive, so the tiny gap is closed by normal grid rebalancing.
|
|
2586
|
-
const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o
|
|
2587
|
-
const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o
|
|
2847
|
+
const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o) || isDustSized(o, buyThresholds)));
|
|
2848
|
+
const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o) || isDustSized(o, sellThresholds)));
|
|
2588
2849
|
const buyDustOrders = await _getDustOrders(manager, eligibleBuyPartials, ORDER_TYPES.BUY, buyThresholds);
|
|
2589
2850
|
const sellDustOrders = await _getDustOrders(manager, eligibleSellPartials, ORDER_TYPES.SELL, sellThresholds);
|
|
2590
2851
|
return {
|
|
@@ -3019,15 +3280,10 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3019
3280
|
const doesNotCollideUnmatched = (c) => {
|
|
3020
3281
|
if (unmatchedPrices.length === 0 || c?.price == null || !Number.isFinite(c.price))
|
|
3021
3282
|
return true;
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
}
|
|
3027
|
-
catch {
|
|
3028
|
-
return Math.abs(p - c.price) / c.price <= ((manager.config.incrementPercent ?? 0) / 100);
|
|
3029
|
-
}
|
|
3030
|
-
});
|
|
3283
|
+
// The unmatched row carries only a price; use the candidate's own
|
|
3284
|
+
// side/size for the tolerance. Tolerance-based, NOT priceSlotEqual at
|
|
3285
|
+
// the asset precision (low-precision assets collapse adjacent levels).
|
|
3286
|
+
return !unmatchedPrices.some((p) => pricesOnSameLevel(p, c.size, railType, c.price, c.size, railType, manager.assets, manager.config?.incrementPercent));
|
|
3031
3287
|
};
|
|
3032
3288
|
if (unmatchedPrices.length > 0) {
|
|
3033
3289
|
manager.logger?.log?.(`[SPREAD-CORRECTION] ${unmatchedPrices.length} known-unmatched chain price level(s) excluded from ${sideName} candidates — sync will adopt them first`, 'warn');
|
|
@@ -3204,20 +3460,17 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3204
3460
|
spreadCandidates = spreadCandidates.filter((c) => {
|
|
3205
3461
|
if (c.price == null)
|
|
3206
3462
|
return false;
|
|
3207
|
-
|
|
3463
|
+
// Grid-vs-grid: resolve both prices to their frozen ladder
|
|
3464
|
+
// level (genesis-aware), NOT priceSlotEqual at the asset
|
|
3465
|
+
// precision and NOT the chain tolerance (both can
|
|
3466
|
+
// collapse/merge adjacent grid levels).
|
|
3208
3467
|
for (const o of allOrders) {
|
|
3209
3468
|
if (!isOrderPlaced(o) || o.price == null)
|
|
3210
3469
|
continue;
|
|
3211
3470
|
if (o.id === c.id)
|
|
3212
3471
|
continue;
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
return false;
|
|
3216
|
-
}
|
|
3217
|
-
catch {
|
|
3218
|
-
if (o.price === c.price)
|
|
3219
|
-
return false;
|
|
3220
|
-
}
|
|
3472
|
+
if (sameGridLevel(o.price, c.price, manager._genesis))
|
|
3473
|
+
return false;
|
|
3221
3474
|
}
|
|
3222
3475
|
return true;
|
|
3223
3476
|
});
|
|
@@ -3,7 +3,7 @@ const require = createRequire(import.meta.url);
|
|
|
3
3
|
import { _countActiveOnGrid, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executePlannedStartupCreates, _reconcileStartupSide, } from './grid_reconcile_internal.js';
|
|
4
4
|
import { ORDER_TYPES, ORDER_STATES, TIMING } from '../constants.js';
|
|
5
5
|
import { readOpenOrdersGuarded } from '../chain_orders.js';
|
|
6
|
-
import { getAssetFeesSafe,
|
|
6
|
+
import { getAssetFeesSafe, pricesOnSameLevel } from './utils/math.js';
|
|
7
7
|
import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, } from './utils/order.js';
|
|
8
8
|
import * as Format from './format.js';
|
|
9
9
|
import { getErrorMessage } from '../utils/errors.js';
|
|
@@ -251,8 +251,9 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
|
|
|
251
251
|
for (const gridOrder of activeGridOrders) {
|
|
252
252
|
if (gridOrder.type !== p.type)
|
|
253
253
|
continue;
|
|
254
|
-
|
|
255
|
-
|
|
254
|
+
// Tolerance-based level check, NOT priceSlotEqual at the asset
|
|
255
|
+
// precision (a low-precision asset collapses adjacent levels).
|
|
256
|
+
const isEqual = pricesOnSameLevel(p.price, p.size ?? 0, p.type, gridOrder.price, gridOrder.size, gridOrder.type, manager.assets, manager.config?.incrementPercent);
|
|
256
257
|
const priceDiff = Math.abs(p.price - gridOrder.price);
|
|
257
258
|
const candidate = { gridOrder, priceDiff, isEqual };
|
|
258
259
|
if (!nearest || priceDiff < nearest.priceDiff)
|
|
@@ -6,17 +6,22 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { ORDER_TYPES, ORDER_STATES, TIMING, BTS_PRECISION } from '../constants.js';
|
|
8
8
|
import { readOpenOrdersGuarded } from '../chain_orders.js';
|
|
9
|
-
import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail,
|
|
9
|
+
import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, sameGridLevel } from './utils/math.js';
|
|
10
10
|
import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge, parseSlotIndex, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
|
|
11
11
|
import { resolveAccountRef } from './utils/system.js';
|
|
12
12
|
import * as Format from './format.js';
|
|
13
13
|
import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
|
|
14
14
|
function computePlacementPriceCollision(manager, gridOrder) {
|
|
15
|
-
|
|
15
|
+
// Grid-vs-grid: resolve each price to its frozen ladder level. NOT
|
|
16
|
+
// priceSlotEqual at the asset precision, which rounds a price through an
|
|
17
|
+
// asset AMOUNT precision and collapses an adjacent band for a
|
|
18
|
+
// low-precision asset (0.000318 and 0.000319 both -> 3 at precision 4,
|
|
19
|
+
// silently dropping every buy after the first). NOT the chain tolerance
|
|
20
|
+
// either: it can exceed the grid increment and merge adjacent levels.
|
|
16
21
|
for (const o of manager.orders.values()) {
|
|
17
22
|
if (!isOrderPlaced(o) || o.id === gridOrder.id)
|
|
18
23
|
continue;
|
|
19
|
-
if (
|
|
24
|
+
if (sameGridLevel(o.price, gridOrder.price, manager._genesis))
|
|
20
25
|
return o;
|
|
21
26
|
}
|
|
22
27
|
return null;
|
|
@@ -1463,7 +1468,6 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1463
1468
|
if (!Number.isFinite(Number(chainPrice)))
|
|
1464
1469
|
return;
|
|
1465
1470
|
const chainPriceNum = Number(chainPrice);
|
|
1466
|
-
const sidePrecision = orderType === ORDER_TYPES.SELL ? manager.assets?.assetA?.precision : manager.assets?.assetB?.precision;
|
|
1467
1471
|
for (const slotOrder of manager.orders.values()) {
|
|
1468
1472
|
if (!slotOrder || !slotOrder.id)
|
|
1469
1473
|
continue;
|
|
@@ -1487,7 +1491,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1487
1491
|
continue;
|
|
1488
1492
|
if (Number(slotOrder.size) <= 0)
|
|
1489
1493
|
continue;
|
|
1490
|
-
if (!
|
|
1494
|
+
if (!pricesOnSameLevel(slotOrder.price, slotOrder.size, orderType, chainPriceNum, slotOrder.size, orderType, manager.assets, manager.config?.incrementPercent))
|
|
1491
1495
|
continue;
|
|
1492
1496
|
vacatedRefillPlanned.add(slotOrder.id);
|
|
1493
1497
|
refillCandidates.push(slotOrder);
|
|
@@ -1638,29 +1642,20 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1638
1642
|
// Edge ladder: edge-priced orphans cancel last (they are adoption
|
|
1639
1643
|
// candidates at edge prices, not first-to-cut).
|
|
1640
1644
|
if (edgeOrderIds && edgeOrderIds.size > 0) {
|
|
1641
|
-
const sidePrecision = orderType === ORDER_TYPES.SELL
|
|
1642
|
-
? manager.assets?.assetA?.precision
|
|
1643
|
-
: manager.assets?.assetB?.precision;
|
|
1644
1645
|
const edgePrices = [];
|
|
1645
1646
|
for (const eid of edgeOrderIds) {
|
|
1646
1647
|
const slot = manager.orders.get(eid);
|
|
1647
1648
|
if (slot && Number.isFinite(Number(slot.price)))
|
|
1648
1649
|
edgePrices.push(Number(slot.price));
|
|
1649
1650
|
}
|
|
1650
|
-
const isEdgePriced = (price) => {
|
|
1651
|
+
const isEdgePriced = (price, size) => {
|
|
1651
1652
|
const p = Number(price);
|
|
1653
|
+
const s = Number(size) || 0;
|
|
1652
1654
|
if (!Number.isFinite(p))
|
|
1653
1655
|
return false;
|
|
1654
|
-
return edgePrices.some((ep) =>
|
|
1655
|
-
try {
|
|
1656
|
-
return priceSlotEqual(ep, p, sidePrecision);
|
|
1657
|
-
}
|
|
1658
|
-
catch {
|
|
1659
|
-
return ep === p;
|
|
1660
|
-
}
|
|
1661
|
-
});
|
|
1656
|
+
return edgePrices.some((ep) => pricesOnSameLevel(ep, s, orderType, p, s, orderType, manager.assets, manager.config?.incrementPercent));
|
|
1662
1657
|
};
|
|
1663
|
-
const parked = parsedUnmatched.filter((x) => isEdgePriced(x.parsed?.price));
|
|
1658
|
+
const parked = parsedUnmatched.filter((x) => isEdgePriced(x.parsed?.price, x.parsed?.size));
|
|
1664
1659
|
if (parked.length > 0 && parked.length < parsedUnmatched.length) {
|
|
1665
1660
|
const parkedIds = new Set(parked.map((x) => x.chain?.id));
|
|
1666
1661
|
parsedUnmatched.sort((a, b) => {
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
|
|
34
34
|
* 2. grid.ts - Grid class (grid creation, synchronization, health)
|
|
35
35
|
* 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
|
|
36
|
-
* 4. format.ts - Numeric formatting (
|
|
36
|
+
* 4. format.ts - Numeric formatting (17 functions for consistent display)
|
|
37
37
|
* 5. accounting.ts - Accountant class (fund calculations and reconciliation)
|
|
38
38
|
* 6. logger.ts - Logger class (structured, color-coded output)
|
|
39
39
|
* 7. async_lock.ts - AsyncLock class (race condition prevention)
|
|
@@ -294,8 +294,9 @@ declare const utils: {
|
|
|
294
294
|
getPrecisionSlack: typeof math.getPrecisionSlack;
|
|
295
295
|
quantumForPrecision: typeof math.quantumForPrecision;
|
|
296
296
|
calculatePriceTolerance: typeof math.calculatePriceTolerance;
|
|
297
|
-
findPriceCollision: typeof math.findPriceCollision;
|
|
298
297
|
findCrossedOrder: typeof math.findCrossedOrder;
|
|
298
|
+
pricesOnSameLevel: typeof math.pricesOnSameLevel;
|
|
299
|
+
sameGridPrice: typeof math.sameGridPrice;
|
|
299
300
|
validateOrderAmountsWithinLimits: typeof math.validateOrderAmountsWithinLimits;
|
|
300
301
|
getMinOrderSize: typeof math.getMinOrderSize;
|
|
301
302
|
getDustThresholdFactor: typeof math.getDustThresholdFactor;
|
|
@@ -323,6 +324,7 @@ declare const utils: {
|
|
|
323
324
|
assertSlotPriceInvariant: typeof math.assertSlotPriceInvariant;
|
|
324
325
|
priceSlotEqual: typeof math.priceSlotEqual;
|
|
325
326
|
derivePriceLevels: typeof math.derivePriceLevels;
|
|
327
|
+
sameGridLevel: typeof math.sameGridLevel;
|
|
326
328
|
buildGenesisFromPriceLevels: typeof math.buildGenesisFromPriceLevels;
|
|
327
329
|
hashPriceLevels: typeof math.hashPriceLevels;
|
|
328
330
|
isChainPriceOutOfGrid: typeof math.isChainPriceOutOfGrid;
|