@tidal-ts/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peter Murphy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,193 @@
1
+ import { BoundedSequence, TimeSeries } from 'pond-ts';
2
+ import type { SeriesSchema } from 'pond-ts';
3
+ import type { Segment } from './sessions.js';
4
+ /**
5
+ * Time-window aggregation for chart styles that bin a continuous series — bars
6
+ * and coarser-than-native candles (OHLC roll-ups). Pond does the windowing
7
+ * (`TimeSeries.aggregate` over a grid); this module is the thin, typed seam
8
+ * Tidal renders against, and it owns the one thing a calendar grid cannot know
9
+ * for a trading chart: **what a "day" means once the bars are intraday** — a
10
+ * session, not a midnight-to-midnight span.
11
+ *
12
+ * It used to own a second thing, **which bucket the first bar lands in**: pond
13
+ * dropped every event before its first emitted bucket, so this module floored
14
+ * the aggregation range by hand (F-charts-16). `pond-ts` 0.64.0 fixed that in
15
+ * the default, and the compensation is gone.
16
+ *
17
+ * A **calendar** window bins via `Sequence.calendar` — `'1d'` (one day), `'1w'`
18
+ * (a calendar week, Monday-anchored), or `'1mo'` (a calendar month), anchored to
19
+ * `UTC` boundaries, which match our UTC-midnight daily bars. A **fixed-duration**
20
+ * window (`'1m'` / `'5m'` / `'1h'`) is instead subdivided inside each session.
21
+ *
22
+ * Kept pure + React-free in `@tidal-ts/core` so it can move to `@pond-ts/finance`.
23
+ */
24
+ /** The window a bar/box bins into.
25
+ *
26
+ * Two families, and the difference decides how the bucket is built: `'1m'` /
27
+ * `'5m'` / `'1h'` are **fixed durations** subdivided inside a session, while
28
+ * `'1d'` / `'1w'` / `'1mo'` are **calendar spans** made of whole sessions.
29
+ *
30
+ * **Not** "the native bar": `'1d'` is one day, which is native only for daily
31
+ * data. On intraday data a `'1d'` window is a real roll-up of ~390 bars, and code
32
+ * that treats `'1d'` as a no-op draws one mark per minute instead of per day. */
33
+ export type SeriesWindow = '1m' | '5m' | '1h' | '1d' | '1w' | '1mo';
34
+ /** Approximate span of each window, for deciding whether it is coarser than the
35
+ * data's native interval. Approximate is enough — months vary, and this only
36
+ * ever answers "is this window bigger than one bar?" */
37
+ export declare const WINDOW_MS: Record<SeriesWindow, number>;
38
+ /** The window ladder, finest → coarsest — the order {@link autoBarWindow} steps
39
+ * through. Derived from {@link WINDOW_MS} rather than restated, so a new window
40
+ * token cannot be added to one and forgotten in the other. */
41
+ export declare const WINDOW_LADDER: readonly SeriesWindow[];
42
+ /** How wide a bar has to be, in CSS px, to be worth drawing as a bar. Three is
43
+ * the smallest that survives a device-pixel grid with a gap either side; below
44
+ * it, neighbouring bars share pixels and the last one drawn wins. */
45
+ export declare const MIN_BAR_PX = 3;
46
+ /**
47
+ * The finest window whose bars are at least `minPx` wide — the fix for bars
48
+ * drawn narrower than a pixel.
49
+ *
50
+ * **Why this exists.** A rise/fall bar is drawn as two layers (the library takes
51
+ * one fill per series; F-charts-12), fall on top. Once bars go sub-pixel they
52
+ * share pixel columns, and the upper layer wins every shared column — so a series
53
+ * that is 47.5% down days renders 82% red. Measured on AAPL's full history:
54
+ * ~42–43% red pixels while bars stayed above 4.5px, climbing to 50% at 0.9px and
55
+ * 82% at 0.31px. The colour was reporting bar density, not the market.
56
+ *
57
+ * Re-ordering the layers only moves the lie to the other colour, and per-pixel
58
+ * blending would average two categorical colours into a third that means nothing.
59
+ * The honest fix is to stop asking for more bars than there are pixels: roll up to
60
+ * a window that fits, where each bar's direction is its own bucket's `open`→
61
+ * `close` — a real weekly or monthly candle rather than an accident of overdraw.
62
+ *
63
+ * Never goes finer than the data (`nativeMs`) — coarser is the only direction,
64
+ * and it is forced by the pixels.
65
+ *
66
+ * This decides only the AUTO case. A series whose window the user set explicitly
67
+ * is drawn at that window, overdraw included: the control panel names the window,
68
+ * and a control that says `1D` while the canvas draws months is a worse failure
69
+ * than the one being fixed. Auto is the default, and says "Auto".
70
+ */
71
+ export declare function autoBarWindow(opts: {
72
+ /** Source bars in view. */
73
+ bars: number;
74
+ /** Their spacing, ms. */
75
+ nativeMs: number;
76
+ /** Plot width, CSS px. */
77
+ widthPx: number;
78
+ /** Minimum drawable bar width. Default {@link MIN_BAR_PX}. */
79
+ minPx?: number;
80
+ }): SeriesWindow;
81
+ /** A single-column aggregation reducer name (a pond built-in). The subset Tidal
82
+ * actually offers a bar; the fuller set lives in pond. */
83
+ export type BarReducer = 'sum' | 'avg' | 'min' | 'max' | 'first' | 'last';
84
+ /**
85
+ * The start of the bucket **containing** `t`, on the same grid `gridFor` walks.
86
+ *
87
+ * Asked of pond rather than computed here. This used to hand-roll the UTC
88
+ * day / Monday-week / month flooring, which meant keeping a second
89
+ * implementation of `Sequence.calendar`'s anchoring in step with pond's by
90
+ * eye — duplication we carried only to compensate for F-charts-16. `pond-ts`
91
+ * 0.64.0 exposes the flooring primitive directly: a single-instant range under
92
+ * `coverage: 'overlap'` selects exactly the bucket containing that instant. So
93
+ * the floor is now the grid's own answer, and the two agree by construction
94
+ * instead of by maintenance.
95
+ *
96
+ * Still needed after F-charts-16's fix — {@link sessionGrid} and
97
+ * {@link liveWindowMs} key sessions by the calendar bucket their open falls in,
98
+ * which is a domain question, not a workaround.
99
+ */
100
+ export declare function floorToWindow(t: number, window: SeriesWindow): number;
101
+ /**
102
+ * Buckets shaped like **trading sessions** rather than calendar spans — the grid
103
+ * an intraday series must roll up on.
104
+ *
105
+ * A calendar day is the wrong bucket for intraday bars in three separate ways,
106
+ * all of which a session bucket fixes:
107
+ *
108
+ * 1. **It spans time that did not trade.** A `[00:00, 24:00)` bucket is mostly
109
+ * closed market. The candle drawn over it stretches across the collapsed
110
+ * overnight seam of a trading-time axis, so the body is wider than the session
111
+ * it describes.
112
+ * 2. **Its midpoint is not a live instant.** Noon UTC is inside the overnight
113
+ * gap, so anything that anchors on the slot centre — the crosshair readout —
114
+ * clamps out of the gap onto the session open and lands on the candle's left
115
+ * edge instead of its middle.
116
+ * 3. **It splits a session across buckets it does not mean to.** A session that
117
+ * runs past midnight UTC lands half in each calendar day, so one trading
118
+ * session draws as two candles. Keying a session by the bucket its OPEN falls
119
+ * in keeps it whole.
120
+ *
121
+ * The two window families divide the sessions in opposite directions:
122
+ *
123
+ * - **Coarser than a session** — `'1d'` is one bucket per session; `'1w'` /
124
+ * `'1mo'` group the sessions of a calendar week / month into one bucket
125
+ * spanning `[first open, last close)`, so a bucket still contains only
126
+ * sessions, never the weekend between them.
127
+ * - **Finer than a session** — `'1m'` / `'5m'` / `'1h'` subdivide each session
128
+ * into fixed steps **anchored on the session open**, with the last step of a
129
+ * session clipped to its close.
130
+ *
131
+ * Anchoring on the open rather than the epoch is the trading convention and it
132
+ * matters at `'1h'`: US equities open at 13:30 UTC, so an epoch-anchored hourly
133
+ * grid would cut a 30-minute stub at 14:00 and put the open in the middle of a
134
+ * bucket, where a session-anchored one runs 13:30–14:30 like every terminal
135
+ * draws it. (At `'5m'` the two coincide — 13:30 is already a 5-minute multiple —
136
+ * which is exactly the kind of coincidence that hides the rule.) Clipping the
137
+ * last step keeps a short final bar instead of letting a bucket run past the
138
+ * close into collapsed time.
139
+ *
140
+ * Returns `undefined` for no segments, so the caller falls back to the calendar
141
+ * grid rather than aggregating over nothing.
142
+ */
143
+ export declare function sessionGrid(segments: readonly Segment[], window: SeriesWindow): BoundedSequence | undefined;
144
+ /**
145
+ * How much **live** time one bucket of `window` covers — the unit a
146
+ * trading-time axis measures durations in, and therefore the unit a zoom limit
147
+ * has to be expressed in.
148
+ *
149
+ * A calendar day is 24 hours; the session inside it is 6.5, and the axis has
150
+ * excised the other 17.5. So a zoom floor of "five days" reads on screen as five
151
+ * days of *trading*, which is nineteen sessions — nearly four times the intended
152
+ * span. The fixed-duration windows have no such gap (a five-minute step inside a
153
+ * session is five live minutes), which is why only the calendar family needs
154
+ * this.
155
+ *
156
+ * Measured from the sessions rather than assumed: the median bucket's live span,
157
+ * where a bucket's span is the session time inside it. That way a half-day
158
+ * before a holiday, or a market that trades 23 hours, needs no special case.
159
+ *
160
+ * `undefined` when there are no sessions to measure — the caller should fall
161
+ * back to {@link WINDOW_MS} and accept the calendar approximation.
162
+ */
163
+ export declare function liveWindowMs(window: SeriesWindow, sessions: readonly Segment[] | undefined): number | undefined;
164
+ /**
165
+ * Bin one numeric column into fixed windows, reducing each window to a single
166
+ * value — the data behind a {@link https://…|BarChart}. Returns an
167
+ * interval-keyed series whose one value column keeps the source column's name
168
+ * (so the chart reads it with the same `column`). At the native window each
169
+ * bucket holds one source point, so the reducer is a no-op; it only bites when
170
+ * the window is coarser than the data.
171
+ *
172
+ * Pass `sessions` for intraday data so the buckets are sessions rather than
173
+ * calendar spans — see {@link sessionGrid}.
174
+ */
175
+ export declare function aggregateColumn(series: TimeSeries<SeriesSchema>, column: string, window: SeriesWindow, reducer?: BarReducer, sessions?: readonly Segment[]): TimeSeries<SeriesSchema>;
176
+ /**
177
+ * Roll a `time`-keyed OHLCV series up into interval-keyed OHLC windows — the
178
+ * series a coarser-than-native candle draws. `open` is the window's first,
179
+ * `high`/`low` its max/min, `close` its last; volume sums. The `<Candlestick>`
180
+ * layer reads `open`/`high`/`low`/`close` directly and derives the body itself,
181
+ * so there's no extent precompute here.
182
+ *
183
+ * Only needed when the window is coarser than the data's own interval: at the
184
+ * native interval a candle takes the raw point-keyed series straight
185
+ * (neighbour-derived slot), no aggregate pass.
186
+ *
187
+ * Pass `sessions` for intraday data so the buckets are sessions rather than
188
+ * calendar spans — see {@link sessionGrid}.
189
+ *
190
+ * The source must carry `open`/`high`/`low`/`close` columns (Tidal's price
191
+ * series does; vol series don't — the caller gates candles to the price panel).
192
+ */
193
+ export declare function ohlcWindow(series: TimeSeries<SeriesSchema>, window: SeriesWindow, sessions?: readonly Segment[]): TimeSeries<SeriesSchema>;
@@ -0,0 +1,288 @@
1
+ import { BoundedSequence, Interval, Sequence, TimeSeries } from 'pond-ts';
2
+ import { DATA_TIME_ZONE } from './timeZone.js';
3
+ /** Approximate span of each window, for deciding whether it is coarser than the
4
+ * data's native interval. Approximate is enough — months vary, and this only
5
+ * ever answers "is this window bigger than one bar?" */
6
+ export const WINDOW_MS = {
7
+ '1m': 60_000,
8
+ '5m': 300_000,
9
+ '1h': 3_600_000,
10
+ '1d': 86_400_000,
11
+ '1w': 604_800_000,
12
+ '1mo': 2_592_000_000,
13
+ };
14
+ /** The window ladder, finest → coarsest — the order {@link autoBarWindow} steps
15
+ * through. Derived from {@link WINDOW_MS} rather than restated, so a new window
16
+ * token cannot be added to one and forgotten in the other. */
17
+ export const WINDOW_LADDER = Object.keys(WINDOW_MS).sort((a, b) => WINDOW_MS[a] - WINDOW_MS[b]);
18
+ /** How wide a bar has to be, in CSS px, to be worth drawing as a bar. Three is
19
+ * the smallest that survives a device-pixel grid with a gap either side; below
20
+ * it, neighbouring bars share pixels and the last one drawn wins. */
21
+ export const MIN_BAR_PX = 3;
22
+ /** Bars a window yields from `bars` source bars spaced `nativeMs` apart. Counts
23
+ * the SOURCE bars rather than the calendar span, because a calendar estimate
24
+ * over trading-day data is 7/5 too high — it counts weekends that carry no bar,
25
+ * and coarsens a year of dailies that would have fitted. */
26
+ function barsAtWindow(bars, nativeMs, window) {
27
+ const span = WINDOW_MS[window];
28
+ if (!(span > nativeMs))
29
+ return bars;
30
+ return Math.max(1, Math.ceil((bars * nativeMs) / span));
31
+ }
32
+ /**
33
+ * The finest window whose bars are at least `minPx` wide — the fix for bars
34
+ * drawn narrower than a pixel.
35
+ *
36
+ * **Why this exists.** A rise/fall bar is drawn as two layers (the library takes
37
+ * one fill per series; F-charts-12), fall on top. Once bars go sub-pixel they
38
+ * share pixel columns, and the upper layer wins every shared column — so a series
39
+ * that is 47.5% down days renders 82% red. Measured on AAPL's full history:
40
+ * ~42–43% red pixels while bars stayed above 4.5px, climbing to 50% at 0.9px and
41
+ * 82% at 0.31px. The colour was reporting bar density, not the market.
42
+ *
43
+ * Re-ordering the layers only moves the lie to the other colour, and per-pixel
44
+ * blending would average two categorical colours into a third that means nothing.
45
+ * The honest fix is to stop asking for more bars than there are pixels: roll up to
46
+ * a window that fits, where each bar's direction is its own bucket's `open`→
47
+ * `close` — a real weekly or monthly candle rather than an accident of overdraw.
48
+ *
49
+ * Never goes finer than the data (`nativeMs`) — coarser is the only direction,
50
+ * and it is forced by the pixels.
51
+ *
52
+ * This decides only the AUTO case. A series whose window the user set explicitly
53
+ * is drawn at that window, overdraw included: the control panel names the window,
54
+ * and a control that says `1D` while the canvas draws months is a worse failure
55
+ * than the one being fixed. Auto is the default, and says "Auto".
56
+ */
57
+ export function autoBarWindow(opts) {
58
+ const { bars, nativeMs, widthPx, minPx = MIN_BAR_PX } = opts;
59
+ const usable = WINDOW_LADDER.filter((w) => WINDOW_MS[w] >= (nativeMs > 0 ? nativeMs : 0));
60
+ // The path for a zero/unknown width too: undecidable, so change nothing.
61
+ const finest = usable[0] ?? WINDOW_LADDER[WINDOW_LADDER.length - 1];
62
+ if (!(widthPx > 0) || !(bars > 0))
63
+ return finest;
64
+ return (usable.find((w) => barsAtWindow(bars, nativeMs, w) * minPx <= widthPx) ??
65
+ usable[usable.length - 1] ??
66
+ finest);
67
+ }
68
+ /** Window token → pond calendar unit. Calendar windows only. */
69
+ const CAL_UNIT = { '1d': 'day', '1w': 'week', '1mo': 'month' };
70
+ /** The fixed-duration windows, and their step. A window in here is subdivided
71
+ * *within* a session rather than aligned to a calendar boundary. */
72
+ const SUB_DAY_MS = { '1m': 60_000, '5m': 300_000, '1h': 3_600_000 };
73
+ const isSubDay = (w) => w in SUB_DAY_MS;
74
+ const buildGrid = (window) => isSubDay(window)
75
+ ? // Epoch-anchored fixed steps — the sessionless fallback. Buckets straddle
76
+ // the close here, which is why a session grid is preferred when there is one.
77
+ Sequence.every(SUB_DAY_MS[window])
78
+ : // Calendar-aware buckets in UTC (our daily bars are UTC-midnight). Weeks are
79
+ // Monday-anchored (`weekStartsOn: 1`); ignored for day/month.
80
+ Sequence.calendar(CAL_UNIT[window], {
81
+ timeZone: DATA_TIME_ZONE,
82
+ weekStartsOn: 1,
83
+ });
84
+ /** One grid per window token. `buildGrid` is deterministic in its argument, and
85
+ * `floorToWindow` asks for a grid per session, so building them once keeps that
86
+ * loop to a lookup. */
87
+ const GRIDS = new Map();
88
+ const gridFor = (window) => {
89
+ const held = GRIDS.get(window);
90
+ if (held)
91
+ return held;
92
+ const built = buildGrid(window);
93
+ GRIDS.set(window, built);
94
+ return built;
95
+ };
96
+ /**
97
+ * The start of the bucket **containing** `t`, on the same grid `gridFor` walks.
98
+ *
99
+ * Asked of pond rather than computed here. This used to hand-roll the UTC
100
+ * day / Monday-week / month flooring, which meant keeping a second
101
+ * implementation of `Sequence.calendar`'s anchoring in step with pond's by
102
+ * eye — duplication we carried only to compensate for F-charts-16. `pond-ts`
103
+ * 0.64.0 exposes the flooring primitive directly: a single-instant range under
104
+ * `coverage: 'overlap'` selects exactly the bucket containing that instant. So
105
+ * the floor is now the grid's own answer, and the two agree by construction
106
+ * instead of by maintenance.
107
+ *
108
+ * Still needed after F-charts-16's fix — {@link sessionGrid} and
109
+ * {@link liveWindowMs} key sessions by the calendar bucket their open falls in,
110
+ * which is a domain question, not a workaround.
111
+ */
112
+ export function floorToWindow(t, window) {
113
+ // Guard the input BEFORE pond does. It throws its own `TypeError` on a
114
+ // non-finite start, which is right — but it fires before the diagnostic
115
+ // below, and that diagnostic would itself throw building `new
116
+ // Date(NaN).toISOString()`. Say which value and which window, once (PR #173
117
+ // review). The arithmetic this replaced returned `NaN` and let it spread.
118
+ if (!Number.isFinite(t))
119
+ throw new Error(`floorToWindow: ${t} is not a timestamp (${window})`);
120
+ const bucket = gridFor(window).bounded({ start: t, end: t }, { coverage: 'overlap' }).first();
121
+ // `'overlap'` on a single instant is documented to return exactly the bucket
122
+ // containing it; a miss would mean a pond contract change, and silently
123
+ // returning the wrong bucket is the failure mode F-charts-16 taught us to
124
+ // refuse.
125
+ if (!bucket)
126
+ throw new Error(`no ${window} bucket contains ${new Date(t).toISOString()}`);
127
+ return bucket.begin();
128
+ }
129
+ /**
130
+ * Buckets shaped like **trading sessions** rather than calendar spans — the grid
131
+ * an intraday series must roll up on.
132
+ *
133
+ * A calendar day is the wrong bucket for intraday bars in three separate ways,
134
+ * all of which a session bucket fixes:
135
+ *
136
+ * 1. **It spans time that did not trade.** A `[00:00, 24:00)` bucket is mostly
137
+ * closed market. The candle drawn over it stretches across the collapsed
138
+ * overnight seam of a trading-time axis, so the body is wider than the session
139
+ * it describes.
140
+ * 2. **Its midpoint is not a live instant.** Noon UTC is inside the overnight
141
+ * gap, so anything that anchors on the slot centre — the crosshair readout —
142
+ * clamps out of the gap onto the session open and lands on the candle's left
143
+ * edge instead of its middle.
144
+ * 3. **It splits a session across buckets it does not mean to.** A session that
145
+ * runs past midnight UTC lands half in each calendar day, so one trading
146
+ * session draws as two candles. Keying a session by the bucket its OPEN falls
147
+ * in keeps it whole.
148
+ *
149
+ * The two window families divide the sessions in opposite directions:
150
+ *
151
+ * - **Coarser than a session** — `'1d'` is one bucket per session; `'1w'` /
152
+ * `'1mo'` group the sessions of a calendar week / month into one bucket
153
+ * spanning `[first open, last close)`, so a bucket still contains only
154
+ * sessions, never the weekend between them.
155
+ * - **Finer than a session** — `'1m'` / `'5m'` / `'1h'` subdivide each session
156
+ * into fixed steps **anchored on the session open**, with the last step of a
157
+ * session clipped to its close.
158
+ *
159
+ * Anchoring on the open rather than the epoch is the trading convention and it
160
+ * matters at `'1h'`: US equities open at 13:30 UTC, so an epoch-anchored hourly
161
+ * grid would cut a 30-minute stub at 14:00 and put the open in the middle of a
162
+ * bucket, where a session-anchored one runs 13:30–14:30 like every terminal
163
+ * draws it. (At `'5m'` the two coincide — 13:30 is already a 5-minute multiple —
164
+ * which is exactly the kind of coincidence that hides the rule.) Clipping the
165
+ * last step keeps a short final bar instead of letting a bucket run past the
166
+ * close into collapsed time.
167
+ *
168
+ * Returns `undefined` for no segments, so the caller falls back to the calendar
169
+ * grid rather than aggregating over nothing.
170
+ */
171
+ export function sessionGrid(segments, window) {
172
+ if (segments.length === 0)
173
+ return undefined;
174
+ if (isSubDay(window)) {
175
+ const step = SUB_DAY_MS[window];
176
+ const steps = [];
177
+ for (const [start, end] of segments)
178
+ for (let t = start; t < end; t += step)
179
+ steps.push(new Interval({ value: t, start: t, end: Math.min(t + step, end) }));
180
+ return new BoundedSequence(steps);
181
+ }
182
+ const groups = new Map();
183
+ for (const [start, end] of segments) {
184
+ const key = floorToWindow(start, window);
185
+ const held = groups.get(key);
186
+ // A session is keyed by the bucket its OPEN falls in, so a session that runs
187
+ // past midnight UTC stays with the day it opened rather than splitting.
188
+ if (held)
189
+ held[1] = Math.max(held[1], end);
190
+ else
191
+ groups.set(key, [start, end]);
192
+ }
193
+ const intervals = [...groups.entries()]
194
+ .sort((a, b) => a[0] - b[0])
195
+ .map(([, [start, end]]) => new Interval({ value: start, start, end }));
196
+ return new BoundedSequence(intervals);
197
+ }
198
+ /**
199
+ * How much **live** time one bucket of `window` covers — the unit a
200
+ * trading-time axis measures durations in, and therefore the unit a zoom limit
201
+ * has to be expressed in.
202
+ *
203
+ * A calendar day is 24 hours; the session inside it is 6.5, and the axis has
204
+ * excised the other 17.5. So a zoom floor of "five days" reads on screen as five
205
+ * days of *trading*, which is nineteen sessions — nearly four times the intended
206
+ * span. The fixed-duration windows have no such gap (a five-minute step inside a
207
+ * session is five live minutes), which is why only the calendar family needs
208
+ * this.
209
+ *
210
+ * Measured from the sessions rather than assumed: the median bucket's live span,
211
+ * where a bucket's span is the session time inside it. That way a half-day
212
+ * before a holiday, or a market that trades 23 hours, needs no special case.
213
+ *
214
+ * `undefined` when there are no sessions to measure — the caller should fall
215
+ * back to {@link WINDOW_MS} and accept the calendar approximation.
216
+ */
217
+ export function liveWindowMs(window, sessions) {
218
+ if (isSubDay(window))
219
+ return SUB_DAY_MS[window];
220
+ if (!sessions || sessions.length === 0)
221
+ return undefined;
222
+ const perBucket = new Map();
223
+ for (const [start, end] of sessions) {
224
+ const key = floorToWindow(start, window);
225
+ perBucket.set(key, (perBucket.get(key) ?? 0) + (end - start));
226
+ }
227
+ const spans = [...perBucket.values()].sort((a, b) => a - b);
228
+ return spans[spans.length >> 1];
229
+ }
230
+ /** The grid a roll-up runs on. Session-shaped when the caller supplies sessions
231
+ * (intraday), calendar otherwise.
232
+ *
233
+ * The calendar case used to floor an explicit `range` here so the leading
234
+ * partial bucket survived — pond emitted its first bucket at the first grid
235
+ * boundary *at or after* the first event, silently dropping everything before
236
+ * it (F-charts-16). `pond-ts` 0.64.0 makes the default do that flooring, so the
237
+ * default range (the series extent) is now the right one and there is nothing
238
+ * to override. */
239
+ function bucketing(window, sessions) {
240
+ // A bounded sequence's intervals are used as-is; otherwise the calendar grid,
241
+ // which pond bounds by the series extent.
242
+ return sessionGrid(sessions ?? [], window) ?? gridFor(window);
243
+ }
244
+ /**
245
+ * Bin one numeric column into fixed windows, reducing each window to a single
246
+ * value — the data behind a {@link https://…|BarChart}. Returns an
247
+ * interval-keyed series whose one value column keeps the source column's name
248
+ * (so the chart reads it with the same `column`). At the native window each
249
+ * bucket holds one source point, so the reducer is a no-op; it only bites when
250
+ * the window is coarser than the data.
251
+ *
252
+ * Pass `sessions` for intraday data so the buckets are sessions rather than
253
+ * calendar spans — see {@link sessionGrid}.
254
+ */
255
+ export function aggregateColumn(series, column, window, reducer = 'avg', sessions) {
256
+ // Computed key ⇒ the mapping lands in aggregate's `string extends K` branch;
257
+ // the spec form ties the output column to `from`. Cast the result to the
258
+ // erased schema — callers read columns by name, not by static type.
259
+ return series.aggregate(bucketing(window, sessions), {
260
+ [column]: { from: column, using: reducer },
261
+ });
262
+ }
263
+ /**
264
+ * Roll a `time`-keyed OHLCV series up into interval-keyed OHLC windows — the
265
+ * series a coarser-than-native candle draws. `open` is the window's first,
266
+ * `high`/`low` its max/min, `close` its last; volume sums. The `<Candlestick>`
267
+ * layer reads `open`/`high`/`low`/`close` directly and derives the body itself,
268
+ * so there's no extent precompute here.
269
+ *
270
+ * Only needed when the window is coarser than the data's own interval: at the
271
+ * native interval a candle takes the raw point-keyed series straight
272
+ * (neighbour-derived slot), no aggregate pass.
273
+ *
274
+ * Pass `sessions` for intraday data so the buckets are sessions rather than
275
+ * calendar spans — see {@link sessionGrid}.
276
+ *
277
+ * The source must carry `open`/`high`/`low`/`close` columns (Tidal's price
278
+ * series does; vol series don't — the caller gates candles to the price panel).
279
+ */
280
+ export function ohlcWindow(series, window, sessions) {
281
+ return series.aggregate(bucketing(window, sessions), {
282
+ open: { from: 'open', using: 'first' },
283
+ high: { from: 'high', using: 'max' },
284
+ low: { from: 'low', using: 'min' },
285
+ close: { from: 'close', using: 'last' },
286
+ volume: { from: 'volume', using: 'sum' },
287
+ });
288
+ }
@@ -0,0 +1,61 @@
1
+ import { TimeSeries } from 'pond-ts';
2
+ /**
3
+ * Adapter for a **columnar** time-series wire envelope → a pond `TimeSeries`.
4
+ * A market-data backend streams pond-ts
5
+ * struct-of-arrays payloads (a `Replace` snapshot, then `Merge` appends for
6
+ * streaming datasets); this turns the decoded snapshot into the same `TimeSeries`
7
+ * carrier the chart layer already renders, and rowifies appends for the live
8
+ * path.
9
+ *
10
+ * pond-ts 0.41's `TimeSeries.fromColumns` is the columnar ingress, so the
11
+ * snapshot path is a thin pass-through — no hand-rolled transpose. Two v1
12
+ * constraints shape this module (logged in `CHARTS_FRICTION.md`, raised with the
13
+ * pond agent):
14
+ * 1. `fromColumns` accepts **time-key + numeric** columns only — the wire's
15
+ * `ticker`/key string columns are partition metadata, not plottable, so
16
+ * they're dropped here rather than fed in (they'd throw).
17
+ * 2. `LiveSeries` has no columnar push in 0.41, so appends must be transposed
18
+ * to rows ({@link appendToRows}) before `pushMany`.
19
+ *
20
+ * Pure + platform-free (no transport knowledge). A backend-specific decode —
21
+ * message framing, replace/merge reconciliation, a dataset catalog — belongs to
22
+ * the consumer, not here.
23
+ */
24
+ /** A cell in a columnar payload. Time cells are epoch ms (a `number`). */
25
+ export type PondValue = number | string | boolean | null;
26
+ /** One column's spec, as the wire's metadata message declares it. */
27
+ export interface WireColumnSpec {
28
+ name: string;
29
+ kind: 'time' | 'number' | 'string';
30
+ /** `false` ⇒ values may be null. */
31
+ required: boolean;
32
+ }
33
+ /** A columnar snapshot (`Replace` frame body, decoded). Column-major:
34
+ * `columns[colName][i]` is row `i`; the `time` column is epoch ms. */
35
+ export interface PondSnapshot {
36
+ name: string;
37
+ count: number;
38
+ schema: WireColumnSpec[];
39
+ columns: Record<string, PondValue[]>;
40
+ }
41
+ /** A columnar append (`Merge` frame body) — a snapshot minus `schema` (the
42
+ * consumer already has it from this series' snapshot). Rows are new since the
43
+ * last frame. */
44
+ export interface PondAppend {
45
+ name: string;
46
+ count: number;
47
+ columns: Record<string, PondValue[]>;
48
+ }
49
+ /**
50
+ * Adapt a decoded {@link PondSnapshot} into a pond `TimeSeries`. Drops string
51
+ * columns (partition metadata), coerces gaps to null, and `sort: true` since
52
+ * wire rows aren't guaranteed ascending.
53
+ */
54
+ export declare function snapshotToTimeSeries(snap: PondSnapshot): TimeSeries<import("pond-ts").SeriesSchema>;
55
+ /**
56
+ * Transpose a columnar {@link PondAppend} into row tuples in the numeric-schema's
57
+ * column order (time first) — the shape `LiveSeries.pushMany` wants, since pond
58
+ * 0.41 has no columnar append. `schema` is the one from this series' snapshot.
59
+ * Missing/non-numeric cells become `NaN` (pond treats non-finite as a gap).
60
+ */
61
+ export declare function appendToRows(append: PondAppend, schema: WireColumnSpec[]): number[][];
@@ -0,0 +1,63 @@
1
+ import { TimeSeries } from 'pond-ts';
2
+ /** The time-key + numeric columns, time first — the projection pond can ingest.
3
+ * Throws if there's no time column (every dataset leads with one). */
4
+ function plottableColumns(schema) {
5
+ const time = schema.find((c) => c.kind === 'time');
6
+ if (!time)
7
+ throw new Error('columnar payload has no time column');
8
+ return [time, ...schema.filter((c) => c.kind === 'number')];
9
+ }
10
+ /** Validate every declared column is present (if required) and aligned to
11
+ * `count` — the doc's "validate count vs columns" guard. */
12
+ function assertAligned(name, count, columns, schema) {
13
+ for (const c of schema) {
14
+ const col = columns[c.name];
15
+ if (col === undefined) {
16
+ if (c.required) {
17
+ throw new Error(`columnar payload "${name}": missing required column "${c.name}"`);
18
+ }
19
+ continue;
20
+ }
21
+ if (col.length !== count) {
22
+ throw new Error(`columnar payload "${name}": column "${c.name}" has ${col.length} values, expected count ${count}`);
23
+ }
24
+ }
25
+ }
26
+ /**
27
+ * Adapt a decoded {@link PondSnapshot} into a pond `TimeSeries`. Drops string
28
+ * columns (partition metadata), coerces gaps to null, and `sort: true` since
29
+ * wire rows aren't guaranteed ascending.
30
+ */
31
+ export function snapshotToTimeSeries(snap) {
32
+ assertAligned(snap.name, snap.count, snap.columns, snap.schema);
33
+ const cols = plottableColumns(snap.schema);
34
+ // Wire-driven schema → pond's static tuple type: a runtime array can't satisfy
35
+ // the `[FirstColumn, ...]` tuple statically, so bridge through `unknown`. pond
36
+ // validates kind + aligned length at construction (and columnar.test covers it).
37
+ const schema = cols.map((c) => ({
38
+ name: c.name,
39
+ kind: c.kind,
40
+ }));
41
+ const columns = {};
42
+ for (const c of cols) {
43
+ columns[c.name] = (snap.columns[c.name] ?? []).map((v) => (typeof v === 'number' ? v : null));
44
+ }
45
+ return TimeSeries.fromColumns({ name: snap.name, schema, columns, sort: true });
46
+ }
47
+ /**
48
+ * Transpose a columnar {@link PondAppend} into row tuples in the numeric-schema's
49
+ * column order (time first) — the shape `LiveSeries.pushMany` wants, since pond
50
+ * 0.41 has no columnar append. `schema` is the one from this series' snapshot.
51
+ * Missing/non-numeric cells become `NaN` (pond treats non-finite as a gap).
52
+ */
53
+ export function appendToRows(append, schema) {
54
+ const cols = plottableColumns(schema);
55
+ const rows = [];
56
+ for (let i = 0; i < append.count; i++) {
57
+ rows.push(cols.map((c) => {
58
+ const v = append.columns[c.name]?.[i];
59
+ return typeof v === 'number' ? v : NaN;
60
+ }));
61
+ }
62
+ return rows;
63
+ }