@orangecharts/wrun-chart-host 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +11 -5
  2. package/dist/constants/scriptEditor/builtin-script-snippets.d.ts +133 -0
  3. package/dist/constants/scriptEditor/builtin-script-snippets.js +451 -0
  4. package/dist/host-env.d.ts +8 -6
  5. package/dist/host-ports.types.d.ts +7 -22
  6. package/dist/index.d.ts +10 -0
  7. package/dist/index.js +10 -0
  8. package/dist/utility/chart/date-labelled-interval.leaf.d.ts +15 -0
  9. package/dist/utility/chart/date-labelled-interval.leaf.js +19 -0
  10. package/dist/utility/chart/indicator-run-interval.util.d.ts +130 -0
  11. package/dist/utility/chart/indicator-run-interval.util.js +268 -0
  12. package/dist/utility/chart/window-geometry.leaf.d.ts +119 -0
  13. package/dist/utility/chart/window-geometry.leaf.js +391 -0
  14. package/dist/utility/chart/window-owner.leaf.d.ts +19 -0
  15. package/dist/utility/chart/window-owner.leaf.js +24 -0
  16. package/dist/utility/html-escape.leaf.d.ts +11 -0
  17. package/dist/utility/html-escape.leaf.js +20 -0
  18. package/dist/utility/wrun/sources/lanes/option_daily.d.ts +43 -15
  19. package/dist/utility/wrun/sources/lanes/option_daily.js +78 -20
  20. package/dist/utility/wrun/sources/lanes/option_stats_10m.d.ts +14 -10
  21. package/dist/utility/wrun/sources/lanes/option_stats_10m.js +5 -4
  22. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +22 -3
  23. package/dist/utility/wrun/sources/opra-option-lanes.util.js +38 -7
  24. package/dist/utility/wrun/sources/registry.js +31 -1
  25. package/dist/utility/wrun/sources/row-lane-registry.js +5 -5
  26. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +49 -0
  27. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +74 -18
  28. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +49 -0
  29. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +57 -47
  30. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +36 -4
  31. package/dist/utility/wrun/sources/row-lanes/option_surface.js +6 -12
  32. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +37 -3
  33. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +128 -2
  34. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +233 -51
  35. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +0 -8
  36. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +26 -24
  37. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +85 -104
  38. package/dist/utility/wrun/wrun-opra-stats.leaf.d.ts +29 -10
  39. package/dist/utility/wrun/wrun-opra-stats.leaf.js +29 -10
  40. package/dist/utility/wrun/wrun-panel-mount.lazy.d.ts +10 -0
  41. package/dist/utility/wrun/wrun-panel-mount.lazy.js +68 -0
  42. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +377 -0
  43. package/dist/utility/wrun/wrun-panel-mount.util.js +2251 -0
  44. package/dist/utility/wrun/wrun-pause-dim.util.d.ts +52 -0
  45. package/dist/utility/wrun/wrun-pause-dim.util.js +153 -0
  46. package/dist/utility/wrun/wrun-plot-gate.types.d.ts +23 -0
  47. package/dist/utility/wrun/wrun-plot-gate.types.js +7 -0
  48. package/dist/utility/wrun/wrun-run-interval-projection.types.d.ts +14 -0
  49. package/dist/utility/wrun/wrun-run-interval-projection.types.js +1 -0
  50. package/package.json +1 -1
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The date-labelled bar rule of chart-display-timezone.util.ts (which re-exports it and reads it for the display
3
+ * offset) as a leaf with no import: the child mount (wrun-panel-mount.util) reads it, and it moves into the wrun
4
+ * chart-host package, which the offset's user store may not reach.
5
+ */
6
+ /**
7
+ * Whether a chart at this BAR interval labels its bars by their date: daily
8
+ * and longer, the TradingView rule. Those bars are stamped 00:00 UTC of their
9
+ * date (crypto, the CME trade date, Monday for weeks), so any negative display
10
+ * offset printed the day before: on New York (-4) the 1 Oct daily bar read
11
+ * "Wed, 30 Sep 2026 20:00" and the 1 Sep month tick read "31". Their dates
12
+ * render from the raw UTC timestamp instead. False without an interval (an
13
+ * event or clock time).
14
+ */
15
+ export declare function isDateLabelledBarInterval(barIntervalMs?: number): boolean;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The date-labelled bar rule of chart-display-timezone.util.ts (which re-exports it and reads it for the display
3
+ * offset) as a leaf with no import: the child mount (wrun-panel-mount.util) reads it, and it moves into the wrun
4
+ * chart-host package, which the offset's user store may not reach.
5
+ */
6
+ const HOUR_MS = 3_600_000;
7
+ const DAY_MS = 24 * HOUR_MS;
8
+ /**
9
+ * Whether a chart at this BAR interval labels its bars by their date: daily
10
+ * and longer, the TradingView rule. Those bars are stamped 00:00 UTC of their
11
+ * date (crypto, the CME trade date, Monday for weeks), so any negative display
12
+ * offset printed the day before: on New York (-4) the 1 Oct daily bar read
13
+ * "Wed, 30 Sep 2026 20:00" and the 1 Sep month tick read "31". Their dates
14
+ * render from the raw UTC timestamp instead. False without an interval (an
15
+ * event or clock time).
16
+ */
17
+ export function isDateLabelledBarInterval(barIntervalMs) {
18
+ return typeof barIntervalMs === 'number' && barIntervalMs >= DAY_MS;
19
+ }
@@ -0,0 +1,130 @@
1
+ import type { BuiltinInputReader } from '../../constants/scriptEditor/builtin-script-snippets.js';
2
+ /**
3
+ * Built-ins whose `timeframe` input runs the engine at that interval: every built-in template with
4
+ * the input, the 14 classics (P2, 2026-10-03) and the 14 TradingView staples (2026-10-04), each
5
+ * pinned by tests/utility/chart/indicator-run-interval.parity.spec.ts against its own chart at that
6
+ * interval. A built-in without the input (Zig Zag, Pivot Points, Volume Bubbles) and every
7
+ * community script run at the chart's interval.
8
+ */
9
+ export declare const NATIVE_RUN_INTERVAL_SUBTYPES: ReadonlySet<string>;
10
+ /**
11
+ * The lookback, in run bars, a converted built-in's chart path computes over where the engine's
12
+ * declared lookback misses a term. The declaration pass reports the deepest single input of each
13
+ * function it sees (MACD's slow period, the Ichimoku lagging span, the stochastic %K window, one
14
+ * Wilder period for ADX), not the chain the template runs: MACD's signal EMA runs over the slow
15
+ * EMA, Ichimoku displaces its spans past the lagging window, the stochastic smooths %K and then
16
+ * %D (and an oscillator smoothing after that), ADX averages period DX values that each need
17
+ * period true ranges. The warm-up (run-interval-engine.util) takes the deeper of this and the
18
+ * declared lookback, so every other converted built-in, whose declaration is right (a period, a
19
+ * volume MA length, none for the path-dependent ADL, OBV and PSAR, which read the warm-up floor),
20
+ * needs no entry. Mirrors WRUN_RUN_INTERVAL_TWINS (wrun-run-interval.util) with the templates' input
21
+ * names. `inputs` reads each input as set on the overlay, else as the template declares it, else 0.
22
+ *
23
+ * The staples (measured against the declaration pass, 2026-10-04): the pass does not trace an input
24
+ * into atr(), wpr() or highestbars(), so Supertrend, Keltner's ATR bands, Williams %R and Aroon
25
+ * declare nothing for it; an offset reads the line that many bars back (Donchian, WMA, VWMA); Hull
26
+ * runs its outer average over round(sqrt(period)) hull inputs; the Stochastic RSI chains the RSI,
27
+ * its stochastic window and the K and D averages. ATR, CMF, Momentum, ROC and the Awesome
28
+ * Oscillator declare their own lookback right. Supertrend is path-dependent beyond its ATR (its
29
+ * bands and trend carry from the first loaded bar), like PSAR.
30
+ */
31
+ export declare const NATIVE_RUN_INTERVAL_LOOKBACK_BARS: Readonly<Record<string, (inputs: BuiltinInputReader) => number>>;
32
+ export interface OverlayRunInterval {
33
+ /** Chart interval key the engine runs at ("1h", "1d"). */
34
+ interval: string;
35
+ intervalMs: number;
36
+ /**
37
+ * On: every chart bar shows the last run bar that closed before it. Off: the same, except the
38
+ * chart bars of the newest run bar's bucket show that (forming) bar.
39
+ */
40
+ waitForClose: boolean;
41
+ /**
42
+ * The run bars ride the CME session lattice: the chart's venue is one the gateway rolls up on it
43
+ * (CME, CBOT, NYMEX, COMEX; overlayWrunRunInterval sets it, for the wrun twins only). A run bar's
44
+ * span is then read on the session calendar (runBarSpan): at 4h, 1D and 1W its session bar's
45
+ * open and close, a 1D bar stamped 00:00Z of its trade date after its 17:00 Chicago open the
46
+ * evening before, a 1W bar on the Monday after its Sunday open; at the widths that divide an hour
47
+ * the lattice is the plain grid. A session gap (the daily halt, a weekend, a holiday) holds no run
48
+ * bar of its own (nextRunBarCloseMs). Data, never a function: the stamp rides contexts and
49
+ * results. Absent everywhere else.
50
+ */
51
+ sessionLattice?: boolean;
52
+ }
53
+ /** What a run bar's span reads: the run interval and whether its bars ride the CME session lattice. */
54
+ export type RunBarCalendar = Pick<OverlayRunInterval, 'intervalMs' | 'sessionLattice'>;
55
+ /** A run bar's span: it takes trades from `open` until `close`. */
56
+ export interface RunBarSpan {
57
+ open: number;
58
+ close: number;
59
+ }
60
+ /**
61
+ * The [open, close) of the run bar stamped `stamp`: `[stamp, stamp + intervalMs)`, or on the CME
62
+ * session lattice its session bar's (cmeSessionBarOpenMs, cmeSessionBarEndMs: a 1D bar stamped at
63
+ * 00:00Z of its trade date opens at the 17:00 Chicago open before it and closes at the next one).
64
+ * A stamp the lattice books no bar to (a width that divides an hour, a regular-hours bar, a time
65
+ * that is no run bar's) reads the plain span.
66
+ */
67
+ export declare function runBarSpan(stamp: number, run: RunBarCalendar): RunBarSpan;
68
+ /**
69
+ * The close of the run bar after the one stamped `stamp`: from there on a chart bar shows a run bar
70
+ * later than it. Plain, the next run bar opens at its close (`stamp + 2 * intervalMs`). On the
71
+ * session lattice a gap (the daily halt, a weekend, a holiday) holds no run bar, so the next one is
72
+ * the run bar of the first chart bar (`chartTimes`, ascending) at or after its close: that chart
73
+ * bar's session bar when `stamp` is one, else the run bar it opens (a session reopens on a run
74
+ * bar's open, a regular-hours one included). Infinity when no chart bar reaches that close.
75
+ */
76
+ export declare function nextRunBarCloseMs(stamp: number, chartTimes: readonly number[], run: RunBarCalendar): number;
77
+ export interface RunIntervalInput {
78
+ /** The overlay's `settings.subType` ("RSI"). */
79
+ subType: unknown;
80
+ /** The overlay's settings: input values live flat under each input's name. */
81
+ settings: unknown;
82
+ /** The chart's interval, as a key ("5m") or milliseconds. */
83
+ chartInterval: unknown;
84
+ /** Market replay keeps the template path. */
85
+ replay?: boolean;
86
+ }
87
+ /**
88
+ * The run interval a Timeframe option label ("1h", "1D") selects on a chart of `chartInterval`:
89
+ * coarser than the chart, else null (the chart's own interval, an unknown label, "chart"). Shared
90
+ * by the kScript built-ins (resolveRunInterval) and their wrun Indicators (wrun-run-interval.util).
91
+ */
92
+ export declare function runIntervalOfTimeframeLabel(label: unknown, chartInterval: unknown): Pick<OverlayRunInterval, 'interval' | 'intervalMs'> | null;
93
+ /**
94
+ * Whether a Timeframe option label selects the chart's own interval or a finer one. Such a
95
+ * selection means "chart" (HTF-NATIVE-PLAN.md D3a): the resolver below answers null for it, and the
96
+ * engine must see `timeframe: "chart"` too (chartIntervalEngineMetadata), or the template's
97
+ * selected-timeframe branch calls htf() with an interval below its base and the engine throws on
98
+ * every update ("htf() timeframe 900000ms must be >= base interval 3600000ms": a 15m selection
99
+ * on a 1h chart froze the line at its last good run, Kyle's 2026-10-03 INT dump). Their wrun twins
100
+ * read it too (wrunTimeframeIsChartOrFiner, wrun-run-interval.util).
101
+ */
102
+ export declare function timeframeIsChartOrFiner(label: unknown, chartInterval: unknown): boolean;
103
+ /**
104
+ * The interval an overlay's engine runs at when it is coarser than the chart's, else null (the
105
+ * overlay runs at the chart's interval, as before). A selection at or below the chart's interval
106
+ * is the chart's own, so it takes the plain chart path too.
107
+ */
108
+ export declare function resolveRunInterval(input: RunIntervalInput): OverlayRunInterval | null;
109
+ /** The settings the engine sees for a run-interval overlay: the template takes its plain chart path. */
110
+ export declare function engineSettingsForRunInterval<T extends object>(settings: T): T & {
111
+ timeframe: 'chart';
112
+ };
113
+ /**
114
+ * Projects run-interval rows (oldest first, `row[0]` = the run bar's stamp, its open off the
115
+ * session lattice) onto the chart's bars: one row per chart time, with the cells of the run row that
116
+ * bar shows. Each run bar's span is read by runBarSpan (`sessionLattice`: the CME session calendar).
117
+ *
118
+ * Wait for close on: a chart bar shows the last run bar that closed at or before it
119
+ * (`close <= chartTime`, plain `stamp + runMs`), so a 5m bar in hour b shows hour b - 1. Off: the
120
+ * same, except the chart bars inside the newest run row's span show that row (the forming bar,
121
+ * live; on the lattice from its session open, before a 1D or 1W stamp). Chart bars before the first
122
+ * shown row get NaN cells. Run rows before the first chart bar (the warm-up) are dropped.
123
+ */
124
+ export declare function projectRunRowsOntoChart(rows: readonly (readonly unknown[] | null | undefined)[], chartTimes: readonly number[], runMs: number, waitForClose: boolean, sessionLattice?: boolean): unknown[][];
125
+ /**
126
+ * The chart time a run-bar time anchor (a drawing point at a run bar's stamp) lands on: where that
127
+ * bar's value first shows (its close with wait for close on, its open with it off, read by
128
+ * runBarSpan), clamped to the chart's loaded bars.
129
+ */
130
+ export declare function projectRunTimeOntoChart(runTime: number, chartTimes: readonly number[], runMs: number, waitForClose: boolean, sessionLattice?: boolean): number;
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Run interval: TradingView's indicator Timeframe model for built-ins (HTF-NATIVE-PLAN.md).
3
+ *
4
+ * A built-in whose `timeframe` input selects an interval coarser than its chart runs its engine AT
5
+ * that interval: the template's plain chart path on real candles of that interval, exactly what a
6
+ * chart on that interval computes. Its rows are then projected onto the chart's bars
7
+ * (projectRunRowsOntoChart). This replaces the template-side selected-timeframe branches, which
8
+ * rebuilt the coarse candles from the chart's loaded bars and never warmed up (2026-10-01: a 5m RSI
9
+ * at 1h read 51.12 against the 1h chart's 50.19).
10
+ *
11
+ * NATIVE_RUN_INTERVAL_SUBTYPES lists the built-ins converted so far. Market replay keeps the
12
+ * template path until replay can serve run-interval candles clipped at the replay cursor.
13
+ */
14
+ import { Intervals } from '../../constants/interval.constants.js';
15
+ import { cmeSessionBarEndMs, cmeSessionBarOpenMs, cmeSessionBucketMs } from './cme-session-bucket.util.js';
16
+ /**
17
+ * Built-ins whose `timeframe` input runs the engine at that interval: every built-in template with
18
+ * the input, the 14 classics (P2, 2026-10-03) and the 14 TradingView staples (2026-10-04), each
19
+ * pinned by tests/utility/chart/indicator-run-interval.parity.spec.ts against its own chart at that
20
+ * interval. A built-in without the input (Zig Zag, Pivot Points, Volume Bubbles) and every
21
+ * community script run at the chart's interval.
22
+ */
23
+ export const NATIVE_RUN_INTERVAL_SUBTYPES = new Set([
24
+ 'ADL',
25
+ 'ADX',
26
+ 'AO',
27
+ 'AROON',
28
+ 'ATR',
29
+ 'BOLLINGER_BANDS',
30
+ 'CCI',
31
+ 'CMF',
32
+ 'DONCHIAN',
33
+ 'EMA',
34
+ 'HMA',
35
+ 'ICHI_CLOUD',
36
+ 'KELTNER',
37
+ 'MACD',
38
+ 'MFI',
39
+ 'MOMENTUM',
40
+ 'OBV',
41
+ 'PSAR',
42
+ 'ROC',
43
+ 'RSI',
44
+ 'SMA',
45
+ 'STOCH',
46
+ 'STOCH_RSI',
47
+ 'SUPERTREND',
48
+ 'VOLUME_BAR',
49
+ 'VWMA',
50
+ 'WILLIAMS_R',
51
+ 'WMA',
52
+ ]);
53
+ /**
54
+ * The lookback, in run bars, a converted built-in's chart path computes over where the engine's
55
+ * declared lookback misses a term. The declaration pass reports the deepest single input of each
56
+ * function it sees (MACD's slow period, the Ichimoku lagging span, the stochastic %K window, one
57
+ * Wilder period for ADX), not the chain the template runs: MACD's signal EMA runs over the slow
58
+ * EMA, Ichimoku displaces its spans past the lagging window, the stochastic smooths %K and then
59
+ * %D (and an oscillator smoothing after that), ADX averages period DX values that each need
60
+ * period true ranges. The warm-up (run-interval-engine.util) takes the deeper of this and the
61
+ * declared lookback, so every other converted built-in, whose declaration is right (a period, a
62
+ * volume MA length, none for the path-dependent ADL, OBV and PSAR, which read the warm-up floor),
63
+ * needs no entry. Mirrors WRUN_RUN_INTERVAL_TWINS (wrun-run-interval.util) with the templates' input
64
+ * names. `inputs` reads each input as set on the overlay, else as the template declares it, else 0.
65
+ *
66
+ * The staples (measured against the declaration pass, 2026-10-04): the pass does not trace an input
67
+ * into atr(), wpr() or highestbars(), so Supertrend, Keltner's ATR bands, Williams %R and Aroon
68
+ * declare nothing for it; an offset reads the line that many bars back (Donchian, WMA, VWMA); Hull
69
+ * runs its outer average over round(sqrt(period)) hull inputs; the Stochastic RSI chains the RSI,
70
+ * its stochastic window and the K and D averages. ATR, CMF, Momentum, ROC and the Awesome
71
+ * Oscillator declare their own lookback right. Supertrend is path-dependent beyond its ATR (its
72
+ * bands and trend carry from the first loaded bar), like PSAR.
73
+ */
74
+ export const NATIVE_RUN_INTERVAL_LOOKBACK_BARS = {
75
+ ADX: (inputs) => 2 * inputs.num('period'),
76
+ AROON: (inputs) => inputs.num('length') + 1,
77
+ DONCHIAN: (inputs) => inputs.num('period') + inputs.num('offset'),
78
+ HMA: (inputs) => inputs.num('period') + Math.round(Math.sqrt(inputs.num('period'))),
79
+ ICHI_CLOUD: (inputs) => Math.max(inputs.num('conversionPeriod'), inputs.num('basePeriod'), inputs.num('laggingSpanPeriod')) +
80
+ inputs.num('displacement'),
81
+ KELTNER: (inputs) => Math.max(inputs.num('period'), keltnerBandBars(inputs)),
82
+ MACD: (inputs) => Math.max(inputs.num('fastPeriod'), inputs.num('slowPeriod')) + inputs.num('signalPeriod'),
83
+ STOCH: (inputs) => inputs.num('kPeriod') + inputs.num('kSmoothing') + inputs.num('dPeriod') + oscillatorSmoothingBars(inputs),
84
+ STOCH_RSI: (inputs) => inputs.num('rsiLength') + inputs.num('stochLength') + inputs.num('kSmoothing') + inputs.num('dSmoothing'),
85
+ SUPERTREND: (inputs) => inputs.num('atrPeriod'),
86
+ VWMA: (inputs) => inputs.num('period') + inputs.num('offset'),
87
+ WILLIAMS_R: (inputs) => inputs.num('length'),
88
+ WMA: (inputs) => inputs.num('period') + inputs.num('offset'),
89
+ };
90
+ /** Keltner's band smoothing: its own ATR period on ATR bands (the default style), nothing more otherwise. */
91
+ function keltnerBandBars(inputs) {
92
+ const style = inputs.str('bandStyle');
93
+ return style === '' || style === 'Average True Range' ? inputs.num('atrPeriod') : 0;
94
+ }
95
+ /** The oscillator smoothing MA (OSCILLATOR_SMOOTHING_INPUTS) chained after the value: 0 while it is off. */
96
+ function oscillatorSmoothingBars(inputs) {
97
+ const type = inputs.str('smoothingType');
98
+ return type === '' || type === 'None' ? 0 : inputs.num('smoothingLength');
99
+ }
100
+ /** The templates' `timeframe` options (CLASSIC_TIMEFRAME_INPUTS) as chart interval keys. */
101
+ const TIMEFRAME_INTERVALS = {
102
+ '5m': '5m',
103
+ '15m': '15m',
104
+ '30m': '30m',
105
+ '1h': '1h',
106
+ '4h': '4h',
107
+ '1D': '1d',
108
+ '1W': '1w',
109
+ };
110
+ /**
111
+ * The [open, close) of the run bar stamped `stamp`: `[stamp, stamp + intervalMs)`, or on the CME
112
+ * session lattice its session bar's (cmeSessionBarOpenMs, cmeSessionBarEndMs: a 1D bar stamped at
113
+ * 00:00Z of its trade date opens at the 17:00 Chicago open before it and closes at the next one).
114
+ * A stamp the lattice books no bar to (a width that divides an hour, a regular-hours bar, a time
115
+ * that is no run bar's) reads the plain span.
116
+ */
117
+ export function runBarSpan(stamp, run) {
118
+ const close = run.sessionLattice ? cmeSessionBarEndMs(stamp, run.intervalMs) : null;
119
+ if (close === null)
120
+ return { open: stamp, close: stamp + run.intervalMs };
121
+ return { open: cmeSessionBarOpenMs(stamp, run.intervalMs) ?? stamp, close };
122
+ }
123
+ /** runBarSpan's close alone, for a loop over many bars that never reads the session open (uncached). */
124
+ function runBarCloseMs(stamp, run) {
125
+ return (run.sessionLattice ? cmeSessionBarEndMs(stamp, run.intervalMs) : null) ?? stamp + run.intervalMs;
126
+ }
127
+ /** The first index whose time is at or after `time` (times ascending); times.length when none. */
128
+ function firstIndexAtOrAfter(times, time) {
129
+ let lo = 0;
130
+ let hi = times.length;
131
+ while (lo < hi) {
132
+ const mid = (lo + hi) >> 1;
133
+ if (times[mid] < time)
134
+ lo = mid + 1;
135
+ else
136
+ hi = mid;
137
+ }
138
+ return lo;
139
+ }
140
+ /**
141
+ * The close of the run bar after the one stamped `stamp`: from there on a chart bar shows a run bar
142
+ * later than it. Plain, the next run bar opens at its close (`stamp + 2 * intervalMs`). On the
143
+ * session lattice a gap (the daily halt, a weekend, a holiday) holds no run bar, so the next one is
144
+ * the run bar of the first chart bar (`chartTimes`, ascending) at or after its close: that chart
145
+ * bar's session bar when `stamp` is one, else the run bar it opens (a session reopens on a run
146
+ * bar's open, a regular-hours one included). Infinity when no chart bar reaches that close.
147
+ */
148
+ export function nextRunBarCloseMs(stamp, chartTimes, run) {
149
+ if (!run.sessionLattice)
150
+ return stamp + 2 * run.intervalMs;
151
+ const sessionClose = cmeSessionBarEndMs(stamp, run.intervalMs);
152
+ const at = firstIndexAtOrAfter(chartTimes, sessionClose ?? stamp + run.intervalMs);
153
+ if (at === chartTimes.length)
154
+ return Number.POSITIVE_INFINITY;
155
+ const first = chartTimes[at];
156
+ const next = sessionClose === null ? first : (cmeSessionBucketMs(first, run.intervalMs) ?? first);
157
+ return runBarCloseMs(next, run);
158
+ }
159
+ function intervalMsOf(interval) {
160
+ const ms = typeof interval === 'number' ? interval : Intervals.map_unit[String(interval)];
161
+ return typeof ms === 'number' && Number.isFinite(ms) && ms > 0 ? ms : undefined;
162
+ }
163
+ /**
164
+ * The run interval a Timeframe option label ("1h", "1D") selects on a chart of `chartInterval`:
165
+ * coarser than the chart, else null (the chart's own interval, an unknown label, "chart"). Shared
166
+ * by the kScript built-ins (resolveRunInterval) and their wrun Indicators (wrun-run-interval.util).
167
+ */
168
+ export function runIntervalOfTimeframeLabel(label, chartInterval) {
169
+ const interval = typeof label === 'string' ? TIMEFRAME_INTERVALS[label] : undefined;
170
+ const intervalMs = intervalMsOf(interval);
171
+ const chartMs = intervalMsOf(chartInterval);
172
+ if (interval === undefined || intervalMs === undefined || chartMs === undefined || intervalMs <= chartMs) {
173
+ return null;
174
+ }
175
+ return { interval, intervalMs };
176
+ }
177
+ /**
178
+ * Whether a Timeframe option label selects the chart's own interval or a finer one. Such a
179
+ * selection means "chart" (HTF-NATIVE-PLAN.md D3a): the resolver below answers null for it, and the
180
+ * engine must see `timeframe: "chart"` too (chartIntervalEngineMetadata), or the template's
181
+ * selected-timeframe branch calls htf() with an interval below its base and the engine throws on
182
+ * every update ("htf() timeframe 900000ms must be >= base interval 3600000ms": a 15m selection
183
+ * on a 1h chart froze the line at its last good run, Kyle's 2026-10-03 INT dump). Their wrun twins
184
+ * read it too (wrunTimeframeIsChartOrFiner, wrun-run-interval.util).
185
+ */
186
+ export function timeframeIsChartOrFiner(label, chartInterval) {
187
+ const interval = typeof label === 'string' ? TIMEFRAME_INTERVALS[label] : undefined;
188
+ const intervalMs = intervalMsOf(interval);
189
+ const chartMs = intervalMsOf(chartInterval);
190
+ return intervalMs !== undefined && chartMs !== undefined && intervalMs <= chartMs;
191
+ }
192
+ /**
193
+ * The interval an overlay's engine runs at when it is coarser than the chart's, else null (the
194
+ * overlay runs at the chart's interval, as before). A selection at or below the chart's interval
195
+ * is the chart's own, so it takes the plain chart path too.
196
+ */
197
+ export function resolveRunInterval(input) {
198
+ if (input.replay)
199
+ return null;
200
+ if (typeof input.subType !== 'string' || !NATIVE_RUN_INTERVAL_SUBTYPES.has(input.subType))
201
+ return null;
202
+ const settings = (input.settings ?? {});
203
+ const run = runIntervalOfTimeframeLabel(settings.timeframe, input.chartInterval);
204
+ return run ? { ...run, waitForClose: settings.waitForClose !== false } : null;
205
+ }
206
+ /** The settings the engine sees for a run-interval overlay: the template takes its plain chart path. */
207
+ export function engineSettingsForRunInterval(settings) {
208
+ return { ...settings, timeframe: 'chart' };
209
+ }
210
+ /**
211
+ * Projects run-interval rows (oldest first, `row[0]` = the run bar's stamp, its open off the
212
+ * session lattice) onto the chart's bars: one row per chart time, with the cells of the run row that
213
+ * bar shows. Each run bar's span is read by runBarSpan (`sessionLattice`: the CME session calendar).
214
+ *
215
+ * Wait for close on: a chart bar shows the last run bar that closed at or before it
216
+ * (`close <= chartTime`, plain `stamp + runMs`), so a 5m bar in hour b shows hour b - 1. Off: the
217
+ * same, except the chart bars inside the newest run row's span show that row (the forming bar,
218
+ * live; on the lattice from its session open, before a 1D or 1W stamp). Chart bars before the first
219
+ * shown row get NaN cells. Run rows before the first chart bar (the warm-up) are dropped.
220
+ */
221
+ export function projectRunRowsOntoChart(rows, chartTimes, runMs, waitForClose, sessionLattice = false) {
222
+ const run = { intervalMs: runMs, sessionLattice };
223
+ const usable = rows.filter((row) => Array.isArray(row) && Number.isFinite(Number(row[0])));
224
+ const width = usable.reduce((max, row) => Math.max(max, row.length), 1);
225
+ const emptyCells = new Array(width - 1).fill(NaN);
226
+ const newest = usable[usable.length - 1];
227
+ const forming = newest ? runBarSpan(Number(newest[0]), run) : { open: NaN, close: NaN };
228
+ const closes = usable.map((row) => runBarCloseMs(Number(row[0]), run));
229
+ const projected = [];
230
+ let shown = -1;
231
+ for (const chartTime of chartTimes) {
232
+ if (!waitForClose && newest && chartTime >= forming.open && chartTime < forming.close) {
233
+ projected.push([chartTime, ...newest.slice(1)]);
234
+ continue;
235
+ }
236
+ while (shown + 1 < usable.length && closes[shown + 1] <= chartTime)
237
+ shown++;
238
+ projected.push(shown < 0 ? [chartTime, ...emptyCells] : [chartTime, ...usable[shown].slice(1)]);
239
+ }
240
+ return projected;
241
+ }
242
+ /**
243
+ * The chart time a run-bar time anchor (a drawing point at a run bar's stamp) lands on: where that
244
+ * bar's value first shows (its close with wait for close on, its open with it off, read by
245
+ * runBarSpan), clamped to the chart's loaded bars.
246
+ */
247
+ export function projectRunTimeOntoChart(runTime, chartTimes, runMs, waitForClose, sessionLattice = false) {
248
+ if (chartTimes.length === 0)
249
+ return runTime;
250
+ const span = runBarSpan(runTime, { intervalMs: runMs, sessionLattice });
251
+ const target = waitForClose ? span.close : span.open;
252
+ const first = chartTimes[0];
253
+ const last = chartTimes[chartTimes.length - 1];
254
+ if (target <= first)
255
+ return first;
256
+ if (target >= last)
257
+ return last;
258
+ let lo = 0;
259
+ let hi = chartTimes.length - 1;
260
+ while (lo < hi) {
261
+ const mid = (lo + hi) >> 1;
262
+ if (chartTimes[mid] < target)
263
+ lo = mid + 1;
264
+ else
265
+ hi = mid;
266
+ }
267
+ return chartTimes[lo];
268
+ }
@@ -0,0 +1,119 @@
1
+ export type WindowPaneKind = 'table' | 'chart' | 'time';
2
+ export interface WindowPane {
3
+ id: string;
4
+ kind: WindowPaneKind;
5
+ /** A table's body row count (header excluded): its content height. */
6
+ rows?: number;
7
+ }
8
+ export interface WindowPaneWeight {
9
+ id: string;
10
+ gridHeight: number;
11
+ }
12
+ /**
13
+ * A window's saved split (`settings.wrunWindowSplit` on the owner row,
14
+ * window-cell.util): pane weights keyed relative to the owner, `self` for the
15
+ * owner's own pane, `panel:<name>` and `series:<name>` for its children,
16
+ * rounded to 4 decimals and summing to 1. Relative keys because the owner's
17
+ * overlay id is not stable across a draft swap and must not be inside its own
18
+ * settings.
19
+ */
20
+ export type WindowSplit = Record<string, number>;
21
+ /** The split key of a window pane: `self` for the owner, a child's id past `<owner>::`. */
22
+ export declare function windowSplitKeyOf(paneId: string): string;
23
+ /** A record of at least one finite positive weight: the only shape the split reader and writer accept. */
24
+ export declare function isWindowSplit(value: unknown): value is WindowSplit;
25
+ /** The engine's pane minimum: a carve under it is refused. */
26
+ export declare const WINDOW_PANE_MIN_GRID_HEIGHT: number;
27
+ /** All tables of a window together take at most half the cell. */
28
+ export declare const WINDOW_TABLES_MAX_TOTAL = 0.5;
29
+ /** Heights closer than this are the same height: the in-place refresh rule's
30
+ * tolerance (samePanelPane) and the reconcile's write threshold. */
31
+ export declare const WINDOW_GRID_HEIGHT_TOLERANCE = 0.005;
32
+ /**
33
+ * The window's weights for a pane set, in the given order. Pure: the same
34
+ * panes and canvas height always plan the same weights (the reconcile's
35
+ * idempotence and the first mount's no-flash both rest on that).
36
+ */
37
+ export declare function planWindowWeights(panes: ReadonlyArray<WindowPane>, canvasHeightPx?: number): WindowPaneWeight[];
38
+ /** The engine meta fields the geometry reads and writes. */
39
+ export interface WindowGeometryMeta {
40
+ id: string;
41
+ type?: string;
42
+ plot?: string;
43
+ gridHeight?: number;
44
+ isPaneHidden?: boolean;
45
+ hostPaneId?: string;
46
+ settings?: Record<string, unknown>;
47
+ rawData?: unknown;
48
+ data?: unknown;
49
+ }
50
+ export interface WindowGeometryChart {
51
+ metadata: ReadonlyArray<WindowGeometryMeta>;
52
+ isDestroyed?: boolean;
53
+ /** The chart canvas in CSS px sizes a table pane to its rows. */
54
+ canvasChartController?: {
55
+ canvasElement?: {
56
+ clientHeight?: number;
57
+ } | null;
58
+ } | null;
59
+ updateSettings?(id: string, payload: Record<string, unknown>): unknown;
60
+ resizeCanvasOnce?(): void;
61
+ }
62
+ /** The body rows of a table pane (a mounted meta or an addOverlay config):
63
+ * its one decorator row's grid minus the header; undefined when unreadable. */
64
+ export declare function tableRowCountOf(pane: {
65
+ rawData?: unknown;
66
+ data?: unknown;
67
+ }): number | undefined;
68
+ /** The owner's mounted window panes, in stack order, classified for the planner. */
69
+ export declare function mountedWindowPanes(metadata: ReadonlyArray<WindowGeometryMeta>, ownerId: string): WindowPane[];
70
+ /** Whether the candle pane is hidden on this engine: the window layout is in force. */
71
+ export declare function isMainPaneHidden(metadata: ReadonlyArray<WindowGeometryMeta>): boolean;
72
+ /**
73
+ * The reader dragged a splitter in a window (the engine's `resize-grids`):
74
+ * the heights on the engine are theirs now. They become the panes' requests
75
+ * (under a hidden main the engine re-splits the stack from
76
+ * `settings.gridHeight` on every pane add, removal, collapse and focus exit,
77
+ * so a request left at the plan would undo the drag there), and the plan
78
+ * stands down: reconcileWindowOwnerGeometry writes no weight until the pane
79
+ * set changes. No engine call: the drag already laid the panes out, and this
80
+ * runs on every drag move. Silent on a normal chart (main visible) and for an
81
+ * owner without a pane. Returns the held weights as the window's split
82
+ * (WindowSplit: keyed relative to the owner, normalized to 1, rounded), the
83
+ * value the host writes to the owner row; undefined when nothing is held, or
84
+ * when a held pane has no usable height yet (nothing worth saving).
85
+ */
86
+ export declare function holdWindowPaneHeights(tc: WindowGeometryChart | null | undefined, ownerId: string): WindowSplit | undefined;
87
+ /**
88
+ * The reader's saved split for the panes mounted now: the owner's
89
+ * `settings.wrunWindowSplit` read back as weights in the panes' order, only
90
+ * when its key set equals the mounted pane set exactly (renormalized to 1,
91
+ * the engine minimum applied, rounded like the plan). Anything else is
92
+ * undefined and the plan applies: a split saved over other panes (one joined
93
+ * or left since), a malformed value, or more panes than the minimum allows
94
+ * (no split satisfies the engine then; the plan is the even split). Pure.
95
+ */
96
+ export declare function savedWindowSplit(ownerSettings: Record<string, unknown> | null | undefined, panes: ReadonlyArray<Pick<WindowPane, 'id'>>): WindowPaneWeight[] | undefined;
97
+ /**
98
+ * Apply the window plan to the OWNER's already-mounted panes: every pane whose
99
+ * engine height is off the plan by WINDOW_GRID_HEIGHT_TOLERANCE or more takes
100
+ * the planned height through the offchart height path, then one resize.
101
+ * Writes nothing while the candle pane is visible (the host hides it first;
102
+ * sum-1 weights beside a visible main would squeeze the candles), and no
103
+ * weight while the reader's own split holds (holdWindowPaneHeights). With
104
+ * nothing held, the reader's saved split (savedWindowSplit over the owner's
105
+ * engine copy, patched in step with the row) is the plan while it names
106
+ * exactly the mounted panes; else the planner's. Main itself is never
107
+ * written. Returns whether anything was written.
108
+ */
109
+ export declare function reconcileWindowOwnerGeometry(tc: WindowGeometryChart | null | undefined, ownerId: string, canvasHeightPx?: number): boolean;
110
+ /**
111
+ * The reversal (Show chart): every pane the owner mounted goes back to the
112
+ * height a normal chart mounts it at (plan section 2.2): chart-shaped panels
113
+ * and time panes at PANEL_CHART_GRID_HEIGHT, a table at its content height.
114
+ * Writes only once the candle pane is visible again (the host releases main
115
+ * first), so the engine carves the panes out of main the way a fresh mount
116
+ * would. Keyed by the owner id because the flag is already off by then.
117
+ * Returns whether anything was written.
118
+ */
119
+ export declare function restoreNormalOwnerGeometry(tc: WindowGeometryChart | null | undefined, ownerId: string, canvasHeightPx?: number): boolean;