bushido-tradingview-mcp 0.1.21 → 0.1.23
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/README.md +2 -2
- package/build/analysisOutcome.js +124 -5
- package/build/dueAnalyses.js +69 -1
- package/build/server.js +15 -3
- package/build/tradeDecisionContext.js +74 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -196,7 +196,7 @@ The AI selects the appropriate tools automatically; you do not need to memorize
|
|
|
196
196
|
|---|---|
|
|
197
197
|
| `get_market_snapshot` | Combines multiple markets, timeframes, and events in one acquisition window with explicit quality status |
|
|
198
198
|
| `get_execution_snapshot` | Normalizes bid/ask, spread, pip/tick, and feed mode; reports ready only after observing a post-request price update |
|
|
199
|
-
| `get_trade_decision_context` | Binds chart, OHLC, levels, MTF, events, COT, real yield, and bid/ask to one `snapshot_id`; blocks live execution evidence during Replay |
|
|
199
|
+
| `get_trade_decision_context` | Binds chart, OHLC, levels, MTF, events, COT, real yield, and bid/ask to one `snapshot_id`; blocks live execution evidence during Replay; the event gate reads the calendar around the request (releases from the after-release minutes before it to the before-release minutes after it completes, shown in `event_gate.window`) and waits when the calendar cannot be read (`unavailable`) or may lack an event in the window (`incomplete`) |
|
|
200
200
|
| `get_aligned_history` | Strictly aligns closed bars from multiple charts by UTC timestamp without forward filling |
|
|
201
201
|
| `compute_market_features` | Deterministically computes returns, ATR, volatility, and correlation from aligned history |
|
|
202
202
|
| `compute_market_regimes` | Classifies closed OHLC as trend/range/transition and low/normal/high volatility using only prior evidence and explicit thresholds; it does not optimize or recommend trades |
|
|
@@ -361,7 +361,7 @@ Use `--real-yield-history PATH` for an isolated store. If the snapshot has no co
|
|
|
361
361
|
|
|
362
362
|
To overlay analysis on the chart, save the template once with `save_pine_script`, then use `ensure_analysis_overlay` to place, update, and obtain its `study_id`. An existing current version is reused without writing, so each analysis does not create another script or study. If a legacy migration preview returns `contextBindingRequired:true`, confirmation binds that analysis to the currently verified symbol/timeframe. Expired analyses remain visible as `EXPIRED`. Template defaults are not treated as analysis and return `unconfigured`. After application, status rechecks inputs, current-price geometry, and drawings; a chart that differs from the stored context returns `stale_context` and `trusted:false`.
|
|
363
363
|
|
|
364
|
-
Current-price geometry does not establish historical hit order. `evaluate_analysis_overlay_outcome` evaluates closed OHLC after the analysis, excluding both the analysis-time bar and the forming bar. After Entry, an optional Confirmation must occur on a later bar; Invalidation before confirmation cancels the setup. Once active, Target 1 versus Stop is evaluated first-hit. This does not prove fills or P&L: touching opposing levels in one bar or opening across a terminal returns `ambiguous`.
|
|
364
|
+
Current-price geometry does not establish historical hit order. `evaluate_analysis_overlay_outcome` evaluates closed OHLC after the analysis, excluding both the analysis-time bar and the forming bar. After Entry, an optional Confirmation must occur on a later bar; Invalidation before confirmation cancels the setup. Once active, Target 1 versus Stop is evaluated first-hit. This does not prove fills or P&L: touching opposing levels in one bar or opening across a terminal returns `ambiguous`. Without a terminal, a result is final (`no_terminal_event`, `not_activated` or `expired_without_confirmation`) only once the closed bars reach the expiry, or a forming bar runs past it (`evidence.expiryCoveredBy` names which); before that it is `incomplete` (`history_ends_before_expiry`) and `evaluate_due_analyses` rechecks it, so a symbol that stops trading before the expiry stays incomplete. Bars alone cannot show that a missing bar was a market closure, so time without bars inside the window makes a result `incomplete` (`gap_in_evaluation_window`) when it has no terminal or would be decided after the gap; a result decided before the first gap stands, and a gap found while the history is still short is reported as a gap. Between two bars, or before a next bar that starts by the expiry, a gap is half a bar or more for bars of up to two hours, and a bar less an hour for longer bars, which daylight saving can move by an hour; with no bar by the expiry, it is room for a window bar before it (a whole one for bars of up to two hours). The gaps are in `evidence.gaps` (the first 10; `evidence.gapCount` counts all). A gap result, or an `ongoing` one flagged `gap_in_evaluation_window`, reports only an entry or confirmation before the first gap, and a result without a terminal over a gap has no excursion metrics. A window across a weekend, a daily or lunch break, or a thin symbol's bars without trades therefore does not complete automatically. `evaluate_due_analyses` takes evaluated results that stayed open (ambiguous or incomplete) last, in the order their current result was first recorded, so they do not crowd out analyses that just became due. An ambiguous or gapped result whose history reached the expiry comes out the same on every recheck with the same bars, so it is listed as skipped (`open_result_fixed_for_timeframe`) unless the run evaluates on another timeframe than its record (`evaluation_timeframe`, or else the analysis timeframe) or sets `include_fixed` (for bars changed by the chart's session or adjustment settings, or a backfill). A result recorded `complete` by an earlier version without closed bars through its expiry is listed as skipped (`legacy_complete_without_coverage`) and not re-evaluated. If history does not reach back to the analysis, load more or request a shorter `evaluation_timeframe`. The latter keeps the `expected_timeframe` overlay contract, temporarily switches only the selected chart, verifies symbol/resolution/bar evidence, and restores it. If `chartState.restored` is false, inspect `currentTimeframe` and restore manually. Daily and weekly aliases are supported; calendar-month `M` is `not_evaluable` because its duration varies.
|
|
365
365
|
|
|
366
366
|
The analysis journal defaults to `~/.tradingview-mcp/analysis-journal.jsonl`; override it with `TRADINGVIEW_MCP_ANALYSIS_JOURNAL_PATH`. `apply_analysis_overlay(confirm:true)` records the definition after verified readback, while outcome evaluation appends only with explicit `record:true`. The same ID and definition are idempotent; reusing an ID for a different definition or assigning conflicting completed labels is rejected. A definition conflict requires a new `analysis_id`, not a retry. If only journal writing fails, the application/evaluation result remains available with `journal.recorded:false` and a warning. Calibration uses only `target_before_stop=1` and `stop_before_target=0`; all other outcomes are counted by exclusion reason.
|
|
367
367
|
|
package/build/analysisOutcome.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
/** Gaps kept in an outcome's evidence; evidence.gapCount counts them all. */
|
|
2
|
+
const MAX_RECORDED_GAPS = 10;
|
|
3
|
+
const HOUR_MS = 3_600_000;
|
|
1
4
|
function resolutionMilliseconds(resolution) {
|
|
2
5
|
const value = resolution.trim().toUpperCase();
|
|
3
6
|
if (/^\d+$/.test(value))
|
|
@@ -19,6 +22,22 @@ function resolutionMilliseconds(resolution) {
|
|
|
19
22
|
throw new Error(`unsupported outcome resolution ${JSON.stringify(resolution)}`);
|
|
20
23
|
return count * unit;
|
|
21
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* Whether the history reaches an analysis's expiry: its last closed bar (starting at `closedThrough`) ends at or after
|
|
27
|
+
* it. Then any bar missing inside the window is one the feed never printed, such as a market closure; before it, the
|
|
28
|
+
* history may simply stop short (BACKLOG 102-04). With no expiry there is nothing to reach.
|
|
29
|
+
*/
|
|
30
|
+
export function historyCoversExpiry(closedThrough, resolution, expiresAt) {
|
|
31
|
+
if (expiresAt === null)
|
|
32
|
+
return true;
|
|
33
|
+
if (closedThrough === null)
|
|
34
|
+
return false;
|
|
35
|
+
const barMs = resolutionMilliseconds(resolution);
|
|
36
|
+
if (barMs === null)
|
|
37
|
+
return false;
|
|
38
|
+
const end = Date.parse(closedThrough) + barMs;
|
|
39
|
+
return Number.isFinite(end) && end >= Date.parse(expiresAt);
|
|
40
|
+
}
|
|
22
41
|
function atOrBeyond(state, value, level, favorable) {
|
|
23
42
|
if (favorable)
|
|
24
43
|
return state.bias === "bullish" ? value >= level : value <= level;
|
|
@@ -115,12 +134,79 @@ export function evaluateAnalysisOverlayOutcome(state, bars, resolution, now = ne
|
|
|
115
134
|
const end = start + barMs;
|
|
116
135
|
return start >= analyzedAtMs && (expiresAtMs === null || end <= expiresAtMs);
|
|
117
136
|
});
|
|
137
|
+
const windowClosed = expiresAtMs !== null && now.getTime() >= expiresAtMs;
|
|
138
|
+
// Whether the history reaches the expiry (historyCoversExpiry), or a forming bar already runs past it: then every bar
|
|
139
|
+
// inside the window has closed. A forming bar ending exactly at the expiry is still inside the window. Recorded as
|
|
140
|
+
// evidence.expiryCoveredBy, so due selection reads the same proof the evaluation used.
|
|
141
|
+
const latestBar = bars.at(-1);
|
|
142
|
+
const formingPastExpiry = expiresAtMs !== null && latestBar?.forming === true && Number.isFinite(latestBar.time) &&
|
|
143
|
+
latestBar.time * 1000 + barMs > expiresAtMs;
|
|
144
|
+
const closedCoversExpiry = expiresAtMs !== null && historyCoversExpiry(evidenceBase.closedThrough, resolution, state.expiresAt);
|
|
145
|
+
const expiryCoveredBy = closedCoversExpiry ? "closed_bar" : formingPastExpiry ? "forming_bar" : null;
|
|
146
|
+
const coversExpiry = expiresAtMs === null || expiryCoveredBy !== null;
|
|
147
|
+
// Bars missing inside the window (BACKLOG 102-04): room for a bar between where the next bar was due (the previous
|
|
148
|
+
// start plus one bar, from the bar the analysis fell in) and the next one, or for a whole window bar before the expiry
|
|
149
|
+
// once the history reaches it. Bars alone cannot show that a gap was a market closure, so a result decided after a
|
|
150
|
+
// gap, or one without a terminal over a window with a gap, stays open. Between bars the room is a bar less the hour a
|
|
151
|
+
// daylight-saving change moves a D or W bar (23 and 25 hour days), so the change is no gap but a day missing at it is.
|
|
152
|
+
const gaps = [];
|
|
153
|
+
const gapMs = barMs - Math.min(HOUR_MS, barMs / 2);
|
|
154
|
+
const anchor = closed.filter((bar) => bar.time * 1000 < analyzedAtMs).at(-1);
|
|
155
|
+
let dueAtMs = anchor === undefined ? analyzedAtMs
|
|
156
|
+
: anchor.time * 1000 + Math.ceil((analyzedAtMs - anchor.time * 1000) / barMs) * barMs;
|
|
157
|
+
for (const bar of eligible) {
|
|
158
|
+
const startMs = bar.time * 1000;
|
|
159
|
+
if (startMs - dueAtMs >= gapMs)
|
|
160
|
+
gaps.push({ from: new Date(dueAtMs).toISOString(), to: bar.timeIso });
|
|
161
|
+
dueAtMs = startMs + barMs;
|
|
162
|
+
}
|
|
163
|
+
// The window's tail runs to the next bar when it starts by the expiry (the forming bar that proves it, or a closed one
|
|
164
|
+
// past it), measured like the room between bars; otherwise to the expiry, with room for a window bar: a whole one for
|
|
165
|
+
// bars of up to two hours, and for longer ones a bar less the hour daylight saving may have moved it.
|
|
166
|
+
const nextStartMs = bars.find((bar) => bar.time * 1000 >= dueAtMs)?.time;
|
|
167
|
+
if (expiresAtMs !== null && expiryCoveredBy !== null) {
|
|
168
|
+
const tailEndsAtBar = nextStartMs !== undefined && nextStartMs * 1000 <= expiresAtMs;
|
|
169
|
+
const tailEndMs = tailEndsAtBar ? nextStartMs * 1000 : expiresAtMs;
|
|
170
|
+
if (tailEndMs - dueAtMs >= (tailEndsAtBar || barMs > 2 * HOUR_MS ? gapMs : barMs)) {
|
|
171
|
+
gaps.push({ from: new Date(dueAtMs).toISOString(), to: new Date(tailEndMs).toISOString() });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
118
174
|
const evidence = {
|
|
119
175
|
...evidenceBase,
|
|
120
176
|
evaluatedBars: eligible.length,
|
|
121
177
|
evidenceThrough: eligible.at(-1)?.timeIso ?? null,
|
|
178
|
+
expiryCoveredBy,
|
|
179
|
+
// A thin symbol on a low timeframe skips every bar without a trade, so the journal keeps the first few and a count.
|
|
180
|
+
gaps: gaps.slice(0, MAX_RECORDED_GAPS),
|
|
181
|
+
gapCount: gaps.length,
|
|
122
182
|
};
|
|
123
|
-
|
|
183
|
+
// An entry or confirmation found at or after the first gap may have come earlier, inside it, so only earlier ones are
|
|
184
|
+
// reported.
|
|
185
|
+
const beforeGap = (at) => at !== null && gaps.length > 0 && Date.parse(at) >= Date.parse(gaps[0].to) ? null : at;
|
|
186
|
+
const gapOpen = (activation) => ({
|
|
187
|
+
status: "incomplete",
|
|
188
|
+
outcome: "gap_in_evaluation_window",
|
|
189
|
+
analysisId: state.analysisId,
|
|
190
|
+
activation: { entryAt: beforeGap(activation.entryAt), confirmationAt: beforeGap(activation.confirmationAt) },
|
|
191
|
+
terminal: null,
|
|
192
|
+
qualityIssues: ["gap_in_evaluation_window"],
|
|
193
|
+
evidence,
|
|
194
|
+
});
|
|
195
|
+
/** A gap before this bar may hide an earlier entry, invalidation or terminal, so nothing decided here is final. */
|
|
196
|
+
const gapBefore = (bar) => gaps.length > 0 && Date.parse(gaps[0].to) <= bar.time * 1000;
|
|
197
|
+
if (eligible.length === 0 && windowClosed && !coversExpiry) {
|
|
198
|
+
return {
|
|
199
|
+
status: "incomplete",
|
|
200
|
+
outcome: "history_ends_before_expiry",
|
|
201
|
+
analysisId: state.analysisId,
|
|
202
|
+
activation: { entryAt: null, confirmationAt: null },
|
|
203
|
+
terminal: null,
|
|
204
|
+
qualityIssues: ["history_ends_before_expiry"],
|
|
205
|
+
evidence,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
if (eligible.length === 0 && windowClosed && gaps.length > 0)
|
|
209
|
+
return gapOpen({ entryAt: null, confirmationAt: null });
|
|
124
210
|
if (eligible.length === 0) {
|
|
125
211
|
return {
|
|
126
212
|
status: windowClosed ? "incomplete" : "ongoing",
|
|
@@ -138,7 +224,7 @@ export function evaluateAnalysisOverlayOutcome(state, bars, resolution, now = ne
|
|
|
138
224
|
let confirmationAt = null;
|
|
139
225
|
let active = false;
|
|
140
226
|
let previousBar = null;
|
|
141
|
-
const ambiguous = (outcome, bar, issue) => ({
|
|
227
|
+
const ambiguous = (outcome, bar, issue) => gapBefore(bar) ? gapOpen({ entryAt, confirmationAt }) : ({
|
|
142
228
|
status: "ambiguous",
|
|
143
229
|
outcome,
|
|
144
230
|
analysisId: state.analysisId,
|
|
@@ -148,7 +234,7 @@ export function evaluateAnalysisOverlayOutcome(state, bars, resolution, now = ne
|
|
|
148
234
|
qualityIssues: [issue],
|
|
149
235
|
evidence,
|
|
150
236
|
});
|
|
151
|
-
const invalidated = (outcome, bar) => ({
|
|
237
|
+
const invalidated = (outcome, bar) => gapBefore(bar) ? gapOpen({ entryAt, confirmationAt }) : ({
|
|
152
238
|
status: "complete",
|
|
153
239
|
outcome,
|
|
154
240
|
analysisId: state.analysisId,
|
|
@@ -226,6 +312,8 @@ export function evaluateAnalysisOverlayOutcome(state, bars, resolution, now = ne
|
|
|
226
312
|
if (openedBeyond && !previousBeyond) {
|
|
227
313
|
return ambiguous("gap_across_terminal", bar, "bar_open_gapped_across_terminal_level");
|
|
228
314
|
}
|
|
315
|
+
if (gapBefore(bar))
|
|
316
|
+
return gapOpen({ entryAt, confirmationAt });
|
|
229
317
|
return {
|
|
230
318
|
status: "complete",
|
|
231
319
|
outcome: terminal.kind === "target" ? "target_before_stop" : "stop_before_target",
|
|
@@ -239,6 +327,25 @@ export function evaluateAnalysisOverlayOutcome(state, bars, resolution, now = ne
|
|
|
239
327
|
}
|
|
240
328
|
previousBar = bar;
|
|
241
329
|
}
|
|
330
|
+
// A gap already found inside the window keeps the result open whatever later history shows, so it is reported first.
|
|
331
|
+
if (windowClosed && gaps.length > 0)
|
|
332
|
+
return gapOpen({ entryAt, confirmationAt });
|
|
333
|
+
// The clock passing the expiry is not enough to close a result with no terminal: until the history reaches the
|
|
334
|
+
// expiry a later bar could still bring the entry, the confirmation or a terminal, so it stays incomplete and due
|
|
335
|
+
// selection rechecks it. History up to 10:15 for an 11:00 expiry was "complete" with no terminal event, and a 10:30
|
|
336
|
+
// bar added later reached the stop (BACKLOG 102-04).
|
|
337
|
+
if (windowClosed && !coversExpiry) {
|
|
338
|
+
return {
|
|
339
|
+
status: "incomplete",
|
|
340
|
+
outcome: "history_ends_before_expiry",
|
|
341
|
+
analysisId: state.analysisId,
|
|
342
|
+
activation: { entryAt, confirmationAt },
|
|
343
|
+
terminal: null,
|
|
344
|
+
qualityIssues: ["history_ends_before_expiry"],
|
|
345
|
+
evidence,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
// Still open: a gap so far keeps only what came before it, and the result is flagged.
|
|
242
349
|
return {
|
|
243
350
|
status: windowClosed ? "complete" : "ongoing",
|
|
244
351
|
outcome: active
|
|
@@ -253,9 +360,9 @@ export function evaluateAnalysisOverlayOutcome(state, bars, resolution, now = ne
|
|
|
253
360
|
? "expired_without_confirmation"
|
|
254
361
|
: "awaiting_confirmation",
|
|
255
362
|
analysisId: state.analysisId,
|
|
256
|
-
activation: { entryAt, confirmationAt },
|
|
363
|
+
activation: { entryAt: beforeGap(entryAt), confirmationAt: beforeGap(confirmationAt) },
|
|
257
364
|
terminal: null,
|
|
258
|
-
qualityIssues: [],
|
|
365
|
+
qualityIssues: gaps.length > 0 ? ["gap_in_evaluation_window"] : [],
|
|
259
366
|
evidence,
|
|
260
367
|
};
|
|
261
368
|
}
|
|
@@ -288,6 +395,18 @@ export function computeAnalysisPathMetrics(state, bars, result) {
|
|
|
288
395
|
measurement: "entry_midpoint_reference; no activated path available",
|
|
289
396
|
};
|
|
290
397
|
}
|
|
398
|
+
// A path without a terminal runs to the last bar, across any gap, so its excursions would be understated.
|
|
399
|
+
if (result.terminal === null && "gapCount" in result.evidence && result.evidence.gapCount > 0) {
|
|
400
|
+
return {
|
|
401
|
+
methodologyVersion: "1.0",
|
|
402
|
+
referenceEntry,
|
|
403
|
+
structuralRiskPrice,
|
|
404
|
+
timing,
|
|
405
|
+
excursion: null,
|
|
406
|
+
grossRealizedR: null,
|
|
407
|
+
measurement: "entry_midpoint_reference; bars missing inside the window",
|
|
408
|
+
};
|
|
409
|
+
}
|
|
291
410
|
const evidenceThroughMs = result.evidence.evidenceThrough === null
|
|
292
411
|
? Number.POSITIVE_INFINITY
|
|
293
412
|
: Date.parse(result.evidence.evidenceThrough);
|
package/build/dueAnalyses.js
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
import { normalizeResolution } from "./analysisOverlay.js";
|
|
2
|
+
import { historyCoversExpiry } from "./analysisOutcome.js";
|
|
3
|
+
/** The outcomes that close an analysis without a terminal event, final only once the history reached its expiry. */
|
|
4
|
+
const WITHOUT_TERMINAL = new Set(["no_terminal_event", "not_activated", "expired_without_confirmation"]);
|
|
5
|
+
/**
|
|
6
|
+
* The proof of reaching the expiry that a record from this version names (evidence.expiryCoveredBy: a closed bar, or a
|
|
7
|
+
* forming bar past the expiry), null when it names none, or undefined for a record from an earlier version.
|
|
8
|
+
*/
|
|
9
|
+
function recordedProof(outcome) {
|
|
10
|
+
const evidence = outcome.result.evidence;
|
|
11
|
+
if (typeof evidence !== "object" || evidence === null || !("expiryCoveredBy" in evidence))
|
|
12
|
+
return undefined;
|
|
13
|
+
const coveredBy = evidence.expiryCoveredBy;
|
|
14
|
+
return coveredBy === "closed_bar" || coveredBy === "forming_bar" ? coveredBy : null;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Whether a recorded outcome's own evidence shows history through the expiry: the proof a record from this version
|
|
18
|
+
* names, or for an older one its last closed bar (see historyCoversExpiry).
|
|
19
|
+
*/
|
|
20
|
+
function recordCoversExpiry(outcome, expiresAt) {
|
|
21
|
+
const proof = recordedProof(outcome);
|
|
22
|
+
if (proof !== undefined)
|
|
23
|
+
return proof !== null;
|
|
24
|
+
const evidence = outcome.result.evidence;
|
|
25
|
+
const closedThrough = typeof evidence === "object" && evidence !== null && typeof evidence.closedThrough === "string"
|
|
26
|
+
? evidence.closedThrough
|
|
27
|
+
: null;
|
|
28
|
+
try {
|
|
29
|
+
return historyCoversExpiry(closedThrough, outcome.evidenceTimeframe, expiresAt);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
1
35
|
export function selectDueAnalyses(analyses, options = {}) {
|
|
2
36
|
const nowMs = (options.now ?? new Date()).getTime();
|
|
3
37
|
const limit = options.limit ?? 20;
|
|
@@ -14,7 +48,27 @@ export function selectDueAnalyses(analyses, options = {}) {
|
|
|
14
48
|
continue;
|
|
15
49
|
}
|
|
16
50
|
if (latest?.status === "complete") {
|
|
17
|
-
|
|
51
|
+
// An earlier version closed a result with no terminal by the clock alone, even when its history stopped short of
|
|
52
|
+
// the expiry (BACKLOG 102-04). Such a record is named, not rechecked: the append-only journal cannot replace it (a
|
|
53
|
+
// terminal found later conflicts, an equal result is a duplicate, an incomplete one ranks below it), so it would be
|
|
54
|
+
// selected on every call and crowd out the analyses that are due. Repairing them is BACKLOG 102-32.
|
|
55
|
+
skipped.push({
|
|
56
|
+
analysisId: definition.analysisId,
|
|
57
|
+
reason: WITHOUT_TERMINAL.has(latest.outcome) && !recordCoversExpiry(latest, definition.expiresAt)
|
|
58
|
+
? "legacy_complete_without_coverage" : "terminal_evaluation_exists",
|
|
59
|
+
});
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
// An ambiguous or gapped result whose history already reached the expiry comes out the same on every recheck with
|
|
63
|
+
// the same bars, so it is named instead of switching the chart for it on every call. A recheck on another timeframe
|
|
64
|
+
// than its record (evaluation_timeframe, or else the analysis timeframe) can change it: shorter bars may order an
|
|
65
|
+
// ambiguous bar, longer ones may cover bars without trades. includeFixed rechecks it anyway, for bars that changed
|
|
66
|
+
// with the chart's session or adjustment settings or a backfill.
|
|
67
|
+
if (options.includeFixed !== true && latest !== null &&
|
|
68
|
+
(latest.status === "ambiguous" || latest.outcome === "gap_in_evaluation_window") &&
|
|
69
|
+
typeof recordedProof(latest) === "string" &&
|
|
70
|
+
normalizeResolution(options.evaluationTimeframe ?? definition.timeframe) === normalizeResolution(latest.evidenceTimeframe)) {
|
|
71
|
+
skipped.push({ analysisId: definition.analysisId, reason: "open_result_fixed_for_timeframe" });
|
|
18
72
|
continue;
|
|
19
73
|
}
|
|
20
74
|
const expiryMs = definition.expiresAt === null ? null : Date.parse(definition.expiresAt);
|
|
@@ -52,7 +106,21 @@ export function selectDueAnalyses(analyses, options = {}) {
|
|
|
52
106
|
skipped.push({ analysisId: definition.analysisId, reason: "active_not_due" });
|
|
53
107
|
}
|
|
54
108
|
}
|
|
109
|
+
// Results that were evaluated and stayed open (ambiguous, a gap, a short or stopped history, history not reaching back)
|
|
110
|
+
// go last: they may never resolve, and with the oldest expiries they would otherwise take every slot from the analyses
|
|
111
|
+
// that just became due (BACKLOG 102-04). They go in the order their current result was first recorded, since a recheck
|
|
112
|
+
// that finds the same result records nothing (rotating them fairly is BACKLOG 102-34). The rest go by expiry, so an
|
|
113
|
+
// analysis whose window has closed but has no final evaluation comes before one still active.
|
|
114
|
+
const evaluatedOpen = (candidate) => candidate.latestOutcome !== null && candidate.latestOutcome.status !== "ongoing";
|
|
55
115
|
candidates.sort((left, right) => {
|
|
116
|
+
const leftOpen = evaluatedOpen(left), rightOpen = evaluatedOpen(right);
|
|
117
|
+
if (leftOpen !== rightOpen)
|
|
118
|
+
return leftOpen ? 1 : -1;
|
|
119
|
+
if (leftOpen) {
|
|
120
|
+
const byEvaluation = Date.parse(left.latestOutcome.evaluatedAt) - Date.parse(right.latestOutcome.evaluatedAt);
|
|
121
|
+
if (byEvaluation !== 0)
|
|
122
|
+
return byEvaluation;
|
|
123
|
+
}
|
|
56
124
|
const leftExpiry = left.definition.expiresAt === null
|
|
57
125
|
? Number.POSITIVE_INFINITY
|
|
58
126
|
: Date.parse(left.definition.expiresAt);
|
package/build/server.js
CHANGED
|
@@ -4179,7 +4179,11 @@ export function createServer({ cdp, tv, scanner, calendar, cot, realYield, journ
|
|
|
4179
4179
|
? {
|
|
4180
4180
|
remediation: result.outcome === "no_closed_bars_in_evaluation_window"
|
|
4181
4181
|
? "set evaluation_timeframe to a shorter interval with closed bars inside the analysis window"
|
|
4182
|
-
:
|
|
4182
|
+
: result.outcome === "history_ends_before_expiry"
|
|
4183
|
+
? "evaluate again once the chart has closed bars through the expiry; evaluate_due_analyses rechecks it"
|
|
4184
|
+
: result.outcome === "gap_in_evaluation_window"
|
|
4185
|
+
? "closed bars are missing inside the window (evidence.gaps) and bars alone cannot show a market closure, so the result stays open; a longer evaluation_timeframe may cover bars a thin symbol skipped without trades"
|
|
4186
|
+
: "call load_more_history, then evaluate again",
|
|
4183
4187
|
}
|
|
4184
4188
|
: {}),
|
|
4185
4189
|
...(result.outcome === "calendar_month_resolution_unsupported"
|
|
@@ -4259,10 +4263,12 @@ export function createServer({ cdp, tv, scanner, calendar, cot, realYield, journ
|
|
|
4259
4263
|
.describe("Maximum analyses to evaluate. Default: 20"),
|
|
4260
4264
|
include_active: z.boolean().optional()
|
|
4261
4265
|
.describe("Include active analyses with no prior evaluation. Default: false"),
|
|
4266
|
+
include_fixed: z.boolean().optional()
|
|
4267
|
+
.describe("Also recheck ambiguous or gapped results whose history reached the expiry on the same timeframe; they come out the same unless the chart's bars changed (session or adjustment settings, a backfill). Default: false"),
|
|
4262
4268
|
confirm: z.boolean().optional()
|
|
4263
4269
|
.describe("Must be true to change the chart and append outcomes. Default: false"),
|
|
4264
4270
|
},
|
|
4265
|
-
}, async ({ chart_index, evaluation_timeframe, count, load_more_bars, limit, include_active, confirm, }) => chartOperations.run(async () => {
|
|
4271
|
+
}, async ({ chart_index, evaluation_timeframe, count, load_more_bars, limit, include_active, include_fixed, confirm, }) => chartOperations.run(async () => {
|
|
4266
4272
|
try {
|
|
4267
4273
|
const initialContext = await tv.getChartContext();
|
|
4268
4274
|
const selectedIndex = chart_index ?? initialContext.activeChartIndex;
|
|
@@ -4284,7 +4290,12 @@ export function createServer({ cdp, tv, scanner, calendar, cot, realYield, journ
|
|
|
4284
4290
|
});
|
|
4285
4291
|
}
|
|
4286
4292
|
const journalView = await journal.list({ limit: 500 });
|
|
4287
|
-
const selection = selectDueAnalyses(journalView.analyses, {
|
|
4293
|
+
const selection = selectDueAnalyses(journalView.analyses, {
|
|
4294
|
+
includeActive: include_active ?? false,
|
|
4295
|
+
limit: limit ?? 20,
|
|
4296
|
+
evaluationTimeframe: evaluation_timeframe,
|
|
4297
|
+
includeFixed: include_fixed ?? false,
|
|
4298
|
+
});
|
|
4288
4299
|
const requestedBars = count ?? 1000;
|
|
4289
4300
|
const historyLoad = load_more_bars ?? 0;
|
|
4290
4301
|
const previewItems = selection.candidates.map((candidate) => {
|
|
@@ -4314,6 +4325,7 @@ export function createServer({ cdp, tv, scanner, calendar, cot, realYield, journ
|
|
|
4314
4325
|
requestedBars,
|
|
4315
4326
|
loadMoreBars: historyLoad,
|
|
4316
4327
|
includeActive: include_active ?? false,
|
|
4328
|
+
includeFixed: include_fixed ?? false,
|
|
4317
4329
|
journalPopulation: journalView.total,
|
|
4318
4330
|
journalScanned: journalView.returned,
|
|
4319
4331
|
journalScanTruncated: journalView.total > journalView.returned,
|
|
@@ -2,6 +2,8 @@ import { cotFreshness } from "./cot.js";
|
|
|
2
2
|
import { normalizeResolution } from "./analysisOverlay.js";
|
|
3
3
|
import { buildMarketSnapshot } from "./marketSnapshot.js";
|
|
4
4
|
import { buildExecutionSnapshot } from "./executionSnapshot.js";
|
|
5
|
+
/** Events the gate reads for its window: the calendar's maximum. */
|
|
6
|
+
const EVENT_GATE_LIMIT = 200;
|
|
5
7
|
function evidence(required, status, source, observedAt, sourceAt, freshness, data) {
|
|
6
8
|
return {
|
|
7
9
|
required,
|
|
@@ -25,6 +27,8 @@ function topLevelStatus(issues) {
|
|
|
25
27
|
}
|
|
26
28
|
export async function buildTradeDecisionContext(dependencies, options, now = new Date()) {
|
|
27
29
|
const requestedAt = now.toISOString();
|
|
30
|
+
// Wall-clock start, so the event gate can tell how long the request took from the given now.
|
|
31
|
+
const startedMs = Date.now();
|
|
28
32
|
const issues = [];
|
|
29
33
|
let replayStatus = null;
|
|
30
34
|
try {
|
|
@@ -112,6 +116,20 @@ export async function buildTradeDecisionContext(dependencies, options, now = new
|
|
|
112
116
|
countries: options.countries,
|
|
113
117
|
minImportance: options.minImportance,
|
|
114
118
|
});
|
|
119
|
+
// The event gate reads its own calendar window (BACKLOG 102-06): the snapshot's events start at the request, so an
|
|
120
|
+
// event released a few minutes ago never reached the after-release blackout and the request could be trade_ready.
|
|
121
|
+
// The window runs from the after-release minutes before the request to the before-release minutes after it, with a
|
|
122
|
+
// minute either side for the source's boundary handling and the time the request takes; the gate applies the exact
|
|
123
|
+
// window below.
|
|
124
|
+
const blackoutFrom = new Date(now.getTime() - options.eventBlackoutAfterMinutes * 60_000);
|
|
125
|
+
const eventGateThroughMs = now.getTime() + options.eventBlackoutBeforeMinutes * 60_000 + 60_000;
|
|
126
|
+
const eventGatePromise = Promise.resolve().then(() => dependencies.calendar.getEvents({
|
|
127
|
+
countries: options.countries,
|
|
128
|
+
from: new Date(blackoutFrom.getTime() - 60_000).toISOString(),
|
|
129
|
+
to: new Date(eventGateThroughMs).toISOString(),
|
|
130
|
+
minImportance: options.minimumEventImportance,
|
|
131
|
+
limit: EVENT_GATE_LIMIT,
|
|
132
|
+
})).then((value) => ({ status: "fulfilled", value }), () => ({ status: "rejected" }));
|
|
115
133
|
const chartEvidencePromise = chartMatches
|
|
116
134
|
? Promise.allSettled([
|
|
117
135
|
dependencies.tv.getOhlcv(options.ohlcvCount, chartIndex),
|
|
@@ -129,11 +147,12 @@ export async function buildTradeDecisionContext(dependencies, options, now = new
|
|
|
129
147
|
const realYieldPromise = options.includeRealYield
|
|
130
148
|
? dependencies.realYield.getLatest().then((value) => ({ status: "fulfilled", value }), () => ({ status: "rejected" }))
|
|
131
149
|
: Promise.resolve(null);
|
|
132
|
-
const [market, initialChartResults, positioningResult, realYieldResult] = await Promise.all([
|
|
150
|
+
const [market, initialChartResults, positioningResult, realYieldResult, eventGateResult] = await Promise.all([
|
|
133
151
|
marketPromise,
|
|
134
152
|
chartEvidencePromise,
|
|
135
153
|
positioningPromise,
|
|
136
154
|
realYieldPromise,
|
|
155
|
+
eventGatePromise,
|
|
137
156
|
]);
|
|
138
157
|
let chartResults = initialChartResults;
|
|
139
158
|
try {
|
|
@@ -336,13 +355,59 @@ export async function buildTradeDecisionContext(dependencies, options, now = new
|
|
|
336
355
|
}
|
|
337
356
|
const importanceRank = { low: 0, medium: 1, high: 2 };
|
|
338
357
|
const eventThreshold = importanceRank[options.minimumEventImportance];
|
|
339
|
-
|
|
340
|
-
|
|
358
|
+
// The window opens at the after-release minutes before the request and closes at the before-release minutes after
|
|
359
|
+
// it completes, so an event that came within reach while the sources were read still counts.
|
|
360
|
+
const blackoutToMs = now.getTime() + Math.max(0, Date.now() - startedMs) + options.eventBlackoutBeforeMinutes * 60_000;
|
|
361
|
+
const gateEvents = eventGateResult.status === "fulfilled" ? eventGateResult.value.events : [];
|
|
362
|
+
// The snapshot's events (from the request on) are checked too, so the gate is never weaker than what it shows.
|
|
363
|
+
const seen = new Set();
|
|
364
|
+
const candidateEvents = [...gateEvents, ...(market.economic_events?.events ?? [])].filter((event) => {
|
|
365
|
+
const key = `${event.id}|${event.date}|${event.title}`;
|
|
366
|
+
if (seen.has(key))
|
|
341
367
|
return false;
|
|
342
|
-
|
|
343
|
-
return
|
|
344
|
-
|
|
368
|
+
seen.add(key);
|
|
369
|
+
return importanceRank[event.importance] >= eventThreshold;
|
|
370
|
+
});
|
|
371
|
+
const activeEvents = candidateEvents.filter((event) => {
|
|
372
|
+
const eventMs = Date.parse(event.date);
|
|
373
|
+
return eventMs >= blackoutFrom.getTime() && eventMs <= blackoutToMs;
|
|
345
374
|
});
|
|
375
|
+
// The window cannot be shown clear without the calendar, or when the gate's own read may lack an event inside it:
|
|
376
|
+
// the source returns the earliest first up to the limit, so a full answer ending inside the window may have cut later
|
|
377
|
+
// ones; an event the gate asked for whose time cannot be read may be inside it; and a request that outlasted the
|
|
378
|
+
// fetch's minute of slack left the end of the window unread.
|
|
379
|
+
const gateDates = gateEvents.map((event) => Date.parse(event.date));
|
|
380
|
+
const incompleteReasons = eventGateResult.status !== "fulfilled" ? [] : [
|
|
381
|
+
...(Math.max(eventGateResult.value.returned || 0, gateEvents.length) >= EVENT_GATE_LIMIT &&
|
|
382
|
+
!(Math.max(...gateDates) > blackoutToMs) ? ["limit_reached"] : []),
|
|
383
|
+
...(gateEvents.some((event, index) => importanceRank[event.importance] >= eventThreshold && Number.isNaN(gateDates[index]))
|
|
384
|
+
? ["unreadable_event_time"] : []),
|
|
385
|
+
...(blackoutToMs > eventGateThroughMs ? ["request_outlasted_window"] : []),
|
|
386
|
+
];
|
|
387
|
+
const eventGateStatus = activeEvents.length > 0
|
|
388
|
+
? "blackout"
|
|
389
|
+
: eventGateResult.status === "rejected"
|
|
390
|
+
? "unavailable"
|
|
391
|
+
: incompleteReasons.length > 0
|
|
392
|
+
? "incomplete"
|
|
393
|
+
: "clear";
|
|
394
|
+
if (eventGateStatus === "unavailable") {
|
|
395
|
+
issues.push({
|
|
396
|
+
code: "event_gate_unavailable",
|
|
397
|
+
severity: "warning",
|
|
398
|
+
component: "economic_events",
|
|
399
|
+
message: "The economic calendar could not be read for the blackout window, so the event gate is not clear.",
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
else if (eventGateStatus === "incomplete") {
|
|
403
|
+
issues.push({
|
|
404
|
+
code: "event_gate_incomplete",
|
|
405
|
+
severity: "warning",
|
|
406
|
+
component: "economic_events",
|
|
407
|
+
message: "The economic calendar read for the blackout window may lack events inside it, so the event gate is not clear.",
|
|
408
|
+
details: { reasons: incompleteReasons, limit: EVENT_GATE_LIMIT },
|
|
409
|
+
});
|
|
410
|
+
}
|
|
346
411
|
if (activeEvents.length > 0) {
|
|
347
412
|
issues.push({
|
|
348
413
|
code: "event_blackout_active",
|
|
@@ -355,7 +420,7 @@ export async function buildTradeDecisionContext(dependencies, options, now = new
|
|
|
355
420
|
const hasErrors = issues.some((issue) => issue.severity === "error");
|
|
356
421
|
const decisionStatus = hasErrors
|
|
357
422
|
? "blocked"
|
|
358
|
-
:
|
|
423
|
+
: eventGateStatus !== "clear" || !executionReady
|
|
359
424
|
? "wait"
|
|
360
425
|
: "trade_ready";
|
|
361
426
|
return {
|
|
@@ -385,9 +450,10 @@ export async function buildTradeDecisionContext(dependencies, options, now = new
|
|
|
385
450
|
execution: evidence(true, executionReady ? "available" : executionSnapshot?.status === "blocked" ? "blocked" : "partial", executionQuote?.source ?? "execution_snapshot", executionQuote?.observed_at ?? executionSnapshot?.completed_at ?? completedAt, executionQuote?.source_at ?? null, executionQuote?.freshness ?? { status: "unavailable" }, executionSnapshot),
|
|
386
451
|
},
|
|
387
452
|
event_gate: {
|
|
388
|
-
status:
|
|
453
|
+
status: eventGateStatus,
|
|
389
454
|
before_minutes: options.eventBlackoutBeforeMinutes,
|
|
390
455
|
after_minutes: options.eventBlackoutAfterMinutes,
|
|
456
|
+
window: { from: blackoutFrom.toISOString(), to: new Date(blackoutToMs).toISOString() },
|
|
391
457
|
minimum_importance: options.minimumEventImportance,
|
|
392
458
|
active_events: activeEvents,
|
|
393
459
|
},
|