dexbot 1.6.17 → 1.6.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/analysis/README.md +10 -9
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +3 -3
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/analyze_args.d.ts +2 -1
- package/dist/analysis/fills_source.d.ts +1 -8
- package/dist/analysis/fills_source.js +1 -1
- package/dist/analysis/grid_correction_check.d.ts +9 -6
- package/dist/analysis/grid_correction_check.js +56 -64
- package/dist/analysis/math_utils.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
- package/dist/market_adapter/cli_args.d.ts +6 -1
- package/dist/market_adapter/cli_args.js +16 -2
- package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
- package/dist/market_adapter/core/kibana_candles.js +3 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
- package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
- package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
- package/dist/market_adapter/inputs/window_cache.js +14 -1
- package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
- package/dist/market_adapter/lp_chart_runner.js +3 -1
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
- package/dist/market_adapter/market_adapter.d.ts +10 -2
- package/dist/market_adapter/market_adapter.js +10 -11
- package/dist/market_adapter/utils/chain.d.ts +2 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
- package/dist/market_adapter/utils/file_json_cache.js +3 -1
- package/dist/market_adapter/utils/file_lock.js +1 -1
- package/dist/market_adapter/utils/native_history.d.ts +7 -3
- package/dist/market_adapter/utils/native_history.js +3 -1
- package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/constants.js +6 -3
- package/dist/modules/dexbot_class.d.ts +8 -0
- package/dist/modules/dexbot_class.js +10 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
- package/dist/modules/dexbot_cow_runtime.js +461 -43
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +56 -9
- package/dist/modules/dexbot_startup_runtime.js +7 -1
- package/dist/modules/graceful_shutdown.d.ts +2 -2
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/launcher/runtime_mode.d.ts +4 -3
- package/dist/modules/node_manager.d.ts +1 -1
- package/dist/modules/node_manager.js +1 -1
- package/dist/modules/order/accounting.js +2 -1
- package/dist/modules/order/export.d.ts +2 -2
- package/dist/modules/order/export.js +2 -2
- package/dist/modules/order/grid.d.ts +19 -14
- package/dist/modules/order/grid.js +262 -61
- package/dist/modules/order/grid_reconcile.js +5 -1
- package/dist/modules/order/grid_reconcile_internal.js +2 -1
- package/dist/modules/order/index.d.ts +9 -3
- package/dist/modules/order/manager.d.ts +10 -0
- package/dist/modules/order/manager.js +41 -11
- package/dist/modules/order/strategy.js +22 -2
- package/dist/modules/order/sync_engine.d.ts +12 -1
- package/dist/modules/order/sync_engine.js +135 -20
- package/dist/modules/order/utils/math.d.ts +8 -9
- package/dist/modules/order/utils/math.js +24 -13
- package/dist/modules/order/utils/order.d.ts +52 -11
- package/dist/modules/order/utils/order.js +137 -21
- package/dist/modules/order/utils/system.d.ts +73 -29
- package/dist/modules/order/utils/system.js +239 -48
- package/dist/modules/order/utils/validate.d.ts +1 -0
- package/dist/modules/order/utils/validate.js +4 -1
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +9 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +20 -10
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +9 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
- package/docs/GRID_PRICE_INVARIANT.md +24 -4
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +15 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +123 -36
- package/docs/README.md +1 -1
- package/docs/architecture.md +115 -13
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +9 -4
- package/modules/README.md +18 -14
- package/package.json +4 -3
|
@@ -13,7 +13,7 @@ const { readOpenOrdersWithMetaSafe } = chainOrdersModule;
|
|
|
13
13
|
import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dexbot_credential_client.js';
|
|
14
14
|
const BroadcastUncertainError = BroadcastUncertainErrorBinding;
|
|
15
15
|
import * as orderUtils from './order/utils/order.js';
|
|
16
|
-
import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference, isLastFillGuardBlocked } from './order/utils/system.js';
|
|
16
|
+
import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference, resolveSpreadCrossingFloor, isLastFillGuardBlocked } from './order/utils/system.js';
|
|
17
17
|
const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
|
|
18
18
|
import * as validate from './order/utils/validate.js';
|
|
19
19
|
const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
|
|
@@ -1945,19 +1945,13 @@ function refreshLastFillPivotFromQueue(bot) {
|
|
|
1945
1945
|
const orderId = fillOp?.order_id || fill?.orderId;
|
|
1946
1946
|
let type = null;
|
|
1947
1947
|
let price = null;
|
|
1948
|
-
//
|
|
1949
|
-
//
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
price = slotPrice;
|
|
1956
|
-
}
|
|
1957
|
-
// Fall back to fill economics (B/A convention, mirroring
|
|
1958
|
-
// _computeFillContext's pays-asset side resolution, including
|
|
1959
|
-
// SPREAD slots carrying on-chain orders).
|
|
1960
|
-
if ((type == null || price == null) && fillOp?.pays && fillOp?.receives && assets?.assetA && assets?.assetB) {
|
|
1948
|
+
// FILL ECONOMICS FIRST: the pays/receives amounts are the trade
|
|
1949
|
+
// fact. The grid slot is only an identity hint — after a
|
|
1950
|
+
// refused-commit adoption it can still be keyed at an old
|
|
1951
|
+
// generation price (live incident: slot-118 @1267 for an order
|
|
1952
|
+
// that traded at 1345.73), and preferring the slot price made the
|
|
1953
|
+
// last-fill pivot / re-anchor judge a market that never traded.
|
|
1954
|
+
if (fillOp?.pays && fillOp?.receives && assets?.assetA && assets?.assetB) {
|
|
1961
1955
|
try {
|
|
1962
1956
|
const pays = fillOp.pays;
|
|
1963
1957
|
const receives = fillOp.receives;
|
|
@@ -1978,6 +1972,17 @@ function refreshLastFillPivotFromQueue(bot) {
|
|
|
1978
1972
|
}
|
|
1979
1973
|
catch { /* best-effort */ }
|
|
1980
1974
|
}
|
|
1975
|
+
// Fall back to the grid slot only when the fill amounts are absent
|
|
1976
|
+
// (a limit fill normally executes at its slot price).
|
|
1977
|
+
if ((type == null || price == null)) {
|
|
1978
|
+
const slot = findSlotByOrderId(orderId);
|
|
1979
|
+
if (slot && (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)) {
|
|
1980
|
+
type = slot.type;
|
|
1981
|
+
const slotPrice = Number(slot.price);
|
|
1982
|
+
if (Number.isFinite(slotPrice) && slotPrice > 0)
|
|
1983
|
+
price = slotPrice;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1981
1986
|
if ((type === ORDER_TYPES.BUY || type === ORDER_TYPES.SELL)
|
|
1982
1987
|
&& Number.isFinite(price) && price > 0) {
|
|
1983
1988
|
latest = { price: price, type };
|
|
@@ -2500,6 +2505,265 @@ function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUp
|
|
|
2500
2505
|
heldRefillSlotIds
|
|
2501
2506
|
};
|
|
2502
2507
|
}
|
|
2508
|
+
/**
|
|
2509
|
+
* Derive the boundary the actual rails imply.
|
|
2510
|
+
*
|
|
2511
|
+
* `boundary` is a claim about where the BUY rail ends and the gap band begins;
|
|
2512
|
+
* live orders are the fact. A fill-driven plan built at a re-anchored boundary
|
|
2513
|
+
* places COUNTER orders above the committed boundary (SELL fill at slot s =>
|
|
2514
|
+
* counter BUY at s - gapSlots). If the refill hold then keeps the old boundary,
|
|
2515
|
+
* those counters sit inside the implied band; the next plan sees the old
|
|
2516
|
+
* geometry and places a SELL on top of them, collapsing the spread (live
|
|
2517
|
+
* incident: a sweep's counters at 1329.7-1345.7 were reclassified as in-band by
|
|
2518
|
+
* a hold to 133, then sells were rotated to 1345.728664 — the exact price of
|
|
2519
|
+
* the buy that had just filled).
|
|
2520
|
+
*
|
|
2521
|
+
* Rails are clamped by construction:
|
|
2522
|
+
*
|
|
2523
|
+
* maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1
|
|
2524
|
+
*
|
|
2525
|
+
* Counter orders therefore win over empty refill holes: a held boundary may
|
|
2526
|
+
* never strand a placed counter. When the plan did not place an order on the
|
|
2527
|
+
* promoted rail (the normal refill-hold case) `maxBuyIdx` stays at/below the
|
|
2528
|
+
* committed boundary and the hold is preserved unchanged.
|
|
2529
|
+
*
|
|
2530
|
+
* @param manager - OrderManager (master grid rails)
|
|
2531
|
+
* @param opContexts - Kept op contexts of the batch (post guard/final gate)
|
|
2532
|
+
* @param desiredBoundary - Plan boundary (falls back to the committed one)
|
|
2533
|
+
* @param gapSlots - Gap band width
|
|
2534
|
+
* @returns Boundary implied by the rails, or null when no rail geometry is
|
|
2535
|
+
* usable / the rails already cross (caller keeps the current value).
|
|
2536
|
+
*/
|
|
2537
|
+
export function deriveRailBoundary(manager, opContexts, desiredBoundary, gapSlots) {
|
|
2538
|
+
let rawGap = Format.toKnownNumber(gapSlots);
|
|
2539
|
+
if (!Number.isFinite(rawGap)) {
|
|
2540
|
+
// Fall back to the genesis gap width before giving up: a restored
|
|
2541
|
+
// manager can briefly hold a null _gapSlots while the genesis is set.
|
|
2542
|
+
rawGap = Format.toKnownNumber(manager?._genesis?.gapSlots);
|
|
2543
|
+
}
|
|
2544
|
+
if (!Number.isFinite(rawGap) || rawGap < 0) {
|
|
2545
|
+
return { boundary: null, maxBuyIdx: null, minSellIdx: null, clamped: false, reason: 'no-gap' };
|
|
2546
|
+
}
|
|
2547
|
+
const gap = Math.floor(rawGap);
|
|
2548
|
+
const isSide = (t) => t === ORDER_TYPES.BUY || t === ORDER_TYPES.SELL;
|
|
2549
|
+
// Base first: the proximity window below is measured from it.
|
|
2550
|
+
const desired = Format.toKnownNumber(desiredBoundary);
|
|
2551
|
+
const committed = Format.toKnownNumber(manager?.boundaryIdx);
|
|
2552
|
+
const gates = manager;
|
|
2553
|
+
const coreBuy = Number(gates.config?.coreOrders?.buy);
|
|
2554
|
+
const coreSell = Number(gates.config?.coreOrders?.sell);
|
|
2555
|
+
const windowSize = Math.max(1, Number.isFinite(coreBuy) ? coreBuy : 1, Number.isFinite(coreSell) ? coreSell : 1);
|
|
2556
|
+
// STRAY RULE: a MASTER rail order only speaks for this batch if it sits on
|
|
2557
|
+
// its own side of the planned boundary — a BUY at/below it, a SELL at/above
|
|
2558
|
+
// the implied sellStart. Anything else is a rail-typed order parked in the
|
|
2559
|
+
// wrong zone (a refused-commit adoption at an old generation level, a
|
|
2560
|
+
// SPREAD-GUARD stray, a stranded hold) and letting it clamp the boundary
|
|
2561
|
+
// would SELF-LEGALIZE the corrupt state (live class: one live sell 18 slots
|
|
2562
|
+
// below clamped 138 -> 115 and re-typed the whole window).
|
|
2563
|
+
// Ops of THIS batch are always counted: a counter order is the rail fact.
|
|
2564
|
+
const baseForProximity = Number.isFinite(desired) ? Number(desired) : (Number.isFinite(committed) ? Number(committed) : null);
|
|
2565
|
+
// Kept for the report line: how many window slots this grid claims per side
|
|
2566
|
+
// (informational; the stray rule needs no window size).
|
|
2567
|
+
const proximityWindow = windowSize + gap + 1;
|
|
2568
|
+
// Start from the live master rails, then apply the kept ops as a delta.
|
|
2569
|
+
// This is the post-batch rail set: cancels remove, creates add, rotations
|
|
2570
|
+
// move (source -> destination), size updates stay.
|
|
2571
|
+
// Rail index per entry is the LIVE ladder position where known (a slot id
|
|
2572
|
+
// can be stale after a refused-commit adoption — same rule the fill, gap
|
|
2573
|
+
// and crossing paths already use), with the slot id as fallback.
|
|
2574
|
+
const rails = new Map();
|
|
2575
|
+
const vacatedSlotIds = new Set();
|
|
2576
|
+
const master = manager?.orders;
|
|
2577
|
+
let maxSlotIdx = null;
|
|
2578
|
+
if (master instanceof Map) {
|
|
2579
|
+
for (const raw of master.values()) {
|
|
2580
|
+
const o = raw;
|
|
2581
|
+
if (!o || !o.id)
|
|
2582
|
+
continue;
|
|
2583
|
+
const parsed = parseSlotIndex(o.id);
|
|
2584
|
+
if (parsed !== null && parsed !== undefined && Number.isFinite(Number(parsed))) {
|
|
2585
|
+
maxSlotIdx = maxSlotIdx === null ? Number(parsed) : Math.max(maxSlotIdx, Number(parsed));
|
|
2586
|
+
}
|
|
2587
|
+
if (!o.orderId || (o.state !== ORDER_STATES.ACTIVE && o.state !== ORDER_STATES.PARTIAL))
|
|
2588
|
+
continue;
|
|
2589
|
+
if (!isSide(o.type))
|
|
2590
|
+
continue;
|
|
2591
|
+
const live = orderUtils.resolveLiveOrderLadderPosition(o, manager?.assets, manager?._genesis);
|
|
2592
|
+
const idx = live.idx !== null && Number.isFinite(Number(live.idx)) ? Number(live.idx) : null;
|
|
2593
|
+
rails.set(String(o.id), { side: o.type, idx, byOp: false });
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
if (opContexts && typeof opContexts[Symbol.iterator] === 'function') {
|
|
2597
|
+
for (const raw of opContexts) {
|
|
2598
|
+
const ctx = raw;
|
|
2599
|
+
if (!ctx)
|
|
2600
|
+
continue;
|
|
2601
|
+
if (ctx.kind === 'cancel') {
|
|
2602
|
+
const id = ctx.order?.id;
|
|
2603
|
+
if (id != null) {
|
|
2604
|
+
rails.delete(String(id));
|
|
2605
|
+
vacatedSlotIds.add(String(id));
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
else if (ctx.kind === 'create') {
|
|
2609
|
+
const id = ctx.id;
|
|
2610
|
+
const side = ctx.order?.type;
|
|
2611
|
+
if (id != null) {
|
|
2612
|
+
const parsedId = parseSlotIndex(String(id));
|
|
2613
|
+
if (parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId))) {
|
|
2614
|
+
maxSlotIdx = maxSlotIdx === null ? Number(parsedId) : Math.max(maxSlotIdx, Number(parsedId));
|
|
2615
|
+
}
|
|
2616
|
+
if (isSide(side)) {
|
|
2617
|
+
rails.set(String(id), {
|
|
2618
|
+
side,
|
|
2619
|
+
idx: parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId)) ? Number(parsedId) : null,
|
|
2620
|
+
byOp: true
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
else if (ctx.kind === 'rotation') {
|
|
2626
|
+
const rotation = ctx.rotation;
|
|
2627
|
+
const oldId = rotation?.oldOrder?.id;
|
|
2628
|
+
const newId = rotation?.newGridId;
|
|
2629
|
+
const side = rotation?.type;
|
|
2630
|
+
if (oldId != null) {
|
|
2631
|
+
rails.delete(String(oldId));
|
|
2632
|
+
vacatedSlotIds.add(String(oldId));
|
|
2633
|
+
}
|
|
2634
|
+
if (newId != null) {
|
|
2635
|
+
const parsedId = parseSlotIndex(String(newId));
|
|
2636
|
+
if (parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId))) {
|
|
2637
|
+
maxSlotIdx = maxSlotIdx === null ? Number(parsedId) : Math.max(maxSlotIdx, Number(parsedId));
|
|
2638
|
+
}
|
|
2639
|
+
if (isSide(side)) {
|
|
2640
|
+
rails.set(String(newId), {
|
|
2641
|
+
side,
|
|
2642
|
+
idx: parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId)) ? Number(parsedId) : null,
|
|
2643
|
+
byOp: true
|
|
2644
|
+
});
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
else if (ctx.kind === 'size-update') {
|
|
2649
|
+
const o = ctx.updateInfo?.partialOrder;
|
|
2650
|
+
if (o?.id != null && isSide(o.type)) {
|
|
2651
|
+
const parsedId = parseSlotIndex(String(o.id));
|
|
2652
|
+
rails.set(String(o.id), {
|
|
2653
|
+
side: o.type,
|
|
2654
|
+
idx: parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId)) ? Number(parsedId) : null,
|
|
2655
|
+
byOp: true
|
|
2656
|
+
});
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
let maxBuyIdx = null;
|
|
2662
|
+
let minSellIdx = null;
|
|
2663
|
+
let ignoredStrays = 0;
|
|
2664
|
+
const sellStartForStray = baseForProximity !== null ? baseForProximity + gap + 1 : null;
|
|
2665
|
+
for (const [, rail] of rails) {
|
|
2666
|
+
const idx = rail.idx;
|
|
2667
|
+
if (idx === null || !Number.isFinite(idx))
|
|
2668
|
+
continue;
|
|
2669
|
+
if (!rail.byOp && baseForProximity !== null) {
|
|
2670
|
+
const stray = rail.side === ORDER_TYPES.BUY
|
|
2671
|
+
? idx > baseForProximity
|
|
2672
|
+
: (sellStartForStray !== null && idx < sellStartForStray);
|
|
2673
|
+
if (stray) {
|
|
2674
|
+
ignoredStrays++;
|
|
2675
|
+
continue;
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
if (rail.side === ORDER_TYPES.BUY)
|
|
2679
|
+
maxBuyIdx = maxBuyIdx === null ? idx : Math.max(maxBuyIdx, idx);
|
|
2680
|
+
else
|
|
2681
|
+
minSellIdx = minSellIdx === null ? idx : Math.min(minSellIdx, idx);
|
|
2682
|
+
}
|
|
2683
|
+
if (maxBuyIdx === null && minSellIdx === null) {
|
|
2684
|
+
return { boundary: null, maxBuyIdx: null, minSellIdx: null, clamped: false, reason: 'no-rails' };
|
|
2685
|
+
}
|
|
2686
|
+
// A live BUY at b needs boundary >= b; a live SELL at s needs
|
|
2687
|
+
// boundary <= s - gap - 1. An empty interval means the rails already
|
|
2688
|
+
// overlap (pre-existing crossed book): do not legalize it here.
|
|
2689
|
+
const upper = minSellIdx === null ? Infinity : minSellIdx - gap - 1;
|
|
2690
|
+
if (maxBuyIdx !== null && maxBuyIdx > upper) {
|
|
2691
|
+
return {
|
|
2692
|
+
boundary: null,
|
|
2693
|
+
maxBuyIdx,
|
|
2694
|
+
minSellIdx,
|
|
2695
|
+
clamped: false,
|
|
2696
|
+
reason: `rail-crossed maxBuy=${maxBuyIdx} > minSell-gap-1=${upper}`
|
|
2697
|
+
};
|
|
2698
|
+
}
|
|
2699
|
+
let base = baseForProximity;
|
|
2700
|
+
if (base === null) {
|
|
2701
|
+
base = maxBuyIdx !== null ? maxBuyIdx : (Number.isFinite(upper) ? upper : 0);
|
|
2702
|
+
}
|
|
2703
|
+
// Grid ceiling: the SELL rail must fit (sellStart <= last slot). A
|
|
2704
|
+
// destination slot in this batch can extend the observed maximum.
|
|
2705
|
+
const gridCeiling = maxSlotIdx !== null && maxSlotIdx - gap - 1 >= 0
|
|
2706
|
+
? maxSlotIdx - gap - 1
|
|
2707
|
+
: null;
|
|
2708
|
+
const allowedUpper = Number.isFinite(upper)
|
|
2709
|
+
? (gridCeiling === null ? upper : Math.min(upper, gridCeiling))
|
|
2710
|
+
: gridCeiling;
|
|
2711
|
+
if (maxBuyIdx !== null && allowedUpper !== null && maxBuyIdx > allowedUpper) {
|
|
2712
|
+
return {
|
|
2713
|
+
boundary: null,
|
|
2714
|
+
maxBuyIdx,
|
|
2715
|
+
minSellIdx,
|
|
2716
|
+
clamped: false,
|
|
2717
|
+
reason: `rail-exceeds-grid maxBuy=${maxBuyIdx} > ceiling=${allowedUpper}`
|
|
2718
|
+
};
|
|
2719
|
+
}
|
|
2720
|
+
let next = base;
|
|
2721
|
+
if (allowedUpper !== null)
|
|
2722
|
+
next = Math.min(next, allowedUpper);
|
|
2723
|
+
if (maxBuyIdx !== null)
|
|
2724
|
+
next = Math.max(next, maxBuyIdx);
|
|
2725
|
+
next = Math.max(0, next);
|
|
2726
|
+
// FINAL GATE — the SAME validator the restore and commit paths use
|
|
2727
|
+
// (validatePersistedBoundary), so the rail clamp can never legalize a
|
|
2728
|
+
// boundary that strands a live order inside the implied band. Slots this
|
|
2729
|
+
// batch vacates (cancels / rotation sources) are allow-listed: they will
|
|
2730
|
+
// not be placed after the batch, so judging them as stranding would refuse
|
|
2731
|
+
// every legitimate evacuation clamp.
|
|
2732
|
+
//
|
|
2733
|
+
// Dense-ladder condition: validateBoundaryCommit derives its sell-rail
|
|
2734
|
+
// ceiling from the SORTED ARRAY LENGTH (`slots.length - 1`), which only
|
|
2735
|
+
// equals the grid ceiling when the master map holds every slot 0..N-1 (the
|
|
2736
|
+
// production invariant). A sparse/partial map would make the gate reject
|
|
2737
|
+
// every candidate as out-of-range, so it is skipped there — the clamp
|
|
2738
|
+
// inequalities above stay the authority in that state.
|
|
2739
|
+
{
|
|
2740
|
+
const slotsForGate = master instanceof Map ? Array.from(master.values()) : [];
|
|
2741
|
+
const dense = slotsForGate.length > 0
|
|
2742
|
+
&& maxSlotIdx !== null
|
|
2743
|
+
&& Number(maxSlotIdx) === slotsForGate.length - 1;
|
|
2744
|
+
if (dense) {
|
|
2745
|
+
const check = math.validatePersistedBoundary(next, slotsForGate, gap, vacatedSlotIds.size > 0 ? { allowInBandSlotIds: vacatedSlotIds } : undefined);
|
|
2746
|
+
if (!check || check.ok !== true) {
|
|
2747
|
+
return {
|
|
2748
|
+
boundary: null,
|
|
2749
|
+
maxBuyIdx,
|
|
2750
|
+
minSellIdx,
|
|
2751
|
+
clamped: false,
|
|
2752
|
+
reason: `unsafe: ${check?.reason ?? 'unknown'}${check?.detail ? ` (${check.detail})` : ''}`
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2757
|
+
return {
|
|
2758
|
+
boundary: next,
|
|
2759
|
+
maxBuyIdx,
|
|
2760
|
+
minSellIdx,
|
|
2761
|
+
clamped: next !== base,
|
|
2762
|
+
...(next !== base
|
|
2763
|
+
? { reason: `rail-clamped maxBuy=${maxBuyIdx ?? 'none'} minSell=${minSellIdx ?? 'none'}${ignoredStrays > 0 ? ` (${ignoredStrays} stray rail order(s) ignored)` : ''}` }
|
|
2764
|
+
: (ignoredStrays > 0 ? { reason: `rail-steady (${ignoredStrays} stray rail order(s) ignored; window=${proximityWindow})` } : {}))
|
|
2765
|
+
};
|
|
2766
|
+
}
|
|
2503
2767
|
/**
|
|
2504
2768
|
* Track consecutive boundary-hold batches on the manager (ops visibility).
|
|
2505
2769
|
*
|
|
@@ -3270,6 +3534,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3270
3534
|
// would spam big batches, so the guard emits one batch summary instead
|
|
3271
3535
|
// (see the summary after the action loop below).
|
|
3272
3536
|
const lastFillGuardStats = { checked: 0, passed: 0, skipped: 0, bypassed: 0, pivotOffGrid: 0 };
|
|
3537
|
+
// One crossing-CREATE observation per batch (see warnCrossingCreate).
|
|
3538
|
+
let crossingCreateWarned = false;
|
|
3273
3539
|
// Fingerprints of the pending-broadcast entries recorded by THIS batch's
|
|
3274
3540
|
// op-building (both CREATE paths). The final pivot gate's compaction
|
|
3275
3541
|
// remaps these entries' stored opIndex/ctxIndex to their post-drop
|
|
@@ -3455,7 +3721,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3455
3721
|
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
3456
3722
|
&& isSpreadCorrectionBypassAllowed(bot);
|
|
3457
3723
|
if (!isCorrectionCreate) {
|
|
3458
|
-
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.
|
|
3724
|
+
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.type, lastFillGuardStats, true);
|
|
3459
3725
|
if (refreshed)
|
|
3460
3726
|
lastFillGuardPivotRefreshed = true;
|
|
3461
3727
|
if (check.blocked) {
|
|
@@ -3473,6 +3739,20 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3473
3739
|
}
|
|
3474
3740
|
}
|
|
3475
3741
|
catch (_e) { /* guard is best-effort */ }
|
|
3742
|
+
// PLANNER/EXECUTION ASYMMETRY (observability only).
|
|
3743
|
+
// The spread-correction planner refuses a candidate that
|
|
3744
|
+
// crosses the live-market/fill floor (doesNotCrossMarket);
|
|
3745
|
+
// this generic CREATE path (reconcile refills, rotation
|
|
3746
|
+
// fallbacks) has no such gate — deliberately, because a hard
|
|
3747
|
+
// veto here would re-open the counter-order deadlock: after
|
|
3748
|
+
// a gap the counter lands on the better side of the market
|
|
3749
|
+
// by construction, and a gapped market can put the planned
|
|
3750
|
+
// level on the other side, where it executes at the BEST
|
|
3751
|
+
// available price (a taker fill, never a worse price).
|
|
3752
|
+
// So this is a fee/liquidity observation, not a safety veto.
|
|
3753
|
+
if (!crossingCreateWarned) {
|
|
3754
|
+
crossingCreateWarned = warnCrossingCreate(bot, createPrice, order.type, order.id);
|
|
3755
|
+
}
|
|
3476
3756
|
const args = buildCreateOrderArgs(effectiveOrder, assetA, assetB);
|
|
3477
3757
|
// GRID-PRICE-INVARIANT (blocking): the CREATE price must be
|
|
3478
3758
|
// the genesis level for this slot. A mismatch means state
|
|
@@ -3642,7 +3922,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3642
3922
|
if (!stampValid) {
|
|
3643
3923
|
stampUsable = false;
|
|
3644
3924
|
bot.manager.logger.log(`[LAST-FILL-GUARD] Stamped evacuation for ${action.id} -> ${action.newGridId} is stale under live ` +
|
|
3645
|
-
`boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} —
|
|
3925
|
+
`boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} — refusing the stale plan`, 'warn');
|
|
3646
3926
|
}
|
|
3647
3927
|
}
|
|
3648
3928
|
if (stampUsable) {
|
|
@@ -3701,31 +3981,53 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3701
3981
|
catch {
|
|
3702
3982
|
sidePrecision = null;
|
|
3703
3983
|
}
|
|
3704
|
-
// Geometry re-proof under the LIVE boundary
|
|
3705
|
-
//
|
|
3706
|
-
//
|
|
3707
|
-
//
|
|
3708
|
-
//
|
|
3709
|
-
|
|
3984
|
+
// Geometry re-proof under the LIVE boundary. A stale
|
|
3985
|
+
// evacuation must NOT fall through to the direction-only
|
|
3986
|
+
// last-fill guard: that guard only checks the fill price,
|
|
3987
|
+
// not whether the move still makes grid sense. Live
|
|
3988
|
+
// incident 2026-10-30: a plan built at boundary 124
|
|
3989
|
+
// wanted to evacuate buys 125-128; by execution the
|
|
3990
|
+
// boundary was 128 and those orders were valid in-rail.
|
|
3991
|
+
// The stale probe was rejected, the normal guard then
|
|
3992
|
+
// allowed the four lower buys, and the grid lost its
|
|
3993
|
+
// bid edge (spread 1.51% -> 2.74%). Fail closed: skip
|
|
3994
|
+
// the op and let the next plan/reconcile re-evaluate.
|
|
3995
|
+
// Non-finite live geometry keeps plan-build authority
|
|
3996
|
+
// (isEvacuationStampStillValid returns true there).
|
|
3997
|
+
let staleSkipReason = null;
|
|
3998
|
+
if (!isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, action.id, action.newGridId, orderType)) {
|
|
3999
|
+
staleSkipReason = `source/dest no longer evacuation geometry under live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}`;
|
|
4000
|
+
}
|
|
4001
|
+
else {
|
|
3710
4002
|
const evacCheck = isEvacuationRotationAllowed(oldPrice, oldSize, newPrice, newSize, orderType, sidePrecision);
|
|
3711
4003
|
if (evacCheck.allowed) {
|
|
3712
4004
|
bypassedEvacuation = true;
|
|
3713
4005
|
bot.manager.logger.log(`[LAST-FILL-GUARD] Allowing ${orderType} evacuation UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ` +
|
|
3714
4006
|
`${evacCheck.reason} (probed live: ${Format.formatPrice6(oldPrice)} -> ${Format.formatPrice6(newPrice)})`, 'warn');
|
|
3715
4007
|
}
|
|
4008
|
+
else {
|
|
4009
|
+
staleSkipReason = evacCheck.reason;
|
|
4010
|
+
}
|
|
3716
4011
|
}
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
4012
|
+
if (!bypassedEvacuation) {
|
|
4013
|
+
lastFillGuardStats.checked++;
|
|
4014
|
+
lastFillGuardStats.skipped++;
|
|
4015
|
+
skippedUpdateCount++;
|
|
4016
|
+
if (action.id)
|
|
4017
|
+
skippedUpdateSlotIds.add(action.id);
|
|
4018
|
+
if (action.newGridId)
|
|
4019
|
+
skippedUpdateSlotIds.add(action.newGridId);
|
|
4020
|
+
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId}: ` +
|
|
4021
|
+
`stale gap-evacuation (${staleSkipReason ?? 'not violation-reducing'}) — next plan re-evaluates`, 'warn');
|
|
4022
|
+
continue;
|
|
3720
4023
|
}
|
|
3721
|
-
// Not allowed: fall through to the normal guard below.
|
|
3722
4024
|
}
|
|
3723
4025
|
}
|
|
3724
4026
|
if (bypassedEvacuation) {
|
|
3725
4027
|
lastFillGuardStats.bypassed++;
|
|
3726
4028
|
}
|
|
3727
4029
|
else {
|
|
3728
|
-
const { check, refreshed } = runLastFillGuardCheck(bot, newPrice,
|
|
4030
|
+
const { check, refreshed } = runLastFillGuardCheck(bot, newPrice, orderType, lastFillGuardStats, true);
|
|
3729
4031
|
if (refreshed)
|
|
3730
4032
|
lastFillGuardPivotRefreshed = true;
|
|
3731
4033
|
if (check.blocked) {
|
|
@@ -3873,7 +4175,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3873
4175
|
// so it obeys the same guard against the frozen
|
|
3874
4176
|
// batch pivot — no origin bypass, same as rotations.
|
|
3875
4177
|
try {
|
|
3876
|
-
const { check: fbCheck, refreshed: fbRefreshed } = runLastFillGuardCheck(bot, fbPrice,
|
|
4178
|
+
const { check: fbCheck, refreshed: fbRefreshed } = runLastFillGuardCheck(bot, fbPrice, fbType, lastFillGuardStats, true);
|
|
3877
4179
|
if (fbRefreshed)
|
|
3878
4180
|
lastFillGuardPivotRefreshed = true;
|
|
3879
4181
|
if (fbCheck.blocked) {
|
|
@@ -4086,10 +4388,35 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4086
4388
|
bot.manager.logger.log(`[COW] Boundary hold: ${refillHold.heldRefillSlotIds.length} refill slot(s) skipped ` +
|
|
4087
4389
|
`(${refillHold.heldRefillSlotIds.join(', ')}) — keeping ${bot.manager.boundaryIdx} over planned ${workingBoundary}`, 'warn');
|
|
4088
4390
|
}
|
|
4391
|
+
// RAIL-DERIVED BOUNDARY: the committed boundary must match the rails the
|
|
4392
|
+
// batch actually places. A fill-driven plan built at a re-anchored
|
|
4393
|
+
// boundary puts counter orders on the promoted rail (SELL fill at s ->
|
|
4394
|
+
// counter BUY at s-gap); holding the old boundary would reclassify those
|
|
4395
|
+
// counters as in-band and the next plan would place sells on top of them
|
|
4396
|
+
// (spread collapse). Counter orders win over empty refill holes: clamp
|
|
4397
|
+
// to [maxBuy, minSell-gap-1]. In the pure-refill-hold case no order was
|
|
4398
|
+
// placed above the committed boundary, so this is a no-op.
|
|
4399
|
+
const railBoundary = deriveRailBoundary(bot.manager, opContexts, effectiveBoundary, bot.manager?._gapSlots);
|
|
4400
|
+
if (railBoundary.boundary !== null && Number.isFinite(Number(railBoundary.boundary))) {
|
|
4401
|
+
const railEffective = Number(railBoundary.boundary);
|
|
4402
|
+
if (railEffective !== effectiveBoundary) {
|
|
4403
|
+
bot.manager.logger.log(`[COW] Boundary rail-derived: planned ${workingBoundary}, held ${effectiveBoundary} -> ${railEffective} ` +
|
|
4404
|
+
`(maxBuy=${railBoundary.maxBuyIdx ?? 'none'}, minSell=${railBoundary.minSellIdx ?? 'none'}) ` +
|
|
4405
|
+
`— keeping placed counter orders on their rails`, 'warn');
|
|
4406
|
+
effectiveBoundary = railEffective;
|
|
4407
|
+
}
|
|
4408
|
+
}
|
|
4409
|
+
else if (railBoundary.reason) {
|
|
4410
|
+
bot.manager.logger.log(`[COW] Boundary rail-derived: unusable (${railBoundary.reason}); keeping ${effectiveBoundary}`, 'warn');
|
|
4411
|
+
}
|
|
4412
|
+
// Commit bookkeeping follows the boundary actually committed: a plan
|
|
4413
|
+
// whose target equals the effective value applied its crawls even when
|
|
4414
|
+
// the refill hold triggered (the counters carried the shift).
|
|
4415
|
+
boundaryHeld = effectiveBoundary !== workingBoundary;
|
|
4089
4416
|
// Consecutive-hold tracking (INV-COW-007 visibility): escalate a
|
|
4090
4417
|
// growing run — the grid is trailing the market and only fresh
|
|
4091
4418
|
// fills unstick it. Cleared automatically on the first clean batch.
|
|
4092
|
-
const consecutiveHolds = trackBoundaryHold(bot.manager,
|
|
4419
|
+
const consecutiveHolds = trackBoundaryHold(bot.manager, boundaryHeld, bot.manager.boundaryIdx, workingBoundary, refillHold.heldRefillSlotIds);
|
|
4093
4420
|
if (consecutiveHolds >= 3) {
|
|
4094
4421
|
bot.manager.logger.log(`[COW] Boundary held ${consecutiveHolds} consecutive batches ` +
|
|
4095
4422
|
`(keeping ${bot.manager.boundaryIdx} over planned ${workingBoundary}). ` +
|
|
@@ -4836,6 +5163,53 @@ function resolveOnGridPivot(manager, rawPrice) {
|
|
|
4836
5163
|
return { price, snapped: false, idx: null, nearestDrift: null };
|
|
4837
5164
|
}
|
|
4838
5165
|
}
|
|
5166
|
+
/**
|
|
5167
|
+
* Warn (once per batch) when a generic CREATE is emitted on the ADVERSE side of
|
|
5168
|
+
* the crossing floor — the guard the spread-correction planner applies through
|
|
5169
|
+
* `doesNotCrossMarket`.
|
|
5170
|
+
*
|
|
5171
|
+
* Non-blocking by design (see the call site): a crossing limit order executes at
|
|
5172
|
+
* the BEST available price, so the risk is taker fees and unintended immediate
|
|
5173
|
+
* execution, not a worse price. Blocking here would re-open the counter-order
|
|
5174
|
+
* deadlock — after a gap the counter lands on the better side by construction,
|
|
5175
|
+
* and a gapped market can put the planned level on the other side of the floor,
|
|
5176
|
+
* where waiting for the market to return is worse than taking it.
|
|
5177
|
+
*
|
|
5178
|
+
* The floor is a pure read of already-cached evidence (a fresh live market read
|
|
5179
|
+
* wins over the fill reference by recency), so this costs no chain call.
|
|
5180
|
+
*
|
|
5181
|
+
* @param {Object} bot
|
|
5182
|
+
* @param {unknown} price - Emitted CREATE price
|
|
5183
|
+
* @param {unknown} type - ORDER_TYPES.BUY/SELL
|
|
5184
|
+
* @param {unknown} slotId - Slot the CREATE targets (log context)
|
|
5185
|
+
* @returns {boolean} True when a warning was emitted (caller stops re-checking this batch)
|
|
5186
|
+
*/
|
|
5187
|
+
function warnCrossingCreate(bot, price, type, slotId) {
|
|
5188
|
+
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
5189
|
+
return false;
|
|
5190
|
+
const p = Number(price);
|
|
5191
|
+
if (!Number.isFinite(p) || p <= 0)
|
|
5192
|
+
return false;
|
|
5193
|
+
let floor = null;
|
|
5194
|
+
try {
|
|
5195
|
+
floor = resolveSpreadCrossingFloor(bot.manager);
|
|
5196
|
+
}
|
|
5197
|
+
catch {
|
|
5198
|
+
floor = null;
|
|
5199
|
+
}
|
|
5200
|
+
if (floor == null || !Number.isFinite(floor) || floor <= 0)
|
|
5201
|
+
return false;
|
|
5202
|
+
const crossing = type === ORDER_TYPES.BUY ? p >= floor : p <= floor;
|
|
5203
|
+
if (!crossing)
|
|
5204
|
+
return false;
|
|
5205
|
+
try {
|
|
5206
|
+
bot.manager?.logger?.log?.(`[COW-CROSS-GUARD] CREATE ${type} for ${String(slotId ?? 'unknown')} at ${Format.formatPrice6(p)} sits on the ` +
|
|
5207
|
+
`crossing side of the floor ${Format.formatPrice6(floor)} (the planner refuses these; a generic refill does not) — ` +
|
|
5208
|
+
`it executes at the best available price, so this is a taker-fee observation, not a veto. Once per batch.`, 'warn');
|
|
5209
|
+
}
|
|
5210
|
+
catch { /* logging is best-effort */ }
|
|
5211
|
+
return true;
|
|
5212
|
+
}
|
|
4839
5213
|
/**
|
|
4840
5214
|
* Run the last-fill guard probe: optionally refresh the pivot from
|
|
4841
5215
|
* still-queued fills, read the durable pivot, and evaluate
|
|
@@ -4853,13 +5227,12 @@ function resolveOnGridPivot(manager, rawPrice) {
|
|
|
4853
5227
|
* operations/opContexts as the filtered arrays.
|
|
4854
5228
|
* @param {Object} bot
|
|
4855
5229
|
* @param {number} price - Target order price
|
|
4856
|
-
* @param {number} size - Order size
|
|
4857
5230
|
* @param {string} type - ORDER_TYPES.BUY/SELL
|
|
4858
5231
|
* @param {Object} stats - lastFillGuardStats tracker (checked++ here)
|
|
4859
5232
|
* @param {boolean} [skipRefresh=false] - Skip the queued-fill pivot refresh
|
|
4860
5233
|
* @returns {{check: Object, refreshed: boolean}}
|
|
4861
5234
|
*/
|
|
4862
|
-
function runLastFillGuardCheck(bot, price,
|
|
5235
|
+
function runLastFillGuardCheck(bot, price, type, stats, skipRefresh = false) {
|
|
4863
5236
|
let refreshed = false;
|
|
4864
5237
|
// The batch-start freeze (see broadcast loop head) owns pivot refreshes;
|
|
4865
5238
|
// per-action refreshes are disabled so every action in a batch is judged
|
|
@@ -4876,7 +5249,6 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4876
5249
|
const lastRef = resolveLastFillGuardReference(bot.manager);
|
|
4877
5250
|
const lastPrice = lastRef.price;
|
|
4878
5251
|
const lastType = lastRef.type;
|
|
4879
|
-
const inc = resolveLastFillGuardIncrement(bot);
|
|
4880
5252
|
// Validate the pivot onto the ladder before use (see resolveOnGridPivot).
|
|
4881
5253
|
// Reported once per probe at warn when the raw pivot was NOT a grid level:
|
|
4882
5254
|
// that is the ratchet precondition, and it is otherwise invisible because
|
|
@@ -4908,7 +5280,7 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4908
5280
|
catch { /* logging is best-effort */ }
|
|
4909
5281
|
stats.pivotOffGrid = (stats.pivotOffGrid || 0) + 1;
|
|
4910
5282
|
}
|
|
4911
|
-
const check = isLastFillGuardBlocked(price,
|
|
5283
|
+
const check = isLastFillGuardBlocked(price, type, onGrid.price, lastType);
|
|
4912
5284
|
stats.checked++;
|
|
4913
5285
|
return { check, refreshed };
|
|
4914
5286
|
}
|
|
@@ -5025,11 +5397,24 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5025
5397
|
`changed=${pivotChanged} refreshed=${refreshed}`, 'debug');
|
|
5026
5398
|
}
|
|
5027
5399
|
catch { /* logging is best-effort */ }
|
|
5028
|
-
if (!pivotChanged)
|
|
5029
|
-
return { ...empty, refreshed };
|
|
5030
5400
|
// Pivot moved (or armed mid-batch): re-check every built op's FINAL
|
|
5031
5401
|
// price. Same bypass rules as the build loop; unjudgeable => KEEP.
|
|
5032
5402
|
const actions = (Array.isArray(opts.actions) ? opts.actions : []);
|
|
5403
|
+
// A stamped gap-evacuation can also go stale WITHOUT a pivot change:
|
|
5404
|
+
// a boundary commit can land between op-building and this gate. Do not
|
|
5405
|
+
// take the no-op fast path while any such stamp no longer matches the
|
|
5406
|
+
// LIVE geometry. The loop below drops it fail-closed.
|
|
5407
|
+
const hasStaleStampedEvac = actions.some((a) => {
|
|
5408
|
+
if (!a || a.origin !== COW_ORIGINS.GAP_EVACUATION)
|
|
5409
|
+
return false;
|
|
5410
|
+
if (!Number.isFinite(Format.toKnownNumber(a.evacBoundary))
|
|
5411
|
+
|| !Number.isFinite(Format.toKnownNumber(a.evacGapSlots)))
|
|
5412
|
+
return false;
|
|
5413
|
+
const evacType = a.order?.type ?? a.type;
|
|
5414
|
+
return !isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, a.id, a.newGridId, evacType);
|
|
5415
|
+
});
|
|
5416
|
+
if (!pivotChanged && !hasStaleStampedEvac)
|
|
5417
|
+
return { ...empty, refreshed };
|
|
5033
5418
|
const batchOrigin = opts.cowResult?.origin;
|
|
5034
5419
|
const actionBySlot = new Map();
|
|
5035
5420
|
for (const a of actions) {
|
|
@@ -5044,7 +5429,6 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5044
5429
|
}
|
|
5045
5430
|
const dropIdx = new Set();
|
|
5046
5431
|
const dropped = [];
|
|
5047
|
-
const inc = resolveLastFillGuardIncrement(bot);
|
|
5048
5432
|
const onGrid = resolveOnGridPivot(bot.manager, liveRef.price);
|
|
5049
5433
|
for (let i = 0; i < opContexts.length; i++) {
|
|
5050
5434
|
const ctx = opContexts[i];
|
|
@@ -5052,14 +5436,12 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5052
5436
|
continue;
|
|
5053
5437
|
let price = null;
|
|
5054
5438
|
let type = null;
|
|
5055
|
-
let size = null;
|
|
5056
5439
|
let slotId = null;
|
|
5057
5440
|
let action = null;
|
|
5058
5441
|
if (ctx.kind === 'create') {
|
|
5059
5442
|
slotId = ctx.id || ctx.order?.id || null;
|
|
5060
5443
|
price = Number(ctx.order?.price);
|
|
5061
5444
|
type = ctx.order?.type || null;
|
|
5062
|
-
size = Number(ctx.order?.size);
|
|
5063
5445
|
action = (slotId && actionBySlot.get(slotId)) || null;
|
|
5064
5446
|
// Spread-correction CREATE bypass (mirrors the build loop:
|
|
5065
5447
|
// per-action origin, batch origin as back-compat fallback).
|
|
@@ -5077,7 +5459,6 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5077
5459
|
slotId = rot.newGridId || rot.oldOrder?.id || null;
|
|
5078
5460
|
price = Number(rot.newPrice);
|
|
5079
5461
|
type = rot.type || null;
|
|
5080
|
-
size = Number(rot.newSize);
|
|
5081
5462
|
// Rotation UPDATEs are keyed by DESTINATION slot (the
|
|
5082
5463
|
// emitted price is the destination's level) — EXCEPT the
|
|
5083
5464
|
// same-slot size-only form (no newGridId, or newGridId ===
|
|
@@ -5121,8 +5502,35 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5121
5502
|
if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
|
|
5122
5503
|
&& Number.isFinite(Format.toKnownNumber(action?.evacBoundary))
|
|
5123
5504
|
&& Number.isFinite(Format.toKnownNumber(action?.evacGapSlots))) {
|
|
5505
|
+
// Stale-stamp backstop: the build loop already refuses a
|
|
5506
|
+
// stamp that no longer matches the LIVE geometry, but the
|
|
5507
|
+
// final gate must not re-grant the bypass if the boundary
|
|
5508
|
+
// moved after op-building. Drop when the source/dest
|
|
5509
|
+
// geometry is no longer valid (the normal guard only
|
|
5510
|
+
// checks price direction).
|
|
5511
|
+
const evacSrcId = rot.oldOrder?.id || null;
|
|
5512
|
+
const evacDestId = rot.newGridId || null;
|
|
5513
|
+
const evacStampLive = evacSrcId != null && evacDestId != null
|
|
5514
|
+
&& isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, evacSrcId, evacDestId, type);
|
|
5515
|
+
if (evacStampLive) {
|
|
5516
|
+
if (stats)
|
|
5517
|
+
stats.bypassed = (Number(stats.bypassed) || 0) + 1;
|
|
5518
|
+
continue;
|
|
5519
|
+
}
|
|
5520
|
+
// Geometry went stale after op-building (e.g. a boundary
|
|
5521
|
+
// commit landed mid-batch). Dropping is the only fail-closed
|
|
5522
|
+
// option: the normal guard below only checks the fill price,
|
|
5523
|
+
// so a non-violating stale move would still ship.
|
|
5524
|
+
dropIdx.add(i);
|
|
5124
5525
|
if (stats)
|
|
5125
|
-
stats.
|
|
5526
|
+
stats.skipped = (Number(stats.skipped) || 0) + 1;
|
|
5527
|
+
dropped.push({ index: i, kind: ctx.kind, slotId, price, type });
|
|
5528
|
+
try {
|
|
5529
|
+
bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate dropping stale gap-evacuation ` +
|
|
5530
|
+
`${ctx.kind} ${slotId ?? 'unknown'}: source/dest no longer evacuation ` +
|
|
5531
|
+
`geometry under live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}`, 'warn');
|
|
5532
|
+
}
|
|
5533
|
+
catch { /* logging is best-effort */ }
|
|
5126
5534
|
continue;
|
|
5127
5535
|
}
|
|
5128
5536
|
}
|
|
@@ -5135,7 +5543,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5135
5543
|
continue;
|
|
5136
5544
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
5137
5545
|
continue;
|
|
5138
|
-
const check = isLastFillGuardBlocked(price,
|
|
5546
|
+
const check = isLastFillGuardBlocked(price, type, onGrid.price, liveType);
|
|
5139
5547
|
if (stats)
|
|
5140
5548
|
stats.checked = (Number(stats.checked) || 0) + 1;
|
|
5141
5549
|
if (!check.blocked) {
|
|
@@ -5371,6 +5779,8 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5371
5779
|
const btsFeeData = getAssetFeesSafe('BTS');
|
|
5372
5780
|
let hadRotation = false;
|
|
5373
5781
|
let updateOperationCount = 0;
|
|
5782
|
+
let createOperationCount = 0;
|
|
5783
|
+
let rotationOperationCount = 0;
|
|
5374
5784
|
const updatesToApply = [];
|
|
5375
5785
|
for (let i = 0; i < opContexts.length; i++) {
|
|
5376
5786
|
const ctx = opContexts[i];
|
|
@@ -5398,6 +5808,7 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5398
5808
|
updateOperationCount++;
|
|
5399
5809
|
}
|
|
5400
5810
|
else if (ctx.kind === 'create') {
|
|
5811
|
+
createOperationCount++;
|
|
5401
5812
|
const chainOrderId = res && res[1];
|
|
5402
5813
|
if (chainOrderId) {
|
|
5403
5814
|
await bot.manager.synchronizeWithChain({
|
|
@@ -5436,6 +5847,7 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5436
5847
|
}
|
|
5437
5848
|
else if (ctx.kind === 'rotation') {
|
|
5438
5849
|
hadRotation = true;
|
|
5850
|
+
rotationOperationCount++;
|
|
5439
5851
|
const rotation = (ctx.rotation ?? {});
|
|
5440
5852
|
const oldOrder = rotation.oldOrder;
|
|
5441
5853
|
const newPrice = rotation.newPrice;
|
|
@@ -5505,10 +5917,16 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5505
5917
|
return {
|
|
5506
5918
|
executed: true,
|
|
5507
5919
|
hadRotation,
|
|
5508
|
-
updateOperationCount
|
|
5920
|
+
updateOperationCount,
|
|
5921
|
+
// Actions that reached post-broadcast processing (guards already
|
|
5922
|
+
// removed skipped ops). Callers that report "orders placed" must use
|
|
5923
|
+
// this instead of the plan's pre-guard action count.
|
|
5924
|
+
executedActionCount: opContexts.length,
|
|
5925
|
+
createOperationCount,
|
|
5926
|
+
rotationOperationCount
|
|
5509
5927
|
};
|
|
5510
5928
|
}
|
|
5511
|
-
export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
|
|
5929
|
+
export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, warnCrossingCreate, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
|
|
5512
5930
|
// Exported for regression tests (issue #23 sibling): the uncertain-broadcast
|
|
5513
5931
|
// discard path must never drop a placement silently when master lost the slot.
|
|
5514
5932
|
export { restoreDiscardedCreates };
|