@tidal-ts/core 0.7.0 → 0.10.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/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @tidal-ts/core
2
+
3
+ The part of [tidal-ts](https://github.com/tidal-app/tidal-ts) with no drawing in
4
+ it: the technical studies, the volatility data layout, bar windows, the adapter
5
+ for a column-by-column wire format, trading sessions and time zones. Built on
6
+ [pond-ts](https://pond-ts.org).
7
+
8
+ **Pre-1.0: pin an exact version.** Every `@tidal-ts/*` package ships on one
9
+ version number.
10
+
11
+ - [Docs](https://tidal-app.github.io/tidal-ts/docs/packages/core/)
12
+ - [Study catalog](https://tidal-app.github.io/tidal-ts/docs/studies/): every study with a live chart, its
13
+ settings, and how traders use it
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install --save-exact @tidal-ts/core @pond-ts/process@0.73.0
19
+ npm install pond-ts@~0.73.0 @pond-ts/financial@~0.73.0
20
+ ```
21
+
22
+ The pond packages are peer dependencies: install them once, on the version
23
+ this release names in its `peerDependencies`, so there is only one copy of
24
+ pond-ts in your bundle.
25
+
26
+ ## A study is data
27
+
28
+ ```ts
29
+ import { applyDerived, deriveId, type DeriveSpec } from '@tidal-ts/core';
30
+
31
+ const rsi: DeriveSpec = { op: 'rsi', inputs: ['close'], params: { period: 14 } };
32
+
33
+ // Compute it onto a pond TimeSeries of bars; the values land in this column.
34
+ const withRsi = applyDerived(series, [rsi]);
35
+ const column = deriveId(rsi);
36
+ ```
37
+
38
+ `studyCatalog()` lists every study on offer, and `opParams`, `opOutputs` and
39
+ `studyLevels` describe each one's settings, outputs and guide lines.
40
+
41
+ To draw it, see [`@tidal-ts/chart`](https://www.npmjs.com/package/@tidal-ts/chart).
42
+
43
+ MIT.
@@ -48,7 +48,7 @@ export interface PondAppend {
48
48
  }
49
49
  /**
50
50
  * Adapt a decoded {@link PondSnapshot} into a pond `TimeSeries`. Drops string
51
- * columns (partition metadata), coerces gaps to null, and `sort: true` since
51
+ * columns (partition metadata), coerces gaps to null, and `ordering: 'reorder'` since
52
52
  * wire rows aren't guaranteed ascending.
53
53
  */
54
54
  export declare function snapshotToTimeSeries(snap: PondSnapshot): TimeSeries<import("pond-ts").SeriesSchema>;
package/dist/columnar.js CHANGED
@@ -25,7 +25,7 @@ function assertAligned(name, count, columns, schema) {
25
25
  }
26
26
  /**
27
27
  * Adapt a decoded {@link PondSnapshot} into a pond `TimeSeries`. Drops string
28
- * columns (partition metadata), coerces gaps to null, and `sort: true` since
28
+ * columns (partition metadata), coerces gaps to null, and `ordering: 'reorder'` since
29
29
  * wire rows aren't guaranteed ascending.
30
30
  */
31
31
  export function snapshotToTimeSeries(snap) {
@@ -42,7 +42,7 @@ export function snapshotToTimeSeries(snap) {
42
42
  for (const c of cols) {
43
43
  columns[c.name] = (snap.columns[c.name] ?? []).map((v) => (typeof v === 'number' ? v : null));
44
44
  }
45
- return TimeSeries.fromColumns({ name: snap.name, schema, columns, sort: true });
45
+ return TimeSeries.fromColumns({ name: snap.name, schema, columns, ordering: 'reorder' });
46
46
  }
47
47
  /**
48
48
  * Transpose a columnar {@link PondAppend} into row tuples in the numeric-schema's
package/dist/derive.d.ts CHANGED
@@ -595,6 +595,29 @@ export declare function studyPick(spec: DeriveSpec): StudyPick | undefined;
595
595
  /** `spec` reading `output` of its multi-output source instead — the same spec
596
596
  * when it has none ({@link studyPick}). A bare nested source becomes a pick. */
597
597
  export declare function withStudyOutput(spec: DeriveSpec, output: string): DeriveSpec;
598
+ /**
599
+ * The pick at the BOTTOM of a study chain — the multi-output source a chain
600
+ * of single-output studies ultimately reads, and which of its outputs.
601
+ *
602
+ * {@link studyPick} answers for a study OF a multi-output study; a study of
603
+ * THAT study nests it, so its pick is one level down, and so on. A study
604
+ * **fanned** over several outputs (`SeriesConfig.fan`) is one chain per output,
605
+ * identical except at this pick, which is why this is the one place the
606
+ * outputs are read from. Follows the first input that leads to a pick; a pair
607
+ * stops the walk, as it does for `studyPick`. `undefined` when the chain reads
608
+ * no multi-output source.
609
+ */
610
+ export declare function fanPick(spec: DeriveSpec): StudyPick | undefined;
611
+ /**
612
+ * `spec` with the pick at the bottom of its chain ({@link fanPick}) reading
613
+ * `output` instead — the same chain, run on another output of its source. The
614
+ * spec unchanged when it reads no multi-output source.
615
+ *
616
+ * This is how a fanned study names each of its lines: `sma(Upper)` and
617
+ * `sma(Lower)` are the same SMA with the pick swapped, so a retune of the SMA
618
+ * moves every line together without a list of specs to keep in step.
619
+ */
620
+ export declare function withFanOutput(spec: DeriveSpec, output: string): DeriveSpec;
598
621
  /**
599
622
  * What a study of `source` reads: the source itself, or — for a multi-output
600
623
  * source — its {@link primaryOutput}, PICKED. Never a bare nested multi-output
package/dist/derive.js CHANGED
@@ -834,6 +834,58 @@ export function withStudyOutput(spec, output) {
834
834
  inputs[pick.index] = { from: pick.from, output };
835
835
  return { ...spec, inputs };
836
836
  }
837
+ /**
838
+ * The pick at the BOTTOM of a study chain — the multi-output source a chain
839
+ * of single-output studies ultimately reads, and which of its outputs.
840
+ *
841
+ * {@link studyPick} answers for a study OF a multi-output study; a study of
842
+ * THAT study nests it, so its pick is one level down, and so on. A study
843
+ * **fanned** over several outputs (`SeriesConfig.fan`) is one chain per output,
844
+ * identical except at this pick, which is why this is the one place the
845
+ * outputs are read from. Follows the first input that leads to a pick; a pair
846
+ * stops the walk, as it does for `studyPick`. `undefined` when the chain reads
847
+ * no multi-output source.
848
+ */
849
+ export function fanPick(spec) {
850
+ if (!isSpecLike(spec) || isPairOp(spec.op))
851
+ return undefined;
852
+ const own = studyPick(spec);
853
+ if (own)
854
+ return own;
855
+ for (const i of spec.inputs ?? []) {
856
+ if (isSpecLike(i) && !isPickedInput(i)) {
857
+ const deep = fanPick(i);
858
+ if (deep)
859
+ return deep;
860
+ }
861
+ }
862
+ return undefined;
863
+ }
864
+ /**
865
+ * `spec` with the pick at the bottom of its chain ({@link fanPick}) reading
866
+ * `output` instead — the same chain, run on another output of its source. The
867
+ * spec unchanged when it reads no multi-output source.
868
+ *
869
+ * This is how a fanned study names each of its lines: `sma(Upper)` and
870
+ * `sma(Lower)` are the same SMA with the pick swapped, so a retune of the SMA
871
+ * moves every line together without a list of specs to keep in step.
872
+ */
873
+ export function withFanOutput(spec, output) {
874
+ if (!isSpecLike(spec) || isPairOp(spec.op))
875
+ return spec;
876
+ if (studyPick(spec))
877
+ return withStudyOutput(spec, output);
878
+ const inputs = spec.inputs ?? [];
879
+ for (let index = 0; index < inputs.length; index++) {
880
+ const i = inputs[index];
881
+ if (isSpecLike(i) && !isPickedInput(i) && fanPick(i)) {
882
+ const next = [...inputs];
883
+ next[index] = withFanOutput(i, output);
884
+ return { ...spec, inputs: next };
885
+ }
886
+ }
887
+ return spec;
888
+ }
837
889
  /**
838
890
  * What a study of `source` reads: the source itself, or — for a multi-output
839
891
  * source — its {@link primaryOutput}, PICKED. Never a bare nested multi-output
package/dist/fixture.d.ts CHANGED
@@ -48,7 +48,7 @@ export type PriceSeries = TimeSeries<typeof PRICE_SCHEMA>;
48
48
  /** Build a {@link PriceSeries} from raw OHLCV rows. The one place the price
49
49
  * `TimeSeries` is constructed — fixture, HTTP source, and the real ticker-history
50
50
  * adapter all funnel through here. Uses the **columnar** ingress (gap-tolerant,
51
- * `sort:true`) so a non-finite cell reads as a gap rather than being rejected —
51
+ * `ordering: 'reorder'`) so a non-finite cell reads as a gap rather than being rejected —
52
52
  * real data can carry the occasional missing OHLCV cell. */
53
53
  export declare function buildPriceSeries(name: string, rows: readonly PriceRow[]): PriceSeries;
54
54
  /**
package/dist/fixture.js CHANGED
@@ -59,7 +59,7 @@ export const PRICE_SCHEMA = [
59
59
  /** Build a {@link PriceSeries} from raw OHLCV rows. The one place the price
60
60
  * `TimeSeries` is constructed — fixture, HTTP source, and the real ticker-history
61
61
  * adapter all funnel through here. Uses the **columnar** ingress (gap-tolerant,
62
- * `sort:true`) so a non-finite cell reads as a gap rather than being rejected —
62
+ * `ordering: 'reorder'`) so a non-finite cell reads as a gap rather than being rejected —
63
63
  * real data can carry the occasional missing OHLCV cell. */
64
64
  export function buildPriceSeries(name, rows) {
65
65
  return TimeSeries.fromColumns({
@@ -73,7 +73,7 @@ export function buildPriceSeries(name, rows) {
73
73
  close: rows.map((r) => r[4]),
74
74
  volume: rows.map((r) => r[5]),
75
75
  },
76
- sort: true,
76
+ ordering: 'reorder',
77
77
  });
78
78
  }
79
79
  /**
package/dist/index.d.ts CHANGED
@@ -2,12 +2,12 @@ export { BAR_INTERVAL_MS, type Instrument, type InstrumentKind, type BarInterval
2
2
  export { generatePriceSeries, buildPriceSeries, DEMO_INSTRUMENTS, PRICE_SCHEMA, type PriceSeriesOptions, type PriceSeries, type PriceRow, } from './fixture.js';
3
3
  export { generateVolSeries, buildVolSeries, VOL_SCHEMA, VOL_TENORS, DEFAULT_VOL_TENOR, impliedCol, hvCol, rvCol, rvCenCol, skewCol, type VolSeries, type VolColumns, type VolTenor, type VolSeriesOptions, } from './vol.js';
4
4
  export { aggregateColumn, floorToWindow, liveWindowMs, ohlcWindow, sessionGrid, WINDOW_MS, WINDOW_LADDER, MIN_BAR_PX, autoBarWindow, type BarReducer, type SeriesWindow, } from './aggregate.js';
5
- export { applyDerived, applyDerivedReport, COMPARE_PREFIX, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, withStudyOutput, type StudyPick, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, type OpParam, usesCompare, type DeriveSkip, type PairPart, type PartStudy, type StudyOption, type NumericColumnReader, DEFAULT_PERIOD, type DeriveInput, type PickedDeriveOutput, type DeriveSpec, type DeriveOp, type TidalOp, type PairOp, } from './derive.js';
5
+ export { applyDerived, applyDerivedReport, COMPARE_PREFIX, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, fanPick, withFanOutput, withStudyOutput, type StudyPick, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, type OpParam, usesCompare, type DeriveSkip, type PairPart, type PartStudy, type StudyOption, type NumericColumnReader, DEFAULT_PERIOD, type DeriveInput, type PickedDeriveOutput, type DeriveSpec, type DeriveOp, type TidalOp, type PairOp, } from './derive.js';
6
6
  export { joinUnderPrefix } from './join.js';
7
7
  export { columnExtent } from './extent.js';
8
8
  export { snapshotToTimeSeries, appendToRows, type PondSnapshot, type PondAppend, type PondValue, type WireColumnSpec, } from './columnar.js';
9
9
  export { exactSessionSegments, inferBarMs, sessionOpenLine, sessionSegments, shiftKeys, sliceBySegments, type Segment, type SessionSegmentOptions, } from './sessions.js';
10
10
  export { monthlyExpirations, thirdFriday } from './expirations.js';
11
- export { holdVolAcrossGrid } from './regrid.js';
11
+ export { holdAcrossGrid, holdVolAcrossGrid, type HeldSchema } from './regrid.js';
12
12
  export { ADOPTED_STUDIES, adoptable, isBandShape, outputMark, studyLevels, studyNeedsColumns, } from './studyCatalog.js';
13
13
  export { DATA_TIME_ZONE, LOCAL_ZONE, TIME_ZONE_CHOICES, resolveTimeZone, timeZoneLabel, type TimeZoneChoice, } from './timeZone.js';
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@ export { BAR_INTERVAL_MS, } from './types.js';
2
2
  export { generatePriceSeries, buildPriceSeries, DEMO_INSTRUMENTS, PRICE_SCHEMA, } from './fixture.js';
3
3
  export { generateVolSeries, buildVolSeries, VOL_SCHEMA, VOL_TENORS, DEFAULT_VOL_TENOR, impliedCol, hvCol, rvCol, rvCenCol, skewCol, } from './vol.js';
4
4
  export { aggregateColumn, floorToWindow, liveWindowMs, ohlcWindow, sessionGrid, WINDOW_MS, WINDOW_LADDER, MIN_BAR_PX, autoBarWindow, } from './aggregate.js';
5
- export { applyDerived, applyDerivedReport, COMPARE_PREFIX, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, withStudyOutput, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, usesCompare, DEFAULT_PERIOD, } from './derive.js';
5
+ export { applyDerived, applyDerivedReport, COMPARE_PREFIX, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, fanPick, withFanOutput, withStudyOutput, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, usesCompare, DEFAULT_PERIOD, } from './derive.js';
6
6
  export { joinUnderPrefix } from './join.js';
7
7
  export { columnExtent } from './extent.js';
8
8
  export { snapshotToTimeSeries, appendToRows, } from './columnar.js';
9
9
  export { exactSessionSegments, inferBarMs, sessionOpenLine, sessionSegments, shiftKeys, sliceBySegments, } from './sessions.js';
10
10
  export { monthlyExpirations, thirdFriday } from './expirations.js';
11
- export { holdVolAcrossGrid } from './regrid.js';
11
+ export { holdAcrossGrid, holdVolAcrossGrid } from './regrid.js';
12
12
  // The corpus adoption (TDL-STUDYCAT). `ADOPTED_STUDIES` is exported so the
13
13
  // count is assertable and a widening of `adoptable` is a visible edit.
14
14
  export { ADOPTED_STUDIES, adoptable, isBandShape, outputMark, studyLevels, studyNeedsColumns, } from './studyCatalog.js';
package/dist/regrid.d.ts CHANGED
@@ -1,4 +1,63 @@
1
+ import { TimeSeries, type ColumnDef, type SeriesSchema, type ValueColumn, type ValueColumnsForSchema } from 'pond-ts';
1
2
  import { type VolSeries } from './vol.js';
3
+ type OptionalColumn<C extends ValueColumn> = C extends ColumnDef<infer N, infer K> ? ColumnDef<N, K> & {
4
+ readonly required: false;
5
+ } : never;
6
+ type OptionalColumns<Cs extends readonly ValueColumn[]> = number extends Cs['length'] ? OptionalColumn<Cs[number]>[] : Cs extends readonly [infer H, ...infer T] ? H extends ValueColumn ? T extends readonly ValueColumn[] ? [OptionalColumn<H>, ...OptionalColumns<T>] : [] : [] : [];
7
+ /**
8
+ * The schema {@link holdAcrossGrid} returns: the input's, with every value
9
+ * column optional. A hold makes gaps by design (a day with no row), so a column
10
+ * declared required would be lying, and pond's row and JSON inputs would refuse
11
+ * the series. pond's own `join` and `align` mark their output columns optional
12
+ * for the same reason.
13
+ */
14
+ export type HeldSchema<S extends SeriesSchema> = readonly [
15
+ S[0],
16
+ ...OptionalColumns<ValueColumnsForSchema<S>>
17
+ ];
18
+ /**
19
+ * Re-key `coarse` onto `grid`, holding each row across the grid points inside
20
+ * its own bar. **Every column comes through**, whatever the schema: the vol
21
+ * curve's, a joined comparison's (`cmp_*`), a study's.
22
+ *
23
+ * This is the hold to use on a series that has already been **folded** — a
24
+ * study, or a compare join, computed at the coarse series' own grain. Fold
25
+ * first, then hold, never the other way round: a 20-bar average of a daily
26
+ * series held across one-minute bars is a 20-*minute* average of a step, and
27
+ * reads that day's raw value rather than the average. A join is the same
28
+ * shape: joining two daily series is ~250 rows a year, and joining them after
29
+ * the hold is ~100,000.
30
+ *
31
+ * A row holds over `[key, key + grainMs)`, and only until the next row starts.
32
+ * So a grid point takes the **last row at or before it**, provided it is still
33
+ * inside that row's bar; past the bar it is a gap. That makes three promises:
34
+ *
35
+ * - **A grid point never reads a bar that starts after it**, whatever the
36
+ * coarse bars' phase. (Flooring both sides to a multiple of `grainMs` would
37
+ * hand 14:10 the hourly bar that opens at 14:30.) It reads a bar from the
38
+ * bar's start, so a daily value keyed at midnight is visible from that day's
39
+ * open, as it is on a daily chart.
40
+ * - **A gap stays a gap.** A day the coarse series has no row for is `NaN`
41
+ * (`undefined` for a string column) across that day, not the day before's
42
+ * value carried on. "Nothing published for this session" is not "the same
43
+ * as yesterday".
44
+ * - **A restatement wins.** Rows sharing a key: the later one holds.
45
+ *
46
+ * It assumes the coarse keys mark the **start** of each bar, which is how a
47
+ * daily series keyed at midnight reads. `grainMs` may be larger than a bar (a
48
+ * calendar month, a day that is 23 hours long): the next row still ends the
49
+ * hold. `Infinity` makes it a plain as-of hold, with no gaps.
50
+ *
51
+ * The result has exactly one row per grid point: an empty grid gives an empty
52
+ * series, and an empty coarse series gives all gaps. Value columns come back
53
+ * optional ({@link HeldSchema}).
54
+ *
55
+ * `grid` must be ascending — a series' own keys are. The coarse series must be
56
+ * keyed by `time`, and its value columns must be `number` or `string` (what
57
+ * `TimeSeries.fromColumns` can take back). Anything else throws, naming the
58
+ * column, rather than dropping it.
59
+ */
60
+ export declare function holdAcrossGrid<S extends SeriesSchema>(coarse: TimeSeries<S>, grid: ArrayLike<number>, grainMs: number): TimeSeries<HeldSchema<S>>;
2
61
  /**
3
62
  * Re-key `coarse` onto `times`, holding each source row across every target
4
63
  * timestamp that falls on its day.
@@ -18,5 +77,10 @@ import { type VolSeries } from './vol.js';
18
77
  * `volGrains: ['30m']` answers a `1d` request with `'30m'` via its
19
78
  * last-resort branch, and this would then re-key a 30-minute series onto a daily
20
79
  * grid, silently keeping each day's LAST intraday value.
80
+ *
81
+ * @deprecated Use {@link holdAcrossGrid}, which keeps every column. This one
82
+ * emits `VOL_SCHEMA` columns only, so holding a folded series with it silently
83
+ * drops each joined comparison column and each study.
21
84
  */
22
85
  export declare function holdVolAcrossGrid(coarse: VolSeries, times: readonly number[], name?: string): VolSeries;
86
+ export {};
package/dist/regrid.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { TimeSeries, } from 'pond-ts';
1
2
  import { buildVolSeries, VOL_SCHEMA } from './vol.js';
2
3
  /**
3
4
  * Hold a **coarse** vol series at a **finer** grid — the daily ATM curve drawn on
@@ -27,6 +28,113 @@ import { buildVolSeries, VOL_SCHEMA } from './vol.js';
27
28
  const DAY_MS = 24 * 60 * 60 * 1000;
28
29
  /** The UTC midnight a timestamp belongs to — the daily series' own key. */
29
30
  const dayOf = (t) => Math.floor(t / DAY_MS) * DAY_MS;
31
+ /**
32
+ * Re-key `coarse` onto `grid`, holding each row across the grid points inside
33
+ * its own bar. **Every column comes through**, whatever the schema: the vol
34
+ * curve's, a joined comparison's (`cmp_*`), a study's.
35
+ *
36
+ * This is the hold to use on a series that has already been **folded** — a
37
+ * study, or a compare join, computed at the coarse series' own grain. Fold
38
+ * first, then hold, never the other way round: a 20-bar average of a daily
39
+ * series held across one-minute bars is a 20-*minute* average of a step, and
40
+ * reads that day's raw value rather than the average. A join is the same
41
+ * shape: joining two daily series is ~250 rows a year, and joining them after
42
+ * the hold is ~100,000.
43
+ *
44
+ * A row holds over `[key, key + grainMs)`, and only until the next row starts.
45
+ * So a grid point takes the **last row at or before it**, provided it is still
46
+ * inside that row's bar; past the bar it is a gap. That makes three promises:
47
+ *
48
+ * - **A grid point never reads a bar that starts after it**, whatever the
49
+ * coarse bars' phase. (Flooring both sides to a multiple of `grainMs` would
50
+ * hand 14:10 the hourly bar that opens at 14:30.) It reads a bar from the
51
+ * bar's start, so a daily value keyed at midnight is visible from that day's
52
+ * open, as it is on a daily chart.
53
+ * - **A gap stays a gap.** A day the coarse series has no row for is `NaN`
54
+ * (`undefined` for a string column) across that day, not the day before's
55
+ * value carried on. "Nothing published for this session" is not "the same
56
+ * as yesterday".
57
+ * - **A restatement wins.** Rows sharing a key: the later one holds.
58
+ *
59
+ * It assumes the coarse keys mark the **start** of each bar, which is how a
60
+ * daily series keyed at midnight reads. `grainMs` may be larger than a bar (a
61
+ * calendar month, a day that is 23 hours long): the next row still ends the
62
+ * hold. `Infinity` makes it a plain as-of hold, with no gaps.
63
+ *
64
+ * The result has exactly one row per grid point: an empty grid gives an empty
65
+ * series, and an empty coarse series gives all gaps. Value columns come back
66
+ * optional ({@link HeldSchema}).
67
+ *
68
+ * `grid` must be ascending — a series' own keys are. The coarse series must be
69
+ * keyed by `time`, and its value columns must be `number` or `string` (what
70
+ * `TimeSeries.fromColumns` can take back). Anything else throws, naming the
71
+ * column, rather than dropping it.
72
+ */
73
+ export function holdAcrossGrid(coarse, grid, grainMs) {
74
+ const [keySpec, ...valueSpecs] = coarse.schema;
75
+ if (keySpec.kind !== 'time')
76
+ throw new Error(`holdAcrossGrid: "${coarse.name}" is keyed by ${keySpec.kind}; only a time key can be held`);
77
+ if (!(grainMs > 0))
78
+ throw new Error(`holdAcrossGrid: grainMs must be a positive number of ms, not ${grainMs}`);
79
+ // One walk of both key buffers: for each grid point, the source row it holds
80
+ // (`-1` for a gap). Shared by every column below, so the per-column work is a
81
+ // plain gather. `coarse.length`, not the buffer's: a key buffer may be longer
82
+ // than the series it belongs to.
83
+ const keys = coarse.keyColumn().begin;
84
+ const n = coarse.length;
85
+ const rows = new Int32Array(grid.length);
86
+ let j = -1;
87
+ let prev = -Infinity;
88
+ for (let i = 0; i < grid.length; i += 1) {
89
+ const t = grid[i];
90
+ if (!(t >= prev))
91
+ throw new Error(`holdAcrossGrid: the grid must be ascending; point ${i} (${t}) follows ${prev}`);
92
+ prev = t;
93
+ while (j + 1 < n && keys[j + 1] <= t)
94
+ j += 1;
95
+ rows[i] = j >= 0 && t < keys[j] + grainMs ? j : -1;
96
+ }
97
+ const columns = {
98
+ [keySpec.name]: Float64Array.from(grid),
99
+ };
100
+ for (const spec of valueSpecs) {
101
+ const src = coarse.column(spec.name);
102
+ if (spec.kind === 'number') {
103
+ // Through `at`, which reads a missing cell as `undefined`. Before pond
104
+ // 0.73 the raw buffer did not mark one (a join's unmatched row read 0);
105
+ // since 0.73 `toFloat64Array()` holds `NaN` there too, so either works.
106
+ // The coarse side is the short one, so this is a few hundred reads.
107
+ const values = new Float64Array(n);
108
+ for (let r = 0; r < n; r += 1) {
109
+ const v = src.at(r);
110
+ values[r] = typeof v === 'number' ? v : NaN;
111
+ }
112
+ const out = new Float64Array(grid.length);
113
+ for (let i = 0; i < grid.length; i += 1) {
114
+ const r = rows[i];
115
+ out[i] = r < 0 ? NaN : values[r];
116
+ }
117
+ columns[spec.name] = out;
118
+ }
119
+ else if (spec.kind === 'string') {
120
+ const out = new Array(grid.length);
121
+ for (let i = 0; i < grid.length; i += 1) {
122
+ const r = rows[i];
123
+ out[i] = r < 0 ? undefined : src.at(r);
124
+ }
125
+ columns[spec.name] = out;
126
+ }
127
+ else {
128
+ throw new Error(`holdAcrossGrid: column "${spec.name}" of "${coarse.name}" is ${spec.kind}; only number and string columns can be held`);
129
+ }
130
+ }
131
+ const schema = [keySpec, ...valueSpecs.map((c) => ({ ...c, required: false }))];
132
+ return TimeSeries.fromColumns({
133
+ name: coarse.name,
134
+ schema: schema,
135
+ columns: columns,
136
+ });
137
+ }
30
138
  /**
31
139
  * Re-key `coarse` onto `times`, holding each source row across every target
32
140
  * timestamp that falls on its day.
@@ -46,6 +154,10 @@ const dayOf = (t) => Math.floor(t / DAY_MS) * DAY_MS;
46
154
  * `volGrains: ['30m']` answers a `1d` request with `'30m'` via its
47
155
  * last-resort branch, and this would then re-key a 30-minute series onto a daily
48
156
  * grid, silently keeping each day's LAST intraday value.
157
+ *
158
+ * @deprecated Use {@link holdAcrossGrid}, which keeps every column. This one
159
+ * emits `VOL_SCHEMA` columns only, so holding a folded series with it silently
160
+ * drops each joined comparison column and each study.
49
161
  */
50
162
  export function holdVolAcrossGrid(coarse, times, name = 'vol') {
51
163
  if (times.length === 0 || coarse.length === 0)
@@ -105,26 +105,29 @@ export declare function inferBarMs(times: readonly number[]): number | undefined
105
105
  *
106
106
  * Shifting the KEY rather than fixing it at the source is deliberate: a candle
107
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.
108
+ * different x for the same row. A line, area or band layer takes charts'
109
+ * `xOffset` for this (charts 0.73) and needs no copy; this is for a layer that
110
+ * has no such prop — `<BarChart>`, whose point-keyed histogram must sit under the
111
+ * shifted lines it explains.
112
+ *
113
+ * pond's `offsetTime` does the move: one pass over the key, value columns shared
114
+ * (0.26 ms on 97k rows × 118 columns, by pond's measurement — the rebuild this
115
+ * used to do cost 235–442 ms on the same shape).
114
116
  */
115
117
  export declare function shiftKeys(series: TimeSeries<SeriesSchema>, ms: number): TimeSeries<SeriesSchema>;
116
118
  /**
117
119
  * The series cut into one sub-series per live segment — `[start, end)` on the
118
120
  * time key, empty segments dropped.
119
121
  *
120
- * For the layer pond gives no `sessionBreaks` of its own — `<AreaChart>`
121
- * (`<LineChart>` has always had it; `<BandChart>` gained it in charts 0.70.0,
122
- * which retired this function's other caller). A fill drawn across a
123
- * collapsed overnight gap bridges seventeen hours of closed market in one
124
- * confident sweep and contradicts the line drawn over it; one layer per segment
125
- * ends the fill at the close and restarts it at the open, which is what that
126
- * line already does. The cost is `segments.length` layers instead of one, so a
127
- * caller asks only when the axis actually collapses.
122
+ * @deprecated No longer needed to break a fill at a session seam: every charts
123
+ * layer that fills or strokes takes `sessionBreaks` since charts 0.73
124
+ * (`<AreaChart>` was the last), so `TimeSeriesChart` no longer calls this. Kept
125
+ * for a host that slices a series per session for some other reason.
126
+ *
127
+ * It existed for `<AreaChart>` before it had `sessionBreaks`: a fill drawn
128
+ * across a collapsed overnight gap bridges seventeen hours of closed market in
129
+ * one confident sweep, and one layer per segment ended it at the close and
130
+ * restarted it at the open, as the line over it did.
128
131
  *
129
132
  * Pond does the cutting — `bisect` finds each edge in O(log n) on the packed key
130
133
  * buffer and `slice` is positional and half-open — so nothing here is
package/dist/sessions.js CHANGED
@@ -153,43 +153,37 @@ function median(values) {
153
153
  *
154
154
  * Shifting the KEY rather than fixing it at the source is deliberate: a candle
155
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.
156
+ * different x for the same row. A line, area or band layer takes charts'
157
+ * `xOffset` for this (charts 0.73) and needs no copy; this is for a layer that
158
+ * has no such prop — `<BarChart>`, whose point-keyed histogram must sit under the
159
+ * shifted lines it explains.
159
160
  *
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.
161
+ * pond's `offsetTime` does the move: one pass over the key, value columns shared
162
+ * (0.26 ms on 97k rows × 118 columns, by pond's measurement — the rebuild this
163
+ * used to do cost 235–442 ms on the same shape).
162
164
  */
163
165
  export function shiftKeys(series, ms) {
164
166
  if (ms === 0)
165
167
  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)
168
+ // Only a time key moves by a constant duration; anything else comes back as it
169
+ // is rather than failing in the render path.
170
+ if (series.schema[0]?.kind !== 'time')
171
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
- });
172
+ return series.offsetTime(ms);
180
173
  }
181
174
  /**
182
175
  * The series cut into one sub-series per live segment — `[start, end)` on the
183
176
  * time key, empty segments dropped.
184
177
  *
185
- * For the layer pond gives no `sessionBreaks` of its own — `<AreaChart>`
186
- * (`<LineChart>` has always had it; `<BandChart>` gained it in charts 0.70.0,
187
- * which retired this function's other caller). A fill drawn across a
188
- * collapsed overnight gap bridges seventeen hours of closed market in one
189
- * confident sweep and contradicts the line drawn over it; one layer per segment
190
- * ends the fill at the close and restarts it at the open, which is what that
191
- * line already does. The cost is `segments.length` layers instead of one, so a
192
- * caller asks only when the axis actually collapses.
178
+ * @deprecated No longer needed to break a fill at a session seam: every charts
179
+ * layer that fills or strokes takes `sessionBreaks` since charts 0.73
180
+ * (`<AreaChart>` was the last), so `TimeSeriesChart` no longer calls this. Kept
181
+ * for a host that slices a series per session for some other reason.
182
+ *
183
+ * It existed for `<AreaChart>` before it had `sessionBreaks`: a fill drawn
184
+ * across a collapsed overnight gap bridges seventeen hours of closed market in
185
+ * one confident sweep, and one layer per segment ended it at the close and
186
+ * restarted it at the open, as the line over it did.
193
187
  *
194
188
  * Pond does the cutting — `bisect` finds each edge in O(log n) on the packed key
195
189
  * buffer and `slice` is positional and half-open — so nothing here is
package/dist/vol.js CHANGED
@@ -173,7 +173,7 @@ export function buildVolSeries(name, columns) {
173
173
  name,
174
174
  schema: VOL_SCHEMA,
175
175
  columns: columns,
176
- sort: true,
176
+ ordering: 'reorder',
177
177
  });
178
178
  }
179
179
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/core",
3
- "version": "0.7.0",
3
+ "version": "0.10.0",
4
4
  "private": false,
5
5
  "description": "Financial time-series vocabulary on pond-ts: the study/derive seam, the vol schema, bar windows, the columnar adapter and session helpers.",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/tidal-app/tidal-ts.git",
10
10
  "directory": "packages/core"
11
11
  },
12
- "homepage": "https://github.com/tidal-app/tidal-ts#readme",
12
+ "homepage": "https://tidal-app.github.io/tidal-ts/docs/packages/core/",
13
13
  "type": "module",
14
14
  "main": "dist/index.js",
15
15
  "types": "dist/index.d.ts",
@@ -31,14 +31,14 @@
31
31
  "access": "public"
32
32
  },
33
33
  "peerDependencies": {
34
- "@pond-ts/financial": "^0.70.0",
35
- "@pond-ts/process": "0.70.0",
36
- "pond-ts": "^0.70.0"
34
+ "@pond-ts/financial": "^0.73.0",
35
+ "@pond-ts/process": "0.73.0",
36
+ "pond-ts": "^0.73.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@pond-ts/financial": "^0.70.0",
40
- "@pond-ts/process": "0.70.0",
41
- "pond-ts": "^0.70.0",
39
+ "@pond-ts/financial": "^0.73.0",
40
+ "@pond-ts/process": "0.73.0",
41
+ "pond-ts": "^0.73.0",
42
42
  "typescript": "^5.7.2",
43
43
  "vitest": "^2.1.8"
44
44
  },