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
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
export interface PivotObservation {
|
|
3
|
+
t: number;
|
|
4
|
+
price: number;
|
|
5
|
+
type: string;
|
|
6
|
+
src: 'fill-pivot' | 'mode' | 'final-gate' | 'rearm';
|
|
7
|
+
}
|
|
8
|
+
export interface RefusalEvent {
|
|
9
|
+
t: number;
|
|
10
|
+
price: number;
|
|
11
|
+
type: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PlacementEvent {
|
|
14
|
+
t: number;
|
|
15
|
+
orderId: string;
|
|
16
|
+
price: number;
|
|
17
|
+
kind: 'placed' | 'plan-action';
|
|
18
|
+
}
|
|
19
|
+
export interface AllowanceEvent {
|
|
20
|
+
t: number;
|
|
21
|
+
direction: string;
|
|
22
|
+
price: number;
|
|
23
|
+
}
|
|
24
|
+
export interface RuntimeLogIndex {
|
|
25
|
+
observations: PivotObservation[];
|
|
26
|
+
refusals: RefusalEvent[];
|
|
27
|
+
placements: Map<string, PlacementEvent[]>;
|
|
28
|
+
allowances: AllowanceEvent[];
|
|
29
|
+
}
|
|
30
|
+
export interface TransitionCandidate {
|
|
31
|
+
prevTime: string;
|
|
32
|
+
currTime: string;
|
|
33
|
+
prevPrice: number;
|
|
34
|
+
currPrice: number;
|
|
35
|
+
direction: 'buy' | 'sell';
|
|
36
|
+
currOrderId: string;
|
|
37
|
+
}
|
|
38
|
+
export interface TransitionVerdict {
|
|
39
|
+
verdict: 'policy-divergence' | 'violation' | 'unverifiable';
|
|
40
|
+
reason: string;
|
|
41
|
+
/** The runtime pivot used at the gate (null when unverifiable). */
|
|
42
|
+
pivot: {
|
|
43
|
+
price: number;
|
|
44
|
+
type: string;
|
|
45
|
+
t: number;
|
|
46
|
+
} | null;
|
|
47
|
+
/** Refusals logged between the two fills (sweep-policy context). */
|
|
48
|
+
refusalsInRange: number;
|
|
49
|
+
}
|
|
50
|
+
/** How far after a placement event the judging gate may log its pivot. */
|
|
51
|
+
export declare const PIVOT_LOOKAHEAD_MS = 120000;
|
|
52
|
+
/** How wide an allowance match may drift around the gate pivot. */
|
|
53
|
+
export declare const ALLOWANCE_WINDOW_MS = 120000;
|
|
54
|
+
/**
|
|
55
|
+
* Kibana truncates fill timestamps to the second while the runtime logs the
|
|
56
|
+
* order's Placed/Plan-action line a few hundred ms later, so a naive
|
|
57
|
+
* `placement.t <= fill.t` test can miss the anchor. An order cannot fill
|
|
58
|
+
* before it exists, so placements slightly AFTER the (truncated) fill
|
|
59
|
+
* timestamp are still valid anchors.
|
|
60
|
+
*/
|
|
61
|
+
export declare const PLACEMENT_AFTER_FILL_MS = 5000;
|
|
62
|
+
/**
|
|
63
|
+
* Parse a bot log into the runtime pivot index. Unknown lines are skipped;
|
|
64
|
+
* the parser is deliberately tolerant of level/tag variation because it must
|
|
65
|
+
* work on rotated and filtered logs too.
|
|
66
|
+
*/
|
|
67
|
+
export declare function parseRuntimeLog(text: string): RuntimeLogIndex;
|
|
68
|
+
/** Latest pivot observation at or before `t` (binary search), or null. */
|
|
69
|
+
export declare function pivotAtOrBefore(observations: PivotObservation[], t: number): PivotObservation | null;
|
|
70
|
+
/** First pivot observation at or after `t`, or null when none within the window. */
|
|
71
|
+
export declare function pivotAtOrAfter(observations: PivotObservation[], t: number, windowMs?: number): PivotObservation | null;
|
|
72
|
+
/**
|
|
73
|
+
* Classify one strict-mode candidate transition against the pivot the runtime
|
|
74
|
+
* held when `currOrderId` was last priced. Verdicts and the fail direction are
|
|
75
|
+
* documented in the module header: anything unprovable stays a violation.
|
|
76
|
+
*/
|
|
77
|
+
export declare function classifyTransition(cand: TransitionCandidate, index: RuntimeLogIndex): TransitionVerdict;
|
|
78
|
+
//# sourceMappingURL=pivot_timeline.d.ts.map
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/**
|
|
4
|
+
* RUNTIME PIVOT TIMELINE — mirror of the runtime's own LAST-FILL-GUARD state,
|
|
5
|
+
* reconstructed from a bot log (profiles/logs/<bot>.log).
|
|
6
|
+
*
|
|
7
|
+
* Why this exists (2026-11-16 incident, retrospective §9.12 addendum): since
|
|
8
|
+
* `66667052`/`bc7b5232` the pivot only arms on WINDOW fills — wrong-side,
|
|
9
|
+
* too-far (premium sweep) and gap-band fills are refused. A sweep of the bot's
|
|
10
|
+
* own premium rail therefore leaves the pivot several grid steps BELOW the true
|
|
11
|
+
* last fill, and the runtime's gate legitimately passes re-quotes that the
|
|
12
|
+
* strict all-fills checker (which feeds true consecutive fills into the same
|
|
13
|
+
* predicate) flags as violations. The fix is not to change the runtime — the
|
|
14
|
+
* refusal policy is deliberate and protects the rail from the 24h unquoted-side
|
|
15
|
+
* deadlock — but to make the checker audit the gate the runtime ACTUALLY ran.
|
|
16
|
+
*
|
|
17
|
+
* This module parses the log's own pivot bookkeeping into a timeline:
|
|
18
|
+
*
|
|
19
|
+
* observations pivot values with timestamps, from (INFO unless noted):
|
|
20
|
+
* [FILL-PIVOT] pivot=P(type) ... (INFO)
|
|
21
|
+
* [LAST-FILL-GUARD] mode=... pivot=P(type) ... (INFO)
|
|
22
|
+
* [LAST-FILL-GUARD] Final gate: queue .. pivot A(type)->B(type) (DEBUG, post value)
|
|
23
|
+
* [LAST-FILL-GUARD] Re-armed on the new generation: P(type)
|
|
24
|
+
* ("Pivot refreshed from N pending queued fill(s)" is NOT an
|
|
25
|
+
* observation: it logs the queue content, which may be a fill
|
|
26
|
+
* the arming policy just refused; the effective pivot is in
|
|
27
|
+
* the adjacent Final-gate / mode= lines.)
|
|
28
|
+
* refusals [LAST-FILL-GUARD] Refusing to arm pivot P(type): ...
|
|
29
|
+
* placements order-id -> (timestamp, price) gate-judgement anchors, from:
|
|
30
|
+
* Placed buy order slot-X @P xS -> 1.7.x (INFO)
|
|
31
|
+
* [COW] Plan action: update slot-X -> slot-Y (orderId=1.7.x, size=.., price=P)
|
|
32
|
+
* allowances guard bypasses that keep a below-pivot placement:
|
|
33
|
+
* [LAST-FILL-GUARD] Allowing SELL P against pivot ...
|
|
34
|
+
* [LAST-FILL-GUARD] Allowing buy evacuation UPDATE ... at P
|
|
35
|
+
*
|
|
36
|
+
* and classifies a strict-mode candidate transition against the pivot the
|
|
37
|
+
* runtime held when the filled order was last priced:
|
|
38
|
+
*
|
|
39
|
+
* policy-divergence the runtime pivot would NOT have blocked the placement —
|
|
40
|
+
* the pivot lagged the strict last fill because the strict
|
|
41
|
+
* fill was refused from arming (sweep/edge/gap-band policy)
|
|
42
|
+
* or the placement ran under a guard allowance.
|
|
43
|
+
* violation the runtime's OWN pivot would have blocked the
|
|
44
|
+
* placement — a real gate failure.
|
|
45
|
+
* unverifiable no placement event or no pivot observation near the
|
|
46
|
+
* gate — the caller keeps the strict violation (fail
|
|
47
|
+
* toward reporting, never toward silence).
|
|
48
|
+
*
|
|
49
|
+
* Approximations (documented, offline-inherent):
|
|
50
|
+
* - The pivot for a placement is the FIRST observation at/after the
|
|
51
|
+
* placement event within PIVOT_LOOKAHEAD_MS — the gate runs between the
|
|
52
|
+
* plan build and the broadcast, and the batch's own mode=/Final-gate line
|
|
53
|
+
* is that gate's effective pivot. A dropped plan re-planned into a later
|
|
54
|
+
* batch resolves to the later batch's pivot (same orderId+action shape).
|
|
55
|
+
* The placement anchor is the order's event whose PRICE matches the
|
|
56
|
+
* filled price (a rotation to another level belongs to a different
|
|
57
|
+
* epoch); without a price match the latest event in the window is used.
|
|
58
|
+
* - Band-exempt allowances are logged at DEBUG; without debug logs such a
|
|
59
|
+
* transition stays a violation (conservative: fail toward reporting).
|
|
60
|
+
* - Spread-correction placements go through the same Plan/Placed lines, so
|
|
61
|
+
* they are covered; a correction order whose placement event is missing
|
|
62
|
+
* resolves to 'unverifiable' (kept as a strict violation).
|
|
63
|
+
*/
|
|
64
|
+
import { isLastFillGuardBlocked } from '../modules/order/utils/system.js';
|
|
65
|
+
/** How far after a placement event the judging gate may log its pivot. */
|
|
66
|
+
export const PIVOT_LOOKAHEAD_MS = 120_000;
|
|
67
|
+
/** How wide an allowance match may drift around the gate pivot. */
|
|
68
|
+
export const ALLOWANCE_WINDOW_MS = 120_000;
|
|
69
|
+
/**
|
|
70
|
+
* Kibana truncates fill timestamps to the second while the runtime logs the
|
|
71
|
+
* order's Placed/Plan-action line a few hundred ms later, so a naive
|
|
72
|
+
* `placement.t <= fill.t` test can miss the anchor. An order cannot fill
|
|
73
|
+
* before it exists, so placements slightly AFTER the (truncated) fill
|
|
74
|
+
* timestamp are still valid anchors.
|
|
75
|
+
*/
|
|
76
|
+
export const PLACEMENT_AFTER_FILL_MS = 5_000;
|
|
77
|
+
/** Relative price tolerance when matching an allowance to a fill price. */
|
|
78
|
+
const ALLOWANCE_PRICE_TOL = 5e-5;
|
|
79
|
+
/**
|
|
80
|
+
* Relative price tolerance when picking the placement anchor for a fill:
|
|
81
|
+
* maker fills average slightly off the quote price, so the anchor is the
|
|
82
|
+
* placement whose price is within 0.1% of the filled price. A rotation to a
|
|
83
|
+
* different grid level is far outside this band and never matches.
|
|
84
|
+
*/
|
|
85
|
+
const PLACEMENT_PRICE_TOL = 1e-3;
|
|
86
|
+
// ─── Line parsing ─────────────────────────────────────────────────────────────
|
|
87
|
+
const TS_RE = /^\[(\d{4}-\d{2}-\d{2}T[\d:.]+Z)\]/;
|
|
88
|
+
function lineTs(line) {
|
|
89
|
+
const m = TS_RE.exec(line);
|
|
90
|
+
if (!m)
|
|
91
|
+
return null;
|
|
92
|
+
const t = Date.parse(m[1]);
|
|
93
|
+
return Number.isFinite(t) ? t : null;
|
|
94
|
+
}
|
|
95
|
+
/** "1,538.559125" | "1538.559125" | "1.3534" -> number | null */
|
|
96
|
+
function num(raw) {
|
|
97
|
+
if (!raw)
|
|
98
|
+
return null;
|
|
99
|
+
const v = Number(raw.replace(/,/g, ''));
|
|
100
|
+
return Number.isFinite(v) ? v : null;
|
|
101
|
+
}
|
|
102
|
+
const FILL_PIVOT_RE = /\[FILL-PIVOT\] pivot=([\d.,eE+-]+)\((buy|sell)\)/;
|
|
103
|
+
const MODE_RE = /\[LAST-FILL-GUARD\] mode=\S+ pivot=([\d.,eE+-]+)\((buy|sell)\)/;
|
|
104
|
+
const FINAL_GATE_RE = /\[LAST-FILL-GUARD\] Final gate: queue \S+ pivot [\d.,eE+-]+\((?:buy|sell)\)->([\d.,eE+-]+)\((buy|sell)\)/;
|
|
105
|
+
const REARM_RE = /\[LAST-FILL-GUARD\] Re-armed on the new generation: ([\d.,eE+-]+)\((buy|sell)\)/;
|
|
106
|
+
const REFUSAL_RE = /\[LAST-FILL-GUARD\] Refusing to arm pivot ([\d.,eE+-]+)\((buy|sell)\)/;
|
|
107
|
+
const PLACED_RE = /\[DEXBot\] Placed (buy|sell) order slot-[\w-]+ @([\d.,eE+-]+) x[\d.,eE+-]+ -> (1\.7\.\d+)/;
|
|
108
|
+
const PLAN_ACTION_RE = /\[COW\] Plan action: (?:update|create) \S+(?: -> \S+)? \(orderId=(1\.7\.\d+)[^)]*?price=([\d.,eE+-]+)/;
|
|
109
|
+
// "Allowing buy evacuation UPDATE for slot-X -> slot-Y at P: ..." (price after "at")
|
|
110
|
+
// "Allowing SELL P against pivot Q: ..." (placement price right after the direction word)
|
|
111
|
+
const ALLOW_AT_RE = /\s+at\s+([\d.,eE+-]+)/;
|
|
112
|
+
const ALLOW_AGAINST_RE = /\b(?:BUY|SELL) ([\d.,eE+-]+) against/;
|
|
113
|
+
const ALLOW_DIR_RE = /\b(buy|sell|BUY|SELL)\b/;
|
|
114
|
+
/**
|
|
115
|
+
* Parse a bot log into the runtime pivot index. Unknown lines are skipped;
|
|
116
|
+
* the parser is deliberately tolerant of level/tag variation because it must
|
|
117
|
+
* work on rotated and filtered logs too.
|
|
118
|
+
*/
|
|
119
|
+
export function parseRuntimeLog(text) {
|
|
120
|
+
const observations = [];
|
|
121
|
+
const refusals = [];
|
|
122
|
+
const placements = new Map();
|
|
123
|
+
const allowances = [];
|
|
124
|
+
for (const line of text.split('\n')) {
|
|
125
|
+
const t = lineTs(line);
|
|
126
|
+
if (t == null)
|
|
127
|
+
continue;
|
|
128
|
+
let m = FILL_PIVOT_RE.exec(line);
|
|
129
|
+
if (m) {
|
|
130
|
+
const price = num(m[1]);
|
|
131
|
+
if (price != null && price > 0)
|
|
132
|
+
observations.push({ t, price, type: m[2], src: 'fill-pivot' });
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
m = MODE_RE.exec(line);
|
|
136
|
+
if (m) {
|
|
137
|
+
const price = num(m[1]);
|
|
138
|
+
if (price != null && price > 0)
|
|
139
|
+
observations.push({ t, price, type: m[2], src: 'mode' });
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
m = FINAL_GATE_RE.exec(line);
|
|
143
|
+
if (m) {
|
|
144
|
+
const price = num(m[1]);
|
|
145
|
+
if (price != null && price > 0)
|
|
146
|
+
observations.push({ t, price, type: m[2], src: 'final-gate' });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
m = REARM_RE.exec(line);
|
|
150
|
+
if (m) {
|
|
151
|
+
const price = num(m[1]);
|
|
152
|
+
if (price != null && price > 0)
|
|
153
|
+
observations.push({ t, price, type: m[2], src: 'rearm' });
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
m = REFUSAL_RE.exec(line);
|
|
157
|
+
if (m) {
|
|
158
|
+
const price = num(m[1]);
|
|
159
|
+
if (price != null && price > 0)
|
|
160
|
+
refusals.push({ t, price, type: m[2] });
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
m = PLACED_RE.exec(line);
|
|
164
|
+
if (m) {
|
|
165
|
+
const price = num(m[2]);
|
|
166
|
+
if (price != null)
|
|
167
|
+
pushPlacement(placements, { t, orderId: m[3], price, kind: 'placed' });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
m = PLAN_ACTION_RE.exec(line);
|
|
171
|
+
if (m) {
|
|
172
|
+
const price = num(m[2]);
|
|
173
|
+
if (price != null)
|
|
174
|
+
pushPlacement(placements, { t, orderId: m[1], price, kind: 'plan-action' });
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (line.includes('[LAST-FILL-GUARD] Allowing')) {
|
|
178
|
+
const dm = ALLOW_DIR_RE.exec(line.slice(line.indexOf('Allowing')));
|
|
179
|
+
const am = ALLOW_AT_RE.exec(line) ?? ALLOW_AGAINST_RE.exec(line);
|
|
180
|
+
if (dm && am) {
|
|
181
|
+
const price = num(am[1]);
|
|
182
|
+
if (price != null)
|
|
183
|
+
allowances.push({ t, direction: dm[1].toLowerCase(), price });
|
|
184
|
+
}
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
observations.sort((a, b) => a.t - b.t);
|
|
189
|
+
refusals.sort((a, b) => a.t - b.t);
|
|
190
|
+
allowances.sort((a, b) => a.t - b.t);
|
|
191
|
+
for (const list of placements.values())
|
|
192
|
+
list.sort((a, b) => a.t - b.t);
|
|
193
|
+
return { observations, refusals, placements, allowances };
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Kibana fills carry an operation suffix on the order id (e.g. `1.7.x:se`),
|
|
197
|
+
* while the runtime log's Plan/Placed lines use the plain `1.7.x`. Normalize
|
|
198
|
+
* to the plain id on both sides so the join works.
|
|
199
|
+
*/
|
|
200
|
+
function normalizeOrderId(orderId) {
|
|
201
|
+
const colon = orderId.indexOf(':');
|
|
202
|
+
return colon === -1 ? orderId : orderId.slice(0, colon);
|
|
203
|
+
}
|
|
204
|
+
function pushPlacement(map, ev) {
|
|
205
|
+
ev.orderId = normalizeOrderId(ev.orderId);
|
|
206
|
+
const list = map.get(ev.orderId);
|
|
207
|
+
if (list)
|
|
208
|
+
list.push(ev);
|
|
209
|
+
else
|
|
210
|
+
map.set(ev.orderId, [ev]);
|
|
211
|
+
}
|
|
212
|
+
/** Latest pivot observation at or before `t` (binary search), or null. */
|
|
213
|
+
export function pivotAtOrBefore(observations, t) {
|
|
214
|
+
let lo = 0;
|
|
215
|
+
let hi = observations.length - 1;
|
|
216
|
+
let best = null;
|
|
217
|
+
while (lo <= hi) {
|
|
218
|
+
const mid = (lo + hi) >> 1;
|
|
219
|
+
if (observations[mid].t <= t) {
|
|
220
|
+
best = observations[mid];
|
|
221
|
+
lo = mid + 1;
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
hi = mid - 1;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return best;
|
|
228
|
+
}
|
|
229
|
+
/** First pivot observation at or after `t`, or null when none within the window. */
|
|
230
|
+
export function pivotAtOrAfter(observations, t, windowMs = PIVOT_LOOKAHEAD_MS) {
|
|
231
|
+
let lo = 0;
|
|
232
|
+
let hi = observations.length;
|
|
233
|
+
while (lo < hi) {
|
|
234
|
+
const mid = (lo + hi) >> 1;
|
|
235
|
+
if (observations[mid].t < t)
|
|
236
|
+
lo = mid + 1;
|
|
237
|
+
else
|
|
238
|
+
hi = mid;
|
|
239
|
+
}
|
|
240
|
+
if (lo < observations.length && observations[lo].t - t <= windowMs)
|
|
241
|
+
return observations[lo];
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
function lastPlacementBefore(map, orderId, t, fillPrice) {
|
|
245
|
+
const limit = t + PLACEMENT_AFTER_FILL_MS;
|
|
246
|
+
const list = map.get(orderId);
|
|
247
|
+
if (!list || list.length === 0)
|
|
248
|
+
return null;
|
|
249
|
+
let latest = null;
|
|
250
|
+
let priced = null;
|
|
251
|
+
for (const ev of list) {
|
|
252
|
+
if (ev.t > limit)
|
|
253
|
+
break;
|
|
254
|
+
latest = ev;
|
|
255
|
+
if (fillPrice != null) {
|
|
256
|
+
const denom = Math.max(Math.abs(fillPrice), 1e-12);
|
|
257
|
+
if (Math.abs(ev.price - fillPrice) / denom <= PLACEMENT_PRICE_TOL)
|
|
258
|
+
priced = ev;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// Prefer the epoch the fill actually belongs to (price-matched re-quote);
|
|
262
|
+
// the latest event is only a fallback when no quote matches the fill.
|
|
263
|
+
return priced ?? latest;
|
|
264
|
+
}
|
|
265
|
+
function countRefusalsBetween(refusals, from, to) {
|
|
266
|
+
let n = 0;
|
|
267
|
+
for (const r of refusals) {
|
|
268
|
+
if (r.t > from && r.t <= to)
|
|
269
|
+
n++;
|
|
270
|
+
if (r.t > to)
|
|
271
|
+
break;
|
|
272
|
+
}
|
|
273
|
+
return n;
|
|
274
|
+
}
|
|
275
|
+
function findAllowance(allowances, direction, price, from, to) {
|
|
276
|
+
for (const a of allowances) {
|
|
277
|
+
if (a.t < from)
|
|
278
|
+
continue;
|
|
279
|
+
if (a.t > to)
|
|
280
|
+
break;
|
|
281
|
+
if (a.direction !== direction)
|
|
282
|
+
continue;
|
|
283
|
+
const denom = Math.max(Math.abs(price), 1e-12);
|
|
284
|
+
if (Math.abs(a.price - price) / denom <= ALLOWANCE_PRICE_TOL)
|
|
285
|
+
return a;
|
|
286
|
+
}
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Parse an ISO timestamp. Kibana fill times are UTC but written naive
|
|
291
|
+
* (`2026-11-16T14:08:18`, no offset); Date.parse would read those as LOCAL
|
|
292
|
+
* time and shift the timeline by the host's UTC offset. Treat any timestamp
|
|
293
|
+
* without an explicit offset as UTC — the log lines and Kibana agree on UTC.
|
|
294
|
+
*/
|
|
295
|
+
function parseIso(t) {
|
|
296
|
+
if (!/[Zz]|[+-]\d{2}:?\d{2}$/.test(t))
|
|
297
|
+
return Date.parse(t + 'Z');
|
|
298
|
+
return Date.parse(t);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Classify one strict-mode candidate transition against the pivot the runtime
|
|
302
|
+
* held when `currOrderId` was last priced. Verdicts and the fail direction are
|
|
303
|
+
* documented in the module header: anything unprovable stays a violation.
|
|
304
|
+
*/
|
|
305
|
+
export function classifyTransition(cand, index) {
|
|
306
|
+
const currT = parseIso(cand.currTime);
|
|
307
|
+
const prevT = parseIso(cand.prevTime);
|
|
308
|
+
const unverifiable = (reason) => ({
|
|
309
|
+
verdict: 'unverifiable',
|
|
310
|
+
reason,
|
|
311
|
+
pivot: null,
|
|
312
|
+
refusalsInRange: Number.isFinite(prevT) && Number.isFinite(currT)
|
|
313
|
+
? countRefusalsBetween(index.refusals, prevT, currT)
|
|
314
|
+
: 0,
|
|
315
|
+
});
|
|
316
|
+
if (!Number.isFinite(currT))
|
|
317
|
+
return unverifiable('unparseable curr fill timestamp');
|
|
318
|
+
const placement = lastPlacementBefore(index.placements, normalizeOrderId(cand.currOrderId), currT, cand.currPrice);
|
|
319
|
+
if (!placement) {
|
|
320
|
+
return unverifiable(`no placement event for order ${cand.currOrderId} before the fill`);
|
|
321
|
+
}
|
|
322
|
+
// The gate runs between plan build and broadcast; its effective pivot is
|
|
323
|
+
// the batch's own mode=/Final-gate line. Look FORWARD from the event, not
|
|
324
|
+
// backward — the previous batch's pivot would understate the gate.
|
|
325
|
+
const obs = pivotAtOrAfter(index.observations, placement.t);
|
|
326
|
+
if (!obs) {
|
|
327
|
+
return unverifiable(`no pivot observation within ${PIVOT_LOOKAHEAD_MS / 1000}s of the placement event`);
|
|
328
|
+
}
|
|
329
|
+
const refusalsInRange = Number.isFinite(prevT)
|
|
330
|
+
? countRefusalsBetween(index.refusals, prevT, currT)
|
|
331
|
+
: 0;
|
|
332
|
+
const pivot = { price: obs.price, type: obs.type, t: obs.t };
|
|
333
|
+
const check = isLastFillGuardBlocked(cand.currPrice, cand.direction, obs.price, obs.type);
|
|
334
|
+
if (!check.blocked) {
|
|
335
|
+
return {
|
|
336
|
+
verdict: 'policy-divergence',
|
|
337
|
+
reason: refusalsInRange > 0
|
|
338
|
+
? `runtime pivot ${obs.price}(${obs.type}) at the gate excluded the strict last fill from arming (window-trade policy, ${refusalsInRange} refusal(s) between the fills)`
|
|
339
|
+
: `runtime pivot ${obs.price}(${obs.type}) at the gate was older than the strict last fill`,
|
|
340
|
+
pivot,
|
|
341
|
+
refusalsInRange,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
const allowed = findAllowance(index.allowances, cand.direction, cand.currPrice, pivot.t - ALLOWANCE_WINDOW_MS, pivot.t + 5000);
|
|
345
|
+
if (allowed) {
|
|
346
|
+
return {
|
|
347
|
+
verdict: 'policy-divergence',
|
|
348
|
+
reason: `guard allowance logged at the gate (band-exempt / stamped evacuation; pivot ${obs.price}(${obs.type}))`,
|
|
349
|
+
pivot,
|
|
350
|
+
refusalsInRange,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
verdict: 'violation',
|
|
355
|
+
reason: `the runtime's own pivot ${obs.price}(${obs.type}) would have blocked this placement`,
|
|
356
|
+
pivot,
|
|
357
|
+
refusalsInRange,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
//# sourceMappingURL=pivot_timeline.js.map
|
|
@@ -249,21 +249,33 @@ async function _acquireLockCoreAsync(lockPath, opts = {}) {
|
|
|
249
249
|
*/
|
|
250
250
|
function acquireFileLockSync(lockPath, opts = {}) {
|
|
251
251
|
const staleMs = typeof opts.staleMs === 'number' && Number.isFinite(opts.staleMs) && opts.staleMs > 0 ? opts.staleMs : (6 * 3600 * 1000);
|
|
252
|
+
// Explicit opts override the market-adapter defaults (default payload,
|
|
253
|
+
// liveness heuristic, and message). Callers that pass none — the market
|
|
254
|
+
// adapter lifecycle lock — keep the exact behavior above; generic callers
|
|
255
|
+
// (e.g. the per-account bot instance lock) parameterize their own payload,
|
|
256
|
+
// holder liveness, and contention message.
|
|
257
|
+
const buildPayload = typeof opts.buildPayload === 'function'
|
|
258
|
+
? opts.buildPayload
|
|
259
|
+
: () => ({ pid: runtime.pid, createdAt: new Date().toISOString() });
|
|
260
|
+
const aliveCheck = typeof opts.aliveCheck === 'function' ? opts.aliveCheck : isLikelyMarketAdapterProcess;
|
|
261
|
+
const resolveRunningMsg = typeof opts.alreadyRunningMsg === 'function'
|
|
262
|
+
? opts.alreadyRunningMsg
|
|
263
|
+
: () => `market adapter already running (lock: ${lockPath}, pid: ${loadLockInfo(lockPath).pid ?? 'unknown'})`;
|
|
252
264
|
return _acquireLockCore(lockPath, {
|
|
253
265
|
staleMs,
|
|
254
266
|
maxAttempts: 2,
|
|
255
267
|
retryMs: 0,
|
|
256
268
|
contention: 'throw',
|
|
257
|
-
aliveCheck
|
|
269
|
+
aliveCheck,
|
|
258
270
|
// The payload's `pid` is display metadata for this message; the
|
|
259
271
|
// release-time identity token is the core-injected `ownerId` (always a
|
|
260
272
|
// fresh unique id, never reused across acquires).
|
|
261
|
-
buildPayload
|
|
273
|
+
buildPayload,
|
|
262
274
|
// Evaluated lazily at throw time so the reported pid reflects the lock
|
|
263
275
|
// holder at the moment contention is detected, not the state when this
|
|
264
276
|
// function was first called (loadLockInfo tolerates a missing lock file).
|
|
265
|
-
alreadyRunningMsg:
|
|
266
|
-
timeoutMsg: `cannot acquire lock: ${lockPath}`,
|
|
277
|
+
alreadyRunningMsg: resolveRunningMsg,
|
|
278
|
+
timeoutMsg: opts.timeoutMsg || `cannot acquire lock: ${lockPath}`,
|
|
267
279
|
});
|
|
268
280
|
}
|
|
269
281
|
function releaseFileLockSync(lock) {
|
|
@@ -119,6 +119,10 @@ declare function loadGeneralSettings(): {
|
|
|
119
119
|
GAP_EVACUATION_STREAK_THRESHOLD: number;
|
|
120
120
|
GAP_EVACUATION_CANCEL_THRESHOLD: number;
|
|
121
121
|
LAST_FILL_PIVOT_TTL_MS: number;
|
|
122
|
+
LAST_FILL_REFUSED_LEVEL_TTL_MS: number;
|
|
123
|
+
LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: number;
|
|
124
|
+
LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: number;
|
|
125
|
+
LAST_FILL_PIVOT_MARKET_FRESH_MS: number;
|
|
122
126
|
RELATIVE_ORDER_UPDATE_THRESHOLD_PERCENT: number;
|
|
123
127
|
};
|
|
124
128
|
TIMING: {
|
|
@@ -166,10 +170,12 @@ declare function loadGeneralSettings(): {
|
|
|
166
170
|
SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
|
|
167
171
|
SPREAD_STALE_FUND_ESCALATE_MS: number;
|
|
168
172
|
SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
|
|
173
|
+
SPREAD_STALE_PIVOT_EXPIRE_MS: number;
|
|
169
174
|
SPREAD_CORRECTION_MAX_ATTEMPTS: number;
|
|
170
175
|
SPREAD_STALE_TRANSIENT_GRACE: number;
|
|
171
176
|
SPREAD_CORRECTION_SYNC_FRESH_MS: number;
|
|
172
177
|
SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
|
|
178
|
+
SPREAD_STALE_RECHECK_MS: number;
|
|
173
179
|
BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
|
|
174
180
|
BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
|
|
175
181
|
GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: number;
|
|
@@ -409,6 +415,7 @@ declare function loadGeneralSettings(): {
|
|
|
409
415
|
MODE: string;
|
|
410
416
|
OPERATION_TYPE: number;
|
|
411
417
|
COALESCE_BACKLOG_REPLAY: boolean;
|
|
418
|
+
GRID_BLOCKED_ESCALATE_CYCLES: number;
|
|
412
419
|
MAX_CONSECUTIVE_CONSUMER_FAILURES: number;
|
|
413
420
|
CONSUMER_BACKOFF_INITIAL_MS: number;
|
|
414
421
|
CONSUMER_BACKOFF_MAX_MS: number;
|
|
@@ -295,7 +295,7 @@ async function askRequiredString(promptText, defaultValue) {
|
|
|
295
295
|
}
|
|
296
296
|
/**
|
|
297
297
|
* Prompts the user for a cron schedule using interval and time.
|
|
298
|
-
* @param {string}
|
|
298
|
+
* @param {string} _promptText - Unused; the prompt text is built below.
|
|
299
299
|
* @param {string} defaultValue - The default value to use if input is empty.
|
|
300
300
|
* @returns {Promise<string>} The user input.
|
|
301
301
|
*/
|
|
@@ -403,10 +403,12 @@ async function askAssetB(promptText, defaultValue, assetA) {
|
|
|
403
403
|
return askAssetSymbol(promptText, defaultValue, (assetB) => assetB === assetA ? `Invalid: Asset B cannot be the same as Asset A (${assetA})` : null);
|
|
404
404
|
}
|
|
405
405
|
/**
|
|
406
|
-
* Prompts the user for a weight distribution value
|
|
406
|
+
* Prompts the user for a weight distribution value, optionally printing the
|
|
407
|
+
* value legend above the prompt.
|
|
407
408
|
* @param {string} promptText - The prompt text to display.
|
|
408
409
|
* @param {number} [defaultValue] - The default value to use if input is empty.
|
|
409
|
-
* @
|
|
410
|
+
* @param {boolean} showLegend - Print the -1..2 legend line before prompting.
|
|
411
|
+
* @returns {Promise<number|string|undefined>} The numeric value, '\x1b' if ESC, or undefined.
|
|
410
412
|
*/
|
|
411
413
|
async function askWeightDistributionValue(promptText, defaultValue, showLegend) {
|
|
412
414
|
const MIN_WEIGHT = -1;
|
|
@@ -420,7 +422,7 @@ async function askWeightDistributionValue(promptText, defaultValue, showLegend)
|
|
|
420
422
|
* Prompts the user for a weight distribution value with a legend.
|
|
421
423
|
* @param {string} promptText - The prompt text to display.
|
|
422
424
|
* @param {number} [defaultValue] - The default value to use if input is empty.
|
|
423
|
-
* @returns {Promise<number|string>} The numeric value
|
|
425
|
+
* @returns {Promise<number|string|undefined>} The numeric value, '\x1b' if ESC, or undefined.
|
|
424
426
|
*/
|
|
425
427
|
async function askWeightDistribution(promptText, defaultValue) {
|
|
426
428
|
return askWeightDistributionValue(promptText, defaultValue, true);
|
|
@@ -429,7 +431,7 @@ async function askWeightDistribution(promptText, defaultValue) {
|
|
|
429
431
|
* Prompts the user for a weight distribution value without a legend.
|
|
430
432
|
* @param {string} promptText - The prompt text to display.
|
|
431
433
|
* @param {number} [defaultValue] - The default value to use if input is empty.
|
|
432
|
-
* @returns {Promise<number|string>} The numeric value
|
|
434
|
+
* @returns {Promise<number|string|undefined>} The numeric value, '\x1b' if ESC, or undefined.
|
|
433
435
|
*/
|
|
434
436
|
async function askWeightDistributionNoLegend(promptText, defaultValue) {
|
|
435
437
|
return askWeightDistributionValue(promptText, defaultValue, false);
|
|
@@ -214,7 +214,12 @@ export function createDefaultBotMetrics() {
|
|
|
214
214
|
gapBandPlacementShadowCount: 0,
|
|
215
215
|
spreadCorrectionRefusedCount: 0,
|
|
216
216
|
spreadCorrectionRefusalCauses: {},
|
|
217
|
-
spreadCorrectionRetryCount: 0
|
|
217
|
+
spreadCorrectionRetryCount: 0,
|
|
218
|
+
stalePlanDroppedCount: 0,
|
|
219
|
+
stalePlanProceedCount: 0,
|
|
220
|
+
clampedNoopUpdateCount: 0,
|
|
221
|
+
chunkAbortedOpCount: 0,
|
|
222
|
+
reloadReplacedRailCount: 0
|
|
218
223
|
};
|
|
219
224
|
}
|
|
220
225
|
//# sourceMappingURL=bot_defaults.js.map
|
|
@@ -242,10 +242,12 @@ declare let TIMING: {
|
|
|
242
242
|
SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
|
|
243
243
|
SPREAD_STALE_FUND_ESCALATE_MS: number;
|
|
244
244
|
SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
|
|
245
|
+
SPREAD_STALE_PIVOT_EXPIRE_MS: number;
|
|
245
246
|
SPREAD_CORRECTION_MAX_ATTEMPTS: number;
|
|
246
247
|
SPREAD_STALE_TRANSIENT_GRACE: number;
|
|
247
248
|
SPREAD_CORRECTION_SYNC_FRESH_MS: number;
|
|
248
249
|
SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
|
|
250
|
+
SPREAD_STALE_RECHECK_MS: number;
|
|
249
251
|
BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
|
|
250
252
|
BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
|
|
251
253
|
GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: number;
|
|
@@ -301,6 +303,10 @@ declare let GRID_LIMITS: {
|
|
|
301
303
|
GAP_EVACUATION_STREAK_THRESHOLD: number;
|
|
302
304
|
GAP_EVACUATION_CANCEL_THRESHOLD: number;
|
|
303
305
|
LAST_FILL_PIVOT_TTL_MS: number;
|
|
306
|
+
LAST_FILL_REFUSED_LEVEL_TTL_MS: number;
|
|
307
|
+
LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: number;
|
|
308
|
+
LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: number;
|
|
309
|
+
LAST_FILL_PIVOT_MARKET_FRESH_MS: number;
|
|
304
310
|
GRID_COMPARISON: {
|
|
305
311
|
RMS_PERCENTAGE: number;
|
|
306
312
|
};
|
|
@@ -352,6 +358,7 @@ declare let FILL_PROCESSING: {
|
|
|
352
358
|
MODE: string;
|
|
353
359
|
OPERATION_TYPE: number;
|
|
354
360
|
COALESCE_BACKLOG_REPLAY: boolean;
|
|
361
|
+
GRID_BLOCKED_ESCALATE_CYCLES: number;
|
|
355
362
|
MAX_CONSECUTIVE_CONSUMER_FAILURES: number;
|
|
356
363
|
CONSUMER_BACKOFF_INITIAL_MS: number;
|
|
357
364
|
CONSUMER_BACKOFF_MAX_MS: number;
|
|
@@ -751,6 +758,10 @@ declare function buildDefaultGeneralSettings(): {
|
|
|
751
758
|
GAP_EVACUATION_STREAK_THRESHOLD: number;
|
|
752
759
|
GAP_EVACUATION_CANCEL_THRESHOLD: number;
|
|
753
760
|
LAST_FILL_PIVOT_TTL_MS: number;
|
|
761
|
+
LAST_FILL_REFUSED_LEVEL_TTL_MS: number;
|
|
762
|
+
LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: number;
|
|
763
|
+
LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: number;
|
|
764
|
+
LAST_FILL_PIVOT_MARKET_FRESH_MS: number;
|
|
754
765
|
RELATIVE_ORDER_UPDATE_THRESHOLD_PERCENT: number;
|
|
755
766
|
};
|
|
756
767
|
TIMING: {
|
|
@@ -798,10 +809,12 @@ declare function buildDefaultGeneralSettings(): {
|
|
|
798
809
|
SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
|
|
799
810
|
SPREAD_STALE_FUND_ESCALATE_MS: number;
|
|
800
811
|
SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
|
|
812
|
+
SPREAD_STALE_PIVOT_EXPIRE_MS: number;
|
|
801
813
|
SPREAD_CORRECTION_MAX_ATTEMPTS: number;
|
|
802
814
|
SPREAD_STALE_TRANSIENT_GRACE: number;
|
|
803
815
|
SPREAD_CORRECTION_SYNC_FRESH_MS: number;
|
|
804
816
|
SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
|
|
817
|
+
SPREAD_STALE_RECHECK_MS: number;
|
|
805
818
|
BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
|
|
806
819
|
BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
|
|
807
820
|
GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: number;
|
|
@@ -1041,6 +1054,7 @@ declare function buildDefaultGeneralSettings(): {
|
|
|
1041
1054
|
MODE: string;
|
|
1042
1055
|
OPERATION_TYPE: number;
|
|
1043
1056
|
COALESCE_BACKLOG_REPLAY: boolean;
|
|
1057
|
+
GRID_BLOCKED_ESCALATE_CYCLES: number;
|
|
1044
1058
|
MAX_CONSECUTIVE_CONSUMER_FAILURES: number;
|
|
1045
1059
|
CONSUMER_BACKOFF_INITIAL_MS: number;
|
|
1046
1060
|
CONSUMER_BACKOFF_MAX_MS: number;
|