dexbot 1.6.13 → 1.6.14
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/README.md +2 -2
- package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
- package/claw/modules/claw_catalog.ts +8 -4
- package/claw/modules/dexbot_profiles.ts +59 -15
- package/claw/modules/types.ts +2 -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/claw/skills/margin-trading/SKILL.md +1 -1
- package/claw/skills/margin-trading/references/position-management.md +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +25 -25
- package/dist/modules/account_bots.d.ts +7 -6
- package/dist/modules/account_bots.js +10 -10
- package/dist/modules/account_orders.d.ts +36 -4
- package/dist/modules/account_orders.js +76 -5
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
- package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
- package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
- package/dist/modules/bot_defaults.d.ts +16 -2
- package/dist/modules/bot_defaults.js +34 -8
- package/dist/modules/bot_settings.d.ts +4 -0
- package/dist/modules/bot_settings.js +55 -21
- package/dist/modules/config.js +6 -1
- package/dist/modules/constants.d.ts +7 -5
- package/dist/modules/constants.js +12 -5
- package/dist/modules/dexbot_class.d.ts +5 -0
- package/dist/modules/dexbot_class.js +8 -3
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
- package/dist/modules/dexbot_cow_runtime.js +331 -46
- package/dist/modules/dexbot_credential_client.d.ts +1 -16
- package/dist/modules/dexbot_credential_client.js +1 -1
- package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
- package/dist/modules/dexbot_fill_runtime.js +12 -1
- package/dist/modules/dexbot_maintenance_runtime.d.ts +18 -80
- package/dist/modules/dexbot_maintenance_runtime.js +57 -68
- package/dist/modules/dexbot_startup_runtime.js +12 -0
- package/dist/modules/dexbot_state_recovery.js +16 -0
- package/dist/modules/key_store.d.ts +0 -5
- package/dist/modules/key_store.js +1 -1
- package/dist/modules/order/accounting.js +11 -11
- package/dist/modules/order/export.js +2 -2
- package/dist/modules/order/format.d.ts +15 -1
- package/dist/modules/order/format.js +19 -1
- package/dist/modules/order/genesis_policy.d.ts +1 -1
- package/dist/modules/order/genesis_policy.js +1 -1
- package/dist/modules/order/grid.d.ts +23 -11
- package/dist/modules/order/grid.js +383 -51
- package/dist/modules/order/grid_reconcile.d.ts +1 -1
- package/dist/modules/order/grid_reconcile.js +5 -5
- package/dist/modules/order/grid_reconcile_internal.js +48 -40
- package/dist/modules/order/index.d.ts +34 -8
- package/dist/modules/order/logger.js +2 -2
- package/dist/modules/order/manager.d.ts +9 -2
- package/dist/modules/order/manager.js +58 -24
- package/dist/modules/order/strategy.d.ts +2 -2
- package/dist/modules/order/strategy.js +51 -21
- package/dist/modules/order/sync_engine.js +4 -0
- package/dist/modules/order/utils/math.d.ts +3 -3
- package/dist/modules/order/utils/math.js +38 -27
- package/dist/modules/order/utils/order.d.ts +58 -58
- package/dist/modules/order/utils/order.js +119 -102
- package/dist/modules/order/utils/system.d.ts +193 -6
- package/dist/modules/order/utils/system.js +392 -29
- package/dist/modules/order/utils/validate.js +26 -4
- package/dist/modules/runtime_settings.d.ts +1 -1
- package/dist/modules/runtime_settings.js +3 -3
- package/dist/modules/types.d.ts +48 -4
- package/dist/scripts/analyze-orders.d.ts +1 -1
- package/dist/scripts/analyze-orders.js +4 -4
- package/dist/scripts/divergence-calc.js +6 -6
- package/dist/scripts/validate_bots.d.ts +1 -1
- package/dist/scripts/validate_bots.js +3 -3
- package/dist/unlock.js +7 -2
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
- package/docs/COW_INVARIANTS.md +6 -6
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +8 -7
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
- package/docs/GRID_PRICE_INVARIANT.md +3 -3
- package/docs/GRID_RECALCULATION.md +4 -1
- package/docs/GRID_RECONCILE.md +4 -4
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +14 -0
- package/docs/MPA_CREDIT_USAGE.md +1 -1
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
- package/docs/README.md +3 -3
- package/docs/architecture.md +6 -6
- package/docs/developer_guide.md +7 -2
- package/package.json +1 -1
- package/tests/README.md +1 -1
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* - Detects and flags out-of-spread conditions
|
|
13
13
|
*
|
|
14
14
|
* ===============================================================================
|
|
15
|
-
* TABLE OF CONTENTS - Grid Functions (
|
|
15
|
+
* TABLE OF CONTENTS - Grid Functions (23 exported functions)
|
|
16
16
|
* ===============================================================================
|
|
17
17
|
*
|
|
18
18
|
* CONFIGURATION & CALCULATION (2 functions)
|
|
@@ -34,8 +34,11 @@
|
|
|
34
34
|
* GRID RECALCULATION (1 function - async)
|
|
35
35
|
* 7. recalculateGrid(manager, opts) - Recalculate grid based on current state
|
|
36
36
|
*
|
|
37
|
-
* GRID STATE CHECKING (
|
|
38
|
-
* 8. checkAndUpdateGridIfNeeded(manager) -
|
|
37
|
+
* GRID STATE CHECKING (2 functions)
|
|
38
|
+
* 8. checkAndUpdateGridIfNeeded(manager) - Complete fund trigger: available-
|
|
39
|
+
* funds ratio + over-allocation + on-chain committed-drift legs
|
|
40
|
+
* 8b. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
|
|
41
|
+
* (the drift core is folded into checkAndUpdateGridIfNeeded)
|
|
39
42
|
*
|
|
40
43
|
* BLOCKCHAIN SYNCHRONIZATION (2 functions - async)
|
|
41
44
|
* 9. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
|
|
@@ -99,14 +102,23 @@ const GRID_CONSTANTS = {
|
|
|
99
102
|
/**
|
|
100
103
|
* Fold a prepared correction (or the absence of one) into the stall cause the
|
|
101
104
|
* caller reports. A plan that existed but funded nothing ('unfunded'), or a
|
|
102
|
-
* zero sizing budget ('stallHint: unfunded'), is a FUND condition
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
105
|
+
* zero sizing budget ('stallHint: unfunded'), is a FUND condition. The named
|
|
106
|
+
* structural causes ('cold-book', 'unmatched-orders', 'readiness-gate') are
|
|
107
|
+
* preserved verbatim; anything else is 'no-candidates'. The two sides are
|
|
108
|
+
* merged with this so an unfunded plan on one side is never masked by an empty
|
|
109
|
+
* plan on the other (e.g. chosen side planned 1 / placed 0, opposite 0).
|
|
106
110
|
*/
|
|
107
111
|
function classifySpreadStall(c) {
|
|
108
|
-
|
|
112
|
+
const hint = c?.stallHint;
|
|
113
|
+
// A plan that existed but funded nothing is a FUND condition and must win
|
|
114
|
+
// over any structural hint (those are only set on empty returns today, but
|
|
115
|
+
// the precedence is explicit so a future hint can never mask 'unfunded').
|
|
116
|
+
if (Number(c?.plannedCount || 0) > 0 || hint === 'unfunded')
|
|
109
117
|
return 'unfunded';
|
|
118
|
+
// Preserve the readiness-gate causes verbatim; they are operationally
|
|
119
|
+
// distinct and the targeted-sync reason states them literally.
|
|
120
|
+
if (hint === 'cold-book' || hint === 'unmatched-orders' || hint === 'readiness-gate')
|
|
121
|
+
return hint;
|
|
110
122
|
return 'no-candidates';
|
|
111
123
|
}
|
|
112
124
|
/**
|
|
@@ -130,8 +142,8 @@ function _snapshotFundState(manager) {
|
|
|
130
142
|
};
|
|
131
143
|
}
|
|
132
144
|
import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, priceSlotEqual, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
|
|
133
|
-
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType,
|
|
134
|
-
import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot } from './utils/system.js';
|
|
145
|
+
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
|
|
146
|
+
import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice } from './utils/system.js';
|
|
135
147
|
import * as MathUtils from './utils/math.js';
|
|
136
148
|
import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
|
|
137
149
|
import { getWhitelistFlags } from '../market_adapter_whitelist.js';
|
|
@@ -230,13 +242,9 @@ export function clearGridBloatFlag(manager) {
|
|
|
230
242
|
* @returns {Promise<any|null>}
|
|
231
243
|
* @private
|
|
232
244
|
*/
|
|
233
|
-
|
|
245
|
+
function _computeSizingContextSync(manager, side) {
|
|
234
246
|
if (!manager || !manager.assets)
|
|
235
247
|
return null;
|
|
236
|
-
// 1. Ensure fund state is fresh before sizing
|
|
237
|
-
if (!skipRecalc) {
|
|
238
|
-
await manager.recalculateFunds();
|
|
239
|
-
}
|
|
240
248
|
const snap = manager.getChainFundsSnapshot ? manager.getChainFundsSnapshot() : {};
|
|
241
249
|
const isBuy = side === 'buy';
|
|
242
250
|
const type = isBuy ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
|
|
@@ -247,8 +255,8 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
|
|
|
247
255
|
// BTS fees are paid for ALL order operations regardless of side, so the
|
|
248
256
|
// BTS-holding side reserves fees for both buy and sell target counts.
|
|
249
257
|
if (budget > 0) {
|
|
250
|
-
const targetBuy = Math.max(0, manager.config.
|
|
251
|
-
const targetSell = Math.max(0, manager.config.
|
|
258
|
+
const targetBuy = Math.max(0, manager.config.coreOrders?.buy ?? 1) + resolveEdgeCount(manager.config, 'buy');
|
|
259
|
+
const targetSell = Math.max(0, manager.config.coreOrders?.sell ?? 1) + resolveEdgeCount(manager.config, 'sell');
|
|
252
260
|
const totalTarget = targetBuy + targetSell;
|
|
253
261
|
const btsOrderType = getBtsSide(manager.config?.assetA, manager.config?.assetB);
|
|
254
262
|
const isBtsSide = isBuy ? (btsOrderType === ORDER_TYPES.BUY) : (btsOrderType === ORDER_TYPES.SELL);
|
|
@@ -269,6 +277,19 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
|
|
|
269
277
|
config: manager.config
|
|
270
278
|
};
|
|
271
279
|
}
|
|
280
|
+
/**
|
|
281
|
+
* Async sizing-context accessor. Refreshes funds unless `skipRecalc`, then
|
|
282
|
+
* delegates to the sync core. Both divergence legs (ratio and committed
|
|
283
|
+
* drift) size through the sync core so they read one fund snapshot.
|
|
284
|
+
*/
|
|
285
|
+
export async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
|
|
286
|
+
if (!manager || !manager.assets)
|
|
287
|
+
return null;
|
|
288
|
+
if (!skipRecalc) {
|
|
289
|
+
await manager.recalculateFunds();
|
|
290
|
+
}
|
|
291
|
+
return _computeSizingContextSync(manager, side);
|
|
292
|
+
}
|
|
272
293
|
/**
|
|
273
294
|
* Create the initial order grid structure based on configuration.
|
|
274
295
|
*
|
|
@@ -1133,22 +1154,22 @@ export async function initializeGrid(manager) {
|
|
|
1133
1154
|
const startPriceWasDerived = typeof mpRaw !== 'number' || Number.isNaN(Number(mpRaw));
|
|
1134
1155
|
const centerIsLive = startPriceWasDerived || gpSource === 'ama';
|
|
1135
1156
|
if (owedCrawls.length > 0 && !centerIsLive) {
|
|
1136
|
-
//
|
|
1157
|
+
// Edge fills never crawl (static insurance). Classify them
|
|
1137
1158
|
// against the OLD generation (manager.orders is replaced below)
|
|
1138
1159
|
// with the same live anchors the runtime derivation uses, so the
|
|
1139
|
-
// fold can never be driven by
|
|
1160
|
+
// fold can never be driven by an edge fill.
|
|
1140
1161
|
const oldSlots = Array.from(manager.orders.values());
|
|
1141
1162
|
const edgeAnchors = {
|
|
1142
|
-
buy:
|
|
1143
|
-
sell:
|
|
1163
|
+
buy: resolveLiveEdgeAnchorPrice(manager, 'buy'),
|
|
1164
|
+
sell: resolveLiveEdgeAnchorPrice(manager, 'sell')
|
|
1144
1165
|
};
|
|
1145
|
-
const
|
|
1146
|
-
const
|
|
1166
|
+
const edgeBuyIds = edgeOrderIdSet(oldSlots, manager.config, ORDER_TYPES.BUY, edgeAnchors.buy, liveWindowIdSet(manager, ORDER_TYPES.BUY));
|
|
1167
|
+
const edgeSellIds = edgeOrderIdSet(oldSlots, manager.config, ORDER_TYPES.SELL, edgeAnchors.sell, liveWindowIdSet(manager, ORDER_TYPES.SELL));
|
|
1147
1168
|
let netShift = 0;
|
|
1148
1169
|
for (const e of owedCrawls) {
|
|
1149
|
-
if (e?.side === ORDER_TYPES.BUY &&
|
|
1170
|
+
if (e?.side === ORDER_TYPES.BUY && edgeBuyIds?.has(e.slotId))
|
|
1150
1171
|
continue;
|
|
1151
|
-
if (e?.side === ORDER_TYPES.SELL &&
|
|
1172
|
+
if (e?.side === ORDER_TYPES.SELL && edgeSellIds?.has(e.slotId))
|
|
1152
1173
|
continue;
|
|
1153
1174
|
if (e?.side === ORDER_TYPES.SELL)
|
|
1154
1175
|
netShift++;
|
|
@@ -1445,14 +1466,14 @@ export function checkAndUpdateGridIfNeeded(manager) {
|
|
|
1445
1466
|
for (const s of sides) {
|
|
1446
1467
|
if (s.grid <= 0)
|
|
1447
1468
|
continue;
|
|
1448
|
-
const
|
|
1469
|
+
const feeCoreOrders = manager.config.coreOrders && typeof manager.config.coreOrders === 'object'
|
|
1449
1470
|
? {
|
|
1450
|
-
...manager.config.
|
|
1451
|
-
buy: Math.max(0, Number(manager.config.
|
|
1452
|
-
sell: Math.max(0, Number(manager.config.
|
|
1471
|
+
...manager.config.coreOrders,
|
|
1472
|
+
buy: Math.max(0, Number(manager.config.coreOrders.buy) || 0) + resolveEdgeCount(manager.config, 'buy'),
|
|
1473
|
+
sell: Math.max(0, Number(manager.config.coreOrders.sell) || 0) + resolveEdgeCount(manager.config, 'sell'),
|
|
1453
1474
|
}
|
|
1454
|
-
: manager.config.
|
|
1455
|
-
const availableFunds = calculateAvailableFundsValue(s.name, manager.accountTotals, manager.funds, manager.config.assetA, manager.config.assetB,
|
|
1475
|
+
: manager.config.coreOrders;
|
|
1476
|
+
const availableFunds = calculateAvailableFundsValue(s.name, manager.accountTotals, manager.funds, manager.config.assetA, manager.config.assetB, feeCoreOrders, manager.config.min_BTS_value, manager.config.feeParams ?? null);
|
|
1456
1477
|
// Denominator: side's allocated capital (or chain total fallback).
|
|
1457
1478
|
const allocated = s.name === 'buy' ? chainSnap.allocatedBuy : chainSnap.allocatedSell;
|
|
1458
1479
|
const denominator = (allocated > 0) ? allocated : (s.grid + availableFunds);
|
|
@@ -1464,8 +1485,11 @@ export function checkAndUpdateGridIfNeeded(manager) {
|
|
|
1464
1485
|
// chain-total drops: a normal fill moves value across sides (pays one
|
|
1465
1486
|
// asset, receives the other), so one side's total routinely drops >=3%
|
|
1466
1487
|
// on ordinary fills — and the fill pipeline already re-sizes from the
|
|
1467
|
-
// post-fill budget. External removal is caught here
|
|
1468
|
-
//
|
|
1488
|
+
// post-fill budget. External removal is caught here only while the plan
|
|
1489
|
+
// still carries the old budget; once the fill pipeline re-derives
|
|
1490
|
+
// VIRTUAL downward the overAlloc gap closes (grid == allocated), and the
|
|
1491
|
+
// committed-drift leg folded in below is what catches it. The two
|
|
1492
|
+
// together cover the pre- and post-pipeline phases.
|
|
1469
1493
|
// NOTE: with an explicit 0 allocation the shared fallback denominator
|
|
1470
1494
|
// yields overAlloc ≈ +100%, i.e. a 0%-funded side holding size always
|
|
1471
1495
|
// triggers — which is the desired unwind (zero budget sizes everything
|
|
@@ -1491,8 +1515,174 @@ export function checkAndUpdateGridIfNeeded(manager) {
|
|
|
1491
1515
|
}
|
|
1492
1516
|
}
|
|
1493
1517
|
}
|
|
1518
|
+
// Fold the committed-drift legs into this single entry so the trigger is
|
|
1519
|
+
// complete on its own. Both numerators above track `virtual` (the grow
|
|
1520
|
+
// denominator via `availableFunds`, the shrink base via `total.grid`), so
|
|
1521
|
+
// an external deposit/withdrawal already folded into the plan by the
|
|
1522
|
+
// fill pipeline is invisible to them. The on-chain committed delta closes
|
|
1523
|
+
// that gap in both directions. Callers must refresh funds first
|
|
1524
|
+
// (monitorDivergence does; direct callers own that responsibility).
|
|
1525
|
+
const driftResult = _computeCommittedSizeDriftSync(manager);
|
|
1526
|
+
result.buyUpdated = result.buyUpdated || driftResult.buyUpdated;
|
|
1527
|
+
result.sellUpdated = result.sellUpdated || driftResult.sellUpdated;
|
|
1528
|
+
result.buyShrink = result.buyShrink || driftResult.buyShrink;
|
|
1529
|
+
result.sellShrink = result.sellShrink || driftResult.sellShrink;
|
|
1530
|
+
return result;
|
|
1531
|
+
}
|
|
1532
|
+
/**
|
|
1533
|
+
* Committed-size drift check (fund trigger blind-spot closure).
|
|
1534
|
+
*
|
|
1535
|
+
* checkAndUpdateGridIfNeeded measures available funds as
|
|
1536
|
+
* `chainFree - virtualReservation`. The fill/rotation sizing pipeline
|
|
1537
|
+
* re-derives VIRTUAL slot sizes from the live budget, so a deposit (or an
|
|
1538
|
+
* external withdrawal) is folded into the virtual reservation on the first
|
|
1539
|
+
* rotation after it lands. chainFree and virtual then move together, the
|
|
1540
|
+
* ratio stays pinned at the unallocated remainder, and a side whose
|
|
1541
|
+
* on-chain (ACTIVE/PARTIAL) orders still carry the pre-deposit sizes is
|
|
1542
|
+
* never flagged — the full-side resize waits for an unrelated full resync
|
|
1543
|
+
* (RMS or AMA recenter).
|
|
1544
|
+
*
|
|
1545
|
+
* This leg closes that blind spot: it computes the geometric ideal for
|
|
1546
|
+
* every side slot from the current budget and measures the gap against the
|
|
1547
|
+
* sizes actually committed on chain, applying the resize path's own
|
|
1548
|
+
* free-balance growth cap so the metric equals the on-chain delta a resize
|
|
1549
|
+
* would really produce. A side whose committed orders would change by
|
|
1550
|
+
* >= GRID_REGENERATION_PERCENTAGE of the committed size is flagged for the
|
|
1551
|
+
* same COW resize path (applyGridDivergenceCorrections), which updates
|
|
1552
|
+
* every changed on-chain order — i.e. the full side.
|
|
1553
|
+
*
|
|
1554
|
+
* Only on-chain slots contribute: VIRTUAL slots are the plan (already sized
|
|
1555
|
+
* by the fill pipeline) and SPREAD placeholders carry no commitment.
|
|
1556
|
+
* Non-slot-N shelf/manual orders are excluded (never resized by the
|
|
1557
|
+
* geometric pass; same gate as _recalculateGridOrderSizesFromBlockchain).
|
|
1558
|
+
*
|
|
1559
|
+
* @param {import('./types').OrderManager} manager - Manager instance with order state
|
|
1560
|
+
* @returns {{ buyUpdated: boolean; sellUpdated: boolean; buyShrink: boolean; sellShrink: boolean }}
|
|
1561
|
+
*/
|
|
1562
|
+
function _computeCommittedSizeDriftSync(manager) {
|
|
1563
|
+
const result = { buyUpdated: false, sellUpdated: false, buyShrink: false, sellShrink: false };
|
|
1564
|
+
if (!manager || !manager.assets || !manager.orders)
|
|
1565
|
+
return result;
|
|
1566
|
+
const rawThreshold = manager.config?.gridLimits?.GRID_REGENERATION_PERCENTAGE;
|
|
1567
|
+
// Same fallback contract as checkAndUpdateGridIfNeeded: a configured 0 or
|
|
1568
|
+
// non-numeric value falls back to the global default rather than disabling.
|
|
1569
|
+
const threshold = (Number.isFinite(Number(rawThreshold)) && Number(rawThreshold) > 0)
|
|
1570
|
+
? Number(rawThreshold)
|
|
1571
|
+
: GRID_LIMITS.GRID_REGENERATION_PERCENTAGE;
|
|
1572
|
+
const sides = [
|
|
1573
|
+
{ name: 'buy', orderType: ORDER_TYPES.BUY },
|
|
1574
|
+
{ name: 'sell', orderType: ORDER_TYPES.SELL }
|
|
1575
|
+
];
|
|
1576
|
+
for (const s of sides) {
|
|
1577
|
+
// Sync core: checkAndUpdateGridIfNeeded is sync and expects funds to
|
|
1578
|
+
// already be fresh (monitorDivergence / checkCommittedSizeDrift recalc).
|
|
1579
|
+
const ctx = _computeSizingContextSync(manager, s.name);
|
|
1580
|
+
if (!ctx || !(ctx.budget > 0))
|
|
1581
|
+
continue;
|
|
1582
|
+
// Must match _recalculateGridOrderSizesFromBlockchain exactly: same
|
|
1583
|
+
// source (manager.orders), same ASC price sort, same denominator set.
|
|
1584
|
+
const allSideSlots = Array.from(manager.orders.values())
|
|
1585
|
+
.filter((o) => o.type === s.orderType)
|
|
1586
|
+
.sort((a, b) => a.price - b.price);
|
|
1587
|
+
if (allSideSlots.length === 0)
|
|
1588
|
+
continue;
|
|
1589
|
+
let newSizes;
|
|
1590
|
+
try {
|
|
1591
|
+
newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, s.orderType, manager.config, 0, ctx.precision);
|
|
1592
|
+
}
|
|
1593
|
+
catch (_err) {
|
|
1594
|
+
continue;
|
|
1595
|
+
}
|
|
1596
|
+
// Replay the resize path's free-balance cap so `growth` is exactly the
|
|
1597
|
+
// committed growth the resize could apply (VIRTUAL slots do not consume
|
|
1598
|
+
// free balance; shrink releases it back for later slots). The cap uses
|
|
1599
|
+
// the float delta (matching the resize), but the reported drift is gated
|
|
1600
|
+
// on the same blockchain-integer change test the resize uses to decide
|
|
1601
|
+
// whether an on-chain UPDATE is emitted.
|
|
1602
|
+
const freeKey = s.name === 'buy' ? 'buyFree' : 'sellFree';
|
|
1603
|
+
let sideFreeAvailable = Number(manager.accountTotals?.[freeKey] || 0);
|
|
1604
|
+
let growth = 0;
|
|
1605
|
+
let shrink = 0;
|
|
1606
|
+
let committedTotal = 0;
|
|
1607
|
+
for (let i = 0; i < allSideSlots.length; i++) {
|
|
1608
|
+
const slot = allSideSlots[i];
|
|
1609
|
+
if (!isOrderOnChain(slot) || !hasOnChainId(slot))
|
|
1610
|
+
continue;
|
|
1611
|
+
if (parseSlotIndex(slot.id) === null)
|
|
1612
|
+
continue;
|
|
1613
|
+
const ideal = Number(newSizes?.[i] || 0);
|
|
1614
|
+
const current = Number(slot.size || 0);
|
|
1615
|
+
committedTotal += current;
|
|
1616
|
+
let newSize = ideal;
|
|
1617
|
+
const delta = ideal - current;
|
|
1618
|
+
if (delta > 0) {
|
|
1619
|
+
const affordableDelta = Math.min(delta, Math.max(0, sideFreeAvailable));
|
|
1620
|
+
if (affordableDelta < delta)
|
|
1621
|
+
newSize = current + affordableDelta;
|
|
1622
|
+
sideFreeAvailable = Math.max(0, sideFreeAvailable - affordableDelta);
|
|
1623
|
+
}
|
|
1624
|
+
else if (delta < 0) {
|
|
1625
|
+
sideFreeAvailable += Math.abs(delta);
|
|
1626
|
+
}
|
|
1627
|
+
// Match the resize's integer-space change gate: a slot whose size
|
|
1628
|
+
// rounds to the same blockchain integer emits no UPDATE and must not
|
|
1629
|
+
// count toward the drift metric (otherwise the leg would re-trigger
|
|
1630
|
+
// against a no-op resize every tick).
|
|
1631
|
+
const currentInt = floatToBlockchainInt(current, ctx.precision);
|
|
1632
|
+
const newInt = floatToBlockchainInt(newSize, ctx.precision);
|
|
1633
|
+
if (currentInt === newInt)
|
|
1634
|
+
continue;
|
|
1635
|
+
const applied = newSize - current;
|
|
1636
|
+
if (applied > 0)
|
|
1637
|
+
growth += applied;
|
|
1638
|
+
else if (applied < 0)
|
|
1639
|
+
shrink += Math.abs(applied);
|
|
1640
|
+
}
|
|
1641
|
+
// Baseline is the on-chain committed size, NOT the whole allocation:
|
|
1642
|
+
// a deposit's active-window share is a small slice of the allocation
|
|
1643
|
+
// (the far rail holds most of the plan), so an `allocated` denominator
|
|
1644
|
+
// would never reach 3% while the committed side is genuinely ~12%
|
|
1645
|
+
// under-sized. Relative to the committed side, a normal fill moves the
|
|
1646
|
+
// budget by well under the threshold, so this stays quiet in steady
|
|
1647
|
+
// state. No on-chain orders -> nothing to resize.
|
|
1648
|
+
if (!(committedTotal > 0))
|
|
1649
|
+
continue;
|
|
1650
|
+
const growthPct = (growth / committedTotal) * 100;
|
|
1651
|
+
const shrinkPct = (shrink / committedTotal) * 100;
|
|
1652
|
+
const growTrigger = growthPct >= threshold;
|
|
1653
|
+
const shrinkTrigger = shrinkPct >= threshold;
|
|
1654
|
+
manager.logger?.log?.(`[DIVERGENCE] ${s.name.toUpperCase()} committed-drift check: committedTotal=${committedTotal.toFixed(5)}, committedGrowth=${growth.toFixed(5)}, committedShrink=${shrink.toFixed(5)}, growth=${growthPct.toFixed(4)}% (threshold=${threshold}%) → ${growTrigger ? 'TRIGGER-GROW' : 'no trigger'} | shrink=${shrinkPct.toFixed(4)}% → ${shrinkTrigger ? 'TRIGGER-SHRINK' : 'no trigger'}`, 'debug');
|
|
1655
|
+
if (growTrigger || shrinkTrigger) {
|
|
1656
|
+
if (!(manager._gridSidesUpdated instanceof Set))
|
|
1657
|
+
manager._gridSidesUpdated = new Set();
|
|
1658
|
+
manager._gridSidesUpdated.add(s.orderType);
|
|
1659
|
+
if (s.name === 'buy') {
|
|
1660
|
+
result.buyUpdated = true;
|
|
1661
|
+
if (shrinkTrigger)
|
|
1662
|
+
result.buyShrink = true;
|
|
1663
|
+
}
|
|
1664
|
+
else {
|
|
1665
|
+
result.sellUpdated = true;
|
|
1666
|
+
if (shrinkTrigger)
|
|
1667
|
+
result.sellShrink = true;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1494
1671
|
return result;
|
|
1495
1672
|
}
|
|
1673
|
+
/**
|
|
1674
|
+
* Async committed-drift accessor: refresh funds, then run the sync core.
|
|
1675
|
+
* Public for callers/tests that want the drift-only result; the complete
|
|
1676
|
+
* trigger is checkAndUpdateGridIfNeeded, which folds this core in.
|
|
1677
|
+
* Naming mirrors the sizing pair: _computeCommittedSizeDriftSync is the
|
|
1678
|
+
* private computation, checkCommittedSizeDrift the public accessor.
|
|
1679
|
+
*/
|
|
1680
|
+
export async function checkCommittedSizeDrift(manager) {
|
|
1681
|
+
if (manager && typeof manager.recalculateFunds === 'function') {
|
|
1682
|
+
await manager.recalculateFunds();
|
|
1683
|
+
}
|
|
1684
|
+
return _computeCommittedSizeDriftSync(manager);
|
|
1685
|
+
}
|
|
1496
1686
|
/**
|
|
1497
1687
|
* Standardize grid sizes using blockchain total context.
|
|
1498
1688
|
*
|
|
@@ -1581,11 +1771,11 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
|
|
|
1581
1771
|
// geometric progression including empties, then re-type the picked slot
|
|
1582
1772
|
// to BUY/SELL before placement. The COW boundary-shift path re-types
|
|
1583
1773
|
// the working grid by geometry first, so crossers stay in the correct
|
|
1584
|
-
// side's denominator.
|
|
1774
|
+
// side's denominator. Edge order slots are included here like any
|
|
1585
1775
|
// other slot-N side slot: this geometric curve sizes them too, and the
|
|
1586
|
-
// activation picker (
|
|
1776
|
+
// activation picker (_pickEdgeSlots) only ever places an edge order
|
|
1587
1777
|
// with the stored size the target-grid sizing pipeline already wrote
|
|
1588
|
-
// (exact values, one sizing rule). Skipping
|
|
1778
|
+
// (exact values, one sizing rule). Skipping edge orders in this pass
|
|
1589
1779
|
// would make the divergence resize disagree with that pipeline. Only
|
|
1590
1780
|
// non-slot-N shelf/manual ids are skipped below.
|
|
1591
1781
|
const orderSource = collectActions ? workingGrid : manager.orders;
|
|
@@ -1608,7 +1798,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
|
|
|
1608
1798
|
const slot = allSideSlots[i];
|
|
1609
1799
|
// Shelf/manual orders (non-slot-N ids, e.g. fork-kept deep-*
|
|
1610
1800
|
// below the rail) sit outside window accounting: geometric
|
|
1611
|
-
// ideals must never resize them on-chain. Same gate as
|
|
1801
|
+
// ideals must never resize them on-chain. Same gate as edge
|
|
1612
1802
|
// classification and startup cancel candidates (issue #27
|
|
1613
1803
|
// follow-up). No-op upstream (grids only mint slot-N).
|
|
1614
1804
|
// NB: they stay in the denominator above (budget math
|
|
@@ -1919,24 +2109,35 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
|
|
|
1919
2109
|
* @returns {Promise<any>}
|
|
1920
2110
|
*/
|
|
1921
2111
|
export async function monitorDivergence(manager, calculatedGrid, persistedGrid) {
|
|
1922
|
-
//
|
|
2112
|
+
// Refresh once so every leg sizes from one snapshot. The trigger itself
|
|
2113
|
+
// is sync and already folds the committed-drift legs in (see
|
|
2114
|
+
// checkAndUpdateGridIfNeeded), so there is no separate drift call here.
|
|
2115
|
+
if (manager && typeof manager.recalculateFunds === 'function') {
|
|
2116
|
+
await manager.recalculateFunds();
|
|
2117
|
+
}
|
|
2118
|
+
// 1. Ratio + committed-drift divergence (available funds /
|
|
2119
|
+
// over-allocation / on-chain committed delta).
|
|
1923
2120
|
const ratioResult = checkAndUpdateGridIfNeeded(manager);
|
|
1924
|
-
|
|
2121
|
+
const ratioBuy = ratioResult.buyUpdated;
|
|
2122
|
+
const ratioSell = ratioResult.sellUpdated;
|
|
2123
|
+
const buyShrink = ratioResult.buyShrink === true;
|
|
2124
|
+
const sellShrink = ratioResult.sellShrink === true;
|
|
2125
|
+
if (ratioBuy || ratioSell) {
|
|
1925
2126
|
return {
|
|
1926
2127
|
needsUpdate: true,
|
|
1927
|
-
buy: { updated:
|
|
1928
|
-
sell: { updated:
|
|
1929
|
-
orderType: getOrderTypeFromUpdatedFlags(
|
|
2128
|
+
buy: { updated: ratioBuy, ratio: ratioBuy, rms: false, metric: 0, shrink: buyShrink },
|
|
2129
|
+
sell: { updated: ratioSell, ratio: ratioSell, rms: false, metric: 0, shrink: sellShrink },
|
|
2130
|
+
orderType: getOrderTypeFromUpdatedFlags(ratioBuy, ratioSell)
|
|
1930
2131
|
};
|
|
1931
2132
|
}
|
|
1932
2133
|
// 2. Check RMS-based divergence (structural deviation)
|
|
1933
2134
|
const rmsResult = await compareGrids(calculatedGrid, persistedGrid, manager);
|
|
1934
|
-
const buyUpdated =
|
|
1935
|
-
const sellUpdated =
|
|
2135
|
+
const buyUpdated = rmsResult.buy.updated;
|
|
2136
|
+
const sellUpdated = rmsResult.sell.updated;
|
|
1936
2137
|
return {
|
|
1937
2138
|
needsUpdate: buyUpdated || sellUpdated,
|
|
1938
|
-
buy: { updated: buyUpdated, ratio:
|
|
1939
|
-
sell: { updated: sellUpdated, ratio:
|
|
2139
|
+
buy: { updated: buyUpdated, ratio: false, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: false },
|
|
2140
|
+
sell: { updated: sellUpdated, ratio: false, rms: rmsResult.sell.updated, metric: rmsResult.sell.metric, shrink: false },
|
|
1940
2141
|
orderType: getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated),
|
|
1941
2142
|
thresholdPct: rmsResult.thresholdPct
|
|
1942
2143
|
};
|
|
@@ -1949,7 +2150,7 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
|
|
|
1949
2150
|
*/
|
|
1950
2151
|
function _getOnChainOrders(manager) {
|
|
1951
2152
|
// Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
|
|
1952
|
-
// deep-*) sit outside window accounting — same gate as
|
|
2153
|
+
// deep-*) sit outside window accounting — same gate as edge
|
|
1953
2154
|
// classification and startup cancel candidates (issue #27 follow-up).
|
|
1954
2155
|
// Without this, a live shelf masks an empty window side (oneSideEmpty
|
|
1955
2156
|
// stays false) and skews the spread inputs. No-op on grids that only
|
|
@@ -2021,6 +2222,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2021
2222
|
const lastPrice = (bestBuy !== null && bestSell !== null)
|
|
2022
2223
|
? (bestBuy + bestSell) / 2
|
|
2023
2224
|
: Number(manager.config.startPrice) || 0;
|
|
2225
|
+
// Keep the crossing floor current: refresh the cached live market price
|
|
2226
|
+
// when it is stale, paced to one read per freshness window. The planner
|
|
2227
|
+
// then uses current market truth instead of a possibly days-old fill,
|
|
2228
|
+
// which is what removes the need for a distance heuristic. Best-effort;
|
|
2229
|
+
// on failure the fill anchor remains the fallback.
|
|
2230
|
+
await maybeRefreshLiveMarketPrice(manager, _BitShares);
|
|
2024
2231
|
// Lock guard is handled at function entry — if _gridLock is absent we return early.
|
|
2025
2232
|
let fundSnapshot = null;
|
|
2026
2233
|
// Detect empty-side condition: when one side has zero on-chain orders,
|
|
@@ -2049,6 +2256,34 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2049
2256
|
manager.outOfSpread = shouldFlagOutOfSpread(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
|
|
2050
2257
|
if (manager.outOfSpread === 0)
|
|
2051
2258
|
return false;
|
|
2259
|
+
// P-A cold book: the orchestration short-circuit, evaluated in the
|
|
2260
|
+
// shared readiness gate so the planner, the crossing filter and the
|
|
2261
|
+
// COW bypass all reason from one verdict. This early return keeps
|
|
2262
|
+
// the cold classification ahead of the one-sided boundary branch.
|
|
2263
|
+
// The planner re-evaluates the gate per call (including the re-plan
|
|
2264
|
+
// path, which deliberately re-reads fresh state), so this is not a
|
|
2265
|
+
// duplicated verdict but the same rule at two points in the cycle.
|
|
2266
|
+
//
|
|
2267
|
+
// A cold book has no realized spread to repair — the "spread" is
|
|
2268
|
+
// synthetic (an empty side plus the startPrice fallback) and a
|
|
2269
|
+
// correction here can only guess a side and place through an unseen
|
|
2270
|
+
// market (issue #31). The reconcile path owns the first window;
|
|
2271
|
+
// 'cold-book' is a structural stall that arms the targeted sync.
|
|
2272
|
+
// Degraded causes (stale/unmatched) keep ok=true. A null reason is
|
|
2273
|
+
// a gate failure (correct-by-refusal) and stalls as 'readiness-gate'.
|
|
2274
|
+
const readiness = evaluateSpreadCorrectionReadiness(manager, {
|
|
2275
|
+
onChainOrders: { buys: onChainBuys, sells: onChainSells }
|
|
2276
|
+
});
|
|
2277
|
+
if (!readiness.ok) {
|
|
2278
|
+
const cold = readiness.reason === 'cold-book';
|
|
2279
|
+
manager.logger?.log?.((cold
|
|
2280
|
+
? `[SPREAD] Book is cold (no live BUY or SELL on chain); skipping spread correction — ` +
|
|
2281
|
+
`the reconcile path owns the first window.`
|
|
2282
|
+
: `[SPREAD] Spread-correction readiness gate failed; skipping this cycle.`) +
|
|
2283
|
+
` Requesting a targeted chain sync.`, 'warn');
|
|
2284
|
+
stall = cold ? 'cold-book' : 'readiness-gate';
|
|
2285
|
+
return false;
|
|
2286
|
+
}
|
|
2052
2287
|
// Check whether the empty side is caused by boundary-at-rail-edge.
|
|
2053
2288
|
// When the boundary crawl has clamped to 0 or allSlots.length-1,
|
|
2054
2289
|
// fill pressure can wipe out one entire side. Spread correction
|
|
@@ -2540,7 +2775,7 @@ function resolveMinSpreadOrdersReserve(manager) {
|
|
|
2540
2775
|
// DEFENSE-IN-DEPTH WALK BOUNDS: the loop itself also stops
|
|
2541
2776
|
// MIN_SPREAD_ORDERS short of the opposite rail edge (idx <= sellStartIdx−1−
|
|
2542
2777
|
// reserve for BUY / idx >= buyEndIdx+1+reserve for SELL), so even if the
|
|
2543
|
-
// cap above is ever miscomputed the walk cannot consume the
|
|
2778
|
+
// cap above is ever miscomputed the walk cannot consume the edged gap.
|
|
2544
2779
|
// When bandSize <= reserve the bound disables promotion entirely.
|
|
2545
2780
|
function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, sellStartIdx, quota, spreadReserve, maxDepth) {
|
|
2546
2781
|
const isBuy = railType === ORDER_TYPES.BUY;
|
|
@@ -2582,6 +2817,32 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2582
2817
|
throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${ORDER_TYPES.BUY}' or '${ORDER_TYPES.SELL}'.`);
|
|
2583
2818
|
}
|
|
2584
2819
|
const ordersToPlace = [];
|
|
2820
|
+
// SHARED READINESS GATE (P-A/P-B/P-C): one verdict for the planner, the
|
|
2821
|
+
// crossing filter and the COW bypass. Hard refusal (cold book) returns
|
|
2822
|
+
// before any planning; degraded causes (stale/unmatched) keep planning
|
|
2823
|
+
// but withhold the bypass and drive the collision filter below.
|
|
2824
|
+
const onChainView = _getOnChainOrders(manager);
|
|
2825
|
+
const readiness = evaluateSpreadCorrectionReadiness(manager, {
|
|
2826
|
+
onChainOrders: { buys: onChainView.onChainBuys, sells: onChainView.onChainSells }
|
|
2827
|
+
});
|
|
2828
|
+
if (!readiness.ok) {
|
|
2829
|
+
// Only 'cold-book' is a named hard-refusal premise; a null reason is
|
|
2830
|
+
// a gate failure and gets its own stall so triage logs are precise.
|
|
2831
|
+
// Either way the targeted sync arms via the stall.
|
|
2832
|
+
const hardRefusalStall = readiness.reason === 'cold-book'
|
|
2833
|
+
? 'cold-book'
|
|
2834
|
+
: 'readiness-gate';
|
|
2835
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing cycle: ${readiness.reason ?? 'readiness-gate-error'} — a targeted sync will re-evaluate`, 'warn');
|
|
2836
|
+
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: hardRefusalStall, origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
2837
|
+
}
|
|
2838
|
+
// Empty-candidate stall cause: name the collision case when unmatched
|
|
2839
|
+
// orders are present, so the targeted-sync reason states the truth.
|
|
2840
|
+
// Keyed off the DATA, not `reason`: reason is priority-ranked (cold >
|
|
2841
|
+
// stale > unmatched), so a stale+unmatched cycle reports 'stale-snapshot'
|
|
2842
|
+
// and would otherwise mask the collision cause.
|
|
2843
|
+
const refusalStallHint = readiness.unmatched.length > 0
|
|
2844
|
+
? 'unmatched-orders'
|
|
2845
|
+
: 'no-candidates';
|
|
2585
2846
|
const railType = preferredSide;
|
|
2586
2847
|
const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
|
|
2587
2848
|
const configuredMissingSlots = Number(outOfSpread || 0);
|
|
@@ -2663,7 +2924,9 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2663
2924
|
// market-nearest comparator that replaced it fixed that case but sorts
|
|
2664
2925
|
// the FAR end first when the empties sit BELOW the window (the normal
|
|
2665
2926
|
// post-fill state), which is the same class of bug mirrored.
|
|
2666
|
-
|
|
2927
|
+
// Reuse the gate's view: one slot-gated scan per planner call feeds both
|
|
2928
|
+
// the readiness verdict and the live window edges below.
|
|
2929
|
+
const { onChainBuys, onChainSells } = onChainView;
|
|
2667
2930
|
const railBestIsMax = railType === ORDER_TYPES.BUY;
|
|
2668
2931
|
const bestLiveOnRail = railBestIsMax
|
|
2669
2932
|
? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
|
|
@@ -2723,11 +2986,59 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2723
2986
|
return true;
|
|
2724
2987
|
return railBestIsMax ? c.price > bestLiveOnRail : c.price < bestLiveOnRail;
|
|
2725
2988
|
};
|
|
2989
|
+
// MARKET-CROSSING GUARD: never place a SELL at/below (or a BUY at/above)
|
|
2990
|
+
// the last price the account actually traded at. On a one-sided or
|
|
2991
|
+
// freshly-regenerated book the local anchor is absent, so without this
|
|
2992
|
+
// the correction happily sells under a market it cannot see (issue
|
|
2993
|
+
// #31). Fail-open when no real fill is known — never guess from grid
|
|
2994
|
+
// geometry. This complements tightensSpread (which is anchor-relative)
|
|
2995
|
+
// with an absolute, market-relative floor.
|
|
2996
|
+
// Crossing floor from the shared readiness verdict: a fresh live market
|
|
2997
|
+
// read when available, else the fill-derived reference. No distance
|
|
2998
|
+
// heuristic — the floor is kept current rather than judged stale.
|
|
2999
|
+
const marketRef = readiness.marketRef;
|
|
3000
|
+
const doesNotCrossMarket = (c) => {
|
|
3001
|
+
if (marketRef == null || c?.price == null || !Number.isFinite(c.price))
|
|
3002
|
+
return true;
|
|
3003
|
+
return railBestIsMax ? c.price < marketRef : c.price > marketRef;
|
|
3004
|
+
};
|
|
3005
|
+
// P-C COLLISION FILTER: when the gate saw fresh unmatched chain orders,
|
|
3006
|
+
// drop candidates whose price level they already occupy — placing
|
|
3007
|
+
// another order at the same level would duplicate a live order the
|
|
3008
|
+
// grid has not adopted yet. Price-level only: the unmatched row carries
|
|
3009
|
+
// no side, and a duplicate at a level is a duplicate regardless.
|
|
3010
|
+
//
|
|
3011
|
+
// Keyed off the DATA, not `reason`: reason is priority-ranked (cold >
|
|
3012
|
+
// stale > unmatched), so a stale+unmatched cycle reports
|
|
3013
|
+
// 'stale-snapshot' while the unmatched list is fully populated. The
|
|
3014
|
+
// P4 protection must not expire with snapshot staleness — those chain
|
|
3015
|
+
// orders only clear on the next sync.
|
|
3016
|
+
const unmatchedPrices = readiness.unmatched.length > 0
|
|
3017
|
+
? readiness.unmatched.map((u) => Number(u?.price)).filter((p) => Number.isFinite(p) && p > 0)
|
|
3018
|
+
: [];
|
|
3019
|
+
const doesNotCollideUnmatched = (c) => {
|
|
3020
|
+
if (unmatchedPrices.length === 0 || c?.price == null || !Number.isFinite(c.price))
|
|
3021
|
+
return true;
|
|
3022
|
+
const precision = railType === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
|
|
3023
|
+
return !unmatchedPrices.some((p) => {
|
|
3024
|
+
try {
|
|
3025
|
+
return priceSlotEqual(p, c.price, precision);
|
|
3026
|
+
}
|
|
3027
|
+
catch {
|
|
3028
|
+
return Math.abs(p - c.price) / c.price <= ((manager.config.incrementPercent ?? 0) / 100);
|
|
3029
|
+
}
|
|
3030
|
+
});
|
|
3031
|
+
};
|
|
3032
|
+
if (unmatchedPrices.length > 0) {
|
|
3033
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] ${unmatchedPrices.length} known-unmatched chain price level(s) excluded from ${sideName} candidates — sync will adopt them first`, 'warn');
|
|
3034
|
+
}
|
|
2726
3035
|
const typedSpreadCandidates = allOrders
|
|
2727
3036
|
.filter((o) => o.type === ORDER_TYPES.SPREAD
|
|
2728
3037
|
&& isSlotAvailable(o)
|
|
2729
3038
|
&& getSlotCorrectType(o) === railType)
|
|
2730
3039
|
.filter(tightensSpread)
|
|
3040
|
+
.filter(doesNotCrossMarket)
|
|
3041
|
+
.filter(doesNotCollideUnmatched)
|
|
2731
3042
|
.sort(sortCandidates)
|
|
2732
3043
|
.slice(0, missingSlots);
|
|
2733
3044
|
// Secondary candidates: orphaned virtual slots that have lost their
|
|
@@ -2770,6 +3081,8 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2770
3081
|
&& !o.orderId
|
|
2771
3082
|
&& getSlotCorrectType(o) === railType)
|
|
2772
3083
|
.filter(tightensSpread)
|
|
3084
|
+
.filter(doesNotCrossMarket)
|
|
3085
|
+
.filter(doesNotCollideUnmatched)
|
|
2773
3086
|
.sort(sortCandidates)
|
|
2774
3087
|
.slice(0, missingSlots);
|
|
2775
3088
|
// If the funded rail is full, the spread itself may be stale: the
|
|
@@ -2814,6 +3127,25 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2814
3127
|
if (boundaryKnown && orphanedVirtualCandidates.length + typedSpreadCandidates.length < missingSlots) {
|
|
2815
3128
|
const rawQuota = missingSlots - orphanedVirtualCandidates.length - typedSpreadCandidates.length;
|
|
2816
3129
|
promotedCandidates.push(..._collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, sellStartIdx, rawQuota, spreadReserve, maxPromotionDepth));
|
|
3130
|
+
// A boundary promotion moves the window into the spread band. If
|
|
3131
|
+
// any of the contiguous run would land through the last real fill,
|
|
3132
|
+
// the whole promotion is refused (dropping only the first slot
|
|
3133
|
+
// would break the run's contiguity and the boundary derivation).
|
|
3134
|
+
const crossingPromoted = marketRef == null
|
|
3135
|
+
? []
|
|
3136
|
+
: promotedCandidates.filter((c) => !doesNotCrossMarket(c));
|
|
3137
|
+
const collidingPromoted = promotedCandidates.filter((c) => !doesNotCollideUnmatched(c));
|
|
3138
|
+
if (marketRef != null && crossingPromoted.length > 0) {
|
|
3139
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing boundary promotion on ${sideName}: ` +
|
|
3140
|
+
`${crossingPromoted.length} slot(s) would cross the last market fill ` +
|
|
3141
|
+
`${Format.formatPrice6(marketRef)}`, 'warn');
|
|
3142
|
+
promotedCandidates.length = 0;
|
|
3143
|
+
}
|
|
3144
|
+
else if (collidingPromoted.length > 0) {
|
|
3145
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing boundary promotion on ${sideName}: ` +
|
|
3146
|
+
`${collidingPromoted.length} slot(s) collide with known-unmatched chain orders`, 'warn');
|
|
3147
|
+
promotedCandidates.length = 0;
|
|
3148
|
+
}
|
|
2817
3149
|
if (promotedCandidates.length > 0) {
|
|
2818
3150
|
manager.logger?.log?.(`[SPREAD-CORRECTION] ${promotedCandidates.length} gap slot(s) available for boundary promotion on ${sideName}`, 'info');
|
|
2819
3151
|
}
|
|
@@ -2901,7 +3233,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2901
3233
|
manager.logger?.log?.(bestLiveOnRail == null
|
|
2902
3234
|
? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
|
|
2903
3235
|
: `[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');
|
|
2904
|
-
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint:
|
|
3236
|
+
return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: refusalStallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
|
|
2905
3237
|
}
|
|
2906
3238
|
const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
|
|
2907
3239
|
const sideSlots = allOrders
|
|
@@ -3037,7 +3369,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
3037
3369
|
// inside the implied band. All real constraints — the
|
|
3038
3370
|
// MIN_SPREAD_ORDERS reserve and opposite-rail stranding — are
|
|
3039
3371
|
// enforced UPSTREAM as walk-depth caps. This backstop only
|
|
3040
|
-
// verifies array limits plus the
|
|
3372
|
+
// verifies array limits plus the edge ceiling; any
|
|
3041
3373
|
// violation signals an internal inconsistency, so promotion is
|
|
3042
3374
|
// refused loudly instead of silently re-geometried.
|
|
3043
3375
|
const maxIdx = allSlotsByPrice.length - 1;
|
|
@@ -70,7 +70,7 @@ export declare function decideStartupGridAction({ persistedGrid, chainOpenOrders
|
|
|
70
70
|
* - Then create missing orders if chain has fewer than target.
|
|
71
71
|
* - Then cancel excess orders if chain has more than target.
|
|
72
72
|
*
|
|
73
|
-
* Targets are derived from config.
|
|
73
|
+
* Targets are derived from config.coreOrders.{buy,sell} and chain counts are computed
|
|
74
74
|
* from current on-chain open orders.
|
|
75
75
|
* @param {Object} params - Destructured parameters
|
|
76
76
|
* @param {Object} params.manager - OrderManager instance
|