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
|
@@ -80,11 +80,12 @@ const require = createRequire(import.meta.url);
|
|
|
80
80
|
import { path } from '../../path_api.js';
|
|
81
81
|
import { getStorage } from '../../storage/index.js';
|
|
82
82
|
const storage = getStorage();
|
|
83
|
-
import { API_LIMITS, ORDER_TYPES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
|
|
83
|
+
import { API_LIMITS, ORDER_TYPES, ORDER_STATES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
|
|
84
84
|
import { PATHS } from '../../paths.js';
|
|
85
85
|
import { toFiniteNumber, isValidNumber, toKnownNumber } from '../format.js';
|
|
86
86
|
import * as MathUtils from './math.js';
|
|
87
87
|
import * as OrderUtils from './order.js';
|
|
88
|
+
import { parseSlotIndex } from './slot.js';
|
|
88
89
|
import Logger from '../../order/logger.js';
|
|
89
90
|
import { runtime } from '../../runtime.js';
|
|
90
91
|
import { getErrorMessage, sleepMs } from '../../utils/errors.js';
|
|
@@ -1245,37 +1246,10 @@ export function evaluateSpreadCorrectionReadiness(manager, options = {}) {
|
|
|
1245
1246
|
* @returns {number|null} Reference price or null
|
|
1246
1247
|
*/
|
|
1247
1248
|
export function resolveSpreadMarketReference(manager) {
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
return live;
|
|
1252
|
-
}
|
|
1253
|
-
const market = Number(manager?._lastMarketFillPrice);
|
|
1254
|
-
const marketType = manager?._lastMarketFillType;
|
|
1255
|
-
if (Number.isFinite(market) && market > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
|
|
1256
|
-
return market;
|
|
1257
|
-
}
|
|
1258
|
-
return null;
|
|
1249
|
+
// ONE predicate: the price-only reader and the price+side reader must never
|
|
1250
|
+
// disagree about what counts as a fill-provenanced market reference.
|
|
1251
|
+
return resolveFillProvenancedReference(manager).price;
|
|
1259
1252
|
}
|
|
1260
|
-
/**
|
|
1261
|
-
* Resolve the reference the generic LAST-FILL-GUARD judges against.
|
|
1262
|
-
*
|
|
1263
|
-
* Prefers the live armed pivot. When that is cold (a grid regeneration
|
|
1264
|
-
* cleared it, or a rejected-snapshot reset ran) it falls back to the
|
|
1265
|
-
* bot-scoped last-market-fill row — the same market truth spread correction
|
|
1266
|
-
* already uses. This is what stops a rebuild from silently un-arming the
|
|
1267
|
-
* guard until the next fill: the price the account last traded at is known,
|
|
1268
|
-
* so a CREATE/rotation must still not cross it.
|
|
1269
|
-
*
|
|
1270
|
-
* Read-time fallback only: it does NOT mutate the pivot or persist an
|
|
1271
|
-
* old-generation value, so the genesis-bound pivot/persist contract is
|
|
1272
|
-
* unchanged. The guard still validates the value onto the CURRENT ladder via
|
|
1273
|
-
* resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
|
|
1274
|
-
* regenerated geometry stays the authority on which placements are off-grid.
|
|
1275
|
-
*
|
|
1276
|
-
* @param {Object} manager - OrderManager instance
|
|
1277
|
-
* @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
|
|
1278
|
-
*/
|
|
1279
1253
|
/**
|
|
1280
1254
|
* Re-anchor the boundary so the newest REAL fill sits outside its own window.
|
|
1281
1255
|
*
|
|
@@ -1293,16 +1267,29 @@ export function resolveSpreadMarketReference(manager) {
|
|
|
1293
1267
|
*
|
|
1294
1268
|
* Only a genuine on-ladder fill price is accepted (same one-increment drift
|
|
1295
1269
|
* bound as `resolveOnGridPivot`), and the candidate must pass the same
|
|
1296
|
-
* placed-order-aware validation the boundary commit gate uses
|
|
1297
|
-
*
|
|
1270
|
+
* placed-order-aware validation the boundary commit gate uses
|
|
1271
|
+
* (`validatePersistedBoundary` — the SAME gate the restore and commit paths
|
|
1272
|
+
* use), so a re-anchor can never strand a live order inside the re-typed band.
|
|
1273
|
+
*
|
|
1274
|
+
* ELIGIBILITY (same rule as the crawl, see deriveTargetBoundary):
|
|
1275
|
+
* - EDGE-pinned insurance fills never anchor. An edge fill is by definition
|
|
1276
|
+
* outside the window it would move, and it is a book event (a fat-finger
|
|
1277
|
+
* wick), not market movement — the crawl already excludes it, and an
|
|
1278
|
+
* absolute anchor from a grid-edge price would teleport the window to that
|
|
1279
|
+
* edge. Such fills also never arm the pivot (recordLastFilledPrices skips
|
|
1280
|
+
* them), so the reference can only be a window fill.
|
|
1281
|
+
* - PARTIAL fills DO anchor: a partial at the far slot is still a real trade
|
|
1282
|
+
* at a real price, and the residual it leaves at the anchor slot is
|
|
1283
|
+
* explicitly allow-listed below (otherwise the geometry deadlocks).
|
|
1298
1284
|
*
|
|
1299
1285
|
* @param {Object} manager - OrderManager (pivot + genesis)
|
|
1300
1286
|
* @param {number|null} boundaryIdx - Boundary the derivation would commit
|
|
1301
1287
|
* @param {Array<Object>} slots - Grid slots (current generation)
|
|
1302
1288
|
* @param {number} gapSlots - Gap band width
|
|
1289
|
+
* @param {Array<Object>} [fills] - Current fill batch (extremum resolution)
|
|
1303
1290
|
* @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
|
|
1304
1291
|
*/
|
|
1305
|
-
export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots) {
|
|
1292
|
+
export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots, fills = null) {
|
|
1306
1293
|
// NB: Number(null) === 0 and Number('') === 0 — a boundary-less manager must
|
|
1307
1294
|
// not be re-anchored onto slot 0 (same absent-value trap as
|
|
1308
1295
|
// consumePendingFillCrawls).
|
|
@@ -1312,7 +1299,13 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
|
|
|
1312
1299
|
const boundary = Number(boundaryIdx);
|
|
1313
1300
|
if (!Number.isFinite(boundary))
|
|
1314
1301
|
return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
|
|
1315
|
-
|
|
1302
|
+
// An absolute re-anchor must be a FILL fact, never a book seed. The
|
|
1303
|
+
// generic guard deliberately accepts a one-sided book seed as a pricing
|
|
1304
|
+
// hint, but using that heuristic as the geometry anchor would move the
|
|
1305
|
+
// boundary off our own resting order price. Prefer the live pivot only
|
|
1306
|
+
// when its provenance is 'fill'; otherwise fall back to the bot-scoped
|
|
1307
|
+
// last-market-fill row (a real trade that survives grid regeneration).
|
|
1308
|
+
const ref = resolveFillProvenancedReference(manager);
|
|
1316
1309
|
const price = Number(ref?.price);
|
|
1317
1310
|
if (!Number.isFinite(price) || price <= 0)
|
|
1318
1311
|
return { boundaryIdx: boundary, reanchored: false, reason: 'cold-pivot' };
|
|
@@ -1342,21 +1335,74 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
|
|
|
1342
1335
|
if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - price) / price > maxDrift) {
|
|
1343
1336
|
return { boundaryIdx: boundary, reanchored: false, reason: 'off-ladder-fill' };
|
|
1344
1337
|
}
|
|
1338
|
+
// BATCH EXTREMUM: the pivot is the LAST-processed fill, but a sweep is
|
|
1339
|
+
// processed in chunks and the pivot is overwritten per chunk (live
|
|
1340
|
+
// incident: one sweep's pivot bounced 1366 -> 1349 -> 1361). Anchoring on
|
|
1341
|
+
// the last chunk under-advances the window and leaves the furthest fill's
|
|
1342
|
+
// counter-order in-band. The rail must clear the FURTHEST fill of the side:
|
|
1343
|
+
// max slot for SELL fills, min slot for BUY fills.
|
|
1344
|
+
let anchorIdx = idx;
|
|
1345
|
+
let anchorPrice = price;
|
|
1346
|
+
const batchExtremum = resolveFillAnchorIndex(fills, side, genesis, maxDrift);
|
|
1347
|
+
if (batchExtremum) {
|
|
1348
|
+
anchorIdx = batchExtremum.idx;
|
|
1349
|
+
if (batchExtremum.price != null && Number.isFinite(batchExtremum.price) && batchExtremum.price > 0) {
|
|
1350
|
+
anchorPrice = batchExtremum.price;
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1345
1353
|
const gap = Number.isFinite(Number(gapSlots)) && Number(gapSlots) >= 0 ? Math.floor(Number(gapSlots)) : 0;
|
|
1346
1354
|
const slotCount = Array.isArray(slots) ? slots.length : 0;
|
|
1347
1355
|
if (slotCount === 0)
|
|
1348
1356
|
return { boundaryIdx: boundary, reanchored: false, reason: 'no-slots' };
|
|
1349
1357
|
const ceiling = (slotCount - gap - 1) >= 0 ? (slotCount - gap - 1) : (slotCount - 1);
|
|
1350
|
-
const required = side === ORDER_TYPES.SELL ?
|
|
1358
|
+
const required = side === ORDER_TYPES.SELL ? anchorIdx - gap : anchorIdx - 1;
|
|
1351
1359
|
if (side === ORDER_TYPES.SELL ? boundary >= required : boundary <= required) {
|
|
1352
1360
|
return { boundaryIdx: boundary, reanchored: false, reason: 'already-outside' };
|
|
1353
1361
|
}
|
|
1354
1362
|
const candidate = Math.max(0, Math.min(ceiling, required));
|
|
1355
1363
|
if (candidate === boundary)
|
|
1356
1364
|
return { boundaryIdx: boundary, reanchored: false, reason: 'no-op' };
|
|
1365
|
+
// Clamping can defeat the anchor: a fill near the grid ceiling needs
|
|
1366
|
+
// `required > ceiling`, so the clamped candidate still leaves the fill
|
|
1367
|
+
// inside its own window. Fail closed instead of reporting a re-anchor that
|
|
1368
|
+
// did not move the fill outside.
|
|
1369
|
+
const outsideWindow = side === ORDER_TYPES.SELL ? candidate >= required : candidate <= required;
|
|
1370
|
+
if (!outsideWindow) {
|
|
1371
|
+
return { boundaryIdx: boundary, reanchored: false, reason: 'ceiling-clamped' };
|
|
1372
|
+
}
|
|
1373
|
+
// The fill's OWN residual is not a stranding placement: a partial fill
|
|
1374
|
+
// leaves the remainder at the fill slot, and any boundary that puts the
|
|
1375
|
+
// fill outside its window necessarily puts that slot inside the implied
|
|
1376
|
+
// band. Allow exactly that residual (PARTIAL, same side, same ladder
|
|
1377
|
+
// level); every other in-band order still refuses the re-anchor.
|
|
1378
|
+
//
|
|
1379
|
+
// ANCHOR-AWARE: the residual sits at the slot the re-anchor is derived
|
|
1380
|
+
// from (`anchorIdx`), which is the batch EXTREMUM, not necessarily the
|
|
1381
|
+
// last-processed pivot (`idx`). Comparing against `idx`/`price` made this
|
|
1382
|
+
// allow-list dead code for every chunked sweep whose furthest fill is not
|
|
1383
|
+
// the pivot — i.e. exactly the case the extremum resolution exists for —
|
|
1384
|
+
// so the re-anchor was refused as 'unsafe: placed_order_in_band'.
|
|
1385
|
+
const allowedInBandSlotIds = [];
|
|
1386
|
+
const fillSlotOrder = Array.isArray(slots) ? slots[anchorIdx] : null;
|
|
1387
|
+
if (fillSlotOrder && fillSlotOrder.orderId
|
|
1388
|
+
&& fillSlotOrder.state === ORDER_STATES.PARTIAL
|
|
1389
|
+
&& fillSlotOrder.type === side) {
|
|
1390
|
+
let orderIdx = null;
|
|
1391
|
+
try {
|
|
1392
|
+
orderIdx = Number(MathUtils.slotIndexForPrice(Number(fillSlotOrder.price), genesis));
|
|
1393
|
+
}
|
|
1394
|
+
catch {
|
|
1395
|
+
orderIdx = null;
|
|
1396
|
+
}
|
|
1397
|
+
const orderPrice = Number(fillSlotOrder.price);
|
|
1398
|
+
if (orderIdx === anchorIdx && Number.isFinite(orderPrice) && orderPrice > 0
|
|
1399
|
+
&& Math.abs(orderPrice - anchorPrice) / anchorPrice <= maxDrift) {
|
|
1400
|
+
allowedInBandSlotIds.push(String(fillSlotOrder.id));
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1357
1403
|
let check = { ok: true };
|
|
1358
1404
|
try {
|
|
1359
|
-
check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap);
|
|
1405
|
+
check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap, allowedInBandSlotIds.length > 0 ? { allowInBandSlotIds: allowedInBandSlotIds } : undefined);
|
|
1360
1406
|
}
|
|
1361
1407
|
catch (err) {
|
|
1362
1408
|
check = { ok: false, reason: getErrorMessage(err) };
|
|
@@ -1365,24 +1411,243 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
|
|
|
1365
1411
|
return { boundaryIdx: boundary, reanchored: false, reason: `unsafe: ${check?.reason ?? 'unknown'}` };
|
|
1366
1412
|
}
|
|
1367
1413
|
try {
|
|
1368
|
-
manager.logger?.log?.(`[BOUNDARY] Re-anchored from the last fill: ${side} filled at slot ${
|
|
1369
|
-
`(${
|
|
1414
|
+
manager.logger?.log?.(`[BOUNDARY] Re-anchored from the last fill: ${side} filled at slot ${anchorIdx} ` +
|
|
1415
|
+
`(${anchorPrice.toFixed(6)}); boundary ${boundary} -> ${candidate} so the fill sits outside ` +
|
|
1370
1416
|
`its own window (crawl alone cannot recover a window behind the fill)`, 'warn');
|
|
1371
1417
|
}
|
|
1372
1418
|
catch { /* logging is best-effort */ }
|
|
1373
|
-
return { boundaryIdx: candidate, reanchored: true, from: boundary, to: candidate, side, fillSlot:
|
|
1419
|
+
return { boundaryIdx: candidate, reanchored: true, from: boundary, to: candidate, side, fillSlot: anchorIdx };
|
|
1374
1420
|
}
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1421
|
+
/**
|
|
1422
|
+
* Resolve the EXTREMUM fill of one side in a fill batch, mapped onto the
|
|
1423
|
+
* genesis ladder.
|
|
1424
|
+
*
|
|
1425
|
+
* The pivot is the LAST-processed fill, which a chunked sweep overwrites per
|
|
1426
|
+
* chunk, so the geometry anchor must be the batch's furthest fill of that side
|
|
1427
|
+
* (max slot for SELL, min slot for BUY) — otherwise the furthest fill's
|
|
1428
|
+
* counter-order lands inside the implied band. Prices are the real execution
|
|
1429
|
+
* prices (sync_engine stamps them from the chain), with the slot id as a
|
|
1430
|
+
* legacy fallback for fill records that carry no price.
|
|
1431
|
+
*
|
|
1432
|
+
* Pure: reads the batch only, no manager state.
|
|
1433
|
+
*
|
|
1434
|
+
* @param {Array<Object>} fills - Fill batch
|
|
1435
|
+
* @param {string} side - ORDER_TYPES.BUY / SELL (entries of the other side are ignored)
|
|
1436
|
+
* @param {Object} genesis - Genesis ladder
|
|
1437
|
+
* @param {number} maxDrift - One-increment drift bound for a price to count as on-ladder
|
|
1438
|
+
* @returns {{idx: number, price: number|null}|null} Extremum, or null when the batch has no usable entry for the side
|
|
1439
|
+
*/
|
|
1440
|
+
function resolveFillAnchorIndex(fills, side, genesis, maxDrift) {
|
|
1441
|
+
if (!Array.isArray(fills) || fills.length === 0)
|
|
1442
|
+
return null;
|
|
1443
|
+
let best = null;
|
|
1444
|
+
for (const f of fills) {
|
|
1445
|
+
if (!f || f.type !== side)
|
|
1446
|
+
continue;
|
|
1447
|
+
let fIdx = null;
|
|
1448
|
+
let fPrice = null;
|
|
1449
|
+
const rawPrice = Number(f.price);
|
|
1450
|
+
if (Number.isFinite(rawPrice) && rawPrice > 0) {
|
|
1451
|
+
try {
|
|
1452
|
+
const candidateIdx = Number(MathUtils.slotIndexForPrice(rawPrice, genesis));
|
|
1453
|
+
const candidateLevel = Number(MathUtils.priceForSlot(candidateIdx, genesis));
|
|
1454
|
+
if (Number.isFinite(candidateIdx) && candidateIdx >= 0
|
|
1455
|
+
&& Number.isFinite(candidateLevel) && candidateLevel > 0
|
|
1456
|
+
&& Math.abs(candidateLevel - rawPrice) / rawPrice <= maxDrift) {
|
|
1457
|
+
fIdx = candidateIdx;
|
|
1458
|
+
fPrice = rawPrice;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
catch { /* fall back to the slot id */ }
|
|
1462
|
+
}
|
|
1463
|
+
if (fIdx === null) {
|
|
1464
|
+
const idIdx = parseSlotIndex(f.id);
|
|
1465
|
+
if (idIdx !== null && idIdx !== undefined && Number.isFinite(Number(idIdx)) && Number(idIdx) >= 0) {
|
|
1466
|
+
fIdx = Number(idIdx);
|
|
1467
|
+
try {
|
|
1468
|
+
fPrice = Number(MathUtils.priceForSlot(fIdx, genesis));
|
|
1469
|
+
}
|
|
1470
|
+
catch {
|
|
1471
|
+
fPrice = null;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
if (fIdx === null)
|
|
1476
|
+
continue;
|
|
1477
|
+
if (best === null
|
|
1478
|
+
|| (side === ORDER_TYPES.SELL && fIdx > best.idx)
|
|
1479
|
+
|| (side === ORDER_TYPES.BUY && fIdx < best.idx)) {
|
|
1480
|
+
best = {
|
|
1481
|
+
idx: fIdx,
|
|
1482
|
+
price: Number.isFinite(Number(fPrice)) && Number(fPrice) > 0 ? Number(fPrice) : null
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
return best;
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* Resolve a FILL-PROVENANCED reference for absolute geometry repairs.
|
|
1490
|
+
*
|
|
1491
|
+
* `resolveLastFillGuardReference` intentionally accepts a one-sided book seed
|
|
1492
|
+
* as a guard hint. A re-anchor is different: it moves the boundary, so a
|
|
1493
|
+
* heuristic max-bid/min-ask price must never be treated as a trade. Accept the
|
|
1494
|
+
* live pivot only when `lastFillPivotSource === 'fill'`; otherwise fall back to
|
|
1495
|
+
* the bot-scoped last-market-fill row, which is written only by real fills and
|
|
1496
|
+
* survives grid regeneration.
|
|
1497
|
+
*
|
|
1498
|
+
* Read-time TTL applies here too (see resolveFillProvenancedRow): an absolute
|
|
1499
|
+
* geometry move must not be derived from a fill older than the pivot lifetime.
|
|
1500
|
+
*
|
|
1501
|
+
* @param {Object} manager - OrderManager instance
|
|
1502
|
+
* @returns {{price: number|null, type: string|null}}
|
|
1503
|
+
*/
|
|
1504
|
+
function resolveFillProvenancedReference(manager) {
|
|
1505
|
+
const row = resolveFillProvenancedRow(manager);
|
|
1506
|
+
return { price: row?.price ?? null, type: row?.type ?? null };
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* The pivot lifetime, in ms. 0 means "no lifetime configured" (never expire).
|
|
1510
|
+
* ONE reader for GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS: the persisted-row
|
|
1511
|
+
* restores, the read-time guards and the re-arm all derive from it.
|
|
1512
|
+
*/
|
|
1513
|
+
function lastFillPivotTtlMs() {
|
|
1514
|
+
const ttl = Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS);
|
|
1515
|
+
return Number.isFinite(ttl) && ttl > 0 ? ttl : 0;
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Is a fill reference older than the pivot lifetime?
|
|
1519
|
+
*
|
|
1520
|
+
* The same bound applies at every reading of a fill reference:
|
|
1521
|
+
* `restoreLastFillPivot` / `restoreLastMarketFill` (persisted rows) and
|
|
1522
|
+
* `resolveLastFillGuardReference` / `resolveFillProvenancedRow` (in-memory
|
|
1523
|
+
* rows). Without the read-time half, a long-lived process keeps a fill older
|
|
1524
|
+
* than 24h vetoing one side forever — and the geometry-bind watchdog
|
|
1525
|
+
* re-centers at most ONCE per pivot and then reports that "a fill or the pivot
|
|
1526
|
+
* TTL restores the side" (trackOutOfSpreadStaleness), a promise the code must
|
|
1527
|
+
* keep without a restart.
|
|
1528
|
+
*
|
|
1529
|
+
* An unknown age (missing/0 timestamp) never expires: legacy managers and the
|
|
1530
|
+
* ambiguous two-sided book seed carry no fill clock, and silently unarming
|
|
1531
|
+
* those would be worse than a stale veto.
|
|
1532
|
+
*
|
|
1533
|
+
* @param {unknown} atMs - Row timestamp (ms epoch)
|
|
1534
|
+
* @param {number} [now=Date.now()] - Injectable clock (tests)
|
|
1535
|
+
* @returns {boolean} True when the row is older than the pivot TTL
|
|
1536
|
+
*/
|
|
1537
|
+
function isFillReferenceExpired(atMs, now = Date.now()) {
|
|
1538
|
+
const ttl = lastFillPivotTtlMs();
|
|
1539
|
+
if (ttl <= 0)
|
|
1540
|
+
return false;
|
|
1541
|
+
const at = Number(atMs);
|
|
1542
|
+
if (!Number.isFinite(at) || at <= 0)
|
|
1543
|
+
return false;
|
|
1544
|
+
return now - at > ttl;
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Report a pivot expiry once per expired timestamp. The read-time readers run
|
|
1548
|
+
* per probe and per guarded action, so an unguarded line would flood the log;
|
|
1549
|
+
* the marker is the expired row's own clock, which also re-arms the report
|
|
1550
|
+
* when a NEW fill later expires.
|
|
1551
|
+
*/
|
|
1552
|
+
function logExpiredFillReference(manager, atMs, now) {
|
|
1553
|
+
const at = Number(atMs);
|
|
1554
|
+
if (!manager || !Number.isFinite(at) || at <= 0)
|
|
1555
|
+
return;
|
|
1556
|
+
if (Number(manager._lastFillPivotExpiryLoggedAt) === at)
|
|
1557
|
+
return;
|
|
1558
|
+
manager._lastFillPivotExpiryLoggedAt = at;
|
|
1559
|
+
try {
|
|
1560
|
+
manager.logger?.log?.(`[LAST-FILL-GUARD] Pivot expired (age ${Math.round((now - at) / 1000)}s > TTL ` +
|
|
1561
|
+
`${Math.round(lastFillPivotTtlMs() / 1000)}s) — guard re-arms on the next fill`, 'info');
|
|
1562
|
+
}
|
|
1563
|
+
catch { /* logging is best-effort */ }
|
|
1564
|
+
}
|
|
1565
|
+
/** Normalize one in-memory triple (price, side, clock) into a fill reference row. */
|
|
1566
|
+
function readFillRow(price, type, atMs) {
|
|
1567
|
+
const p = Number(price);
|
|
1568
|
+
if (!Number.isFinite(p) || p <= 0)
|
|
1569
|
+
return null;
|
|
1570
|
+
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
1571
|
+
return null;
|
|
1572
|
+
const at = Number(atMs);
|
|
1573
|
+
return { price: p, type, fillsAt: Number.isFinite(at) && at > 0 ? at : null };
|
|
1574
|
+
}
|
|
1575
|
+
/** Keep a row only while it is inside the pivot lifetime (logging the expiry once). */
|
|
1576
|
+
function acceptFillRow(manager, row, now) {
|
|
1577
|
+
if (!row)
|
|
1578
|
+
return null;
|
|
1579
|
+
if (isFillReferenceExpired(row.fillsAt, now)) {
|
|
1580
|
+
logExpiredFillReference(manager, row.fillsAt, now);
|
|
1581
|
+
return null;
|
|
1380
1582
|
}
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1583
|
+
return row;
|
|
1584
|
+
}
|
|
1585
|
+
/** Live armed pivot as a row, or null when cold OR past the pivot lifetime. */
|
|
1586
|
+
function liveFillRow(manager, now) {
|
|
1587
|
+
return acceptFillRow(manager, readFillRow(manager?._lastFilledPrice, manager?._lastFilledType, manager?._lastFilledAt), now);
|
|
1588
|
+
}
|
|
1589
|
+
/** Bot-scoped last-market-fill row, or null when absent OR past the pivot lifetime. */
|
|
1590
|
+
function marketFillRow(manager, now) {
|
|
1591
|
+
return acceptFillRow(manager, readFillRow(manager?._lastMarketFillPrice, manager?._lastMarketFillType, manager?._lastMarketFillAt), now);
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* FILL-PROVENANCED row for absolute geometry repairs (boundary re-anchor,
|
|
1595
|
+
* spread market reference): the live pivot only when its provenance is
|
|
1596
|
+
* `'fill'`, else the bot-scoped market row.
|
|
1597
|
+
*
|
|
1598
|
+
* The row's OWN timestamp travels with the row. Pairing one value's price with
|
|
1599
|
+
* another value's clock is what let `rearmLastFillPivotFromMarketFill` stamp a
|
|
1600
|
+
* market-fill price with a BOOK seed's (fresh) timestamp — silently refreshing
|
|
1601
|
+
* the 24h lifetime on every rebuild.
|
|
1602
|
+
*
|
|
1603
|
+
* @param {Object} manager - OrderManager instance
|
|
1604
|
+
* @param {number} [now=Date.now()] - Injectable clock (tests)
|
|
1605
|
+
* @returns {FillPivotRow|null} Row, or null when both sources are cold/expired
|
|
1606
|
+
*/
|
|
1607
|
+
function resolveFillProvenancedRow(manager, now = Date.now()) {
|
|
1608
|
+
if (manager?.lastFillPivotSource === 'fill') {
|
|
1609
|
+
const live = liveFillRow(manager, now);
|
|
1610
|
+
if (live)
|
|
1611
|
+
return live;
|
|
1385
1612
|
}
|
|
1613
|
+
return marketFillRow(manager, now);
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* Resolve the reference the generic LAST-FILL-GUARD judges against.
|
|
1617
|
+
*
|
|
1618
|
+
* Prefers the live armed pivot. When that is cold (a grid regeneration
|
|
1619
|
+
* cleared it, or a rejected-snapshot reset ran) it falls back to the
|
|
1620
|
+
* bot-scoped last-market-fill row — the same market truth spread correction
|
|
1621
|
+
* already uses. This is what stops a rebuild from silently un-arming the
|
|
1622
|
+
* guard until the next fill: the price the account last traded at is known,
|
|
1623
|
+
* so a CREATE/rotation must still not cross it.
|
|
1624
|
+
*
|
|
1625
|
+
* Read-time fallback only: it does NOT mutate the pivot or persist an
|
|
1626
|
+
* old-generation value, so the genesis-bound pivot/persist contract is
|
|
1627
|
+
* unchanged. The guard still validates the value onto the CURRENT ladder via
|
|
1628
|
+
* resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
|
|
1629
|
+
* regenerated geometry stays the authority on which placements are off-grid.
|
|
1630
|
+
*
|
|
1631
|
+
* The rebuild path re-arms the pivot explicitly (rearmLastFillPivotFromMarketFill)
|
|
1632
|
+
* so this fallback covers only the window before that write, not the whole
|
|
1633
|
+
* post-rebuild lifetime.
|
|
1634
|
+
*
|
|
1635
|
+
* LIFETIME: a fill reference older than GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS is
|
|
1636
|
+
* ignored (read-time expiry, same bound the restore path applies), so a stale
|
|
1637
|
+
* pivot cannot veto one side forever in a long-lived process. Unknown ages
|
|
1638
|
+
* (missing timestamp) never expire.
|
|
1639
|
+
*
|
|
1640
|
+
* @param {Object} manager - OrderManager instance
|
|
1641
|
+
* @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
|
|
1642
|
+
*/
|
|
1643
|
+
export function resolveLastFillGuardReference(manager) {
|
|
1644
|
+
const now = Date.now();
|
|
1645
|
+
const live = liveFillRow(manager, now);
|
|
1646
|
+
if (live)
|
|
1647
|
+
return { price: live.price, type: live.type };
|
|
1648
|
+
const market = marketFillRow(manager, now);
|
|
1649
|
+
if (market)
|
|
1650
|
+
return { price: market.price, type: market.type };
|
|
1386
1651
|
return { price: null, type: null };
|
|
1387
1652
|
}
|
|
1388
1653
|
/**
|
|
@@ -1400,18 +1665,21 @@ export function resolveLastFillGuardReference(manager) {
|
|
|
1400
1665
|
* we actually did: a BUY below the last sell, a SELL above the last buy. Equal
|
|
1401
1666
|
* price counts as blocked — that is a re-place at the just-filled level, the
|
|
1402
1667
|
* immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
|
|
1403
|
-
* or no fill side recorded — e.g. a book-seeded pivot) => disabled.
|
|
1404
|
-
*
|
|
1668
|
+
* or no fill side recorded — e.g. a book-seeded pivot) => disabled.
|
|
1669
|
+
*
|
|
1670
|
+
* Signature note: the old band rule also consumed order size and the grid
|
|
1671
|
+
* increment (it judged against `pivot ± increment/2`). Both are gone on
|
|
1672
|
+
* purpose — re-adding an increment term re-opens retrospective §9.7 (a BUY
|
|
1673
|
+
* below a SELL fill was blocked, a SELL one tick above our cost was blocked,
|
|
1674
|
+
* and spread tightening became structurally impossible after any fill).
|
|
1405
1675
|
*
|
|
1406
1676
|
* @param {number} price - Target order price
|
|
1407
|
-
* @param {number} _size - Order size (unused, kept for compat)
|
|
1408
1677
|
* @param {string} type - ORDER_TYPES.BUY/SELL
|
|
1409
1678
|
* @param {number|null} lastPrice - Most recent fill price
|
|
1410
1679
|
* @param {string|null} lastType - Most recent fill side; null keeps the guard cold
|
|
1411
|
-
* @param {number|any} _incrementPercent - Unused (kept for signature compat)
|
|
1412
1680
|
* @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
|
|
1413
1681
|
*/
|
|
1414
|
-
export function isLastFillGuardBlocked(price,
|
|
1682
|
+
export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
|
|
1415
1683
|
const numPrice = Number(price);
|
|
1416
1684
|
if (!Number.isFinite(numPrice))
|
|
1417
1685
|
return { blocked: false, pivot: null };
|
|
@@ -1424,6 +1692,97 @@ export function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType,
|
|
|
1424
1692
|
return { blocked: true, pivot, threshold: pivot };
|
|
1425
1693
|
return { blocked: false, pivot: null, threshold: null };
|
|
1426
1694
|
}
|
|
1695
|
+
/**
|
|
1696
|
+
* LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
|
|
1697
|
+
*
|
|
1698
|
+
* Wraps isLastFillGuardBlocked with the same pivot resolution the runtime uses
|
|
1699
|
+
* (live fill pivot, then the bot-scoped market-fill row) and adds the
|
|
1700
|
+
* SAME-LEVEL refusal: a placement within half a grid step of the pivot is a
|
|
1701
|
+
* re-place at the level that just traded, which the raw `>=`/`<=` comparison
|
|
1702
|
+
* lets through because a slot price and its execution price differ by
|
|
1703
|
+
* rounding (live: slot 1310.046339 filled at 1310.060435).
|
|
1704
|
+
*
|
|
1705
|
+
* Unlike the COW-path guard this is meant for the reconcile/startup placement
|
|
1706
|
+
* paths (create + relocation), which previously had no last-fill check at all:
|
|
1707
|
+
* a startup-style top-up could therefore re-create a BUY at the price the bot
|
|
1708
|
+
* had just bought at, or place a BUY above it (the "buying later at higher
|
|
1709
|
+
* prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
|
|
1710
|
+
* still builds.
|
|
1711
|
+
*
|
|
1712
|
+
* @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
|
|
1713
|
+
* @param {number} price - Target placement price
|
|
1714
|
+
* @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
|
|
1715
|
+
* @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
|
|
1716
|
+
*/
|
|
1717
|
+
export function isLastFillPlacementBlocked(manager, price, type) {
|
|
1718
|
+
const numPrice = Number(price);
|
|
1719
|
+
if (!Number.isFinite(numPrice) || numPrice <= 0)
|
|
1720
|
+
return { blocked: false, pivot: null };
|
|
1721
|
+
let reference = { price: null, type: null };
|
|
1722
|
+
try {
|
|
1723
|
+
reference = resolveLastFillGuardReference(manager);
|
|
1724
|
+
}
|
|
1725
|
+
catch {
|
|
1726
|
+
reference = { price: null, type: null };
|
|
1727
|
+
}
|
|
1728
|
+
const pivot = reference.price;
|
|
1729
|
+
const pivotType = reference.type;
|
|
1730
|
+
if (pivot == null || pivotType == null)
|
|
1731
|
+
return { blocked: false, pivot: null };
|
|
1732
|
+
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
1733
|
+
return { blocked: false, pivot };
|
|
1734
|
+
try {
|
|
1735
|
+
if (MathUtils.pricesWithinHalfStep(numPrice, pivot, manager?.config?.incrementPercent)) {
|
|
1736
|
+
return { blocked: true, pivot, reason: 'same-level' };
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
catch { /* fall through to the direction rule */ }
|
|
1740
|
+
const guard = isLastFillGuardBlocked(numPrice, type, pivot, pivotType);
|
|
1741
|
+
if (guard.blocked)
|
|
1742
|
+
return { blocked: true, pivot, reason: 'direction' };
|
|
1743
|
+
return { blocked: false, pivot };
|
|
1744
|
+
}
|
|
1745
|
+
/**
|
|
1746
|
+
* Are fills still UNSETTLED (arrived but not yet absorbed by the grid)?
|
|
1747
|
+
*
|
|
1748
|
+
* While this returns true the master grid still holds filled slots as ACTIVE
|
|
1749
|
+
* and the boundary has not crawled for them, so any geometry-derived plan
|
|
1750
|
+
* (window top-up, startup-style reconcile) is built on the PREVIOUS book. The
|
|
1751
|
+
* live incident: a 120s stale broadcast region deferred 12 fills, the
|
|
1752
|
+
* post-fill reconcile saw "buy 12/20" on that stale master and re-created 8
|
|
1753
|
+
* BUYs at the TOP of the un-crawled rail (1282.78 -> 1310.04), which filled
|
|
1754
|
+
* within seconds (9 buy-lower violations, 23.5% of the window's BTS).
|
|
1755
|
+
*
|
|
1756
|
+
* Accepts a bot (its `manager` is inspected) or a bare manager.
|
|
1757
|
+
*
|
|
1758
|
+
* @param {Object} source - DEXBot-like or OrderManager-like instance
|
|
1759
|
+
* @returns {{unsettled: boolean, reason: string|null}}
|
|
1760
|
+
*/
|
|
1761
|
+
export function hasUnsettledFills(source) {
|
|
1762
|
+
if (!source || typeof source !== 'object')
|
|
1763
|
+
return { unsettled: false, reason: null };
|
|
1764
|
+
const outer = source;
|
|
1765
|
+
const mgr = (outer.manager && typeof outer.manager === 'object'
|
|
1766
|
+
? outer.manager
|
|
1767
|
+
: outer);
|
|
1768
|
+
try {
|
|
1769
|
+
const queued = Array.isArray(outer._incomingFillQueue) ? outer._incomingFillQueue.length : 0;
|
|
1770
|
+
if (queued > 0)
|
|
1771
|
+
return { unsettled: true, reason: `${queued} fill(s) queued for processing` };
|
|
1772
|
+
if (outer._deferredFillsPending === true)
|
|
1773
|
+
return { unsettled: true, reason: 'deferred fill drain pending' };
|
|
1774
|
+
const inFlight = Number(mgr._fillBatchInFlight);
|
|
1775
|
+
if (Number.isFinite(inFlight) && inFlight > 0)
|
|
1776
|
+
return { unsettled: true, reason: 'fill batch in flight' };
|
|
1777
|
+
const owed = Array.isArray(mgr._pendingFillCrawls) ? mgr._pendingFillCrawls.length : 0;
|
|
1778
|
+
if (owed > 0)
|
|
1779
|
+
return { unsettled: true, reason: `${owed} owed boundary crawl(s)` };
|
|
1780
|
+
}
|
|
1781
|
+
catch {
|
|
1782
|
+
return { unsettled: false, reason: null };
|
|
1783
|
+
}
|
|
1784
|
+
return { unsettled: false, reason: null };
|
|
1785
|
+
}
|
|
1427
1786
|
/**
|
|
1428
1787
|
* Restore the persisted bot-scoped last-market-fill reference into the
|
|
1429
1788
|
* manager. Deliberately independent of the boundary and the genesis: this is
|
|
@@ -1456,9 +1815,8 @@ export function restoreLastMarketFill(manager, persisted, options = {}) {
|
|
|
1456
1815
|
catch { /* best-effort */ }
|
|
1457
1816
|
};
|
|
1458
1817
|
const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Persisted last-market-fill expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(ttl / 1000)}s) — reference dropped`, 'info');
|
|
1818
|
+
if (isFillReferenceExpired(row.fillsAt, now)) {
|
|
1819
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Persisted last-market-fill expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(lastFillPivotTtlMs() / 1000)}s) — reference dropped`, 'info');
|
|
1462
1820
|
dropPersistedRow();
|
|
1463
1821
|
return false;
|
|
1464
1822
|
}
|
|
@@ -1468,6 +1826,51 @@ export function restoreLastMarketFill(manager, persisted, options = {}) {
|
|
|
1468
1826
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Restored last-market-fill ${row.price}(${row.type}) age=${Math.round((now - row.fillsAt) / 1000)}s — spread correction will not trade through it`, 'info');
|
|
1469
1827
|
return true;
|
|
1470
1828
|
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Re-arm the LAST-FILL-GUARD pivot from the bot-scoped market-fill row.
|
|
1831
|
+
*
|
|
1832
|
+
* The grid-rebuild path deliberately clears the armed pivot (a new generation).
|
|
1833
|
+
* The guard must NOT stay cold afterwards: the price the account last traded at
|
|
1834
|
+
* is still market truth, so the pivot is re-armed on the NEW generation
|
|
1835
|
+
* explicitly, through the single shared writer, at the original fill timestamp.
|
|
1836
|
+
* That makes the documented contract real ("the guard re-arms against the new
|
|
1837
|
+
* ladder") instead of relying on the read-time fallback in
|
|
1838
|
+
* `resolveLastFillGuardReference` for the whole post-rebuild lifetime — a
|
|
1839
|
+
* fallback that cannot be re-validated, persisted or logged.
|
|
1840
|
+
*
|
|
1841
|
+
* Provenance stays 'fill' (a book seed never qualifies). The price is not
|
|
1842
|
+
* rewritten: an off-new-ladder value is handled by the same one-increment
|
|
1843
|
+
* `resolveOnGridPivot` rule every other probe uses.
|
|
1844
|
+
*
|
|
1845
|
+
* The timestamp comes from the SAME row as the price (see
|
|
1846
|
+
* resolveFillProvenancedRow). Reading `_lastFilledAt` unconditionally paired a
|
|
1847
|
+
* market-row price with a book-seed clock: a book seed writes `_lastFilledAt`
|
|
1848
|
+
* but never the market row, and `setLastFillPivot(..., 'fill')` then re-stamps
|
|
1849
|
+
* `_lastMarketFillAt` with that newer time — refreshing the 24h lifetime on
|
|
1850
|
+
* every rebuild until the row never expires.
|
|
1851
|
+
*
|
|
1852
|
+
* EXPIRED ROWS DO NOT RE-ARM (resolveFillProvenancedRow drops them), so the
|
|
1853
|
+
* documented pivot lifetime holds with or without a restart.
|
|
1854
|
+
*
|
|
1855
|
+
* @param {Object} manager - OrderManager instance
|
|
1856
|
+
* @returns {boolean} True when a pivot was re-armed
|
|
1857
|
+
*/
|
|
1858
|
+
export function rearmLastFillPivotFromMarketFill(manager) {
|
|
1859
|
+
if (!manager)
|
|
1860
|
+
return false;
|
|
1861
|
+
const row = resolveFillProvenancedRow(manager);
|
|
1862
|
+
if (!row)
|
|
1863
|
+
return false;
|
|
1864
|
+
// A source with no clock cannot be aged; stamping `now` keeps the re-armed
|
|
1865
|
+
// pivot inside the same lifetime from this rebuild on (production rows
|
|
1866
|
+
// always carry the fill's own `fillsAt`).
|
|
1867
|
+
const at = row.fillsAt != null ? row.fillsAt : Date.now();
|
|
1868
|
+
if (!setLastFillPivot(manager, row.type, row.price, 'fill', at))
|
|
1869
|
+
return false;
|
|
1870
|
+
manager.logger?.log?.(`[LAST-FILL-GUARD] Re-armed on the new generation: ${row.price}(${row.type}) from the last real fill ` +
|
|
1871
|
+
`(age ${Math.max(0, Math.round((Date.now() - at) / 1000))}s) — the guard survives a rebuild by design`, 'info');
|
|
1872
|
+
return true;
|
|
1873
|
+
}
|
|
1471
1874
|
/**
|
|
1472
1875
|
* Shared field gate for a persisted fill-derived row: finite price > 0,
|
|
1473
1876
|
* BUY/SELL side, finite positive timestamp. One shape contract for the
|
|
@@ -1663,10 +2066,11 @@ export function restoreLastFillPivot(manager, persisted, options = {}) {
|
|
|
1663
2066
|
}
|
|
1664
2067
|
catch { /* best-effort */ }
|
|
1665
2068
|
};
|
|
1666
|
-
// TTL first: an expired pivot is dropped, not re-armed
|
|
2069
|
+
// TTL first: an expired pivot is dropped, not re-armed (one shared bound
|
|
2070
|
+
// with the read-time readers and the market-row restore).
|
|
1667
2071
|
const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
|
|
1668
|
-
if (
|
|
1669
|
-
manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(
|
|
2072
|
+
if (isFillReferenceExpired(row.fillsAt, now)) {
|
|
2073
|
+
manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(lastFillPivotTtlMs() / 1000)}s) — guard re-arms on the next fill`, 'info');
|
|
1670
2074
|
dropPersistedRow();
|
|
1671
2075
|
return false;
|
|
1672
2076
|
}
|
|
@@ -1893,9 +2297,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
|
|
|
1893
2297
|
// stays a rail-typed VIRTUAL hole (size preserved for the
|
|
1894
2298
|
// rotation pairing downstream); only true gap-band slots
|
|
1895
2299
|
// become side-neutral SPREAD.
|
|
1896
|
-
const holeGeoType = OrderUtils.geometryTypeForSlotIndex(
|
|
1897
|
-
? OrderUtils.parseSlotIndex(current?.id)
|
|
1898
|
-
: null, workingBoundaryIdx, gapSlots);
|
|
2300
|
+
const holeGeoType = OrderUtils.geometryTypeForSlotIndex(parseSlotIndex(current?.id), workingBoundaryIdx, gapSlots);
|
|
1899
2301
|
workingGrid.set(onChainOrder.id, (holeGeoType === ORDER_TYPES.BUY || holeGeoType === ORDER_TYPES.SELL)
|
|
1900
2302
|
? OrderUtils.toRailHolePlaceholder(current, holeGeoType)
|
|
1901
2303
|
: OrderUtils.convertToSpreadPlaceholder(current));
|