tickwire 0.0.0-stage → 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.
Files changed (80) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +209 -2
  3. package/dist/backtest/backtest.d.ts +101 -0
  4. package/dist/backtest/backtest.js +200 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +179 -0
  7. package/dist/core/aggregate.d.ts +19 -0
  8. package/dist/core/aggregate.js +64 -0
  9. package/dist/core/clock.d.ts +6 -0
  10. package/dist/core/clock.js +18 -0
  11. package/dist/core/errors.d.ts +51 -0
  12. package/dist/core/errors.js +53 -0
  13. package/dist/core/http.d.ts +38 -0
  14. package/dist/core/http.js +119 -0
  15. package/dist/core/instrument.d.ts +14 -0
  16. package/dist/core/instrument.js +22 -0
  17. package/dist/core/provider.d.ts +47 -0
  18. package/dist/core/provider.js +1 -0
  19. package/dist/core/rate-limiter.d.ts +30 -0
  20. package/dist/core/rate-limiter.js +68 -0
  21. package/dist/core/stream.d.ts +90 -0
  22. package/dist/core/stream.js +224 -0
  23. package/dist/core/timeframe.d.ts +16 -0
  24. package/dist/core/timeframe.js +21 -0
  25. package/dist/core/types.d.ts +52 -0
  26. package/dist/core/types.js +1 -0
  27. package/dist/core/util.d.ts +8 -0
  28. package/dist/core/util.js +24 -0
  29. package/dist/index.d.ts +26 -0
  30. package/dist/index.js +22 -0
  31. package/dist/indicators/atr.d.ts +21 -0
  32. package/dist/indicators/atr.js +41 -0
  33. package/dist/indicators/bollinger.d.ts +22 -0
  34. package/dist/indicators/bollinger.js +42 -0
  35. package/dist/indicators/ema.d.ts +16 -0
  36. package/dist/indicators/ema.js +40 -0
  37. package/dist/indicators/index.d.ts +8 -0
  38. package/dist/indicators/index.js +8 -0
  39. package/dist/indicators/indicator.d.ts +15 -0
  40. package/dist/indicators/indicator.js +17 -0
  41. package/dist/indicators/macd.d.ts +31 -0
  42. package/dist/indicators/macd.js +48 -0
  43. package/dist/indicators/rsi.d.ts +17 -0
  44. package/dist/indicators/rsi.js +53 -0
  45. package/dist/indicators/sma.d.ts +14 -0
  46. package/dist/indicators/sma.js +43 -0
  47. package/dist/indicators/vwap.d.ts +25 -0
  48. package/dist/indicators/vwap.js +37 -0
  49. package/dist/providers/alpaca.d.ts +44 -0
  50. package/dist/providers/alpaca.js +227 -0
  51. package/dist/providers/binance.d.ts +31 -0
  52. package/dist/providers/binance.js +187 -0
  53. package/dist/providers/coinbase.d.ts +28 -0
  54. package/dist/providers/coinbase.js +179 -0
  55. package/dist/providers/create.d.ts +6 -0
  56. package/dist/providers/create.js +21 -0
  57. package/dist/providers/kraken.d.ts +30 -0
  58. package/dist/providers/kraken.js +203 -0
  59. package/dist/providers/options.d.ts +22 -0
  60. package/dist/providers/options.js +1 -0
  61. package/dist/providers/paging.d.ts +30 -0
  62. package/dist/providers/paging.js +59 -0
  63. package/dist/series/check.d.ts +32 -0
  64. package/dist/series/check.js +63 -0
  65. package/dist/series/live.d.ts +31 -0
  66. package/dist/series/live.js +121 -0
  67. package/dist/series/load.d.ts +35 -0
  68. package/dist/series/load.js +100 -0
  69. package/dist/series/store.d.ts +50 -0
  70. package/dist/series/store.js +148 -0
  71. package/dist/series/time.d.ts +15 -0
  72. package/dist/series/time.js +62 -0
  73. package/dist/watch/sinks.d.ts +7 -0
  74. package/dist/watch/sinks.js +22 -0
  75. package/dist/watch/watch.d.ts +78 -0
  76. package/dist/watch/watch.js +203 -0
  77. package/docs/agents.md +84 -0
  78. package/docs/positioning.md +94 -0
  79. package/docs/providers.md +92 -0
  80. package/package.json +68 -4
