dexbot 1.6.17 → 1.7.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.
- package/CHANGELOG.md +58 -0
- package/README.md +24 -18
- package/analysis/README.md +105 -12
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +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/analyze_args.d.ts +2 -1
- package/dist/analysis/analyze_dynamic_weight.js +2 -1
- package/dist/analysis/analyze_kalman.js +3 -2
- package/dist/analysis/analyze_liquidity.d.ts +17 -0
- package/dist/analysis/analyze_liquidity.js +325 -0
- package/dist/analysis/analyze_regime.js +3 -2
- package/dist/analysis/analyze_regime_windows.js +3 -2
- package/dist/analysis/analyze_volatility.js +3 -2
- package/dist/analysis/fills_source.d.ts +1 -8
- package/dist/analysis/fills_source.js +1 -1
- package/dist/analysis/grid_correction_check.d.ts +9 -6
- package/dist/analysis/grid_correction_check.js +56 -64
- package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
- package/dist/analysis/liquidity/liquidity_chain.js +178 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
- package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
- package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
- package/dist/analysis/liquidity/liquidity_view.js +55 -0
- package/dist/analysis/math_utils.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +1 -1
- package/dist/analysis/trade_profitability.js +2 -1
- package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
- package/dist/dexbot.js +74 -169
- package/dist/market_adapter/cli_args.d.ts +6 -1
- package/dist/market_adapter/cli_args.js +16 -2
- package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
- package/dist/market_adapter/core/kibana_candles.js +3 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
- package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
- package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
- package/dist/market_adapter/inputs/window_cache.js +14 -1
- package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
- package/dist/market_adapter/lp_chart_runner.js +3 -1
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
- package/dist/market_adapter/market_adapter.d.ts +10 -2
- package/dist/market_adapter/market_adapter.js +10 -11
- package/dist/market_adapter/utils/chain.d.ts +2 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
- package/dist/market_adapter/utils/file_json_cache.js +3 -1
- package/dist/market_adapter/utils/file_lock.js +1 -1
- package/dist/market_adapter/utils/native_history.d.ts +7 -3
- package/dist/market_adapter/utils/native_history.js +3 -1
- package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
- package/dist/modules/asset_lookup.d.ts +25 -0
- package/dist/modules/asset_lookup.js +75 -0
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/chain_scan.d.ts +64 -0
- package/dist/modules/chain_scan.js +80 -0
- package/dist/modules/cli_colors.d.ts +5 -0
- package/dist/modules/cli_colors.js +7 -0
- package/dist/modules/cli_progress.d.ts +51 -0
- package/dist/modules/cli_progress.js +113 -0
- package/dist/modules/constants.js +6 -3
- package/dist/modules/dexbot_class.d.ts +8 -0
- package/dist/modules/dexbot_class.js +10 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
- package/dist/modules/dexbot_cow_runtime.js +475 -47
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_fill_runtime.js +20 -0
- package/dist/modules/dexbot_maintenance_runtime.js +71 -9
- package/dist/modules/dexbot_startup_runtime.js +7 -1
- package/dist/modules/graceful_shutdown.d.ts +2 -2
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/launcher/runtime_entry.d.ts +21 -1
- package/dist/modules/launcher/runtime_entry.js +36 -1
- package/dist/modules/launcher/runtime_mode.d.ts +4 -3
- package/dist/modules/liquidity_pool_ref.d.ts +32 -0
- package/dist/modules/liquidity_pool_ref.js +116 -0
- package/dist/modules/node_manager.d.ts +1 -1
- package/dist/modules/node_manager.js +1 -1
- package/dist/modules/order/accounting.js +2 -1
- package/dist/modules/order/export.d.ts +2 -2
- package/dist/modules/order/export.js +2 -2
- package/dist/modules/order/grid.d.ts +19 -14
- package/dist/modules/order/grid.js +269 -61
- package/dist/modules/order/grid_reconcile.js +27 -2
- package/dist/modules/order/grid_reconcile_internal.js +94 -15
- package/dist/modules/order/index.d.ts +24 -4
- package/dist/modules/order/manager.d.ts +12 -0
- package/dist/modules/order/manager.js +44 -11
- package/dist/modules/order/strategy.js +22 -2
- package/dist/modules/order/sync_engine.d.ts +32 -1
- package/dist/modules/order/sync_engine.js +209 -26
- package/dist/modules/order/utils/math.d.ts +26 -10
- package/dist/modules/order/utils/math.js +54 -14
- package/dist/modules/order/utils/order.d.ts +158 -11
- package/dist/modules/order/utils/order.js +434 -21
- package/dist/modules/order/utils/system.d.ts +136 -30
- package/dist/modules/order/utils/system.js +465 -63
- package/dist/modules/order/utils/validate.d.ts +1 -0
- package/dist/modules/order/utils/validate.js +37 -3
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +14 -0
- package/dist/modules/utils/asset_symbols.d.ts +13 -2
- package/dist/modules/utils/asset_symbols.js +21 -2
- package/dist/scripts/analysis_runner.d.ts +10 -0
- package/dist/scripts/analysis_runner.js +33 -0
- package/dist/scripts/analyze-orders.js +2 -1
- package/dist/scripts/asset.d.ts +26 -0
- package/dist/scripts/asset.js +165 -0
- package/dist/scripts/bts_distribution.d.ts +1 -0
- package/dist/scripts/bts_distribution.js +194 -142
- package/dist/scripts/chart_command.d.ts +1 -1
- package/dist/scripts/chart_command.js +60 -86
- package/dist/scripts/chart_targets.d.ts +18 -0
- package/dist/scripts/chart_targets.js +52 -0
- package/dist/scripts/dw.js +1 -1
- package/dist/scripts/liquid.d.ts +24 -0
- package/dist/scripts/liquid.js +134 -0
- package/dist/scripts/rich_list.js +12 -16
- package/dist/scripts/token_distribution.d.ts +2 -0
- package/dist/scripts/token_distribution.js +132 -108
- package/dist/scripts/tv.js +1 -1
- package/dist/scripts/verify-browser-bundle.js +18 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +21 -11
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
- package/docs/GRID_PRICE_INVARIANT.md +28 -5
- package/docs/GRID_RECONCILE.md +25 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +37 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +3 -1
- package/docs/architecture.md +115 -13
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +9 -4
- package/modules/README.md +23 -15
- package/package.json +6 -3
- package/scripts/README.md +23 -7
|
@@ -251,7 +251,7 @@ export function recordSpreadCorrectionRefusal(manager, cause) {
|
|
|
251
251
|
* invalidating corrections. Counter-only; never throws.
|
|
252
252
|
* @param {Object} manager - OrderManager instance
|
|
253
253
|
*/
|
|
254
|
-
|
|
254
|
+
function recordSpreadCorrectionRetry(manager) {
|
|
255
255
|
try {
|
|
256
256
|
const m = manager?._metrics;
|
|
257
257
|
if (!m)
|
|
@@ -290,18 +290,66 @@ export function getOccupiedCorrectionSlots(manager, correction) {
|
|
|
290
290
|
if (liveState && cur.orderId)
|
|
291
291
|
occupied.push(o.id);
|
|
292
292
|
}
|
|
293
|
+
// Rotation destinations are empty slots when planned; if one was
|
|
294
|
+
// taken between plan and broadcast the UPDATE would overwrite/duplicate
|
|
295
|
+
// it, so treat it exactly like an occupied CREATE destination.
|
|
296
|
+
for (const r of correction.ordersToRotate || []) {
|
|
297
|
+
const dest = r?.newGridId;
|
|
298
|
+
if (!dest)
|
|
299
|
+
continue;
|
|
300
|
+
const cur = orders.get(dest);
|
|
301
|
+
if (!cur)
|
|
302
|
+
continue;
|
|
303
|
+
const liveState = cur.state === ORDER_STATES.ACTIVE || cur.state === ORDER_STATES.PARTIAL;
|
|
304
|
+
if (liveState && cur.orderId)
|
|
305
|
+
occupied.push(dest);
|
|
306
|
+
}
|
|
293
307
|
}
|
|
294
308
|
catch { /* best-effort detection */ }
|
|
295
309
|
return occupied;
|
|
296
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* Executable-action count for a spread correction: CREATEs plus fund-constrained
|
|
313
|
+
* ROTATIONs. A rotation tightens the spread exactly like a create; callers that
|
|
314
|
+
* test only ordersToPlace would misclassify a rotation-only plan as "nothing
|
|
315
|
+
* to do" and skip the broadcast.
|
|
316
|
+
* @param {Object|null|undefined} correction - Prepared spread correction
|
|
317
|
+
* @returns {number} Number of actions the COW plan will execute
|
|
318
|
+
*/
|
|
319
|
+
function getSpreadCorrectionActionCount(correction) {
|
|
320
|
+
return (correction?.ordersToPlace?.length || 0) + (correction?.ordersToRotate?.length || 0);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Rotation-only fallback when normal side selection has no fundable side.
|
|
324
|
+
*
|
|
325
|
+
* `determineOrderSideByFunds` is still pure-fund-driven, so a rail with
|
|
326
|
+
* exactly zero free on both sides returns null. Rotations, however, need no
|
|
327
|
+
* new commitment: a fully allocated rail can still be repaired by moving a
|
|
328
|
+
* resting order into a promoted gap slot. Try both sides and accept the first
|
|
329
|
+
* executable plan (create or rotation). Callers must only use this when the
|
|
330
|
+
* side decision failed for INSUFFICIENT FREE FUNDS, not for an unavailable
|
|
331
|
+
* market price where cross-asset side comparison is unsafe.
|
|
332
|
+
* @param {Object} manager - Order manager
|
|
333
|
+
* @returns {Promise<{correction: SpreadCorrection, side: OrderType}|null>}
|
|
334
|
+
*/
|
|
335
|
+
async function prepareZeroFreeRotationFallback(manager) {
|
|
336
|
+
for (const side of [ORDER_TYPES.BUY, ORDER_TYPES.SELL]) {
|
|
337
|
+
const correction = await prepareSpreadCorrectionOrders(manager, side, manager.outOfSpread);
|
|
338
|
+
if (correction && getSpreadCorrectionActionCount(correction) > 0) {
|
|
339
|
+
return { correction, side };
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
297
344
|
/**
|
|
298
345
|
* P1/P3 shared re-plan: derive a spread correction from the CURRENT master
|
|
299
346
|
* state (side chosen from fresh on-chain book, opposite-side starvation
|
|
300
|
-
* fallback).
|
|
301
|
-
*
|
|
302
|
-
*
|
|
347
|
+
* fallback). A zero-free decision still tries the rotation-only fallback.
|
|
348
|
+
* Used both for the plan-time collision dedupe and the bounded refusal retry.
|
|
349
|
+
* Read-only against the grid; no _gridLock needed (matches the existing TOCTOU
|
|
350
|
+
* fund re-plan contract).
|
|
303
351
|
* @param {Object} manager - OrderManager instance
|
|
304
|
-
* @returns {Promise<Object|null>} A correction with at least one
|
|
352
|
+
* @returns {Promise<Object|null>} A correction with at least one executable action, or null
|
|
305
353
|
*/
|
|
306
354
|
export async function replanSpreadCorrectionFromFreshMaster(manager) {
|
|
307
355
|
const freshOnChain = _getOnChainOrders(manager);
|
|
@@ -310,13 +358,17 @@ export async function replanSpreadCorrectionFromFreshMaster(manager) {
|
|
|
310
358
|
? (freshBest.bestBuy + freshBest.bestSell) / 2
|
|
311
359
|
: Number(manager.config.startPrice) || 0;
|
|
312
360
|
const decision = determineOrderSideByFunds(manager, freshPrice);
|
|
313
|
-
if (!decision.side)
|
|
314
|
-
|
|
361
|
+
if (!decision.side) {
|
|
362
|
+
if (decision.code !== 'no-free-funds')
|
|
363
|
+
return null;
|
|
364
|
+
const fallback = await prepareZeroFreeRotationFallback(manager);
|
|
365
|
+
return fallback?.correction ?? null;
|
|
366
|
+
}
|
|
315
367
|
let c = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
|
|
316
|
-
if ((c
|
|
368
|
+
if (getSpreadCorrectionActionCount(c) === 0) {
|
|
317
369
|
const opposite = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
|
|
318
370
|
const oc = await prepareSpreadCorrectionOrders(manager, opposite, manager.outOfSpread);
|
|
319
|
-
if ((oc
|
|
371
|
+
if (getSpreadCorrectionActionCount(oc) > 0)
|
|
320
372
|
c = oc;
|
|
321
373
|
}
|
|
322
374
|
return c;
|
|
@@ -340,7 +392,7 @@ export async function resolveOccupiedCorrection(manager, correction, attempt, ma
|
|
|
340
392
|
if (!(occupied.length > 0 && attempt < maxAttempts))
|
|
341
393
|
return { action: 'broadcast' };
|
|
342
394
|
const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
|
|
343
|
-
if (replanned && (replanned
|
|
395
|
+
if (replanned && getSpreadCorrectionActionCount(replanned) > 0) {
|
|
344
396
|
return { action: 'replanned', correction: replanned, occupied };
|
|
345
397
|
}
|
|
346
398
|
return { action: 'blocked', occupied };
|
|
@@ -366,8 +418,9 @@ function _snapshotFundState(manager) {
|
|
|
366
418
|
};
|
|
367
419
|
}
|
|
368
420
|
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';
|
|
369
|
-
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot,
|
|
370
|
-
import {
|
|
421
|
+
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
|
|
422
|
+
import { parseSlotIndex } from './utils/slot.js';
|
|
423
|
+
import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillPlacementBlocked } from './utils/system.js';
|
|
371
424
|
import * as MathUtils from './utils/math.js';
|
|
372
425
|
import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
|
|
373
426
|
import { getWhitelistFlags } from '../market_adapter_whitelist.js';
|
|
@@ -1462,10 +1515,13 @@ export async function initializeGrid(manager) {
|
|
|
1462
1515
|
manager._clearPendingFillCrawls?.('grid rebuild');
|
|
1463
1516
|
// Same generation contract for the LAST-FILL-GUARD pivot: it was
|
|
1464
1517
|
// armed against the previous ladder, and restoreLastFillPivot would
|
|
1465
|
-
// refuse it against the new genesis anyway. Drop it now
|
|
1466
|
-
//
|
|
1467
|
-
//
|
|
1468
|
-
//
|
|
1518
|
+
// refuse it against the new genesis anyway. Drop it now, then RE-ARM it
|
|
1519
|
+
// from the bot-scoped last real fill (rearmLastFillPivotFromMarketFill)
|
|
1520
|
+
// — the guard must not stay cold after a rebuild, and the re-arm is an
|
|
1521
|
+
// explicit, logged, persistable write instead of the read-time fallback
|
|
1522
|
+
// in resolveLastFillGuardReference doing the same job silently for the
|
|
1523
|
+
// rest of the run. Provenance stays 'fill', so a book seed never
|
|
1524
|
+
// qualifies.
|
|
1469
1525
|
try {
|
|
1470
1526
|
if (typeof manager._resetLastFillPivot === 'function') {
|
|
1471
1527
|
manager._resetLastFillPivot('grid rebuild');
|
|
@@ -1473,6 +1529,7 @@ export async function initializeGrid(manager) {
|
|
|
1473
1529
|
else {
|
|
1474
1530
|
resetLastFillPivot(manager, 'grid rebuild');
|
|
1475
1531
|
}
|
|
1532
|
+
rearmLastFillPivotFromMarketFill(manager);
|
|
1476
1533
|
}
|
|
1477
1534
|
catch { }
|
|
1478
1535
|
// RC-8: Update boundary with notification to dependent systems
|
|
@@ -1500,7 +1557,7 @@ export async function initializeGrid(manager) {
|
|
|
1500
1557
|
const buyCtx = await _getSizingContext(manager, 'buy', { skipRecalc: true });
|
|
1501
1558
|
if (!sellCtx || !buyCtx)
|
|
1502
1559
|
throw new Error('Failed to retrieve sizing context for grid initialization');
|
|
1503
|
-
let sizedOrders = calculateOrderSizes(orders, manager.config, sellCtx.budget, buyCtx.budget,
|
|
1560
|
+
let sizedOrders = calculateOrderSizes(orders, manager.config, sellCtx.budget, buyCtx.budget, precA, precB);
|
|
1504
1561
|
// Verification of sizes
|
|
1505
1562
|
const sells = filterOrdersByType(sizedOrders, ORDER_TYPES.SELL).map((o) => Number(o.size || 0));
|
|
1506
1563
|
const buys = filterOrdersByType(sizedOrders, ORDER_TYPES.BUY).map((o) => Number(o.size || 0));
|
|
@@ -1812,7 +1869,7 @@ function _computeCommittedSizeDriftSync(manager) {
|
|
|
1812
1869
|
continue;
|
|
1813
1870
|
let newSizes;
|
|
1814
1871
|
try {
|
|
1815
|
-
newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, s.orderType, manager.config,
|
|
1872
|
+
newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, s.orderType, manager.config, ctx.precision);
|
|
1816
1873
|
}
|
|
1817
1874
|
catch (_err) {
|
|
1818
1875
|
continue;
|
|
@@ -2009,7 +2066,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
|
|
|
2009
2066
|
if (allSideSlots.length === 0)
|
|
2010
2067
|
return collectActions ? { actions: [], changed: false } : undefined;
|
|
2011
2068
|
// Calculate geometric sizes for the ENTIRE rail
|
|
2012
|
-
const newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, orderType, manager.config,
|
|
2069
|
+
const newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, orderType, manager.config, ctx.precision);
|
|
2013
2070
|
const actions = [];
|
|
2014
2071
|
let changed = false;
|
|
2015
2072
|
const freeKey = isBuy ? 'buyFree' : 'sellFree';
|
|
@@ -2264,7 +2321,7 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
|
|
|
2264
2321
|
return comparedOrders;
|
|
2265
2322
|
// Calculate geometric ideals for the ENTIRE side (all slots)
|
|
2266
2323
|
try {
|
|
2267
|
-
const allIdealSizes = calculateRotationOrderSizes(ctx.budget, 0, sideSlots.length, type, manager.config,
|
|
2324
|
+
const allIdealSizes = calculateRotationOrderSizes(ctx.budget, 0, sideSlots.length, type, manager.config, ctx.precision);
|
|
2268
2325
|
// Map Ideal sizes to IDs for quick lookup
|
|
2269
2326
|
const idealMap = new Map();
|
|
2270
2327
|
sideSlots.forEach((slot, i) => idealMap.set(slot.id, allIdealSizes[i]));
|
|
@@ -2556,17 +2613,33 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2556
2613
|
}
|
|
2557
2614
|
catch { /* best-effort */ }
|
|
2558
2615
|
const decision = determineOrderSideByFunds(manager, lastPrice);
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2616
|
+
let chosenSide = decision.side;
|
|
2617
|
+
if (!chosenSide) {
|
|
2618
|
+
// Exact-zero free funds still allow a no-new-commitment repair:
|
|
2619
|
+
// rotate a resting order into the promoted gap slot.
|
|
2620
|
+
if (decision.code === 'no-free-funds') {
|
|
2621
|
+
const fallback = await prepareZeroFreeRotationFallback(manager);
|
|
2622
|
+
if (fallback) {
|
|
2623
|
+
correction = fallback.correction;
|
|
2624
|
+
chosenSide = fallback.side;
|
|
2625
|
+
manager.logger?.log?.(`[SPREAD] No fundable side, but a rotation-only repair is available on ${fallback.side}; ` +
|
|
2626
|
+
`using resting inventory (no new commitment).`, 'info');
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
if (!chosenSide) {
|
|
2630
|
+
stall = 'no-free-funds';
|
|
2631
|
+
return false;
|
|
2632
|
+
}
|
|
2562
2633
|
}
|
|
2563
2634
|
// Perform spread correction by placing orders on the chosen side.
|
|
2564
|
-
|
|
2635
|
+
if (!correction) {
|
|
2636
|
+
correction = await prepareSpreadCorrectionOrders(manager, chosenSide, manager.outOfSpread);
|
|
2637
|
+
}
|
|
2565
2638
|
if (!correction) {
|
|
2566
2639
|
stall = 'no-candidates';
|
|
2567
2640
|
return false;
|
|
2568
2641
|
}
|
|
2569
|
-
let placeCount = correction
|
|
2642
|
+
let placeCount = getSpreadCorrectionActionCount(correction);
|
|
2570
2643
|
// Fold each side into the stall cause; merge (never overwrite) across
|
|
2571
2644
|
// the starvation fallback so an UNFUNDED plan on the chosen side is
|
|
2572
2645
|
// not masked by an empty plan on the opposite side. The old code
|
|
@@ -2584,7 +2657,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2584
2657
|
const oppositeCorrection = await prepareSpreadCorrectionOrders(manager, oppositeSide, manager.outOfSpread);
|
|
2585
2658
|
if (oppositeCorrection) {
|
|
2586
2659
|
correction = oppositeCorrection;
|
|
2587
|
-
placeCount = oppositeCorrection
|
|
2660
|
+
placeCount = getSpreadCorrectionActionCount(oppositeCorrection);
|
|
2588
2661
|
const oppositeStall = classifySpreadStall(oppositeCorrection);
|
|
2589
2662
|
// Precedence merge (never overwrite): 'unfunded' > sync-repairable
|
|
2590
2663
|
// > geometry bind > readiness > 'no-candidates'. The old collapse
|
|
@@ -2652,18 +2725,22 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2652
2725
|
? (freshBest.bestBuy + freshBest.bestSell) / 2
|
|
2653
2726
|
: Number(manager.config.startPrice) || 0;
|
|
2654
2727
|
const rePlanDecision = determineOrderSideByFunds(manager, freshPrice);
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
// signal the caller to refresh account totals/open orders.
|
|
2659
|
-
stall = 'no-free-funds';
|
|
2660
|
-
return { ordersPlaced: 0, partialsMoved: 0, stall };
|
|
2728
|
+
let rePlanCorrection = null;
|
|
2729
|
+
if (rePlanDecision.side) {
|
|
2730
|
+
rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
|
|
2661
2731
|
}
|
|
2662
|
-
|
|
2663
|
-
|
|
2732
|
+
else if (rePlanDecision.code === 'no-free-funds') {
|
|
2733
|
+
// Fund state changed to zero free between lock release and
|
|
2734
|
+
// broadcast. Do not discard a rotation-only repair: it
|
|
2735
|
+
// needs no new funds.
|
|
2736
|
+
const fallback = await prepareZeroFreeRotationFallback(manager);
|
|
2737
|
+
rePlanCorrection = fallback?.correction ?? null;
|
|
2738
|
+
}
|
|
2739
|
+
if (rePlanCorrection && getSpreadCorrectionActionCount(rePlanCorrection) > 0) {
|
|
2664
2740
|
activeCorrection = rePlanCorrection;
|
|
2665
2741
|
manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
|
|
2666
|
-
`re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates
|
|
2742
|
+
`re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates, ` +
|
|
2743
|
+
`${activeCorrection.ordersToRotate?.length || 0} rotation(s)`, 'info');
|
|
2667
2744
|
}
|
|
2668
2745
|
else {
|
|
2669
2746
|
manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
|
|
@@ -2723,7 +2800,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2723
2800
|
lastResult = batchResult ?? null;
|
|
2724
2801
|
if (batchResult && batchResult.executed === true) {
|
|
2725
2802
|
await manager.recalculateFunds();
|
|
2726
|
-
const placed = activeCorrection
|
|
2803
|
+
const placed = getSpreadCorrectionActionCount(activeCorrection);
|
|
2727
2804
|
return { ordersPlaced: placed, partialsMoved: 0 };
|
|
2728
2805
|
}
|
|
2729
2806
|
const cause = classifySpreadRefusalCause(batchResult);
|
|
@@ -2735,7 +2812,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2735
2812
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Batch refused (${cause}); re-planning from fresh master ` +
|
|
2736
2813
|
`(attempt ${attempts + 1}/${MAX_SPREAD_ATTEMPTS})`, 'warn');
|
|
2737
2814
|
const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
|
|
2738
|
-
if (!replanned || (replanned
|
|
2815
|
+
if (!replanned || getSpreadCorrectionActionCount(replanned) === 0)
|
|
2739
2816
|
break;
|
|
2740
2817
|
recordSpreadCorrectionRetry(manager);
|
|
2741
2818
|
activeCorrection = replanned;
|
|
@@ -2897,7 +2974,7 @@ async function _computeDustThresholdMap(manager, type) {
|
|
|
2897
2974
|
.filter((o) => o.type === type)
|
|
2898
2975
|
.sort((a, b) => a.price - b.price);
|
|
2899
2976
|
const idealSizes = ctx && ctx.budget > 0
|
|
2900
|
-
? allocateFundsByWeights(ctx.budget, sideSlots.length, (manager.config.weightDistribution ?? {})[side], (manager.config.incrementPercent ?? 0) / 100, type === ORDER_TYPES.BUY,
|
|
2977
|
+
? allocateFundsByWeights(ctx.budget, sideSlots.length, (manager.config.weightDistribution ?? {})[side], (manager.config.incrementPercent ?? 0) / 100, type === ORDER_TYPES.BUY, ctx.precision)
|
|
2901
2978
|
: [];
|
|
2902
2979
|
const map = new Map();
|
|
2903
2980
|
sideSlots.forEach((s, idx) => {
|
|
@@ -2975,7 +3052,7 @@ export async function getDustOrders(manager, partials, side) {
|
|
|
2975
3052
|
* @param {import('./types').OrderManager} manager - The manager instance.
|
|
2976
3053
|
* @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
|
|
2977
3054
|
* normalize sell-side funds into buy-side units for a fair cross-asset comparison.
|
|
2978
|
-
* @returns {{ side: import('./types').OrderType|null, reason: string }} The side to correct on, or null
|
|
3055
|
+
* @returns {{ side: import('./types').OrderType|null, reason: string, code?: 'market-price-unavailable'|'no-free-funds' }} The side to correct on, or null with a structured cause.
|
|
2979
3056
|
*/
|
|
2980
3057
|
export function determineOrderSideByFunds(manager, currentMarketPrice) {
|
|
2981
3058
|
const buyAvailable = Math.min(Number(manager.funds?.available?.buy || 0), Number(manager.accountTotals?.buyFree || 0));
|
|
@@ -3020,7 +3097,7 @@ export function determineOrderSideByFunds(manager, currentMarketPrice) {
|
|
|
3020
3097
|
}
|
|
3021
3098
|
if (skipReason) {
|
|
3022
3099
|
manager.logger?.log?.(`Spread correction skipped: ${skipReason}; refusing to compare raw cross-asset units`, 'warn');
|
|
3023
|
-
return { side: null, reason: skipReason };
|
|
3100
|
+
return { side: null, reason: skipReason, code: 'market-price-unavailable' };
|
|
3024
3101
|
}
|
|
3025
3102
|
if (!side) {
|
|
3026
3103
|
// PURE FUND-DRIVEN: a zero/insufficient free balance skips the
|
|
@@ -3034,7 +3111,11 @@ export function determineOrderSideByFunds(manager, currentMarketPrice) {
|
|
|
3034
3111
|
: `Spread correction skipped: insufficient free funds ` +
|
|
3035
3112
|
`(buy=${Format.formatAmount8(buyAvailable)}, sell=${Format.formatAmount8(sellAvailable)})`, 'warn');
|
|
3036
3113
|
}
|
|
3037
|
-
return {
|
|
3114
|
+
return {
|
|
3115
|
+
side,
|
|
3116
|
+
reason: side ? `Choosing ${side}` : (skipReason || 'Insufficient free funds'),
|
|
3117
|
+
...(side ? {} : { code: 'no-free-funds' })
|
|
3118
|
+
};
|
|
3038
3119
|
}
|
|
3039
3120
|
/**
|
|
3040
3121
|
* Resolve the MIN_SPREAD_ORDERS gap reserve used by boundary promotion.
|
|
@@ -3154,12 +3235,34 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3154
3235
|
return false;
|
|
3155
3236
|
if (c?.price == null || !Number.isFinite(Number(c.price)))
|
|
3156
3237
|
return false;
|
|
3157
|
-
|
|
3238
|
+
// Judge candidates with the SAME predicate the placement guards use
|
|
3239
|
+
// (direction rule + same grid level). The raw-pivot direction check
|
|
3240
|
+
// this replaces was blind to the same-level shape — a slot level and
|
|
3241
|
+
// its own execution price differ by rounding (slot 1310.046339
|
|
3242
|
+
// filled at 1310.060435) — so it admitted candidates that the
|
|
3243
|
+
// broadcast guard then refused, burning a correction cycle on a
|
|
3244
|
+
// guaranteed refusal and under-reporting "Excluded N".
|
|
3245
|
+
return isLastFillPlacementBlocked(manager, Number(c.price), railType).blocked === true;
|
|
3158
3246
|
};
|
|
3159
3247
|
let lastFillExcluded = 0;
|
|
3248
|
+
// A slot can legitimately appear in MORE than one candidate pool (an
|
|
3249
|
+
// empty in-rail slot normalized to SPREAD qualifies for both the SPREAD
|
|
3250
|
+
// pool and the orphan pool; the merge below dedupes them), so count the
|
|
3251
|
+
// excluded SLOTS, not the pool visits — otherwise each vetoed slot is
|
|
3252
|
+
// reported twice and the "Excluded N" line overstates how much of the
|
|
3253
|
+
// side the pivot blocked, exactly when the pools overlap most.
|
|
3254
|
+
const lastFillExcludedSlotIds = new Set();
|
|
3160
3255
|
const passesLastFill = (c) => {
|
|
3161
3256
|
if (!lastFillBlocks(c))
|
|
3162
3257
|
return true;
|
|
3258
|
+
const slotId = c?.id != null ? String(c.id) : '';
|
|
3259
|
+
if (slotId === '') {
|
|
3260
|
+
lastFillExcluded++;
|
|
3261
|
+
return false;
|
|
3262
|
+
}
|
|
3263
|
+
if (lastFillExcludedSlotIds.has(slotId))
|
|
3264
|
+
return false;
|
|
3265
|
+
lastFillExcludedSlotIds.add(slotId);
|
|
3163
3266
|
lastFillExcluded++;
|
|
3164
3267
|
return false;
|
|
3165
3268
|
};
|
|
@@ -3610,16 +3713,18 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3610
3713
|
...spreadCandidates.map((slot) => ({ ...slot, type: railType }))
|
|
3611
3714
|
].sort((a, b) => a.price - b.price);
|
|
3612
3715
|
const ctx = await _getSizingContext(manager, sideName);
|
|
3613
|
-
if (!ctx ||
|
|
3614
|
-
// A
|
|
3615
|
-
|
|
3616
|
-
// arming the refresh for it. A missing context or an empty rail is
|
|
3617
|
-
// genuinely structural.
|
|
3618
|
-
const stallHint = (ctx && Number(ctx.budget) <= 0) ? 'unfunded' : 'no-candidates';
|
|
3619
|
-
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3716
|
+
if (!ctx || syntheticSideSlots.length === 0) {
|
|
3717
|
+
// A missing context or an empty rail is genuinely structural.
|
|
3718
|
+
return { ordersToPlace: [], ordersToUpdate: [], ordersToRotate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3620
3719
|
}
|
|
3621
3720
|
const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
|
|
3622
|
-
|
|
3721
|
+
// Zero free funds must NOT return early: the fund-constrained rotation
|
|
3722
|
+
// below is the only repair a fully allocated rail has. With no budget
|
|
3723
|
+
// every create is skipped below, then a resting order is rotated into
|
|
3724
|
+
// the promoted slot (same booked size, no new commitment).
|
|
3725
|
+
const idealSizes = ctx.budget > 0
|
|
3726
|
+
? allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, (manager.config.weightDistribution ?? {})[sideName], (manager.config.incrementPercent ?? 0) / 100, railType === ORDER_TYPES.BUY, ctx.precision)
|
|
3727
|
+
: [];
|
|
3623
3728
|
const idealById = new Map();
|
|
3624
3729
|
syntheticSideSlots.forEach((slot, idx) => {
|
|
3625
3730
|
idealById.set(slot.id, Number(idealSizes[idx] || 0));
|
|
@@ -3654,9 +3759,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3654
3759
|
});
|
|
3655
3760
|
}
|
|
3656
3761
|
}
|
|
3657
|
-
if (prioritizedTargets.length === 0) {
|
|
3658
|
-
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3659
|
-
}
|
|
3660
3762
|
// Chain-truth budget (see deriveChainTruthFundBudget): `availableFund`
|
|
3661
3763
|
// already had the virtual reservation subtracted, and that reservation
|
|
3662
3764
|
// is the projection of THESE candidates — subtracting it from the
|
|
@@ -3735,10 +3837,103 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3735
3837
|
});
|
|
3736
3838
|
remainingBudget -= createSize;
|
|
3737
3839
|
}
|
|
3840
|
+
// FUND-CONSTRAINED PROMOTION: free funds could not fund every
|
|
3841
|
+
// tightening slot. A fully allocated rail (botFunds 100%, every slot
|
|
3842
|
+
// resting) has ~0 free forever, so create-only repair can never close
|
|
3843
|
+
// the spread (live 2026-10-30: "planned 4, placing 1"). Rotate a
|
|
3844
|
+
// resting same-side order into each unfunded promoted slot instead.
|
|
3845
|
+
// The move commits NO new funds (size is the source's booked size) and
|
|
3846
|
+
// is bounded by the same promotion/geometry guards as a create.
|
|
3847
|
+
const ordersToRotate = [];
|
|
3848
|
+
{
|
|
3849
|
+
const fundedCreateIds = new Set(ordersToPlace.map((o) => String(o.id)));
|
|
3850
|
+
// Use the POST-FILTER candidate list, not raw promotedCandidates:
|
|
3851
|
+
// spreadCandidates has already passed slot dedupe and the
|
|
3852
|
+
// placed-price collision filter (a promoted slot whose price is
|
|
3853
|
+
// already occupied from another slot must not become a rotation
|
|
3854
|
+
// destination). Re-derive the subset instead of bypassing those
|
|
3855
|
+
// guards.
|
|
3856
|
+
const promotedIds = new Set(promotedCandidates.map((c) => String(c.id)));
|
|
3857
|
+
const unfundedPromotions = spreadCandidates
|
|
3858
|
+
.filter((c) => promotedIds.has(String(c.id)))
|
|
3859
|
+
.filter((c) => !fundedCreateIds.has(String(c.id)))
|
|
3860
|
+
.filter((c) => isSlotAvailable(c));
|
|
3861
|
+
if (unfundedPromotions.length > 0) {
|
|
3862
|
+
const windowIds = liveWindowIdSet(manager, railType);
|
|
3863
|
+
const edgeIds = edgeOrderIdSet(allSlotsByPrice, manager.config, railType, resolveLiveEdgeAnchorPrice(manager, sideName), windowIds);
|
|
3864
|
+
const sourcePool = allOrders
|
|
3865
|
+
.filter((o) => o.type === railType
|
|
3866
|
+
&& o.state === ORDER_STATES.ACTIVE
|
|
3867
|
+
&& !!o.orderId
|
|
3868
|
+
&& Number(o.size) > 0
|
|
3869
|
+
&& o.price != null
|
|
3870
|
+
&& Number.isFinite(Number(o.price)))
|
|
3871
|
+
.filter((o) => {
|
|
3872
|
+
const idx = slotIndexMap.get(o.id);
|
|
3873
|
+
if (idx === undefined)
|
|
3874
|
+
return false;
|
|
3875
|
+
return railType === ORDER_TYPES.BUY ? idx <= buyEndIdx : idx >= sellStartIdx;
|
|
3876
|
+
})
|
|
3877
|
+
.filter((o) => !edgeIds || !edgeIds.has(String(o.id)))
|
|
3878
|
+
.sort((a, b) => railType === ORDER_TYPES.BUY
|
|
3879
|
+
? Number(a.price) - Number(b.price)
|
|
3880
|
+
: Number(b.price) - Number(a.price));
|
|
3881
|
+
const usedSourceIds = new Set();
|
|
3882
|
+
for (const dest of unfundedPromotions) {
|
|
3883
|
+
const source = sourcePool.find((s) => !usedSourceIds.has(String(s.id)));
|
|
3884
|
+
if (!source)
|
|
3885
|
+
break;
|
|
3886
|
+
const sourceSize = Number(source.size);
|
|
3887
|
+
if (!Number.isFinite(sourceSize) || sourceSize <= 0)
|
|
3888
|
+
continue;
|
|
3889
|
+
// Same booked size: a rotation is not a re-size and must
|
|
3890
|
+
// never need new funds. If the source size is unhealthy at
|
|
3891
|
+
// the destination (it is the same asset/side, so this is
|
|
3892
|
+
// only a corrupt-size guard), skip rather than shrink.
|
|
3893
|
+
if (!isOrderHealthy(sourceSize, railType, manager.assets, sourceSize))
|
|
3894
|
+
continue;
|
|
3895
|
+
const destPrice = Number(dest.price);
|
|
3896
|
+
if (!Number.isFinite(destPrice) || destPrice <= 0)
|
|
3897
|
+
continue;
|
|
3898
|
+
ordersToRotate.push({
|
|
3899
|
+
id: String(source.id),
|
|
3900
|
+
orderId: String(source.orderId),
|
|
3901
|
+
oldOrder: source,
|
|
3902
|
+
newGridId: String(dest.id),
|
|
3903
|
+
newPrice: destPrice,
|
|
3904
|
+
newSize: sourceSize,
|
|
3905
|
+
type: railType
|
|
3906
|
+
});
|
|
3907
|
+
usedSourceIds.add(String(source.id));
|
|
3908
|
+
}
|
|
3909
|
+
if (ordersToRotate.length > 0) {
|
|
3910
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained promotion on ${sideName}: rotating ` +
|
|
3911
|
+
`${ordersToRotate.length} resting order(s) into the gap ` +
|
|
3912
|
+
`(${ordersToRotate.map((r) => `${r.id}->${r.newGridId}`).join(', ')}) — ` +
|
|
3913
|
+
`no new funds required`, 'warn');
|
|
3914
|
+
}
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
if (ordersToPlace.length === 0 && ordersToRotate.length === 0) {
|
|
3918
|
+
// Candidates existed but neither free funds nor a rotation source
|
|
3919
|
+
// could act: a FUND/rail-structure stall, not a structural absence.
|
|
3920
|
+
return {
|
|
3921
|
+
ordersToPlace: [],
|
|
3922
|
+
ordersToUpdate: [],
|
|
3923
|
+
ordersToRotate: [],
|
|
3924
|
+
plannedCount: spreadCandidates.length,
|
|
3925
|
+
stallHint: 'unfunded',
|
|
3926
|
+
origin: COW_ORIGINS.SPREAD_CORRECTION
|
|
3927
|
+
};
|
|
3928
|
+
}
|
|
3738
3929
|
let boundaryIdx;
|
|
3739
|
-
const placedPromotedIds = new Set(
|
|
3740
|
-
|
|
3741
|
-
|
|
3930
|
+
const placedPromotedIds = new Set([
|
|
3931
|
+
...ordersToPlace
|
|
3932
|
+
.filter((order) => promotedCandidates.some((slot) => slot.id === order.id))
|
|
3933
|
+
.map((order) => order.id),
|
|
3934
|
+
...ordersToRotate
|
|
3935
|
+
.map((rotation) => rotation.newGridId)
|
|
3936
|
+
]);
|
|
3742
3937
|
if (placedPromotedIds.size > 0) {
|
|
3743
3938
|
// Derive boundary from the placed promoted set's extremes (via
|
|
3744
3939
|
// slotIndexMap), not the contiguous prefix. Any promoted-but-
|
|
@@ -3790,12 +3985,25 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3790
3985
|
if (spreadCandidates.length < missingSlots) {
|
|
3791
3986
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Requested ${missingSlots} extra slot(s), found ${spreadCandidates.length} available slot(s) on ${sideName}`, 'warn');
|
|
3792
3987
|
}
|
|
3793
|
-
if (ordersToPlace.length < spreadCandidates.length) {
|
|
3794
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained placement on ${sideName}: planned ${spreadCandidates.length},
|
|
3988
|
+
if (ordersToPlace.length + ordersToRotate.length < spreadCandidates.length) {
|
|
3989
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained placement on ${sideName}: planned ${spreadCandidates.length}, ` +
|
|
3990
|
+
`placing ${ordersToPlace.length} create(s) + ${ordersToRotate.length} rotation(s)`, 'info');
|
|
3795
3991
|
}
|
|
3796
|
-
if (ordersToPlace.length > 0) {
|
|
3797
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length},
|
|
3992
|
+
if (ordersToPlace.length > 0 || ordersToRotate.length > 0) {
|
|
3993
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length}, rotations=${ordersToRotate.length}, ` +
|
|
3994
|
+
`remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
|
|
3798
3995
|
}
|
|
3799
|
-
return {
|
|
3996
|
+
return {
|
|
3997
|
+
ordersToPlace,
|
|
3998
|
+
ordersToUpdate: [],
|
|
3999
|
+
ordersToRotate,
|
|
4000
|
+
// Number of tightening candidates found before funding/rotation.
|
|
4001
|
+
// Include rotation targets: a rotation-only plan has a non-zero
|
|
4002
|
+
// planned count and must not look like an empty plan to callers
|
|
4003
|
+
// that distinguish 'unfunded' from 'no-candidates'.
|
|
4004
|
+
plannedCount: spreadCandidates.length,
|
|
4005
|
+
...(boundaryIdx === undefined ? {} : { boundaryIdx }),
|
|
4006
|
+
origin: COW_ORIGINS.SPREAD_CORRECTION
|
|
4007
|
+
};
|
|
3800
4008
|
}
|
|
3801
4009
|
//# sourceMappingURL=grid.js.map
|
|
@@ -4,7 +4,7 @@ import { _countActiveOnGrid, _cancelChainOrder, _recoverStartupSyncFailure, _ref
|
|
|
4
4
|
import { ORDER_TYPES, ORDER_STATES, TIMING } from '../constants.js';
|
|
5
5
|
import { readOpenOrdersGuarded } from '../chain_orders.js';
|
|
6
6
|
import { getAssetFeesSafe, pricesOnSameLevel } from './utils/math.js';
|
|
7
|
-
import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, } from './utils/order.js';
|
|
7
|
+
import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, reviveVirtualSlotFromChain, } from './utils/order.js';
|
|
8
8
|
import * as Format from './format.js';
|
|
9
9
|
import { getErrorMessage } from '../utils/errors.js';
|
|
10
10
|
function _startupChainSnapshotSignature(orders, manager) {
|
|
@@ -79,7 +79,11 @@ export async function attemptResumePersistedGridByPriceMatch({ manager, persiste
|
|
|
79
79
|
const { loadGrid } = require('./grid');
|
|
80
80
|
// Prefer explicit genesis if caller wired it, else fall back to manager._genesis
|
|
81
81
|
const genesisArg = genesis ?? manager._genesis ?? null;
|
|
82
|
-
|
|
82
|
+
// This is a resume/adoption path, not a poison-ingestion path. Pure
|
|
83
|
+
// in-band stranding is the normal SPREAD-GUARD / partial-fill-anchor
|
|
84
|
+
// state and GAP-EVAC owns cleanup; keep the persisted boundary so a
|
|
85
|
+
// re-anchor surviving in the snapshot is not rebuilt away here.
|
|
86
|
+
await loadGrid(manager, persistedGrid, boundaryIdx, genesisArg, { tolerateTransientStranding: true });
|
|
83
87
|
await manager.synchronizeWithChain(chainOpenOrders, 'readOpenOrders');
|
|
84
88
|
const matchedOrderIds = new Set((Array.from(manager.orders.values()))
|
|
85
89
|
.filter((o) => o && isOrderOnChain(o))
|
|
@@ -196,6 +200,11 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
|
|
|
196
200
|
}
|
|
197
201
|
const applyUpdate = manager._applyOrderUpdate.bind(manager);
|
|
198
202
|
const chainIds = new Set((Array.isArray(chainOpenOrders) ? chainOpenOrders : []).map(o => o?.id).filter((id) => Boolean(id)));
|
|
203
|
+
const chainOrderById = new Map();
|
|
204
|
+
for (const raw of (Array.isArray(chainOpenOrders) ? chainOpenOrders : [])) {
|
|
205
|
+
if (raw?.id)
|
|
206
|
+
chainOrderById.set(String(raw.id), raw);
|
|
207
|
+
}
|
|
199
208
|
for (const order of manager.orders.values()) {
|
|
200
209
|
if (isOrderPlaced(order)) {
|
|
201
210
|
if (!order.orderId || !chainIds.has(order.orderId)) {
|
|
@@ -224,6 +233,22 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
|
|
|
224
233
|
}, 'startup-phantom', { skipAccounting: true });
|
|
225
234
|
}
|
|
226
235
|
}
|
|
236
|
+
else if (order.orderId && chainIds.has(String(order.orderId))) {
|
|
237
|
+
// DARK LEVEL: the slot is not placed but its chain order is
|
|
238
|
+
// still live (a phantom cleanup on a truncated read, or a
|
|
239
|
+
// refused-commit adoption). Left as-is it is invisible to
|
|
240
|
+
// window accounting (_countActiveOnGrid counts only
|
|
241
|
+
// ACTIVE/PARTIAL) while its order still counts in chainCount —
|
|
242
|
+
// so this side reads a shortfall it can never repair, and the
|
|
243
|
+
// planner sees a free level that already holds an order (the
|
|
244
|
+
// duplicate-price precondition). Revive in place: no broadcast,
|
|
245
|
+
// and only when the order really rests at this slot's level.
|
|
246
|
+
const rawChain = chainOrderById.get(String(order.orderId)) ?? null;
|
|
247
|
+
const parsedChain = rawChain ? parseChainOrder(rawChain, manager.assets) : null;
|
|
248
|
+
// The helper logs the revive itself (one warn line, same text
|
|
249
|
+
// on both call sites) — no second log here.
|
|
250
|
+
await reviveVirtualSlotFromChain(manager, order, parsedChain, rawChain, 'startup-revive', { skipAccounting: true });
|
|
251
|
+
}
|
|
227
252
|
}
|
|
228
253
|
const matchedChainOrderIds = new Set();
|
|
229
254
|
for (const gridOrder of manager.orders.values()) {
|