@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 +21 -0
- package/dist/aggregate.d.ts +193 -0
- package/dist/aggregate.js +288 -0
- package/dist/columnar.d.ts +61 -0
- package/dist/columnar.js +63 -0
- package/dist/derive.d.ts +555 -0
- package/dist/derive.js +740 -0
- package/dist/expirations.d.ts +85 -0
- package/dist/expirations.js +151 -0
- package/dist/extent.d.ts +20 -0
- package/dist/extent.js +44 -0
- package/dist/fixture.d.ts +64 -0
- package/dist/fixture.js +116 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +16 -0
- package/dist/join.d.ts +31 -0
- package/dist/join.js +36 -0
- package/dist/regrid.d.ts +22 -0
- package/dist/regrid.js +85 -0
- package/dist/sessions.d.ts +141 -0
- package/dist/sessions.js +232 -0
- package/dist/studyCatalog.d.ts +129 -0
- package/dist/studyCatalog.js +361 -0
- package/dist/timeZone.d.ts +51 -0
- package/dist/timeZone.js +80 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +12 -0
- package/dist/vol.d.ts +160 -0
- package/dist/vol.js +252 -0
- package/package.json +50 -0
package/dist/regrid.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { buildVolSeries, VOL_SCHEMA } from './vol.js';
|
|
2
|
+
/**
|
|
3
|
+
* Hold a **coarse** vol series at a **finer** grid — the daily ATM curve drawn on
|
|
4
|
+
* an intraday axis.
|
|
5
|
+
*
|
|
6
|
+
* The archive has no intraday vol (finest is 30-minute surfaces, and none of them
|
|
7
|
+
* loaded), so a 1-minute request returns a vol series with *no vol columns at
|
|
8
|
+
* all* — the panel goes blank. That reads as breakage, when the honest answer is
|
|
9
|
+
* "we know this daily, and here it is". So the service fetches vol at the finest
|
|
10
|
+
* grain that has it and this holds each daily value across that day's bars.
|
|
11
|
+
*
|
|
12
|
+
* A **step function**, deliberately, and not interpolation. The daily ATM vol is
|
|
13
|
+
* one observation attributed to a session; drawing a slope between two of them
|
|
14
|
+
* would invent intraday structure we have no evidence for and that the surface
|
|
15
|
+
* datasets would contradict once loaded. A flat segment says "constant as far as
|
|
16
|
+
* we know", which is true.
|
|
17
|
+
*
|
|
18
|
+
* ## Why the coarse series cannot simply be handed to the chart
|
|
19
|
+
*
|
|
20
|
+
* A daily series keyed at UTC midnight, placed on an axis built from 1-minute
|
|
21
|
+
* bars, poisons the axis rather than the panel: `TimeSeriesChart` derives its trading
|
|
22
|
+
* sessions from the **union** of every source's timestamps, so midnight — which is
|
|
23
|
+
* not a trading minute — would enter the session model, and the inferred bar
|
|
24
|
+
* interval would be a mix of one day and one minute. Regridding first means the
|
|
25
|
+
* two series share one grid and the axis sees only real trading minutes.
|
|
26
|
+
*/
|
|
27
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
28
|
+
/** The UTC midnight a timestamp belongs to — the daily series' own key. */
|
|
29
|
+
const dayOf = (t) => Math.floor(t / DAY_MS) * DAY_MS;
|
|
30
|
+
/**
|
|
31
|
+
* Re-key `coarse` onto `times`, holding each source row across every target
|
|
32
|
+
* timestamp that falls on its day.
|
|
33
|
+
*
|
|
34
|
+
* `times` must be ascending (the price series' own keys). A target day the coarse
|
|
35
|
+
* series has no row for yields `NaN` across that day, which the chart reads as a
|
|
36
|
+
* gap rather than as zero — correct, since "no vol published for this session" is
|
|
37
|
+
* not "vol was nothing".
|
|
38
|
+
*
|
|
39
|
+
* Returns the coarse series unchanged when there is **nothing to hold** — an empty
|
|
40
|
+
* target grid, or an empty source.
|
|
41
|
+
*
|
|
42
|
+
* It does NOT short-circuit a source that is already as dense as the target; an
|
|
43
|
+
* earlier version of this sentence claimed it did, and did not. Today that path is
|
|
44
|
+
* unreachable (`volGrains` is `['1d']` everywhere, so the fallback grain is always
|
|
45
|
+
* coarser), but `resolveGrain` does not guarantee it: a source declaring
|
|
46
|
+
* `volGrains: ['30m']` answers a `1d` request with `'30m'` via its
|
|
47
|
+
* last-resort branch, and this would then re-key a 30-minute series onto a daily
|
|
48
|
+
* grid, silently keeping each day's LAST intraday value.
|
|
49
|
+
*/
|
|
50
|
+
export function holdVolAcrossGrid(coarse, times, name = 'vol') {
|
|
51
|
+
if (times.length === 0 || coarse.length === 0)
|
|
52
|
+
return coarse;
|
|
53
|
+
// Row index per source day. Later rows win: a day appearing twice is a
|
|
54
|
+
// restatement (a daily-history feed does restate `ccVar`), and the newer value is
|
|
55
|
+
// the one to hold.
|
|
56
|
+
const key = coarse.keyColumn();
|
|
57
|
+
const rowOfDay = new Map();
|
|
58
|
+
for (let i = 0; i < coarse.length; i += 1) {
|
|
59
|
+
const t = key.at(i);
|
|
60
|
+
if (t !== undefined)
|
|
61
|
+
rowOfDay.set(dayOf(t), i);
|
|
62
|
+
}
|
|
63
|
+
// Read every schema column once, then walk the target grid per column. Column
|
|
64
|
+
// access is the cheap direction here (columnar storage), and the day lookup is
|
|
65
|
+
// shared across columns via `rows` below.
|
|
66
|
+
const rows = times.map((t) => rowOfDay.get(dayOf(t)));
|
|
67
|
+
const columns = { time: [...times] };
|
|
68
|
+
for (const spec of VOL_SCHEMA) {
|
|
69
|
+
if (spec.name === 'time')
|
|
70
|
+
continue;
|
|
71
|
+
const src = coarse.column(spec.name);
|
|
72
|
+
// Every `VOL_SCHEMA` column is emitted whether the source has it or not:
|
|
73
|
+
// `buildVolSeries` requires the full schema, and keeping the vol series' TYPE
|
|
74
|
+
// stable is worth more than signalling absence through a missing column. A
|
|
75
|
+
// column the source lacks comes through as all-NaN, which the chart reads as a
|
|
76
|
+
// series with no points — an empty layer, not a wrong one.
|
|
77
|
+
const out = new Array(times.length);
|
|
78
|
+
for (let i = 0; i < times.length; i += 1) {
|
|
79
|
+
const r = src === undefined || rows[i] === undefined ? undefined : src.at(rows[i]);
|
|
80
|
+
out[i] = typeof r === 'number' && Number.isFinite(r) ? r : NaN;
|
|
81
|
+
}
|
|
82
|
+
columns[spec.name] = out;
|
|
83
|
+
}
|
|
84
|
+
return buildVolSeries(name, columns);
|
|
85
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { TimeSeries } from 'pond-ts';
|
|
2
|
+
import type { SeriesSchema } from 'pond-ts';
|
|
3
|
+
/** A live (non-excised) span of the time axis — everything between spans is
|
|
4
|
+
* collapsed. Structurally pond's `LiveSegment`. */
|
|
5
|
+
export type Segment = readonly [start: number, end: number];
|
|
6
|
+
export interface SessionSegmentOptions {
|
|
7
|
+
/**
|
|
8
|
+
* A gap larger than `barMs × gapFactor` starts a new segment. Default `1.5`.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately just above one bar: on a trading-time axis, time with no bar is
|
|
11
|
+
* time that did not trade, and collapsing it is the point. That covers
|
|
12
|
+
* overnight, weekends, holidays and half-days with one rule and no calendar.
|
|
13
|
+
*/
|
|
14
|
+
gapFactor?: number;
|
|
15
|
+
/** The bar interval. Inferred from the median gap when omitted, which is
|
|
16
|
+
* robust to holes as long as under half the bars are missing. */
|
|
17
|
+
barMs?: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Derive the axis's live segments **from the data**, so non-trading time
|
|
21
|
+
* collapses.
|
|
22
|
+
*
|
|
23
|
+
* Good enough for most windows, and **measurably not good enough for short ones**
|
|
24
|
+
* — see {@link exactSessionSegments}, which supersedes this wherever a calendar is
|
|
25
|
+
* available.
|
|
26
|
+
*
|
|
27
|
+
* The threshold is relative to the *median* gap in the window, so it is only right
|
|
28
|
+
* while the median is representative. Measured over the app's own ranges, on daily
|
|
29
|
+
* bars spanning Thanksgiving 2025:
|
|
30
|
+
*
|
|
31
|
+
* | range | bars | median gap | threshold | holiday |
|
|
32
|
+
* | ----- | ---- | ---------- | --------- | ------- |
|
|
33
|
+
* | `5D` | 5 | 2d | 3.00d | **inside a live span → a gap on screen** |
|
|
34
|
+
* | `1M`+ | 21+ | 1d | 1.50d | collapsed correctly |
|
|
35
|
+
*
|
|
36
|
+
* At five bars, half the gaps are weekends, so the median is 2 days and a 1-day
|
|
37
|
+
* holiday gap no longer clears the bar. The same holiday therefore renders
|
|
38
|
+
* differently depending on how far you are zoomed out — and a market closure is a
|
|
39
|
+
* property of the market, not of the viewport.
|
|
40
|
+
*
|
|
41
|
+
* This still earns its place: it needs no calendar, it handles a symbol that simply
|
|
42
|
+
* did not print, and intraday it is unambiguous (an overnight gap is ~100× a bar,
|
|
43
|
+
* so no median can blur it). Prefer {@link exactSessionSegments} at daily grain, and
|
|
44
|
+
* keep this for intraday and for any source with no calendar behind it.
|
|
45
|
+
*
|
|
46
|
+
* Why it matters: `weekendSkip()` collapses weekends only. On a year of 1-minute
|
|
47
|
+
* bars that leaves ~190 overnight gaps of ~8 hours on the axis, so each trading
|
|
48
|
+
* day's 6.5 hours occupies about a quarter of its day's width — roughly a 1px
|
|
49
|
+
* stripe separated by 3px of nothing. Most of the axis is empty.
|
|
50
|
+
*
|
|
51
|
+
* Returns `[]` for fewer than two points — the caller should fall back to a
|
|
52
|
+
* continuous axis rather than excise everything.
|
|
53
|
+
*/
|
|
54
|
+
export declare function sessionSegments(times: readonly number[], options?: SessionSegmentOptions): Segment[];
|
|
55
|
+
/**
|
|
56
|
+
* Live segments by **exact adjacency** — one span per contiguous run of bars.
|
|
57
|
+
*
|
|
58
|
+
* Two bars are in the same span iff the second starts exactly one interval after
|
|
59
|
+
* the first. No threshold, so nothing to tune and — the point — nothing that
|
|
60
|
+
* changes with the window. {@link sessionSegments} compares each gap against the
|
|
61
|
+
* *median* gap in view, which is only right while the median is representative;
|
|
62
|
+
* at five daily bars it is 2 days, and a 1-day holiday gap stops clearing it. This
|
|
63
|
+
* has no median to distort.
|
|
64
|
+
*
|
|
65
|
+
* **Requires dense data**: every interval inside a session must be present, because
|
|
66
|
+
* a single missing bar reads as a session boundary. That holds for daily bars (a
|
|
67
|
+
* trading day either printed or was not a session) and for our 1-minute archive,
|
|
68
|
+
* which is gap-free in session — and it does NOT hold for a sparse or thinly-traded
|
|
69
|
+
* series, where {@link sessionSegments}'s tolerance is the right trade.
|
|
70
|
+
*
|
|
71
|
+
* `starts` must be sorted ascending. Consecutive intervals merge rather than
|
|
72
|
+
* becoming one segment each: adjacent bars have no gap to collapse, and 53 segments
|
|
73
|
+
* a year draw the same axis as 252 for a fraction of the work.
|
|
74
|
+
*
|
|
75
|
+
* It takes the instants it is **given**, which is what makes it work for either
|
|
76
|
+
* input: pass the days you hold and the axis shows real bars; pass a trading
|
|
77
|
+
* calendar and it shows that a session *should* have been there. That choice is the
|
|
78
|
+
* caller's, not this function's.
|
|
79
|
+
*
|
|
80
|
+
* Returns `[]` for an empty input, so a caller falls back rather than excising
|
|
81
|
+
* everything.
|
|
82
|
+
*/
|
|
83
|
+
export declare function exactSessionSegments(starts: readonly number[], intervalMs: number): Segment[];
|
|
84
|
+
/**
|
|
85
|
+
* The series' native bar interval, inferred as the **median** gap between keys.
|
|
86
|
+
*
|
|
87
|
+
* Median rather than min or mean: a missing bar doubles one gap and a session
|
|
88
|
+
* boundary multiplies another by hundreds, so anything sensitive to outliers
|
|
89
|
+
* reports nonsense. The median lands on the true interval as long as under half
|
|
90
|
+
* the bars are missing.
|
|
91
|
+
*
|
|
92
|
+
* Returns `undefined` for fewer than two points — the caller should not guess.
|
|
93
|
+
*/
|
|
94
|
+
export declare function inferBarMs(times: readonly number[]): number | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* Shift every key forward by `ms`, keeping the values where they are.
|
|
97
|
+
*
|
|
98
|
+
* Exists because **a bar's timestamp is its OPEN, and a line through `close`
|
|
99
|
+
* belongs at the bar's END.** The archive stamps the bar that covers 13:30–13:31
|
|
100
|
+
* as `13:30`, so its `close` is the price at ~13:31; plotting that close at 13:30
|
|
101
|
+
* draws every intraday close one bar early. Uniform, so invisible mid-series —
|
|
102
|
+
* and exactly visible at a session seam, where the day's final close lands at
|
|
103
|
+
* 21:59 instead of 22:00 and the first close of the next session lands on the
|
|
104
|
+
* open instead of a minute after it.
|
|
105
|
+
*
|
|
106
|
+
* Shifting the KEY rather than fixing it at the source is deliberate: a candle
|
|
107
|
+
* needs the span `[open, close]` and draws from the open, so the two styles want
|
|
108
|
+
* different x for the same row. Charts plots a line at the key's `begin`
|
|
109
|
+
* whichever key kind it is, so the only way to move the line is to move the key —
|
|
110
|
+
* and only for the layers that want it moved.
|
|
111
|
+
*
|
|
112
|
+
* Costs one pass over the key column plus a rebuild (~14 ms at 100k rows), so it
|
|
113
|
+
* belongs behind a per-fetch memo, never in a render path.
|
|
114
|
+
*/
|
|
115
|
+
export declare function shiftKeys(series: TimeSeries<SeriesSchema>, ms: number): TimeSeries<SeriesSchema>;
|
|
116
|
+
/**
|
|
117
|
+
* The price path a session actually traced: its **open**, then every close.
|
|
118
|
+
*
|
|
119
|
+
* A line of closes alone starts a minute late. The bar covering 15:30–15:31 has
|
|
120
|
+
* its close at 15:31, so a close-keyed line's first point is 15:31 — while the
|
|
121
|
+
* axis holds 15:30 as live time with nothing drawn on it. The opening print is a
|
|
122
|
+
* real observed price at 15:30, and omitting it is a consequence of picking one
|
|
123
|
+
* column, not of what happened.
|
|
124
|
+
*
|
|
125
|
+
* So each session contributes `bars + 1` points: `(open time, open)` followed by
|
|
126
|
+
* one `(close time, close)` per bar. Every point remains an observation — the
|
|
127
|
+
* price at 15:30 was the open, at 15:31 the first close, at 15:32 the second — and
|
|
128
|
+
* the line now spans the whole live segment instead of starting inside it.
|
|
129
|
+
*
|
|
130
|
+
* Emits ONE column, named after `close`, so a chart already asking for that column
|
|
131
|
+
* needs no change. Only a series carrying both columns can use this; a vol series
|
|
132
|
+
* has no open, and its line keeps the shifted closes (see {@link shiftKeys}).
|
|
133
|
+
*
|
|
134
|
+
* A session boundary is a key gap wider than `barMs × gapFactor` — the same rule
|
|
135
|
+
* {@link sessionSegments} uses, so the two cannot disagree about where a session
|
|
136
|
+
* starts.
|
|
137
|
+
*/
|
|
138
|
+
export declare function sessionOpenLine(series: TimeSeries<SeriesSchema>, barMs: number, columns: {
|
|
139
|
+
open: string;
|
|
140
|
+
close: string;
|
|
141
|
+
}, gapFactor?: number): TimeSeries<SeriesSchema>;
|
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { TimeSeries } from 'pond-ts';
|
|
2
|
+
/**
|
|
3
|
+
* Derive the axis's live segments **from the data**, so non-trading time
|
|
4
|
+
* collapses.
|
|
5
|
+
*
|
|
6
|
+
* Good enough for most windows, and **measurably not good enough for short ones**
|
|
7
|
+
* — see {@link exactSessionSegments}, which supersedes this wherever a calendar is
|
|
8
|
+
* available.
|
|
9
|
+
*
|
|
10
|
+
* The threshold is relative to the *median* gap in the window, so it is only right
|
|
11
|
+
* while the median is representative. Measured over the app's own ranges, on daily
|
|
12
|
+
* bars spanning Thanksgiving 2025:
|
|
13
|
+
*
|
|
14
|
+
* | range | bars | median gap | threshold | holiday |
|
|
15
|
+
* | ----- | ---- | ---------- | --------- | ------- |
|
|
16
|
+
* | `5D` | 5 | 2d | 3.00d | **inside a live span → a gap on screen** |
|
|
17
|
+
* | `1M`+ | 21+ | 1d | 1.50d | collapsed correctly |
|
|
18
|
+
*
|
|
19
|
+
* At five bars, half the gaps are weekends, so the median is 2 days and a 1-day
|
|
20
|
+
* holiday gap no longer clears the bar. The same holiday therefore renders
|
|
21
|
+
* differently depending on how far you are zoomed out — and a market closure is a
|
|
22
|
+
* property of the market, not of the viewport.
|
|
23
|
+
*
|
|
24
|
+
* This still earns its place: it needs no calendar, it handles a symbol that simply
|
|
25
|
+
* did not print, and intraday it is unambiguous (an overnight gap is ~100× a bar,
|
|
26
|
+
* so no median can blur it). Prefer {@link exactSessionSegments} at daily grain, and
|
|
27
|
+
* keep this for intraday and for any source with no calendar behind it.
|
|
28
|
+
*
|
|
29
|
+
* Why it matters: `weekendSkip()` collapses weekends only. On a year of 1-minute
|
|
30
|
+
* bars that leaves ~190 overnight gaps of ~8 hours on the axis, so each trading
|
|
31
|
+
* day's 6.5 hours occupies about a quarter of its day's width — roughly a 1px
|
|
32
|
+
* stripe separated by 3px of nothing. Most of the axis is empty.
|
|
33
|
+
*
|
|
34
|
+
* Returns `[]` for fewer than two points — the caller should fall back to a
|
|
35
|
+
* continuous axis rather than excise everything.
|
|
36
|
+
*/
|
|
37
|
+
export function sessionSegments(times, options = {}) {
|
|
38
|
+
const finite = times.filter((t) => Number.isFinite(t));
|
|
39
|
+
if (finite.length < 2)
|
|
40
|
+
return [];
|
|
41
|
+
// Duplicates are expected — a union of several symbols repeats every shared
|
|
42
|
+
// minute — and a zero gap must not be mistaken for a bar interval.
|
|
43
|
+
const gaps = [];
|
|
44
|
+
for (let i = 1; i < finite.length; i += 1) {
|
|
45
|
+
const d = finite[i] - finite[i - 1];
|
|
46
|
+
if (d > 0)
|
|
47
|
+
gaps.push(d);
|
|
48
|
+
}
|
|
49
|
+
if (gaps.length === 0)
|
|
50
|
+
return [];
|
|
51
|
+
const barMs = options.barMs ?? median(gaps);
|
|
52
|
+
const threshold = barMs * (options.gapFactor ?? 1.5);
|
|
53
|
+
const segments = [];
|
|
54
|
+
let start = finite[0];
|
|
55
|
+
let prev = finite[0];
|
|
56
|
+
for (let i = 1; i < finite.length; i += 1) {
|
|
57
|
+
const t = finite[i];
|
|
58
|
+
if (t - prev > threshold) {
|
|
59
|
+
// Close the run one bar past its last point, so the final bar of a session
|
|
60
|
+
// has width instead of collapsing to a hairline at the boundary.
|
|
61
|
+
segments.push([start, prev + barMs]);
|
|
62
|
+
start = t;
|
|
63
|
+
}
|
|
64
|
+
prev = t;
|
|
65
|
+
}
|
|
66
|
+
segments.push([start, prev + barMs]);
|
|
67
|
+
return segments;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Live segments by **exact adjacency** — one span per contiguous run of bars.
|
|
71
|
+
*
|
|
72
|
+
* Two bars are in the same span iff the second starts exactly one interval after
|
|
73
|
+
* the first. No threshold, so nothing to tune and — the point — nothing that
|
|
74
|
+
* changes with the window. {@link sessionSegments} compares each gap against the
|
|
75
|
+
* *median* gap in view, which is only right while the median is representative;
|
|
76
|
+
* at five daily bars it is 2 days, and a 1-day holiday gap stops clearing it. This
|
|
77
|
+
* has no median to distort.
|
|
78
|
+
*
|
|
79
|
+
* **Requires dense data**: every interval inside a session must be present, because
|
|
80
|
+
* a single missing bar reads as a session boundary. That holds for daily bars (a
|
|
81
|
+
* trading day either printed or was not a session) and for our 1-minute archive,
|
|
82
|
+
* which is gap-free in session — and it does NOT hold for a sparse or thinly-traded
|
|
83
|
+
* series, where {@link sessionSegments}'s tolerance is the right trade.
|
|
84
|
+
*
|
|
85
|
+
* `starts` must be sorted ascending. Consecutive intervals merge rather than
|
|
86
|
+
* becoming one segment each: adjacent bars have no gap to collapse, and 53 segments
|
|
87
|
+
* a year draw the same axis as 252 for a fraction of the work.
|
|
88
|
+
*
|
|
89
|
+
* It takes the instants it is **given**, which is what makes it work for either
|
|
90
|
+
* input: pass the days you hold and the axis shows real bars; pass a trading
|
|
91
|
+
* calendar and it shows that a session *should* have been there. That choice is the
|
|
92
|
+
* caller's, not this function's.
|
|
93
|
+
*
|
|
94
|
+
* Returns `[]` for an empty input, so a caller falls back rather than excising
|
|
95
|
+
* everything.
|
|
96
|
+
*/
|
|
97
|
+
export function exactSessionSegments(starts, intervalMs) {
|
|
98
|
+
const days = starts.filter((t) => Number.isFinite(t));
|
|
99
|
+
if (days.length === 0 || !(intervalMs > 0))
|
|
100
|
+
return [];
|
|
101
|
+
const segments = [];
|
|
102
|
+
let start = days[0];
|
|
103
|
+
let prev = days[0];
|
|
104
|
+
for (let i = 1; i < days.length; i += 1) {
|
|
105
|
+
const t = days[i];
|
|
106
|
+
// Adjacent sessions extend the run; anything else — a weekend, a holiday, a
|
|
107
|
+
// day the caller filtered out — closes it. No threshold, so nothing to tune
|
|
108
|
+
// and nothing that changes with the window.
|
|
109
|
+
if (t !== prev + intervalMs) {
|
|
110
|
+
segments.push([start, prev + intervalMs]);
|
|
111
|
+
start = t;
|
|
112
|
+
}
|
|
113
|
+
prev = t;
|
|
114
|
+
}
|
|
115
|
+
segments.push([start, prev + intervalMs]);
|
|
116
|
+
return segments;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The series' native bar interval, inferred as the **median** gap between keys.
|
|
120
|
+
*
|
|
121
|
+
* Median rather than min or mean: a missing bar doubles one gap and a session
|
|
122
|
+
* boundary multiplies another by hundreds, so anything sensitive to outliers
|
|
123
|
+
* reports nonsense. The median lands on the true interval as long as under half
|
|
124
|
+
* the bars are missing.
|
|
125
|
+
*
|
|
126
|
+
* Returns `undefined` for fewer than two points — the caller should not guess.
|
|
127
|
+
*/
|
|
128
|
+
export function inferBarMs(times) {
|
|
129
|
+
const finite = times.filter((t) => Number.isFinite(t));
|
|
130
|
+
const gaps = [];
|
|
131
|
+
for (let i = 1; i < finite.length; i += 1) {
|
|
132
|
+
const d = finite[i] - finite[i - 1];
|
|
133
|
+
if (d > 0)
|
|
134
|
+
gaps.push(d);
|
|
135
|
+
}
|
|
136
|
+
return gaps.length ? median(gaps) : undefined;
|
|
137
|
+
}
|
|
138
|
+
function median(values) {
|
|
139
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
140
|
+
const mid = sorted.length >> 1;
|
|
141
|
+
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Shift every key forward by `ms`, keeping the values where they are.
|
|
145
|
+
*
|
|
146
|
+
* Exists because **a bar's timestamp is its OPEN, and a line through `close`
|
|
147
|
+
* belongs at the bar's END.** The archive stamps the bar that covers 13:30–13:31
|
|
148
|
+
* as `13:30`, so its `close` is the price at ~13:31; plotting that close at 13:30
|
|
149
|
+
* draws every intraday close one bar early. Uniform, so invisible mid-series —
|
|
150
|
+
* and exactly visible at a session seam, where the day's final close lands at
|
|
151
|
+
* 21:59 instead of 22:00 and the first close of the next session lands on the
|
|
152
|
+
* open instead of a minute after it.
|
|
153
|
+
*
|
|
154
|
+
* Shifting the KEY rather than fixing it at the source is deliberate: a candle
|
|
155
|
+
* needs the span `[open, close]` and draws from the open, so the two styles want
|
|
156
|
+
* different x for the same row. Charts plots a line at the key's `begin`
|
|
157
|
+
* whichever key kind it is, so the only way to move the line is to move the key —
|
|
158
|
+
* and only for the layers that want it moved.
|
|
159
|
+
*
|
|
160
|
+
* Costs one pass over the key column plus a rebuild (~14 ms at 100k rows), so it
|
|
161
|
+
* belongs behind a per-fetch memo, never in a render path.
|
|
162
|
+
*/
|
|
163
|
+
export function shiftKeys(series, ms) {
|
|
164
|
+
if (ms === 0)
|
|
165
|
+
return series;
|
|
166
|
+
const out = series.toColumns();
|
|
167
|
+
const key = out.schema.find((c) => c.kind === 'time')?.name;
|
|
168
|
+
// No time key (a value-keyed series) ⇒ nothing to shift, and shifting the wrong
|
|
169
|
+
// column would corrupt values rather than fail.
|
|
170
|
+
if (key === undefined)
|
|
171
|
+
return series;
|
|
172
|
+
const src = out.columns[key];
|
|
173
|
+
const shifted = new Float64Array(src.length);
|
|
174
|
+
for (let i = 0; i < src.length; i += 1)
|
|
175
|
+
shifted[i] = src[i] + ms;
|
|
176
|
+
return TimeSeries.fromColumns({
|
|
177
|
+
...out,
|
|
178
|
+
columns: { ...out.columns, [key]: shifted },
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The price path a session actually traced: its **open**, then every close.
|
|
183
|
+
*
|
|
184
|
+
* A line of closes alone starts a minute late. The bar covering 15:30–15:31 has
|
|
185
|
+
* its close at 15:31, so a close-keyed line's first point is 15:31 — while the
|
|
186
|
+
* axis holds 15:30 as live time with nothing drawn on it. The opening print is a
|
|
187
|
+
* real observed price at 15:30, and omitting it is a consequence of picking one
|
|
188
|
+
* column, not of what happened.
|
|
189
|
+
*
|
|
190
|
+
* So each session contributes `bars + 1` points: `(open time, open)` followed by
|
|
191
|
+
* one `(close time, close)` per bar. Every point remains an observation — the
|
|
192
|
+
* price at 15:30 was the open, at 15:31 the first close, at 15:32 the second — and
|
|
193
|
+
* the line now spans the whole live segment instead of starting inside it.
|
|
194
|
+
*
|
|
195
|
+
* Emits ONE column, named after `close`, so a chart already asking for that column
|
|
196
|
+
* needs no change. Only a series carrying both columns can use this; a vol series
|
|
197
|
+
* has no open, and its line keeps the shifted closes (see {@link shiftKeys}).
|
|
198
|
+
*
|
|
199
|
+
* A session boundary is a key gap wider than `barMs × gapFactor` — the same rule
|
|
200
|
+
* {@link sessionSegments} uses, so the two cannot disagree about where a session
|
|
201
|
+
* starts.
|
|
202
|
+
*/
|
|
203
|
+
export function sessionOpenLine(series, barMs, columns, gapFactor = 1.5) {
|
|
204
|
+
const out = series.toColumns();
|
|
205
|
+
const keyName = out.schema.find((c) => c.kind === 'time')?.name;
|
|
206
|
+
const opens = out.columns[columns.open];
|
|
207
|
+
const closes = out.columns[columns.close];
|
|
208
|
+
if (keyName === undefined || !opens || !closes)
|
|
209
|
+
return series;
|
|
210
|
+
const keys = out.columns[keyName];
|
|
211
|
+
const n = keys.length;
|
|
212
|
+
const t = [];
|
|
213
|
+
const v = [];
|
|
214
|
+
const threshold = barMs * gapFactor;
|
|
215
|
+
for (let i = 0; i < n; i += 1) {
|
|
216
|
+
// A session start: the first bar, or one whose predecessor is a gap away.
|
|
217
|
+
if (i === 0 || keys[i] - keys[i - 1] > threshold) {
|
|
218
|
+
t.push(keys[i]);
|
|
219
|
+
v.push(opens[i] ?? null);
|
|
220
|
+
}
|
|
221
|
+
t.push(keys[i] + barMs);
|
|
222
|
+
v.push(closes[i] ?? null);
|
|
223
|
+
}
|
|
224
|
+
return TimeSeries.fromColumns({
|
|
225
|
+
name: out.name,
|
|
226
|
+
schema: [
|
|
227
|
+
{ name: keyName, kind: 'time' },
|
|
228
|
+
{ name: columns.close, kind: 'number' },
|
|
229
|
+
],
|
|
230
|
+
columns: { [keyName]: t, [columns.close]: v },
|
|
231
|
+
});
|
|
232
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { STUDIES } from '@pond-ts/financial/catalog';
|
|
2
|
+
import { type Def, type OpContext, type OpResult } 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 declare const BAND_OUTPUTS: readonly ["Middle", "Upper", "Lower"];
|
|
29
|
+
/** A descriptor as the catalog declares it — structurally, so this module does
|
|
30
|
+
* not depend on the catalog's exported type names. */
|
|
31
|
+
type Descriptor = (typeof STUDIES)[number];
|
|
32
|
+
/**
|
|
33
|
+
* The raw bar columns a study needs beyond its target's own column.
|
|
34
|
+
*
|
|
35
|
+
* Empty for a single-`column` study, which reads whatever it is a study OF —
|
|
36
|
+
* that is what makes an SMA of an SMA compose. A multi-input study is not "of a
|
|
37
|
+
* column" but "of a SERIES": an ATR reads high, low and close directly, so its
|
|
38
|
+
* inputs are the roles' own defaults and its target only decides which row it
|
|
39
|
+
* lands in.
|
|
40
|
+
*/
|
|
41
|
+
export declare function studyNeedsColumns(d: Descriptor): string[];
|
|
42
|
+
/**
|
|
43
|
+
* Whether a study may draw on its source's axis — pond's rule, and the reason
|
|
44
|
+
* the `unit` field was worth asking for: **only `'inherit'` may share.**
|
|
45
|
+
*
|
|
46
|
+
* Read off the CATALOG's unit rather than the registry's, because the registry
|
|
47
|
+
* holds the translated display unit and `delta` deliberately translates to
|
|
48
|
+
* `'inherit'` there. An RSI on the vol axis is the failure this prevents: it is
|
|
49
|
+
* bounded 0..100 against a vol reading ~20, so sharing stretches the axis five
|
|
50
|
+
* times and squashes the series the study was meant to explain.
|
|
51
|
+
*/
|
|
52
|
+
export declare const sharesSourceAxis: (d: Descriptor) => boolean;
|
|
53
|
+
/** How one declared output should be drawn. `'line'` unless the overlay says
|
|
54
|
+
* otherwise — see {@link OUTPUT_MARKS}. */
|
|
55
|
+
export declare function outputMark(op: string, suffix: string): 'line' | 'bar';
|
|
56
|
+
/**
|
|
57
|
+
* True if the outputs are a band **Tidal's `band` style can actually read**.
|
|
58
|
+
*
|
|
59
|
+
* Keyed on the output IDS, not on `family`: `family: 'bands'` is a MENU
|
|
60
|
+
* grouping, and reading it as a render instruction gets two cases wrong in
|
|
61
|
+
* opposite directions — `bollingerBandwidth` and `bollingerPercentB` are
|
|
62
|
+
* `'bands'` and are single-output oscillators, while `ichimoku`'s cloud is
|
|
63
|
+
* `'trend'`. Declaration order does not matter: `donchian` declares
|
|
64
|
+
* Upper/Lower/Middle where the rest declare Middle/Upper/Lower. SIX studies
|
|
65
|
+
* match — not the eight in `family: 'bands'`, for the reason below.
|
|
66
|
+
*
|
|
67
|
+
* The test is the EXACT {@link BAND_OUTPUTS} set, not "has an Upper and a
|
|
68
|
+
* Lower", because `bandColumns` reads all three suffixes off the spec id and a
|
|
69
|
+
* missing one names a column that does not exist. Two shapes in the corpus
|
|
70
|
+
* would otherwise qualify and then fail to draw:
|
|
71
|
+
*
|
|
72
|
+
* - `rainbowOscillator` declares `['', 'Upper', 'Lower']` — its main output IS
|
|
73
|
+
* the id, so there is no `…Middle`. It is excluded today only by its enum
|
|
74
|
+
* param, which means TDL-STUDYENUM would have made it adoptable and
|
|
75
|
+
* `opIsBand` would have rendered it as a band with an empty wash.
|
|
76
|
+
* - `atrBands` and `primeNumberBands` declare `['Upper', 'Lower']` with no
|
|
77
|
+
* centre at all. A two-output band is a real mark Tidal cannot draw yet.
|
|
78
|
+
*
|
|
79
|
+
* Both are TDL-STUDYDRAW's problem, and both should be excluded by the RULE
|
|
80
|
+
* rather than by a filter clause that happens to catch them.
|
|
81
|
+
*
|
|
82
|
+
* F-charts-26 asks for this to be declared rather than inferred.
|
|
83
|
+
*/
|
|
84
|
+
export declare const isBandShape: (d: Descriptor) => boolean;
|
|
85
|
+
/**
|
|
86
|
+
* Whether a descriptor can be adopted as-is, today.
|
|
87
|
+
*
|
|
88
|
+
* Deliberately narrow. Each clause is a seam Tidal has not built yet, and the
|
|
89
|
+
* roadmap task that builds it — a study that reaches the registry reaches the
|
|
90
|
+
* picker, so "offered but wrong" is worse than "not offered".
|
|
91
|
+
*/
|
|
92
|
+
export declare function adoptable(d: Descriptor): boolean;
|
|
93
|
+
/** The studies adopted into the registry, in catalog order. */
|
|
94
|
+
export declare const ADOPTED_STUDIES: readonly Descriptor[];
|
|
95
|
+
/**
|
|
96
|
+
* Names of **adopted** studies that must not share their source's axis, so a
|
|
97
|
+
* consumer can ask without holding the catalog.
|
|
98
|
+
*
|
|
99
|
+
* Built from {@link ADOPTED_STUDIES}, not from the whole corpus: a hand-declared
|
|
100
|
+
* op must answer from the REGISTRY, which is Tidal's own declaration and
|
|
101
|
+
* outranks the catalog for a name Tidal owns. Scoping it here is what keeps
|
|
102
|
+
* that precedence right — over the whole corpus, a future hand-declared op
|
|
103
|
+
* sharing a catalog study's name would silently take the catalog's answer.
|
|
104
|
+
*/
|
|
105
|
+
export declare const OWN_AXIS_STUDIES: ReadonlySet<string>;
|
|
106
|
+
/**
|
|
107
|
+
* A generic `run` for any single-column study.
|
|
108
|
+
*
|
|
109
|
+
* Replaces the per-op adapters (`corpusStudy`, `bollingerRun`), which were each
|
|
110
|
+
* hardwired to one param name, one input and one output shape. This one reads
|
|
111
|
+
* the shape off the descriptor: the declared params go through as options, the
|
|
112
|
+
* single input binds by its declared role, and `naming.kind` decides whether
|
|
113
|
+
* the corpus is asked for one named column or a prefixed family.
|
|
114
|
+
*/
|
|
115
|
+
export declare function catalogRun(d: Descriptor): (ctx: OpContext) => OpResult;
|
|
116
|
+
/**
|
|
117
|
+
* One catalog descriptor as a registry definition.
|
|
118
|
+
*
|
|
119
|
+
* `lookback` is deliberately OMITTED. The catalog does not carry it, it is
|
|
120
|
+
* per-study knowledge (`sma` is `period - 1`; an IIR has no exact finite answer
|
|
121
|
+
* and the multiplier is a claim about acceptable error), and the registry
|
|
122
|
+
* documents omitted as **unknown, not zero** — `requiredHistory` reports the
|
|
123
|
+
* gap rather than handing back a number a caller would slice against. So
|
|
124
|
+
* omitting costs us the history-slicing win on these studies and cannot make a
|
|
125
|
+
* warm-up hole read as data. Inventing a multiplier for 26 studies would be the
|
|
126
|
+
* opposite trade. Asked for in F-charts-26.
|
|
127
|
+
*/
|
|
128
|
+
export declare function catalogOp(d: Descriptor): Def;
|
|
129
|
+
export {};
|