dexbot 1.6.16 → 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 +58 -0
- package/analysis/README.md +10 -9
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +3 -3
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
- 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/grid_reset_sim.js +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
- 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/account_bots.d.ts +3 -0
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/chain_keys.d.ts +1 -1
- package/dist/modules/constants.d.ts +6 -0
- package/dist/modules/constants.js +37 -6
- package/dist/modules/credit_pricing.d.ts +20 -1
- package/dist/modules/credit_pricing.js +23 -1
- package/dist/modules/credit_runtime.js +33 -16
- package/dist/modules/dexbot_class.d.ts +11 -1
- package/dist/modules/dexbot_class.js +15 -2
- package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
- package/dist/modules/dexbot_cow_runtime.js +507 -108
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +117 -12
- 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/credential_daemon.d.ts +14 -2
- package/dist/modules/launcher/credential_daemon.js +60 -26
- 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 +26 -14
- package/dist/modules/order/grid.js +416 -73
- 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 +22 -1
- package/dist/modules/order/manager.d.ts +40 -7
- package/dist/modules/order/manager.js +149 -23
- package/dist/modules/order/strategy.d.ts +5 -0
- package/dist/modules/order/strategy.js +44 -3
- 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 +49 -10
- package/dist/modules/order/utils/math.js +71 -14
- package/dist/modules/order/utils/order.d.ts +65 -11
- package/dist/modules/order/utils/order.js +198 -28
- package/dist/modules/order/utils/system.d.ts +112 -2
- package/dist/modules/order/utils/system.js +338 -12
- package/dist/modules/order/utils/validate.d.ts +4 -1
- package/dist/modules/order/utils/validate.js +9 -2
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +44 -2
- package/dist/scripts/analyze-credit.js +64 -23
- package/dist/scripts/bts_distribution.d.ts +66 -0
- package/dist/scripts/bts_distribution.js +2102 -0
- package/dist/scripts/token_distribution.d.ts +45 -0
- package/dist/scripts/token_distribution.js +1870 -0
- package/dist/unlock.js +42 -24
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +24 -8
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
- package/docs/GRID_PRICE_INVARIANT.md +29 -3
- package/docs/GRID_RECALCULATION.md +3 -3
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +22 -0
- package/docs/MPA_CREDIT_USAGE.md +3 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
- package/docs/README.md +1 -1
- package/docs/architecture.md +205 -6
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +11 -6
- package/modules/README.md +18 -14
- package/package.json +6 -3
- package/scripts/README.md +85 -148
|
@@ -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 } 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;
|
|
@@ -1861,65 +1861,24 @@ function collectGapBandPlacementShadowSlots(actions, boundary, gapSlots) {
|
|
|
1861
1861
|
return [];
|
|
1862
1862
|
}
|
|
1863
1863
|
}
|
|
1864
|
-
/**
|
|
1865
|
-
* LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
|
|
1866
|
-
* last fill @x with increment i (blocked shapes): BUY > x*(1 - i/2/100),
|
|
1867
|
-
* SELL < x*(1 + i/2/100)
|
|
1868
|
-
* e.g. x=1000, i=0.5% => BUY > 997.5 and SELL < 1002.5 are blocked
|
|
1869
|
-
* Cold (pivot null or lastType null) => disabled. Spread-correction CREATES
|
|
1870
|
-
* bypass per-action (see broadcast sites); gap-evacuation rotation UPDATEs
|
|
1871
|
-
* bypass only via the violation-reducing allowance (origin='gap-evacuation',
|
|
1872
|
-
* UPDATE-only, frozen B-stamp or live-proven isEvacuationRotationAllowed) —
|
|
1873
|
-
* see the UPDATE rotation guard block.
|
|
1874
|
-
* The pivot is the latest fill of either side and is never expired: it stays
|
|
1875
|
-
* the durable mark (last sold level floors new sells; buy fills pull it down
|
|
1876
|
-
* and re-open the sell side, buy-below-sell is never gated).
|
|
1877
|
-
* @param {number} price - Target order price
|
|
1878
|
-
* @param {number} size - Order size (unused, kept for compat)
|
|
1879
|
-
* @param {string} type - ORDER_TYPES.BUY/SELL
|
|
1880
|
-
* @param {number|null} lastPrice - Most recent fill price
|
|
1881
|
-
* @param {string|null} lastType - Most recent fill side (BUY/SELL)
|
|
1882
|
-
* @param {number|any} incrementPercent - Grid increment percent (e.g. 0.5). If assets object passed, falls back to default.
|
|
1883
|
-
* @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
|
|
1884
|
-
*/
|
|
1885
|
-
function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, incrementPercent) {
|
|
1886
|
-
const numPrice = Number(price);
|
|
1887
|
-
if (!Number.isFinite(numPrice))
|
|
1888
|
-
return { blocked: false, pivot: null };
|
|
1889
|
-
if (lastPrice == null || !Number.isFinite(Number(lastPrice)) || lastType == null)
|
|
1890
|
-
return { blocked: false, pivot: null };
|
|
1891
|
-
const pivot = Number(lastPrice);
|
|
1892
|
-
// Resolve increment: fallback to default 0.5 (also covers legacy assets-object 6th arg)
|
|
1893
|
-
let inc = Number(incrementPercent);
|
|
1894
|
-
if (!Number.isFinite(inc) || inc <= 0) {
|
|
1895
|
-
inc = Number(constantsModule?.DEFAULT_CONFIG?.incrementPercent ?? 0.5);
|
|
1896
|
-
}
|
|
1897
|
-
if (!Number.isFinite(inc) || inc <= 0)
|
|
1898
|
-
return { blocked: false, pivot: null };
|
|
1899
|
-
const halfInc = inc / 2;
|
|
1900
|
-
const halfPct = halfInc / 100;
|
|
1901
|
-
const buyThreshold = pivot * (1 - halfPct);
|
|
1902
|
-
const sellThreshold = pivot * (1 + halfPct);
|
|
1903
|
-
if (type === ORDER_TYPES.BUY && numPrice > buyThreshold)
|
|
1904
|
-
return { blocked: true, pivot, halfInc, threshold: buyThreshold };
|
|
1905
|
-
if (type === ORDER_TYPES.SELL && numPrice < sellThreshold)
|
|
1906
|
-
return { blocked: true, pivot, halfInc, threshold: sellThreshold };
|
|
1907
|
-
return { blocked: false, pivot: null, halfInc, threshold: null };
|
|
1908
|
-
}
|
|
1909
1864
|
/**
|
|
1910
1865
|
* Whether a spread-correction CREATE may bypass the LAST-FILL-GUARD.
|
|
1911
1866
|
*
|
|
1912
|
-
*
|
|
1913
|
-
*
|
|
1914
|
-
*
|
|
1867
|
+
* Remaining purpose: the STARTUP BOOK SEED proxy. Before the first real fill a
|
|
1868
|
+
* single-sided book arms the guard on our own resting quote (max bid / min
|
|
1869
|
+
* ask) — a proxy that `b14a1fc8` deliberately keeps non-persistent ("a book
|
|
1870
|
+
* seed never fossilizes into the snapshot as market truth") because it goes
|
|
1871
|
+
* wrong whenever the book is not adjacent to the last fill. Blocking a
|
|
1872
|
+
* tightening placement against that proxy would be arbitrary, so the correction
|
|
1873
|
+
* is released from it while the local snapshot can be trusted.
|
|
1874
|
+
*
|
|
1875
|
+
* A real FILL reference always denies the bypass. Since the planner now filters
|
|
1876
|
+
* candidates with the SAME predicate the guard applies, planner-built
|
|
1877
|
+
* corrections never even propose an op that would need it — the bypass is a
|
|
1878
|
+
* proxy-case valve, not a licence to trade through the last real fill.
|
|
1915
1879
|
*
|
|
1916
|
-
*
|
|
1917
|
-
*
|
|
1918
|
-
* issue-#31 adverse fill.
|
|
1919
|
-
* 2. A cold/book pivot is a heuristic (book seed) or absent, so the historical
|
|
1920
|
-
* fail-open bypass is kept — but only while the LOCAL snapshot is fresh.
|
|
1921
|
-
* A stale snapshot (known-unmatched chain orders, or an old sync) can hide
|
|
1922
|
-
* the real window edge, so the bypass is withheld and the guard applies.
|
|
1880
|
+
* Denied too when the snapshot is stale or has known-unmatched chain orders
|
|
1881
|
+
* (a stale edge can hide the real window edge), fail-closed on a gate throw.
|
|
1923
1882
|
*
|
|
1924
1883
|
* Exported for tests.
|
|
1925
1884
|
* @param {Object} bot
|
|
@@ -1986,19 +1945,13 @@ function refreshLastFillPivotFromQueue(bot) {
|
|
|
1986
1945
|
const orderId = fillOp?.order_id || fill?.orderId;
|
|
1987
1946
|
let type = null;
|
|
1988
1947
|
let price = null;
|
|
1989
|
-
//
|
|
1990
|
-
//
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
price = slotPrice;
|
|
1997
|
-
}
|
|
1998
|
-
// Fall back to fill economics (B/A convention, mirroring
|
|
1999
|
-
// _computeFillContext's pays-asset side resolution, including
|
|
2000
|
-
// SPREAD slots carrying on-chain orders).
|
|
2001
|
-
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) {
|
|
2002
1955
|
try {
|
|
2003
1956
|
const pays = fillOp.pays;
|
|
2004
1957
|
const receives = fillOp.receives;
|
|
@@ -2019,6 +1972,17 @@ function refreshLastFillPivotFromQueue(bot) {
|
|
|
2019
1972
|
}
|
|
2020
1973
|
catch { /* best-effort */ }
|
|
2021
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
|
+
}
|
|
2022
1986
|
if ((type === ORDER_TYPES.BUY || type === ORDER_TYPES.SELL)
|
|
2023
1987
|
&& Number.isFinite(price) && price > 0) {
|
|
2024
1988
|
latest = { price: price, type };
|
|
@@ -2311,13 +2275,25 @@ function buildCowResultFromPlan(bot, plan) {
|
|
|
2311
2275
|
const refillSlotIds = Array.isArray(plan?.refillSlotIds)
|
|
2312
2276
|
? plan.refillSlotIds.filter((id) => typeof id === 'string' && id.length > 0)
|
|
2313
2277
|
: undefined;
|
|
2278
|
+
// Crawl-ledger wire: exactly which owed records this plan's derivation
|
|
2279
|
+
// folded (see CowResult.consumedCrawlIds). Absent/non-array => undefined,
|
|
2280
|
+
// which the commit reads as "clear nothing" rather than "clear all".
|
|
2281
|
+
const consumedCrawlIds = Array.isArray(plan?.consumedCrawlIds)
|
|
2282
|
+
? plan.consumedCrawlIds
|
|
2283
|
+
.filter((e) => {
|
|
2284
|
+
const rec = e;
|
|
2285
|
+
return !!rec && typeof rec.slotId === 'string' && rec.slotId.length > 0
|
|
2286
|
+
&& typeof rec.side === 'string' && rec.side.length > 0;
|
|
2287
|
+
})
|
|
2288
|
+
: undefined;
|
|
2314
2289
|
return {
|
|
2315
2290
|
workingGrid,
|
|
2316
2291
|
workingIndexes: workingGrid.getIndexes(),
|
|
2317
2292
|
workingBoundary: workingBoundary,
|
|
2318
2293
|
actions,
|
|
2319
2294
|
origin: plan.origin,
|
|
2320
|
-
...(refillSlotIds !== undefined ? { refillSlotIds } : {})
|
|
2295
|
+
...(refillSlotIds !== undefined ? { refillSlotIds } : {}),
|
|
2296
|
+
...(consumedCrawlIds !== undefined ? { consumedCrawlIds } : {})
|
|
2321
2297
|
};
|
|
2322
2298
|
}
|
|
2323
2299
|
/**
|
|
@@ -2529,6 +2505,265 @@ function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUp
|
|
|
2529
2505
|
heldRefillSlotIds
|
|
2530
2506
|
};
|
|
2531
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
|
+
}
|
|
2532
2767
|
/**
|
|
2533
2768
|
* Track consecutive boundary-hold batches on the manager (ops visibility).
|
|
2534
2769
|
*
|
|
@@ -3299,6 +3534,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3299
3534
|
// would spam big batches, so the guard emits one batch summary instead
|
|
3300
3535
|
// (see the summary after the action loop below).
|
|
3301
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;
|
|
3302
3539
|
// Fingerprints of the pending-broadcast entries recorded by THIS batch's
|
|
3303
3540
|
// op-building (both CREATE paths). The final pivot gate's compaction
|
|
3304
3541
|
// remaps these entries' stored opIndex/ctxIndex to their post-drop
|
|
@@ -3473,7 +3710,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3473
3710
|
skippedCreateSlotIds.add(order.id);
|
|
3474
3711
|
continue;
|
|
3475
3712
|
}
|
|
3476
|
-
// LAST-FILL PRICE GUARD:
|
|
3713
|
+
// LAST-FILL PRICE GUARD: direction rule (BUY < pivot, SELL > pivot).
|
|
3477
3714
|
// Bypass is per-action: only spread-correction CREATES skip so gap repair can close.
|
|
3478
3715
|
// The batch-level origin is honored only for actions without their own origin stamp
|
|
3479
3716
|
// (back-compat for plans that bypass buildActionsFromPlan). Cold (null) => disabled.
|
|
@@ -3484,13 +3721,13 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3484
3721
|
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
3485
3722
|
&& isSpreadCorrectionBypassAllowed(bot);
|
|
3486
3723
|
if (!isCorrectionCreate) {
|
|
3487
|
-
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.
|
|
3724
|
+
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.type, lastFillGuardStats, true);
|
|
3488
3725
|
if (refreshed)
|
|
3489
3726
|
lastFillGuardPivotRefreshed = true;
|
|
3490
3727
|
if (check.blocked) {
|
|
3491
3728
|
lastFillGuardStats.skipped++;
|
|
3492
3729
|
const dir = order.type === ORDER_TYPES.BUY ? 'above' : 'below';
|
|
3493
|
-
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (
|
|
3730
|
+
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (direction rule: BUY must be below / SELL above the last fill); re-planned after market moves`, 'debug');
|
|
3494
3731
|
if (order.id)
|
|
3495
3732
|
skippedCreateSlotIds.add(order.id);
|
|
3496
3733
|
continue;
|
|
@@ -3502,6 +3739,20 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3502
3739
|
}
|
|
3503
3740
|
}
|
|
3504
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
|
+
}
|
|
3505
3756
|
const args = buildCreateOrderArgs(effectiveOrder, assetA, assetB);
|
|
3506
3757
|
// GRID-PRICE-INVARIANT (blocking): the CREATE price must be
|
|
3507
3758
|
// the genesis level for this slot. A mismatch means state
|
|
@@ -3630,7 +3881,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3630
3881
|
`${crossedOrderLabel(crossedOrder)}; re-planned after its cancel confirms.`, 'warn');
|
|
3631
3882
|
continue;
|
|
3632
3883
|
}
|
|
3633
|
-
// LAST-FILL PRICE GUARD (UPDATE rotation):
|
|
3884
|
+
// LAST-FILL PRICE GUARD (UPDATE rotation): direction rule — same as CREATE,
|
|
3634
3885
|
// plus the GAP-EVACUATION ALLOWANCE (violation-reducing): a rotation stamped
|
|
3635
3886
|
// origin='gap-evacuation' at plan-build moves a live order OUT of the gap band
|
|
3636
3887
|
// onto its rail with bit-exact non-growing size — it shrinks the violation
|
|
@@ -3671,7 +3922,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3671
3922
|
if (!stampValid) {
|
|
3672
3923
|
stampUsable = false;
|
|
3673
3924
|
bot.manager.logger.log(`[LAST-FILL-GUARD] Stamped evacuation for ${action.id} -> ${action.newGridId} is stale under live ` +
|
|
3674
|
-
`boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} —
|
|
3925
|
+
`boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} — refusing the stale plan`, 'warn');
|
|
3675
3926
|
}
|
|
3676
3927
|
}
|
|
3677
3928
|
if (stampUsable) {
|
|
@@ -3730,31 +3981,53 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3730
3981
|
catch {
|
|
3731
3982
|
sidePrecision = null;
|
|
3732
3983
|
}
|
|
3733
|
-
// Geometry re-proof under the LIVE boundary
|
|
3734
|
-
//
|
|
3735
|
-
//
|
|
3736
|
-
//
|
|
3737
|
-
//
|
|
3738
|
-
|
|
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 {
|
|
3739
4002
|
const evacCheck = isEvacuationRotationAllowed(oldPrice, oldSize, newPrice, newSize, orderType, sidePrecision);
|
|
3740
4003
|
if (evacCheck.allowed) {
|
|
3741
4004
|
bypassedEvacuation = true;
|
|
3742
4005
|
bot.manager.logger.log(`[LAST-FILL-GUARD] Allowing ${orderType} evacuation UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ` +
|
|
3743
4006
|
`${evacCheck.reason} (probed live: ${Format.formatPrice6(oldPrice)} -> ${Format.formatPrice6(newPrice)})`, 'warn');
|
|
3744
4007
|
}
|
|
4008
|
+
else {
|
|
4009
|
+
staleSkipReason = evacCheck.reason;
|
|
4010
|
+
}
|
|
3745
4011
|
}
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
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;
|
|
3749
4023
|
}
|
|
3750
|
-
// Not allowed: fall through to the normal guard below.
|
|
3751
4024
|
}
|
|
3752
4025
|
}
|
|
3753
4026
|
if (bypassedEvacuation) {
|
|
3754
4027
|
lastFillGuardStats.bypassed++;
|
|
3755
4028
|
}
|
|
3756
4029
|
else {
|
|
3757
|
-
const { check, refreshed } = runLastFillGuardCheck(bot, newPrice,
|
|
4030
|
+
const { check, refreshed } = runLastFillGuardCheck(bot, newPrice, orderType, lastFillGuardStats, true);
|
|
3758
4031
|
if (refreshed)
|
|
3759
4032
|
lastFillGuardPivotRefreshed = true;
|
|
3760
4033
|
if (check.blocked) {
|
|
@@ -3765,7 +4038,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3765
4038
|
if (action.newGridId)
|
|
3766
4039
|
skippedUpdateSlotIds.add(action.newGridId);
|
|
3767
4040
|
const dir = orderType === ORDER_TYPES.BUY ? 'above' : 'below';
|
|
3768
|
-
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (
|
|
4041
|
+
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (direction rule: BUY must be below / SELL above the last fill)`, 'debug');
|
|
3769
4042
|
continue;
|
|
3770
4043
|
}
|
|
3771
4044
|
lastFillGuardStats.passed++;
|
|
@@ -3902,7 +4175,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3902
4175
|
// so it obeys the same guard against the frozen
|
|
3903
4176
|
// batch pivot — no origin bypass, same as rotations.
|
|
3904
4177
|
try {
|
|
3905
|
-
const { check: fbCheck, refreshed: fbRefreshed } = runLastFillGuardCheck(bot, fbPrice,
|
|
4178
|
+
const { check: fbCheck, refreshed: fbRefreshed } = runLastFillGuardCheck(bot, fbPrice, fbType, lastFillGuardStats, true);
|
|
3906
4179
|
if (fbRefreshed)
|
|
3907
4180
|
lastFillGuardPivotRefreshed = true;
|
|
3908
4181
|
if (fbCheck.blocked) {
|
|
@@ -3910,8 +4183,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3910
4183
|
const fbDir = fbType === ORDER_TYPES.BUY ? 'above' : 'below';
|
|
3911
4184
|
bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping CREATE fallback for ${targetSlotId} at ` +
|
|
3912
4185
|
`${Format.formatPrice6(fbPrice)}: ${fbDir} last filled ` +
|
|
3913
|
-
`${Format.formatPrice6(Number(fbCheck.pivot))} (
|
|
3914
|
-
|
|
4186
|
+
`${Format.formatPrice6(Number(fbCheck.pivot))} (direction rule: BUY must be ` +
|
|
4187
|
+
`below / SELL above the last fill); re-planned after market moves`, 'debug');
|
|
3915
4188
|
continue;
|
|
3916
4189
|
}
|
|
3917
4190
|
lastFillGuardStats.passed++;
|
|
@@ -4115,10 +4388,35 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4115
4388
|
bot.manager.logger.log(`[COW] Boundary hold: ${refillHold.heldRefillSlotIds.length} refill slot(s) skipped ` +
|
|
4116
4389
|
`(${refillHold.heldRefillSlotIds.join(', ')}) — keeping ${bot.manager.boundaryIdx} over planned ${workingBoundary}`, 'warn');
|
|
4117
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;
|
|
4118
4416
|
// Consecutive-hold tracking (INV-COW-007 visibility): escalate a
|
|
4119
4417
|
// growing run — the grid is trailing the market and only fresh
|
|
4120
4418
|
// fills unstick it. Cleared automatically on the first clean batch.
|
|
4121
|
-
const consecutiveHolds = trackBoundaryHold(bot.manager,
|
|
4419
|
+
const consecutiveHolds = trackBoundaryHold(bot.manager, boundaryHeld, bot.manager.boundaryIdx, workingBoundary, refillHold.heldRefillSlotIds);
|
|
4122
4420
|
if (consecutiveHolds >= 3) {
|
|
4123
4421
|
bot.manager.logger.log(`[COW] Boundary held ${consecutiveHolds} consecutive batches ` +
|
|
4124
4422
|
`(keeping ${bot.manager.boundaryIdx} over planned ${workingBoundary}). ` +
|
|
@@ -4327,7 +4625,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4327
4625
|
// options.result, so a later throw in this frame (e.g.
|
|
4328
4626
|
// processBatchResults after a successful commit) cannot pop a
|
|
4329
4627
|
// second time for the same grid in the batch catch below.
|
|
4330
|
-
const commitOk = await bot.manager._commitWorkingGrid(workingGrid, workingIndexes, effectiveBoundary, {
|
|
4628
|
+
const commitOk = await bot.manager._commitWorkingGrid(workingGrid, workingIndexes, effectiveBoundary, {
|
|
4629
|
+
skipRecalc: true,
|
|
4630
|
+
result: cowResult,
|
|
4631
|
+
boundaryHeld,
|
|
4632
|
+
consumedCrawlIds: cowResult?.consumedCrawlIds
|
|
4633
|
+
});
|
|
4331
4634
|
if (!commitOk) {
|
|
4332
4635
|
// Master changed during broadcast (e.g. a fill landed and was
|
|
4333
4636
|
// processed concurrently) so the commit was refused. The batch
|
|
@@ -4440,7 +4743,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4440
4743
|
// _commitWorkingGrid pops on every settle path and clears
|
|
4441
4744
|
// the push marker via options.result, so a later throw here
|
|
4442
4745
|
// must not pop again in the batch catch below.
|
|
4443
|
-
const pollCommitOk = await bot.manager._commitWorkingGrid(workingGrid, workingIndexes, effectiveBoundary, {
|
|
4746
|
+
const pollCommitOk = await bot.manager._commitWorkingGrid(workingGrid, workingIndexes, effectiveBoundary, {
|
|
4747
|
+
skipRecalc: true,
|
|
4748
|
+
result: cowResult,
|
|
4749
|
+
boundaryHeld,
|
|
4750
|
+
consumedCrawlIds: cowResult?.consumedCrawlIds
|
|
4751
|
+
});
|
|
4444
4752
|
if (!pollCommitOk) {
|
|
4445
4753
|
// Master moved while polling — same recovery as the
|
|
4446
4754
|
// refused-commit path: adopt from chain, keep pending
|
|
@@ -4855,6 +5163,53 @@ function resolveOnGridPivot(manager, rawPrice) {
|
|
|
4855
5163
|
return { price, snapped: false, idx: null, nearestDrift: null };
|
|
4856
5164
|
}
|
|
4857
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
|
+
}
|
|
4858
5213
|
/**
|
|
4859
5214
|
* Run the last-fill guard probe: optionally refresh the pivot from
|
|
4860
5215
|
* still-queued fills, read the durable pivot, and evaluate
|
|
@@ -4872,13 +5227,12 @@ function resolveOnGridPivot(manager, rawPrice) {
|
|
|
4872
5227
|
* operations/opContexts as the filtered arrays.
|
|
4873
5228
|
* @param {Object} bot
|
|
4874
5229
|
* @param {number} price - Target order price
|
|
4875
|
-
* @param {number} size - Order size
|
|
4876
5230
|
* @param {string} type - ORDER_TYPES.BUY/SELL
|
|
4877
5231
|
* @param {Object} stats - lastFillGuardStats tracker (checked++ here)
|
|
4878
5232
|
* @param {boolean} [skipRefresh=false] - Skip the queued-fill pivot refresh
|
|
4879
5233
|
* @returns {{check: Object, refreshed: boolean}}
|
|
4880
5234
|
*/
|
|
4881
|
-
function runLastFillGuardCheck(bot, price,
|
|
5235
|
+
function runLastFillGuardCheck(bot, price, type, stats, skipRefresh = false) {
|
|
4882
5236
|
let refreshed = false;
|
|
4883
5237
|
// The batch-start freeze (see broadcast loop head) owns pivot refreshes;
|
|
4884
5238
|
// per-action refreshes are disabled so every action in a batch is judged
|
|
@@ -4895,7 +5249,6 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4895
5249
|
const lastRef = resolveLastFillGuardReference(bot.manager);
|
|
4896
5250
|
const lastPrice = lastRef.price;
|
|
4897
5251
|
const lastType = lastRef.type;
|
|
4898
|
-
const inc = resolveLastFillGuardIncrement(bot);
|
|
4899
5252
|
// Validate the pivot onto the ladder before use (see resolveOnGridPivot).
|
|
4900
5253
|
// Reported once per probe at warn when the raw pivot was NOT a grid level:
|
|
4901
5254
|
// that is the ratchet precondition, and it is otherwise invisible because
|
|
@@ -4927,7 +5280,7 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4927
5280
|
catch { /* logging is best-effort */ }
|
|
4928
5281
|
stats.pivotOffGrid = (stats.pivotOffGrid || 0) + 1;
|
|
4929
5282
|
}
|
|
4930
|
-
const check = isLastFillGuardBlocked(price,
|
|
5283
|
+
const check = isLastFillGuardBlocked(price, type, onGrid.price, lastType);
|
|
4931
5284
|
stats.checked++;
|
|
4932
5285
|
return { check, refreshed };
|
|
4933
5286
|
}
|
|
@@ -5044,11 +5397,24 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5044
5397
|
`changed=${pivotChanged} refreshed=${refreshed}`, 'debug');
|
|
5045
5398
|
}
|
|
5046
5399
|
catch { /* logging is best-effort */ }
|
|
5047
|
-
if (!pivotChanged)
|
|
5048
|
-
return { ...empty, refreshed };
|
|
5049
5400
|
// Pivot moved (or armed mid-batch): re-check every built op's FINAL
|
|
5050
5401
|
// price. Same bypass rules as the build loop; unjudgeable => KEEP.
|
|
5051
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 };
|
|
5052
5418
|
const batchOrigin = opts.cowResult?.origin;
|
|
5053
5419
|
const actionBySlot = new Map();
|
|
5054
5420
|
for (const a of actions) {
|
|
@@ -5063,7 +5429,6 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5063
5429
|
}
|
|
5064
5430
|
const dropIdx = new Set();
|
|
5065
5431
|
const dropped = [];
|
|
5066
|
-
const inc = resolveLastFillGuardIncrement(bot);
|
|
5067
5432
|
const onGrid = resolveOnGridPivot(bot.manager, liveRef.price);
|
|
5068
5433
|
for (let i = 0; i < opContexts.length; i++) {
|
|
5069
5434
|
const ctx = opContexts[i];
|
|
@@ -5071,14 +5436,12 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5071
5436
|
continue;
|
|
5072
5437
|
let price = null;
|
|
5073
5438
|
let type = null;
|
|
5074
|
-
let size = null;
|
|
5075
5439
|
let slotId = null;
|
|
5076
5440
|
let action = null;
|
|
5077
5441
|
if (ctx.kind === 'create') {
|
|
5078
5442
|
slotId = ctx.id || ctx.order?.id || null;
|
|
5079
5443
|
price = Number(ctx.order?.price);
|
|
5080
5444
|
type = ctx.order?.type || null;
|
|
5081
|
-
size = Number(ctx.order?.size);
|
|
5082
5445
|
action = (slotId && actionBySlot.get(slotId)) || null;
|
|
5083
5446
|
// Spread-correction CREATE bypass (mirrors the build loop:
|
|
5084
5447
|
// per-action origin, batch origin as back-compat fallback).
|
|
@@ -5096,7 +5459,6 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5096
5459
|
slotId = rot.newGridId || rot.oldOrder?.id || null;
|
|
5097
5460
|
price = Number(rot.newPrice);
|
|
5098
5461
|
type = rot.type || null;
|
|
5099
|
-
size = Number(rot.newSize);
|
|
5100
5462
|
// Rotation UPDATEs are keyed by DESTINATION slot (the
|
|
5101
5463
|
// emitted price is the destination's level) — EXCEPT the
|
|
5102
5464
|
// same-slot size-only form (no newGridId, or newGridId ===
|
|
@@ -5140,8 +5502,35 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5140
5502
|
if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
|
|
5141
5503
|
&& Number.isFinite(Format.toKnownNumber(action?.evacBoundary))
|
|
5142
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);
|
|
5143
5525
|
if (stats)
|
|
5144
|
-
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 */ }
|
|
5145
5534
|
continue;
|
|
5146
5535
|
}
|
|
5147
5536
|
}
|
|
@@ -5154,7 +5543,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5154
5543
|
continue;
|
|
5155
5544
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
5156
5545
|
continue;
|
|
5157
|
-
const check = isLastFillGuardBlocked(price,
|
|
5546
|
+
const check = isLastFillGuardBlocked(price, type, onGrid.price, liveType);
|
|
5158
5547
|
if (stats)
|
|
5159
5548
|
stats.checked = (Number(stats.checked) || 0) + 1;
|
|
5160
5549
|
if (!check.blocked) {
|
|
@@ -5171,7 +5560,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
5171
5560
|
try {
|
|
5172
5561
|
bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate dropping ${type} ${ctx.kind} for ${slotId ?? 'unknown'} at ` +
|
|
5173
5562
|
`${Format.formatPrice6(price)}: ${dir} last filled ${check.pivot != null ? Format.formatPrice6(Number(check.pivot)) : 'n/a'} ` +
|
|
5174
|
-
`(
|
|
5563
|
+
`(direction rule: BUY must be below / SELL above the last fill); re-planned after market moves`, 'warn');
|
|
5175
5564
|
}
|
|
5176
5565
|
catch { /* logging is best-effort */ }
|
|
5177
5566
|
}
|
|
@@ -5390,6 +5779,8 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5390
5779
|
const btsFeeData = getAssetFeesSafe('BTS');
|
|
5391
5780
|
let hadRotation = false;
|
|
5392
5781
|
let updateOperationCount = 0;
|
|
5782
|
+
let createOperationCount = 0;
|
|
5783
|
+
let rotationOperationCount = 0;
|
|
5393
5784
|
const updatesToApply = [];
|
|
5394
5785
|
for (let i = 0; i < opContexts.length; i++) {
|
|
5395
5786
|
const ctx = opContexts[i];
|
|
@@ -5417,6 +5808,7 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5417
5808
|
updateOperationCount++;
|
|
5418
5809
|
}
|
|
5419
5810
|
else if (ctx.kind === 'create') {
|
|
5811
|
+
createOperationCount++;
|
|
5420
5812
|
const chainOrderId = res && res[1];
|
|
5421
5813
|
if (chainOrderId) {
|
|
5422
5814
|
await bot.manager.synchronizeWithChain({
|
|
@@ -5455,6 +5847,7 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5455
5847
|
}
|
|
5456
5848
|
else if (ctx.kind === 'rotation') {
|
|
5457
5849
|
hadRotation = true;
|
|
5850
|
+
rotationOperationCount++;
|
|
5458
5851
|
const rotation = (ctx.rotation ?? {});
|
|
5459
5852
|
const oldOrder = rotation.oldOrder;
|
|
5460
5853
|
const newPrice = rotation.newPrice;
|
|
@@ -5524,10 +5917,16 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5524
5917
|
return {
|
|
5525
5918
|
executed: true,
|
|
5526
5919
|
hadRotation,
|
|
5527
|
-
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
|
|
5528
5927
|
};
|
|
5529
5928
|
}
|
|
5530
|
-
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 };
|
|
5531
5930
|
// Exported for regression tests (issue #23 sibling): the uncertain-broadcast
|
|
5532
5931
|
// discard path must never drop a placement silently when master lost the slot.
|
|
5533
5932
|
export { restoreDiscardedCreates };
|