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,227 @@
1
+ import { systemClock } from '../core/clock.js';
2
+ import { AuthenticationError, NotSupportedError, ProviderError } 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 { parseTimeframe } from '../core/timeframe.js';
8
+ import { isoMs, isRecord, num } from '../core/util.js';
9
+ import { collectCandles, normalizeCandles, resolveQuery } from './paging.js';
10
+ const ID = 'alpaca';
11
+ const COMMON_TIMEFRAMES = ['1m', '5m', '15m', '30m', '1h', '2h', '4h', '1d', '1w', '1M'];
12
+ const PAGE = 10_000;
13
+ const EARLIEST = Date.UTC(2015, 0, 1);
14
+ /** Alpaca timeframe string for a tickwire timeframe (`5m` → `5Min`), or undefined if Alpaca has no equivalent. */
15
+ export function alpacaTimeframe(timeframe) {
16
+ const match = /^([1-9]\d*)([mhdwM])$/.exec(timeframe);
17
+ if (!match)
18
+ return undefined;
19
+ const n = Number(match[1]);
20
+ switch (match[2]) {
21
+ case 'm':
22
+ return n <= 59 ? `${n}Min` : undefined;
23
+ case 'h':
24
+ return n <= 23 ? `${n}Hour` : undefined;
25
+ case 'd':
26
+ return n === 1 ? '1Day' : undefined;
27
+ case 'w':
28
+ return n === 1 ? '1Week' : undefined;
29
+ case 'M':
30
+ return [1, 2, 3, 4, 6, 12].includes(n) ? `${n}Month` : undefined;
31
+ default:
32
+ return undefined;
33
+ }
34
+ }
35
+ /**
36
+ * Alpaca Market Data API v2 for US stocks. Needs a free Alpaca account and API key
37
+ * (`APCA_API_KEY_ID` / `APCA_API_SECRET_KEY`). The free plan serves the IEX feed and allows
38
+ * 200 requests per minute; the default client-side budget is 180 per minute. The free plan also allows
39
+ * a single WebSocket connection at a time: run one stream per account.
40
+ */
41
+ export class AlpacaProvider {
42
+ id = ID;
43
+ capabilities = {
44
+ candleTimeframes: COMMON_TIMEFRAMES,
45
+ streamTimeframes: ['1m'],
46
+ candlesFromTrades: false,
47
+ };
48
+ http;
49
+ clock;
50
+ wsUrl;
51
+ WebSocket;
52
+ keyId;
53
+ secretKey;
54
+ feed;
55
+ adjustment;
56
+ constructor(options = {}) {
57
+ const env = typeof process !== 'undefined' ? process.env : {};
58
+ this.keyId = options.keyId ?? env.APCA_API_KEY_ID;
59
+ this.secretKey = options.secretKey ?? env.APCA_API_SECRET_KEY;
60
+ this.feed = options.feed ?? 'iex';
61
+ this.adjustment = options.adjustment ?? 'raw';
62
+ this.clock = options.clock ?? systemClock;
63
+ this.wsUrl = (options.wsUrl ?? 'wss://stream.data.alpaca.markets/v2').replace(/\/$/, '');
64
+ this.WebSocket = options.WebSocket;
65
+ this.http = new HttpClient({
66
+ provider: ID,
67
+ baseUrl: options.baseUrl ?? 'https://data.alpaca.markets',
68
+ limiter: new RateLimiter(options.rateLimit ?? { capacity: 10, refillPerSecond: 3 }, this.clock),
69
+ clock: this.clock,
70
+ ...(options.fetch ? { fetch: options.fetch } : {}),
71
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
72
+ ...(options.retries !== undefined ? { retries: options.retries } : {}),
73
+ mapError: (status, body) => {
74
+ const message = isRecord(body) && typeof body.message === 'string' ? body.message : typeof body === 'string' ? body.trim().slice(0, 120) : undefined;
75
+ if (status === 401 || status === 403) {
76
+ return new AuthenticationError(`alpaca: credentials rejected (HTTP ${status}${message ? `: ${message}` : ''})`, { provider: ID });
77
+ }
78
+ if (status !== 429 && message)
79
+ return new ProviderError(`alpaca: ${message}`, { provider: ID, status });
80
+ return undefined;
81
+ },
82
+ });
83
+ }
84
+ credentials() {
85
+ if (!this.keyId || !this.secretKey) {
86
+ throw new AuthenticationError('alpaca: missing API key. Set APCA_API_KEY_ID and APCA_API_SECRET_KEY, or pass keyId and secretKey.', { provider: ID });
87
+ }
88
+ return { 'APCA-API-KEY-ID': this.keyId, 'APCA-API-SECRET-KEY': this.secretKey };
89
+ }
90
+ nativeSymbol(input) {
91
+ const inst = toInstrument(input);
92
+ if (inst.native)
93
+ return inst.native;
94
+ if (inst.assetClass !== 'stock')
95
+ throw new NotSupportedError(`alpaca: only US stocks are supported in tickwire 0.1 (got ${inst.symbol})`, { provider: ID });
96
+ return inst.base;
97
+ }
98
+ async getCandles(input, timeframe, query = {}) {
99
+ const symbol = this.nativeSymbol(input);
100
+ const tf = alpacaTimeframe(timeframe);
101
+ if (!tf)
102
+ throw new NotSupportedError(`alpaca: timeframe ${timeframe} is not supported`, { provider: ID });
103
+ const headers = this.credentials();
104
+ const step = parseTimeframe(timeframe).ms;
105
+ const q = resolveQuery(query, this.clock.now());
106
+ // Alpaca pages with next_page_token inside one [start, end] window.
107
+ const fetchBars = async (start, end, n, sort, signal) => {
108
+ const out = [];
109
+ let pageToken;
110
+ do {
111
+ const body = await this.http.get(`/v2/stocks/${encodeURIComponent(symbol)}/bars`, {
112
+ timeframe: tf,
113
+ start: new Date(start).toISOString(),
114
+ end: new Date(end).toISOString(),
115
+ limit: Math.min(PAGE, n - out.length),
116
+ feed: this.feed,
117
+ adjustment: this.adjustment,
118
+ sort,
119
+ page_token: pageToken,
120
+ }, { headers, ...(signal ? { signal } : {}) });
121
+ if (!isRecord(body))
122
+ throw new ProviderError('alpaca: unexpected bars payload', { provider: ID });
123
+ const now = this.clock.now();
124
+ for (const bar of Array.isArray(body.bars) ? body.bars : [])
125
+ out.push(parseBar(bar, step, now));
126
+ pageToken = typeof body.next_page_token === 'string' && body.next_page_token ? body.next_page_token : undefined;
127
+ } while (pageToken && out.length < n);
128
+ return normalizeCandles(out);
129
+ };
130
+ const candles = await collectCandles({
131
+ pageSize: PAGE,
132
+ // Forward pages cover the whole [from, to] window; backward pages are window-limited.
133
+ shortPageIsLast: { forward: true, backward: false },
134
+ forward: (from, to, n, signal) => fetchBars(from, to, n, 'asc', signal),
135
+ backward: async (to, n, signal) => {
136
+ // Markets are closed most of the time: look back well beyond n periods.
137
+ const start = Math.max(EARLIEST, to - n * step * 5 - 7 * 86_400_000);
138
+ if (start >= to)
139
+ return [];
140
+ return (await fetchBars(start, to, n, 'desc', signal)).slice(-n);
141
+ },
142
+ }, q, query.signal);
143
+ return normalizeCandles(candles);
144
+ }
145
+ async getQuote(input, options = {}) {
146
+ const inst = toInstrument(input);
147
+ const body = await this.http.get(`/v2/stocks/${encodeURIComponent(this.nativeSymbol(inst))}/snapshot`, { feed: this.feed }, { headers: this.credentials(), ...options });
148
+ if (!isRecord(body) || !isRecord(body.latestQuote))
149
+ throw new ProviderError('alpaca: unexpected snapshot payload', { provider: ID });
150
+ const quote = body.latestQuote;
151
+ const trade = isRecord(body.latestTrade) ? body.latestTrade : undefined;
152
+ return {
153
+ instrument: inst,
154
+ time: isoMs(quote.t, 'quote time', ID),
155
+ bid: num(quote.bp, 'bid', ID),
156
+ bidSize: num(quote.bs, 'bid size', ID),
157
+ ask: num(quote.ap, 'ask', ID),
158
+ askSize: num(quote.as, 'ask size', ID),
159
+ ...(trade ? { last: num(trade.p, 'last', ID) } : {}),
160
+ };
161
+ }
162
+ stream(channel, symbol, options, parse) {
163
+ const { 'APCA-API-KEY-ID': key, 'APCA-API-SECRET-KEY': secret } = this.credentials();
164
+ return createReconnectingStream({
165
+ // Alpaca sends nothing while the market is closed.
166
+ idleTimeoutMs: 0,
167
+ ...options,
168
+ provider: ID,
169
+ url: `${this.wsUrl}/${this.feed}`,
170
+ clock: this.clock,
171
+ ...(this.WebSocket ? { WebSocket: this.WebSocket } : {}),
172
+ session: {
173
+ onOpen: () => undefined,
174
+ onMessage: (batch, send) => {
175
+ const out = [];
176
+ for (const msg of Array.isArray(batch) ? batch : [batch]) {
177
+ if (!isRecord(msg))
178
+ continue;
179
+ if (msg.T === 'success' && msg.msg === 'connected')
180
+ send({ action: 'auth', key, secret });
181
+ else if (msg.T === 'success' && msg.msg === 'authenticated')
182
+ send({ action: 'subscribe', [channel]: [symbol] });
183
+ else if (msg.T === 'error') {
184
+ const code = Number(msg.code);
185
+ const text = `alpaca: ${String(msg.msg)} (code ${String(msg.code)})`;
186
+ throw code === 401 || code === 402 || code === 403
187
+ ? new AuthenticationError(text, { provider: ID })
188
+ : new ProviderError(text, { provider: ID, code: String(msg.code) });
189
+ }
190
+ else
191
+ out.push(...parse(msg));
192
+ }
193
+ return out;
194
+ },
195
+ },
196
+ });
197
+ }
198
+ streamTrades(input, options = {}) {
199
+ const inst = toInstrument(input);
200
+ const symbol = this.nativeSymbol(inst);
201
+ return this.stream('trades', symbol, options, (m) => m.T === 't' && m.S === symbol
202
+ ? [{ instrument: inst, id: String(m.i), time: isoMs(m.t, 'time', ID), price: num(m.p, 'price', ID), size: num(m.s, 'size', ID) }]
203
+ : []);
204
+ }
205
+ streamCandles(input, timeframe, options = {}) {
206
+ if (timeframe !== '1m') {
207
+ throw new NotSupportedError('alpaca: the bar stream only carries 1-minute bars (aggregate them, or stream trades with CandleBuilder)', { provider: ID });
208
+ }
209
+ const symbol = this.nativeSymbol(input);
210
+ // `b` = minute bar when the minute is over; `u` = late correction of a bar already sent.
211
+ return this.stream('bars', symbol, options, (m) => (m.T === 'b' || m.T === 'u') && m.S === symbol ? [{ ...parseBar(m, 0, Infinity), closed: true }] : []);
212
+ }
213
+ }
214
+ function parseBar(bar, step, now) {
215
+ if (!isRecord(bar))
216
+ throw new ProviderError('alpaca: unexpected bar', { provider: ID });
217
+ const time = isoMs(bar.t, 'bar time', ID);
218
+ return {
219
+ time,
220
+ open: num(bar.o, 'open', ID),
221
+ high: num(bar.h, 'high', ID),
222
+ low: num(bar.l, 'low', ID),
223
+ close: num(bar.c, 'close', ID),
224
+ volume: num(bar.v, 'volume', ID),
225
+ closed: time + step <= now,
226
+ };
227
+ }
@@ -0,0 +1,31 @@
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
+ * Binance Spot public market data (REST + WebSocket streams), no API key needed.
9
+ *
10
+ * Binance limits REST usage to 6 000 request weight per minute per IP; the default client-side budget is
11
+ * half of that. Binance is not available in every country: residents of the United States should use
12
+ * Binance.US through `baseUrl: 'https://api.binance.us'` and `wsUrl: 'wss://stream.binance.us:9443'`,
13
+ * within Binance.US terms.
14
+ */
15
+ export declare class BinanceProvider implements Provider {
16
+ readonly id = "binance";
17
+ readonly capabilities: ProviderCapabilities;
18
+ private readonly http;
19
+ private readonly clock;
20
+ private readonly wsUrl;
21
+ private readonly WebSocket;
22
+ constructor(options?: ProviderOptions);
23
+ nativeSymbol(input: InstrumentLike): string;
24
+ private checkTimeframe;
25
+ getCandles(input: InstrumentLike, timeframe: Timeframe, query?: CandleQuery): Promise<Candle[]>;
26
+ private parseKline;
27
+ getQuote(input: InstrumentLike, options?: RequestOptions): Promise<Quote>;
28
+ private stream;
29
+ streamTrades(input: InstrumentLike, options?: StreamOptions): TickStream<Trade>;
30
+ streamCandles(input: InstrumentLike, timeframe: Timeframe, options?: StreamOptions): TickStream<Candle>;
31
+ }
@@ -0,0 +1,187 @@
1
+ import { systemClock } from '../core/clock.js';
2
+ import { InvalidArgumentError, NotSupportedError, ProviderError, RateLimitError } from '../core/errors.js';
3
+ import { HttpClient, retryAfterMs } 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 { isRecord, num } from '../core/util.js';
8
+ import { collectCandles, normalizeCandles, resolveQuery } from './paging.js';
9
+ const ID = 'binance';
10
+ const TIMEFRAMES = ['1s', '1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '3d', '1w', '1M'];
11
+ /** Weights from the Binance Spot API docs (GET /api/v3/klines and /api/v3/ticker/24hr for one symbol). */
12
+ const KLINES_WEIGHT = 2;
13
+ const TICKER_WEIGHT = 2;
14
+ /**
15
+ * Binance Spot public market data (REST + WebSocket streams), no API key needed.
16
+ *
17
+ * Binance limits REST usage to 6 000 request weight per minute per IP; the default client-side budget is
18
+ * half of that. Binance is not available in every country: residents of the United States should use
19
+ * Binance.US through `baseUrl: 'https://api.binance.us'` and `wsUrl: 'wss://stream.binance.us:9443'`,
20
+ * within Binance.US terms.
21
+ */
22
+ export class BinanceProvider {
23
+ id = ID;
24
+ capabilities = {
25
+ candleTimeframes: TIMEFRAMES,
26
+ streamTimeframes: TIMEFRAMES,
27
+ candlesFromTrades: false,
28
+ };
29
+ http;
30
+ clock;
31
+ wsUrl;
32
+ WebSocket;
33
+ constructor(options = {}) {
34
+ this.clock = options.clock ?? systemClock;
35
+ this.wsUrl = (options.wsUrl ?? 'wss://stream.binance.com:9443').replace(/\/$/, '');
36
+ this.WebSocket = options.WebSocket;
37
+ this.http = new HttpClient({
38
+ provider: ID,
39
+ baseUrl: options.baseUrl ?? 'https://api.binance.com',
40
+ limiter: new RateLimiter(options.rateLimit ?? { capacity: 1_000, refillPerSecond: 50 }, this.clock),
41
+ clock: this.clock,
42
+ ...(options.fetch ? { fetch: options.fetch } : {}),
43
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
44
+ ...(options.retries !== undefined ? { retries: options.retries } : {}),
45
+ mapError: (status, body, headers) => {
46
+ const after = retryAfterMs(headers);
47
+ if (status === 418) {
48
+ return new RateLimitError('binance: IP banned for exceeding rate limits (HTTP 418)', {
49
+ provider: ID,
50
+ retryAfterMs: Infinity,
51
+ });
52
+ }
53
+ if (status === 429) {
54
+ return new RateLimitError('binance: rate limited (HTTP 429)', { provider: ID, ...(after !== undefined ? { retryAfterMs: after } : {}) });
55
+ }
56
+ if (isRecord(body) && typeof body.msg === 'string') {
57
+ return new ProviderError(`binance: ${body.msg}`, { provider: ID, status, code: String(body.code) });
58
+ }
59
+ return undefined;
60
+ },
61
+ });
62
+ }
63
+ nativeSymbol(input) {
64
+ const inst = toInstrument(input);
65
+ if (inst.native)
66
+ return inst.native;
67
+ if (inst.assetClass !== 'crypto')
68
+ throw new NotSupportedError(`binance: only crypto pairs are available (got ${inst.symbol})`, { provider: ID });
69
+ return `${inst.base}${inst.quote}`;
70
+ }
71
+ checkTimeframe(timeframe) {
72
+ if (!TIMEFRAMES.includes(timeframe)) {
73
+ throw new NotSupportedError(`binance: timeframe ${timeframe} is not supported (use ${TIMEFRAMES.join(', ')})`, { provider: ID });
74
+ }
75
+ return timeframe;
76
+ }
77
+ async getCandles(input, timeframe, query = {}) {
78
+ const symbol = this.nativeSymbol(input);
79
+ const interval = this.checkTimeframe(timeframe);
80
+ const q = resolveQuery(query, this.clock.now());
81
+ const fetchPage = async (params, signal) => {
82
+ const rows = await this.http.get('/api/v3/klines', { symbol, interval, ...params }, { weight: KLINES_WEIGHT, ...(signal ? { signal } : {}) });
83
+ if (!Array.isArray(rows))
84
+ throw new ProviderError('binance: unexpected klines payload', { provider: ID });
85
+ const now = this.clock.now();
86
+ return rows.map((row) => this.parseKline(row, now));
87
+ };
88
+ const candles = await collectCandles({
89
+ pageSize: 1000,
90
+ shortPageIsLast: { forward: true, backward: true },
91
+ forward: (from, to, n, signal) => fetchPage({ startTime: from, endTime: to, limit: n }, signal),
92
+ backward: (to, n, signal) => fetchPage({ endTime: to, limit: n }, signal),
93
+ }, q, query.signal);
94
+ return normalizeCandles(candles);
95
+ }
96
+ parseKline(row, now) {
97
+ if (!Array.isArray(row) || row.length < 7)
98
+ throw new ProviderError('binance: unexpected kline row', { provider: ID });
99
+ return {
100
+ time: num(row[0], 'open time', ID),
101
+ open: num(row[1], 'open', ID),
102
+ high: num(row[2], 'high', ID),
103
+ low: num(row[3], 'low', ID),
104
+ close: num(row[4], 'close', ID),
105
+ volume: num(row[5], 'volume', ID),
106
+ closed: num(row[6], 'close time', ID) < now,
107
+ };
108
+ }
109
+ async getQuote(input, options = {}) {
110
+ const inst = toInstrument(input);
111
+ const body = await this.http.get('/api/v3/ticker/24hr', { symbol: this.nativeSymbol(inst) }, { weight: TICKER_WEIGHT, ...options });
112
+ if (!isRecord(body))
113
+ throw new ProviderError('binance: unexpected ticker payload', { provider: ID });
114
+ return {
115
+ instrument: inst,
116
+ time: typeof body.closeTime === 'number' ? body.closeTime : this.clock.now(),
117
+ bid: num(body.bidPrice, 'bidPrice', ID),
118
+ ask: num(body.askPrice, 'askPrice', ID),
119
+ bidSize: num(body.bidQty, 'bidQty', ID),
120
+ askSize: num(body.askQty, 'askQty', ID),
121
+ last: num(body.lastPrice, 'lastPrice', ID),
122
+ };
123
+ }
124
+ stream(path, options, parse) {
125
+ return createReconnectingStream({
126
+ // Binance sends no application heartbeat: a quiet pair is not a dead connection.
127
+ idleTimeoutMs: 0,
128
+ ...options,
129
+ provider: ID,
130
+ url: `${this.wsUrl}/ws/${path}`,
131
+ clock: this.clock,
132
+ ...(this.WebSocket ? { WebSocket: this.WebSocket } : {}),
133
+ session: {
134
+ onOpen: () => undefined,
135
+ onMessage: (msg) => {
136
+ if (!isRecord(msg))
137
+ return [];
138
+ if (isRecord(msg.error) || (typeof msg.code === 'number' && typeof msg.msg === 'string')) {
139
+ const err = isRecord(msg.error) ? msg.error : msg;
140
+ throw new ProviderError(`binance: ${String(err.msg)}`, { provider: ID, code: String(err.code) });
141
+ }
142
+ return parse(msg);
143
+ },
144
+ },
145
+ });
146
+ }
147
+ streamTrades(input, options = {}) {
148
+ const inst = toInstrument(input);
149
+ return this.stream(`${this.nativeSymbol(inst).toLowerCase()}@trade`, options, (msg) => {
150
+ if (msg.e !== 'trade')
151
+ return [];
152
+ return [
153
+ {
154
+ instrument: inst,
155
+ id: String(msg.t),
156
+ time: num(msg.T, 'trade time', ID),
157
+ price: num(msg.p, 'price', ID),
158
+ size: num(msg.q, 'quantity', ID),
159
+ // m = buyer is the maker, so the aggressor sold.
160
+ side: msg.m ? 'sell' : 'buy',
161
+ },
162
+ ];
163
+ });
164
+ }
165
+ streamCandles(input, timeframe, options = {}) {
166
+ const interval = this.checkTimeframe(timeframe);
167
+ const symbol = this.nativeSymbol(input).toLowerCase();
168
+ if (!symbol)
169
+ throw new InvalidArgumentError('binance: empty symbol');
170
+ return this.stream(`${symbol}@kline_${interval}`, options, (msg) => {
171
+ if (msg.e !== 'kline' || !isRecord(msg.k))
172
+ return [];
173
+ const k = msg.k;
174
+ return [
175
+ {
176
+ time: num(k.t, 'open time', ID),
177
+ open: num(k.o, 'open', ID),
178
+ high: num(k.h, 'high', ID),
179
+ low: num(k.l, 'low', ID),
180
+ close: num(k.c, 'close', ID),
181
+ volume: num(k.v, 'volume', ID),
182
+ closed: k.x === true,
183
+ },
184
+ ];
185
+ });
186
+ }
187
+ }
@@ -0,0 +1,28 @@
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
+ * Coinbase Exchange public market data (REST + WebSocket feed), no API key needed.
9
+ *
10
+ * Public REST endpoints are limited per IP (10 requests per second, bursts of 15, per the Exchange docs);
11
+ * the default client-side budget is 8 per second. Coinbase Exchange has no candle channel:
12
+ * `streamCandles` builds candles locally from the `matches` channel.
13
+ */
14
+ export declare class CoinbaseProvider implements Provider {
15
+ readonly id = "coinbase";
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
+ getCandles(input: InstrumentLike, timeframe: Timeframe, query?: CandleQuery): Promise<Candle[]>;
24
+ getQuote(input: InstrumentLike, options?: RequestOptions): Promise<Quote>;
25
+ private matches;
26
+ streamTrades(input: InstrumentLike, options?: StreamOptions): TickStream<Trade>;
27
+ streamCandles(input: InstrumentLike, timeframe: Timeframe, options?: StreamOptions): TickStream<Candle>;
28
+ }
@@ -0,0 +1,179 @@
1
+ import { CandleBuilder } from '../core/aggregate.js';
2
+ import { systemClock } from '../core/clock.js';
3
+ import { NotSupportedError, ProviderError } from '../core/errors.js';
4
+ import { HttpClient } from '../core/http.js';
5
+ import { instrument as toInstrument } from '../core/instrument.js';
6
+ import { RateLimiter } from '../core/rate-limiter.js';
7
+ import { createReconnectingStream } from '../core/stream.js';
8
+ import { parseTimeframe } from '../core/timeframe.js';
9
+ import { isoMs, isRecord, num } from '../core/util.js';
10
+ import { collectCandles, normalizeCandles, resolveQuery } from './paging.js';
11
+ const ID = 'coinbase';
12
+ const GRANULARITY = { '1m': 60, '5m': 300, '15m': 900, '1h': 3600, '6h': 21600, '1d': 86400 };
13
+ const TIMEFRAMES = Object.keys(GRANULARITY);
14
+ const STREAM_TIMEFRAMES = ['1s', '5s', '15s', '30s', '1m', '5m', '15m', '30m', '1h', '4h', '6h', '1d'];
15
+ const PAGE = 300;
16
+ /**
17
+ * Coinbase Exchange public market data (REST + WebSocket feed), no API key needed.
18
+ *
19
+ * Public REST endpoints are limited per IP (10 requests per second, bursts of 15, per the Exchange docs);
20
+ * the default client-side budget is 8 per second. Coinbase Exchange has no candle channel:
21
+ * `streamCandles` builds candles locally from the `matches` channel.
22
+ */
23
+ export class CoinbaseProvider {
24
+ id = ID;
25
+ capabilities = {
26
+ candleTimeframes: TIMEFRAMES,
27
+ streamTimeframes: STREAM_TIMEFRAMES,
28
+ candlesFromTrades: true,
29
+ };
30
+ http;
31
+ clock;
32
+ wsUrl;
33
+ WebSocket;
34
+ constructor(options = {}) {
35
+ this.clock = options.clock ?? systemClock;
36
+ this.wsUrl = options.wsUrl ?? 'wss://ws-feed.exchange.coinbase.com';
37
+ this.WebSocket = options.WebSocket;
38
+ this.http = new HttpClient({
39
+ provider: ID,
40
+ baseUrl: options.baseUrl ?? 'https://api.exchange.coinbase.com',
41
+ limiter: new RateLimiter(options.rateLimit ?? { capacity: 10, refillPerSecond: 8 }, this.clock),
42
+ clock: this.clock,
43
+ ...(options.fetch ? { fetch: options.fetch } : {}),
44
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
45
+ ...(options.retries !== undefined ? { retries: options.retries } : {}),
46
+ mapError: (status, body) => {
47
+ if (status !== 429 && isRecord(body) && typeof body.message === 'string') {
48
+ return new ProviderError(`coinbase: ${body.message}`, { provider: ID, status });
49
+ }
50
+ return undefined;
51
+ },
52
+ });
53
+ }
54
+ nativeSymbol(input) {
55
+ const inst = toInstrument(input);
56
+ if (inst.native)
57
+ return inst.native;
58
+ if (inst.assetClass !== 'crypto')
59
+ throw new NotSupportedError(`coinbase: only crypto pairs are available (got ${inst.symbol})`, { provider: ID });
60
+ return `${inst.base}-${inst.quote}`;
61
+ }
62
+ async getCandles(input, timeframe, query = {}) {
63
+ const product = this.nativeSymbol(input);
64
+ const granularity = GRANULARITY[timeframe];
65
+ if (granularity === undefined) {
66
+ throw new NotSupportedError(`coinbase: timeframe ${timeframe} is not supported (use ${TIMEFRAMES.join(', ')})`, { provider: ID });
67
+ }
68
+ const step = granularity * 1000;
69
+ const q = resolveQuery(query, this.clock.now());
70
+ const fetchWindow = async (start, end, signal) => {
71
+ const rows = await this.http.get(`/products/${encodeURIComponent(product)}/candles`, { granularity, start: new Date(start).toISOString(), end: new Date(end).toISOString() }, signal ? { signal } : {});
72
+ if (!Array.isArray(rows))
73
+ throw new ProviderError('coinbase: unexpected candles payload', { provider: ID });
74
+ const now = this.clock.now();
75
+ return normalizeCandles(rows.map((row) => parseRow(row, step, now)));
76
+ };
77
+ const floor = (t) => Math.floor(t / step) * step;
78
+ const candles = await collectCandles({
79
+ pageSize: PAGE,
80
+ forward: async (from, to, n, signal) => {
81
+ // Skip empty windows (before listing, or no trades) until data or the end of the range.
82
+ for (let start = Math.ceil(from / step) * step; start <= to; start += n * step) {
83
+ const page = await fetchWindow(start, Math.min(to, start + (n - 1) * step), signal);
84
+ if (page.length > 0)
85
+ return page;
86
+ }
87
+ return [];
88
+ },
89
+ backward: async (to, n, signal) => {
90
+ const end = floor(to);
91
+ return (await fetchWindow(end - (n - 1) * step, end, signal)).slice(-n);
92
+ },
93
+ }, q, query.signal);
94
+ return normalizeCandles(candles);
95
+ }
96
+ async getQuote(input, options = {}) {
97
+ const inst = toInstrument(input);
98
+ const product = encodeURIComponent(this.nativeSymbol(inst));
99
+ const [book, ticker] = await Promise.all([
100
+ this.http.get(`/products/${product}/book`, { level: 1 }, options),
101
+ this.http.get(`/products/${product}/ticker`, {}, options),
102
+ ]);
103
+ if (!isRecord(book) || !Array.isArray(book.bids) || !Array.isArray(book.asks) || !isRecord(ticker)) {
104
+ throw new ProviderError('coinbase: unexpected book/ticker payload', { provider: ID });
105
+ }
106
+ const bid = book.bids[0];
107
+ const ask = book.asks[0];
108
+ if (!Array.isArray(bid) || !Array.isArray(ask))
109
+ throw new ProviderError('coinbase: empty order book', { provider: ID });
110
+ return {
111
+ instrument: inst,
112
+ time: typeof book.time === 'string' ? isoMs(book.time, 'time', ID) : isoMs(ticker.time, 'time', ID),
113
+ bid: num(bid[0], 'bid', ID),
114
+ bidSize: num(bid[1], 'bid size', ID),
115
+ ask: num(ask[0], 'ask', ID),
116
+ askSize: num(ask[1], 'ask size', ID),
117
+ last: num(ticker.price, 'price', ID),
118
+ };
119
+ }
120
+ matches(product, options, onTrade, onHeartbeat) {
121
+ return createReconnectingStream({
122
+ ...options,
123
+ provider: ID,
124
+ url: this.wsUrl,
125
+ clock: this.clock,
126
+ ...(this.WebSocket ? { WebSocket: this.WebSocket } : {}),
127
+ session: {
128
+ onOpen: (send) => send({ type: 'subscribe', product_ids: [product], channels: ['matches', 'heartbeat'] }),
129
+ onMessage: (msg) => {
130
+ if (!isRecord(msg))
131
+ return [];
132
+ if (msg.type === 'error') {
133
+ throw new ProviderError(`coinbase: ${String(msg.message)}${msg.reason ? ` (${String(msg.reason)})` : ''}`, { provider: ID });
134
+ }
135
+ if (msg.type === 'heartbeat' && typeof msg.time === 'string')
136
+ return onHeartbeat(isoMs(msg.time, 'time', ID));
137
+ // `last_match` replays the previous trade on (re)subscription: skipped to avoid duplicates.
138
+ if (msg.type !== 'match' || msg.product_id !== product)
139
+ return [];
140
+ return onTrade({
141
+ id: String(msg.trade_id),
142
+ time: isoMs(msg.time, 'time', ID),
143
+ price: num(msg.price, 'price', ID),
144
+ size: num(msg.size, 'size', ID),
145
+ // `side` is the maker order side; the aggressor took the other side.
146
+ side: msg.side === 'buy' ? 'sell' : 'buy',
147
+ });
148
+ },
149
+ },
150
+ });
151
+ }
152
+ streamTrades(input, options = {}) {
153
+ const inst = toInstrument(input);
154
+ return this.matches(this.nativeSymbol(inst), options, (t) => [{ instrument: inst, ...t }], () => []);
155
+ }
156
+ streamCandles(input, timeframe, options = {}) {
157
+ if (!STREAM_TIMEFRAMES.includes(timeframe)) {
158
+ parseTimeframe(timeframe);
159
+ throw new NotSupportedError(`coinbase: stream timeframe ${timeframe} is not supported (use ${STREAM_TIMEFRAMES.join(', ')})`, { provider: ID });
160
+ }
161
+ const builder = new CandleBuilder(timeframe);
162
+ return this.matches(this.nativeSymbol(input), options, (t) => builder.update(t), (time) => builder.flush(time));
163
+ }
164
+ }
165
+ function parseRow(row, step, now) {
166
+ // [time (s), low, high, open, close, volume]
167
+ if (!Array.isArray(row) || row.length < 6)
168
+ throw new ProviderError('coinbase: unexpected candle row', { provider: ID });
169
+ const time = num(row[0], 'time', ID) * 1000;
170
+ return {
171
+ time,
172
+ low: num(row[1], 'low', ID),
173
+ high: num(row[2], 'high', ID),
174
+ open: num(row[3], 'open', ID),
175
+ close: num(row[4], 'close', ID),
176
+ volume: num(row[5], 'volume', ID),
177
+ closed: time + step <= now,
178
+ };
179
+ }
@@ -0,0 +1,6 @@
1
+ import type { Provider } from '../core/provider.js';
2
+ import { type AlpacaOptions } from './alpaca.js';
3
+ export declare const PROVIDER_IDS: readonly ["binance", "coinbase", "kraken", "alpaca"];
4
+ export type ProviderId = (typeof PROVIDER_IDS)[number];
5
+ /** A provider by id. Alpaca reads `APCA_API_KEY_ID` and `APCA_API_SECRET_KEY` unless keys are passed. */
6
+ export declare function createProvider(id: string, options?: AlpacaOptions): Provider;