dexbot 1.6.18 → 1.7.1
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 +68 -0
- package/README.md +24 -18
- package/analysis/README.md +117 -5
- 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/account_resolver.js +5 -6
- package/dist/analysis/analyze_dynamic_weight.js +2 -1
- package/dist/analysis/analyze_kalman.js +3 -2
- package/dist/analysis/analyze_liquidity.d.ts +17 -0
- package/dist/analysis/analyze_liquidity.js +336 -0
- package/dist/analysis/analyze_regime.js +3 -2
- package/dist/analysis/analyze_regime_windows.js +3 -2
- package/dist/analysis/analyze_volatility.js +3 -2
- package/dist/analysis/bot_key_utils.d.ts +44 -1
- package/dist/analysis/bot_key_utils.js +76 -7
- package/dist/analysis/fills_cache.js +2 -1
- package/dist/analysis/grid_correction_check.d.ts +1 -19
- package/dist/analysis/grid_correction_check.js +12 -30
- package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
- package/dist/analysis/liquidity/liquidity_chain.js +178 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
- package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
- package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
- package/dist/analysis/liquidity/liquidity_view.js +66 -0
- package/dist/analysis/resolve_bot_accounts.js +7 -6
- package/dist/analysis/trade_profitability.js +4 -2
- package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
- package/dist/credential-daemon.js +13 -2
- package/dist/dexbot.js +77 -172
- package/dist/modules/account_bots.d.ts +11 -1
- package/dist/modules/account_orders.d.ts +12 -0
- package/dist/modules/account_orders.js +30 -0
- package/dist/modules/asset_lookup.d.ts +25 -0
- package/dist/modules/asset_lookup.js +75 -0
- package/dist/modules/bitshares-native/transport.js +24 -6
- package/dist/modules/bitshares_client.d.ts +24 -6
- package/dist/modules/bitshares_client.js +44 -7
- package/dist/modules/bot_settings.d.ts +2 -0
- package/dist/modules/chain_scan.d.ts +64 -0
- package/dist/modules/chain_scan.js +80 -0
- package/dist/modules/cli_colors.d.ts +5 -0
- package/dist/modules/cli_colors.js +7 -0
- package/dist/modules/cli_progress.d.ts +51 -0
- package/dist/modules/cli_progress.js +113 -0
- package/dist/modules/constants.d.ts +26 -3
- package/dist/modules/constants.js +63 -8
- package/dist/modules/dexbot_class.d.ts +1 -6
- package/dist/modules/dexbot_class.js +14 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
- package/dist/modules/dexbot_cow_runtime.js +634 -136
- package/dist/modules/dexbot_fill_runtime.js +132 -23
- package/dist/modules/dexbot_maintenance_runtime.js +242 -74
- package/dist/modules/dexbot_startup_runtime.js +32 -20
- package/dist/modules/dexbot_state_recovery.d.ts +33 -1
- package/dist/modules/dexbot_state_recovery.js +167 -5
- package/dist/modules/launcher/runtime_entry.d.ts +21 -1
- package/dist/modules/launcher/runtime_entry.js +36 -1
- package/dist/modules/liquidity_pool_ref.d.ts +32 -0
- package/dist/modules/liquidity_pool_ref.js +116 -0
- package/dist/modules/node_connect_policy.d.ts +8 -1
- package/dist/modules/node_connect_policy.js +18 -2
- package/dist/modules/node_flap_score.d.ts +87 -0
- package/dist/modules/node_flap_score.js +124 -0
- package/dist/modules/node_health_cache.d.ts +40 -3
- package/dist/modules/node_health_cache.js +66 -20
- package/dist/modules/node_manager.d.ts +101 -19
- package/dist/modules/node_manager.js +255 -65
- package/dist/modules/order/accounting.js +56 -7
- package/dist/modules/order/format.d.ts +24 -10
- package/dist/modules/order/format.js +30 -10
- package/dist/modules/order/grid.js +91 -13
- package/dist/modules/order/grid_reconcile.d.ts +5 -1
- package/dist/modules/order/grid_reconcile.js +333 -189
- package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
- package/dist/modules/order/grid_reconcile_internal.js +298 -100
- package/dist/modules/order/index.d.ts +19 -1
- package/dist/modules/order/lifecycle.d.ts +353 -0
- package/dist/modules/order/lifecycle.js +1109 -0
- package/dist/modules/order/manager.d.ts +273 -5
- package/dist/modules/order/manager.js +654 -48
- package/dist/modules/order/placement_lock.d.ts +102 -0
- package/dist/modules/order/placement_lock.js +222 -0
- package/dist/modules/order/strategy.js +13 -1
- package/dist/modules/order/sync_engine.d.ts +33 -1
- package/dist/modules/order/sync_engine.js +241 -73
- package/dist/modules/order/utils/math.d.ts +39 -1
- package/dist/modules/order/utils/math.js +83 -1
- package/dist/modules/order/utils/order.d.ts +181 -5
- package/dist/modules/order/utils/order.js +455 -9
- package/dist/modules/order/utils/system.d.ts +81 -1
- package/dist/modules/order/utils/system.js +331 -44
- package/dist/modules/order/utils/validate.d.ts +7 -1
- package/dist/modules/order/utils/validate.js +80 -3
- package/dist/modules/outcome.d.ts +54 -0
- package/dist/modules/outcome.js +51 -0
- package/dist/modules/settings_merge.d.ts +4 -0
- package/dist/modules/settings_merge.js +9 -0
- package/dist/modules/timing_policy.d.ts +82 -0
- package/dist/modules/timing_policy.js +244 -0
- package/dist/modules/types.d.ts +137 -0
- package/dist/modules/utils/asset_symbols.d.ts +13 -2
- package/dist/modules/utils/asset_symbols.js +21 -2
- package/dist/scripts/analysis_runner.d.ts +10 -0
- package/dist/scripts/analysis_runner.js +33 -0
- package/dist/scripts/analyze-credit.js +54 -17
- package/dist/scripts/analyze-orders.d.ts +4 -2
- package/dist/scripts/analyze-orders.js +115 -35
- package/dist/scripts/asset.d.ts +26 -0
- package/dist/scripts/asset.js +165 -0
- package/dist/scripts/bts_distribution.d.ts +1 -0
- package/dist/scripts/bts_distribution.js +194 -142
- package/dist/scripts/chart_command.d.ts +1 -1
- package/dist/scripts/chart_command.js +60 -86
- package/dist/scripts/chart_targets.d.ts +18 -0
- package/dist/scripts/chart_targets.js +48 -0
- package/dist/scripts/dw.js +1 -1
- package/dist/scripts/liquid.d.ts +24 -0
- package/dist/scripts/liquid.js +134 -0
- package/dist/scripts/rich_list.js +12 -16
- package/dist/scripts/test-credit-renewal.js +12 -5
- package/dist/scripts/token_distribution.d.ts +2 -0
- package/dist/scripts/token_distribution.js +132 -108
- package/dist/scripts/tv.js +1 -1
- package/dist/scripts/verify-browser-bundle.js +18 -0
- package/docs/COW_INVARIANTS.md +69 -10
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +5 -2
- package/docs/GRID_RECONCILE.md +36 -11
- package/docs/LOGGING.md +50 -4
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
- package/docs/README.md +23 -2
- package/docs/WORKFLOW.md +12 -4
- package/docs/architecture.md +42 -5
- package/docs/developer_guide.md +25 -8
- package/modules/README.md +8 -1
- package/package.json +3 -1
- package/scripts/README.md +39 -7
- package/scripts/pdev.sh +14 -1
- package/scripts/pmain.sh +23 -8
- package/scripts/ptest.sh +7 -0
- package/tests/README.md +30 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Extracted from grid_reconcile.ts for file-size management.
|
|
5
5
|
* All helpers are prefixed with _ and are NOT part of the public API.
|
|
6
6
|
*/
|
|
7
|
-
import type { OrderManagerLike, ManagedOrder, ChainOrder, ParsedChainOrder, ChainOrdersLike, LoggerLike, UnknownRecord, StartupCreatePlan, StartupUpdatePlan, StartupCancelPlan, OrderType } from '../types.js';
|
|
7
|
+
import type { OrderManagerLike, ManagedOrder, ChainOrder, ParsedChainOrder, ChainOrdersLike, AssetPair, LoggerLike, UnknownRecord, StartupCreatePlan, StartupUpdatePlan, StartupCancelPlan, OrderType } from '../types.js';
|
|
8
8
|
interface PreparedStartupUpdate {
|
|
9
9
|
plan: StartupUpdatePlan;
|
|
10
10
|
chainOrderId: string;
|
|
@@ -149,6 +149,42 @@ declare function _executePlannedStartupCreates({ createPlans, chainOrders, accou
|
|
|
149
149
|
manager: OrderManagerLike;
|
|
150
150
|
dryRun: boolean;
|
|
151
151
|
}): Promise<Set<string>>;
|
|
152
|
+
/**
|
|
153
|
+
* Partition the unmatched chain orders of one side into an UPDATE pool and a
|
|
154
|
+
* dust-surplus CANCEL pool.
|
|
155
|
+
*
|
|
156
|
+
* Policy (single implementation used by the startup reconcile):
|
|
157
|
+
* - dust = size below the per-slot single-dust threshold (same definition the
|
|
158
|
+
* partial-dust health check uses);
|
|
159
|
+
* - when the NON-dust orders alone can cover every slot this side needs, dust
|
|
160
|
+
* orders are surplus -> CANCEL only. They are never grown into a full slot
|
|
161
|
+
* and no replacement is created for them (there are already enough real
|
|
162
|
+
* orders to cover the target);
|
|
163
|
+
* - otherwise dust stays eligible to fill the remaining slots.
|
|
164
|
+
*
|
|
165
|
+
* Extracted so the policy is unit-testable and cannot drift between the
|
|
166
|
+
* startup reconcile and any future caller.
|
|
167
|
+
* @param {Object} input
|
|
168
|
+
* @param {Array} input.sortedUnmatched - Unmatched chain orders, pre-sorted by price
|
|
169
|
+
* @param {Array} input.desiredSlots - Target slots this side wants to activate
|
|
170
|
+
* @param {Object} input.assets - Asset metadata (precisions)
|
|
171
|
+
* @param {number} [input.dustThresholdPercent] - Dust threshold percentage
|
|
172
|
+
* @returns {Object} { updatePool, dustSurplus, nonDustCount, dustCount, referenceIdeal, dustThreshold, enoughNonDust }
|
|
173
|
+
*/
|
|
174
|
+
declare function _classifyStartupOrderReuse({ sortedUnmatched, desiredSlots, assets, dustThresholdPercent, }: {
|
|
175
|
+
sortedUnmatched: ChainOrder[];
|
|
176
|
+
desiredSlots: ManagedOrder[];
|
|
177
|
+
assets: AssetPair;
|
|
178
|
+
dustThresholdPercent?: number;
|
|
179
|
+
}): {
|
|
180
|
+
updatePool: ChainOrder[];
|
|
181
|
+
dustSurplus: ChainOrder[];
|
|
182
|
+
nonDustCount: number;
|
|
183
|
+
dustCount: number;
|
|
184
|
+
referenceIdeal: number;
|
|
185
|
+
dustThreshold: number;
|
|
186
|
+
enoughNonDust: boolean;
|
|
187
|
+
};
|
|
152
188
|
declare function _reconcileStartupSide({ orderType, targetCount, chainSideOrders, unmatchedSideOrders, manager, chainOrders, account, privateKey, dryRun, plannedCreates, plannedUpdates, plannedCancels, planOnly, }: {
|
|
153
189
|
orderType: OrderType;
|
|
154
190
|
targetCount: number;
|
|
@@ -166,5 +202,5 @@ declare function _reconcileStartupSide({ orderType, targetCount, chainSideOrders
|
|
|
166
202
|
}): Promise<{
|
|
167
203
|
chainCount: number;
|
|
168
204
|
}>;
|
|
169
|
-
export { _countActiveOnGrid, _pickVirtualSlotsToActivate, _createOrderFromGrid, _prepareStartupUpdatePlan, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executeStartupCreateGroupBatch, _createStartupOrderWithHandling, _executePlannedStartupCreates, _reconcileStartupSide };
|
|
205
|
+
export { _countActiveOnGrid, _pickVirtualSlotsToActivate, _createOrderFromGrid, _prepareStartupUpdatePlan, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executeStartupCreateGroupBatch, _createStartupOrderWithHandling, _executePlannedStartupCreates, _reconcileStartupSide, _classifyStartupOrderReuse };
|
|
170
206
|
//# sourceMappingURL=grid_reconcile_internal.d.ts.map
|
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { ORDER_TYPES, ORDER_STATES, TIMING, BTS_PRECISION } from '../constants.js';
|
|
8
8
|
import { readOpenOrdersGuarded } from '../chain_orders.js';
|
|
9
|
-
import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, 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, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
|
|
9
|
+
import { getMinOrderSize, getSingleDustThreshold, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, resolveGapSlots, isSlotInRail, pricesOnSameLevel, pricesWithinHalfStep, 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, reportGridPriceInvariant, liveWindowIdSet, getLivePendingBroadcasts } from './utils/order.js';
|
|
11
11
|
import { parseSlotIndex } from './utils/slot.js';
|
|
12
|
-
import { resolveAccountRef } from './utils/system.js';
|
|
12
|
+
import { resolveAccountRef, isLastFillPlacementBlocked, hasUnsettledFills } from './utils/system.js';
|
|
13
13
|
import * as Format from './format.js';
|
|
14
14
|
import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
|
|
15
15
|
function computePlacementPriceCollision(manager, gridOrder) {
|
|
@@ -206,6 +206,15 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
|
|
|
206
206
|
// Derived budgeted size per slot, built once (O(n)) so below-min lookups
|
|
207
207
|
// don't recompute full-side sizing for every candidate (avoid O(n²)).
|
|
208
208
|
const derivedSizes = _deriveBudgetedSideSizes(manager, type);
|
|
209
|
+
// LAST-FILL placement discipline at PICK time: a candidate on the wrong
|
|
210
|
+
// side of the last fill (or on its own level) must not consume activation
|
|
211
|
+
// budget — the create would be refused downstream anyway, and the pick
|
|
212
|
+
// budget is what decides which levels get restored. Skipping it lets the
|
|
213
|
+
// picker fall through to the NEXT level down (BUY) / up (SELL), which is
|
|
214
|
+
// the "rotate to the bottom BUY / counter SELL" behaviour: the level that
|
|
215
|
+
// just traded is never re-stamped same-side.
|
|
216
|
+
let lastFillSkipped = 0;
|
|
217
|
+
let lastFillPivot = null;
|
|
209
218
|
for (const slot of slotsOfType) {
|
|
210
219
|
if (valid.length >= count)
|
|
211
220
|
break;
|
|
@@ -226,6 +235,13 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
|
|
|
226
235
|
}
|
|
227
236
|
}
|
|
228
237
|
if (slot.id && effectiveSize >= effectiveMin) {
|
|
238
|
+
const fillGuard = isLastFillPlacementBlocked(manager, slot.price, type);
|
|
239
|
+
if (fillGuard.blocked) {
|
|
240
|
+
lastFillSkipped++;
|
|
241
|
+
if (lastFillPivot == null)
|
|
242
|
+
lastFillPivot = fillGuard.pivot;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
229
245
|
// Re-type the picked slot to the activation side: empty slots are
|
|
230
246
|
// stored SPREAD (side-neutral), but an order being placed here must
|
|
231
247
|
// carry the concrete BUY/SELL rail type (SPREAD+ACTIVE is illegal,
|
|
@@ -238,6 +254,10 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
|
|
|
238
254
|
}
|
|
239
255
|
}
|
|
240
256
|
}
|
|
257
|
+
if (lastFillSkipped > 0) {
|
|
258
|
+
manager.logger?.log?.(`Startup: ${type.toUpperCase()} pick skipped ${lastFillSkipped} slot(s) on the wrong side of the last fill ` +
|
|
259
|
+
`(pivot ${lastFillPivot == null ? 'n/a' : Format.formatPrice6(lastFillPivot)}); picked ${valid.length}/${count}`, 'debug');
|
|
260
|
+
}
|
|
241
261
|
return valid;
|
|
242
262
|
}
|
|
243
263
|
/**
|
|
@@ -470,6 +490,45 @@ async function _createOrderFromGrid({ chainOrders, account, privateKey, manager,
|
|
|
470
490
|
manager.logger?.log?.(`[_createOrderFromGrid] SKIP: Slot ${gridOrder.id} already has orderId ${currentSlot.orderId}`, 'warn');
|
|
471
491
|
return null;
|
|
472
492
|
}
|
|
493
|
+
// PENDING-BROADCAST GUARD: an earlier uncertain CREATE for this slot may
|
|
494
|
+
// already be live on chain but not yet adopted. The COW pre-broadcast guard
|
|
495
|
+
// blocks the whole CREATE batch for this case; the reconcile/startup path
|
|
496
|
+
// must not re-create the same slot OR the same price level either (same
|
|
497
|
+
// duplicate class).
|
|
498
|
+
//
|
|
499
|
+
// Liveness comes from the shared authority (`getLivePendingBroadcasts`), so
|
|
500
|
+
// this path cannot disagree with the COW guard about what is expired. It
|
|
501
|
+
// checks BOTH the slot id and the price level: a rebuild re-maps a price
|
|
502
|
+
// onto a different slot id, and reconcile is exactly the rebuild path — so
|
|
503
|
+
// a slot-id-only check would miss the entry the COW guard was written to
|
|
504
|
+
// catch. Placement is held and the chain snapshot was just re-read, so a
|
|
505
|
+
// live entry here is authoritative.
|
|
506
|
+
{
|
|
507
|
+
const pendingEntries = getLivePendingBroadcasts(manager);
|
|
508
|
+
for (const pending of pendingEntries) {
|
|
509
|
+
const slotId = pending?.slotId ?? pending?.orderId ?? pending?.order?.id;
|
|
510
|
+
if (slotId == null || String(slotId) !== String(gridOrder.id))
|
|
511
|
+
continue;
|
|
512
|
+
manager.logger?.log?.(`[_createOrderFromGrid] SKIP (PENDING-BROADCAST): Create for ${gridOrder.id} at ` +
|
|
513
|
+
`${Format.formatPrice6(Number(gridOrder.price))} may already be live from an uncertain broadcast; ` +
|
|
514
|
+
`waiting for recovery/adoption instead of duplicating it`, 'warn');
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
for (const pending of pendingEntries) {
|
|
518
|
+
const pendingPrice = Number(pending?.order?.price);
|
|
519
|
+
if (!Number.isFinite(pendingPrice) || pendingPrice <= 0)
|
|
520
|
+
continue;
|
|
521
|
+
const pendingType = pending?.orderType ?? pending?.order?.type;
|
|
522
|
+
if (pendingType && gridOrder.type && pendingType !== gridOrder.type)
|
|
523
|
+
continue;
|
|
524
|
+
if (!pricesOnSameLevel(pendingPrice, Number(pending?.order?.size) || 0, pendingType, Number(gridOrder.price), Number(gridOrder.size) || 0, gridOrder.type, manager.assets, manager.config?.incrementPercent))
|
|
525
|
+
continue;
|
|
526
|
+
manager.logger?.log?.(`[_createOrderFromGrid] SKIP (PENDING-BROADCAST): Create for ${gridOrder.id} at ` +
|
|
527
|
+
`${Format.formatPrice6(Number(gridOrder.price))} would duplicate the price level of an uncertain ` +
|
|
528
|
+
`CREATE for slot ${String(pending?.slotId ?? '?')}; waiting for recovery/adoption`, 'warn');
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
473
532
|
const createPrice = gridOrder.price;
|
|
474
533
|
// CROSSING-PLACEMENT GUARD: a create must not cross an opposite-side
|
|
475
534
|
// live order (master, unmatched orphan, or pending broadcast) — see computePlacementCrossing.
|
|
@@ -483,6 +542,21 @@ async function _createOrderFromGrid({ chainOrders, account, privateKey, manager,
|
|
|
483
542
|
`@${Format.formatPrice6(crossed.price ?? crossed.order?.price ?? 0)}`, 'warn');
|
|
484
543
|
return null;
|
|
485
544
|
}
|
|
545
|
+
// LAST-FILL GUARD: never place a BUY on/above the price that just traded,
|
|
546
|
+
// nor a SELL on/below it (same level included — see
|
|
547
|
+
// isLastFillPlacementBlocked). The COW planner has this discipline; the
|
|
548
|
+
// reconcile/startup create path did not, so a top-up could re-create the
|
|
549
|
+
// level it had just bought at (live: 19 of 37 creates at an already-filled
|
|
550
|
+
// level, 9 of them above the previous fill). Refusing here fails closed to
|
|
551
|
+
// the next reconcile cycle, when the crawl has moved the rail.
|
|
552
|
+
const fillGuard = isLastFillPlacementBlocked(manager, createPrice, gridOrder.type);
|
|
553
|
+
if (fillGuard.blocked) {
|
|
554
|
+
manager.logger?.log?.(`[_createOrderFromGrid] SKIP (LAST-FILL-GUARD): Create for ${gridOrder.id} at ` +
|
|
555
|
+
`${Format.formatPrice6(createPrice)} on the wrong side of the last fill ` +
|
|
556
|
+
`${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason}); ` +
|
|
557
|
+
`the rail must crawl before this level is refilled`, 'warn');
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
486
560
|
// Price collision guard: reject if another placed order already exists at this price level.
|
|
487
561
|
const priceCollision = computePlacementPriceCollision(manager, gridOrder);
|
|
488
562
|
if (priceCollision) {
|
|
@@ -761,11 +835,30 @@ function _prepareStartupUpdatePlan(plan, manager, logger) {
|
|
|
761
835
|
`re-align on the next reconcile cycle.`, 'warn');
|
|
762
836
|
return null;
|
|
763
837
|
}
|
|
838
|
+
// LAST-FILL GUARD: a relocation re-prices a live order onto a different
|
|
839
|
+
// level, so it is a placement and obeys the same direction rule as a
|
|
840
|
+
// create (BUY lower, SELL higher; never the level that just traded). A
|
|
841
|
+
// same-price relocation is an ADOPTION (the chain order already rests at
|
|
842
|
+
// the target level), not a placement — it is left alone.
|
|
843
|
+
const parsedChainOrder = parseChainOrder(plan.chainOrderObj, manager.assets);
|
|
844
|
+
const chainPrice = Number(parsedChainOrder?.price);
|
|
845
|
+
const samePriceAdoption = Number.isFinite(chainPrice)
|
|
846
|
+
&& pricesWithinHalfStep(chainPrice, Number(gridOrder.price), manager.config?.incrementPercent);
|
|
847
|
+
if (!samePriceAdoption) {
|
|
848
|
+
const fillGuard = isLastFillPlacementBlocked(manager, gridOrder.price, gridOrder.type);
|
|
849
|
+
if (fillGuard.blocked) {
|
|
850
|
+
logger?.log?.(`[STARTUP-LAST-FILL-GUARD] Skipping relocation update ${chainOrderId} -> ${gridOrder.id}: ` +
|
|
851
|
+
`target ${gridOrder.type} @${Format.formatPrice6(gridOrder.price)} is on the wrong side of the ` +
|
|
852
|
+
`last fill ${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason}); ` +
|
|
853
|
+
`re-align on the next reconcile cycle.`, 'warn');
|
|
854
|
+
return null;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
764
857
|
return {
|
|
765
858
|
plan,
|
|
766
859
|
chainOrderId,
|
|
767
860
|
gridOrder,
|
|
768
|
-
parsedChain:
|
|
861
|
+
parsedChain: parsedChainOrder,
|
|
769
862
|
updateParams: {
|
|
770
863
|
newPrice: gridOrder.price,
|
|
771
864
|
amountToSell,
|
|
@@ -1152,6 +1245,16 @@ async function _executeStartupCreateGroupBatch({ group, chainOrders, account, pr
|
|
|
1152
1245
|
`@${Format.formatPrice6(crossed.price ?? crossed.order?.price ?? 0)}`, 'warn');
|
|
1153
1246
|
continue;
|
|
1154
1247
|
}
|
|
1248
|
+
// LAST-FILL GUARD: creates only — never restore a level on the wrong
|
|
1249
|
+
// side of the last fill (includes the level that just traded). See
|
|
1250
|
+
// isLastFillPlacementBlocked.
|
|
1251
|
+
const fillGuard = isLastFillPlacementBlocked(manager, createPrice, gridOrder.type);
|
|
1252
|
+
if (fillGuard.blocked) {
|
|
1253
|
+
logger?.log?.(`Startup: Skip create ${plan.orderLabel} (LAST-FILL-GUARD) - price ` +
|
|
1254
|
+
`${Format.formatPrice6(createPrice)} is on the wrong side of the last fill ` +
|
|
1255
|
+
`${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason})`, 'warn');
|
|
1256
|
+
continue;
|
|
1257
|
+
}
|
|
1155
1258
|
const { amountToSell, sellAssetId, minToReceive, receiveAssetId } = buildCreateOrderArgs(gridOrder, manager.assets.assetA, manager.assets.assetB);
|
|
1156
1259
|
// GRID-PRICE-INVARIANT (blocking): see docs/GRID_PRICE_INVARIANT.md.
|
|
1157
1260
|
if (!reportGridPriceInvariant(manager, gridOrder?.id, gridOrder?.price, 'STARTUP-CREATE')) {
|
|
@@ -1398,6 +1501,53 @@ async function _executePlannedStartupCreates({ createPlans, chainOrders, account
|
|
|
1398
1501
|
`across ${groups.length} group(s)${failedCount > 0 ? `, ${failedCount} failed/skipped (see error logs)` : ''}`, failedCount > 0 ? 'warn' : 'info');
|
|
1399
1502
|
return createdOrderIds;
|
|
1400
1503
|
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Partition the unmatched chain orders of one side into an UPDATE pool and a
|
|
1506
|
+
* dust-surplus CANCEL pool.
|
|
1507
|
+
*
|
|
1508
|
+
* Policy (single implementation used by the startup reconcile):
|
|
1509
|
+
* - dust = size below the per-slot single-dust threshold (same definition the
|
|
1510
|
+
* partial-dust health check uses);
|
|
1511
|
+
* - when the NON-dust orders alone can cover every slot this side needs, dust
|
|
1512
|
+
* orders are surplus -> CANCEL only. They are never grown into a full slot
|
|
1513
|
+
* and no replacement is created for them (there are already enough real
|
|
1514
|
+
* orders to cover the target);
|
|
1515
|
+
* - otherwise dust stays eligible to fill the remaining slots.
|
|
1516
|
+
*
|
|
1517
|
+
* Extracted so the policy is unit-testable and cannot drift between the
|
|
1518
|
+
* startup reconcile and any future caller.
|
|
1519
|
+
* @param {Object} input
|
|
1520
|
+
* @param {Array} input.sortedUnmatched - Unmatched chain orders, pre-sorted by price
|
|
1521
|
+
* @param {Array} input.desiredSlots - Target slots this side wants to activate
|
|
1522
|
+
* @param {Object} input.assets - Asset metadata (precisions)
|
|
1523
|
+
* @param {number} [input.dustThresholdPercent] - Dust threshold percentage
|
|
1524
|
+
* @returns {Object} { updatePool, dustSurplus, nonDustCount, dustCount, referenceIdeal, dustThreshold, enoughNonDust }
|
|
1525
|
+
*/
|
|
1526
|
+
function _classifyStartupOrderReuse({ sortedUnmatched, desiredSlots, assets, dustThresholdPercent, }) {
|
|
1527
|
+
const referenceIdeal = desiredSlots.length > 0
|
|
1528
|
+
? desiredSlots.reduce((sum, slot) => sum + (Number(slot?.size) || 0), 0) / desiredSlots.length
|
|
1529
|
+
: 0;
|
|
1530
|
+
const dustThreshold = getSingleDustThreshold(referenceIdeal, dustThresholdPercent);
|
|
1531
|
+
const isDustOrder = (chainOrder) => {
|
|
1532
|
+
if (!(dustThreshold > 0))
|
|
1533
|
+
return false;
|
|
1534
|
+
const parsed = parseChainOrder(chainOrder, assets);
|
|
1535
|
+
const size = Number(parsed?.size ?? 0);
|
|
1536
|
+
return size > 0 && size < dustThreshold;
|
|
1537
|
+
};
|
|
1538
|
+
const nonDustUnmatched = sortedUnmatched.filter((chainOrder) => !isDustOrder(chainOrder));
|
|
1539
|
+
const dustUnmatched = sortedUnmatched.filter((chainOrder) => isDustOrder(chainOrder));
|
|
1540
|
+
const enoughNonDust = desiredSlots.length > 0 && nonDustUnmatched.length >= desiredSlots.length;
|
|
1541
|
+
return {
|
|
1542
|
+
updatePool: enoughNonDust ? nonDustUnmatched : sortedUnmatched,
|
|
1543
|
+
dustSurplus: enoughNonDust ? dustUnmatched : [],
|
|
1544
|
+
nonDustCount: nonDustUnmatched.length,
|
|
1545
|
+
dustCount: dustUnmatched.length,
|
|
1546
|
+
referenceIdeal,
|
|
1547
|
+
dustThreshold,
|
|
1548
|
+
enoughNonDust,
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1401
1551
|
async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders, unmatchedSideOrders, manager, chainOrders, account, privateKey, dryRun, plannedCreates, plannedUpdates, plannedCancels, planOnly = false, }) {
|
|
1402
1552
|
const logger = manager?.logger;
|
|
1403
1553
|
const sideUpper = orderType === ORDER_TYPES.SELL ? 'SELL' : 'BUY';
|
|
@@ -1437,7 +1587,19 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1437
1587
|
desiredSlots = [...desiredSlots.slice(0, keepCount), ...freshEdge];
|
|
1438
1588
|
}
|
|
1439
1589
|
const sortedUnmatched = unmatchedSideOrders.slice(0).sort(sortUpdateComparator);
|
|
1440
|
-
const
|
|
1590
|
+
const classifiedReuse = _classifyStartupOrderReuse({
|
|
1591
|
+
sortedUnmatched,
|
|
1592
|
+
desiredSlots,
|
|
1593
|
+
assets: manager.assets,
|
|
1594
|
+
dustThresholdPercent: manager.config?.gridLimits?.PARTIAL_DUST_THRESHOLD_PERCENTAGE,
|
|
1595
|
+
});
|
|
1596
|
+
// Only the Phase-1 (planOnly) caller can execute cancels. A non-planOnly
|
|
1597
|
+
// caller must keep every order eligible for update rather than silently
|
|
1598
|
+
// dropping dust from both the update pool and the cancel queue.
|
|
1599
|
+
const updatePool = planOnly ? classifiedReuse.updatePool : sortedUnmatched;
|
|
1600
|
+
const dustSurplus = planOnly ? classifiedReuse.dustSurplus : [];
|
|
1601
|
+
const nonDustCount = classifiedReuse.nonDustCount;
|
|
1602
|
+
const updateCount = Math.min(updatePool.length, desiredSlots.length);
|
|
1441
1603
|
let cancelledIndex = null;
|
|
1442
1604
|
let projectedSideBalance = Number(manager.accountTotals?.[balanceKey] || 0);
|
|
1443
1605
|
// Vacated-rail-slot tracking (Phase 4, vacate+create atomic): a re-map
|
|
@@ -1454,16 +1616,17 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1454
1616
|
const refillCandidates = [];
|
|
1455
1617
|
const planVacatedRailRefill = (chainOrder, parsedChain) => {
|
|
1456
1618
|
const boundary = manager.boundaryIdx;
|
|
1457
|
-
|
|
1619
|
+
// Geometry comes from the single source of truth (resolveGapSlots:
|
|
1620
|
+
// `_gapSlots` when published, config-derived otherwise). Reading the raw
|
|
1621
|
+
// field here made an unpublished `_gapSlots` silently disable the refill
|
|
1622
|
+
// while every other classify site derived a valid band.
|
|
1623
|
+
const gapSlots = resolveGapSlots(manager);
|
|
1458
1624
|
// Explicit null/undefined/'' guard BEFORE Number(): Number(null) === 0
|
|
1459
1625
|
// is finite and would defeat this bail-out, running the refill scan on
|
|
1460
|
-
// a bogus boundary 0
|
|
1461
|
-
// getSellStartIdx).
|
|
1626
|
+
// a bogus boundary 0.
|
|
1462
1627
|
if (boundary === null || boundary === undefined || boundary === '')
|
|
1463
1628
|
return;
|
|
1464
|
-
if (
|
|
1465
|
-
return;
|
|
1466
|
-
if (!Number.isFinite(Number(boundary)) || !Number.isFinite(Number(gapSlots)))
|
|
1629
|
+
if (!Number.isFinite(Number(boundary)))
|
|
1467
1630
|
return;
|
|
1468
1631
|
const chainPrice = parsedChain?.price;
|
|
1469
1632
|
if (!Number.isFinite(Number(chainPrice)))
|
|
@@ -1509,7 +1672,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1509
1672
|
account,
|
|
1510
1673
|
privateKey,
|
|
1511
1674
|
manager,
|
|
1512
|
-
unmatchedOrders:
|
|
1675
|
+
unmatchedOrders: updatePool,
|
|
1513
1676
|
updateCount,
|
|
1514
1677
|
orderType,
|
|
1515
1678
|
dryRun,
|
|
@@ -1524,7 +1687,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1524
1687
|
releaseUntrackedFunds: true,
|
|
1525
1688
|
orderType,
|
|
1526
1689
|
boundaryIdx: manager?.boundaryIdx,
|
|
1527
|
-
gapSlots: manager
|
|
1690
|
+
gapSlots: resolveGapSlots(manager),
|
|
1528
1691
|
});
|
|
1529
1692
|
}
|
|
1530
1693
|
}
|
|
@@ -1532,7 +1695,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1532
1695
|
for (let i = 0; i < updateCount; i++) {
|
|
1533
1696
|
if (cancelledIndex !== null && i === cancelledIndex)
|
|
1534
1697
|
continue;
|
|
1535
|
-
const chainOrder =
|
|
1698
|
+
const chainOrder = updatePool[i];
|
|
1536
1699
|
const gridOrder = desiredSlots[i];
|
|
1537
1700
|
const gridSize = Number(gridOrder.size) || 0;
|
|
1538
1701
|
const parsedChain = parseChainOrder(chainOrder, manager.assets);
|
|
@@ -1588,7 +1751,29 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1588
1751
|
},
|
|
1589
1752
|
});
|
|
1590
1753
|
}
|
|
1591
|
-
const processedUnmatched =
|
|
1754
|
+
const processedUnmatched = updatePool.slice(updateCount);
|
|
1755
|
+
// Queue the dust-surplus cancels after the update plans. Phase 2 always runs
|
|
1756
|
+
// cancels before creates/updates, so these can never be paired into a slot.
|
|
1757
|
+
// planOnly is the Phase-1 contract; the actual broadcast happens in Phase 2.
|
|
1758
|
+
let dustCancelledCount = 0;
|
|
1759
|
+
if (planOnly && dustSurplus.length > 0) {
|
|
1760
|
+
const alreadyPlanned = new Set(plannedCancels.map((plan) => String(plan.chainOrderId)));
|
|
1761
|
+
for (const dustOrder of dustSurplus) {
|
|
1762
|
+
if (alreadyPlanned.has(String(dustOrder.id)))
|
|
1763
|
+
continue;
|
|
1764
|
+
plannedCancels.push({
|
|
1765
|
+
chainOrderId: dustOrder.id,
|
|
1766
|
+
chainOrderObj: dustOrder,
|
|
1767
|
+
releaseUntrackedFunds: true,
|
|
1768
|
+
orderType,
|
|
1769
|
+
boundaryIdx: manager?.boundaryIdx,
|
|
1770
|
+
gapSlots: resolveGapSlots(manager),
|
|
1771
|
+
});
|
|
1772
|
+
dustCancelledCount++;
|
|
1773
|
+
logger?.log?.(`Startup: Cancelling ${sideUpper} dust order ${dustOrder.id} ` +
|
|
1774
|
+
`(${nonDustCount} non-dust order(s) already cover ${desiredSlots.length} needed slot(s); not pricing it into a full-size slot)`, 'info');
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1592
1777
|
// Slot-N gated chain count: fork-kept shelf/manual orders (non-slot-N
|
|
1593
1778
|
// grid ids, e.g. deep-*) sit outside window accounting — same gate as
|
|
1594
1779
|
// _countActiveOnGrid and matched-excess candidates (issue #27 follow-up).
|
|
@@ -1607,19 +1792,41 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1607
1792
|
}
|
|
1608
1793
|
}
|
|
1609
1794
|
catch { /* fail-open: keep unfiltered count */ }
|
|
1795
|
+
// Dust-surplus cancels are already queued above, so the remaining chain
|
|
1796
|
+
// count must exclude them. Use the ACTUALLY queued count, not
|
|
1797
|
+
// dustSurplus.length: the alreadyPlanned guard can skip a dust order that
|
|
1798
|
+
// is already in plannedCancels, and subtracting it twice would fabricate
|
|
1799
|
+
// a shortfall (or over-cancel a healthy matched order). Without this
|
|
1800
|
+
// adjustment `createCount` would over-count (no create for the freed level)
|
|
1801
|
+
// and `cancelCount` would double-count the dust as excess.
|
|
1802
|
+
chainCount = Math.max(0, chainCount - dustCancelledCount);
|
|
1610
1803
|
const createCount = Math.max(0, targetCount - chainCount);
|
|
1611
1804
|
const remainingSlots = desiredSlots.slice(updateCount);
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1805
|
+
// UNSETTLED-FILL GATE: while fills are queued, draining, in flight, or
|
|
1806
|
+
// owed a crawl, the master still treats filled slots as ACTIVE and the
|
|
1807
|
+
// boundary has not crawled for them. Any window top-up derived from that
|
|
1808
|
+
// geometry refills the EXPENSIVE end of the rail — the live incident
|
|
1809
|
+
// (12s of buys at 1282.78 -> 1310.04 while the market was ~1280). Defer
|
|
1810
|
+
// the top-up to the cycle after the fills (and their crawl) are committed;
|
|
1811
|
+
// 1:1 repairs (cancelled-slot replacement, vacated-rail refill) still run.
|
|
1812
|
+
const unsettled = hasUnsettledFills(manager);
|
|
1813
|
+
if (unsettled.unsettled && createCount > 0) {
|
|
1814
|
+
logger?.log?.(`Startup: Deferring ${Math.min(createCount, remainingSlots.length)} ${sideUpper} window top-up create(s): ` +
|
|
1815
|
+
`${unsettled.reason} — the rail must absorb the fills before it is refilled`, 'warn');
|
|
1816
|
+
}
|
|
1817
|
+
else {
|
|
1818
|
+
for (let i = 0; i < Math.min(createCount, remainingSlots.length); i++) {
|
|
1819
|
+
const gridOrder = remainingSlots[i];
|
|
1820
|
+
logger?.log?.(`Startup: Creating ${sideUpper} for grid ${gridOrder.id} (price=${Format.formatPrice6(gridOrder.price)}, size=${Format.formatSizeByOrderType(gridOrder.size, orderType, manager.assets)})`, 'info');
|
|
1821
|
+
plannedCreates.push({
|
|
1822
|
+
orderType,
|
|
1823
|
+
gridOrder,
|
|
1824
|
+
orderLabel: sideUpper,
|
|
1825
|
+
// Intentionally no recovery metadata here.
|
|
1826
|
+
// This preserves legacy behavior: regular virtual-slot creates only log failures,
|
|
1827
|
+
// while cancelled-slot replacement creates trigger a startup recovery sync.
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1623
1830
|
}
|
|
1624
1831
|
// Guard: when the matcher found zero active grid orders (matchedOnGrid === 0)
|
|
1625
1832
|
// AND we're actively scaling up (neededSlots > 0), the grid is freshly
|
|
@@ -1688,94 +1895,85 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1688
1895
|
return fa - fb;
|
|
1689
1896
|
});
|
|
1690
1897
|
}
|
|
1898
|
+
// ONE SELECTION, TWO SINKS. The planOnly and inline branches used to walk
|
|
1899
|
+
// the same two ordered lists with duplicated (and drifting) conditions —
|
|
1900
|
+
// the "plan/execute parity" bug class. Selection happens once here; a
|
|
1901
|
+
// planOnly call records the list for Phase 2, an inline call executes it.
|
|
1902
|
+
// Priority is identical either way: unmatched orphans first (untracked
|
|
1903
|
+
// funds), then matched surplus (funds stay tracked on the grid slot), and
|
|
1904
|
+
// edge order slots last (static insurance, already sorted above).
|
|
1905
|
+
const excessGapSlots = resolveGapSlots(manager);
|
|
1906
|
+
const excessPlans = [];
|
|
1907
|
+
for (const x of parsedUnmatched) {
|
|
1908
|
+
if (excessPlans.length >= cancelCount)
|
|
1909
|
+
break;
|
|
1910
|
+
excessPlans.push({
|
|
1911
|
+
chainOrderId: x.chain.id,
|
|
1912
|
+
chainOrderObj: x.chain,
|
|
1913
|
+
releaseUntrackedFunds: true,
|
|
1914
|
+
orderType,
|
|
1915
|
+
boundaryIdx: manager?.boundaryIdx,
|
|
1916
|
+
gapSlots: excessGapSlots,
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
// Matched excess must be PLANNED too, not only executed (issue #27
|
|
1920
|
+
// follow-up): startup reconcile always runs planOnly, and on a
|
|
1921
|
+
// fully-placed grid every chain order is matched — parsedUnmatched is
|
|
1922
|
+
// empty, so the surplus lived entirely on matched slots and was silently
|
|
1923
|
+
// dropped while the inline branch kept cancelling it. Nothing ever
|
|
1924
|
+
// created the vacancy, and a fully-placed grid could never converge to
|
|
1925
|
+
// its additive window+edge target (live 12 vs target 8 across restarts).
|
|
1926
|
+
for (const o of matchedExcess) {
|
|
1927
|
+
if (excessPlans.length >= cancelCount)
|
|
1928
|
+
break;
|
|
1929
|
+
if (!o.orderId)
|
|
1930
|
+
continue;
|
|
1931
|
+
excessPlans.push({
|
|
1932
|
+
chainOrderId: o.orderId,
|
|
1933
|
+
chainOrderObj: o,
|
|
1934
|
+
gridOrderId: o.id,
|
|
1935
|
+
gridOrder: { ...o },
|
|
1936
|
+
orderType,
|
|
1937
|
+
boundaryIdx: manager?.boundaryIdx,
|
|
1938
|
+
gapSlots: excessGapSlots,
|
|
1939
|
+
// Matched-slot funds are tracked on the grid slot; only unmatched
|
|
1940
|
+
// orphans release untracked funds.
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1691
1943
|
if (planOnly) {
|
|
1692
|
-
//
|
|
1693
|
-
//
|
|
1694
|
-
if (
|
|
1695
|
-
logger?.log?.(`Startup: ${sideUpper} excess ${
|
|
1696
|
-
for (const x of parsedUnmatched) {
|
|
1697
|
-
if (cancelCount <= 0)
|
|
1698
|
-
break;
|
|
1699
|
-
plannedCancels.push({
|
|
1700
|
-
chainOrderId: x.chain.id,
|
|
1701
|
-
chainOrderObj: x.chain,
|
|
1702
|
-
releaseUntrackedFunds: true,
|
|
1703
|
-
orderType,
|
|
1704
|
-
boundaryIdx: manager?.boundaryIdx,
|
|
1705
|
-
gapSlots: manager?._gapSlots,
|
|
1706
|
-
});
|
|
1707
|
-
cancelCount--;
|
|
1708
|
-
}
|
|
1944
|
+
// Phase-1 contract: record the cancellations for Phase 2 execution so
|
|
1945
|
+
// no blockchain I/O runs inside _gridLock (Level 3).
|
|
1946
|
+
if (excessPlans.length > 0) {
|
|
1947
|
+
logger?.log?.(`Startup: ${sideUpper} excess ${excessPlans.length} order(s) queued for cancellation (Phase 2)`, 'info');
|
|
1709
1948
|
}
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
// it. Nothing ever created the vacancy, and a fully-placed grid
|
|
1716
|
-
// could never converge to its additive window+edge target (live
|
|
1717
|
-
// 12 vs target 8 sat static across every restart). Same priority
|
|
1718
|
-
// as the execute branch: unmatched first (above), matched after,
|
|
1719
|
-
// edge order last (matchedExcess ordering).
|
|
1720
|
-
for (const o of matchedExcess) {
|
|
1721
|
-
if (cancelCount <= 0)
|
|
1722
|
-
break;
|
|
1723
|
-
if (!o.orderId)
|
|
1724
|
-
continue;
|
|
1725
|
-
logger?.log?.(`Startup: ${sideUpper} excess matched ${o.orderId} (grid ${o.id}) queued for cancellation (Phase 2)`, 'warn');
|
|
1726
|
-
plannedCancels.push({
|
|
1727
|
-
chainOrderId: o.orderId,
|
|
1728
|
-
chainOrderObj: o,
|
|
1729
|
-
gridOrderId: o.id,
|
|
1730
|
-
gridOrder: { ...o },
|
|
1731
|
-
orderType,
|
|
1732
|
-
boundaryIdx: manager?.boundaryIdx,
|
|
1733
|
-
gapSlots: manager?._gapSlots,
|
|
1734
|
-
// Matched-slot funds are tracked on the grid slot; only
|
|
1735
|
-
// unmatched orphans release untracked funds (mirrors the
|
|
1736
|
-
// execute branch, which passes no release flag here).
|
|
1737
|
-
});
|
|
1738
|
-
cancelCount--;
|
|
1949
|
+
for (const plan of excessPlans) {
|
|
1950
|
+
if (plan.gridOrderId) {
|
|
1951
|
+
logger?.log?.(`Startup: ${sideUpper} excess matched ${plan.chainOrderId} (grid ${plan.gridOrderId}) queued for cancellation (Phase 2)`, 'warn');
|
|
1952
|
+
}
|
|
1953
|
+
plannedCancels.push(plan);
|
|
1739
1954
|
}
|
|
1740
1955
|
}
|
|
1741
1956
|
else {
|
|
1742
|
-
for (const
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1957
|
+
for (const plan of excessPlans) {
|
|
1958
|
+
const label = plan.gridOrderId
|
|
1959
|
+
? `excess matched ${sideUpper} ${plan.chainOrderId} (grid ${plan.gridOrderId})`
|
|
1960
|
+
: `excess ${sideUpper} chain order ${plan.chainOrderId}`;
|
|
1961
|
+
logger?.log?.(`Startup: Cancelling ${label}`, plan.gridOrderId ? 'warn' : 'info');
|
|
1746
1962
|
try {
|
|
1747
1963
|
await _cancelChainOrder({
|
|
1748
1964
|
chainOrders,
|
|
1749
1965
|
account,
|
|
1750
1966
|
privateKey,
|
|
1751
1967
|
manager,
|
|
1752
|
-
chainOrderId:
|
|
1753
|
-
chainOrderObj:
|
|
1754
|
-
releaseUntrackedFunds: true,
|
|
1968
|
+
chainOrderId: plan.chainOrderId,
|
|
1969
|
+
chainOrderObj: plan.chainOrderObj,
|
|
1970
|
+
releaseUntrackedFunds: plan.releaseUntrackedFunds === true,
|
|
1755
1971
|
dryRun,
|
|
1756
1972
|
});
|
|
1757
|
-
logger?.log?.(`Startup: Successfully cancelled
|
|
1758
|
-
cancelCount--;
|
|
1973
|
+
logger?.log?.(`Startup: Successfully cancelled ${label}`, 'info');
|
|
1759
1974
|
}
|
|
1760
1975
|
catch (err) {
|
|
1761
|
-
logger?.log?.(`Startup: Failed to cancel ${
|
|
1762
|
-
}
|
|
1763
|
-
}
|
|
1764
|
-
if (cancelCount > 0) {
|
|
1765
|
-
for (const o of matchedExcess) {
|
|
1766
|
-
if (cancelCount <= 0)
|
|
1767
|
-
break;
|
|
1768
|
-
if (!o.orderId)
|
|
1769
|
-
continue;
|
|
1770
|
-
logger?.log?.(`Startup: Cancelling excess matched ${sideUpper} ${o.orderId} (grid ${o.id})`, 'warn');
|
|
1771
|
-
try {
|
|
1772
|
-
await _cancelChainOrder({ chainOrders, account, privateKey, manager, chainOrderId: o.orderId, dryRun, chainOrderObj: null });
|
|
1773
|
-
logger?.log?.(`Startup: Successfully cancelled excess matched ${sideUpper} order ${o.orderId} (grid ${o.id})`, 'info');
|
|
1774
|
-
cancelCount--;
|
|
1775
|
-
}
|
|
1776
|
-
catch (err) {
|
|
1777
|
-
logger?.log?.(`Startup: Failed to cancel matched ${sideUpper} ${o.orderId}: ${getErrorMessage(err)}`, 'error');
|
|
1778
|
-
}
|
|
1976
|
+
logger?.log?.(`Startup: Failed to cancel ${label}: ${getErrorMessage(err)}`, 'error');
|
|
1779
1977
|
}
|
|
1780
1978
|
}
|
|
1781
1979
|
}
|
|
@@ -1784,5 +1982,5 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1784
1982
|
chainCount,
|
|
1785
1983
|
};
|
|
1786
1984
|
}
|
|
1787
|
-
export { _countActiveOnGrid, _pickVirtualSlotsToActivate, _createOrderFromGrid, _prepareStartupUpdatePlan, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executeStartupCreateGroupBatch, _createStartupOrderWithHandling, _executePlannedStartupCreates, _reconcileStartupSide };
|
|
1985
|
+
export { _countActiveOnGrid, _pickVirtualSlotsToActivate, _createOrderFromGrid, _prepareStartupUpdatePlan, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executeStartupCreateGroupBatch, _createStartupOrderWithHandling, _executePlannedStartupCreates, _reconcileStartupSide, _classifyStartupOrderReuse };
|
|
1788
1986
|
//# sourceMappingURL=grid_reconcile_internal.js.map
|