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,21 @@
1
+ import { InvalidArgumentError } from '../core/errors.js';
2
+ import { AlpacaProvider } from './alpaca.js';
3
+ import { BinanceProvider } from './binance.js';
4
+ import { CoinbaseProvider } from './coinbase.js';
5
+ import { KrakenProvider } from './kraken.js';
6
+ export const PROVIDER_IDS = ['binance', 'coinbase', 'kraken', 'alpaca'];
7
+ /** A provider by id. Alpaca reads `APCA_API_KEY_ID` and `APCA_API_SECRET_KEY` unless keys are passed. */
8
+ export function createProvider(id, options = {}) {
9
+ switch (id.toLowerCase()) {
10
+ case 'binance':
11
+ return new BinanceProvider(options);
12
+ case 'coinbase':
13
+ return new CoinbaseProvider(options);
14
+ case 'kraken':
15
+ return new KrakenProvider(options);
16
+ case 'alpaca':
17
+ return new AlpacaProvider(options);
18
+ default:
19
+ throw new InvalidArgumentError(`Unknown provider "${id}" (expected ${PROVIDER_IDS.join(', ')})`);
20
+ }
21
+ }
@@ -0,0 +1,30 @@
1
+ import { type InstrumentLike } from '../core/instrument.js';
2
+ import type { CandleQuery, Provider, ProviderCapabilities, RequestOptions } from '../core/provider.js';
3
+ import { type StreamOptions, type TickStream } from '../core/stream.js';
4
+ import type { Timeframe } from '../core/timeframe.js';
5
+ import type { Candle, Quote, Trade } from '../core/types.js';
6
+ import type { ProviderOptions } from './options.js';
7
+ /**
8
+ * Kraken Spot public market data (REST + WebSocket v2), no API key needed.
9
+ *
10
+ * Kraken's OHLC endpoint only returns the most recent 720 candles of each timeframe, whatever `from` is;
11
+ * older history is not available through it. Public REST calls are throttled per IP; the default
12
+ * client-side budget is 1 request per second with bursts of 3.
13
+ */
14
+ export declare class KrakenProvider implements Provider {
15
+ readonly id = "kraken";
16
+ readonly capabilities: ProviderCapabilities;
17
+ private readonly http;
18
+ private readonly clock;
19
+ private readonly wsUrl;
20
+ private readonly WebSocket;
21
+ constructor(options?: ProviderOptions);
22
+ nativeSymbol(input: InstrumentLike): string;
23
+ /** Kraken answers HTTP 200 with an `error` array; turn it into typed errors and return `result`. */
24
+ private call;
25
+ getCandles(input: InstrumentLike, timeframe: Timeframe, query?: CandleQuery): Promise<Candle[]>;
26
+ getQuote(input: InstrumentLike, options?: RequestOptions): Promise<Quote>;
27
+ private stream;
28
+ streamTrades(input: InstrumentLike, options?: StreamOptions): TickStream<Trade>;
29
+ streamCandles(input: InstrumentLike, timeframe: Timeframe, options?: StreamOptions): TickStream<Candle>;
30
+ }
@@ -0,0 +1,203 @@
1
+ import { systemClock } from '../core/clock.js';
2
+ import { NotSupportedError, ProviderError, RateLimitError } from '../core/errors.js';
3
+ import { HttpClient } from '../core/http.js';
4
+ import { instrument as toInstrument } from '../core/instrument.js';
5
+ import { RateLimiter } from '../core/rate-limiter.js';
6
+ import { createReconnectingStream } from '../core/stream.js';
7
+ import { isoMs, isRecord, num } from '../core/util.js';
8
+ import { collectCandles, normalizeCandles, resolveQuery } from './paging.js';
9
+ const ID = 'kraken';
10
+ const INTERVAL = { '1m': 1, '5m': 5, '15m': 15, '30m': 30, '1h': 60, '4h': 240, '1d': 1440, '1w': 10080, '15d': 21600 };
11
+ const TIMEFRAMES = Object.keys(INTERVAL);
12
+ const MAX_HISTORY = 720;
13
+ /**
14
+ * Kraken Spot public market data (REST + WebSocket v2), no API key needed.
15
+ *
16
+ * Kraken's OHLC endpoint only returns the most recent 720 candles of each timeframe, whatever `from` is;
17
+ * older history is not available through it. Public REST calls are throttled per IP; the default
18
+ * client-side budget is 1 request per second with bursts of 3.
19
+ */
20
+ export class KrakenProvider {
21
+ id = ID;
22
+ capabilities = {
23
+ candleTimeframes: TIMEFRAMES,
24
+ streamTimeframes: TIMEFRAMES,
25
+ candlesFromTrades: false,
26
+ maxHistoryCandles: MAX_HISTORY,
27
+ };
28
+ http;
29
+ clock;
30
+ wsUrl;
31
+ WebSocket;
32
+ constructor(options = {}) {
33
+ this.clock = options.clock ?? systemClock;
34
+ this.wsUrl = options.wsUrl ?? 'wss://ws.kraken.com/v2';
35
+ this.WebSocket = options.WebSocket;
36
+ this.http = new HttpClient({
37
+ provider: ID,
38
+ baseUrl: options.baseUrl ?? 'https://api.kraken.com',
39
+ limiter: new RateLimiter(options.rateLimit ?? { capacity: 3, refillPerSecond: 1 }, this.clock),
40
+ clock: this.clock,
41
+ ...(options.fetch ? { fetch: options.fetch } : {}),
42
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
43
+ ...(options.retries !== undefined ? { retries: options.retries } : {}),
44
+ mapError: (status, body) => {
45
+ const message = errorMessage(body);
46
+ return message && status !== 429 ? new ProviderError(`kraken: ${message}`, { provider: ID, status }) : undefined;
47
+ },
48
+ });
49
+ }
50
+ nativeSymbol(input) {
51
+ const inst = toInstrument(input);
52
+ if (inst.native)
53
+ return inst.native;
54
+ if (inst.assetClass !== 'crypto')
55
+ throw new NotSupportedError(`kraken: only crypto pairs are available (got ${inst.symbol})`, { provider: ID });
56
+ return `${inst.base}/${inst.quote}`;
57
+ }
58
+ /** Kraken answers HTTP 200 with an `error` array; turn it into typed errors and return `result`. */
59
+ async call(path, query, options = {}) {
60
+ const body = await this.http.get(path, query, options);
61
+ const message = errorMessage(body);
62
+ if (message) {
63
+ if (/rate limit|too many requests/i.test(message))
64
+ throw new RateLimitError(`kraken: ${message}`, { provider: ID });
65
+ throw new ProviderError(`kraken: ${message}`, { provider: ID, code: message.split(':')[0] ?? message });
66
+ }
67
+ if (!isRecord(body) || !isRecord(body.result))
68
+ throw new ProviderError('kraken: unexpected payload', { provider: ID });
69
+ return body.result;
70
+ }
71
+ async getCandles(input, timeframe, query = {}) {
72
+ const pair = this.nativeSymbol(input);
73
+ const interval = INTERVAL[timeframe];
74
+ if (interval === undefined) {
75
+ throw new NotSupportedError(`kraken: timeframe ${timeframe} is not supported (use ${TIMEFRAMES.join(', ')})`, { provider: ID });
76
+ }
77
+ const q = resolveQuery(query, this.clock.now());
78
+ // One response holds everything Kraken serves (the latest 720 candles): fetch it once per call.
79
+ let all;
80
+ const load = (signal) => (all ??= this.call('/0/public/OHLC', { pair, interval }, signal ? { signal } : {}).then((result) => {
81
+ const key = Object.keys(result).find((k) => k !== 'last');
82
+ const rows = key === undefined ? undefined : result[key];
83
+ if (!Array.isArray(rows))
84
+ throw new ProviderError('kraken: unexpected OHLC payload', { provider: ID });
85
+ const now = this.clock.now();
86
+ const step = interval * 60_000;
87
+ return normalizeCandles(rows.map((row) => {
88
+ // [time (s), open, high, low, close, vwap, volume, count]
89
+ if (!Array.isArray(row) || row.length < 7)
90
+ throw new ProviderError('kraken: unexpected OHLC row', { provider: ID });
91
+ const time = num(row[0], 'time', ID) * 1000;
92
+ return {
93
+ time,
94
+ open: num(row[1], 'open', ID),
95
+ high: num(row[2], 'high', ID),
96
+ low: num(row[3], 'low', ID),
97
+ close: num(row[4], 'close', ID),
98
+ volume: num(row[6], 'volume', ID),
99
+ closed: time + step <= now,
100
+ };
101
+ }));
102
+ }));
103
+ const candles = await collectCandles({
104
+ pageSize: MAX_HISTORY + 1, // 720 committed candles plus the running one
105
+ shortPageIsLast: { forward: true, backward: true },
106
+ forward: async (from, to, n, signal) => (await load(signal)).filter((c) => c.time >= from && c.time <= to).slice(0, n),
107
+ backward: async (to, n, signal) => (await load(signal)).filter((c) => c.time <= to).slice(-n),
108
+ }, q, query.signal);
109
+ return normalizeCandles(candles);
110
+ }
111
+ async getQuote(input, options = {}) {
112
+ const inst = toInstrument(input);
113
+ const result = await this.call('/0/public/Ticker', { pair: this.nativeSymbol(inst) }, options);
114
+ const t = Object.values(result)[0];
115
+ if (!isRecord(t) || !Array.isArray(t.a) || !Array.isArray(t.b) || !Array.isArray(t.c)) {
116
+ throw new ProviderError('kraken: unexpected ticker payload', { provider: ID });
117
+ }
118
+ return {
119
+ instrument: inst,
120
+ // The ticker carries no timestamp: local receive time.
121
+ time: this.clock.now(),
122
+ ask: num(t.a[0], 'ask', ID),
123
+ askSize: num(t.a[2], 'ask lot volume', ID),
124
+ bid: num(t.b[0], 'bid', ID),
125
+ bidSize: num(t.b[2], 'bid lot volume', ID),
126
+ last: num(t.c[0], 'last', ID),
127
+ };
128
+ }
129
+ stream(params, options, parse) {
130
+ const channel = params.channel;
131
+ return createReconnectingStream({
132
+ ...options,
133
+ provider: ID,
134
+ url: this.wsUrl,
135
+ clock: this.clock,
136
+ ...(this.WebSocket ? { WebSocket: this.WebSocket } : {}),
137
+ session: {
138
+ onOpen: (send) => send({ method: 'subscribe', params: { ...params, snapshot: false } }),
139
+ onMessage: (msg) => {
140
+ if (!isRecord(msg))
141
+ return [];
142
+ if (msg.method === 'subscribe' && msg.success === false) {
143
+ throw new ProviderError(`kraken: subscription rejected (${String(msg.error)})`, { provider: ID });
144
+ }
145
+ if (msg.channel !== channel || !Array.isArray(msg.data))
146
+ return [];
147
+ return parse(msg.data.filter(isRecord), String(msg.type));
148
+ },
149
+ },
150
+ });
151
+ }
152
+ streamTrades(input, options = {}) {
153
+ const inst = toInstrument(input);
154
+ const symbol = this.nativeSymbol(inst);
155
+ return this.stream({ channel: 'trade', symbol: [symbol] }, options, (data) => data
156
+ .filter((d) => d.symbol === symbol)
157
+ .map((d) => ({
158
+ instrument: inst,
159
+ id: String(d.trade_id),
160
+ time: isoMs(d.timestamp, 'timestamp', ID),
161
+ price: num(d.price, 'price', ID),
162
+ size: num(d.qty, 'qty', ID),
163
+ ...(d.side === 'buy' || d.side === 'sell' ? { side: d.side } : {}),
164
+ })));
165
+ }
166
+ streamCandles(input, timeframe, options = {}) {
167
+ const symbol = this.nativeSymbol(input);
168
+ const interval = INTERVAL[timeframe];
169
+ if (interval === undefined) {
170
+ throw new NotSupportedError(`kraken: timeframe ${timeframe} is not supported (use ${TIMEFRAMES.join(', ')})`, { provider: ID });
171
+ }
172
+ // Kraken pushes the running candle on every change; a new period start closes the previous one.
173
+ let last;
174
+ return this.stream({ channel: 'ohlc', symbol: [symbol], interval }, options, (data) => {
175
+ const out = [];
176
+ for (const d of data) {
177
+ if (d.symbol !== symbol || num(d.interval, 'interval', ID) !== interval)
178
+ continue;
179
+ const candle = {
180
+ time: isoMs(d.interval_begin, 'interval_begin', ID),
181
+ open: num(d.open, 'open', ID),
182
+ high: num(d.high, 'high', ID),
183
+ low: num(d.low, 'low', ID),
184
+ close: num(d.close, 'close', ID),
185
+ volume: num(d.volume, 'volume', ID),
186
+ closed: false,
187
+ };
188
+ if (last && candle.time < last.time)
189
+ continue;
190
+ if (last && candle.time > last.time)
191
+ out.push({ ...last, closed: true });
192
+ last = candle;
193
+ out.push(candle);
194
+ }
195
+ return out;
196
+ });
197
+ }
198
+ }
199
+ function errorMessage(body) {
200
+ if (isRecord(body) && Array.isArray(body.error) && body.error.length > 0)
201
+ return body.error.map(String).join('; ');
202
+ return undefined;
203
+ }
@@ -0,0 +1,22 @@
1
+ import type { Clock } from '../core/clock.js';
2
+ import type { FetchLike } from '../core/http.js';
3
+ import type { RateLimitOptions } from '../core/rate-limiter.js';
4
+ import type { WebSocketConstructor } from '../core/stream.js';
5
+ export interface ProviderOptions {
6
+ /** REST base URL override (for a regional endpoint, a proxy, or tests). */
7
+ baseUrl?: string;
8
+ /** WebSocket base URL override. */
9
+ wsUrl?: string;
10
+ /** `fetch` implementation (default: global `fetch`). */
11
+ fetch?: FetchLike;
12
+ /** WebSocket implementation (default: global `WebSocket`, Node 22+). */
13
+ WebSocket?: WebSocketConstructor;
14
+ /** Client-side rate limit, in the provider's weight units. Defaults stay below the documented limits. */
15
+ rateLimit?: RateLimitOptions;
16
+ /** Per-request timeout in ms (default 10 000). */
17
+ timeoutMs?: number;
18
+ /** Retries on network errors, 5xx and 429 (default 2). */
19
+ retries?: number;
20
+ /** Clock override, for tests. */
21
+ clock?: Clock;
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import type { CandleQuery } from '../core/provider.js';
2
+ import type { Candle } from '../core/types.js';
3
+ export declare const DEFAULT_LIMIT = 500;
4
+ export declare const MAX_CANDLES = 50000;
5
+ export interface PageFetcher {
6
+ /** Largest page the provider returns. */
7
+ pageSize: number;
8
+ /** Candles with `from <= time <= to`, ascending, at most `n`, starting at `from`. */
9
+ forward(from: number, to: number, n: number, signal?: AbortSignal): Promise<Candle[]>;
10
+ /** The latest candles with `time <= to`, ascending, at most `n`. */
11
+ backward(to: number, n: number, signal?: AbortSignal): Promise<Candle[]>;
12
+ /**
13
+ * `true` when a page shorter than requested proves there is nothing more in that direction
14
+ * (count-based APIs). Window-based APIs (Coinbase) leave it unset.
15
+ */
16
+ shortPageIsLast?: {
17
+ forward: boolean;
18
+ backward: boolean;
19
+ };
20
+ }
21
+ export interface ResolvedQuery {
22
+ from?: number;
23
+ to: number;
24
+ limit: number;
25
+ }
26
+ export declare function resolveQuery(query: CandleQuery, now: number): ResolvedQuery;
27
+ /** Walk pages until the range or the limit is covered. Returns ascending, de-duplicated candles. */
28
+ export declare function collectCandles(fetcher: PageFetcher, q: ResolvedQuery, signal?: AbortSignal): Promise<Candle[]>;
29
+ /** Sort ascending and drop duplicate open times (keeps the last one seen). */
30
+ export declare function normalizeCandles(candles: Candle[]): Candle[];
@@ -0,0 +1,59 @@
1
+ import { InvalidArgumentError } from '../core/errors.js';
2
+ import { toMs } from '../core/util.js';
3
+ export const DEFAULT_LIMIT = 500;
4
+ export const MAX_CANDLES = 50_000;
5
+ export function resolveQuery(query, now) {
6
+ const to = query.to === undefined ? now : toMs(query.to, 'to');
7
+ const from = query.from === undefined ? undefined : toMs(query.from, 'from');
8
+ if (from !== undefined && from > to)
9
+ throw new InvalidArgumentError('`from` must be before `to`');
10
+ if (query.limit !== undefined && !(Number.isInteger(query.limit) && query.limit > 0)) {
11
+ throw new InvalidArgumentError('`limit` must be a positive integer');
12
+ }
13
+ const limit = Math.min(query.limit ?? (from === undefined ? DEFAULT_LIMIT : MAX_CANDLES), MAX_CANDLES);
14
+ return from === undefined ? { to, limit } : { from, to, limit };
15
+ }
16
+ /** Walk pages until the range or the limit is covered. Returns ascending, de-duplicated candles. */
17
+ export async function collectCandles(fetcher, q, signal) {
18
+ const out = [];
19
+ if (q.from !== undefined) {
20
+ let cursor = q.from;
21
+ while (out.length < q.limit) {
22
+ signal?.throwIfAborted();
23
+ const n = Math.min(fetcher.pageSize, q.limit - out.length);
24
+ const page = (await fetcher.forward(cursor, q.to, n, signal)).filter((c) => c.time >= cursor && c.time <= q.to);
25
+ if (page.length === 0)
26
+ break;
27
+ out.push(...page);
28
+ const last = page[page.length - 1].time;
29
+ if (last >= q.to || (fetcher.shortPageIsLast?.forward && page.length < n))
30
+ break;
31
+ cursor = last + 1;
32
+ }
33
+ return out.slice(0, q.limit);
34
+ }
35
+ const chunks = [];
36
+ let count = 0;
37
+ let cursor = q.to;
38
+ while (count < q.limit) {
39
+ signal?.throwIfAborted();
40
+ const n = Math.min(fetcher.pageSize, q.limit - count);
41
+ const page = (await fetcher.backward(cursor, n, signal)).filter((c) => c.time <= cursor);
42
+ if (page.length === 0)
43
+ break;
44
+ chunks.unshift(page);
45
+ count += page.length;
46
+ cursor = page[0].time - 1;
47
+ if (fetcher.shortPageIsLast?.backward && page.length < n)
48
+ break;
49
+ }
50
+ const all = chunks.flat();
51
+ return all.slice(Math.max(0, all.length - q.limit));
52
+ }
53
+ /** Sort ascending and drop duplicate open times (keeps the last one seen). */
54
+ export function normalizeCandles(candles) {
55
+ const byTime = new Map();
56
+ for (const c of candles)
57
+ byTime.set(c.time, c);
58
+ return [...byTime.values()].sort((a, b) => a.time - b.time);
59
+ }
@@ -0,0 +1,32 @@
1
+ import type { Timeframe } from '../core/timeframe.js';
2
+ import type { Candle } from '../core/types.js';
3
+ export interface Gap {
4
+ /** Open time of the first missing period. */
5
+ from: number;
6
+ /** Open time of the last missing period. */
7
+ to: number;
8
+ /** Number of missing periods. */
9
+ missing: number;
10
+ }
11
+ export interface SeriesReport {
12
+ count: number;
13
+ first?: number;
14
+ last?: number;
15
+ /** Periods with no candle between two candles. Normal for stocks outside market hours and for illiquid pairs. */
16
+ gaps: Gap[];
17
+ /** Open times present more than once. */
18
+ duplicates: number[];
19
+ /** `true` when the candles were not in ascending time order. */
20
+ unordered: boolean;
21
+ /** Candles that are not aligned on the timeframe grid (open time not reached by stepping from the first). */
22
+ misaligned: number[];
23
+ /** Candles still forming (`closed: false`) anywhere but last. */
24
+ formingInside: number[];
25
+ }
26
+ /** Inspect a candle series for gaps, duplicates, ordering and alignment problems. */
27
+ export declare function checkCandles(candles: readonly Candle[], timeframe: Timeframe): SeriesReport;
28
+ /**
29
+ * Sort ascending and keep one candle per open time: a closed candle wins over a forming one,
30
+ * otherwise the last one seen wins. Gaps cannot be invented; refetch them (see `loadCandles`).
31
+ */
32
+ export declare function cleanCandles(candles: Iterable<Candle>): Candle[];
@@ -0,0 +1,63 @@
1
+ import { nextPeriod } from './time.js';
2
+ const MAX_GAP_STEPS = 1_000_000;
3
+ /** Inspect a candle series for gaps, duplicates, ordering and alignment problems. */
4
+ export function checkCandles(candles, timeframe) {
5
+ const seen = new Set();
6
+ const duplicates = new Set();
7
+ let unordered = false;
8
+ const formingInside = [];
9
+ candles.forEach((c, i) => {
10
+ if (seen.has(c.time))
11
+ duplicates.add(c.time);
12
+ seen.add(c.time);
13
+ if (i > 0 && c.time < candles[i - 1].time)
14
+ unordered = true;
15
+ if (!c.closed && i < candles.length - 1)
16
+ formingInside.push(c.time);
17
+ });
18
+ const times = [...seen].sort((a, b) => a - b);
19
+ const gaps = [];
20
+ const misaligned = [];
21
+ for (let i = 1; i < times.length; i++) {
22
+ const prev = times[i - 1];
23
+ const cur = times[i];
24
+ let t = nextPeriod(prev, timeframe);
25
+ let missing = 0;
26
+ let first = t;
27
+ let last = t;
28
+ while (t < cur && missing < MAX_GAP_STEPS) {
29
+ if (missing === 0)
30
+ first = t;
31
+ last = t;
32
+ missing++;
33
+ t = nextPeriod(t, timeframe);
34
+ }
35
+ if (t !== cur)
36
+ misaligned.push(cur);
37
+ if (missing > 0)
38
+ gaps.push({ from: first, to: last, missing });
39
+ }
40
+ return {
41
+ count: candles.length,
42
+ ...(times.length ? { first: times[0], last: times[times.length - 1] } : {}),
43
+ gaps,
44
+ duplicates: [...duplicates].sort((a, b) => a - b),
45
+ unordered,
46
+ misaligned,
47
+ formingInside,
48
+ };
49
+ }
50
+ /**
51
+ * Sort ascending and keep one candle per open time: a closed candle wins over a forming one,
52
+ * otherwise the last one seen wins. Gaps cannot be invented; refetch them (see `loadCandles`).
53
+ */
54
+ export function cleanCandles(candles) {
55
+ const byTime = new Map();
56
+ for (const c of candles) {
57
+ const prev = byTime.get(c.time);
58
+ if (prev && prev.closed && !c.closed)
59
+ continue;
60
+ byTime.set(c.time, c);
61
+ }
62
+ return [...byTime.values()].sort((a, b) => a.time - b.time);
63
+ }
@@ -0,0 +1,31 @@
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, TickStream } from '../core/stream.js';
5
+ import type { Timeframe } from '../core/timeframe.js';
6
+ import type { Candle } from '../core/types.js';
7
+ import type { TimeInput } from '../core/util.js';
8
+ import type { CandleStore } from './store.js';
9
+ import { type Duration } from './time.js';
10
+ export interface LiveCandlesOptions extends Omit<StreamOptions, 'signal'> {
11
+ provider: Provider;
12
+ instrument: InstrumentLike;
13
+ timeframe: Timeframe;
14
+ /** History to emit before going live: a number of candles (default 200), a duration (`3d`) or a start time. */
15
+ history?: TimeInput | Duration | number;
16
+ /** Cache for the history and for every candle that closes while live. */
17
+ store?: CandleStore;
18
+ /** Called once the history has been emitted, before the first live candle. */
19
+ onHistoryEnd?: (count: number) => void;
20
+ signal?: AbortSignal;
21
+ clock?: Clock;
22
+ }
23
+ /**
24
+ * One continuous candle series: closed history first, then live updates, with no gap and no overlap at the seam.
25
+ *
26
+ * - Every closed candle is emitted once, in ascending order (`closed: true`).
27
+ * - Forming candles (`closed: false`) are emitted on each update, between the closed ones.
28
+ * - When the live feed skips periods (reconnection, missed close), they are fetched from the provider's
29
+ * history API and emitted before going on. Periods the provider has no candle for stay absent.
30
+ */
31
+ export declare function liveCandles(options: LiveCandlesOptions): TickStream<Candle>;
@@ -0,0 +1,121 @@
1
+ import { systemClock } from '../core/clock.js';
2
+ import { instrument as toInstrument } from '../core/instrument.js';
3
+ import { loadCandles } from './load.js';
4
+ import { nextPeriod, periodFloor, resolveTime } from './time.js';
5
+ /**
6
+ * One continuous candle series: closed history first, then live updates, with no gap and no overlap at the seam.
7
+ *
8
+ * - Every closed candle is emitted once, in ascending order (`closed: true`).
9
+ * - Forming candles (`closed: false`) are emitted on each update, between the closed ones.
10
+ * - When the live feed skips periods (reconnection, missed close), they are fetched from the provider's
11
+ * history API and emitted before going on. Periods the provider has no candle for stay absent.
12
+ */
13
+ export function liveCandles(options) {
14
+ const { provider, timeframe, store } = options;
15
+ const clock = options.clock ?? systemClock;
16
+ const inst = toInstrument(options.instrument);
17
+ const controller = new AbortController();
18
+ const onAbort = () => close();
19
+ options.signal?.addEventListener('abort', onAbort, { once: true });
20
+ const signal = controller.signal;
21
+ const { provider: _p, instrument: _i, timeframe: _t, history: _h, store: _s, signal: _sig, clock: _c, onHistoryEnd, ...streamOptions } = options;
22
+ const live = provider.streamCandles(inst, timeframe, { ...streamOptions, signal });
23
+ const key = { provider: provider.id, symbol: inst.symbol, timeframe };
24
+ let finished = false;
25
+ const historyFrom = (now) => {
26
+ const h = options.history ?? 200;
27
+ if (typeof h === 'number' && h < 1e9) {
28
+ let t = periodFloor(now, timeframe);
29
+ for (let i = 0; i < h; i++)
30
+ t = periodFloor(t - 1, timeframe);
31
+ return t;
32
+ }
33
+ return resolveTime(h, now);
34
+ };
35
+ async function* run() {
36
+ const iterator = live[Symbol.asyncIterator]();
37
+ // The feed is already connecting while the history loads; its first messages are buffered.
38
+ const history = await loadCandles({
39
+ provider,
40
+ instrument: inst,
41
+ timeframe,
42
+ from: historyFrom(clock.now()),
43
+ clock,
44
+ signal,
45
+ ...(store ? { store } : {}),
46
+ });
47
+ let lastClosed;
48
+ for (const c of history) {
49
+ yield c;
50
+ lastClosed = c.time;
51
+ }
52
+ onHistoryEnd?.(history.length);
53
+ const fill = async function* (until) {
54
+ if (lastClosed === undefined)
55
+ return;
56
+ const from = nextPeriod(lastClosed, timeframe);
57
+ if (from >= until)
58
+ return;
59
+ const missing = await provider.getCandles(inst, timeframe, { from, to: until - 1, limit: 50_000, signal });
60
+ const closed = missing.filter((c) => c.closed && c.time >= from && c.time < until);
61
+ if (store && closed.length)
62
+ await store.append(key, closed, [[from, until - 1]]);
63
+ for (const c of closed) {
64
+ yield c;
65
+ lastClosed = c.time;
66
+ }
67
+ };
68
+ while (!finished) {
69
+ const { value: c, done } = await iterator.next();
70
+ if (done)
71
+ return;
72
+ if (lastClosed !== undefined && c.time <= lastClosed)
73
+ continue;
74
+ yield* fill(c.time);
75
+ if (c.closed) {
76
+ if (store)
77
+ await store.append(key, [c], [[c.time, nextPeriod(c.time, timeframe) - 1]]);
78
+ lastClosed = c.time;
79
+ }
80
+ yield c;
81
+ }
82
+ }
83
+ const gen = run();
84
+ const close = () => {
85
+ if (finished)
86
+ return;
87
+ finished = true;
88
+ options.signal?.removeEventListener('abort', onAbort);
89
+ controller.abort();
90
+ live.close();
91
+ };
92
+ if (options.signal?.aborted)
93
+ close();
94
+ return {
95
+ [Symbol.asyncIterator]: () => ({
96
+ next: async () => {
97
+ try {
98
+ const r = await gen.next();
99
+ if (r.done)
100
+ close();
101
+ return r;
102
+ }
103
+ catch (error) {
104
+ close();
105
+ if (signal.aborted && finished)
106
+ return { value: undefined, done: true };
107
+ throw error;
108
+ }
109
+ },
110
+ return: async () => {
111
+ close();
112
+ await gen.return(undefined);
113
+ return { value: undefined, done: true };
114
+ },
115
+ }),
116
+ close,
117
+ get closed() {
118
+ return finished;
119
+ },
120
+ };
121
+ }
@@ -0,0 +1,35 @@
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 Timeframe } from '../core/timeframe.js';
5
+ import type { Candle } from '../core/types.js';
6
+ import type { TimeInput } from '../core/util.js';
7
+ import { type CandleStore } from './store.js';
8
+ import { type Duration } from './time.js';
9
+ export interface LoadCandlesOptions {
10
+ provider: Provider;
11
+ instrument: InstrumentLike;
12
+ timeframe: Timeframe;
13
+ /** Start: a time, or a duration back from now (`7d`, `6mo`). */
14
+ from: TimeInput | Duration;
15
+ /** End (default: now). */
16
+ to?: TimeInput | Duration;
17
+ /** Keep closed candles here and only fetch what is missing. Without it, everything is fetched. */
18
+ store?: CandleStore;
19
+ /** Append the candle still forming, when the range reaches it (default false). */
20
+ forming?: boolean;
21
+ /** Called for each range actually requested from the provider. */
22
+ onFetch?: (range: {
23
+ from: number;
24
+ to: number;
25
+ candles: number;
26
+ }) => void;
27
+ signal?: AbortSignal;
28
+ clock?: Clock;
29
+ }
30
+ /**
31
+ * Closed candles over a range, ascending, without duplicates. With a `store`, closed candles are kept
32
+ * and later calls only fetch the ranges never fetched before; a range the provider has no data for
33
+ * (before listing, outside its history limit) is remembered as fetched too.
34
+ */
35
+ export declare function loadCandles(options: LoadCandlesOptions): Promise<Candle[]>;