dexbot 1.7.1 → 1.7.3
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 +52 -0
- 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/grid_correction_check.d.ts +60 -1
- package/dist/analysis/grid_correction_check.js +268 -18
- package/dist/analysis/pivot_timeline.d.ts +78 -0
- package/dist/analysis/pivot_timeline.js +360 -0
- package/dist/market_adapter/utils/file_lock.js +16 -4
- package/dist/modules/account_bots.d.ts +7 -0
- package/dist/modules/account_bots.js +7 -5
- package/dist/modules/bot_defaults.js +6 -1
- package/dist/modules/constants.d.ts +14 -0
- package/dist/modules/constants.js +82 -2
- package/dist/modules/dexbot_class.d.ts +39 -0
- package/dist/modules/dexbot_class.js +86 -1
- package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
- package/dist/modules/dexbot_cow_runtime.js +299 -75
- package/dist/modules/dexbot_maintenance_runtime.d.ts +32 -2
- package/dist/modules/dexbot_maintenance_runtime.js +196 -16
- package/dist/modules/dexbot_state_recovery.js +15 -1
- package/dist/modules/launcher/instance_lock.d.ts +27 -0
- package/dist/modules/launcher/instance_lock.js +131 -0
- package/dist/modules/node_flap_score.d.ts +6 -6
- package/dist/modules/node_flap_score.js +6 -6
- package/dist/modules/order/accounting.d.ts +9 -4
- package/dist/modules/order/accounting.js +89 -26
- package/dist/modules/order/async_lock.d.ts +7 -1
- package/dist/modules/order/async_lock.js +7 -1
- package/dist/modules/order/export.js +25 -18
- package/dist/modules/order/fill_ledger.d.ts +99 -0
- package/dist/modules/order/fill_ledger.js +103 -0
- package/dist/modules/order/grid.d.ts +94 -18
- package/dist/modules/order/grid.js +247 -75
- package/dist/modules/order/grid_reconcile_internal.js +16 -4
- package/dist/modules/order/index.d.ts +29 -6
- package/dist/modules/order/index.js +5 -5
- package/dist/modules/order/lifecycle.js +3 -3
- package/dist/modules/order/manager.d.ts +36 -24
- package/dist/modules/order/manager.js +159 -39
- package/dist/modules/order/placement_lock.d.ts +30 -0
- package/dist/modules/order/placement_lock.js +48 -0
- package/dist/modules/order/sync_engine.d.ts +66 -118
- package/dist/modules/order/sync_engine.js +118 -162
- package/dist/modules/order/utils/math.d.ts +7 -3
- package/dist/modules/order/utils/math.js +7 -3
- package/dist/modules/order/utils/order.d.ts +79 -42
- package/dist/modules/order/utils/order.js +183 -86
- package/dist/modules/order/utils/system.d.ts +192 -8
- package/dist/modules/order/utils/system.js +534 -34
- package/dist/modules/paths.d.ts +1 -0
- package/dist/modules/paths.js +1 -0
- package/dist/modules/timing_policy.js +4 -2
- package/dist/modules/types.d.ts +49 -27
- package/dist/pm2.js +126 -0
- package/dist/unlock.js +26 -1
- package/docs/COW_INVARIANTS.md +5 -1
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECONCILE.md +3 -3
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +192 -31
- package/docs/README.md +1 -1
- package/docs/architecture.md +26 -8
- package/modules/README.md +4 -0
- package/package.json +4 -3
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Price derivation, persistence, grid correction, and UI/interactive utilities.
|
|
5
5
|
*
|
|
6
6
|
* ===============================================================================
|
|
7
|
-
* TABLE OF CONTENTS (
|
|
7
|
+
* TABLE OF CONTENTS (52 exported functions + 12 structural view types)
|
|
8
8
|
* ===============================================================================
|
|
9
9
|
*
|
|
10
10
|
* SECTION 1: PRICE DERIVATION (9 functions + 1 internal)
|
|
@@ -50,7 +50,20 @@
|
|
|
50
50
|
* - resetLastFillPivot(manager) - Clear the pivot to cold state
|
|
51
51
|
* - restoreLastFillPivot(manager) - Restore the persisted pivot into the manager
|
|
52
52
|
*
|
|
53
|
-
* SECTION 7:
|
|
53
|
+
* SECTION 7: FILL PIPELINE & LAST-FILL GUARD (9 functions)
|
|
54
|
+
* - reanchorBoundaryFromLastFill(manager, ...) - Re-anchor a rebuilt boundary to the last fill
|
|
55
|
+
* - rearmLastFillPivotFromMarketFill(manager) - Re-arm the pivot from the last market fill
|
|
56
|
+
* - isLastFillGuardBlocked(price, type, lastPrice, lastType) - LAST-FILL-GUARD direction predicate
|
|
57
|
+
* - isLastFillBandSellExempt(manager, price) - Geometry territory for a SELL counter-order
|
|
58
|
+
* - evaluateLastFillGuard(manager, price, type, pivot, pivotType) - Shared placement verdict
|
|
59
|
+
* - isLastFillPlacementBlocked(manager, price, type) - Placement-side LAST-FILL-GUARD wrapper
|
|
60
|
+
* - readFillPipelineState(source) - Projection of the fill-pipeline state
|
|
61
|
+
* - resolveGridUpdateBlockers(source, options) - Blockers that forbid a grid update right now
|
|
62
|
+
* - noteGridUpdateBlockers(...) - Log/record the blockers for one decision
|
|
63
|
+
* - hasUnsettledFills(source) - Whether any fill is still unsettled (with a reason)
|
|
64
|
+
* - getPipelineInFlightAgeMs(source, nowMs) - Age of the oldest in-flight pipeline work
|
|
65
|
+
*
|
|
66
|
+
* SECTION 8: UI & INTERACTIVE UTILITIES (6 functions)
|
|
54
67
|
* - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
|
|
55
68
|
* - sleep(ms) - Pause execution for specified duration
|
|
56
69
|
* - readInput(prompt, options) - Read user input from stdin
|
|
@@ -59,7 +72,7 @@
|
|
|
59
72
|
* - withBlockchainRetry(fn, label, options) - Blockchain op with timeout + retry + node failover
|
|
60
73
|
* (withTimeout lives in ./timeout)
|
|
61
74
|
*
|
|
62
|
-
* SECTION
|
|
75
|
+
* SECTION 9: GENERAL UTILITIES (7 functions)
|
|
63
76
|
* - resolveAccountRef(manager, account) - Resolve best account reference
|
|
64
77
|
* - deepFreeze(obj) - Recursively freeze object for immutability
|
|
65
78
|
* - cloneMap(map) - Create shallow clone of Map
|
|
@@ -70,8 +83,8 @@
|
|
|
70
83
|
*
|
|
71
84
|
* STRUCTURAL VIEW TYPES:
|
|
72
85
|
* AssetMeta, PoolReserve, PoolEntry, BitSharesClient, AmaCenterSnapshot,
|
|
73
|
-
* FeeCacheEntryData,
|
|
74
|
-
*
|
|
86
|
+
* FeeCacheEntryData, SpreadCorrectionReadiness, GridUpdateBlockerCode,
|
|
87
|
+
* GridUpdateBlocker, FillPipelineState, GridResizeResult, CowResult
|
|
75
88
|
*
|
|
76
89
|
* ===============================================================================
|
|
77
90
|
*/
|
|
@@ -80,7 +93,7 @@ const require = createRequire(import.meta.url);
|
|
|
80
93
|
import { path } from '../../path_api.js';
|
|
81
94
|
import { getStorage } from '../../storage/index.js';
|
|
82
95
|
const storage = getStorage();
|
|
83
|
-
import { API_LIMITS, ORDER_TYPES, ORDER_STATES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
|
|
96
|
+
import { API_LIMITS, ORDER_TYPES, ORDER_STATES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING, FILL_PROCESSING } from '../../constants.js';
|
|
84
97
|
import { PATHS } from '../../paths.js';
|
|
85
98
|
import { toFiniteNumber, isValidNumber, toKnownNumber } from '../format.js';
|
|
86
99
|
import * as MathUtils from './math.js';
|
|
@@ -863,6 +876,9 @@ export async function initializeFeeCache(botsConfig, BitShares) {
|
|
|
863
876
|
(hasDiskFallback ? '. Using previously cached value from disk.' : '.'));
|
|
864
877
|
}
|
|
865
878
|
}
|
|
879
|
+
// The math-side fee-cache entry is a narrower structural view of the same
|
|
880
|
+
// row this module persists. Cast through the setter's own parameter type
|
|
881
|
+
// instead of naming a type that is not exported from utils/math.ts.
|
|
866
882
|
MathUtils._setFeeCache(cache);
|
|
867
883
|
_saveFeeCacheToDisk(cache);
|
|
868
884
|
return cache;
|
|
@@ -1719,6 +1735,185 @@ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
|
|
|
1719
1735
|
return { blocked: true, pivot, threshold: pivot };
|
|
1720
1736
|
return { blocked: false, pivot: null, threshold: null };
|
|
1721
1737
|
}
|
|
1738
|
+
/**
|
|
1739
|
+
* REFUSED-LEVEL SAME-LEVEL RE-FILL BLOCK (§9.12/P2 amended, 2026-11-16).
|
|
1740
|
+
*
|
|
1741
|
+
* A fill the pivot-arming policy refused (wrong-side / too-far premium sweep)
|
|
1742
|
+
* does not arm the direction pivot — deliberately, so the guard keeps trading
|
|
1743
|
+
* around the live market instead of deadlocking the side for the pivot TTL.
|
|
1744
|
+
* But the same-level re-fill refusal (§9.12/P2: "the exact pivot level remains
|
|
1745
|
+
* blocked as a same-level re-fill") keys off the ARMED pivot, so the P1
|
|
1746
|
+
* refusal silently suspended it: a spread-correction slot could be re-armed at
|
|
1747
|
+
* the identical level and refill immediately, in a loop, for as long as a
|
|
1748
|
+
* taker kept lifting it.
|
|
1749
|
+
*
|
|
1750
|
+
* This predicate closes that gap with a SEPARATE, minimal role: the refused
|
|
1751
|
+
* fill's own level, same side only, within half a grid step (the same
|
|
1752
|
+
* pricesWithinHalfStep test isLastFillPlacementBlocked uses), for a short
|
|
1753
|
+
* in-memory TTL (GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS). It vetoes exactly
|
|
1754
|
+
* one price level — the just-filled one — and nothing else: the counter-side
|
|
1755
|
+
* stays governed by the (older) direction pivot and spread correction can
|
|
1756
|
+
* still trade around the live market, so the unquoted-side deadlock P1 was
|
|
1757
|
+
* written against cannot re-open through it. Fail-open on anything unreadable.
|
|
1758
|
+
*
|
|
1759
|
+
* @param {Object} manager - OrderManager instance
|
|
1760
|
+
* @param {number} price - Candidate placement price
|
|
1761
|
+
* @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
|
|
1762
|
+
* @returns {{blocked: boolean, level: number|null}} Verdict + the refused level
|
|
1763
|
+
*/
|
|
1764
|
+
export function isRefusedLevelRefillBlocked(manager, price, type) {
|
|
1765
|
+
const p = Number(price);
|
|
1766
|
+
const level = Number(manager?._lastRefusedFillPrice);
|
|
1767
|
+
const at = Number(manager?._lastRefusedFillAt);
|
|
1768
|
+
const refType = manager?._lastRefusedFillType;
|
|
1769
|
+
if (!Number.isFinite(p) || !Number.isFinite(level) || level <= 0)
|
|
1770
|
+
return { blocked: false, level: null };
|
|
1771
|
+
if (refType !== ORDER_TYPES.BUY && refType !== ORDER_TYPES.SELL)
|
|
1772
|
+
return { blocked: false, level: null };
|
|
1773
|
+
if (type !== refType)
|
|
1774
|
+
return { blocked: false, level };
|
|
1775
|
+
const ttl = Number(GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS);
|
|
1776
|
+
if (!(ttl > 0) || !Number.isFinite(at) || at <= 0 || (Date.now() - at) > ttl)
|
|
1777
|
+
return { blocked: false, level };
|
|
1778
|
+
let sameLevel = false;
|
|
1779
|
+
try {
|
|
1780
|
+
sameLevel = MathUtils.pricesWithinHalfStep(p, level, Number(manager?.config?.incrementPercent));
|
|
1781
|
+
}
|
|
1782
|
+
catch {
|
|
1783
|
+
sameLevel = p === level;
|
|
1784
|
+
}
|
|
1785
|
+
return { blocked: sameLevel, level };
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* The direction rule PLUS the geometry-territory exemption — the verdict
|
|
1789
|
+
* every COW-path guard shares (probe and final gate), so no site re-implements
|
|
1790
|
+
* "may this op be placed against the last fill?".
|
|
1791
|
+
*
|
|
1792
|
+
* Also applies the REFUSED-LEVEL same-level re-fill block (§9.12/P2 amended):
|
|
1793
|
+
* a placement on the same side within half a grid step of a fill whose
|
|
1794
|
+
* pivot-arm was refused stays blocked even though the direction pivot itself
|
|
1795
|
+
* stayed behind that fill. See isRefusedLevelRefillBlocked.
|
|
1796
|
+
*
|
|
1797
|
+
* @param {Object} manager - OrderManager instance (geometry for the exemption)
|
|
1798
|
+
* @param {number} price - Target price
|
|
1799
|
+
* @param {string} type - ORDER_TYPES.BUY/SELL
|
|
1800
|
+
* @param {number|null} pivotPrice - Resolved pivot (already ladder-snapped by the caller)
|
|
1801
|
+
* @param {string|null} pivotType - Pivot side; null keeps the guard cold
|
|
1802
|
+
* @returns {{blocked: boolean, pivot: number|null, threshold?: number|null, bandExempt?: boolean, refusedLevel?: boolean}}
|
|
1803
|
+
*/
|
|
1804
|
+
export function evaluateLastFillGuard(manager, price, type, pivotPrice, pivotType) {
|
|
1805
|
+
const check = isLastFillGuardBlocked(price, type, pivotPrice, pivotType);
|
|
1806
|
+
let verdict;
|
|
1807
|
+
if (!check.blocked)
|
|
1808
|
+
verdict = check;
|
|
1809
|
+
else if (type === ORDER_TYPES.SELL && isLastFillBandSellExempt(manager, price)) {
|
|
1810
|
+
verdict = { blocked: false, pivot: check.pivot, bandExempt: true };
|
|
1811
|
+
}
|
|
1812
|
+
else
|
|
1813
|
+
verdict = check;
|
|
1814
|
+
if (!verdict.blocked) {
|
|
1815
|
+
const refused = isRefusedLevelRefillBlocked(manager, price, type);
|
|
1816
|
+
if (refused.blocked) {
|
|
1817
|
+
return { blocked: true, pivot: refused.level, threshold: refused.level, refusedLevel: true };
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
return verdict;
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
*
|
|
1824
|
+
* The direction rule (isLastFillGuardBlocked) says "never sell at/below the last
|
|
1825
|
+
* sale". That is right when the veto is evidence of a fault — retrospective
|
|
1826
|
+
* §9.7/§9.9: "a sell slot below the last sale is evidence that the boundary/
|
|
1827
|
+
* crawl is behind the fill". It is WRONG when the geometry is exactly where the
|
|
1828
|
+
* fill re-anchor puts it: after a SELL fill at slot f the re-anchor rule is
|
|
1829
|
+
* `boundary >= f - gapSlots`, so the gap band (boundary, boundary+gap] tops out
|
|
1830
|
+
* AT the filled level and every band slot is `<= pivot` by construction. The
|
|
1831
|
+
* pivot then vetoes 100% of the counter-order rungs it just derived.
|
|
1832
|
+
*
|
|
1833
|
+
* Live (2026-11-15): a sweep armed the pivot at the band's own top level; every
|
|
1834
|
+
* sell slot in the band was refused as "at/through the last fill", no sell
|
|
1835
|
+
* could be re-placed, and the spread stayed 3.0% (limit 1.65%) for 86 minutes
|
|
1836
|
+
* until an operator-visible watchdog ran out of options.
|
|
1837
|
+
*
|
|
1838
|
+
* The exemption is a GEOMETRY fact, not a second direction rule: it applies
|
|
1839
|
+
* - SELL only. The BUY mirror is deliberately absent — after a BUY fill the
|
|
1840
|
+
* band sits ABOVE the fill, and buys above the last buy are the chase class
|
|
1841
|
+
* the guard was introduced for (§9.7 "buying later at higher prices").
|
|
1842
|
+
* - inside the band only (boundary < idx <= boundary + gap),
|
|
1843
|
+
* - strictly below the pivot's own ladder level (the pivot level itself is
|
|
1844
|
+
* always refused as a same-level re-fill),
|
|
1845
|
+
* - only when the boundary already satisfies the fill anchor
|
|
1846
|
+
* (`boundary >= pivotIdx - gapSlots`), i.e. the geometry is NOT behind the
|
|
1847
|
+
* fill — the precise precondition §9.7 names for the refusal.
|
|
1848
|
+
* Fail-closed on anything unprovable (no genesis, off-ladder price, unknown
|
|
1849
|
+
* boundary/gap).
|
|
1850
|
+
*
|
|
1851
|
+
* @param {Object} manager - OrderManager instance (pivot + boundary + gap + genesis)
|
|
1852
|
+
* @param {number} price - SELL placement price
|
|
1853
|
+
* @returns {boolean} True when the pivot must NOT veto this placement
|
|
1854
|
+
*/
|
|
1855
|
+
export function isLastFillBandSellExempt(manager, price) {
|
|
1856
|
+
if (!manager)
|
|
1857
|
+
return false;
|
|
1858
|
+
const p = Number(price);
|
|
1859
|
+
if (!Number.isFinite(p) || p <= 0)
|
|
1860
|
+
return false;
|
|
1861
|
+
let ref = { price: null, type: null };
|
|
1862
|
+
try {
|
|
1863
|
+
ref = resolveFillProvenancedReference(manager);
|
|
1864
|
+
}
|
|
1865
|
+
catch {
|
|
1866
|
+
return false;
|
|
1867
|
+
}
|
|
1868
|
+
if (ref.type !== ORDER_TYPES.SELL || ref.price == null || !Number.isFinite(Number(ref.price)))
|
|
1869
|
+
return false;
|
|
1870
|
+
const genesis = manager._genesis;
|
|
1871
|
+
const levels = genesis?.priceLevels;
|
|
1872
|
+
if (!Array.isArray(levels) || levels.length === 0)
|
|
1873
|
+
return false;
|
|
1874
|
+
const gapRaw = manager._gapSlots;
|
|
1875
|
+
const gap = Number(gapRaw);
|
|
1876
|
+
const boundary = Number(manager.boundaryIdx);
|
|
1877
|
+
if (!Number.isFinite(gap) || gap < 0 || !Number.isFinite(boundary))
|
|
1878
|
+
return false;
|
|
1879
|
+
const lo = Number(levels[0]);
|
|
1880
|
+
const hi = Number(levels[levels.length - 1]);
|
|
1881
|
+
const inRail = (v) => Number.isFinite(v) && v >= lo && v <= hi;
|
|
1882
|
+
if (!inRail(p) || !inRail(Number(ref.price)))
|
|
1883
|
+
return false;
|
|
1884
|
+
let pivotIdx;
|
|
1885
|
+
let candIdx;
|
|
1886
|
+
try {
|
|
1887
|
+
const g = genesis;
|
|
1888
|
+
pivotIdx = Number(MathUtils.slotIndexForPrice(Number(ref.price), g));
|
|
1889
|
+
candIdx = Number(MathUtils.slotIndexForPrice(p, g));
|
|
1890
|
+
}
|
|
1891
|
+
catch {
|
|
1892
|
+
return false;
|
|
1893
|
+
}
|
|
1894
|
+
if (!Number.isFinite(pivotIdx) || !Number.isFinite(candIdx))
|
|
1895
|
+
return false;
|
|
1896
|
+
// Only a genuine ladder level: same one-increment drift bound the re-anchor
|
|
1897
|
+
// uses, so an adopted/orphan price cannot invent an exemption.
|
|
1898
|
+
const incRaw = Number(manager.config?.incrementPercent);
|
|
1899
|
+
const maxDrift = Number.isFinite(incRaw) && incRaw > 0 ? incRaw / 100 : 0.005;
|
|
1900
|
+
let levelPrice;
|
|
1901
|
+
try {
|
|
1902
|
+
levelPrice = Number(MathUtils.priceForSlot(candIdx, genesis));
|
|
1903
|
+
}
|
|
1904
|
+
catch {
|
|
1905
|
+
return false;
|
|
1906
|
+
}
|
|
1907
|
+
if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - p) / p > maxDrift)
|
|
1908
|
+
return false;
|
|
1909
|
+
if (candIdx <= boundary)
|
|
1910
|
+
return false;
|
|
1911
|
+
if (candIdx > boundary + Math.floor(gap))
|
|
1912
|
+
return false;
|
|
1913
|
+
if (candIdx >= pivotIdx)
|
|
1914
|
+
return false;
|
|
1915
|
+
return boundary >= pivotIdx - Math.floor(gap);
|
|
1916
|
+
}
|
|
1722
1917
|
/**
|
|
1723
1918
|
* LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
|
|
1724
1919
|
*
|
|
@@ -1736,10 +1931,14 @@ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
|
|
|
1736
1931
|
* prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
|
|
1737
1932
|
* still builds.
|
|
1738
1933
|
*
|
|
1934
|
+
* The SELL band exemption (isLastFillBandSellExempt) is applied between the two
|
|
1935
|
+
* rules: a re-place at the traded level stays blocked, a band counter-order is
|
|
1936
|
+
* not.
|
|
1937
|
+
*
|
|
1739
1938
|
* @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
|
|
1740
1939
|
* @param {number} price - Target placement price
|
|
1741
1940
|
* @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
|
|
1742
|
-
* @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
|
|
1941
|
+
* @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'|'refused-level'}}
|
|
1743
1942
|
*/
|
|
1744
1943
|
export function isLastFillPlacementBlocked(manager, price, type) {
|
|
1745
1944
|
const numPrice = Number(price);
|
|
@@ -1754,8 +1953,17 @@ export function isLastFillPlacementBlocked(manager, price, type) {
|
|
|
1754
1953
|
}
|
|
1755
1954
|
const pivot = reference.price;
|
|
1756
1955
|
const pivotType = reference.type;
|
|
1757
|
-
if (pivot == null || pivotType == null)
|
|
1956
|
+
if (pivot == null || pivotType == null) {
|
|
1957
|
+
// Cold direction pivot: a refused (off-market) fill marker can still be
|
|
1958
|
+
// live and must keep blocking the same-level re-fill (§9.12/P2 amended).
|
|
1959
|
+
try {
|
|
1960
|
+
const refused = isRefusedLevelRefillBlocked(manager, numPrice, type);
|
|
1961
|
+
if (refused.blocked)
|
|
1962
|
+
return { blocked: true, pivot: refused.level, reason: 'refused-level' };
|
|
1963
|
+
}
|
|
1964
|
+
catch { /* fail-open */ }
|
|
1758
1965
|
return { blocked: false, pivot: null };
|
|
1966
|
+
}
|
|
1759
1967
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
1760
1968
|
return { blocked: false, pivot };
|
|
1761
1969
|
try {
|
|
@@ -1764,14 +1972,153 @@ export function isLastFillPlacementBlocked(manager, price, type) {
|
|
|
1764
1972
|
}
|
|
1765
1973
|
}
|
|
1766
1974
|
catch { /* fall through to the direction rule */ }
|
|
1767
|
-
const guard =
|
|
1975
|
+
const guard = evaluateLastFillGuard(manager, numPrice, type, pivot, pivotType);
|
|
1768
1976
|
if (guard.blocked)
|
|
1769
|
-
return { blocked: true, pivot, reason: 'direction' };
|
|
1977
|
+
return { blocked: true, pivot: guard.pivot, reason: guard.refusedLevel ? 'refused-level' : 'direction' };
|
|
1770
1978
|
return { blocked: false, pivot };
|
|
1771
1979
|
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Read the fill-pipeline counters ONCE, from a bot or a bare manager.
|
|
1982
|
+
*
|
|
1983
|
+
* This is the only place that peeks these fields. The previous projection
|
|
1984
|
+
* (`hasUnsettledFills`) swallowed every read error and returned "settled",
|
|
1985
|
+
* which is a fail-OPEN answer in a fail-closed system: an unreadable queue
|
|
1986
|
+
* looked like an idle one and the grid was updated from a stale master.
|
|
1987
|
+
* Unreadable is now a first-class state (`ok: false`), surfaced as
|
|
1988
|
+
* `unknown-blocker`.
|
|
1989
|
+
*
|
|
1990
|
+
* These counters are pipeline bookkeeping, not lifecycle evidence: absence
|
|
1991
|
+
* decisions still use the lifecycle registry (INV-LIFE-003), so this reader
|
|
1992
|
+
* cannot become a second evidence set.
|
|
1993
|
+
*/
|
|
1994
|
+
export function readFillPipelineState(source) {
|
|
1995
|
+
const settled = { ok: true, queued: 0, deferred: false, inFlight: 0, owed: 0 };
|
|
1996
|
+
if (!source || typeof source !== 'object')
|
|
1997
|
+
return settled;
|
|
1998
|
+
try {
|
|
1999
|
+
const outer = source;
|
|
2000
|
+
const mgr = (outer.manager && typeof outer.manager === 'object'
|
|
2001
|
+
? outer.manager
|
|
2002
|
+
: outer);
|
|
2003
|
+
const queue = outer._incomingFillQueue;
|
|
2004
|
+
if (queue !== undefined && queue !== null && !Array.isArray(queue)) {
|
|
2005
|
+
return { ...settled, ok: false, error: '_incomingFillQueue is not an array' };
|
|
2006
|
+
}
|
|
2007
|
+
const crawls = mgr._pendingFillCrawls;
|
|
2008
|
+
if (crawls !== undefined && crawls !== null && !Array.isArray(crawls)) {
|
|
2009
|
+
return { ...settled, ok: false, error: '_pendingFillCrawls is not an array' };
|
|
2010
|
+
}
|
|
2011
|
+
const inFlightRaw = mgr._fillBatchInFlight;
|
|
2012
|
+
const inFlight = Number(inFlightRaw);
|
|
2013
|
+
if (inFlightRaw !== undefined && inFlightRaw !== null && !Number.isFinite(inFlight)) {
|
|
2014
|
+
return { ...settled, ok: false, error: '_fillBatchInFlight is not a number' };
|
|
2015
|
+
}
|
|
2016
|
+
return {
|
|
2017
|
+
ok: true,
|
|
2018
|
+
queued: Array.isArray(queue) ? queue.length : 0,
|
|
2019
|
+
deferred: outer._deferredFillsPending === true,
|
|
2020
|
+
inFlight: Number.isFinite(inFlight) && inFlight > 0 ? inFlight : 0,
|
|
2021
|
+
owed: Array.isArray(crawls) ? crawls.length : 0,
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
catch (err) {
|
|
2025
|
+
return { ok: false, queued: 0, deferred: false, inFlight: 0, owed: 0, error: getErrorMessage(err) };
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Every reason the grid must NOT be mutated this cycle, as codes.
|
|
2030
|
+
*
|
|
2031
|
+
* Composition only — no new evidence: the fill counters come from
|
|
2032
|
+
* `readFillPipelineState`, the broadcast policy from `getLivePendingBroadcasts`
|
|
2033
|
+
* (INV-BROADCAST-005), the region from `isPlacementActive`, the rebuild flag
|
|
2034
|
+
* from the manager. A grid blocker (may the grid mutate?) is deliberately NOT
|
|
2035
|
+
* the per-action fresh-placement grace and NOT a known-wrong-side fact; those
|
|
2036
|
+
* stay with the planner and the correction queue (INV-RECON-006).
|
|
2037
|
+
*/
|
|
2038
|
+
function fillStateBlockers(state) {
|
|
2039
|
+
if (!state.ok) {
|
|
2040
|
+
return [{ code: 'unknown-blocker', detail: state.error || 'fill pipeline state unreadable' }];
|
|
2041
|
+
}
|
|
2042
|
+
const blockers = [];
|
|
2043
|
+
if (state.queued > 0)
|
|
2044
|
+
blockers.push({ code: 'fill-queued', detail: `${state.queued} fill(s) queued for processing` });
|
|
2045
|
+
if (state.deferred)
|
|
2046
|
+
blockers.push({ code: 'fill-deferred', detail: 'deferred fill drain pending' });
|
|
2047
|
+
if (state.inFlight > 0)
|
|
2048
|
+
blockers.push({ code: 'fill-in-flight', detail: 'fill batch in flight' });
|
|
2049
|
+
if (state.owed > 0)
|
|
2050
|
+
blockers.push({ code: 'crawl-owed', detail: `${state.owed} owed boundary crawl(s)` });
|
|
2051
|
+
return blockers;
|
|
2052
|
+
}
|
|
2053
|
+
export function resolveGridUpdateBlockers(source, options = {}) {
|
|
2054
|
+
const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
|
|
2055
|
+
const blockers = fillStateBlockers(readFillPipelineState(source));
|
|
2056
|
+
if (!source || typeof source !== 'object')
|
|
2057
|
+
return blockers;
|
|
2058
|
+
const outer = source;
|
|
2059
|
+
const mgr = (outer.manager && typeof outer.manager === 'object' ? outer.manager : source);
|
|
2060
|
+
try {
|
|
2061
|
+
if (typeof mgr.isPlacementActive === 'function' && mgr.isPlacementActive() === true) {
|
|
2062
|
+
const kind = typeof mgr.placementKind === 'function' ? mgr.placementKind() : '';
|
|
2063
|
+
blockers.push({ code: 'placement-held', detail: `placement region held by ${kind || 'unknown'}` });
|
|
2064
|
+
}
|
|
2065
|
+
if (typeof mgr.isStructuralRebuildInProgress === 'function' && mgr.isStructuralRebuildInProgress() === true) {
|
|
2066
|
+
blockers.push({ code: 'rebuild-active', detail: 'structural rebuild in progress' });
|
|
2067
|
+
}
|
|
2068
|
+
// Read-only: a predicate must not GC the pending set or emit log lines.
|
|
2069
|
+
const pending = OrderUtils.getLivePendingBroadcasts(mgr, { now, gc: false });
|
|
2070
|
+
const pendingCount = Array.isArray(pending) ? pending.length : 0;
|
|
2071
|
+
if (pendingCount > 0) {
|
|
2072
|
+
blockers.push({ code: 'broadcast-pending', detail: `${pendingCount} unresolved broadcast(s)` });
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
catch (err) {
|
|
2076
|
+
if (!blockers.some((b) => b.code === 'unknown-blocker')) {
|
|
2077
|
+
blockers.push({ code: 'unknown-blocker', detail: `blocker probe failed: ${getErrorMessage(err)}` });
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
return blockers;
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* Count consecutive blocked cycles and decide whether the state is STUCK.
|
|
2084
|
+
*
|
|
2085
|
+
* Escalation is deliberately narrow: only `unknown-blocker` (unreadable
|
|
2086
|
+
* pipeline state) escalates. A busy pipeline (`fill-in-flight`,
|
|
2087
|
+
* `broadcast-pending`, a held region) is normal work and must not trigger a
|
|
2088
|
+
* structural resync — the placement/broadcast watchdogs own those bounds. The
|
|
2089
|
+
* counter is a cycle count, not a timing window: it is NOT a `TIMING` entry and
|
|
2090
|
+
* must not be classified in `modules/timing_policy.ts`.
|
|
2091
|
+
*
|
|
2092
|
+
* @returns `{ cycles, escalate }`; `escalate` is true exactly when the state
|
|
2093
|
+
* stayed unreadable for `FILL_PROCESSING.GRID_BLOCKED_ESCALATE_CYCLES`
|
|
2094
|
+
* consecutive attempts.
|
|
2095
|
+
*/
|
|
2096
|
+
export function noteGridUpdateBlockers(source, blockers, options = {}) {
|
|
2097
|
+
if (!source || typeof source !== 'object')
|
|
2098
|
+
return { cycles: 0, escalate: false };
|
|
2099
|
+
const holder = source.manager && typeof source.manager === 'object'
|
|
2100
|
+
? source.manager
|
|
2101
|
+
: source;
|
|
2102
|
+
const list = Array.isArray(blockers) ? blockers : [];
|
|
2103
|
+
const unreadable = list.some((b) => b && b.code === 'unknown-blocker');
|
|
2104
|
+
if (list.length === 0 || !unreadable) {
|
|
2105
|
+
holder._gridUpdateBlockedCycles = 0;
|
|
2106
|
+
return { cycles: 0, escalate: false };
|
|
2107
|
+
}
|
|
2108
|
+
const prev = Number(holder._gridUpdateBlockedCycles);
|
|
2109
|
+
const cycles = (Number.isFinite(prev) && prev > 0 ? prev : 0) + 1;
|
|
2110
|
+
holder._gridUpdateBlockedCycles = cycles;
|
|
2111
|
+
const rawLimit = Number(options.limit ?? FILL_PROCESSING.GRID_BLOCKED_ESCALATE_CYCLES);
|
|
2112
|
+
const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? rawLimit : 12;
|
|
2113
|
+
return { cycles, escalate: cycles >= limit };
|
|
2114
|
+
}
|
|
1772
2115
|
/**
|
|
1773
2116
|
* Are fills still UNSETTLED (arrived but not yet absorbed by the grid)?
|
|
1774
2117
|
*
|
|
2118
|
+
* Projection over `resolveGridUpdateBlockers` so the prose reason and the code
|
|
2119
|
+
* cannot disagree. Kept as a boolean for its existing callers; new callers
|
|
2120
|
+
* should ask for the codes.
|
|
2121
|
+
*
|
|
1775
2122
|
* While this returns true the master grid still holds filled slots as ACTIVE
|
|
1776
2123
|
* and the boundary has not crawled for them, so any geometry-derived plan
|
|
1777
2124
|
* (window top-up, startup-style reconcile) is built on the PREVIOUS book. The
|
|
@@ -1786,29 +2133,14 @@ export function isLastFillPlacementBlocked(manager, price, type) {
|
|
|
1786
2133
|
* @returns {{unsettled: boolean, reason: string|null}}
|
|
1787
2134
|
*/
|
|
1788
2135
|
export function hasUnsettledFills(source) {
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
try {
|
|
1796
|
-
const queued = Array.isArray(outer._incomingFillQueue) ? outer._incomingFillQueue.length : 0;
|
|
1797
|
-
if (queued > 0)
|
|
1798
|
-
return { unsettled: true, reason: `${queued} fill(s) queued for processing` };
|
|
1799
|
-
if (outer._deferredFillsPending === true)
|
|
1800
|
-
return { unsettled: true, reason: 'deferred fill drain pending' };
|
|
1801
|
-
const inFlight = Number(mgr._fillBatchInFlight);
|
|
1802
|
-
if (Number.isFinite(inFlight) && inFlight > 0)
|
|
1803
|
-
return { unsettled: true, reason: 'fill batch in flight' };
|
|
1804
|
-
const owed = Array.isArray(mgr._pendingFillCrawls) ? mgr._pendingFillCrawls.length : 0;
|
|
1805
|
-
if (owed > 0)
|
|
1806
|
-
return { unsettled: true, reason: `${owed} owed boundary crawl(s)` };
|
|
1807
|
-
}
|
|
1808
|
-
catch {
|
|
2136
|
+
// Fill state only: this predicate answers "have the fills settled?", not
|
|
2137
|
+
// "is the host busy?" (placement/broadcast/rebuild are the full resolver's
|
|
2138
|
+
// business). A projection that pulled the host codes in would report fills
|
|
2139
|
+
// unsettled whenever, say, a placement probe threw.
|
|
2140
|
+
const fill = fillStateBlockers(readFillPipelineState(source))[0];
|
|
2141
|
+
if (!fill)
|
|
1809
2142
|
return { unsettled: false, reason: null };
|
|
1810
|
-
}
|
|
1811
|
-
return { unsettled: false, reason: null };
|
|
2143
|
+
return { unsettled: true, reason: fill.detail };
|
|
1812
2144
|
}
|
|
1813
2145
|
/**
|
|
1814
2146
|
* Age of the most recent bot-level pipeline raise.
|
|
@@ -1997,6 +2329,78 @@ export function normalizeLastFillPivot(row) {
|
|
|
1997
2329
|
export function normalizeLastMarketFill(row) {
|
|
1998
2330
|
return normalizeFillRow(row);
|
|
1999
2331
|
}
|
|
2332
|
+
/**
|
|
2333
|
+
* LAST-FILL-PIVOT MARKET BOUND — is this fill evidence of the CURRENT window,
|
|
2334
|
+
* or of something else? Two legs, one reference:
|
|
2335
|
+
*
|
|
2336
|
+
* wrong-side BUY above mid / SELL below mid (past the one-step tolerance).
|
|
2337
|
+
* Fills at/through the opposite side of the book cannot happen on
|
|
2338
|
+
* an honest market — a crossed-book artifact (typically the
|
|
2339
|
+
* bot's own misplaced order swept by an external taker).
|
|
2340
|
+
* too-far Either side, further than
|
|
2341
|
+
* GRID_LIMITS.LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS increments
|
|
2342
|
+
* from the mid. Live: a taker swept our rail up to a level 14.5
|
|
2343
|
+
* steps (4.4%) ABOVE the mid and EVERY one of those fills is on
|
|
2344
|
+
* the honest side by direction, so the wrong-side leg let them
|
|
2345
|
+
* through; the top one armed the pivot at the band's own top,
|
|
2346
|
+
* vetoing every sell the geometry had just derived and freeing
|
|
2347
|
+
* nothing for 86 minutes. A premium sweep is not a window trade.
|
|
2348
|
+
*
|
|
2349
|
+
* Both legs judge against the cached live market price, and only while it is
|
|
2350
|
+
* fresh (GRID_LIMITS.LAST_FILL_PIVOT_MARKET_FRESH_MS) — fail-open otherwise.
|
|
2351
|
+
* The reference is deliberately the BOOK read, not the fill-derived one: a
|
|
2352
|
+
* trade must be judged against the quotes it traded through, never against
|
|
2353
|
+
* itself (which would make the bound self-satisfying).
|
|
2354
|
+
*
|
|
2355
|
+
* @param {Object} manager - OrderManager instance
|
|
2356
|
+
* @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
|
|
2357
|
+
* @param {number} price - Fill price
|
|
2358
|
+
* @returns {{ steps: number, mid: number, kind?: 'wrong-side'|'too-far' } | null}
|
|
2359
|
+
* Off-market detail, or null when the fill is window evidence / unknowable
|
|
2360
|
+
*/
|
|
2361
|
+
function offMarketFill(manager, type, price) {
|
|
2362
|
+
const mid = Number(manager?._liveMarketPrice);
|
|
2363
|
+
const midAt = Number(manager?._liveMarketPriceAt);
|
|
2364
|
+
if (!Number.isFinite(mid) || mid <= 0)
|
|
2365
|
+
return null;
|
|
2366
|
+
if (!Number.isFinite(midAt) || midAt <= 0)
|
|
2367
|
+
return null;
|
|
2368
|
+
const freshMs = Number(GRID_LIMITS.LAST_FILL_PIVOT_MARKET_FRESH_MS);
|
|
2369
|
+
if (!(freshMs > 0) || (Date.now() - midAt) > freshMs)
|
|
2370
|
+
return null;
|
|
2371
|
+
const incRaw = Number(manager?.config?.incrementPercent);
|
|
2372
|
+
const stepPct = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 0.5;
|
|
2373
|
+
const step = 1 + (stepPct / 100);
|
|
2374
|
+
const tolerance = Number(GRID_LIMITS.LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS);
|
|
2375
|
+
const tol = Number.isFinite(tolerance) && tolerance >= 0 ? tolerance : 1;
|
|
2376
|
+
// Relative epsilon so "exactly N steps above mid" is not refused by
|
|
2377
|
+
// floating-point drift in Math.pow (1000 * 1.005 === 1004.9999999999999).
|
|
2378
|
+
const eps = mid * 1e-9;
|
|
2379
|
+
if (type === ORDER_TYPES.BUY) {
|
|
2380
|
+
const limit = mid * Math.pow(step, tol);
|
|
2381
|
+
if (price > limit + eps) {
|
|
2382
|
+
return { steps: Math.max(1, Math.round(Math.log(price / mid) / Math.log(step))), mid, kind: 'wrong-side' };
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
else {
|
|
2386
|
+
const limit = mid / Math.pow(step, tol);
|
|
2387
|
+
if (price < limit - eps) {
|
|
2388
|
+
return { steps: Math.max(1, Math.round(Math.log(mid / price) / Math.log(step))), mid, kind: 'wrong-side' };
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
// Second leg: a fill inside the direction tolerance can still be a premium
|
|
2392
|
+
// sweep (a taker paying through several of our levels). Distance is judged
|
|
2393
|
+
// symmetrically — both sides are equally far from the market.
|
|
2394
|
+
const maxStepsRaw = Number(GRID_LIMITS.LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS);
|
|
2395
|
+
const maxSteps = Number.isFinite(maxStepsRaw) && maxStepsRaw > 0 ? maxStepsRaw : 0;
|
|
2396
|
+
if (maxSteps > 0) {
|
|
2397
|
+
const dist = Math.abs(Math.log(price / mid) / Math.log(step));
|
|
2398
|
+
if (dist > maxSteps + 1e-9) {
|
|
2399
|
+
return { steps: Math.max(1, Math.round(dist)), mid, kind: 'too-far' };
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
return null;
|
|
2403
|
+
}
|
|
2000
2404
|
/**
|
|
2001
2405
|
* Write the LAST-FILL-GUARD pivot scalar family in one place (free
|
|
2002
2406
|
* implementation shared by the manager method, cow_runtime's queued-fill
|
|
@@ -2024,6 +2428,48 @@ export function setLastFillPivot(manager, type, price, provenance, atMs) {
|
|
|
2024
2428
|
const p = Number(price);
|
|
2025
2429
|
if (!Number.isFinite(p) || p <= 0)
|
|
2026
2430
|
return false;
|
|
2431
|
+
// LAST-FILL-PIVOT MARKET BOUND (fill provenance only): a real fill may arm
|
|
2432
|
+
// the guard only when it is evidence of the CURRENT window — on the
|
|
2433
|
+
// market's own side of the live reference AND within a full spread of it.
|
|
2434
|
+
// A wrong-side fill is a crossed-book artifact; a fill many steps away on
|
|
2435
|
+
// the honest side is a premium sweep of our own rail. Both are cases where
|
|
2436
|
+
// arming the pivot vetoes the very band the geometry derives, for the full
|
|
2437
|
+
// 24h TTL. Fail-open when no fresh live price exists: an ancient mid must
|
|
2438
|
+
// never veto a fresh fill after a fast move.
|
|
2439
|
+
// Deliberately applied to EVERY fill-provenance write (direct fills,
|
|
2440
|
+
// queued-fill refresh, rebuild re-arm) so no path can re-arm an
|
|
2441
|
+
// off-market row. The market-fill reference is skipped with it — an
|
|
2442
|
+
// off-market row as the crossing floor would freeze correction the same
|
|
2443
|
+
// way.
|
|
2444
|
+
if (provenance === 'fill') {
|
|
2445
|
+
const offMarket = offMarketFill(manager, type, p);
|
|
2446
|
+
if (offMarket) {
|
|
2447
|
+
const why = offMarket.kind === 'too-far'
|
|
2448
|
+
? `it priced ${offMarket.steps} grid step(s) away from the live market `
|
|
2449
|
+
+ `${offMarket.mid} — a premium sweep of our own rail, not a window trade`
|
|
2450
|
+
: `it priced ${offMarket.steps} grid step(s) on the wrong side of the live market `
|
|
2451
|
+
+ `${offMarket.mid} — a crossed-book artifact, not market truth`;
|
|
2452
|
+
// REFUSED-LEVEL MARKER (§9.12/P2 amended): the fill does not arm the
|
|
2453
|
+
// direction pivot, but its LEVEL must still refuse the immediate
|
|
2454
|
+
// re-place at the just-filled price. Without this the P1 refusal
|
|
2455
|
+
// silently suspended the P2 same-level block (which keys off the
|
|
2456
|
+
// ARMED pivot): a spread-correction slot re-armed at the identical
|
|
2457
|
+
// level and refilled in a loop for as long as a taker kept lifting
|
|
2458
|
+
// it (live 2026-11-16: 5 full fills at one premium level in 2.5
|
|
2459
|
+
// minutes). In-memory, TTL-bounded (LAST_FILL_REFUSED_LEVEL_TTL_MS).
|
|
2460
|
+
try {
|
|
2461
|
+
manager._lastRefusedFillPrice = p;
|
|
2462
|
+
manager._lastRefusedFillType = type;
|
|
2463
|
+
manager._lastRefusedFillAt = Date.now();
|
|
2464
|
+
}
|
|
2465
|
+
catch { /* marker is best-effort */ }
|
|
2466
|
+
const ttlMin = Math.round(Number(GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS) / 60000);
|
|
2467
|
+
manager.logger?.log?.(`[LAST-FILL-GUARD] Refusing to arm pivot ${p}(${type}): ${why}; the guard `
|
|
2468
|
+
+ `stays as-is and spread correction keeps trading around the live market; `
|
|
2469
|
+
+ `the just-filled level stays blocked as a same-level re-fill for ${ttlMin}m`, 'warn');
|
|
2470
|
+
return false;
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2027
2473
|
const now = Number.isFinite(Number(atMs)) && Number(atMs) > 0 ? Number(atMs) : Date.now();
|
|
2028
2474
|
manager._lastFilledPrice = p;
|
|
2029
2475
|
manager._lastFilledType = type;
|
|
@@ -2072,6 +2518,11 @@ export function resetLastFillPivot(manager, reason = 'unspecified') {
|
|
|
2072
2518
|
manager.lastFillPivotSource = null;
|
|
2073
2519
|
manager._lastFilledBuyPrice = null;
|
|
2074
2520
|
manager._lastFilledSellPrice = null;
|
|
2521
|
+
// The refused-level marker belongs to the same guard generation: a grid
|
|
2522
|
+
// rebuild invalidates the geometry (and any marker read against it).
|
|
2523
|
+
manager._lastRefusedFillPrice = null;
|
|
2524
|
+
manager._lastRefusedFillType = null;
|
|
2525
|
+
manager._lastRefusedFillAt = 0;
|
|
2075
2526
|
if (wasArmed) {
|
|
2076
2527
|
try {
|
|
2077
2528
|
manager.logger?.log?.(`[LAST-FILL-GUARD] Pivot cleared (${reason}); guard re-arms on the next fill`, 'info');
|
|
@@ -2080,6 +2531,48 @@ export function resetLastFillPivot(manager, reason = 'unspecified') {
|
|
|
2080
2531
|
}
|
|
2081
2532
|
return wasArmed;
|
|
2082
2533
|
}
|
|
2534
|
+
/**
|
|
2535
|
+
* Drop the ENTIRE last-fill guard state — the pivot scalar family AND the
|
|
2536
|
+
* bot-scoped last-market-fill reference, live and persisted — after the
|
|
2537
|
+
* spread watchdog concluded the pivot can never heal the grid (geometry
|
|
2538
|
+
* re-center already tried and failed; SPREAD_STALE_PIVOT_EXPIRE_MS elapsed).
|
|
2539
|
+
*
|
|
2540
|
+
* Mirrors restoreLastMarketFill's dead-row contract: persisted rows are
|
|
2541
|
+
* erased too, so a restart/rebuild cannot re-arm the same veto via
|
|
2542
|
+
* rearmLastFillPivotFromMarketFill. Both references re-arm on the next real
|
|
2543
|
+
* fill.
|
|
2544
|
+
*
|
|
2545
|
+
* @param {Object} manager - OrderManager instance
|
|
2546
|
+
* @param {string} reason - Log/debug label for the expiry
|
|
2547
|
+
*/
|
|
2548
|
+
export function expireLastFillGuardReferences(manager, reason = 'unspecified') {
|
|
2549
|
+
if (!manager)
|
|
2550
|
+
return;
|
|
2551
|
+
const pivotArmed = manager._lastFilledPrice != null && manager._lastFilledType != null;
|
|
2552
|
+
const fillRefArmed = manager._lastMarketFillPrice != null;
|
|
2553
|
+
resetLastFillPivot(manager, reason);
|
|
2554
|
+
manager._lastMarketFillPrice = null;
|
|
2555
|
+
manager._lastMarketFillType = null;
|
|
2556
|
+
manager._lastMarketFillAt = 0;
|
|
2557
|
+
try {
|
|
2558
|
+
const acct = manager.accountOrders;
|
|
2559
|
+
if (acct && typeof acct.clearPersistedLastMarketFill === 'function') {
|
|
2560
|
+
void acct.clearPersistedLastMarketFill();
|
|
2561
|
+
}
|
|
2562
|
+
if (acct && typeof acct.clearPersistedLastFillPivot === 'function') {
|
|
2563
|
+
void acct.clearPersistedLastFillPivot();
|
|
2564
|
+
}
|
|
2565
|
+
}
|
|
2566
|
+
catch { /* best-effort */ }
|
|
2567
|
+
if (pivotArmed || fillRefArmed) {
|
|
2568
|
+
try {
|
|
2569
|
+
manager.logger?.log?.(`[LAST-FILL-GUARD] Expired guard references (${reason}): pivot and last-market-fill ` +
|
|
2570
|
+
`cleared live and persisted — spread correction trades around the live market ` +
|
|
2571
|
+
`again; both re-arm on the next real fill`, 'warn');
|
|
2572
|
+
}
|
|
2573
|
+
catch { /* logging is best-effort */ }
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2083
2576
|
/**
|
|
2084
2577
|
* Restore the persisted LAST-FILL-GUARD pivot into the manager.
|
|
2085
2578
|
*
|
|
@@ -2163,7 +2656,14 @@ export function restoreLastFillPivot(manager, persisted, options = {}) {
|
|
|
2163
2656
|
if (!validated)
|
|
2164
2657
|
return false;
|
|
2165
2658
|
// Arm through the shared writer, preserving the persisted timestamp.
|
|
2166
|
-
|
|
2659
|
+
// The writer's wrong-side market bound can refuse (fresh live mid on
|
|
2660
|
+
// the other side of the row) — treat that like any other dead row:
|
|
2661
|
+
// erase the persisted value so a restart cannot re-arm the same veto.
|
|
2662
|
+
const armed = setLastFillPivot(manager, row.type, validated.price, 'fill', row.fillsAt);
|
|
2663
|
+
if (!armed) {
|
|
2664
|
+
dropPersistedRow();
|
|
2665
|
+
return false;
|
|
2666
|
+
}
|
|
2167
2667
|
manager.logger?.log?.(`[LAST-FILL-GUARD] Restored persisted pivot ${validated.price}(${row.type})` +
|
|
2168
2668
|
`${validated.slotIdx != null ? ` slot=${validated.slotIdx}` : ''}` +
|
|
2169
2669
|
`${validated.snapped ? ' (snapped)' : ''} age=${Math.round((now - row.fillsAt) / 1000)}s from snapshot`, 'info');
|
|
@@ -2205,7 +2705,7 @@ export async function retryPersistenceIfNeeded(manager) {
|
|
|
2205
2705
|
*
|
|
2206
2706
|
* @param {Object} manager - OrderManager instance
|
|
2207
2707
|
* @param {Object} accountOrders - AccountOrders data accessor
|
|
2208
|
-
* @param {string}
|
|
2708
|
+
* @param {string} _botKey - Unused; persistence is keyed off the manager.
|
|
2209
2709
|
* @param {Function} updateOrdersOnChainBatchFn - Batch update function for blockchain operations
|
|
2210
2710
|
* @param {Function} updateGridFromBlockchainSnapshotFn - Grid resize function (injected to avoid circular dependency with grid.ts)
|
|
2211
2711
|
* @returns {Promise<void>}
|