@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.
@@ -0,0 +1,361 @@
1
+ import { STUDIES } from '@pond-ts/financial/catalog';
2
+ import { int, num } from '@pond-ts/process';
3
+ /**
4
+ * The corpus's **runtime study catalog**, mapped onto Tidal's op registry.
5
+ *
6
+ * `STUDIES` (`@pond-ts/financial/catalog`, shipped in 0.67.0 — F-charts-25,
7
+ * asked for and delivered) is one `StudyDescriptor` per study: input roles,
8
+ * params with bounds and `suggest`, output suffixes with units, and `run`. All
9
+ * of that is exactly what a `@pond-ts/process` registry wants, so the adoption
10
+ * is a MAP rather than a transcription — which was the whole point of the ask.
11
+ *
12
+ * Everything downstream of the registry already generates itself from it: the
13
+ * study picker (`studyCatalog()`), the param controls (`opParams`), the labels
14
+ * (`studyTag`), band detection (`opIsBand`). So a study reaching `TIDAL_OPS`
15
+ * reaches the product. That is the leverage, and it is also the hazard — which
16
+ * is why {@link adoptable} is narrow and says why for each exclusion.
17
+ *
18
+ * Plan of record: Tidal's studies plan.
19
+ */
20
+ /**
21
+ * The output suffixes a `band` config reads, in the order a band op returns
22
+ * them (the engine pairs them positionally, so the two lists are one list).
23
+ *
24
+ * Lives HERE rather than in `derive.ts` because the adoption filter and the
25
+ * band style have to agree about what a band is, and the only way to agree is
26
+ * to read one list. `derive.ts` re-exports it under the same name.
27
+ */
28
+ export const BAND_OUTPUTS = ['Middle', 'Upper', 'Lower'];
29
+ /**
30
+ * A private column name for the corpus call. We hand the study a name we chose,
31
+ * read the columns straight back out, and let the ENGINE name the real ones off
32
+ * the spec id — so no mapping layer sits between the corpus's naming and ours.
33
+ */
34
+ const OUT = '__tdlStudy';
35
+ /**
36
+ * The bar columns Tidal can bind a study's input roles to.
37
+ *
38
+ * The price series carries open/high/low/close/volume (`fixture.ts`'s schema,
39
+ * and the columnar adapter's); the vol series carries `VOL_SCHEMA` and has no
40
+ * bars at all. So a study reading `high`/`low` is offerable on a PRICE series
41
+ * and nowhere else — {@link studyNeedsColumns} is what lets the picker ask.
42
+ */
43
+ const BAR_COLUMNS = new Set(['open', 'high', 'low', 'close', 'volume']);
44
+ /**
45
+ * The raw bar columns a study needs beyond its target's own column.
46
+ *
47
+ * Empty for a single-`column` study, which reads whatever it is a study OF —
48
+ * that is what makes an SMA of an SMA compose. A multi-input study is not "of a
49
+ * column" but "of a SERIES": an ATR reads high, low and close directly, so its
50
+ * inputs are the roles' own defaults and its target only decides which row it
51
+ * lands in.
52
+ */
53
+ export function studyNeedsColumns(d) {
54
+ return d.inputs.filter((i) => i.role !== 'column').map((i) => i.default);
55
+ }
56
+ /** True if every input role can be bound: the single `column` role to the
57
+ * target, and every other role to a bar column we actually carry. */
58
+ const bindable = (d) => d.inputs.every((i) => i.role === 'column' || (typeof i.default === 'string' && BAR_COLUMNS.has(i.default)));
59
+ /** True if every declared param is numeric. */
60
+ const numericParams = (d) => Object.values((d.params ?? {})).every((p) => p.kind === 'integer' || p.kind === 'number');
61
+ /**
62
+ * The corpus's unit vocabulary, in Tidal's display terms.
63
+ *
64
+ * Pond declares a closed vocabulary of 8; Tidal's `axisFormat` speaks `'$'` /
65
+ * `'%'` / `'variance'` / `'count'` / unitless. Translating HERE keeps one
66
+ * vocabulary inside the registry, so `specUnit` and every axis label go on
67
+ * working unchanged — folding pond's words in raw would have left the registry
68
+ * bilingual, with `'percent'` reaching a formatter that only knows `'%'`.
69
+ *
70
+ * `delta` maps to `'inherit'` on purpose: a difference genuinely IS in its
71
+ * source's units (a momentum of a price is a price move), so it should FORMAT
72
+ * like its source. It must not SHARE its source's axis, though, which is a
73
+ * different question — see {@link sharesSourceAxis}.
74
+ */
75
+ const DISPLAY_UNIT = {
76
+ inherit: 'inherit',
77
+ delta: 'inherit',
78
+ percent: '%',
79
+ ratio: '',
80
+ volume: 'count',
81
+ bars: 'count',
82
+ index: '',
83
+ signal: '',
84
+ };
85
+ /**
86
+ * Whether a study may draw on its source's axis — pond's rule, and the reason
87
+ * the `unit` field was worth asking for: **only `'inherit'` may share.**
88
+ *
89
+ * Read off the CATALOG's unit rather than the registry's, because the registry
90
+ * holds the translated display unit and `delta` deliberately translates to
91
+ * `'inherit'` there. An RSI on the vol axis is the failure this prevents: it is
92
+ * bounded 0..100 against a vol reading ~20, so sharing stretches the axis five
93
+ * times and squashes the series the study was meant to explain.
94
+ */
95
+ export const sharesSourceAxis = (d) => d.outputs.every((o) => o.unit === 'inherit');
96
+ /**
97
+ * The suffix the PRIMARY output is declared under when the catalog leaves it
98
+ * empty.
99
+ *
100
+ * `@pond-ts/financial`'s catalog and `@pond-ts/process`'s registry disagree
101
+ * here, and the registry is the stricter of the two: 12 studies declare an
102
+ * unnamed primary beside a named secondary (`trix` is `['', 'Signal']`), and
103
+ * `define` refuses that outright — _"every output needs a suffix — '' would
104
+ * collide with the spec id"_. It is right to refuse: with two outputs, one of
105
+ * them cannot also BE the id.
106
+ *
107
+ * So the registry sees `Value`/`Signal` where the catalog said `''`/`Signal`.
108
+ * The lists are deliberately different and must not be conflated:
109
+ * {@link catalogRun} reads the CORPUS by the catalog's own suffix, while the
110
+ * engine names OUR column off the registry's. Logged as F-charts-27.
111
+ */
112
+ const PRIMARY_SUFFIX = 'Value';
113
+ /** The suffixes to DECLARE for a descriptor — the catalog's, except that a
114
+ * multi-output op's empty primary is named (see {@link PRIMARY_SUFFIX}). */
115
+ function declaredSuffixes(d) {
116
+ const ids = d.outputs.map((o) => o.id);
117
+ if (ids.length < 2)
118
+ return ids;
119
+ return ids.map((id) => (id === '' ? PRIMARY_SUFFIX : id));
120
+ }
121
+ /**
122
+ * The per-output MARK, where the catalog cannot say — the render overlay.
123
+ *
124
+ * `unit` answers axis membership completely, and `outputs` answers how many
125
+ * columns there are, but nothing in the descriptor says how any one of them
126
+ * should be DRAWN. A MACD is `Line` / `Signal` / `Hist`, all three `delta`: the
127
+ * catalog's answer is complete and still insufficient, because two of them are
128
+ * lines and the third is a histogram. That is F-charts-26's headline case and
129
+ * this map is the workaround it asks to delete.
130
+ *
131
+ * Hand-declared and keyed by (op, suffix) rather than inferred from the name.
132
+ * `Hist` occurs exactly ONCE in the whole 109-study corpus, so a `/hist/i` rule
133
+ * would be a special case wearing a rule's clothes — it would fire on this one
134
+ * study and silently miss any future histogram named anything else. A band
135
+ * could be a rule because `Upper`/`Lower` recurs nine times; this cannot.
136
+ */
137
+ const OUTPUT_MARKS = {
138
+ // The histogram is the MACD line minus its signal, so it crosses zero exactly
139
+ // where the two lines cross — which is the reading most people take off a
140
+ // MACD, and it is unavailable when the difference is drawn as a third line.
141
+ macd: { Hist: 'bar' },
142
+ };
143
+ /** How one declared output should be drawn. `'line'` unless the overlay says
144
+ * otherwise — see {@link OUTPUT_MARKS}. */
145
+ export function outputMark(op, suffix) {
146
+ return OUTPUT_MARKS[op]?.[suffix] ?? 'line';
147
+ }
148
+ /** The output suffixes, which is also the order {@link catalogRun} returns them
149
+ * in — the engine pairs them positionally. */
150
+ const suffixes = (d) => d.outputs.map((o) => o.id);
151
+ /**
152
+ * True if the outputs are a band **Tidal's `band` style can actually read**.
153
+ *
154
+ * Keyed on the output IDS, not on `family`: `family: 'bands'` is a MENU
155
+ * grouping, and reading it as a render instruction gets two cases wrong in
156
+ * opposite directions — `bollingerBandwidth` and `bollingerPercentB` are
157
+ * `'bands'` and are single-output oscillators, while `ichimoku`'s cloud is
158
+ * `'trend'`. Declaration order does not matter: `donchian` declares
159
+ * Upper/Lower/Middle where the rest declare Middle/Upper/Lower. SIX studies
160
+ * match — not the eight in `family: 'bands'`, for the reason below.
161
+ *
162
+ * The test is the EXACT {@link BAND_OUTPUTS} set, not "has an Upper and a
163
+ * Lower", because `bandColumns` reads all three suffixes off the spec id and a
164
+ * missing one names a column that does not exist. Two shapes in the corpus
165
+ * would otherwise qualify and then fail to draw:
166
+ *
167
+ * - `rainbowOscillator` declares `['', 'Upper', 'Lower']` — its main output IS
168
+ * the id, so there is no `…Middle`. It is excluded today only by its enum
169
+ * param, which means TDL-STUDYENUM would have made it adoptable and
170
+ * `opIsBand` would have rendered it as a band with an empty wash.
171
+ * - `atrBands` and `primeNumberBands` declare `['Upper', 'Lower']` with no
172
+ * centre at all. A two-output band is a real mark Tidal cannot draw yet.
173
+ *
174
+ * Both are TDL-STUDYDRAW's problem, and both should be excluded by the RULE
175
+ * rather than by a filter clause that happens to catch them.
176
+ *
177
+ * F-charts-26 asks for this to be declared rather than inferred.
178
+ */
179
+ export const isBandShape = (d) => {
180
+ const ids = suffixes(d);
181
+ return ids.length === BAND_OUTPUTS.length && BAND_OUTPUTS.every((b) => ids.includes(b));
182
+ };
183
+ /** Ops Tidal declares BY HAND, which the loop must not redeclare.
184
+ *
185
+ * `sma`/`ema`/`bollinger` are kept hand-written on purpose: they carry exact
186
+ * `lookback` declarations (`period - 1`, and `4 * period` for the IIR — a claim
187
+ * about acceptable error that only the op can make) which the catalog does not
188
+ * carry, plus hand-written labels. Regenerating them would TRADE those away
189
+ * for uniformity. `realizedVol` is ours and not in the corpus at all
190
+ * (F-charts-11); the pair ops are two-input. */
191
+ const HAND_DECLARED = new Set([
192
+ 'sma',
193
+ 'ema',
194
+ 'bollinger',
195
+ 'realizedVol',
196
+ 'diff',
197
+ 'ratio',
198
+ 'logRatio',
199
+ ]);
200
+ /**
201
+ * Whether a descriptor can be adopted as-is, today.
202
+ *
203
+ * Deliberately narrow. Each clause is a seam Tidal has not built yet, and the
204
+ * roadmap task that builds it — a study that reaches the registry reaches the
205
+ * picker, so "offered but wrong" is worse than "not offered".
206
+ */
207
+ export function adoptable(d) {
208
+ // Already ours, with something better than the generated version.
209
+ if (HAND_DECLARED.has(d.name))
210
+ return false;
211
+ // Every input role must bind: the `column` role to the target, the rest to a
212
+ // bar column we carry. That admits the 54 studies reading high/low/close/
213
+ // volume off a bar series (TDL-STUDYINPUT) and still refuses the 4 wanting a
214
+ // benchmark SERIES, whose role carries no default at all — a second subject,
215
+ // which is the compare seam's job (TDL-STUDYBENCH).
216
+ if (!bindable(d))
217
+ return false;
218
+ // Numeric params only. 18 studies declare an enum (mostly one shared `maType`
219
+ // vocabulary); `@pond-ts/process` has `EnumParam`, so the REGISTRY would take
220
+ // them — it is `ParamControl` that is numeric-only. TDL-STUDYENUM.
221
+ if (!numericParams(d))
222
+ return false;
223
+ // Multi-output is in: a band draws as a wash (`style: 'band'`), and anything
224
+ // else draws as N lines off one spec (`style: 'lines'`), one per declared
225
+ // output. What is still missing is a per-output MARK — a MACD's histogram
226
+ // draws as a line here, which is legible but not the conventional
227
+ // presentation, and `ichimoku`'s cloud wants a fill between two of its five.
228
+ // Those are the named exceptions in TDL-STUDYDRAW, not a reason to withhold
229
+ // the studies.
230
+ // A `signal` output is STATE, not a series: a direction flag, a cross event,
231
+ // an impulse. Drawing one as a line is meaningless — it belongs beside its
232
+ // sibling as a colour driver, or alone as a marker, and Tidal has neither
233
+ // channel for a study yet. `elderImpulse` is the one that reaches here (the
234
+ // other five carry an enum or a second column and are already out).
235
+ // TDL-STUDYDRAW.
236
+ if (d.outputs.some((o) => o.unit === 'signal'))
237
+ return false;
238
+ // An `anchor` is CONTEXT, not a control: `sessionVwap` needs the series
239
+ // tagged with session ids and `anchoredVwap` needs an anchor time, neither of
240
+ // which Tidal supplies to the fold — so both compute nothing at all rather
241
+ // than computing something wrong. Pond flagged this in the reply that shipped
242
+ // the catalog, and the fold test caught it independently (2 of 58 producing
243
+ // no column), which is the useful kind of agreement. TDL-STUDYANCHOR.
244
+ if (d.anchor != null)
245
+ return false;
246
+ return true;
247
+ }
248
+ /** The studies adopted into the registry, in catalog order. */
249
+ export const ADOPTED_STUDIES = STUDIES.filter(adoptable);
250
+ /**
251
+ * Names of **adopted** studies that must not share their source's axis, so a
252
+ * consumer can ask without holding the catalog.
253
+ *
254
+ * Built from {@link ADOPTED_STUDIES}, not from the whole corpus: a hand-declared
255
+ * op must answer from the REGISTRY, which is Tidal's own declaration and
256
+ * outranks the catalog for a name Tidal owns. Scoping it here is what keeps
257
+ * that precedence right — over the whole corpus, a future hand-declared op
258
+ * sharing a catalog study's name would silently take the catalog's answer.
259
+ */
260
+ export const OWN_AXIS_STUDIES = new Set(ADOPTED_STUDIES.filter((d) => !sharesSourceAxis(d)).map((d) => d.name));
261
+ /** Map one catalog param onto the registry's param vocabulary.
262
+ *
263
+ * `example` means "no default, here is a sensible value" — the catalog uses it
264
+ * for the 16 required params. The registry needs a concrete default to fill, so
265
+ * the example becomes it; that is the only place this mapping invents anything,
266
+ * and inventing the corpus's own suggestion is the safe version. */
267
+ /* KNOWN GAP: `optional` and `requires` are dropped. Exactly one study in the
268
+ * corpus uses them (`balanceOfPower`: an optional `period`, and a `maType` that
269
+ * `requires` it), and it carries an enum so it is not adoptable anyway. The
270
+ * registry has no vocabulary for a conditional param, so this is a silent drop
271
+ * that becomes a real one the day TDL-STUDYENUM lands — noted here rather than
272
+ * discovered there. */
273
+ function mapParam(p) {
274
+ const fallback = typeof p.default === 'number' ? p.default : p.example;
275
+ const spec = {
276
+ default: fallback ?? 0,
277
+ ...(p.min === undefined ? {} : { min: p.min }),
278
+ ...(p.max === undefined ? {} : { max: p.max }),
279
+ ...(p.suggest === undefined ? {} : { suggest: p.suggest }),
280
+ };
281
+ return p.kind === 'integer' ? int(spec) : num(spec);
282
+ }
283
+ /**
284
+ * A generic `run` for any single-column study.
285
+ *
286
+ * Replaces the per-op adapters (`corpusStudy`, `bollingerRun`), which were each
287
+ * hardwired to one param name, one input and one output shape. This one reads
288
+ * the shape off the descriptor: the declared params go through as options, the
289
+ * single input binds by its declared role, and `naming.kind` decides whether
290
+ * the corpus is asked for one named column or a prefixed family.
291
+ */
292
+ export function catalogRun(d) {
293
+ // The CATALOG's suffixes, not the declared ones: this reads columns back out
294
+ // of the corpus, which names them the way the catalog says. The engine then
295
+ // names our columns off `declaredSuffixes`. Positional, so the two lists line
296
+ // up index by index and never need to match by string.
297
+ const ids = suffixes(d);
298
+ // EVERY role, not just the first: a multi-input study reads high, low and
299
+ // close, and binding only `inputs[0]` handed the corpus `high: undefined`,
300
+ // which fails inside the study rather than at our seam.
301
+ const roles = d.inputs.map((i) => i.role);
302
+ const wide = d.naming.kind === 'prefix';
303
+ const study = d.run;
304
+ return (ctx) => {
305
+ // No missing-column pre-check: the engine rejects an unknown raw input at
306
+ // COMPILE, so a gone-column spec never reaches here (pond#666 → #667).
307
+ const bound = { ...ctx.params };
308
+ for (const role of roles)
309
+ bound[role] = ctx.inputs[role];
310
+ const out = study(ctx.series, {
311
+ ...bound,
312
+ ...(wide ? { prefix: OUT } : { output: OUT }),
313
+ });
314
+ const read = out;
315
+ if (!wide) {
316
+ const col = read.column(OUT);
317
+ if (!col)
318
+ throw new Error(`${ctx.id}: ${d.name} produced no column`);
319
+ return col;
320
+ }
321
+ // Positional, matching the declared `outputs` order.
322
+ return ids.map((id) => {
323
+ const col = read.column(`${OUT}${id}`);
324
+ if (!col)
325
+ throw new Error(`${ctx.id}: ${d.name} produced no ${id || 'value'} column`);
326
+ return col;
327
+ });
328
+ };
329
+ }
330
+ /**
331
+ * One catalog descriptor as a registry definition.
332
+ *
333
+ * `lookback` is deliberately OMITTED. The catalog does not carry it, it is
334
+ * per-study knowledge (`sma` is `period - 1`; an IIR has no exact finite answer
335
+ * and the multiplier is a claim about acceptable error), and the registry
336
+ * documents omitted as **unknown, not zero** — `requiredHistory` reports the
337
+ * gap rather than handing back a number a caller would slice against. So
338
+ * omitting costs us the history-slicing win on these studies and cannot make a
339
+ * warm-up hole read as data. Inventing a multiplier for 26 studies would be the
340
+ * opposite trade. Asked for in F-charts-26.
341
+ */
342
+ export function catalogOp(d) {
343
+ const params = Object.fromEntries(Object.entries((d.params ?? {})).map(([k, p]) => [
344
+ k,
345
+ mapParam(p),
346
+ ]));
347
+ return {
348
+ name: d.name,
349
+ family: d.family,
350
+ summary: d.summary,
351
+ params,
352
+ inputs: d.inputs.map((i) => ({ role: i.role })),
353
+ // DECLARED suffixes, which differ from the catalog's for the 12 studies with
354
+ // an unnamed primary — `catalogRun` still reads the corpus by the catalog's.
355
+ outputs: declaredSuffixes(d).map((id, i) => ({
356
+ id,
357
+ unit: DISPLAY_UNIT[d.outputs[i].unit] ?? '',
358
+ })),
359
+ run: catalogRun(d),
360
+ };
361
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * **The two zones**, kept apart on purpose (TradingView's split, which is the
3
+ * one their model gets most right).
4
+ *
5
+ * - {@link DATA_TIME_ZONE} is what the numbers ARE. The archive stamps a daily
6
+ * bar at UTC midnight, `CalendarService` returns UTC-midnight open days,
7
+ * `EarningsService` the same, `aggregate`'s day/week/month buckets run in it,
8
+ * and the range picker's `YTD` starts there. It follows the DATA, and one day
9
+ * the instrument's own exchange, never a user preference.
10
+ * - The **display zone** is what the axis READS in. Purely visual, exactly as
11
+ * TradingView documents it: "the specified time zone does **not** affect time
12
+ * calculations". Changing it must never re-bucket anything.
13
+ *
14
+ * Wiring them to one value would mean picking "New York" silently re-aggregated
15
+ * the data, which is the bug their split exists to prevent.
16
+ */
17
+ export declare const DATA_TIME_ZONE = "UTC";
18
+ /** One offered zone: the IANA id stored, and how the control says it. */
19
+ export interface TimeZoneChoice {
20
+ id: string;
21
+ label: string;
22
+ }
23
+ /**
24
+ * The zones the control offers.
25
+ *
26
+ * Deliberately short. TradingView lists 80-odd because it serves every market;
27
+ * this is the set of markets this was built for, plus the two that are about the
28
+ * READER rather than the market. `Local` resolves at render time — it is a
29
+ * preference ("wherever I am"), not a zone, which is why it is stored as the
30
+ * literal `local` and not as whatever it resolved to when it was picked.
31
+ */
32
+ export declare const LOCAL_ZONE = "local";
33
+ export declare const TIME_ZONE_CHOICES: readonly TimeZoneChoice[];
34
+ /**
35
+ * A stored zone as an IANA id the chart can use — `local` resolved here, an
36
+ * unknown id falling back rather than throwing, and **no zone at all meaning
37
+ * the data zone**. Only the literal `local` asks for the viewer's zone: a host
38
+ * that passes nothing (Storybook, a library consumer) gets the axis in the zone
39
+ * the numbers are in, which is the bug the display zone exists to prevent —
40
+ * and it is what {@link timeZoneLabel} already said `undefined` meant.
41
+ *
42
+ * The fallback is not defensive padding: `Sequence.calendar` THROWS on an
43
+ * unknown zone since 0.69, IANA ids are renamed periodically
44
+ * (`Europe/Kiev` → `Europe/Kyiv`), and this value is persisted — so a preset
45
+ * written today can name a zone a later runtime has dropped. A stale preference
46
+ * must degrade to UTC, never take the chart down.
47
+ */
48
+ export declare function resolveTimeZone(stored: string | undefined): string;
49
+ /** How the status bar names the active zone: the choice's label when we offer
50
+ * it, else the bare id (a zone restored from an older build). */
51
+ export declare function timeZoneLabel(stored: string | undefined): string;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * **The two zones**, kept apart on purpose (TradingView's split, which is the
3
+ * one their model gets most right).
4
+ *
5
+ * - {@link DATA_TIME_ZONE} is what the numbers ARE. The archive stamps a daily
6
+ * bar at UTC midnight, `CalendarService` returns UTC-midnight open days,
7
+ * `EarningsService` the same, `aggregate`'s day/week/month buckets run in it,
8
+ * and the range picker's `YTD` starts there. It follows the DATA, and one day
9
+ * the instrument's own exchange, never a user preference.
10
+ * - The **display zone** is what the axis READS in. Purely visual, exactly as
11
+ * TradingView documents it: "the specified time zone does **not** affect time
12
+ * calculations". Changing it must never re-bucket anything.
13
+ *
14
+ * Wiring them to one value would mean picking "New York" silently re-aggregated
15
+ * the data, which is the bug their split exists to prevent.
16
+ */
17
+ export const DATA_TIME_ZONE = 'UTC';
18
+ /**
19
+ * The zones the control offers.
20
+ *
21
+ * Deliberately short. TradingView lists 80-odd because it serves every market;
22
+ * this is the set of markets this was built for, plus the two that are about the
23
+ * READER rather than the market. `Local` resolves at render time — it is a
24
+ * preference ("wherever I am"), not a zone, which is why it is stored as the
25
+ * literal `local` and not as whatever it resolved to when it was picked.
26
+ */
27
+ export const LOCAL_ZONE = 'local';
28
+ export const TIME_ZONE_CHOICES = [
29
+ { id: 'UTC', label: 'UTC' },
30
+ { id: 'America/New_York', label: 'New York' },
31
+ { id: 'America/Chicago', label: 'Chicago' },
32
+ { id: 'Europe/London', label: 'London' },
33
+ { id: 'Europe/Amsterdam', label: 'Amsterdam' },
34
+ { id: 'Europe/Madrid', label: 'Madrid' },
35
+ { id: 'Asia/Tokyo', label: 'Tokyo' },
36
+ { id: 'Australia/Sydney', label: 'Sydney' },
37
+ { id: LOCAL_ZONE, label: 'Local' },
38
+ ];
39
+ /**
40
+ * A stored zone as an IANA id the chart can use — `local` resolved here, an
41
+ * unknown id falling back rather than throwing, and **no zone at all meaning
42
+ * the data zone**. Only the literal `local` asks for the viewer's zone: a host
43
+ * that passes nothing (Storybook, a library consumer) gets the axis in the zone
44
+ * the numbers are in, which is the bug the display zone exists to prevent —
45
+ * and it is what {@link timeZoneLabel} already said `undefined` meant.
46
+ *
47
+ * The fallback is not defensive padding: `Sequence.calendar` THROWS on an
48
+ * unknown zone since 0.69, IANA ids are renamed periodically
49
+ * (`Europe/Kiev` → `Europe/Kyiv`), and this value is persisted — so a preset
50
+ * written today can name a zone a later runtime has dropped. A stale preference
51
+ * must degrade to UTC, never take the chart down.
52
+ */
53
+ export function resolveTimeZone(stored) {
54
+ if (!stored)
55
+ return DATA_TIME_ZONE;
56
+ if (stored === LOCAL_ZONE) {
57
+ try {
58
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || DATA_TIME_ZONE;
59
+ }
60
+ catch {
61
+ return DATA_TIME_ZONE;
62
+ }
63
+ }
64
+ try {
65
+ // The cheapest real validation: formatting with an unknown zone throws.
66
+ new Intl.DateTimeFormat('en', { timeZone: stored }).format(0);
67
+ return stored;
68
+ }
69
+ catch {
70
+ return DATA_TIME_ZONE;
71
+ }
72
+ }
73
+ /** How the status bar names the active zone: the choice's label when we offer
74
+ * it, else the bare id (a zone restored from an older build). */
75
+ export function timeZoneLabel(stored) {
76
+ const found = TIME_ZONE_CHOICES.find((c) => c.id === (stored ?? DATA_TIME_ZONE));
77
+ if (found)
78
+ return found.label;
79
+ return stored ?? DATA_TIME_ZONE;
80
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Tidal domain vocabulary — the financial-instrument types every other layer
3
+ * speaks. Pure: no React, no platform deps, no pond import. (The pond
4
+ * `TimeSeries` is the *carrier* for price data; see `fixture.ts` / the data
5
+ * layer. These types describe *what* a series is of.)
6
+ */
7
+ /** The asset class an instrument belongs to. Drives display + later, which
8
+ * data endpoint serves it. */
9
+ export type InstrumentKind = 'equity' | 'crypto' | 'fx' | 'index';
10
+ /** A tradeable thing Tidal can chart. `symbol` is the stable identity
11
+ * (e.g. `AAPL`, `BTC-USD`); `name` is display-only. */
12
+ export interface Instrument {
13
+ symbol: string;
14
+ name: string;
15
+ kind: InstrumentKind;
16
+ }
17
+ /** A bar interval (the spacing between samples). Display + generation use it;
18
+ * the value is the bar duration in milliseconds. */
19
+ export type BarInterval = '1m' | '5m' | '1h' | '1d';
20
+ export declare const BAR_INTERVAL_MS: Record<BarInterval, number>;
package/dist/types.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Tidal domain vocabulary — the financial-instrument types every other layer
3
+ * speaks. Pure: no React, no platform deps, no pond import. (The pond
4
+ * `TimeSeries` is the *carrier* for price data; see `fixture.ts` / the data
5
+ * layer. These types describe *what* a series is of.)
6
+ */
7
+ export const BAR_INTERVAL_MS = {
8
+ '1m': 60_000,
9
+ '5m': 5 * 60_000,
10
+ '1h': 60 * 60_000,
11
+ '1d': 24 * 60 * 60_000,
12
+ };