dexbot 1.6.16 → 1.6.18
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/analysis/README.md +10 -9
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +3 -3
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
- 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/analyze_lambda_vs_slow.js +5 -3
- package/dist/analysis/analyze_args.d.ts +2 -1
- 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/math_utils.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +1 -1
- package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
- 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/account_bots.d.ts +3 -0
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/chain_keys.d.ts +1 -1
- package/dist/modules/constants.d.ts +6 -0
- package/dist/modules/constants.js +37 -6
- package/dist/modules/credit_pricing.d.ts +20 -1
- package/dist/modules/credit_pricing.js +23 -1
- package/dist/modules/credit_runtime.js +33 -16
- package/dist/modules/dexbot_class.d.ts +11 -1
- package/dist/modules/dexbot_class.js +15 -2
- package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
- package/dist/modules/dexbot_cow_runtime.js +507 -108
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +117 -12
- 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/credential_daemon.d.ts +14 -2
- package/dist/modules/launcher/credential_daemon.js +60 -26
- package/dist/modules/launcher/runtime_mode.d.ts +4 -3
- 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 +26 -14
- package/dist/modules/order/grid.js +416 -73
- package/dist/modules/order/grid_reconcile.js +5 -1
- package/dist/modules/order/grid_reconcile_internal.js +2 -1
- package/dist/modules/order/index.d.ts +22 -1
- package/dist/modules/order/manager.d.ts +40 -7
- package/dist/modules/order/manager.js +149 -23
- package/dist/modules/order/strategy.d.ts +5 -0
- package/dist/modules/order/strategy.js +44 -3
- package/dist/modules/order/sync_engine.d.ts +12 -1
- package/dist/modules/order/sync_engine.js +135 -20
- package/dist/modules/order/utils/math.d.ts +49 -10
- package/dist/modules/order/utils/math.js +71 -14
- package/dist/modules/order/utils/order.d.ts +65 -11
- package/dist/modules/order/utils/order.js +198 -28
- package/dist/modules/order/utils/system.d.ts +112 -2
- package/dist/modules/order/utils/system.js +338 -12
- package/dist/modules/order/utils/validate.d.ts +4 -1
- package/dist/modules/order/utils/validate.js +9 -2
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +44 -2
- package/dist/scripts/analyze-credit.js +64 -23
- package/dist/scripts/bts_distribution.d.ts +66 -0
- package/dist/scripts/bts_distribution.js +2102 -0
- package/dist/scripts/token_distribution.d.ts +45 -0
- package/dist/scripts/token_distribution.js +1870 -0
- package/dist/unlock.js +42 -24
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +24 -8
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
- package/docs/GRID_PRICE_INVARIANT.md +29 -3
- package/docs/GRID_RECALCULATION.md +3 -3
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +22 -0
- package/docs/MPA_CREDIT_USAGE.md +3 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
- package/docs/README.md +1 -1
- package/docs/architecture.md +205 -6
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +11 -6
- package/modules/README.md +18 -14
- package/package.json +6 -3
- package/scripts/README.md +85 -148
|
@@ -128,12 +128,36 @@ function classifySpreadStall(c) {
|
|
|
128
128
|
// the precedence is explicit so a future hint can never mask 'unfunded').
|
|
129
129
|
if (Number(c?.plannedCount || 0) > 0 || hint === 'unfunded')
|
|
130
130
|
return 'unfunded';
|
|
131
|
-
// Preserve the
|
|
132
|
-
//
|
|
133
|
-
|
|
131
|
+
// Preserve the named causes verbatim; they are operationally distinct (one
|
|
132
|
+
// wants a sync, one wants a re-center) and the watchdog keys its escalation
|
|
133
|
+
// window off them.
|
|
134
|
+
if (hint === 'cold-book' || hint === 'unmatched-orders' || hint === 'readiness-gate'
|
|
135
|
+
|| hint === 'last-fill-blocked')
|
|
134
136
|
return hint;
|
|
135
137
|
return 'no-candidates';
|
|
136
138
|
}
|
|
139
|
+
/**
|
|
140
|
+
* Merge two side stalls so the starvation fallback cannot mask a named cause.
|
|
141
|
+
* 'unfunded' stays top (a refresh may repair it); 'unmatched-orders' next (a
|
|
142
|
+
* sync repairs it); then the geometry bind; readiness causes; 'no-candidates'
|
|
143
|
+
* is the floor. Exported for tests.
|
|
144
|
+
*/
|
|
145
|
+
export function mergeSpreadStalls(a, b) {
|
|
146
|
+
const rank = {
|
|
147
|
+
'unfunded': 5,
|
|
148
|
+
'no-free-funds': 5,
|
|
149
|
+
'unmatched-orders': 4,
|
|
150
|
+
'last-fill-blocked': 3,
|
|
151
|
+
'cold-book': 2,
|
|
152
|
+
'readiness-gate': 2,
|
|
153
|
+
'no-candidates': 1,
|
|
154
|
+
'batch-not-executed': 1,
|
|
155
|
+
'apply-error': 1
|
|
156
|
+
};
|
|
157
|
+
const ra = rank[String(a)] ?? 0;
|
|
158
|
+
const rb = rank[String(b)] ?? 0;
|
|
159
|
+
return (rb > ra ? String(b) : String(a));
|
|
160
|
+
}
|
|
137
161
|
/**
|
|
138
162
|
* Spread-correction refusal causes — the single vocabulary shared by
|
|
139
163
|
* classifySpreadRefusalCause, the retry/transience decision and the
|
|
@@ -227,7 +251,7 @@ export function recordSpreadCorrectionRefusal(manager, cause) {
|
|
|
227
251
|
* invalidating corrections. Counter-only; never throws.
|
|
228
252
|
* @param {Object} manager - OrderManager instance
|
|
229
253
|
*/
|
|
230
|
-
|
|
254
|
+
function recordSpreadCorrectionRetry(manager) {
|
|
231
255
|
try {
|
|
232
256
|
const m = manager?._metrics;
|
|
233
257
|
if (!m)
|
|
@@ -266,18 +290,66 @@ export function getOccupiedCorrectionSlots(manager, correction) {
|
|
|
266
290
|
if (liveState && cur.orderId)
|
|
267
291
|
occupied.push(o.id);
|
|
268
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
|
+
}
|
|
269
307
|
}
|
|
270
308
|
catch { /* best-effort detection */ }
|
|
271
309
|
return occupied;
|
|
272
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
|
+
}
|
|
273
344
|
/**
|
|
274
345
|
* P1/P3 shared re-plan: derive a spread correction from the CURRENT master
|
|
275
346
|
* state (side chosen from fresh on-chain book, opposite-side starvation
|
|
276
|
-
* fallback).
|
|
277
|
-
*
|
|
278
|
-
*
|
|
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).
|
|
279
351
|
* @param {Object} manager - OrderManager instance
|
|
280
|
-
* @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
|
|
281
353
|
*/
|
|
282
354
|
export async function replanSpreadCorrectionFromFreshMaster(manager) {
|
|
283
355
|
const freshOnChain = _getOnChainOrders(manager);
|
|
@@ -286,13 +358,17 @@ export async function replanSpreadCorrectionFromFreshMaster(manager) {
|
|
|
286
358
|
? (freshBest.bestBuy + freshBest.bestSell) / 2
|
|
287
359
|
: Number(manager.config.startPrice) || 0;
|
|
288
360
|
const decision = determineOrderSideByFunds(manager, freshPrice);
|
|
289
|
-
if (!decision.side)
|
|
290
|
-
|
|
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
|
+
}
|
|
291
367
|
let c = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
|
|
292
|
-
if ((c
|
|
368
|
+
if (getSpreadCorrectionActionCount(c) === 0) {
|
|
293
369
|
const opposite = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
|
|
294
370
|
const oc = await prepareSpreadCorrectionOrders(manager, opposite, manager.outOfSpread);
|
|
295
|
-
if ((oc
|
|
371
|
+
if (getSpreadCorrectionActionCount(oc) > 0)
|
|
296
372
|
c = oc;
|
|
297
373
|
}
|
|
298
374
|
return c;
|
|
@@ -316,7 +392,7 @@ export async function resolveOccupiedCorrection(manager, correction, attempt, ma
|
|
|
316
392
|
if (!(occupied.length > 0 && attempt < maxAttempts))
|
|
317
393
|
return { action: 'broadcast' };
|
|
318
394
|
const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
|
|
319
|
-
if (replanned && (replanned
|
|
395
|
+
if (replanned && getSpreadCorrectionActionCount(replanned) > 0) {
|
|
320
396
|
return { action: 'replanned', correction: replanned, occupied };
|
|
321
397
|
}
|
|
322
398
|
return { action: 'blocked', occupied };
|
|
@@ -342,8 +418,9 @@ function _snapshotFundState(manager) {
|
|
|
342
418
|
};
|
|
343
419
|
}
|
|
344
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';
|
|
345
|
-
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot,
|
|
346
|
-
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, isLastFillGuardBlocked } from './utils/system.js';
|
|
347
424
|
import * as MathUtils from './utils/math.js';
|
|
348
425
|
import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
|
|
349
426
|
import { getWhitelistFlags } from '../market_adapter_whitelist.js';
|
|
@@ -1438,10 +1515,13 @@ export async function initializeGrid(manager) {
|
|
|
1438
1515
|
manager._clearPendingFillCrawls?.('grid rebuild');
|
|
1439
1516
|
// Same generation contract for the LAST-FILL-GUARD pivot: it was
|
|
1440
1517
|
// armed against the previous ladder, and restoreLastFillPivot would
|
|
1441
|
-
// refuse it against the new genesis anyway. Drop it now
|
|
1442
|
-
//
|
|
1443
|
-
//
|
|
1444
|
-
//
|
|
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.
|
|
1445
1525
|
try {
|
|
1446
1526
|
if (typeof manager._resetLastFillPivot === 'function') {
|
|
1447
1527
|
manager._resetLastFillPivot('grid rebuild');
|
|
@@ -1449,6 +1529,7 @@ export async function initializeGrid(manager) {
|
|
|
1449
1529
|
else {
|
|
1450
1530
|
resetLastFillPivot(manager, 'grid rebuild');
|
|
1451
1531
|
}
|
|
1532
|
+
rearmLastFillPivotFromMarketFill(manager);
|
|
1452
1533
|
}
|
|
1453
1534
|
catch { }
|
|
1454
1535
|
// RC-8: Update boundary with notification to dependent systems
|
|
@@ -1476,7 +1557,7 @@ export async function initializeGrid(manager) {
|
|
|
1476
1557
|
const buyCtx = await _getSizingContext(manager, 'buy', { skipRecalc: true });
|
|
1477
1558
|
if (!sellCtx || !buyCtx)
|
|
1478
1559
|
throw new Error('Failed to retrieve sizing context for grid initialization');
|
|
1479
|
-
let sizedOrders = calculateOrderSizes(orders, manager.config, sellCtx.budget, buyCtx.budget,
|
|
1560
|
+
let sizedOrders = calculateOrderSizes(orders, manager.config, sellCtx.budget, buyCtx.budget, precA, precB);
|
|
1480
1561
|
// Verification of sizes
|
|
1481
1562
|
const sells = filterOrdersByType(sizedOrders, ORDER_TYPES.SELL).map((o) => Number(o.size || 0));
|
|
1482
1563
|
const buys = filterOrdersByType(sizedOrders, ORDER_TYPES.BUY).map((o) => Number(o.size || 0));
|
|
@@ -1788,7 +1869,7 @@ function _computeCommittedSizeDriftSync(manager) {
|
|
|
1788
1869
|
continue;
|
|
1789
1870
|
let newSizes;
|
|
1790
1871
|
try {
|
|
1791
|
-
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);
|
|
1792
1873
|
}
|
|
1793
1874
|
catch (_err) {
|
|
1794
1875
|
continue;
|
|
@@ -1985,7 +2066,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
|
|
|
1985
2066
|
if (allSideSlots.length === 0)
|
|
1986
2067
|
return collectActions ? { actions: [], changed: false } : undefined;
|
|
1987
2068
|
// Calculate geometric sizes for the ENTIRE rail
|
|
1988
|
-
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);
|
|
1989
2070
|
const actions = [];
|
|
1990
2071
|
let changed = false;
|
|
1991
2072
|
const freeKey = isBuy ? 'buyFree' : 'sellFree';
|
|
@@ -2240,7 +2321,7 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
|
|
|
2240
2321
|
return comparedOrders;
|
|
2241
2322
|
// Calculate geometric ideals for the ENTIRE side (all slots)
|
|
2242
2323
|
try {
|
|
2243
|
-
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);
|
|
2244
2325
|
// Map Ideal sizes to IDs for quick lookup
|
|
2245
2326
|
const idealMap = new Map();
|
|
2246
2327
|
sideSlots.forEach((slot, i) => idealMap.set(slot.id, allIdealSizes[i]));
|
|
@@ -2532,17 +2613,33 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2532
2613
|
}
|
|
2533
2614
|
catch { /* best-effort */ }
|
|
2534
2615
|
const decision = determineOrderSideByFunds(manager, lastPrice);
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
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
|
+
}
|
|
2538
2633
|
}
|
|
2539
2634
|
// Perform spread correction by placing orders on the chosen side.
|
|
2540
|
-
|
|
2635
|
+
if (!correction) {
|
|
2636
|
+
correction = await prepareSpreadCorrectionOrders(manager, chosenSide, manager.outOfSpread);
|
|
2637
|
+
}
|
|
2541
2638
|
if (!correction) {
|
|
2542
2639
|
stall = 'no-candidates';
|
|
2543
2640
|
return false;
|
|
2544
2641
|
}
|
|
2545
|
-
let placeCount = correction
|
|
2642
|
+
let placeCount = getSpreadCorrectionActionCount(correction);
|
|
2546
2643
|
// Fold each side into the stall cause; merge (never overwrite) across
|
|
2547
2644
|
// the starvation fallback so an UNFUNDED plan on the chosen side is
|
|
2548
2645
|
// not masked by an empty plan on the opposite side. The old code
|
|
@@ -2560,11 +2657,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2560
2657
|
const oppositeCorrection = await prepareSpreadCorrectionOrders(manager, oppositeSide, manager.outOfSpread);
|
|
2561
2658
|
if (oppositeCorrection) {
|
|
2562
2659
|
correction = oppositeCorrection;
|
|
2563
|
-
placeCount = oppositeCorrection
|
|
2660
|
+
placeCount = getSpreadCorrectionActionCount(oppositeCorrection);
|
|
2564
2661
|
const oppositeStall = classifySpreadStall(oppositeCorrection);
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2662
|
+
// Precedence merge (never overwrite): 'unfunded' > sync-repairable
|
|
2663
|
+
// > geometry bind > readiness > 'no-candidates'. The old collapse
|
|
2664
|
+
// to 'unfunded'/'no-candidates' dropped every named cause.
|
|
2665
|
+
sideStall = mergeSpreadStalls(sideStall, oppositeStall);
|
|
2568
2666
|
}
|
|
2569
2667
|
}
|
|
2570
2668
|
// Capture fund snapshot under lock for pre-flight verification before broadcast
|
|
@@ -2627,18 +2725,22 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2627
2725
|
? (freshBest.bestBuy + freshBest.bestSell) / 2
|
|
2628
2726
|
: Number(manager.config.startPrice) || 0;
|
|
2629
2727
|
const rePlanDecision = determineOrderSideByFunds(manager, freshPrice);
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
// signal the caller to refresh account totals/open orders.
|
|
2634
|
-
stall = 'no-free-funds';
|
|
2635
|
-
return { ordersPlaced: 0, partialsMoved: 0, stall };
|
|
2728
|
+
let rePlanCorrection = null;
|
|
2729
|
+
if (rePlanDecision.side) {
|
|
2730
|
+
rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
|
|
2636
2731
|
}
|
|
2637
|
-
|
|
2638
|
-
|
|
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) {
|
|
2639
2740
|
activeCorrection = rePlanCorrection;
|
|
2640
2741
|
manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
|
|
2641
|
-
`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');
|
|
2642
2744
|
}
|
|
2643
2745
|
else {
|
|
2644
2746
|
manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
|
|
@@ -2698,7 +2800,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2698
2800
|
lastResult = batchResult ?? null;
|
|
2699
2801
|
if (batchResult && batchResult.executed === true) {
|
|
2700
2802
|
await manager.recalculateFunds();
|
|
2701
|
-
const placed = activeCorrection
|
|
2803
|
+
const placed = getSpreadCorrectionActionCount(activeCorrection);
|
|
2702
2804
|
return { ordersPlaced: placed, partialsMoved: 0 };
|
|
2703
2805
|
}
|
|
2704
2806
|
const cause = classifySpreadRefusalCause(batchResult);
|
|
@@ -2710,7 +2812,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2710
2812
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Batch refused (${cause}); re-planning from fresh master ` +
|
|
2711
2813
|
`(attempt ${attempts + 1}/${MAX_SPREAD_ATTEMPTS})`, 'warn');
|
|
2712
2814
|
const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
|
|
2713
|
-
if (!replanned || (replanned
|
|
2815
|
+
if (!replanned || getSpreadCorrectionActionCount(replanned) === 0)
|
|
2714
2816
|
break;
|
|
2715
2817
|
recordSpreadCorrectionRetry(manager);
|
|
2716
2818
|
activeCorrection = replanned;
|
|
@@ -2872,7 +2974,7 @@ async function _computeDustThresholdMap(manager, type) {
|
|
|
2872
2974
|
.filter((o) => o.type === type)
|
|
2873
2975
|
.sort((a, b) => a.price - b.price);
|
|
2874
2976
|
const idealSizes = ctx && ctx.budget > 0
|
|
2875
|
-
? 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)
|
|
2876
2978
|
: [];
|
|
2877
2979
|
const map = new Map();
|
|
2878
2980
|
sideSlots.forEach((s, idx) => {
|
|
@@ -2950,7 +3052,7 @@ export async function getDustOrders(manager, partials, side) {
|
|
|
2950
3052
|
* @param {import('./types').OrderManager} manager - The manager instance.
|
|
2951
3053
|
* @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
|
|
2952
3054
|
* normalize sell-side funds into buy-side units for a fair cross-asset comparison.
|
|
2953
|
-
* @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.
|
|
2954
3056
|
*/
|
|
2955
3057
|
export function determineOrderSideByFunds(manager, currentMarketPrice) {
|
|
2956
3058
|
const buyAvailable = Math.min(Number(manager.funds?.available?.buy || 0), Number(manager.accountTotals?.buyFree || 0));
|
|
@@ -2995,7 +3097,7 @@ export function determineOrderSideByFunds(manager, currentMarketPrice) {
|
|
|
2995
3097
|
}
|
|
2996
3098
|
if (skipReason) {
|
|
2997
3099
|
manager.logger?.log?.(`Spread correction skipped: ${skipReason}; refusing to compare raw cross-asset units`, 'warn');
|
|
2998
|
-
return { side: null, reason: skipReason };
|
|
3100
|
+
return { side: null, reason: skipReason, code: 'market-price-unavailable' };
|
|
2999
3101
|
}
|
|
3000
3102
|
if (!side) {
|
|
3001
3103
|
// PURE FUND-DRIVEN: a zero/insufficient free balance skips the
|
|
@@ -3009,7 +3111,11 @@ export function determineOrderSideByFunds(manager, currentMarketPrice) {
|
|
|
3009
3111
|
: `Spread correction skipped: insufficient free funds ` +
|
|
3010
3112
|
`(buy=${Format.formatAmount8(buyAvailable)}, sell=${Format.formatAmount8(sellAvailable)})`, 'warn');
|
|
3011
3113
|
}
|
|
3012
|
-
return {
|
|
3114
|
+
return {
|
|
3115
|
+
side,
|
|
3116
|
+
reason: side ? `Choosing ${side}` : (skipReason || 'Insufficient free funds'),
|
|
3117
|
+
...(side ? {} : { code: 'no-free-funds' })
|
|
3118
|
+
};
|
|
3013
3119
|
}
|
|
3014
3120
|
/**
|
|
3015
3121
|
* Resolve the MIN_SPREAD_ORDERS gap reserve used by boundary promotion.
|
|
@@ -3106,6 +3212,56 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3106
3212
|
: 'no-candidates';
|
|
3107
3213
|
const railType = preferredSide;
|
|
3108
3214
|
const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
|
|
3215
|
+
// LAST-FILL FILTER (planner-side, same predicate as the broadcast guard).
|
|
3216
|
+
//
|
|
3217
|
+
// The guard drops any create at/through the last fill price, so a plan
|
|
3218
|
+
// built from such candidates can only end as "batch prepared but not
|
|
3219
|
+
// executed" (observed live: the only funded candidate was a SELL below
|
|
3220
|
+
// the 0.447640 fill, both attempts were dropped, and the correction
|
|
3221
|
+
// burned its cycle on a refusal). Filter here instead: the quota is then
|
|
3222
|
+
// filled from candidates the guard can accept, and an empty pool is an
|
|
3223
|
+
// honest "nothing to place" rather than a vetoed batch.
|
|
3224
|
+
//
|
|
3225
|
+
// Uses resolveLastFillGuardReference (the SAME effective pivot the guard
|
|
3226
|
+
// probes, including the persisted fallback that survives a rebuild) so
|
|
3227
|
+
// planner and guard cannot drift apart.
|
|
3228
|
+
const lastFillRef = resolveLastFillGuardReference(manager);
|
|
3229
|
+
const lastFillPivot = lastFillRef.price != null && Number.isFinite(Number(lastFillRef.price))
|
|
3230
|
+
? Number(lastFillRef.price)
|
|
3231
|
+
: null;
|
|
3232
|
+
const lastFillSide = lastFillRef.type;
|
|
3233
|
+
const lastFillBlocks = (c) => {
|
|
3234
|
+
if (lastFillPivot == null || lastFillSide == null)
|
|
3235
|
+
return false;
|
|
3236
|
+
if (c?.price == null || !Number.isFinite(Number(c.price)))
|
|
3237
|
+
return false;
|
|
3238
|
+
return isLastFillGuardBlocked(Number(c.price), railType, lastFillPivot, lastFillSide).blocked === true;
|
|
3239
|
+
};
|
|
3240
|
+
let lastFillExcluded = 0;
|
|
3241
|
+
// A slot can legitimately appear in MORE than one candidate pool (an
|
|
3242
|
+
// empty in-rail slot normalized to SPREAD qualifies for both the SPREAD
|
|
3243
|
+
// pool and the orphan pool; the merge below dedupes them), so count the
|
|
3244
|
+
// excluded SLOTS, not the pool visits — otherwise each vetoed slot is
|
|
3245
|
+
// reported twice and the "Excluded N" line overstates how much of the
|
|
3246
|
+
// side the pivot blocked, exactly when the pools overlap most.
|
|
3247
|
+
const lastFillExcludedSlotIds = new Set();
|
|
3248
|
+
const passesLastFill = (c) => {
|
|
3249
|
+
if (!lastFillBlocks(c))
|
|
3250
|
+
return true;
|
|
3251
|
+
const slotId = c?.id != null ? String(c.id) : '';
|
|
3252
|
+
if (slotId === '') {
|
|
3253
|
+
lastFillExcluded++;
|
|
3254
|
+
return false;
|
|
3255
|
+
}
|
|
3256
|
+
if (lastFillExcludedSlotIds.has(slotId))
|
|
3257
|
+
return false;
|
|
3258
|
+
lastFillExcludedSlotIds.add(slotId);
|
|
3259
|
+
lastFillExcluded++;
|
|
3260
|
+
return false;
|
|
3261
|
+
};
|
|
3262
|
+
const lastFillRuleText = lastFillPivot == null
|
|
3263
|
+
? ''
|
|
3264
|
+
: `${railType === ORDER_TYPES.BUY ? 'BUY must be below' : 'SELL must be above'} the last fill ${Format.formatPrice6(lastFillPivot)}`;
|
|
3109
3265
|
const configuredMissingSlots = Number(outOfSpread || 0);
|
|
3110
3266
|
const missingSlots = configuredMissingSlots > 0
|
|
3111
3267
|
? Math.floor(configuredMissingSlots)
|
|
@@ -3292,6 +3448,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3292
3448
|
.filter((o) => o.type === ORDER_TYPES.SPREAD
|
|
3293
3449
|
&& isSlotAvailable(o)
|
|
3294
3450
|
&& getSlotCorrectType(o) === railType)
|
|
3451
|
+
.filter(passesLastFill)
|
|
3295
3452
|
.filter(tightensSpread)
|
|
3296
3453
|
.filter(doesNotCrossMarket)
|
|
3297
3454
|
.filter(doesNotCollideUnmatched)
|
|
@@ -3336,6 +3493,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3336
3493
|
&& o.state === ORDER_STATES.VIRTUAL
|
|
3337
3494
|
&& !o.orderId
|
|
3338
3495
|
&& getSlotCorrectType(o) === railType)
|
|
3496
|
+
.filter(passesLastFill)
|
|
3339
3497
|
.filter(tightensSpread)
|
|
3340
3498
|
.filter(doesNotCrossMarket)
|
|
3341
3499
|
.filter(doesNotCollideUnmatched)
|
|
@@ -3432,10 +3590,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3432
3590
|
// consume the whole quota without ever entering the gap.
|
|
3433
3591
|
const remainingQuota = Math.max(0, missingSlots - orphanedVirtualCandidates.length);
|
|
3434
3592
|
let spreadCandidates = [
|
|
3435
|
-
...promotedCandidates,
|
|
3593
|
+
...promotedCandidates.filter(passesLastFill),
|
|
3436
3594
|
...typedSpreadCandidates.slice(0, remainingQuota),
|
|
3437
3595
|
...orphanedVirtualCandidates
|
|
3438
3596
|
];
|
|
3597
|
+
if (lastFillExcluded > 0) {
|
|
3598
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Excluded ${lastFillExcluded} candidate(s) from ${sideName} planning: ` +
|
|
3599
|
+
`${lastFillRuleText} (the broadcast guard would drop them)`, 'debug');
|
|
3600
|
+
}
|
|
3439
3601
|
// Dedupe by slot id: an empty in-rail slot typed SPREAD (normalized) now
|
|
3440
3602
|
// qualifies for BOTH orphanedVirtualCandidates and typedSpreadCandidates
|
|
3441
3603
|
// (both accept SPREAD type + rail geometry), so a single slot can be
|
|
@@ -3483,10 +3645,57 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3483
3645
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Identified ${spreadCandidates.length}/${missingSlots} slot(s) for activation on ${sideName} (orphaned=${orphanedVirtualCandidates.length}, spread=${spreadCandidates.length - orphanedVirtualCandidates.length})`, 'debug');
|
|
3484
3646
|
}
|
|
3485
3647
|
if (spreadCandidates.length === 0) {
|
|
3486
|
-
manager.logger?.log?.(
|
|
3487
|
-
? `[SPREAD-CORRECTION] No
|
|
3488
|
-
|
|
3489
|
-
|
|
3648
|
+
manager.logger?.log?.(lastFillExcluded > 0 && lastFillPivot != null
|
|
3649
|
+
? `[SPREAD-CORRECTION] No placeable ${sideName} slot: every tightening slot is at/through the last fill ` +
|
|
3650
|
+
`${Format.formatPrice6(lastFillPivot)} (${lastFillRuleText}). The spread cannot be tightened on this ` +
|
|
3651
|
+
`side; a boundary move or a fill must restore headroom.`
|
|
3652
|
+
: bestLiveOnRail == null
|
|
3653
|
+
? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
|
|
3654
|
+
: `[SPREAD-CORRECTION] No spread-tightening slot on ${sideName} (best live ${bestLiveOnRail}); every remaining empty slot sits beyond the live window and cannot narrow the spread. Skipping.`, 'warn');
|
|
3655
|
+
// Name the geometry bind: the window itself is wrong (a sell slot
|
|
3656
|
+
// below the last sale means the boundary/crawl is behind the fill),
|
|
3657
|
+
// so placement cannot repair the side and a re-center can.
|
|
3658
|
+
const emptyStall = (lastFillExcluded > 0 && lastFillPivot != null)
|
|
3659
|
+
? 'last-fill-blocked'
|
|
3660
|
+
: refusalStallHint;
|
|
3661
|
+
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: emptyStall, origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3662
|
+
}
|
|
3663
|
+
// RAIL-OVERSUBSCRIBED: availableFund is chainFree − virtualReservation, so
|
|
3664
|
+
// it reads 0 whenever the empty rail already reserves more than the free
|
|
3665
|
+
// balance (observed live: free 454560.80 vs virtual 456046.21, a 1485 base
|
|
3666
|
+
// short, "planned 3, placing 0" every cycle for 84 minutes). That is not
|
|
3667
|
+
// "wait for a fill": the rail must be re-sized from chain truth, which a
|
|
3668
|
+
// re-center does. Detect it BEFORE the sizing-context gate (a zero budget
|
|
3669
|
+
// is the very symptom) and flag it so the persistence watchdog escalates
|
|
3670
|
+
// on its short fund window instead of the 30-minute structural one.
|
|
3671
|
+
{
|
|
3672
|
+
const sideChainFree = Math.max(0, Number(sideName === 'buy'
|
|
3673
|
+
? manager.accountTotals?.buyFree
|
|
3674
|
+
: manager.accountTotals?.sellFree) || 0);
|
|
3675
|
+
const sideVirtual = Math.max(0, Number(sideName === 'buy'
|
|
3676
|
+
? manager.funds?.virtual?.buy
|
|
3677
|
+
: manager.funds?.virtual?.sell) || 0);
|
|
3678
|
+
const sideAvailable = Math.max(0, Math.min(Number(manager.funds?.available?.[sideName] || 0), sideChainFree));
|
|
3679
|
+
const epsilon = 1e-8;
|
|
3680
|
+
if (sideAvailable <= epsilon && (sideVirtual - sideChainFree) > epsilon) {
|
|
3681
|
+
try {
|
|
3682
|
+
manager._spreadRailOversubscribed = {
|
|
3683
|
+
side: sideName, virtual: sideVirtual, free: sideChainFree, at: Date.now()
|
|
3684
|
+
};
|
|
3685
|
+
}
|
|
3686
|
+
catch { /* best-effort */ }
|
|
3687
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] ${sideName} rail is OVERSUBSCRIBED: virtual reservation ` +
|
|
3688
|
+
`${Format.formatAmount8(sideVirtual)} exceeds chain free ${Format.formatAmount8(sideChainFree)} ` +
|
|
3689
|
+
`by ${Format.formatAmount8(sideVirtual - sideChainFree)} — the projection is stale, so the ` +
|
|
3690
|
+
`correction funds what the chain actually holds free; a rail re-size (structural re-center) ` +
|
|
3691
|
+
`is still the durable repair`, 'warn');
|
|
3692
|
+
}
|
|
3693
|
+
else if (sideAvailable > epsilon) {
|
|
3694
|
+
try {
|
|
3695
|
+
manager._spreadRailOversubscribed = null;
|
|
3696
|
+
}
|
|
3697
|
+
catch { /* best-effort */ }
|
|
3698
|
+
}
|
|
3490
3699
|
}
|
|
3491
3700
|
const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
|
|
3492
3701
|
const sideSlots = allOrders
|
|
@@ -3497,16 +3706,18 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3497
3706
|
...spreadCandidates.map((slot) => ({ ...slot, type: railType }))
|
|
3498
3707
|
].sort((a, b) => a.price - b.price);
|
|
3499
3708
|
const ctx = await _getSizingContext(manager, sideName);
|
|
3500
|
-
if (!ctx ||
|
|
3501
|
-
// A
|
|
3502
|
-
|
|
3503
|
-
// arming the refresh for it. A missing context or an empty rail is
|
|
3504
|
-
// genuinely structural.
|
|
3505
|
-
const stallHint = (ctx && Number(ctx.budget) <= 0) ? 'unfunded' : 'no-candidates';
|
|
3506
|
-
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3709
|
+
if (!ctx || syntheticSideSlots.length === 0) {
|
|
3710
|
+
// A missing context or an empty rail is genuinely structural.
|
|
3711
|
+
return { ordersToPlace: [], ordersToUpdate: [], ordersToRotate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3507
3712
|
}
|
|
3508
3713
|
const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
|
|
3509
|
-
|
|
3714
|
+
// Zero free funds must NOT return early: the fund-constrained rotation
|
|
3715
|
+
// below is the only repair a fully allocated rail has. With no budget
|
|
3716
|
+
// every create is skipped below, then a resting order is rotated into
|
|
3717
|
+
// the promoted slot (same booked size, no new commitment).
|
|
3718
|
+
const idealSizes = ctx.budget > 0
|
|
3719
|
+
? allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, (manager.config.weightDistribution ?? {})[sideName], (manager.config.incrementPercent ?? 0) / 100, railType === ORDER_TYPES.BUY, ctx.precision)
|
|
3720
|
+
: [];
|
|
3510
3721
|
const idealById = new Map();
|
|
3511
3722
|
syntheticSideSlots.forEach((slot, idx) => {
|
|
3512
3723
|
idealById.set(slot.id, Number(idealSizes[idx] || 0));
|
|
@@ -3541,18 +3752,44 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3541
3752
|
});
|
|
3542
3753
|
}
|
|
3543
3754
|
}
|
|
3544
|
-
|
|
3545
|
-
|
|
3755
|
+
// Chain-truth budget (see deriveChainTruthFundBudget): `availableFund`
|
|
3756
|
+
// already had the virtual reservation subtracted, and that reservation
|
|
3757
|
+
// is the projection of THESE candidates — subtracting it from the
|
|
3758
|
+
// budget that funds them is circular. When the projection exceeds what
|
|
3759
|
+
// the chain holds free it reads 0 forever, so the holes can never be
|
|
3760
|
+
// filled and the projection can never shrink (live: `planned 3,
|
|
3761
|
+
// placing 0` for 84 minutes). Re-derive from chain truth, capped by
|
|
3762
|
+
// what the candidates need and by the real free balance.
|
|
3763
|
+
const candidateIdeals = prioritizedTargets.reduce((sum, t) => sum + Math.max(0, Number(t.ideal) || 0), 0);
|
|
3764
|
+
const chainFreeForSide = Math.max(0, Number(sideName === 'buy'
|
|
3765
|
+
? manager.accountTotals?.buyFree
|
|
3766
|
+
: manager.accountTotals?.sellFree) || 0);
|
|
3767
|
+
const virtualIntentForSide = Math.max(0, Number(sideName === 'buy'
|
|
3768
|
+
? manager.funds?.virtual?.buy
|
|
3769
|
+
: manager.funds?.virtual?.sell) || 0);
|
|
3770
|
+
const fundBudget = MathUtils.deriveChainTruthFundBudget({
|
|
3771
|
+
availableFund,
|
|
3772
|
+
virtualIntent: virtualIntentForSide,
|
|
3773
|
+
chainFree: chainFreeForSide,
|
|
3774
|
+
candidateIdeals,
|
|
3775
|
+
});
|
|
3776
|
+
if (fundBudget.eroded) {
|
|
3777
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] ${sideName} projection exceeds chain free by ` +
|
|
3778
|
+
`${Format.formatAmount8(fundBudget.oversubscribed)}; funding the candidates from chain truth ` +
|
|
3779
|
+
`(${Format.formatAmount8(fundBudget.budget)} for ${Format.formatAmount8(candidateIdeals)} of ideal ` +
|
|
3780
|
+
`size) instead of placing nothing`, 'warn');
|
|
3546
3781
|
}
|
|
3547
|
-
let remainingBudget =
|
|
3782
|
+
let remainingBudget = fundBudget.budget;
|
|
3548
3783
|
// FUNDING PROBE (diagnostic): one line per correction cycle showing the
|
|
3549
3784
|
// quantities that decide whether candidates can be funded. availableFund
|
|
3550
3785
|
// is min(funds.available[side], accountTotals[side]Free); when the
|
|
3551
3786
|
// virtual rail has already reserved the free balance this reads ~0 even
|
|
3552
|
-
// though the side still holds inventory
|
|
3553
|
-
//
|
|
3787
|
+
// though the side still holds inventory. `spendable` is what the loop
|
|
3788
|
+
// actually spends (chain truth when the projection is oversubscribed),
|
|
3789
|
+
// so the two never have to be inferred from each other.
|
|
3554
3790
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Funding probe side=${sideName}: ` +
|
|
3555
3791
|
`availableFund=${Format.formatAmount8(availableFund)} ` +
|
|
3792
|
+
`spendable=${Format.formatAmount8(fundBudget.budget)} ` +
|
|
3556
3793
|
`budget=${Format.formatAmount8(Number(ctx.budget || 0))} ` +
|
|
3557
3794
|
`virtual=${Format.formatAmount8(Number(sideName === 'buy' ? manager.funds?.virtual?.buy : manager.funds?.virtual?.sell) || 0)} ` +
|
|
3558
3795
|
`free=${Format.formatAmount8(Number(sideName === 'buy' ? manager.accountTotals?.buyFree : manager.accountTotals?.sellFree) || 0)} ` +
|
|
@@ -3593,10 +3830,103 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3593
3830
|
});
|
|
3594
3831
|
remainingBudget -= createSize;
|
|
3595
3832
|
}
|
|
3833
|
+
// FUND-CONSTRAINED PROMOTION: free funds could not fund every
|
|
3834
|
+
// tightening slot. A fully allocated rail (botFunds 100%, every slot
|
|
3835
|
+
// resting) has ~0 free forever, so create-only repair can never close
|
|
3836
|
+
// the spread (live 2026-10-30: "planned 4, placing 1"). Rotate a
|
|
3837
|
+
// resting same-side order into each unfunded promoted slot instead.
|
|
3838
|
+
// The move commits NO new funds (size is the source's booked size) and
|
|
3839
|
+
// is bounded by the same promotion/geometry guards as a create.
|
|
3840
|
+
const ordersToRotate = [];
|
|
3841
|
+
{
|
|
3842
|
+
const fundedCreateIds = new Set(ordersToPlace.map((o) => String(o.id)));
|
|
3843
|
+
// Use the POST-FILTER candidate list, not raw promotedCandidates:
|
|
3844
|
+
// spreadCandidates has already passed slot dedupe and the
|
|
3845
|
+
// placed-price collision filter (a promoted slot whose price is
|
|
3846
|
+
// already occupied from another slot must not become a rotation
|
|
3847
|
+
// destination). Re-derive the subset instead of bypassing those
|
|
3848
|
+
// guards.
|
|
3849
|
+
const promotedIds = new Set(promotedCandidates.map((c) => String(c.id)));
|
|
3850
|
+
const unfundedPromotions = spreadCandidates
|
|
3851
|
+
.filter((c) => promotedIds.has(String(c.id)))
|
|
3852
|
+
.filter((c) => !fundedCreateIds.has(String(c.id)))
|
|
3853
|
+
.filter((c) => isSlotAvailable(c));
|
|
3854
|
+
if (unfundedPromotions.length > 0) {
|
|
3855
|
+
const windowIds = liveWindowIdSet(manager, railType);
|
|
3856
|
+
const edgeIds = edgeOrderIdSet(allSlotsByPrice, manager.config, railType, resolveLiveEdgeAnchorPrice(manager, sideName), windowIds);
|
|
3857
|
+
const sourcePool = allOrders
|
|
3858
|
+
.filter((o) => o.type === railType
|
|
3859
|
+
&& o.state === ORDER_STATES.ACTIVE
|
|
3860
|
+
&& !!o.orderId
|
|
3861
|
+
&& Number(o.size) > 0
|
|
3862
|
+
&& o.price != null
|
|
3863
|
+
&& Number.isFinite(Number(o.price)))
|
|
3864
|
+
.filter((o) => {
|
|
3865
|
+
const idx = slotIndexMap.get(o.id);
|
|
3866
|
+
if (idx === undefined)
|
|
3867
|
+
return false;
|
|
3868
|
+
return railType === ORDER_TYPES.BUY ? idx <= buyEndIdx : idx >= sellStartIdx;
|
|
3869
|
+
})
|
|
3870
|
+
.filter((o) => !edgeIds || !edgeIds.has(String(o.id)))
|
|
3871
|
+
.sort((a, b) => railType === ORDER_TYPES.BUY
|
|
3872
|
+
? Number(a.price) - Number(b.price)
|
|
3873
|
+
: Number(b.price) - Number(a.price));
|
|
3874
|
+
const usedSourceIds = new Set();
|
|
3875
|
+
for (const dest of unfundedPromotions) {
|
|
3876
|
+
const source = sourcePool.find((s) => !usedSourceIds.has(String(s.id)));
|
|
3877
|
+
if (!source)
|
|
3878
|
+
break;
|
|
3879
|
+
const sourceSize = Number(source.size);
|
|
3880
|
+
if (!Number.isFinite(sourceSize) || sourceSize <= 0)
|
|
3881
|
+
continue;
|
|
3882
|
+
// Same booked size: a rotation is not a re-size and must
|
|
3883
|
+
// never need new funds. If the source size is unhealthy at
|
|
3884
|
+
// the destination (it is the same asset/side, so this is
|
|
3885
|
+
// only a corrupt-size guard), skip rather than shrink.
|
|
3886
|
+
if (!isOrderHealthy(sourceSize, railType, manager.assets, sourceSize))
|
|
3887
|
+
continue;
|
|
3888
|
+
const destPrice = Number(dest.price);
|
|
3889
|
+
if (!Number.isFinite(destPrice) || destPrice <= 0)
|
|
3890
|
+
continue;
|
|
3891
|
+
ordersToRotate.push({
|
|
3892
|
+
id: String(source.id),
|
|
3893
|
+
orderId: String(source.orderId),
|
|
3894
|
+
oldOrder: source,
|
|
3895
|
+
newGridId: String(dest.id),
|
|
3896
|
+
newPrice: destPrice,
|
|
3897
|
+
newSize: sourceSize,
|
|
3898
|
+
type: railType
|
|
3899
|
+
});
|
|
3900
|
+
usedSourceIds.add(String(source.id));
|
|
3901
|
+
}
|
|
3902
|
+
if (ordersToRotate.length > 0) {
|
|
3903
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained promotion on ${sideName}: rotating ` +
|
|
3904
|
+
`${ordersToRotate.length} resting order(s) into the gap ` +
|
|
3905
|
+
`(${ordersToRotate.map((r) => `${r.id}->${r.newGridId}`).join(', ')}) — ` +
|
|
3906
|
+
`no new funds required`, 'warn');
|
|
3907
|
+
}
|
|
3908
|
+
}
|
|
3909
|
+
}
|
|
3910
|
+
if (ordersToPlace.length === 0 && ordersToRotate.length === 0) {
|
|
3911
|
+
// Candidates existed but neither free funds nor a rotation source
|
|
3912
|
+
// could act: a FUND/rail-structure stall, not a structural absence.
|
|
3913
|
+
return {
|
|
3914
|
+
ordersToPlace: [],
|
|
3915
|
+
ordersToUpdate: [],
|
|
3916
|
+
ordersToRotate: [],
|
|
3917
|
+
plannedCount: spreadCandidates.length,
|
|
3918
|
+
stallHint: 'unfunded',
|
|
3919
|
+
origin: COW_ORIGINS.SPREAD_CORRECTION
|
|
3920
|
+
};
|
|
3921
|
+
}
|
|
3596
3922
|
let boundaryIdx;
|
|
3597
|
-
const placedPromotedIds = new Set(
|
|
3598
|
-
|
|
3599
|
-
|
|
3923
|
+
const placedPromotedIds = new Set([
|
|
3924
|
+
...ordersToPlace
|
|
3925
|
+
.filter((order) => promotedCandidates.some((slot) => slot.id === order.id))
|
|
3926
|
+
.map((order) => order.id),
|
|
3927
|
+
...ordersToRotate
|
|
3928
|
+
.map((rotation) => rotation.newGridId)
|
|
3929
|
+
]);
|
|
3600
3930
|
if (placedPromotedIds.size > 0) {
|
|
3601
3931
|
// Derive boundary from the placed promoted set's extremes (via
|
|
3602
3932
|
// slotIndexMap), not the contiguous prefix. Any promoted-but-
|
|
@@ -3648,12 +3978,25 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3648
3978
|
if (spreadCandidates.length < missingSlots) {
|
|
3649
3979
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Requested ${missingSlots} extra slot(s), found ${spreadCandidates.length} available slot(s) on ${sideName}`, 'warn');
|
|
3650
3980
|
}
|
|
3651
|
-
if (ordersToPlace.length < spreadCandidates.length) {
|
|
3652
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained placement on ${sideName}: planned ${spreadCandidates.length},
|
|
3981
|
+
if (ordersToPlace.length + ordersToRotate.length < spreadCandidates.length) {
|
|
3982
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained placement on ${sideName}: planned ${spreadCandidates.length}, ` +
|
|
3983
|
+
`placing ${ordersToPlace.length} create(s) + ${ordersToRotate.length} rotation(s)`, 'info');
|
|
3653
3984
|
}
|
|
3654
|
-
if (ordersToPlace.length > 0) {
|
|
3655
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length},
|
|
3985
|
+
if (ordersToPlace.length > 0 || ordersToRotate.length > 0) {
|
|
3986
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length}, rotations=${ordersToRotate.length}, ` +
|
|
3987
|
+
`remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
|
|
3656
3988
|
}
|
|
3657
|
-
return {
|
|
3989
|
+
return {
|
|
3990
|
+
ordersToPlace,
|
|
3991
|
+
ordersToUpdate: [],
|
|
3992
|
+
ordersToRotate,
|
|
3993
|
+
// Number of tightening candidates found before funding/rotation.
|
|
3994
|
+
// Include rotation targets: a rotation-only plan has a non-zero
|
|
3995
|
+
// planned count and must not look like an empty plan to callers
|
|
3996
|
+
// that distinguish 'unfunded' from 'no-candidates'.
|
|
3997
|
+
plannedCount: spreadCandidates.length,
|
|
3998
|
+
...(boundaryIdx === undefined ? {} : { boundaryIdx }),
|
|
3999
|
+
origin: COW_ORIGINS.SPREAD_CORRECTION
|
|
4000
|
+
};
|
|
3658
4001
|
}
|
|
3659
4002
|
//# sourceMappingURL=grid.js.map
|