dexbot 1.6.17 → 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 +32 -0
- package/analysis/README.md +10 -9
- 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/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/tradingview_uplot_chart_generator.js +3 -3
- 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/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- 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 +461 -43
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +56 -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_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 +19 -14
- package/dist/modules/order/grid.js +262 -61
- 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 +9 -3
- package/dist/modules/order/manager.d.ts +10 -0
- package/dist/modules/order/manager.js +41 -11
- package/dist/modules/order/strategy.js +22 -2
- 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 +8 -9
- package/dist/modules/order/utils/math.js +24 -13
- package/dist/modules/order/utils/order.d.ts +52 -11
- package/dist/modules/order/utils/order.js +137 -21
- package/dist/modules/order/utils/system.d.ts +73 -29
- package/dist/modules/order/utils/system.js +239 -48
- package/dist/modules/order/utils/validate.d.ts +1 -0
- package/dist/modules/order/utils/validate.js +4 -1
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +9 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +20 -10
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +9 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
- package/docs/GRID_PRICE_INVARIANT.md +24 -4
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +15 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +123 -36
- package/docs/README.md +1 -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 +18 -14
- package/package.json +4 -3
|
@@ -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, isLastFillGuardBlocked } 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,27 @@ 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
|
-
return isLastFillGuardBlocked(Number(c.price),
|
|
3238
|
+
return isLastFillGuardBlocked(Number(c.price), railType, lastFillPivot, lastFillSide).blocked === true;
|
|
3158
3239
|
};
|
|
3159
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();
|
|
3160
3248
|
const passesLastFill = (c) => {
|
|
3161
3249
|
if (!lastFillBlocks(c))
|
|
3162
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);
|
|
3163
3259
|
lastFillExcluded++;
|
|
3164
3260
|
return false;
|
|
3165
3261
|
};
|
|
@@ -3610,16 +3706,18 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3610
3706
|
...spreadCandidates.map((slot) => ({ ...slot, type: railType }))
|
|
3611
3707
|
].sort((a, b) => a.price - b.price);
|
|
3612
3708
|
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 };
|
|
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 };
|
|
3620
3712
|
}
|
|
3621
3713
|
const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
|
|
3622
|
-
|
|
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
|
+
: [];
|
|
3623
3721
|
const idealById = new Map();
|
|
3624
3722
|
syntheticSideSlots.forEach((slot, idx) => {
|
|
3625
3723
|
idealById.set(slot.id, Number(idealSizes[idx] || 0));
|
|
@@ -3654,9 +3752,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3654
3752
|
});
|
|
3655
3753
|
}
|
|
3656
3754
|
}
|
|
3657
|
-
if (prioritizedTargets.length === 0) {
|
|
3658
|
-
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
3659
|
-
}
|
|
3660
3755
|
// Chain-truth budget (see deriveChainTruthFundBudget): `availableFund`
|
|
3661
3756
|
// already had the virtual reservation subtracted, and that reservation
|
|
3662
3757
|
// is the projection of THESE candidates — subtracting it from the
|
|
@@ -3735,10 +3830,103 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3735
3830
|
});
|
|
3736
3831
|
remainingBudget -= createSize;
|
|
3737
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
|
+
}
|
|
3738
3922
|
let boundaryIdx;
|
|
3739
|
-
const placedPromotedIds = new Set(
|
|
3740
|
-
|
|
3741
|
-
|
|
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
|
+
]);
|
|
3742
3930
|
if (placedPromotedIds.size > 0) {
|
|
3743
3931
|
// Derive boundary from the placed promoted set's extremes (via
|
|
3744
3932
|
// slotIndexMap), not the contiguous prefix. Any promoted-but-
|
|
@@ -3790,12 +3978,25 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3790
3978
|
if (spreadCandidates.length < missingSlots) {
|
|
3791
3979
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Requested ${missingSlots} extra slot(s), found ${spreadCandidates.length} available slot(s) on ${sideName}`, 'warn');
|
|
3792
3980
|
}
|
|
3793
|
-
if (ordersToPlace.length < spreadCandidates.length) {
|
|
3794
|
-
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');
|
|
3795
3984
|
}
|
|
3796
|
-
if (ordersToPlace.length > 0) {
|
|
3797
|
-
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');
|
|
3798
3988
|
}
|
|
3799
|
-
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
|
+
};
|
|
3800
4001
|
}
|
|
3801
4002
|
//# sourceMappingURL=grid.js.map
|
|
@@ -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))
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
import { ORDER_TYPES, ORDER_STATES, TIMING, BTS_PRECISION } from '../constants.js';
|
|
8
8
|
import { readOpenOrdersGuarded } from '../chain_orders.js';
|
|
9
9
|
import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, sameGridLevel } from './utils/math.js';
|
|
10
|
-
import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge,
|
|
10
|
+
import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
|
|
11
|
+
import { parseSlotIndex } from './utils/slot.js';
|
|
11
12
|
import { resolveAccountRef } from './utils/system.js';
|
|
12
13
|
import * as Format from './format.js';
|
|
13
14
|
import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
|
|
@@ -86,7 +86,11 @@ declare const utils: {
|
|
|
86
86
|
} | null;
|
|
87
87
|
}): system.SpreadCorrectionReadiness;
|
|
88
88
|
resolveSpreadMarketReference(manager: import("../types.js").OrderManagerLike): number | null;
|
|
89
|
-
reanchorBoundaryFromLastFill(manager: import("../types.js").OrderManagerLike, boundaryIdx: number | null | undefined, slots: import("../types.js").ManagedOrder[] | null | undefined, gapSlots: number
|
|
89
|
+
reanchorBoundaryFromLastFill(manager: import("../types.js").OrderManagerLike, boundaryIdx: number | null | undefined, slots: import("../types.js").ManagedOrder[] | null | undefined, gapSlots: number, fills?: Array<{
|
|
90
|
+
id?: string;
|
|
91
|
+
type?: string;
|
|
92
|
+
price?: unknown;
|
|
93
|
+
}> | null | undefined): {
|
|
90
94
|
boundaryIdx: number | null;
|
|
91
95
|
reanchored: boolean;
|
|
92
96
|
from?: number | null;
|
|
@@ -99,7 +103,7 @@ declare const utils: {
|
|
|
99
103
|
price: number | null;
|
|
100
104
|
type: string | null;
|
|
101
105
|
};
|
|
102
|
-
isLastFillGuardBlocked(price: number,
|
|
106
|
+
isLastFillGuardBlocked(price: number, type: unknown, lastPrice: number | null, lastType: string | null): {
|
|
103
107
|
blocked: boolean;
|
|
104
108
|
pivot: number | null;
|
|
105
109
|
threshold?: number | null;
|
|
@@ -107,6 +111,7 @@ declare const utils: {
|
|
|
107
111
|
restoreLastMarketFill(manager: import("../types.js").OrderManagerLike, persisted: unknown, options?: {
|
|
108
112
|
now?: number;
|
|
109
113
|
}): boolean;
|
|
114
|
+
rearmLastFillPivotFromMarketFill(manager: import("../types.js").OrderManagerLike): boolean;
|
|
110
115
|
normalizeLastFillPivot(row: unknown): {
|
|
111
116
|
price: number;
|
|
112
117
|
type: string;
|
|
@@ -191,6 +196,7 @@ declare const utils: {
|
|
|
191
196
|
reason?: string;
|
|
192
197
|
};
|
|
193
198
|
parseChainOrder: typeof order.parseChainOrder;
|
|
199
|
+
resolveLiveOrderLadderPosition: typeof order.resolveLiveOrderLadderPosition;
|
|
194
200
|
applyChainSizeToGridOrder: typeof order.applyChainSizeToGridOrder;
|
|
195
201
|
buildFillKey: typeof order.buildFillKey;
|
|
196
202
|
correctOrderPriceOnChain: typeof order.correctOrderPriceOnChain;
|
|
@@ -213,7 +219,6 @@ declare const utils: {
|
|
|
213
219
|
crossingCandidateChainId: typeof order.crossingCandidateChainId;
|
|
214
220
|
isCrossingCheckCandidate: typeof order.isCrossingCheckCandidate;
|
|
215
221
|
buildCrossingCheckCandidates: typeof order.buildCrossingCheckCandidates;
|
|
216
|
-
parseSlotIndex: typeof order.parseSlotIndex;
|
|
217
222
|
filterOrdersByType: typeof order.filterOrdersByType;
|
|
218
223
|
buildOutsideInPairGroups: typeof order.buildOutsideInPairGroups;
|
|
219
224
|
extractBatchOperationResults: typeof order.extractBatchOperationResults;
|
|
@@ -254,6 +259,7 @@ declare const utils: {
|
|
|
254
259
|
chainOrderUnchangedFromCache: typeof order.chainOrderUnchangedFromCache;
|
|
255
260
|
detectCrossedBookPlan: typeof order.detectCrossedBookPlan;
|
|
256
261
|
collectKnownOnChainOrderIds: typeof order.collectKnownOnChainOrderIds;
|
|
262
|
+
collectEdgePinnedFillIds: typeof order.collectEdgePinnedFillIds;
|
|
257
263
|
edgeOrderIdSet: typeof order.edgeOrderIdSet;
|
|
258
264
|
liveWindowIdSet: typeof order.liveWindowIdSet;
|
|
259
265
|
checkGridPriceInvariant: typeof order.checkGridPriceInvariant;
|
|
@@ -759,6 +759,16 @@ declare class OrderManager implements OrderManagerLike {
|
|
|
759
759
|
* discriminator (null => disabled). The per-side fields are not read by the
|
|
760
760
|
* guard itself; they feed the book-seed cold-check and per-side seeding in
|
|
761
761
|
* seedLastFilledPricesFromBook.
|
|
762
|
+
*
|
|
763
|
+
* EDGE-PINNED FILLS ARE SKIPPED. An edge order is static fat-finger
|
|
764
|
+
* insurance resting at the grid floor/ceiling, not market movement: the
|
|
765
|
+
* boundary crawl already excludes its fills, and the pivot doubles as the
|
|
766
|
+
* geometry anchor for reanchorBoundaryFromLastFill. Letting a wick on an
|
|
767
|
+
* edge order arm the pivot at a rail-edge price would both veto that whole
|
|
768
|
+
* side of the book and (as an absolute anchor) teleport the window to the
|
|
769
|
+
* edge. Skipping keeps the reference on the last WINDOW trade, matching
|
|
770
|
+
* the crawl's classification (collectEdgePinnedFillIds is the shared
|
|
771
|
+
* definition).
|
|
762
772
|
* @param {Array} fills
|
|
763
773
|
*/
|
|
764
774
|
recordLastFilledPrices(fills: COWFillLike[]): void;
|