dexbot 1.6.17 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -0
- package/README.md +24 -18
- package/analysis/README.md +105 -12
- 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/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 +325 -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/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/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 +523 -0
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
- package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
- package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
- package/dist/analysis/liquidity/liquidity_view.js +55 -0
- package/dist/analysis/math_utils.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +1 -1
- package/dist/analysis/trade_profitability.js +2 -1
- package/dist/analysis/tradingview/analyze_tradingview.js +2 -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/dexbot.js +74 -169
- 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/asset_lookup.d.ts +25 -0
- package/dist/modules/asset_lookup.js +75 -0
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- 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.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 +475 -47
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_fill_runtime.js +20 -0
- package/dist/modules/dexbot_maintenance_runtime.js +71 -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_entry.d.ts +21 -1
- package/dist/modules/launcher/runtime_entry.js +36 -1
- package/dist/modules/launcher/runtime_mode.d.ts +4 -3
- package/dist/modules/liquidity_pool_ref.d.ts +32 -0
- package/dist/modules/liquidity_pool_ref.js +116 -0
- 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 +269 -61
- package/dist/modules/order/grid_reconcile.js +27 -2
- package/dist/modules/order/grid_reconcile_internal.js +94 -15
- package/dist/modules/order/index.d.ts +24 -4
- package/dist/modules/order/manager.d.ts +12 -0
- package/dist/modules/order/manager.js +44 -11
- package/dist/modules/order/strategy.js +22 -2
- package/dist/modules/order/sync_engine.d.ts +32 -1
- package/dist/modules/order/sync_engine.js +209 -26
- package/dist/modules/order/utils/math.d.ts +26 -10
- package/dist/modules/order/utils/math.js +54 -14
- package/dist/modules/order/utils/order.d.ts +158 -11
- package/dist/modules/order/utils/order.js +434 -21
- package/dist/modules/order/utils/system.d.ts +136 -30
- package/dist/modules/order/utils/system.js +465 -63
- package/dist/modules/order/utils/validate.d.ts +1 -0
- package/dist/modules/order/utils/validate.js +37 -3
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +14 -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-orders.js +2 -1
- 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 +52 -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/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/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +21 -11
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
- package/docs/GRID_PRICE_INVARIANT.md +28 -5
- package/docs/GRID_RECONCILE.md +25 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +37 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +3 -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 +23 -15
- package/package.json +6 -3
- package/scripts/README.md +23 -7
|
@@ -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;
|
|
@@ -1777,15 +1777,22 @@ function recordRestampBuyAboveAnchor(bot, price, type) {
|
|
|
1777
1777
|
try {
|
|
1778
1778
|
if (type !== ORDER_TYPES.BUY)
|
|
1779
1779
|
return false;
|
|
1780
|
-
|
|
1780
|
+
// ONE reference, the same one the guard judges against: the raw live
|
|
1781
|
+
// fields miss the market-row fallback (a rebuild) and would still count
|
|
1782
|
+
// against an expired pivot that no longer gates anything.
|
|
1783
|
+
const reference = resolveLastFillGuardReference(bot?.manager);
|
|
1784
|
+
if (reference.type !== ORDER_TYPES.BUY)
|
|
1781
1785
|
return false;
|
|
1782
|
-
const pivot = Number(
|
|
1786
|
+
const pivot = Number(reference.price);
|
|
1783
1787
|
const p = Number(price);
|
|
1784
1788
|
if (!Number.isFinite(pivot) || pivot <= 0 || !Number.isFinite(p) || p <= 0)
|
|
1785
1789
|
return false;
|
|
1786
1790
|
// At or above the pivot is the re-stamp shape; a lower BUY is the
|
|
1787
|
-
// legitimate rotation target (I3) and is not counted.
|
|
1788
|
-
|
|
1791
|
+
// legitimate rotation target (I3) and is not counted. SAME LEVEL counts
|
|
1792
|
+
// too: a slot level and its execution price differ by rounding (slot
|
|
1793
|
+
// 1310.046339 filled at 1310.060435), so a bare `p < pivot` misses
|
|
1794
|
+
// exactly the shape this counter exists to expose.
|
|
1795
|
+
if (p < pivot && !math.pricesWithinHalfStep(p, pivot, bot?.manager?.config?.incrementPercent))
|
|
1789
1796
|
return false;
|
|
1790
1797
|
if (bot._metrics)
|
|
1791
1798
|
bot._metrics.restampBuyAboveAnchorCount = (bot._metrics.restampBuyAboveAnchorCount || 0) + 1;
|
|
@@ -1945,19 +1952,13 @@ function refreshLastFillPivotFromQueue(bot) {
|
|
|
1945
1952
|
const orderId = fillOp?.order_id || fill?.orderId;
|
|
1946
1953
|
let type = null;
|
|
1947
1954
|
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) {
|
|
1955
|
+
// FILL ECONOMICS FIRST: the pays/receives amounts are the trade
|
|
1956
|
+
// fact. The grid slot is only an identity hint — after a
|
|
1957
|
+
// refused-commit adoption it can still be keyed at an old
|
|
1958
|
+
// generation price (live incident: slot-118 @1267 for an order
|
|
1959
|
+
// that traded at 1345.73), and preferring the slot price made the
|
|
1960
|
+
// last-fill pivot / re-anchor judge a market that never traded.
|
|
1961
|
+
if (fillOp?.pays && fillOp?.receives && assets?.assetA && assets?.assetB) {
|
|
1961
1962
|
try {
|
|
1962
1963
|
const pays = fillOp.pays;
|
|
1963
1964
|
const receives = fillOp.receives;
|
|
@@ -1978,6 +1979,17 @@ function refreshLastFillPivotFromQueue(bot) {
|
|
|
1978
1979
|
}
|
|
1979
1980
|
catch { /* best-effort */ }
|
|
1980
1981
|
}
|
|
1982
|
+
// Fall back to the grid slot only when the fill amounts are absent
|
|
1983
|
+
// (a limit fill normally executes at its slot price).
|
|
1984
|
+
if ((type == null || price == null)) {
|
|
1985
|
+
const slot = findSlotByOrderId(orderId);
|
|
1986
|
+
if (slot && (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)) {
|
|
1987
|
+
type = slot.type;
|
|
1988
|
+
const slotPrice = Number(slot.price);
|
|
1989
|
+
if (Number.isFinite(slotPrice) && slotPrice > 0)
|
|
1990
|
+
price = slotPrice;
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1981
1993
|
if ((type === ORDER_TYPES.BUY || type === ORDER_TYPES.SELL)
|
|
1982
1994
|
&& Number.isFinite(price) && price > 0) {
|
|
1983
1995
|
latest = { price: price, type };
|
|
@@ -2500,6 +2512,265 @@ function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUp
|
|
|
2500
2512
|
heldRefillSlotIds
|
|
2501
2513
|
};
|
|
2502
2514
|
}
|
|
2515
|
+
/**
|
|
2516
|
+
* Derive the boundary the actual rails imply.
|
|
2517
|
+
*
|
|
2518
|
+
* `boundary` is a claim about where the BUY rail ends and the gap band begins;
|
|
2519
|
+
* live orders are the fact. A fill-driven plan built at a re-anchored boundary
|
|
2520
|
+
* places COUNTER orders above the committed boundary (SELL fill at slot s =>
|
|
2521
|
+
* counter BUY at s - gapSlots). If the refill hold then keeps the old boundary,
|
|
2522
|
+
* those counters sit inside the implied band; the next plan sees the old
|
|
2523
|
+
* geometry and places a SELL on top of them, collapsing the spread (live
|
|
2524
|
+
* incident: a sweep's counters at 1329.7-1345.7 were reclassified as in-band by
|
|
2525
|
+
* a hold to 133, then sells were rotated to 1345.728664 — the exact price of
|
|
2526
|
+
* the buy that had just filled).
|
|
2527
|
+
*
|
|
2528
|
+
* Rails are clamped by construction:
|
|
2529
|
+
*
|
|
2530
|
+
* maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1
|
|
2531
|
+
*
|
|
2532
|
+
* Counter orders therefore win over empty refill holes: a held boundary may
|
|
2533
|
+
* never strand a placed counter. When the plan did not place an order on the
|
|
2534
|
+
* promoted rail (the normal refill-hold case) `maxBuyIdx` stays at/below the
|
|
2535
|
+
* committed boundary and the hold is preserved unchanged.
|
|
2536
|
+
*
|
|
2537
|
+
* @param manager - OrderManager (master grid rails)
|
|
2538
|
+
* @param opContexts - Kept op contexts of the batch (post guard/final gate)
|
|
2539
|
+
* @param desiredBoundary - Plan boundary (falls back to the committed one)
|
|
2540
|
+
* @param gapSlots - Gap band width
|
|
2541
|
+
* @returns Boundary implied by the rails, or null when no rail geometry is
|
|
2542
|
+
* usable / the rails already cross (caller keeps the current value).
|
|
2543
|
+
*/
|
|
2544
|
+
export function deriveRailBoundary(manager, opContexts, desiredBoundary, gapSlots) {
|
|
2545
|
+
let rawGap = Format.toKnownNumber(gapSlots);
|
|
2546
|
+
if (!Number.isFinite(rawGap)) {
|
|
2547
|
+
// Fall back to the genesis gap width before giving up: a restored
|
|
2548
|
+
// manager can briefly hold a null _gapSlots while the genesis is set.
|
|
2549
|
+
rawGap = Format.toKnownNumber(manager?._genesis?.gapSlots);
|
|
2550
|
+
}
|
|
2551
|
+
if (!Number.isFinite(rawGap) || rawGap < 0) {
|
|
2552
|
+
return { boundary: null, maxBuyIdx: null, minSellIdx: null, clamped: false, reason: 'no-gap' };
|
|
2553
|
+
}
|
|
2554
|
+
const gap = Math.floor(rawGap);
|
|
2555
|
+
const isSide = (t) => t === ORDER_TYPES.BUY || t === ORDER_TYPES.SELL;
|
|
2556
|
+
// Base first: the proximity window below is measured from it.
|
|
2557
|
+
const desired = Format.toKnownNumber(desiredBoundary);
|
|
2558
|
+
const committed = Format.toKnownNumber(manager?.boundaryIdx);
|
|
2559
|
+
const gates = manager;
|
|
2560
|
+
const coreBuy = Number(gates.config?.coreOrders?.buy);
|
|
2561
|
+
const coreSell = Number(gates.config?.coreOrders?.sell);
|
|
2562
|
+
const windowSize = Math.max(1, Number.isFinite(coreBuy) ? coreBuy : 1, Number.isFinite(coreSell) ? coreSell : 1);
|
|
2563
|
+
// STRAY RULE: a MASTER rail order only speaks for this batch if it sits on
|
|
2564
|
+
// its own side of the planned boundary — a BUY at/below it, a SELL at/above
|
|
2565
|
+
// the implied sellStart. Anything else is a rail-typed order parked in the
|
|
2566
|
+
// wrong zone (a refused-commit adoption at an old generation level, a
|
|
2567
|
+
// SPREAD-GUARD stray, a stranded hold) and letting it clamp the boundary
|
|
2568
|
+
// would SELF-LEGALIZE the corrupt state (live class: one live sell 18 slots
|
|
2569
|
+
// below clamped 138 -> 115 and re-typed the whole window).
|
|
2570
|
+
// Ops of THIS batch are always counted: a counter order is the rail fact.
|
|
2571
|
+
const baseForProximity = Number.isFinite(desired) ? Number(desired) : (Number.isFinite(committed) ? Number(committed) : null);
|
|
2572
|
+
// Kept for the report line: how many window slots this grid claims per side
|
|
2573
|
+
// (informational; the stray rule needs no window size).
|
|
2574
|
+
const proximityWindow = windowSize + gap + 1;
|
|
2575
|
+
// Start from the live master rails, then apply the kept ops as a delta.
|
|
2576
|
+
// This is the post-batch rail set: cancels remove, creates add, rotations
|
|
2577
|
+
// move (source -> destination), size updates stay.
|
|
2578
|
+
// Rail index per entry is the LIVE ladder position where known (a slot id
|
|
2579
|
+
// can be stale after a refused-commit adoption — same rule the fill, gap
|
|
2580
|
+
// and crossing paths already use), with the slot id as fallback.
|
|
2581
|
+
const rails = new Map();
|
|
2582
|
+
const vacatedSlotIds = new Set();
|
|
2583
|
+
const master = manager?.orders;
|
|
2584
|
+
let maxSlotIdx = null;
|
|
2585
|
+
if (master instanceof Map) {
|
|
2586
|
+
for (const raw of master.values()) {
|
|
2587
|
+
const o = raw;
|
|
2588
|
+
if (!o || !o.id)
|
|
2589
|
+
continue;
|
|
2590
|
+
const parsed = parseSlotIndex(o.id);
|
|
2591
|
+
if (parsed !== null && parsed !== undefined && Number.isFinite(Number(parsed))) {
|
|
2592
|
+
maxSlotIdx = maxSlotIdx === null ? Number(parsed) : Math.max(maxSlotIdx, Number(parsed));
|
|
2593
|
+
}
|
|
2594
|
+
if (!o.orderId || (o.state !== ORDER_STATES.ACTIVE && o.state !== ORDER_STATES.PARTIAL))
|
|
2595
|
+
continue;
|
|
2596
|
+
if (!isSide(o.type))
|
|
2597
|
+
continue;
|
|
2598
|
+
const live = orderUtils.resolveLiveOrderLadderPosition(o, manager?.assets, manager?._genesis);
|
|
2599
|
+
const idx = live.idx !== null && Number.isFinite(Number(live.idx)) ? Number(live.idx) : null;
|
|
2600
|
+
rails.set(String(o.id), { side: o.type, idx, byOp: false });
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
if (opContexts && typeof opContexts[Symbol.iterator] === 'function') {
|
|
2604
|
+
for (const raw of opContexts) {
|
|
2605
|
+
const ctx = raw;
|
|
2606
|
+
if (!ctx)
|
|
2607
|
+
continue;
|
|
2608
|
+
if (ctx.kind === 'cancel') {
|
|
2609
|
+
const id = ctx.order?.id;
|
|
2610
|
+
if (id != null) {
|
|
2611
|
+
rails.delete(String(id));
|
|
2612
|
+
vacatedSlotIds.add(String(id));
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
else if (ctx.kind === 'create') {
|
|
2616
|
+
const id = ctx.id;
|
|
2617
|
+
const side = ctx.order?.type;
|
|
2618
|
+
if (id != null) {
|
|
2619
|
+
const parsedId = parseSlotIndex(String(id));
|
|
2620
|
+
if (parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId))) {
|
|
2621
|
+
maxSlotIdx = maxSlotIdx === null ? Number(parsedId) : Math.max(maxSlotIdx, Number(parsedId));
|
|
2622
|
+
}
|
|
2623
|
+
if (isSide(side)) {
|
|
2624
|
+
rails.set(String(id), {
|
|
2625
|
+
side,
|
|
2626
|
+
idx: parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId)) ? Number(parsedId) : null,
|
|
2627
|
+
byOp: true
|
|
2628
|
+
});
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
else if (ctx.kind === 'rotation') {
|
|
2633
|
+
const rotation = ctx.rotation;
|
|
2634
|
+
const oldId = rotation?.oldOrder?.id;
|
|
2635
|
+
const newId = rotation?.newGridId;
|
|
2636
|
+
const side = rotation?.type;
|
|
2637
|
+
if (oldId != null) {
|
|
2638
|
+
rails.delete(String(oldId));
|
|
2639
|
+
vacatedSlotIds.add(String(oldId));
|
|
2640
|
+
}
|
|
2641
|
+
if (newId != null) {
|
|
2642
|
+
const parsedId = parseSlotIndex(String(newId));
|
|
2643
|
+
if (parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId))) {
|
|
2644
|
+
maxSlotIdx = maxSlotIdx === null ? Number(parsedId) : Math.max(maxSlotIdx, Number(parsedId));
|
|
2645
|
+
}
|
|
2646
|
+
if (isSide(side)) {
|
|
2647
|
+
rails.set(String(newId), {
|
|
2648
|
+
side,
|
|
2649
|
+
idx: parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId)) ? Number(parsedId) : null,
|
|
2650
|
+
byOp: true
|
|
2651
|
+
});
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
else if (ctx.kind === 'size-update') {
|
|
2656
|
+
const o = ctx.updateInfo?.partialOrder;
|
|
2657
|
+
if (o?.id != null && isSide(o.type)) {
|
|
2658
|
+
const parsedId = parseSlotIndex(String(o.id));
|
|
2659
|
+
rails.set(String(o.id), {
|
|
2660
|
+
side: o.type,
|
|
2661
|
+
idx: parsedId !== null && parsedId !== undefined && Number.isFinite(Number(parsedId)) ? Number(parsedId) : null,
|
|
2662
|
+
byOp: true
|
|
2663
|
+
});
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
let maxBuyIdx = null;
|
|
2669
|
+
let minSellIdx = null;
|
|
2670
|
+
let ignoredStrays = 0;
|
|
2671
|
+
const sellStartForStray = baseForProximity !== null ? baseForProximity + gap + 1 : null;
|
|
2672
|
+
for (const [, rail] of rails) {
|
|
2673
|
+
const idx = rail.idx;
|
|
2674
|
+
if (idx === null || !Number.isFinite(idx))
|
|
2675
|
+
continue;
|
|
2676
|
+
if (!rail.byOp && baseForProximity !== null) {
|
|
2677
|
+
const stray = rail.side === ORDER_TYPES.BUY
|
|
2678
|
+
? idx > baseForProximity
|
|
2679
|
+
: (sellStartForStray !== null && idx < sellStartForStray);
|
|
2680
|
+
if (stray) {
|
|
2681
|
+
ignoredStrays++;
|
|
2682
|
+
continue;
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
if (rail.side === ORDER_TYPES.BUY)
|
|
2686
|
+
maxBuyIdx = maxBuyIdx === null ? idx : Math.max(maxBuyIdx, idx);
|
|
2687
|
+
else
|
|
2688
|
+
minSellIdx = minSellIdx === null ? idx : Math.min(minSellIdx, idx);
|
|
2689
|
+
}
|
|
2690
|
+
if (maxBuyIdx === null && minSellIdx === null) {
|
|
2691
|
+
return { boundary: null, maxBuyIdx: null, minSellIdx: null, clamped: false, reason: 'no-rails' };
|
|
2692
|
+
}
|
|
2693
|
+
// A live BUY at b needs boundary >= b; a live SELL at s needs
|
|
2694
|
+
// boundary <= s - gap - 1. An empty interval means the rails already
|
|
2695
|
+
// overlap (pre-existing crossed book): do not legalize it here.
|
|
2696
|
+
const upper = minSellIdx === null ? Infinity : minSellIdx - gap - 1;
|
|
2697
|
+
if (maxBuyIdx !== null && maxBuyIdx > upper) {
|
|
2698
|
+
return {
|
|
2699
|
+
boundary: null,
|
|
2700
|
+
maxBuyIdx,
|
|
2701
|
+
minSellIdx,
|
|
2702
|
+
clamped: false,
|
|
2703
|
+
reason: `rail-crossed maxBuy=${maxBuyIdx} > minSell-gap-1=${upper}`
|
|
2704
|
+
};
|
|
2705
|
+
}
|
|
2706
|
+
let base = baseForProximity;
|
|
2707
|
+
if (base === null) {
|
|
2708
|
+
base = maxBuyIdx !== null ? maxBuyIdx : (Number.isFinite(upper) ? upper : 0);
|
|
2709
|
+
}
|
|
2710
|
+
// Grid ceiling: the SELL rail must fit (sellStart <= last slot). A
|
|
2711
|
+
// destination slot in this batch can extend the observed maximum.
|
|
2712
|
+
const gridCeiling = maxSlotIdx !== null && maxSlotIdx - gap - 1 >= 0
|
|
2713
|
+
? maxSlotIdx - gap - 1
|
|
2714
|
+
: null;
|
|
2715
|
+
const allowedUpper = Number.isFinite(upper)
|
|
2716
|
+
? (gridCeiling === null ? upper : Math.min(upper, gridCeiling))
|
|
2717
|
+
: gridCeiling;
|
|
2718
|
+
if (maxBuyIdx !== null && allowedUpper !== null && maxBuyIdx > allowedUpper) {
|
|
2719
|
+
return {
|
|
2720
|
+
boundary: null,
|
|
2721
|
+
maxBuyIdx,
|
|
2722
|
+
minSellIdx,
|
|
2723
|
+
clamped: false,
|
|
2724
|
+
reason: `rail-exceeds-grid maxBuy=${maxBuyIdx} > ceiling=${allowedUpper}`
|
|
2725
|
+
};
|
|
2726
|
+
}
|
|
2727
|
+
let next = base;
|
|
2728
|
+
if (allowedUpper !== null)
|
|
2729
|
+
next = Math.min(next, allowedUpper);
|
|
2730
|
+
if (maxBuyIdx !== null)
|
|
2731
|
+
next = Math.max(next, maxBuyIdx);
|
|
2732
|
+
next = Math.max(0, next);
|
|
2733
|
+
// FINAL GATE — the SAME validator the restore and commit paths use
|
|
2734
|
+
// (validatePersistedBoundary), so the rail clamp can never legalize a
|
|
2735
|
+
// boundary that strands a live order inside the implied band. Slots this
|
|
2736
|
+
// batch vacates (cancels / rotation sources) are allow-listed: they will
|
|
2737
|
+
// not be placed after the batch, so judging them as stranding would refuse
|
|
2738
|
+
// every legitimate evacuation clamp.
|
|
2739
|
+
//
|
|
2740
|
+
// Dense-ladder condition: validateBoundaryCommit derives its sell-rail
|
|
2741
|
+
// ceiling from the SORTED ARRAY LENGTH (`slots.length - 1`), which only
|
|
2742
|
+
// equals the grid ceiling when the master map holds every slot 0..N-1 (the
|
|
2743
|
+
// production invariant). A sparse/partial map would make the gate reject
|
|
2744
|
+
// every candidate as out-of-range, so it is skipped there — the clamp
|
|
2745
|
+
// inequalities above stay the authority in that state.
|
|
2746
|
+
{
|
|
2747
|
+
const slotsForGate = master instanceof Map ? Array.from(master.values()) : [];
|
|
2748
|
+
const dense = slotsForGate.length > 0
|
|
2749
|
+
&& maxSlotIdx !== null
|
|
2750
|
+
&& Number(maxSlotIdx) === slotsForGate.length - 1;
|
|
2751
|
+
if (dense) {
|
|
2752
|
+
const check = math.validatePersistedBoundary(next, slotsForGate, gap, vacatedSlotIds.size > 0 ? { allowInBandSlotIds: vacatedSlotIds } : undefined);
|
|
2753
|
+
if (!check || check.ok !== true) {
|
|
2754
|
+
return {
|
|
2755
|
+
boundary: null,
|
|
2756
|
+
maxBuyIdx,
|
|
2757
|
+
minSellIdx,
|
|
2758
|
+
clamped: false,
|
|
2759
|
+
reason: `unsafe: ${check?.reason ?? 'unknown'}${check?.detail ? ` (${check.detail})` : ''}`
|
|
2760
|
+
};
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
return {
|
|
2765
|
+
boundary: next,
|
|
2766
|
+
maxBuyIdx,
|
|
2767
|
+
minSellIdx,
|
|
2768
|
+
clamped: next !== base,
|
|
2769
|
+
...(next !== base
|
|
2770
|
+
? { reason: `rail-clamped maxBuy=${maxBuyIdx ?? 'none'} minSell=${minSellIdx ?? 'none'}${ignoredStrays > 0 ? ` (${ignoredStrays} stray rail order(s) ignored)` : ''}` }
|
|
2771
|
+
: (ignoredStrays > 0 ? { reason: `rail-steady (${ignoredStrays} stray rail order(s) ignored; window=${proximityWindow})` } : {}))
|
|
2772
|
+
};
|
|
2773
|
+
}
|
|
2503
2774
|
/**
|
|
2504
2775
|
* Track consecutive boundary-hold batches on the manager (ops visibility).
|
|
2505
2776
|
*
|
|
@@ -2823,6 +3094,9 @@ async function runPreBroadcastGuards(bot, cowResult) {
|
|
|
2823
3094
|
case 'create_price_invalid':
|
|
2824
3095
|
reason = `broadcast price is not a finite number`;
|
|
2825
3096
|
break;
|
|
3097
|
+
case 'slot_create_uncertain':
|
|
3098
|
+
reason = `an earlier CREATE here has an unknown outcome (createUncertain)`;
|
|
3099
|
+
break;
|
|
2826
3100
|
default:
|
|
2827
3101
|
reason = `existing orderId=${violation.currentOrderId}`;
|
|
2828
3102
|
}
|
|
@@ -3270,6 +3544,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3270
3544
|
// would spam big batches, so the guard emits one batch summary instead
|
|
3271
3545
|
// (see the summary after the action loop below).
|
|
3272
3546
|
const lastFillGuardStats = { checked: 0, passed: 0, skipped: 0, bypassed: 0, pivotOffGrid: 0 };
|
|
3547
|
+
// One crossing-CREATE observation per batch (see warnCrossingCreate).
|
|
3548
|
+
let crossingCreateWarned = false;
|
|
3273
3549
|
// Fingerprints of the pending-broadcast entries recorded by THIS batch's
|
|
3274
3550
|
// op-building (both CREATE paths). The final pivot gate's compaction
|
|
3275
3551
|
// remaps these entries' stored opIndex/ctxIndex to their post-drop
|
|
@@ -3455,7 +3731,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3455
3731
|
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
3456
3732
|
&& isSpreadCorrectionBypassAllowed(bot);
|
|
3457
3733
|
if (!isCorrectionCreate) {
|
|
3458
|
-
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.
|
|
3734
|
+
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.type, lastFillGuardStats, true);
|
|
3459
3735
|
if (refreshed)
|
|
3460
3736
|
lastFillGuardPivotRefreshed = true;
|
|
3461
3737
|
if (check.blocked) {
|
|
@@ -3473,6 +3749,20 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3473
3749
|
}
|
|
3474
3750
|
}
|
|
3475
3751
|
catch (_e) { /* guard is best-effort */ }
|
|
3752
|
+
// PLANNER/EXECUTION ASYMMETRY (observability only).
|
|
3753
|
+
// The spread-correction planner refuses a candidate that
|
|
3754
|
+
// crosses the live-market/fill floor (doesNotCrossMarket);
|
|
3755
|
+
// this generic CREATE path (reconcile refills, rotation
|
|
3756
|
+
// fallbacks) has no such gate — deliberately, because a hard
|
|
3757
|
+
// veto here would re-open the counter-order deadlock: after
|
|
3758
|
+
// a gap the counter lands on the better side of the market
|
|
3759
|
+
// by construction, and a gapped market can put the planned
|
|
3760
|
+
// level on the other side, where it executes at the BEST
|
|
3761
|
+
// available price (a taker fill, never a worse price).
|
|
3762
|
+
// So this is a fee/liquidity observation, not a safety veto.
|
|
3763
|
+
if (!crossingCreateWarned) {
|
|
3764
|
+
crossingCreateWarned = warnCrossingCreate(bot, createPrice, order.type, order.id);
|
|
3765
|
+
}
|
|
3476
3766
|
const args = buildCreateOrderArgs(effectiveOrder, assetA, assetB);
|
|
3477
3767
|
// GRID-PRICE-INVARIANT (blocking): the CREATE price must be
|
|
3478
3768
|
// the genesis level for this slot. A mismatch means state
|
|
@@ -3642,7 +3932,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3642
3932
|
if (!stampValid) {
|
|
3643
3933
|
stampUsable = false;
|
|
3644
3934
|
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} —
|
|
3935
|
+
`boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} — refusing the stale plan`, 'warn');
|
|
3646
3936
|
}
|
|
3647
3937
|
}
|
|
3648
3938
|
if (stampUsable) {
|
|
@@ -3701,31 +3991,53 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3701
3991
|
catch {
|
|
3702
3992
|
sidePrecision = null;
|
|
3703
3993
|
}
|
|
3704
|
-
// Geometry re-proof under the LIVE boundary
|
|
3705
|
-
//
|
|
3706
|
-
//
|
|
3707
|
-
//
|
|
3708
|
-
//
|
|
3709
|
-
|
|
3994
|
+
// Geometry re-proof under the LIVE boundary. A stale
|
|
3995
|
+
// evacuation must NOT fall through to the direction-only
|
|
3996
|
+
// last-fill guard: that guard only checks the fill price,
|
|
3997
|
+
// not whether the move still makes grid sense. Live
|
|
3998
|
+
// incident 2026-10-30: a plan built at boundary 124
|
|
3999
|
+
// wanted to evacuate buys 125-128; by execution the
|
|
4000
|
+
// boundary was 128 and those orders were valid in-rail.
|
|
4001
|
+
// The stale probe was rejected, the normal guard then
|
|
4002
|
+
// allowed the four lower buys, and the grid lost its
|
|
4003
|
+
// bid edge (spread 1.51% -> 2.74%). Fail closed: skip
|
|
4004
|
+
// the op and let the next plan/reconcile re-evaluate.
|
|
4005
|
+
// Non-finite live geometry keeps plan-build authority
|
|
4006
|
+
// (isEvacuationStampStillValid returns true there).
|
|
4007
|
+
let staleSkipReason = null;
|
|
4008
|
+
if (!isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, action.id, action.newGridId, orderType)) {
|
|
4009
|
+
staleSkipReason = `source/dest no longer evacuation geometry under live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}`;
|
|
4010
|
+
}
|
|
4011
|
+
else {
|
|
3710
4012
|
const evacCheck = isEvacuationRotationAllowed(oldPrice, oldSize, newPrice, newSize, orderType, sidePrecision);
|
|
3711
4013
|
if (evacCheck.allowed) {
|
|
3712
4014
|
bypassedEvacuation = true;
|
|
3713
4015
|
bot.manager.logger.log(`[LAST-FILL-GUARD] Allowing ${orderType} evacuation UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ` +
|
|
3714
4016
|
`${evacCheck.reason} (probed live: ${Format.formatPrice6(oldPrice)} -> ${Format.formatPrice6(newPrice)})`, 'warn');
|
|
3715
4017
|
}
|
|
4018
|
+
else {
|
|
4019
|
+
staleSkipReason = evacCheck.reason;
|
|
4020
|
+
}
|
|
3716
4021
|
}
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
4022
|
+
if (!bypassedEvacuation) {
|
|
4023
|
+
lastFillGuardStats.checked++;
|
|
4024
|
+
lastFillGuardStats.skipped++;
|
|
4025
|
+
skippedUpdateCount++;
|
|
4026
|
+
if (action.id)
|
|
4027
|
+
skippedUpdateSlotIds.add(action.id);
|
|
4028
|
+
if (action.newGridId)
|
|
4029
|
+
skippedUpdateSlotIds.add(action.newGridId);
|
|
4030
|
+
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId}: ` +
|
|
4031
|
+
`stale gap-evacuation (${staleSkipReason ?? 'not violation-reducing'}) — next plan re-evaluates`, 'warn');
|
|
4032
|
+
continue;
|
|
3720
4033
|
}
|
|
3721
|
-
// Not allowed: fall through to the normal guard below.
|
|
3722
4034
|
}
|
|
3723
4035
|
}
|
|
3724
4036
|
if (bypassedEvacuation) {
|
|
3725
4037
|
lastFillGuardStats.bypassed++;
|
|
3726
4038
|
}
|
|
3727
4039
|
else {
|
|
3728
|
-
const { check, refreshed } = runLastFillGuardCheck(bot, newPrice,
|
|
4040
|
+
const { check, refreshed } = runLastFillGuardCheck(bot, newPrice, orderType, lastFillGuardStats, true);
|
|
3729
4041
|
if (refreshed)
|
|
3730
4042
|
lastFillGuardPivotRefreshed = true;
|
|
3731
4043
|
if (check.blocked) {
|
|
@@ -3873,7 +4185,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3873
4185
|
// so it obeys the same guard against the frozen
|
|
3874
4186
|
// batch pivot — no origin bypass, same as rotations.
|
|
3875
4187
|
try {
|
|
3876
|
-
const { check: fbCheck, refreshed: fbRefreshed } = runLastFillGuardCheck(bot, fbPrice,
|
|
4188
|
+
const { check: fbCheck, refreshed: fbRefreshed } = runLastFillGuardCheck(bot, fbPrice, fbType, lastFillGuardStats, true);
|
|
3877
4189
|
if (fbRefreshed)
|
|
3878
4190
|
lastFillGuardPivotRefreshed = true;
|
|
3879
4191
|
if (fbCheck.blocked) {
|
|
@@ -4086,10 +4398,35 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4086
4398
|
bot.manager.logger.log(`[COW] Boundary hold: ${refillHold.heldRefillSlotIds.length} refill slot(s) skipped ` +
|
|
4087
4399
|
`(${refillHold.heldRefillSlotIds.join(', ')}) — keeping ${bot.manager.boundaryIdx} over planned ${workingBoundary}`, 'warn');
|
|
4088
4400
|
}
|
|
4401
|
+
// RAIL-DERIVED BOUNDARY: the committed boundary must match the rails the
|
|
4402
|
+
// batch actually places. A fill-driven plan built at a re-anchored
|
|
4403
|
+
// boundary puts counter orders on the promoted rail (SELL fill at s ->
|
|
4404
|
+
// counter BUY at s-gap); holding the old boundary would reclassify those
|
|
4405
|
+
// counters as in-band and the next plan would place sells on top of them
|
|
4406
|
+
// (spread collapse). Counter orders win over empty refill holes: clamp
|
|
4407
|
+
// to [maxBuy, minSell-gap-1]. In the pure-refill-hold case no order was
|
|
4408
|
+
// placed above the committed boundary, so this is a no-op.
|
|
4409
|
+
const railBoundary = deriveRailBoundary(bot.manager, opContexts, effectiveBoundary, bot.manager?._gapSlots);
|
|
4410
|
+
if (railBoundary.boundary !== null && Number.isFinite(Number(railBoundary.boundary))) {
|
|
4411
|
+
const railEffective = Number(railBoundary.boundary);
|
|
4412
|
+
if (railEffective !== effectiveBoundary) {
|
|
4413
|
+
bot.manager.logger.log(`[COW] Boundary rail-derived: planned ${workingBoundary}, held ${effectiveBoundary} -> ${railEffective} ` +
|
|
4414
|
+
`(maxBuy=${railBoundary.maxBuyIdx ?? 'none'}, minSell=${railBoundary.minSellIdx ?? 'none'}) ` +
|
|
4415
|
+
`— keeping placed counter orders on their rails`, 'warn');
|
|
4416
|
+
effectiveBoundary = railEffective;
|
|
4417
|
+
}
|
|
4418
|
+
}
|
|
4419
|
+
else if (railBoundary.reason) {
|
|
4420
|
+
bot.manager.logger.log(`[COW] Boundary rail-derived: unusable (${railBoundary.reason}); keeping ${effectiveBoundary}`, 'warn');
|
|
4421
|
+
}
|
|
4422
|
+
// Commit bookkeeping follows the boundary actually committed: a plan
|
|
4423
|
+
// whose target equals the effective value applied its crawls even when
|
|
4424
|
+
// the refill hold triggered (the counters carried the shift).
|
|
4425
|
+
boundaryHeld = effectiveBoundary !== workingBoundary;
|
|
4089
4426
|
// Consecutive-hold tracking (INV-COW-007 visibility): escalate a
|
|
4090
4427
|
// growing run — the grid is trailing the market and only fresh
|
|
4091
4428
|
// fills unstick it. Cleared automatically on the first clean batch.
|
|
4092
|
-
const consecutiveHolds = trackBoundaryHold(bot.manager,
|
|
4429
|
+
const consecutiveHolds = trackBoundaryHold(bot.manager, boundaryHeld, bot.manager.boundaryIdx, workingBoundary, refillHold.heldRefillSlotIds);
|
|
4093
4430
|
if (consecutiveHolds >= 3) {
|
|
4094
4431
|
bot.manager.logger.log(`[COW] Boundary held ${consecutiveHolds} consecutive batches ` +
|
|
4095
4432
|
`(keeping ${bot.manager.boundaryIdx} over planned ${workingBoundary}). ` +
|
|
@@ -4836,6 +5173,53 @@ function resolveOnGridPivot(manager, rawPrice) {
|
|
|
4836
5173
|
return { price, snapped: false, idx: null, nearestDrift: null };
|
|
4837
5174
|
}
|
|
4838
5175
|
}
|
|
5176
|
+
/**
|
|
5177
|
+
* Warn (once per batch) when a generic CREATE is emitted on the ADVERSE side of
|
|
5178
|
+
* the crossing floor — the guard the spread-correction planner applies through
|
|
5179
|
+
* `doesNotCrossMarket`.
|
|
5180
|
+
*
|
|
5181
|
+
* Non-blocking by design (see the call site): a crossing limit order executes at
|
|
5182
|
+
* the BEST available price, so the risk is taker fees and unintended immediate
|
|
5183
|
+
* execution, not a worse price. Blocking here would re-open the counter-order
|
|
5184
|
+
* deadlock — after a gap the counter lands on the better side by construction,
|
|
5185
|
+
* and a gapped market can put the planned level on the other side of the floor,
|
|
5186
|
+
* where waiting for the market to return is worse than taking it.
|
|
5187
|
+
*
|
|
5188
|
+
* The floor is a pure read of already-cached evidence (a fresh live market read
|
|
5189
|
+
* wins over the fill reference by recency), so this costs no chain call.
|
|
5190
|
+
*
|
|
5191
|
+
* @param {Object} bot
|
|
5192
|
+
* @param {unknown} price - Emitted CREATE price
|
|
5193
|
+
* @param {unknown} type - ORDER_TYPES.BUY/SELL
|
|
5194
|
+
* @param {unknown} slotId - Slot the CREATE targets (log context)
|
|
5195
|
+
* @returns {boolean} True when a warning was emitted (caller stops re-checking this batch)
|
|
5196
|
+
*/
|
|
5197
|
+
function warnCrossingCreate(bot, price, type, slotId) {
|
|
5198
|
+
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
5199
|
+
return false;
|
|
5200
|
+
const p = Number(price);
|
|
5201
|
+
if (!Number.isFinite(p) || p <= 0)
|
|
5202
|
+
return false;
|
|
5203
|
+
let floor = null;
|
|
5204
|
+
try {
|
|
5205
|
+
floor = resolveSpreadCrossingFloor(bot.manager);
|
|
5206
|
+
}
|
|
5207
|
+
catch {
|
|
5208
|
+
floor = null;
|
|
5209
|
+
}
|
|
5210
|
+
if (floor == null || !Number.isFinite(floor) || floor <= 0)
|
|
5211
|
+
return false;
|
|
5212
|
+
const crossing = type === ORDER_TYPES.BUY ? p >= floor : p <= floor;
|
|
5213
|
+
if (!crossing)
|
|
5214
|
+
return false;
|
|
5215
|
+
try {
|
|
5216
|
+
bot.manager?.logger?.log?.(`[COW-CROSS-GUARD] CREATE ${type} for ${String(slotId ?? 'unknown')} at ${Format.formatPrice6(p)} sits on the ` +
|
|
5217
|
+
`crossing side of the floor ${Format.formatPrice6(floor)} (the planner refuses these; a generic refill does not) — ` +
|
|
5218
|
+
`it executes at the best available price, so this is a taker-fee observation, not a veto. Once per batch.`, 'warn');
|
|
5219
|
+
}
|
|
5220
|
+
catch { /* logging is best-effort */ }
|
|
5221
|
+
return true;
|
|
5222
|
+
}
|
|
4839
5223
|
/**
|
|
4840
5224
|
* Run the last-fill guard probe: optionally refresh the pivot from
|
|
4841
5225
|
* still-queued fills, read the durable pivot, and evaluate
|
|
@@ -4853,13 +5237,12 @@ function resolveOnGridPivot(manager, rawPrice) {
|
|
|
4853
5237
|
* operations/opContexts as the filtered arrays.
|
|
4854
5238
|
* @param {Object} bot
|
|
4855
5239
|
* @param {number} price - Target order price
|
|
4856
|
-
* @param {number} size - Order size
|
|
4857
5240
|
* @param {string} type - ORDER_TYPES.BUY/SELL
|
|
4858
5241
|
* @param {Object} stats - lastFillGuardStats tracker (checked++ here)
|
|
4859
5242
|
* @param {boolean} [skipRefresh=false] - Skip the queued-fill pivot refresh
|
|
4860
5243
|
* @returns {{check: Object, refreshed: boolean}}
|
|
4861
5244
|
*/
|
|
4862
|
-
function runLastFillGuardCheck(bot, price,
|
|
5245
|
+
function runLastFillGuardCheck(bot, price, type, stats, skipRefresh = false) {
|
|
4863
5246
|
let refreshed = false;
|
|
4864
5247
|
// The batch-start freeze (see broadcast loop head) owns pivot refreshes;
|
|
4865
5248
|
// per-action refreshes are disabled so every action in a batch is judged
|
|
@@ -4876,7 +5259,6 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4876
5259
|
const lastRef = resolveLastFillGuardReference(bot.manager);
|
|
4877
5260
|
const lastPrice = lastRef.price;
|
|
4878
5261
|
const lastType = lastRef.type;
|
|
4879
|
-
const inc = resolveLastFillGuardIncrement(bot);
|
|
4880
5262
|
// Validate the pivot onto the ladder before use (see resolveOnGridPivot).
|
|
4881
5263
|
// Reported once per probe at warn when the raw pivot was NOT a grid level:
|
|
4882
5264
|
// that is the ratchet precondition, and it is otherwise invisible because
|
|
@@ -4908,7 +5290,7 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4908
5290
|
catch { /* logging is best-effort */ }
|
|
4909
5291
|
stats.pivotOffGrid = (stats.pivotOffGrid || 0) + 1;
|
|
4910
5292
|
}
|
|
4911
|
-
const check = isLastFillGuardBlocked(price,
|
|
5293
|
+
const check = isLastFillGuardBlocked(price, type, onGrid.price, lastType);
|
|
4912
5294
|
stats.checked++;
|
|
4913
5295
|
return { check, refreshed };
|
|
4914
5296
|
}
|
|
@@ -5025,11 +5407,24 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5025
5407
|
`changed=${pivotChanged} refreshed=${refreshed}`, 'debug');
|
|
5026
5408
|
}
|
|
5027
5409
|
catch { /* logging is best-effort */ }
|
|
5028
|
-
if (!pivotChanged)
|
|
5029
|
-
return { ...empty, refreshed };
|
|
5030
5410
|
// Pivot moved (or armed mid-batch): re-check every built op's FINAL
|
|
5031
5411
|
// price. Same bypass rules as the build loop; unjudgeable => KEEP.
|
|
5032
5412
|
const actions = (Array.isArray(opts.actions) ? opts.actions : []);
|
|
5413
|
+
// A stamped gap-evacuation can also go stale WITHOUT a pivot change:
|
|
5414
|
+
// a boundary commit can land between op-building and this gate. Do not
|
|
5415
|
+
// take the no-op fast path while any such stamp no longer matches the
|
|
5416
|
+
// LIVE geometry. The loop below drops it fail-closed.
|
|
5417
|
+
const hasStaleStampedEvac = actions.some((a) => {
|
|
5418
|
+
if (!a || a.origin !== COW_ORIGINS.GAP_EVACUATION)
|
|
5419
|
+
return false;
|
|
5420
|
+
if (!Number.isFinite(Format.toKnownNumber(a.evacBoundary))
|
|
5421
|
+
|| !Number.isFinite(Format.toKnownNumber(a.evacGapSlots)))
|
|
5422
|
+
return false;
|
|
5423
|
+
const evacType = a.order?.type ?? a.type;
|
|
5424
|
+
return !isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, a.id, a.newGridId, evacType);
|
|
5425
|
+
});
|
|
5426
|
+
if (!pivotChanged && !hasStaleStampedEvac)
|
|
5427
|
+
return { ...empty, refreshed };
|
|
5033
5428
|
const batchOrigin = opts.cowResult?.origin;
|
|
5034
5429
|
const actionBySlot = new Map();
|
|
5035
5430
|
for (const a of actions) {
|
|
@@ -5044,7 +5439,6 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5044
5439
|
}
|
|
5045
5440
|
const dropIdx = new Set();
|
|
5046
5441
|
const dropped = [];
|
|
5047
|
-
const inc = resolveLastFillGuardIncrement(bot);
|
|
5048
5442
|
const onGrid = resolveOnGridPivot(bot.manager, liveRef.price);
|
|
5049
5443
|
for (let i = 0; i < opContexts.length; i++) {
|
|
5050
5444
|
const ctx = opContexts[i];
|
|
@@ -5052,14 +5446,12 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5052
5446
|
continue;
|
|
5053
5447
|
let price = null;
|
|
5054
5448
|
let type = null;
|
|
5055
|
-
let size = null;
|
|
5056
5449
|
let slotId = null;
|
|
5057
5450
|
let action = null;
|
|
5058
5451
|
if (ctx.kind === 'create') {
|
|
5059
5452
|
slotId = ctx.id || ctx.order?.id || null;
|
|
5060
5453
|
price = Number(ctx.order?.price);
|
|
5061
5454
|
type = ctx.order?.type || null;
|
|
5062
|
-
size = Number(ctx.order?.size);
|
|
5063
5455
|
action = (slotId && actionBySlot.get(slotId)) || null;
|
|
5064
5456
|
// Spread-correction CREATE bypass (mirrors the build loop:
|
|
5065
5457
|
// per-action origin, batch origin as back-compat fallback).
|
|
@@ -5077,7 +5469,6 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5077
5469
|
slotId = rot.newGridId || rot.oldOrder?.id || null;
|
|
5078
5470
|
price = Number(rot.newPrice);
|
|
5079
5471
|
type = rot.type || null;
|
|
5080
|
-
size = Number(rot.newSize);
|
|
5081
5472
|
// Rotation UPDATEs are keyed by DESTINATION slot (the
|
|
5082
5473
|
// emitted price is the destination's level) — EXCEPT the
|
|
5083
5474
|
// same-slot size-only form (no newGridId, or newGridId ===
|
|
@@ -5121,8 +5512,35 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5121
5512
|
if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
|
|
5122
5513
|
&& Number.isFinite(Format.toKnownNumber(action?.evacBoundary))
|
|
5123
5514
|
&& Number.isFinite(Format.toKnownNumber(action?.evacGapSlots))) {
|
|
5515
|
+
// Stale-stamp backstop: the build loop already refuses a
|
|
5516
|
+
// stamp that no longer matches the LIVE geometry, but the
|
|
5517
|
+
// final gate must not re-grant the bypass if the boundary
|
|
5518
|
+
// moved after op-building. Drop when the source/dest
|
|
5519
|
+
// geometry is no longer valid (the normal guard only
|
|
5520
|
+
// checks price direction).
|
|
5521
|
+
const evacSrcId = rot.oldOrder?.id || null;
|
|
5522
|
+
const evacDestId = rot.newGridId || null;
|
|
5523
|
+
const evacStampLive = evacSrcId != null && evacDestId != null
|
|
5524
|
+
&& isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, evacSrcId, evacDestId, type);
|
|
5525
|
+
if (evacStampLive) {
|
|
5526
|
+
if (stats)
|
|
5527
|
+
stats.bypassed = (Number(stats.bypassed) || 0) + 1;
|
|
5528
|
+
continue;
|
|
5529
|
+
}
|
|
5530
|
+
// Geometry went stale after op-building (e.g. a boundary
|
|
5531
|
+
// commit landed mid-batch). Dropping is the only fail-closed
|
|
5532
|
+
// option: the normal guard below only checks the fill price,
|
|
5533
|
+
// so a non-violating stale move would still ship.
|
|
5534
|
+
dropIdx.add(i);
|
|
5124
5535
|
if (stats)
|
|
5125
|
-
stats.
|
|
5536
|
+
stats.skipped = (Number(stats.skipped) || 0) + 1;
|
|
5537
|
+
dropped.push({ index: i, kind: ctx.kind, slotId, price, type });
|
|
5538
|
+
try {
|
|
5539
|
+
bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate dropping stale gap-evacuation ` +
|
|
5540
|
+
`${ctx.kind} ${slotId ?? 'unknown'}: source/dest no longer evacuation ` +
|
|
5541
|
+
`geometry under live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}`, 'warn');
|
|
5542
|
+
}
|
|
5543
|
+
catch { /* logging is best-effort */ }
|
|
5126
5544
|
continue;
|
|
5127
5545
|
}
|
|
5128
5546
|
}
|
|
@@ -5135,7 +5553,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5135
5553
|
continue;
|
|
5136
5554
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
5137
5555
|
continue;
|
|
5138
|
-
const check = isLastFillGuardBlocked(price,
|
|
5556
|
+
const check = isLastFillGuardBlocked(price, type, onGrid.price, liveType);
|
|
5139
5557
|
if (stats)
|
|
5140
5558
|
stats.checked = (Number(stats.checked) || 0) + 1;
|
|
5141
5559
|
if (!check.blocked) {
|
|
@@ -5371,6 +5789,8 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5371
5789
|
const btsFeeData = getAssetFeesSafe('BTS');
|
|
5372
5790
|
let hadRotation = false;
|
|
5373
5791
|
let updateOperationCount = 0;
|
|
5792
|
+
let createOperationCount = 0;
|
|
5793
|
+
let rotationOperationCount = 0;
|
|
5374
5794
|
const updatesToApply = [];
|
|
5375
5795
|
for (let i = 0; i < opContexts.length; i++) {
|
|
5376
5796
|
const ctx = opContexts[i];
|
|
@@ -5398,6 +5818,7 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5398
5818
|
updateOperationCount++;
|
|
5399
5819
|
}
|
|
5400
5820
|
else if (ctx.kind === 'create') {
|
|
5821
|
+
createOperationCount++;
|
|
5401
5822
|
const chainOrderId = res && res[1];
|
|
5402
5823
|
if (chainOrderId) {
|
|
5403
5824
|
await bot.manager.synchronizeWithChain({
|
|
@@ -5436,6 +5857,7 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5436
5857
|
}
|
|
5437
5858
|
else if (ctx.kind === 'rotation') {
|
|
5438
5859
|
hadRotation = true;
|
|
5860
|
+
rotationOperationCount++;
|
|
5439
5861
|
const rotation = (ctx.rotation ?? {});
|
|
5440
5862
|
const oldOrder = rotation.oldOrder;
|
|
5441
5863
|
const newPrice = rotation.newPrice;
|
|
@@ -5505,10 +5927,16 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5505
5927
|
return {
|
|
5506
5928
|
executed: true,
|
|
5507
5929
|
hadRotation,
|
|
5508
|
-
updateOperationCount
|
|
5930
|
+
updateOperationCount,
|
|
5931
|
+
// Actions that reached post-broadcast processing (guards already
|
|
5932
|
+
// removed skipped ops). Callers that report "orders placed" must use
|
|
5933
|
+
// this instead of the plan's pre-guard action count.
|
|
5934
|
+
executedActionCount: opContexts.length,
|
|
5935
|
+
createOperationCount,
|
|
5936
|
+
rotationOperationCount
|
|
5509
5937
|
};
|
|
5510
5938
|
}
|
|
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 };
|
|
5939
|
+
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
5940
|
// Exported for regression tests (issue #23 sibling): the uncertain-broadcast
|
|
5513
5941
|
// discard path must never drop a placement silently when master lost the slot.
|
|
5514
5942
|
export { restoreDiscardedCreates };
|