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
package/dist/cli.js ADDED
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { InvalidArgumentError, TickwireError } from './core/errors.js';
4
+ import { instrument } from './core/instrument.js';
5
+ import { parseTimeframe } from './core/timeframe.js';
6
+ import { createProvider } from './providers/create.js';
7
+ import { checkCandles } from './series/check.js';
8
+ import { loadCandles } from './series/load.js';
9
+ import { defaultCacheDir, FileStore } from './series/store.js';
10
+ import { periodFloor } from './series/time.js';
11
+ const HELP = `tickwire: market data from the command line. Output is JSON on stdout; errors are JSON on stderr.
12
+
13
+ Usage:
14
+ tickwire candles <provider> <instrument> <timeframe> [options]
15
+ tickwire check <provider> <instrument> <timeframe> [options] gaps, duplicates and alignment
16
+ tickwire quote <provider> <instrument>
17
+ tickwire cache path | clear [<provider> <instrument> <timeframe>]
18
+
19
+ Providers: binance, coinbase, kraken, alpaca (APCA_API_KEY_ID / APCA_API_SECRET_KEY).
20
+ Instruments: BTC/USDT, ETH/USD, AAPL. Timeframes: 1m 5m 15m 1h 4h 1d 1w 1M.
21
+
22
+ Options for candles and check:
23
+ --since <duration|time> start, e.g. 7d, 6mo, 1y, 2026-01-01 (default: the last --limit candles)
24
+ --to <duration|time> end (default: now)
25
+ --limit <n> keep only the last n candles (default 200 without --since)
26
+ --forming append the candle still forming
27
+ --format json|jsonl|csv candles output (default json: a summary plus the candles)
28
+ --no-cache fetch everything, keep nothing
29
+ --cache-dir <dir> default: $TICKWIRE_CACHE or ~/.cache/tickwire
30
+
31
+ Examples:
32
+ tickwire candles binance BTC/USDT 1h --since 7d
33
+ tickwire candles alpaca AAPL 1d --since 1y --format csv
34
+ tickwire quote coinbase ETH/USD`;
35
+ function out(value) {
36
+ process.stdout.write(JSON.stringify(value) + '\n');
37
+ }
38
+ function args(positionals, n, usage) {
39
+ if (positionals.length < n)
40
+ throw new InvalidArgumentError(`usage: tickwire ${usage}`);
41
+ return positionals;
42
+ }
43
+ async function store(values) {
44
+ if (values['no-cache'])
45
+ return undefined;
46
+ return new FileStore(typeof values['cache-dir'] === 'string' ? values['cache-dir'] : await defaultCacheDir());
47
+ }
48
+ async function candles(pos, values) {
49
+ const [providerId, symbol, tf] = args(pos, 3, `${pos[0] ?? 'candles'} <provider> <instrument> <timeframe>`).slice(1);
50
+ parseTimeframe(tf);
51
+ const timeframe = tf;
52
+ const provider = createProvider(providerId);
53
+ const limit = values.limit === undefined ? (values.since === undefined ? 200 : undefined) : Number(values.limit);
54
+ if (limit !== undefined && !(Number.isInteger(limit) && limit > 0))
55
+ throw new InvalidArgumentError('--limit must be a positive integer');
56
+ let from = values.since;
57
+ if (from === undefined) {
58
+ let t = periodFloor(Date.now(), timeframe);
59
+ for (let i = 0; i < limit; i++)
60
+ t = periodFloor(t - 1, timeframe);
61
+ from = t;
62
+ }
63
+ const s = await store(values);
64
+ const list = await loadCandles({
65
+ provider,
66
+ instrument: instrument(symbol),
67
+ timeframe,
68
+ from,
69
+ ...(values.to !== undefined ? { to: values.to } : {}),
70
+ ...(values.forming ? { forming: true } : {}),
71
+ ...(s ? { store: s } : {}),
72
+ });
73
+ return limit === undefined ? list : list.slice(-limit);
74
+ }
75
+ const iso = (t) => new Date(t).toISOString();
76
+ async function candlesCommand(pos, values) {
77
+ const list = await candles(pos, values);
78
+ const format = values.format ?? 'json';
79
+ if (format === 'jsonl') {
80
+ for (const c of list)
81
+ out(c);
82
+ }
83
+ else if (format === 'csv') {
84
+ process.stdout.write('time,open,high,low,close,volume,closed\n');
85
+ for (const c of list)
86
+ process.stdout.write(`${iso(c.time)},${c.open},${c.high},${c.low},${c.close},${c.volume},${c.closed}\n`);
87
+ }
88
+ else if (format === 'json') {
89
+ const [, provider, symbol, timeframe] = pos;
90
+ out({
91
+ provider,
92
+ instrument: instrument(symbol).symbol,
93
+ timeframe,
94
+ count: list.length,
95
+ first: list[0] ? iso(list[0].time) : null,
96
+ last: list.length ? iso(list[list.length - 1].time) : null,
97
+ gaps: checkCandles(list, timeframe).gaps.length,
98
+ candles: list,
99
+ });
100
+ }
101
+ else {
102
+ throw new InvalidArgumentError('--format must be json, jsonl or csv');
103
+ }
104
+ }
105
+ async function checkCommand(pos, values) {
106
+ const r = checkCandles(await candles(pos, values), pos[3]);
107
+ out({
108
+ count: r.count,
109
+ first: r.first !== undefined ? iso(r.first) : null,
110
+ last: r.last !== undefined ? iso(r.last) : null,
111
+ missingPeriods: r.gaps.reduce((a, g) => a + g.missing, 0),
112
+ gaps: r.gaps.map((g) => ({ from: iso(g.from), to: iso(g.to), missing: g.missing })),
113
+ duplicates: r.duplicates.map(iso),
114
+ unordered: r.unordered,
115
+ misaligned: r.misaligned.map(iso),
116
+ });
117
+ }
118
+ async function quoteCommand(pos) {
119
+ const [, providerId, symbol] = args(pos, 3, 'quote <provider> <instrument>');
120
+ out(await createProvider(providerId).getQuote(instrument(symbol)));
121
+ }
122
+ async function cacheCommand(pos, values) {
123
+ const dir = typeof values['cache-dir'] === 'string' ? values['cache-dir'] : await defaultCacheDir();
124
+ if (pos[1] === 'path')
125
+ return out({ path: dir });
126
+ if (pos[1] !== 'clear')
127
+ throw new InvalidArgumentError('usage: tickwire cache path | clear [<provider> <instrument> <timeframe>]');
128
+ const fs = new FileStore(dir);
129
+ const [, , providerId, symbol, tf] = pos;
130
+ if (providerId && symbol && tf) {
131
+ parseTimeframe(tf);
132
+ await fs.clear({ provider: providerId, symbol: instrument(symbol).symbol, timeframe: tf });
133
+ }
134
+ else {
135
+ await fs.clear();
136
+ }
137
+ out({ cleared: true });
138
+ }
139
+ const COMMANDS = {
140
+ candles: candlesCommand,
141
+ check: checkCommand,
142
+ quote: quoteCommand,
143
+ cache: cacheCommand,
144
+ };
145
+ async function main(argv) {
146
+ const { values, positionals } = parseArgs({
147
+ args: argv,
148
+ allowPositionals: true,
149
+ options: {
150
+ since: { type: 'string' },
151
+ to: { type: 'string' },
152
+ limit: { type: 'string' },
153
+ forming: { type: 'boolean' },
154
+ format: { type: 'string' },
155
+ 'no-cache': { type: 'boolean' },
156
+ 'cache-dir': { type: 'string' },
157
+ help: { type: 'boolean', short: 'h' },
158
+ },
159
+ });
160
+ const command = positionals[0];
161
+ if (!command || values.help || command === 'help') {
162
+ process.stdout.write(HELP + '\n');
163
+ return;
164
+ }
165
+ const run = COMMANDS[command];
166
+ if (!run)
167
+ throw new InvalidArgumentError(`Unknown command "${command}". Run tickwire --help.`);
168
+ await run(positionals, values);
169
+ }
170
+ process.stdout.on('error', (error) => {
171
+ if (error.code === 'EPIPE')
172
+ process.exit(0);
173
+ throw error;
174
+ });
175
+ main(process.argv.slice(2)).catch((error) => {
176
+ const e = error instanceof Error ? error : new Error(String(error));
177
+ process.stderr.write(JSON.stringify({ error: { name: e.name, message: e.message, ...(e instanceof TickwireError && e.provider ? { provider: e.provider } : {}) } }) + '\n');
178
+ process.exitCode = e instanceof InvalidArgumentError || e.name === 'TypeError' ? 2 : 1;
179
+ });
@@ -0,0 +1,19 @@
1
+ import { type Timeframe } from './timeframe.js';
2
+ import type { Candle, Trade } from './types.js';
3
+ /** Open time of the period containing `time`, aligned on UTC (seconds to weeks; weeks start on Monday). */
4
+ export declare function periodStart(time: number, timeframe: Timeframe): number;
5
+ /**
6
+ * Builds candles from a trade feed. `update(trade)` returns the candles to emit:
7
+ * the previous candle with `closed: true` when a new period starts, then the running candle.
8
+ * Periods without trades produce no candle.
9
+ */
10
+ export declare class CandleBuilder {
11
+ readonly timeframe: Timeframe;
12
+ private current;
13
+ constructor(timeframe: Timeframe);
14
+ update(trade: Pick<Trade, 'time' | 'price' | 'size'>): Candle[];
15
+ /** Close the running candle when its period is over at `now` (call it on a timer to close idle periods). */
16
+ flush(now: number): Candle[];
17
+ }
18
+ /** Batch version: candles from a list of trades in time order. The last candle is marked open. */
19
+ export declare function candlesFromTrades(trades: Iterable<Pick<Trade, 'time' | 'price' | 'size'>>, timeframe: Timeframe): Candle[];
@@ -0,0 +1,64 @@
1
+ import { InvalidArgumentError } from './errors.js';
2
+ import { parseTimeframe } from './timeframe.js';
3
+ /** Open time of the period containing `time`, aligned on UTC (seconds to weeks; weeks start on Monday). */
4
+ export function periodStart(time, timeframe) {
5
+ const { unit, ms } = parseTimeframe(timeframe);
6
+ if (unit === 'M')
7
+ throw new InvalidArgumentError('Monthly periods cannot be built from trades');
8
+ if (unit === 'w') {
9
+ const monday = 4 * 86_400_000; // 1970-01-05 was a Monday
10
+ return Math.floor((time - monday) / ms) * ms + monday;
11
+ }
12
+ return Math.floor(time / ms) * ms;
13
+ }
14
+ /**
15
+ * Builds candles from a trade feed. `update(trade)` returns the candles to emit:
16
+ * the previous candle with `closed: true` when a new period starts, then the running candle.
17
+ * Periods without trades produce no candle.
18
+ */
19
+ export class CandleBuilder {
20
+ timeframe;
21
+ current = null;
22
+ constructor(timeframe) {
23
+ this.timeframe = timeframe;
24
+ periodStart(0, timeframe); // validates
25
+ }
26
+ update(trade) {
27
+ const time = periodStart(trade.time, this.timeframe);
28
+ const out = [];
29
+ const c = this.current;
30
+ if (c && time < c.time)
31
+ return out; // late trade from a period already closed
32
+ if (c && time > c.time) {
33
+ out.push({ ...c, closed: true });
34
+ this.current = null;
35
+ }
36
+ if (!this.current) {
37
+ this.current = { time, open: trade.price, high: trade.price, low: trade.price, close: trade.price, volume: 0 };
38
+ }
39
+ const cur = this.current;
40
+ cur.high = Math.max(cur.high, trade.price);
41
+ cur.low = Math.min(cur.low, trade.price);
42
+ cur.close = trade.price;
43
+ cur.volume += trade.size;
44
+ out.push({ ...cur, closed: false });
45
+ return out;
46
+ }
47
+ /** Close the running candle when its period is over at `now` (call it on a timer to close idle periods). */
48
+ flush(now) {
49
+ const c = this.current;
50
+ if (!c || periodStart(now, this.timeframe) <= c.time)
51
+ return [];
52
+ this.current = null;
53
+ return [{ ...c, closed: true }];
54
+ }
55
+ }
56
+ /** Batch version: candles from a list of trades in time order. The last candle is marked open. */
57
+ export function candlesFromTrades(trades, timeframe) {
58
+ const builder = new CandleBuilder(timeframe);
59
+ const out = new Map();
60
+ for (const trade of trades)
61
+ for (const c of builder.update(trade))
62
+ out.set(c.time, c);
63
+ return [...out.values()];
64
+ }
@@ -0,0 +1,6 @@
1
+ /** Time source and timer, injectable for tests. */
2
+ export interface Clock {
3
+ now(): number;
4
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
5
+ }
6
+ export declare const systemClock: Clock;
@@ -0,0 +1,18 @@
1
+ export const systemClock = {
2
+ now: () => Date.now(),
3
+ sleep: (ms, signal) => new Promise((resolve, reject) => {
4
+ if (signal?.aborted) {
5
+ reject(signal.reason ?? new Error('Aborted'));
6
+ return;
7
+ }
8
+ const timer = setTimeout(() => {
9
+ signal?.removeEventListener('abort', onAbort);
10
+ resolve();
11
+ }, Math.max(0, ms));
12
+ const onAbort = () => {
13
+ clearTimeout(timer);
14
+ reject(signal?.reason ?? new Error('Aborted'));
15
+ };
16
+ signal?.addEventListener('abort', onAbort, { once: true });
17
+ }),
18
+ };
@@ -0,0 +1,51 @@
1
+ /** Base class of every error thrown by tickwire. */
2
+ export declare class TickwireError extends Error {
3
+ readonly name: string;
4
+ /** Provider id (`binance`, `kraken`…) when the error comes from a provider. */
5
+ readonly provider?: string;
6
+ constructor(message: string, options?: {
7
+ provider?: string;
8
+ cause?: unknown;
9
+ });
10
+ }
11
+ /** Invalid argument given by the caller (unknown timeframe, bad instrument, from > to…). */
12
+ export declare class InvalidArgumentError extends TickwireError {
13
+ readonly name = "InvalidArgumentError";
14
+ }
15
+ /** The provider does not support this feature or timeframe. */
16
+ export declare class NotSupportedError extends TickwireError {
17
+ readonly name = "NotSupportedError";
18
+ }
19
+ /** Missing or rejected credentials. */
20
+ export declare class AuthenticationError extends TickwireError {
21
+ readonly name = "AuthenticationError";
22
+ }
23
+ /** The request could not reach the provider (DNS, TCP, TLS, timeout). */
24
+ export declare class NetworkError extends TickwireError {
25
+ readonly name = "NetworkError";
26
+ }
27
+ /** The provider answered with a rate limit (HTTP 429/418 or equivalent). */
28
+ export declare class RateLimitError extends TickwireError {
29
+ readonly name = "RateLimitError";
30
+ /** Delay suggested by the provider before retrying, in ms. */
31
+ readonly retryAfterMs?: number;
32
+ constructor(message: string, options?: {
33
+ provider?: string;
34
+ cause?: unknown;
35
+ retryAfterMs?: number;
36
+ });
37
+ }
38
+ /** The provider answered with an error (unknown symbol, server error, unexpected payload). */
39
+ export declare class ProviderError extends TickwireError {
40
+ readonly name = "ProviderError";
41
+ /** HTTP status, when the error comes from an HTTP response. */
42
+ readonly status?: number;
43
+ /** Provider error code, when it gives one. */
44
+ readonly code?: string;
45
+ constructor(message: string, options?: {
46
+ provider?: string;
47
+ cause?: unknown;
48
+ status?: number;
49
+ code?: string;
50
+ });
51
+ }
@@ -0,0 +1,53 @@
1
+ /** Base class of every error thrown by tickwire. */
2
+ export class TickwireError extends Error {
3
+ name = 'TickwireError';
4
+ /** Provider id (`binance`, `kraken`…) when the error comes from a provider. */
5
+ provider;
6
+ constructor(message, options = {}) {
7
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
8
+ if (options.provider !== undefined)
9
+ this.provider = options.provider;
10
+ }
11
+ }
12
+ /** Invalid argument given by the caller (unknown timeframe, bad instrument, from > to…). */
13
+ export class InvalidArgumentError extends TickwireError {
14
+ name = 'InvalidArgumentError';
15
+ }
16
+ /** The provider does not support this feature or timeframe. */
17
+ export class NotSupportedError extends TickwireError {
18
+ name = 'NotSupportedError';
19
+ }
20
+ /** Missing or rejected credentials. */
21
+ export class AuthenticationError extends TickwireError {
22
+ name = 'AuthenticationError';
23
+ }
24
+ /** The request could not reach the provider (DNS, TCP, TLS, timeout). */
25
+ export class NetworkError extends TickwireError {
26
+ name = 'NetworkError';
27
+ }
28
+ /** The provider answered with a rate limit (HTTP 429/418 or equivalent). */
29
+ export class RateLimitError extends TickwireError {
30
+ name = 'RateLimitError';
31
+ /** Delay suggested by the provider before retrying, in ms. */
32
+ retryAfterMs;
33
+ constructor(message, options = {}) {
34
+ super(message, options);
35
+ if (options.retryAfterMs !== undefined)
36
+ this.retryAfterMs = options.retryAfterMs;
37
+ }
38
+ }
39
+ /** The provider answered with an error (unknown symbol, server error, unexpected payload). */
40
+ export class ProviderError extends TickwireError {
41
+ name = 'ProviderError';
42
+ /** HTTP status, when the error comes from an HTTP response. */
43
+ status;
44
+ /** Provider error code, when it gives one. */
45
+ code;
46
+ constructor(message, options = {}) {
47
+ super(message, options);
48
+ if (options.status !== undefined)
49
+ this.status = options.status;
50
+ if (options.code !== undefined)
51
+ this.code = options.code;
52
+ }
53
+ }
@@ -0,0 +1,38 @@
1
+ import { type Clock } from './clock.js';
2
+ import { TickwireError } from './errors.js';
3
+ import type { RateLimiter } from './rate-limiter.js';
4
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
5
+ export type Query = Record<string, string | number | boolean | undefined>;
6
+ export interface HttpClientOptions {
7
+ provider: string;
8
+ baseUrl: string;
9
+ limiter: RateLimiter;
10
+ fetch?: FetchLike;
11
+ clock?: Clock;
12
+ /** Per-request timeout in ms (default 10 000). */
13
+ timeoutMs?: number;
14
+ /** Retries on network errors, 5xx and 429 (default 2). */
15
+ retries?: number;
16
+ headers?: Record<string, string>;
17
+ /**
18
+ * Turn a non-2xx answer into an error. Return `undefined` to fall back to the default mapping.
19
+ * `body` is the parsed JSON when possible, otherwise the raw text.
20
+ */
21
+ mapError?: (status: number, body: unknown, headers: Headers) => TickwireError | undefined;
22
+ }
23
+ export interface RequestOptions {
24
+ /** Rate-limit weight of this request (default 1). */
25
+ weight?: number;
26
+ signal?: AbortSignal;
27
+ headers?: Record<string, string>;
28
+ }
29
+ /** Small JSON-over-HTTP client: rate limiting, timeouts, retries with backoff, typed errors. */
30
+ export declare class HttpClient {
31
+ private readonly options;
32
+ constructor(options: HttpClientOptions);
33
+ url(path: string, query?: Query): string;
34
+ get<T = unknown>(path: string, query?: Query, request?: RequestOptions): Promise<T>;
35
+ private once;
36
+ }
37
+ export declare function retryAfterMs(headers: Headers): number | undefined;
38
+ export declare function defaultHttpError(provider: string, status: number, body: unknown, headers: Headers): TickwireError;
@@ -0,0 +1,119 @@
1
+ import { systemClock } from './clock.js';
2
+ import { NetworkError, ProviderError, RateLimitError, TickwireError } from './errors.js';
3
+ /** Small JSON-over-HTTP client: rate limiting, timeouts, retries with backoff, typed errors. */
4
+ export class HttpClient {
5
+ options;
6
+ constructor(options) {
7
+ const fetchImpl = options.fetch ?? globalThis.fetch;
8
+ if (!fetchImpl)
9
+ throw new TickwireError('No fetch implementation available: pass one in the provider options');
10
+ this.options = {
11
+ clock: systemClock,
12
+ timeoutMs: 10_000,
13
+ retries: 2,
14
+ ...options,
15
+ fetch: fetchImpl,
16
+ };
17
+ }
18
+ url(path, query = {}) {
19
+ const url = new URL(path, this.options.baseUrl.endsWith('/') ? this.options.baseUrl : `${this.options.baseUrl}/`);
20
+ for (const [key, value] of Object.entries(query)) {
21
+ if (value !== undefined)
22
+ url.searchParams.set(key, String(value));
23
+ }
24
+ return url.toString();
25
+ }
26
+ async get(path, query = {}, request = {}) {
27
+ const { limiter, clock, retries } = this.options;
28
+ const url = this.url(path, query);
29
+ for (let attempt = 0;; attempt++) {
30
+ await limiter.acquire(request.weight ?? 1, request.signal);
31
+ try {
32
+ return (await this.once(url, request));
33
+ }
34
+ catch (error) {
35
+ const retryable = error instanceof NetworkError ||
36
+ (error instanceof RateLimitError && error.retryAfterMs !== Infinity) ||
37
+ (error instanceof ProviderError && error.status !== undefined && error.status >= 500);
38
+ if (!retryable || attempt >= retries || request.signal?.aborted)
39
+ throw error;
40
+ let delay = Math.min(250 * 2 ** attempt, 5_000);
41
+ if (error instanceof RateLimitError) {
42
+ delay = error.retryAfterMs ?? Math.max(delay, 1_000);
43
+ limiter.pauseFor(delay);
44
+ }
45
+ await clock.sleep(delay, request.signal);
46
+ }
47
+ }
48
+ }
49
+ async once(url, request) {
50
+ const { provider, timeoutMs } = this.options;
51
+ const controller = new AbortController();
52
+ const timer = setTimeout(() => controller.abort(new Error(`Timed out after ${timeoutMs} ms`)), timeoutMs);
53
+ const onAbort = () => controller.abort(request.signal?.reason);
54
+ request.signal?.addEventListener('abort', onAbort, { once: true });
55
+ let response;
56
+ let text;
57
+ try {
58
+ response = await this.options.fetch(url, {
59
+ method: 'GET',
60
+ headers: { accept: 'application/json', ...this.options.headers, ...request.headers },
61
+ signal: controller.signal,
62
+ });
63
+ text = await response.text();
64
+ }
65
+ catch (error) {
66
+ if (request.signal?.aborted)
67
+ throw request.signal.reason ?? error;
68
+ throw new NetworkError(`${provider}: request failed (${error.message ?? String(error)})`, {
69
+ provider,
70
+ cause: error,
71
+ });
72
+ }
73
+ finally {
74
+ clearTimeout(timer);
75
+ request.signal?.removeEventListener('abort', onAbort);
76
+ }
77
+ let body = text;
78
+ try {
79
+ body = text === '' ? undefined : JSON.parse(text);
80
+ }
81
+ catch {
82
+ // keep raw text
83
+ }
84
+ if (!response.ok) {
85
+ const mapped = this.options.mapError?.(response.status, body, response.headers);
86
+ if (mapped)
87
+ throw mapped;
88
+ throw defaultHttpError(provider, response.status, body, response.headers);
89
+ }
90
+ if (typeof body === 'string') {
91
+ throw new ProviderError(`${provider}: expected JSON, got ${JSON.stringify(text.slice(0, 120))}`, {
92
+ provider,
93
+ status: response.status,
94
+ });
95
+ }
96
+ return body;
97
+ }
98
+ }
99
+ export function retryAfterMs(headers) {
100
+ const value = headers.get('retry-after');
101
+ if (value === null)
102
+ return undefined;
103
+ const seconds = Number(value);
104
+ if (Number.isFinite(seconds))
105
+ return Math.max(0, seconds * 1000);
106
+ const date = Date.parse(value);
107
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
108
+ }
109
+ export function defaultHttpError(provider, status, body, headers) {
110
+ const detail = typeof body === 'string' ? body.slice(0, 200) : JSON.stringify(body)?.slice(0, 200);
111
+ if (status === 429) {
112
+ const after = retryAfterMs(headers);
113
+ return new RateLimitError(`${provider}: rate limited (HTTP 429)`, {
114
+ provider,
115
+ ...(after !== undefined ? { retryAfterMs: after } : {}),
116
+ });
117
+ }
118
+ return new ProviderError(`${provider}: HTTP ${status}${detail ? ` ${detail}` : ''}`, { provider, status });
119
+ }
@@ -0,0 +1,14 @@
1
+ import type { AssetClass, Instrument } from './types.js';
2
+ export interface InstrumentOptions {
3
+ /** Force the asset class (default: `crypto` for `BASE/QUOTE`, `stock` otherwise). */
4
+ assetClass?: AssetClass;
5
+ /** Provider-native symbol, bypassing the provider's own translation. */
6
+ native?: string;
7
+ }
8
+ /**
9
+ * Build an instrument from its canonical symbol: `BTC/USD`, `eth/usdt`, `AAPL`.
10
+ * Symbols are upper-cased.
11
+ */
12
+ export declare function instrument(symbol: string | Instrument, options?: InstrumentOptions): Instrument;
13
+ /** Accepts an instrument or a symbol string. */
14
+ export type InstrumentLike = Instrument | string;
@@ -0,0 +1,22 @@
1
+ import { InvalidArgumentError } from './errors.js';
2
+ /**
3
+ * Build an instrument from its canonical symbol: `BTC/USD`, `eth/usdt`, `AAPL`.
4
+ * Symbols are upper-cased.
5
+ */
6
+ export function instrument(symbol, options = {}) {
7
+ if (typeof symbol !== 'string')
8
+ return symbol;
9
+ const clean = symbol.trim().toUpperCase();
10
+ if (!/^[A-Z0-9.\-_]+(\/[A-Z0-9.\-_]+)?$/.test(clean)) {
11
+ throw new InvalidArgumentError(`Invalid instrument "${symbol}" (expected BASE/QUOTE like BTC/USD, or a ticker like AAPL)`);
12
+ }
13
+ const [base, quote] = clean.split('/');
14
+ const assetClass = options.assetClass ?? (quote ? 'crypto' : 'stock');
15
+ return {
16
+ symbol: clean,
17
+ base,
18
+ quote: quote ?? 'USD',
19
+ assetClass,
20
+ ...(options.native !== undefined ? { native: options.native } : {}),
21
+ };
22
+ }
@@ -0,0 +1,47 @@
1
+ import type { InstrumentLike } from './instrument.js';
2
+ import type { StreamOptions, TickStream } from './stream.js';
3
+ import type { Timeframe } from './timeframe.js';
4
+ import type { Candle, Quote, Trade } from './types.js';
5
+ import type { TimeInput } from './util.js';
6
+ export interface CandleQuery {
7
+ /** Oldest candle open time to include. */
8
+ from?: TimeInput;
9
+ /** Newest candle open time to include (default: now). */
10
+ to?: TimeInput;
11
+ /**
12
+ * Maximum number of candles. With `from`, the first `limit` candles after it; without `from`,
13
+ * the latest `limit` candles up to `to`. Default 500 without `from`, unlimited (up to 50 000) with it.
14
+ */
15
+ limit?: number;
16
+ signal?: AbortSignal;
17
+ }
18
+ export interface RequestOptions {
19
+ signal?: AbortSignal;
20
+ }
21
+ /** Capabilities of a provider, for feature detection. */
22
+ export interface ProviderCapabilities {
23
+ /** Timeframes accepted by `getCandles`. */
24
+ readonly candleTimeframes: readonly Timeframe[];
25
+ /** Timeframes accepted by `streamCandles`. */
26
+ readonly streamTimeframes: readonly Timeframe[];
27
+ /** `true` when `streamCandles` builds candles locally from the trade feed. */
28
+ readonly candlesFromTrades: boolean;
29
+ /** Oldest data reachable by `getCandles`, when the provider caps history (Kraken: last 720 candles). */
30
+ readonly maxHistoryCandles?: number;
31
+ }
32
+ /** One interface for every market data source. */
33
+ export interface Provider {
34
+ /** Stable id: `binance`, `coinbase`, `kraken`, `alpaca`. */
35
+ readonly id: string;
36
+ readonly capabilities: ProviderCapabilities;
37
+ /** Provider-native symbol for an instrument (`BTCUSDT`, `BTC-USD`…). */
38
+ nativeSymbol(instrument: InstrumentLike): string;
39
+ /** Historical candles in ascending time order. The running period, if included, has `closed: false`. */
40
+ getCandles(instrument: InstrumentLike, timeframe: Timeframe, query?: CandleQuery): Promise<Candle[]>;
41
+ /** Best bid/ask (and last price when available). */
42
+ getQuote(instrument: InstrumentLike, options?: RequestOptions): Promise<Quote>;
43
+ /** Live trades. */
44
+ streamTrades(instrument: InstrumentLike, options?: StreamOptions): TickStream<Trade>;
45
+ /** Live candles: an update on each change, `closed: true` once the period is over. */
46
+ streamCandles(instrument: InstrumentLike, timeframe: Timeframe, options?: StreamOptions): TickStream<Candle>;
47
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { type Clock } from './clock.js';
2
+ export interface RateLimitOptions {
3
+ /** Maximum burst, in weight units. */
4
+ capacity: number;
5
+ /** Weight units regained per second. */
6
+ refillPerSecond: number;
7
+ }
8
+ /**
9
+ * Token bucket shared by every request of a provider instance.
10
+ * Requests wait in FIFO order until enough weight is available, so the provider's limit is never exceeded
11
+ * by this process. A rate-limit answer from the server can also pause the bucket (`pauseFor`).
12
+ */
13
+ export declare class RateLimiter {
14
+ readonly capacity: number;
15
+ readonly refillPerSecond: number;
16
+ private tokens;
17
+ private last;
18
+ private pausedUntil;
19
+ private chain;
20
+ private readonly clock;
21
+ constructor(options: RateLimitOptions, clock?: Clock);
22
+ /** Weight currently available (after refill). */
23
+ available(): number;
24
+ /** Block every request until `ms` from now (used after a 429 with Retry-After). */
25
+ pauseFor(ms: number): void;
26
+ /** Wait until `weight` units are available, then consume them. */
27
+ acquire(weight?: number, signal?: AbortSignal): Promise<void>;
28
+ private refill;
29
+ private take;
30
+ }