@@ -0,0 +1,100 @@
1
+ import { systemClock } from '../core/clock.js';
2
+ import { InvalidArgumentError } from '../core/errors.js';
3
+ import { instrument as toInstrument } from '../core/instrument.js';
4
+ import { parseTimeframe } from '../core/timeframe.js';
5
+ import { cleanCandles } from './check.js';
6
+ import { missingRanges } from './store.js';
7
+ import { nextPeriod, periodFloor, resolveTime } from './time.js';
8
+ /** Periods requested per provider call: below the 50 000 limit of `getCandles`. */
9
+ const CHUNK_PERIODS = 10_000;
10
+ const locks = new Map();
11
+ async function withLock(key, fn) {
12
+ const previous = locks.get(key) ?? Promise.resolve();
13
+ const run = previous.then(fn, fn);
14
+ const settled = run.catch(() => undefined);
15
+ locks.set(key, settled);
16
+ try {
17
+ return await run;
18
+ }
19
+ finally {
20
+ if (locks.get(key) === settled)
21
+ locks.delete(key);
22
+ }
23
+ }
24
+ /** Provider history for `[a, b]`, in chunks below the `getCandles` limit. */
25
+ async function fetchRange(options, a, b) {
26
+ const { provider, timeframe, signal } = options;
27
+ const out = [];
28
+ let cursor = a;
29
+ while (cursor <= b) {
30
+ signal?.throwIfAborted();
31
+ let end = cursor;
32
+ for (let i = 0; i < CHUNK_PERIODS && end <= b; i++)
33
+ end = nextPeriod(end, timeframe);
34
+ const chunkTo = Math.min(end - 1, b);
35
+ const got = await provider.getCandles(options.instrument, timeframe, { from: cursor, to: chunkTo, limit: 50_000, ...(signal ? { signal } : {}) });
36
+ const kept = got.filter((c) => c.time >= cursor && c.time <= chunkTo);
37
+ options.onFetch?.({ from: cursor, to: chunkTo, candles: kept.length });
38
+ out.push(...kept);
39
+ cursor = chunkTo + 1;
40
+ }
41
+ return out;
42
+ }
43
+ /** Closed candles of `[from, closedTo]` from the store, fetching and storing the ranges it lacks. */
44
+ function cachedRange(options, symbol, r) {
45
+ const { provider, timeframe } = options;
46
+ const store = options.store;
47
+ const key = { provider: provider.id, symbol, timeframe };
48
+ return withLock(`${provider.id}\u0000${symbol}\u0000${timeframe}`, async () => {
49
+ const stored = await store.read(key);
50
+ const fetched = [];
51
+ const covered = [];
52
+ for (const [a, b] of missingRanges(stored.covered, r.from, r.closedTo)) {
53
+ const got = await fetchRange(options, a, b);
54
+ const firstOpen = got.find((c) => !c.closed);
55
+ const final = got.filter((c) => c.closed && (!firstOpen || c.time < firstOpen.time));
56
+ fetched.push(...final);
57
+ // Recent periods may not be published yet: only trust them as fetched once a candle came back.
58
+ const last = final[final.length - 1];
59
+ const lastEnd = last ? nextPeriod(last.time, timeframe) - 1 : -Infinity;
60
+ const end = Math.min(firstOpen ? firstOpen.time - 1 : b, Math.max(r.settled, lastEnd));
61
+ if (end >= a)
62
+ covered.push([a, end]);
63
+ }
64
+ if (fetched.length || covered.length)
65
+ await store.append(key, fetched, covered);
66
+ return cleanCandles([...stored.candles, ...fetched]).filter((c) => c.time >= r.from && c.time <= r.closedTo);
67
+ });
68
+ }
69
+ /**
70
+ * Closed candles over a range, ascending, without duplicates. With a `store`, closed candles are kept
71
+ * and later calls only fetch the ranges never fetched before; a range the provider has no data for
72
+ * (before listing, outside its history limit) is remembered as fetched too.
73
+ */
74
+ export async function loadCandles(options) {
75
+ const { provider, timeframe, store, signal } = options;
76
+ const clock = options.clock ?? systemClock;
77
+ const inst = toInstrument(options.instrument);
78
+ const now = clock.now();
79
+ const from = periodFloor(resolveTime(options.from, now), timeframe);
80
+ const to = options.to === undefined ? now : resolveTime(options.to, now);
81
+ if (from > to)
82
+ throw new InvalidArgumentError('loadCandles: `from` must be before `to`');
83
+ /** Open time of the period still running: everything before it is final. */
84
+ const running = periodFloor(now, timeframe);
85
+ const closedTo = Math.min(to, running - 1);
86
+ /** Before this time, a period with no candle is taken as final (no trades, market closed, before listing). */
87
+ const settled = now - Math.max(2 * parseTimeframe(timeframe).ms, 20 * 60_000);
88
+ const range = { from, closedTo, settled };
89
+ let closed = [];
90
+ if (from <= closedTo) {
91
+ closed = store ? await cachedRange(options, inst.symbol, range) : (await fetchRange(options, from, closedTo)).filter((c) => c.closed);
92
+ }
93
+ if (options.forming && to >= running) {
94
+ const latest = await provider.getCandles(inst, timeframe, { limit: 2, ...(signal ? { signal } : {}) });
95
+ const open = latest.find((c) => !c.closed && c.time === running);
96
+ if (open)
97
+ closed = [...closed, open];
98
+ }
99
+ return cleanCandles(closed);
100
+ }
@@ -0,0 +1,50 @@
1
+ import type { Timeframe } from '../core/timeframe.js';
2
+ import type { Candle } from '../core/types.js';
3
+ /** Identifies one cached series. */
4
+ export interface SeriesKey {
5
+ provider: string;
6
+ /** Canonical instrument symbol (`BTC/USD`, `AAPL`). */
7
+ symbol: string;
8
+ timeframe: Timeframe;
9
+ }
10
+ /** Closed candles of one series, and the time ranges already fetched (inclusive open times). */
11
+ export interface StoredSeries {
12
+ candles: Candle[];
13
+ covered: [number, number][];
14
+ }
15
+ /** Where closed candles are kept between runs. */
16
+ export interface CandleStore {
17
+ read(key: SeriesKey): Promise<StoredSeries>;
18
+ /** Add closed candles and mark `covered` as fetched. */
19
+ append(key: SeriesKey, candles: readonly Candle[], covered: readonly [number, number][]): Promise<void>;
20
+ /** Forget one series, or everything. */
21
+ clear(key?: SeriesKey): Promise<void>;
22
+ }
23
+ /** Merge overlapping or touching ranges. */
24
+ export declare function mergeRanges(ranges: readonly (readonly [number, number])[]): [number, number][];
25
+ /** Parts of `[from, to]` not inside `covered` (merged). */
26
+ export declare function missingRanges(covered: readonly (readonly [number, number])[], from: number, to: number): [number, number][];
27
+ /** In-memory store (tests, short scripts). */
28
+ export declare class MemoryStore implements CandleStore {
29
+ private readonly data;
30
+ read(key: SeriesKey): Promise<StoredSeries>;
31
+ append(key: SeriesKey, candles: readonly Candle[], covered: readonly [number, number][]): Promise<void>;
32
+ clear(key?: SeriesKey): Promise<void>;
33
+ }
34
+ /**
35
+ * Store on disk, one folder per provider and instrument:
36
+ * `<dir>/<provider>/<symbol>/<timeframe>.jsonl` (one candle per line, append-only) and `<timeframe>.ranges.json`.
37
+ * Files can be read by any tool that understands JSON Lines (DuckDB, Polars, jq).
38
+ * Node, Bun and Deno only (uses `node:fs`).
39
+ */
40
+ export declare class FileStore implements CandleStore {
41
+ readonly dir: string;
42
+ constructor(dir: string);
43
+ private paths;
44
+ read(key: SeriesKey): Promise<StoredSeries>;
45
+ private rewrite;
46
+ append(key: SeriesKey, candles: readonly Candle[], covered: readonly [number, number][]): Promise<void>;
47
+ clear(key?: SeriesKey): Promise<void>;
48
+ }
49
+ /** Default cache folder: `$TICKWIRE_CACHE`, else `$XDG_CACHE_HOME/tickwire`, else `~/.cache/tickwire`. */
50
+ export declare function defaultCacheDir(): Promise<string>;
@@ -0,0 +1,148 @@
1
+ import { cleanCandles } from './check.js';
2
+ /** Merge overlapping or touching ranges. */
3
+ export function mergeRanges(ranges) {
4
+ const sorted = ranges.map(([a, b]) => [a, b]).sort((x, y) => x[0] - y[0]);
5
+ const out = [];
6
+ for (const r of sorted) {
7
+ const last = out[out.length - 1];
8
+ if (last && r[0] <= last[1] + 1)
9
+ last[1] = Math.max(last[1], r[1]);
10
+ else
11
+ out.push(r);
12
+ }
13
+ return out;
14
+ }
15
+ /** Parts of `[from, to]` not inside `covered` (merged). */
16
+ export function missingRanges(covered, from, to) {
17
+ const out = [];
18
+ let cursor = from;
19
+ for (const [a, b] of mergeRanges(covered)) {
20
+ if (b < cursor)
21
+ continue;
22
+ if (a > to)
23
+ break;
24
+ if (a > cursor)
25
+ out.push([cursor, Math.min(a - 1, to)]);
26
+ cursor = Math.max(cursor, b + 1);
27
+ if (cursor > to)
28
+ break;
29
+ }
30
+ if (cursor <= to)
31
+ out.push([cursor, to]);
32
+ return out;
33
+ }
34
+ const keyString = (k) => `${k.provider}\u0000${k.symbol}\u0000${k.timeframe}`;
35
+ /** In-memory store (tests, short scripts). */
36
+ export class MemoryStore {
37
+ data = new Map();
38
+ read(key) {
39
+ const s = this.data.get(keyString(key));
40
+ return Promise.resolve({ candles: [...(s?.candles ?? [])], covered: [...(s?.covered ?? [])] });
41
+ }
42
+ append(key, candles, covered) {
43
+ const k = keyString(key);
44
+ const s = this.data.get(k) ?? { candles: [], covered: [] };
45
+ this.data.set(k, { candles: cleanCandles([...s.candles, ...candles]), covered: mergeRanges([...s.covered, ...covered]) });
46
+ return Promise.resolve();
47
+ }
48
+ clear(key) {
49
+ if (key)
50
+ this.data.delete(keyString(key));
51
+ else
52
+ this.data.clear();
53
+ return Promise.resolve();
54
+ }
55
+ }
56
+ /** File name of a timeframe that stays distinct on case-insensitive file systems (`1M` → `1mo`). */
57
+ const tfFile = (tf) => tf.replace(/M$/, 'mo');
58
+ /**
59
+ * Store on disk, one folder per provider and instrument:
60
+ * `<dir>/<provider>/<symbol>/<timeframe>.jsonl` (one candle per line, append-only) and `<timeframe>.ranges.json`.
61
+ * Files can be read by any tool that understands JSON Lines (DuckDB, Polars, jq).
62
+ * Node, Bun and Deno only (uses `node:fs`).
63
+ */
64
+ export class FileStore {
65
+ dir;
66
+ constructor(dir) {
67
+ this.dir = dir;
68
+ }
69
+ async paths(key) {
70
+ const { join } = await import('node:path');
71
+ const folder = join(this.dir, encodeURIComponent(key.provider), encodeURIComponent(key.symbol));
72
+ const base = join(folder, tfFile(key.timeframe));
73
+ return { folder, data: `${base}.jsonl`, ranges: `${base}.ranges.json` };
74
+ }
75
+ async read(key) {
76
+ const fs = await import('node:fs/promises');
77
+ const p = await this.paths(key);
78
+ const text = await fs.readFile(p.data, 'utf8').catch(() => '');
79
+ const raw = [];
80
+ for (const line of text.split('\n')) {
81
+ if (!line.trim())
82
+ continue;
83
+ try {
84
+ const c = JSON.parse(line);
85
+ if (Number.isFinite(c.time))
86
+ raw.push({ ...c, closed: true });
87
+ }
88
+ catch {
89
+ // a torn last line after a crash: skip it, the range will be fetched again
90
+ }
91
+ }
92
+ const candles = cleanCandles(raw);
93
+ let covered;
94
+ try {
95
+ covered = mergeRanges(JSON.parse(await fs.readFile(p.ranges, 'utf8')));
96
+ }
97
+ catch {
98
+ covered = [];
99
+ }
100
+ if (candles.length < raw.length)
101
+ await this.rewrite(p, candles);
102
+ return { candles, covered };
103
+ }
104
+ async rewrite(p, candles) {
105
+ const fs = await import('node:fs/promises');
106
+ const tmp = `${p.data}.${process.pid}.tmp`;
107
+ await fs.writeFile(tmp, candles.map((c) => JSON.stringify(c)).join('\n') + (candles.length ? '\n' : ''));
108
+ await fs.rename(tmp, p.data);
109
+ }
110
+ async append(key, candles, covered) {
111
+ const fs = await import('node:fs/promises');
112
+ const p = await this.paths(key);
113
+ await fs.mkdir(p.folder, { recursive: true });
114
+ const closed = candles.filter((c) => c.closed);
115
+ if (closed.length)
116
+ await fs.appendFile(p.data, closed.map((c) => JSON.stringify(c)).join('\n') + '\n');
117
+ if (covered.length) {
118
+ let previous;
119
+ try {
120
+ previous = JSON.parse(await fs.readFile(p.ranges, 'utf8'));
121
+ }
122
+ catch {
123
+ previous = [];
124
+ }
125
+ const tmp = `${p.ranges}.${process.pid}.tmp`;
126
+ await fs.writeFile(tmp, JSON.stringify(mergeRanges([...previous, ...covered])));
127
+ await fs.rename(tmp, p.ranges);
128
+ }
129
+ }
130
+ async clear(key) {
131
+ const fs = await import('node:fs/promises');
132
+ if (!key) {
133
+ await fs.rm(this.dir, { recursive: true, force: true });
134
+ return;
135
+ }
136
+ const p = await this.paths(key);
137
+ await Promise.all([fs.rm(p.data, { force: true }), fs.rm(p.ranges, { force: true })]);
138
+ }
139
+ }
140
+ /** Default cache folder: `$TICKWIRE_CACHE`, else `$XDG_CACHE_HOME/tickwire`, else `~/.cache/tickwire`. */
141
+ export async function defaultCacheDir() {
142
+ const { homedir } = await import('node:os');
143
+ const { join } = await import('node:path');
144
+ const env = process.env;
145
+ if (env.TICKWIRE_CACHE)
146
+ return env.TICKWIRE_CACHE;
147
+ return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'tickwire');
148
+ }
@@ -0,0 +1,15 @@
1
+ import { type Timeframe } from '../core/timeframe.js';
2
+ import { type TimeInput } from '../core/util.js';
3
+ /**
4
+ * A relative duration: a count followed by a unit. `s`, `m` (minutes), `h`, `d`, `w`, `mo` or `M` (calendar
5
+ * months), `y` (calendar years). Examples: `90m`, `12h`, `7d`, `6mo`, `1y`.
6
+ */
7
+ export type Duration = string;
8
+ /** Point in time `duration` before `now`. Months and years follow the UTC calendar. */
9
+ export declare function ago(duration: Duration, now?: number): number;
10
+ /** A `TimeInput`, or a duration counted back from `now` (`7d`, `6mo`). */
11
+ export declare function resolveTime(value: TimeInput | Duration, now?: number): number;
12
+ /** Open time of the period containing `time` (UTC; weeks start on Monday; months on the 1st). */
13
+ export declare function periodFloor(time: number, timeframe: Timeframe): number;
14
+ /** Open time of the period after the one opening at `time`. */
15
+ export declare function nextPeriod(time: number, timeframe: Timeframe): number;
@@ -0,0 +1,62 @@
1
+ import { InvalidArgumentError } from '../core/errors.js';
2
+ import { parseTimeframe } from '../core/timeframe.js';
3
+ import { toMs } from '../core/util.js';
4
+ const DURATION_MS = {
5
+ s: 1_000,
6
+ m: 60_000,
7
+ h: 3_600_000,
8
+ d: 86_400_000,
9
+ w: 604_800_000,
10
+ };
11
+ /** Point in time `duration` before `now`. Months and years follow the UTC calendar. */
12
+ export function ago(duration, now = Date.now()) {
13
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(mo|M|y|[smhdw])\s*$/.exec(duration);
14
+ if (!match)
15
+ throw new InvalidArgumentError(`Invalid duration "${duration}" (expected e.g. 90m, 12h, 7d, 2w, 6mo, 1y)`);
16
+ const count = Number(match[1]);
17
+ const unit = match[2];
18
+ if (unit === 'mo' || unit === 'M' || unit === 'y') {
19
+ if (!Number.isInteger(count))
20
+ throw new InvalidArgumentError(`Invalid duration "${duration}": months and years must be whole`);
21
+ return addMonths(now, -(unit === 'y' ? 12 * count : count));
22
+ }
23
+ return now - count * DURATION_MS[unit];
24
+ }
25
+ /** A `TimeInput`, or a duration counted back from `now` (`7d`, `6mo`). */
26
+ export function resolveTime(value, now = Date.now()) {
27
+ if (typeof value === 'string' && /^\s*\d+(?:\.\d+)?\s*(mo|M|y|[smhdw])\s*$/.test(value))
28
+ return ago(value, now);
29
+ return toMs(value);
30
+ }
31
+ function addMonths(time, months) {
32
+ const d = new Date(time);
33
+ const target = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + months, 1));
34
+ const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
35
+ target.setUTCDate(Math.min(d.getUTCDate(), lastDay));
36
+ target.setUTCHours(d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
37
+ return target.getTime();
38
+ }
39
+ /** Open time of the period containing `time` (UTC; weeks start on Monday; months on the 1st). */
40
+ export function periodFloor(time, timeframe) {
41
+ const { unit, count, ms } = parseTimeframe(timeframe);
42
+ if (unit === 'M') {
43
+ const d = new Date(time);
44
+ const index = d.getUTCFullYear() * 12 + d.getUTCMonth();
45
+ const start = index - (((index % count) + count) % count);
46
+ return Date.UTC(Math.floor(start / 12), start % 12, 1);
47
+ }
48
+ if (unit === 'w') {
49
+ const monday = 4 * 86_400_000; // 1970-01-05 was a Monday
50
+ return Math.floor((time - monday) / ms) * ms + monday;
51
+ }
52
+ return Math.floor(time / ms) * ms;
53
+ }
54
+ /** Open time of the period after the one opening at `time`. */
55
+ export function nextPeriod(time, timeframe) {
56
+ const { unit, count, ms } = parseTimeframe(timeframe);
57
+ if (unit === 'M') {
58
+ const d = new Date(time);
59
+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + count, 1);
60
+ }
61
+ return time + ms;
62
+ }
@@ -0,0 +1,7 @@
1
+ /** Appends each value as one JSON line to a file (Node, Bun, Deno). Returns the function to call per event. */
2
+ export declare function appendJsonl(path: string): (value: unknown) => Promise<void>;
3
+ /** POSTs each value as JSON to a URL (a webhook). Throws on a non-2xx answer. */
4
+ export declare function postJson(url: string, init?: {
5
+ headers?: Record<string, string>;
6
+ fetch?: typeof fetch;
7
+ }): (value: unknown) => Promise<void>;
@@ -0,0 +1,22 @@
1
+ /** Appends each value as one JSON line to a file (Node, Bun, Deno). Returns the function to call per event. */
2
+ export function appendJsonl(path) {
3
+ return async (value) => {
4
+ const fs = await import('node:fs/promises');
5
+ const { dirname } = await import('node:path');
6
+ await fs.mkdir(dirname(path), { recursive: true });
7
+ await fs.appendFile(path, JSON.stringify(value) + '\n');
8
+ };
9
+ }
10
+ /** POSTs each value as JSON to a URL (a webhook). Throws on a non-2xx answer. */
11
+ export function postJson(url, init = {}) {
12
+ const doFetch = init.fetch ?? fetch;
13
+ return async (value) => {
14
+ const res = await doFetch(url, {
15
+ method: 'POST',
16
+ headers: { 'content-type': 'application/json', ...init.headers },
17
+ body: JSON.stringify(value),
18
+ });
19
+ if (!res.ok)
20
+ throw new Error(`postJson: ${url} answered HTTP ${res.status}`);
21
+ };
22
+ }
@@ -0,0 +1,78 @@
1
+ import { type Clock } from '../core/clock.js';
2
+ import { type InstrumentLike } from '../core/instrument.js';
3
+ import type { Provider } from '../core/provider.js';
4
+ import type { StreamOptions, StreamStatus, TickStream } from '../core/stream.js';
5
+ import type { Timeframe } from '../core/timeframe.js';
6
+ import type { Candle, Instrument } from '../core/types.js';
7
+ import type { CandleStore } from '../series/store.js';
8
+ export interface WatchContext {
9
+ readonly instrument: Instrument;
10
+ readonly timeframe: Timeframe;
11
+ /** Recent candles, oldest first. The last one is still forming when `on` is `'update'` and the period is running. */
12
+ readonly candles: readonly Candle[];
13
+ /** The newest candle (`candles.at(-1)`). */
14
+ readonly candle: Candle;
15
+ /** Closing prices of `candles`. */
16
+ readonly closes: readonly number[];
17
+ }
18
+ /**
19
+ * The condition. Return a falsy value when nothing happens; return `true` or any value describing the
20
+ * setup (a message, an object) to trigger. That value is passed along as `detail`.
21
+ */
22
+ export type WatchCondition = (ctx: WatchContext) => unknown;
23
+ export interface WatchOptions extends Omit<StreamOptions, 'signal' | 'onStatus'> {
24
+ provider: Provider;
25
+ /** One instrument or several, all watched with the same condition. */
26
+ instruments: InstrumentLike | readonly InstrumentLike[];
27
+ timeframe: Timeframe;
28
+ when: WatchCondition;
29
+ /** Name carried in every event, to tell watchers apart in a shared log. */
30
+ name?: string;
31
+ /** Evaluate on each closed candle (default) or on every live update. */
32
+ on?: 'close' | 'update';
33
+ /**
34
+ * `edge` (default): trigger when the condition becomes true, then wait until it is false again.
35
+ * `every`: trigger each time it is evaluated true.
36
+ */
37
+ mode?: 'edge' | 'every';
38
+ /** Minimum time between two triggers for one instrument, in ms (default 0). */
39
+ cooldownMs?: number;
40
+ /** Candles kept in the context (default 300). Also the history loaded at start. */
41
+ history?: number;
42
+ /** Evaluate the condition on the history as it loads (default false: only live candles can trigger). */
43
+ evaluateHistory?: boolean;
44
+ store?: CandleStore;
45
+ signal?: AbortSignal;
46
+ onStatus?: (status: StreamStatus & {
47
+ instrument: string;
48
+ }) => void;
49
+ /** Called when the condition throws; the watcher keeps going. Default: the error is rethrown and stops it. */
50
+ onError?: (error: unknown, ctx: WatchContext) => void;
51
+ clock?: Clock;
52
+ }
53
+ export interface WatchEvent {
54
+ type: 'trigger';
55
+ name?: string;
56
+ /** Canonical symbol. */
57
+ instrument: string;
58
+ provider: string;
59
+ timeframe: Timeframe;
60
+ /** When the trigger was emitted (ms). */
61
+ at: number;
62
+ /** The candle the condition fired on. */
63
+ candle: Candle;
64
+ /** What the condition returned. */
65
+ detail: unknown;
66
+ }
67
+ /**
68
+ * Watches one or more instruments and emits an event when the condition triggers.
69
+ * Runs until closed; reconnections and missed candles are handled by `liveCandles`.
70
+ *
71
+ * ```ts
72
+ * for await (const e of watch({ provider, instruments: ['ETH/USDT'], timeframe: '1h',
73
+ * when: ({ closes }) => (rsi(closes, 14).at(-1) ?? 50) < 30 && 'RSI 14 under 30' })) {
74
+ * console.log(JSON.stringify(e));
75
+ * }
76
+ * ```
77
+ */
78
+ export declare function watch(options: WatchOptions): TickStream<WatchEvent>;