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,203 @@
1
+ import { systemClock } from '../core/clock.js';
2
+ import { InvalidArgumentError } from '../core/errors.js';
3
+ import { instrument as toInstrument } from '../core/instrument.js';
4
+ import { liveCandles } from '../series/live.js';
5
+ /** Add or replace the newest candle, keeping at most `max`. */
6
+ function remember(window, c, max) {
7
+ if (window.length && window[window.length - 1].time === c.time)
8
+ window[window.length - 1] = c;
9
+ else
10
+ window.push(c);
11
+ if (window.length > max)
12
+ window.splice(0, window.length - max);
13
+ }
14
+ /** Runs the condition; a throw goes to `onError` when set (result: undefined). */
15
+ function check(options, ctx) {
16
+ if (!options.onError)
17
+ return options.when(ctx);
18
+ try {
19
+ return options.when(ctx);
20
+ }
21
+ catch (error) {
22
+ options.onError(error, ctx);
23
+ return undefined;
24
+ }
25
+ }
26
+ /** Edge, every and cooldown rules: decides whether a true condition fires. */
27
+ function gate(options, clock) {
28
+ const edge = (options.mode ?? 'edge') === 'edge';
29
+ const cooldownMs = options.cooldownMs ?? 0;
30
+ let armed = true;
31
+ let lastTrigger = -Infinity;
32
+ return (active) => {
33
+ if (!active) {
34
+ armed = true;
35
+ return undefined;
36
+ }
37
+ const now = clock.now();
38
+ if ((edge && !armed) || now - lastTrigger < cooldownMs)
39
+ return undefined;
40
+ armed = false;
41
+ lastTrigger = now;
42
+ return now;
43
+ };
44
+ }
45
+ function evaluator(options, inst, history, clock) {
46
+ const { name, provider, timeframe, evaluateHistory } = options;
47
+ const onClose = (options.on ?? 'close') === 'close';
48
+ const window = [];
49
+ const fire = gate(options, clock);
50
+ return (c, live) => {
51
+ remember(window, c, history);
52
+ if ((!live && !evaluateHistory) || (onClose && !c.closed))
53
+ return undefined;
54
+ const candles = onClose ? window.filter((x) => x.closed) : window;
55
+ const result = check(options, { instrument: inst, timeframe, candles, candle: c, closes: candles.map((x) => x.close) });
56
+ const at = fire(Boolean(result));
57
+ if (at === undefined)
58
+ return undefined;
59
+ return {
60
+ type: 'trigger',
61
+ ...(name !== undefined ? { name } : {}),
62
+ instrument: inst.symbol,
63
+ provider: provider.id,
64
+ timeframe,
65
+ at,
66
+ candle: c,
67
+ detail: result,
68
+ };
69
+ };
70
+ }
71
+ /** Async queue exposed as a TickStream. */
72
+ class EventQueue {
73
+ onFinish;
74
+ items = [];
75
+ waiter = null;
76
+ finished = false;
77
+ failure;
78
+ constructor(onFinish) {
79
+ this.onFinish = onFinish;
80
+ }
81
+ push(item) {
82
+ if (this.finished)
83
+ return;
84
+ const w = this.waiter;
85
+ this.waiter = null;
86
+ if (w)
87
+ w.resolve({ value: item, done: false });
88
+ else
89
+ this.items.push(item);
90
+ }
91
+ finish(error) {
92
+ if (this.finished)
93
+ return;
94
+ this.finished = true;
95
+ this.failure = error;
96
+ this.onFinish();
97
+ const w = this.waiter;
98
+ if (!w || this.items.length)
99
+ return;
100
+ this.waiter = null;
101
+ if (error)
102
+ w.reject(error);
103
+ else
104
+ w.resolve({ value: undefined, done: true });
105
+ }
106
+ stream() {
107
+ const iterator = {
108
+ next: () => {
109
+ if (this.items.length)
110
+ return Promise.resolve({ value: this.items.shift(), done: false });
111
+ if (this.finished)
112
+ return this.failure ? Promise.reject(this.failure) : Promise.resolve({ value: undefined, done: true });
113
+ return new Promise((resolve, reject) => {
114
+ this.waiter = { resolve, reject };
115
+ });
116
+ },
117
+ return: () => {
118
+ this.finish();
119
+ this.items.length = 0;
120
+ return Promise.resolve({ value: undefined, done: true });
121
+ },
122
+ };
123
+ const isFinished = () => this.finished;
124
+ return {
125
+ [Symbol.asyncIterator]: () => iterator,
126
+ close: () => this.finish(),
127
+ get closed() {
128
+ return isFinished();
129
+ },
130
+ };
131
+ }
132
+ }
133
+ /**
134
+ * Watches one or more instruments and emits an event when the condition triggers.
135
+ * Runs until closed; reconnections and missed candles are handled by `liveCandles`.
136
+ *
137
+ * ```ts
138
+ * for await (const e of watch({ provider, instruments: ['ETH/USDT'], timeframe: '1h',
139
+ * when: ({ closes }) => (rsi(closes, 14).at(-1) ?? 50) < 30 && 'RSI 14 under 30' })) {
140
+ * console.log(JSON.stringify(e));
141
+ * }
142
+ * ```
143
+ */
144
+ export function watch(options) {
145
+ const list = (Array.isArray(options.instruments) ? options.instruments : [options.instruments]);
146
+ if (list.length === 0)
147
+ throw new InvalidArgumentError('watch: at least one instrument is required');
148
+ const instruments = list.map((i) => toInstrument(i));
149
+ const history = options.history ?? 300;
150
+ if (!(Number.isInteger(history) && history > 0))
151
+ throw new InvalidArgumentError('watch: history must be a positive integer');
152
+ const clock = options.clock ?? systemClock;
153
+ const controller = new AbortController();
154
+ const feeds = [];
155
+ const onAbort = () => controller.abort();
156
+ const queue = new EventQueue(() => {
157
+ options.signal?.removeEventListener('abort', onAbort);
158
+ controller.abort();
159
+ for (const f of feeds)
160
+ f.close();
161
+ });
162
+ options.signal?.addEventListener('abort', onAbort, { once: true });
163
+ controller.signal.addEventListener('abort', () => queue.finish(), { once: true });
164
+ if (options.signal?.aborted)
165
+ controller.abort();
166
+ const { provider, timeframe, store, onStatus, when: _when, name: _name, instruments: _instruments, on: _on, mode: _mode, cooldownMs: _cooldown, history: _history, evaluateHistory: _evaluateHistory, signal: _signal, onError: _onError, clock: _clock, ...streamOptions } = options;
167
+ let running = instruments.length;
168
+ for (const inst of instruments) {
169
+ let live = false;
170
+ const feed = liveCandles({
171
+ ...streamOptions,
172
+ provider,
173
+ instrument: inst,
174
+ timeframe,
175
+ history,
176
+ signal: controller.signal,
177
+ clock,
178
+ ...(store ? { store } : {}),
179
+ onHistoryEnd: () => {
180
+ live = true;
181
+ },
182
+ ...(onStatus ? { onStatus: (s) => onStatus({ ...s, instrument: inst.symbol }) } : {}),
183
+ });
184
+ feeds.push(feed);
185
+ const evaluate = evaluator(options, inst, history, clock);
186
+ void (async () => {
187
+ try {
188
+ for await (const c of feed) {
189
+ const event = evaluate(c, live);
190
+ if (event)
191
+ queue.push(event);
192
+ }
193
+ }
194
+ catch (error) {
195
+ queue.finish(error);
196
+ return;
197
+ }
198
+ if (--running === 0)
199
+ queue.finish();
200
+ })();
201
+ }
202
+ return queue.stream();
203
+ }
package/docs/agents.md ADDED
@@ -0,0 +1,84 @@
1
+ # TickWire for agents
2
+
3
+ This guide is for AI agents that use TickWire on their own computer. Write short TypeScript scripts and run them with `bun script.ts`, or with Node 22+ (`node script.mjs`). Use `tickwire` on the command line for quick lookups.
4
+
5
+ Install with `npm install tickwire` (or `bun add tickwire`); the `tickwire` command comes with it (`npx tickwire --help`).
6
+
7
+ ## Rules
8
+
9
+ - **Only official provider APIs, used with the user's own access.**
10
+ - Binance, Coinbase and Kraken market data needs no key.
11
+ - Alpaca needs the user's key in `APCA_API_KEY_ID` and `APCA_API_SECRET_KEY`.
12
+ - Data is for the user's own use: never redistribute it. Each provider's terms are in [providers.md](providers.md).
13
+ - **Instruments.** Crypto pairs are written `BASE/QUOTE` (`BTC/USDT` on Binance, `BTC/USD` on Coinbase and Kraken). Stocks are written by ticker (`AAPL`, Alpaca).
14
+ - **Timeframes:** `1m 5m 15m 1h 4h 1d 1w 1M`. Durations for ranges: `90m 12h 7d 2w 6mo 1y`.
15
+ - **Times are milliseconds since the epoch, in UTC.** A candle's `time` is its open time, and `closed: false` means it is still forming.
16
+ - **Keep outputs small.** Print summaries (last value, counts, extremes), not thousands of candles.
17
+
18
+ ## Recipes
19
+
20
+ **Candles for a range, cached between runs**
21
+
22
+ ```ts
23
+ import { BinanceProvider, FileStore, defaultCacheDir, loadCandles } from 'tickwire';
24
+ const candles = await loadCandles({
25
+ provider: new BinanceProvider(), instrument: 'BTC/USDT', timeframe: '1h',
26
+ from: '7d', store: new FileStore(await defaultCacheDir()),
27
+ });
28
+ ```
29
+
30
+ Shell: `tickwire candles binance BTC/USDT 1h --since 7d`. It uses the same cache.
31
+
32
+ **Indicators**
33
+
34
+ ```ts
35
+ import { rsi, macd } from 'tickwire';
36
+ const closes = candles.map((c) => c.close);
37
+ console.log({ rsi14: rsi(closes, 14).at(-1), macd: macd(closes).at(-1) });
38
+ ```
39
+
40
+ **Data quality.** `checkCandles(candles, '1h')` lists gaps, duplicates and misaligned candles. Gaps are normal for stocks outside market hours and for illiquid pairs.
41
+
42
+ **Watch markets around the clock**
43
+
44
+ ```ts
45
+ import { BinanceProvider, watch, rsi, appendJsonl } from 'tickwire';
46
+ const log = appendJsonl('/home/agent/alerts/oversold.jsonl');
47
+ for await (const e of watch({
48
+ provider: new BinanceProvider(), instruments: ['ETH/USDT', 'SOL/USDT'], timeframe: '15m', name: 'oversold',
49
+ when: ({ closes }) => { const v = rsi(closes, 14).at(-1); return v !== undefined && v < 30 && { rsi: v }; },
50
+ })) await log(e);
51
+ ```
52
+
53
+ How to run it:
54
+ - Start it as a background process and keep its PID, so you can stop it later.
55
+ - To be woken up, have a scheduled check read the new lines of the `.jsonl` file, or send them to a webhook with `postJson(url)`.
56
+ - After a machine restart, start the watchers again.
57
+
58
+ Two defaults to know:
59
+ - A watcher fires when its condition becomes true. It fires again only after the condition has turned false and back to true.
60
+ - `detail` is whatever the condition returned. Put in it what you will need to explain the alert.
61
+
62
+ **Backtest a rule**
63
+
64
+ ```ts
65
+ import { backtest, rsi } from 'tickwire';
66
+ const result = backtest({ candles, strategy: (ctx) => {
67
+ const v = rsi(ctx.lookback(50).map((c) => c.close), 14).at(-1);
68
+ if (v === undefined) return;
69
+ if (v < 30 && ctx.position === 0) ctx.buy();
70
+ if (v > 55 && ctx.position > 0) ctx.sell();
71
+ } });
72
+ console.log(result.metrics);
73
+ ```
74
+
75
+ The strategy only sees closed candles, and orders fill at the next candle's open. Default fees are 0.1 %, and default slippage is 0.05 %.
76
+
77
+ ## Errors
78
+
79
+ Every error extends `TickwireError`:
80
+ - `RateLimitError`: wait `retryAfterMs`, then retry.
81
+ - `AuthenticationError`: the key is missing or was rejected. Ask the user.
82
+ - `NotSupportedError`: this provider does not offer that timeframe or market.
83
+
84
+ On the command line, errors are JSON on stderr. The exit code is 2 for a bad argument and 1 for any other error.
@@ -0,0 +1,94 @@
1
+ # Positioning
2
+
3
+ What TickWire is for, who uses it, and what it is not. This rests on a review of existing tools done on 2026-12-01 against GitHub, npm, PyPI and the official docs. Issue numbers point to each project's own GitHub repository.
4
+
5
+ ## In one sentence
6
+
7
+ TickWire is the market toolkit for **AI agents that have a computer**: the agent writes and runs TypeScript with it to fetch prices, watch markets around the clock, study a trader's history and apply that trader's strategy.
8
+
9
+ ## Who it is for
10
+
11
+ **The main user is an agent, not a developer.** That agent runs all the time on its own machine and works for one trader. It writes short scripts (Node or Bun, TypeScript runs as is) and keeps them running. The trader gives it a direction rather than a specification, often as a chart screenshot, a voice note or a one-line message.
12
+
13
+ **The case we build for first: AI-assisted manual trading.** A discretionary trader has a strategy and spends hours watching screens for setups. Their agent takes over the watching and keeps them to their own rules:
14
+
15
+ 1. **Onboarding.** The agent asks about the trader's experience and preferences.
16
+ 2. **Learning the strategy.** It imports the trader's history, often hundreds or thousands of trades. It puts every entry and exit back in its market context and suggests the patterns it sees as questions ("you mostly enter on a breakout after 10:00, is that deliberate?"). The trader confirms or corrects, and the strategy is learned through conversation.
17
+ 3. **Smart alerts.** The agent turns the strategy into watchers that run 24/7 and wake it only when a setup forms.
18
+ 4. **Discipline.** Before an order, the agent checks it against the strategy and asks when the trade looks driven by emotion rather than by the plan.
19
+ 5. **Hands-off execution.** Only when the trader asks for it, the agent applies the learned rules while they sleep, within the risk limits they set.
20
+
21
+ That product is an agent experience, not part of this library. TickWire is what makes the agent's job easy. Fully automated strategy research (algorithmic trading) also benefits from the same primitives, but it is not what drives the design.
22
+
23
+ ## Why existing tools do not cover it
24
+
25
+ - **Exchange connectors give you API calls, not series you can trust.** [CCXT](https://github.com/ccxt/ccxt) covers 100+ exchanges, but known bugs show what it leaves to you:
26
+ - Candles go wrong per exchange: the last candle is missing or stale (ccxt#24007), and pagination fails for one market type only (ccxt#23194).
27
+ - Data comes back duplicated (ccxt#4277).
28
+ - Joining the history to the live stream is up to you (ccxt#25699).
29
+ - Its Alpaca support is crypto only.
30
+ - **Indicator libraries are catalogues, not watchers.**
31
+ - technicalindicators has not had a release since 2020, and its users report wrong values (#249, #220).
32
+ - trading-signals is good and streaming-first. It has no crypto exchanges, though, and nothing to watch markets or to study a trader's own trades.
33
+ - **Backtesters test strategies written as code by quants.**
34
+ - backtrader is unmaintained.
35
+ - vectorbt is moving to a paid version.
36
+ - freqtrade, NautilusTrader and Lean are heavy.
37
+ - None of them starts from a person's trade history.
38
+ - **Agent tools for markets are thin API wrappers, mostly MCP servers.** They return unbounded arrays of raw data. An agent with a computer does better writing code against a good library, and keeping it running.
39
+
40
+ ## What TickWire provides
41
+
42
+ 1. **Series you can trust.**
43
+ - Backfill switches to the live stream without a gap or an overlap.
44
+ - Each candle says explicitly whether it is still forming or closed.
45
+ - Gaps and duplicates are found, repaired, and the rest is reported.
46
+ - A local cache resumes where it stopped, so the agent never downloads the same months twice.
47
+ 2. **Watchers.** Conditions written in plain TypeScript (for example "RSI 14 under 30 on ETH 1h and a break of yesterday's low") run as long-lived background processes. They use almost no resources and emit an event when they trigger. That is how an agent watches dozens of setups around the clock and only wakes up when something happens.
48
+ 3. **Trade history analysis.**
49
+ - Imports fills from brokers and exchanges, or from CSV exports.
50
+ - Rebuilds round trips.
51
+ - Records the market context at every entry and exit: trend, volatility, distance to recent highs and lows, time of day, indicator values.
52
+ - Gives the agent comparable features to form hypotheses about the trader's strategy, and to check them on enough trades to mean something.
53
+ 4. **Replay and backtest of a learned strategy.** Strategies only see closed candles, and orders fill at the next open, so look-ahead is impossible. The same data and rules always give the same result.
54
+ 5. **Accounts and guarded execution.**
55
+ - Reads positions, orders and balances through each broker's official API.
56
+ - Places orders only through a guard: per-trade and per-day loss limits, a maximum size and a kill switch, all set by the trader.
57
+ 6. **Show, don't dump.** Compact summaries and charts rendered as SVG with no dependencies, so the agent can answer a screenshot with a chart.
58
+ 7. **Forgiving inputs.** Instrument search ("eth" finds the right symbol on each provider), lenient timeframes and natural time ranges, because the trader speaks loosely and the agent translates.
59
+
60
+ ### Interface choice
61
+
62
+ - **Code first.** The library is the product. It ships with a guide written for agents, inside the package, with short runnable recipes.
63
+ - **A small command-line tool, only where code is clumsy.** It covers one-shot lookups, cache management and starting or stopping watchers. Everything else is a few lines of TypeScript run by Node or Bun.
64
+ - **No MCP server.** Agents with a computer write code and outgrow fixed tool lists quickly.
65
+
66
+ ## Ambition
67
+
68
+ TickWire aims to replace the stack an agent would otherwise patch together: CCXT for access, TA-Lib or a JS indicator package for maths, a backtester, and its own glue for caching, watching and journaling. It aims to be better on every step an agent assisting a trader actually takes. Coverage grows with official, documented broker and exchange APIs, starting with crypto and US equities. Futures and forex brokers come next, because many day traders trade there.
69
+
70
+ ## What TickWire is not
71
+
72
+ - **Not a source of trading advice.** The agent applies the strategy its user taught it, within the limits its user set. TickWire ships no strategy and no signals.
73
+ - **Not a data redistributor.** Each user fetches their own data with their own access, under each provider's terms ([providers.md](providers.md)).
74
+ - **Not a CCXT clone.** It does not chase venue count for its own sake.
75
+
76
+ ## Scope of v0.1 and next steps
77
+
78
+ | Item | v0.1 | Next |
79
+ |---|---|---|
80
+ | Providers: Binance, Coinbase, Kraken, Alpaca (market data) | done | account and order endpoints behind the guard |
81
+ | Indicators (SMA, EMA, RSI, MACD, Bollinger, ATR, VWAP) | done | checked against published reference values; more only when the feature extraction needs them |
82
+ | Backtest (next-open fills, fees, slippage, metrics) | done | strategies replayed from a learned rule set |
83
+ | Series: backfill + live + gap repair + local cache | done (`loadCandles`, `liveCandles`, `checkCandles`, `FileStore`) | |
84
+ | Watchers (long-running conditions, events) | done (`watch`, `appendJsonl`, `postJson`) | |
85
+ | Trade history import and context features | | second |
86
+ | Agent guide in the package | done ([agents.md](agents.md)) | |
87
+ | SVG charts, instrument search | | second |
88
+ | Small CLI (candles, check, quote, cache) | done | |
89
+
90
+ ## Risks
91
+
92
+ - **trading-signals is the closest neighbour.** It is streaming indicators plus a backtester, and a backtest MCP server is proposed in typedtrader#1275. It does not address the manual trader or crypto exchanges, which is where we start.
93
+ - **Inferring a strategy from history is easy to overfit.** It needs hundreds of trades, hypotheses presented as questions, and checks on trades held out from the analysis.
94
+ - **Exchange terms.** Several providers limit data to personal use or ask for consent before third-party applications are built (Kraken's terms, section 9, binds its users). The model fits: the agent belongs to the trader, runs on the trader's behalf, and redistributes nothing.
@@ -0,0 +1,92 @@
1
+ # Providers
2
+
3
+ TickWire only talks to official, documented market data APIs. It hosts nothing and redistributes no data:
4
+ each user's own machine connects directly to the provider, with that user's own access, and **each user is
5
+ bound by the provider's terms**. TickWire is not affiliated with, endorsed or sponsored by any of the
6
+ providers below; their names and marks belong to their owners.
7
+
8
+ The summaries below were checked on 2026-12-01. They are not legal advice and terms change: read the
9
+ linked documents yourself before using a provider, and in particular before building anything that other
10
+ people will use.
11
+
12
+ | Provider | Key | Assets | `getCandles` timeframes | Streams | Client-side default budget |
13
+ |---|---|---|---|---|---|
14
+ | `BinanceProvider` | none | crypto spot | 1s 1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M | trades, klines | 3 000 weight/min (Binance allows 6 000) |
15
+ | `CoinbaseProvider` | none | crypto spot | 1m 5m 15m 1h 6h 1d | trades; candles built locally from trades | 8 req/s (Coinbase allows 10, burst 15) |
16
+ | `KrakenProvider` | none | crypto spot | 1m 5m 15m 30m 1h 4h 1d 1w 15d (latest 720 only) | trades, OHLC | 1 req/s, burst 3 |
17
+ | `AlpacaProvider` | free Alpaca key | US stocks | 1-59m, 1-23h, 1d, 1w, 1/2/3/4/6/12M | trades, 1-minute bars | 180 req/min (free plan allows 200) |
18
+
19
+ Every provider retries network errors, 5xx and 429 answers with backoff (honouring `Retry-After`), never
20
+ retries a ban, and reconnects WebSocket streams with exponential backoff. You can lower the budgets with the
21
+ `rateLimit` option; do not raise them above the provider's documented limits.
22
+
23
+ ## Binance
24
+
25
+ - **Endpoints:** `https://api.binance.com` (`GET /api/v3/klines`, weight 2, up to 1 000 candles per call;
26
+ `GET /api/v3/ticker/24hr`, weight 2) and `wss://stream.binance.com:9443/ws/<symbol>@trade` /
27
+ `@kline_<interval>`. A market-data-only host, `https://data-api.binance.vision`, can be set with `baseUrl`.
28
+ - **Limits:** 6 000 request weight per minute per IP. Over it, Binance answers 429, then 418 (IP ban from
29
+ 2 minutes to 3 days) if requests continue. WebSocket connections last at most 24 hours (TickWire
30
+ reconnects), 5 incoming messages per second, 300 connections per 5 minutes per IP.
31
+ - **Terms:** [Binance Terms of Use](https://www.binance.com/en/terms) and the
32
+ [list of prohibited countries](https://www.binance.com/en/legal/list-of-prohibited-countries).
33
+ The licence covers non-commercial personal or internal business use. Commercial uses of Binance market
34
+ data (trading services, data feeds, apps that profit from the data) need Binance's written consent.
35
+ Persons in or tied to the United States, and residents of Canada and the Netherlands, among others,
36
+ are not eligible, and using a VPN to get around this is forbidden. Binance.US is a separate company with
37
+ its own terms; its endpoints can be set with `baseUrl` and `wsUrl` if you are eligible there.
38
+ The `data-api.binance.vision` host may also fall under the
39
+ [Binance Vision terms](https://data.binance.vision/Binance_Vision-Terms_of_Use.pdf) (CC BY-NC-SA 4.0).
40
+ - **API docs:** <https://developers.binance.com/docs/binance-spot-api-docs>
41
+
42
+ ## Coinbase Exchange
43
+
44
+ - **Endpoints:** `https://api.exchange.coinbase.com` (`/products/{id}/candles`, at most 300 candles per
45
+ call; `/products/{id}/book?level=1`; `/products/{id}/ticker`) and `wss://ws-feed.exchange.coinbase.com`
46
+ (`matches` and `heartbeat` channels, which need no authentication).
47
+ - **Limits:** public REST endpoints, 10 requests per second per IP with bursts of 15. WebSocket: subscribe
48
+ within 5 seconds of connecting (TickWire does it on open).
49
+ - **Terms:** the [Coinbase Market Data Terms of Use](https://www.coinbase.com/legal/market_data) cover all
50
+ market data Coinbase makes available. Use is for your own or your organisation's **personal or research
51
+ purposes**; the data may not be used to build an application for end users other than you, and may not
52
+ be redistributed, displayed or disseminated outside your organisation, used as a benchmark, or used to
53
+ train AI models, without Coinbase's written consent. The
54
+ [Developer Platform terms](https://www.coinbase.com/legal/developer-platform/terms-of-service) also apply
55
+ to its developer tools.
56
+ - **API docs:** <https://docs.cdp.coinbase.com/exchange/>
57
+
58
+ ## Kraken
59
+
60
+ - **Endpoints:** `https://api.kraken.com/0/public/OHLC` and `/0/public/Ticker`, and
61
+ `wss://ws.kraken.com/v2` (`trade` and `ohlc` channels).
62
+ - **History:** the OHLC endpoint only returns the 720 most recent candles of a timeframe, whatever the
63
+ requested start; TickWire never pretends otherwise (`capabilities.maxHistoryCandles`).
64
+ - **Limits:** about one public REST call per second per IP (and per pair for OHLC); errors
65
+ `EAPI:Rate limit exceeded` become `RateLimitError`. About 150 WebSocket connection attempts per 10 minutes
66
+ per IP, then a 10-minute ban: keep the default reconnection backoff.
67
+ - **Terms:** the [Kraken Terms of Service](https://www.kraken.com/legal/global-terms) allow use of Kraken's
68
+ content only for your own benefit, forbid redistribution and commercial exploitation, and their section 9
69
+ forbids developing third-party applications that interact with Kraken's content without Kraken's prior
70
+ written consent. Read it before using this provider. Kraken does not serve some countries and US states
71
+ (see its [geographic restrictions](https://support.kraken.com/articles/360001368823-geographic-restrictions)).
72
+ - **API docs:** <https://docs.kraken.com/api-reference/>
73
+
74
+ ## Alpaca
75
+
76
+ - **Access:** create an Alpaca account, generate API keys, and set `APCA_API_KEY_ID` and
77
+ `APCA_API_SECRET_KEY` (or pass `keyId` and `secretKey`). Keys are only sent to Alpaca.
78
+ - **Endpoints:** `https://data.alpaca.markets/v2/stocks/{symbol}/bars` (paged with `next_page_token`) and
79
+ `/snapshot`, and `wss://stream.data.alpaca.markets/v2/iex` (or `/sip` with `feed: 'sip'` on a paid plan).
80
+ - **Limits (free plan):** IEX feed only for real time, 200 historical calls per minute, 30 streamed symbols,
81
+ and usually a single stream connection per account (a second one fails with error 406). Full-market (SIP)
82
+ history is only available for data older than 15 minutes without a subscription.
83
+ - **Terms:** [Alpaca Terms and Conditions](https://files.alpaca.markets/disclosures/library/TermsAndConditions.pdf):
84
+ personal, non-commercial use; making the service available to others through your own application
85
+ requires 30 days' written notice to Alpaca; Alpaca data may not be redistributed.
86
+ - **API docs:** <https://docs.alpaca.markets/docs/about-market-data-api>
87
+
88
+ ## Adding a provider
89
+
90
+ A provider implements the `Provider` interface (`src/core/provider.ts`). Before adding one, check that it
91
+ offers an official, documented API whose terms allow use through a client library, note those terms here,
92
+ and record test fixtures from it with `scripts/record-fixtures.mjs` so that the test suite stays offline.
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "tickwire",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Market toolkit for AI agents that write code: reliable candle series with a local cache, 24/7 watchers, indicators and backtests on official exchange and broker APIs.",
5
+ "license": "ISC",
6
+ "author": "Mathieu Colmon",
7
+ "type": "module",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Mathieu2301/tickwire.git"
11
+ },
12
+ "homepage": "https://github.com/Mathieu2301/tickwire#readme",
13
+ "keywords": [
14
+ "market-data",
15
+ "crypto",
16
+ "stocks",
17
+ "candles",
18
+ "ohlcv",
19
+ "websocket",
20
+ "indicators",
21
+ "backtest",
22
+ "binance",
23
+ "coinbase",
24
+ "kraken",
25
+ "alpaca"
26
+ ],
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "sideEffects": false,
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "main": "./dist/index.js",
39
+ "types": "./dist/index.d.ts",
40
+ "files": [
41
+ "dist",
42
+ "docs",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "scripts": {
47
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
48
+ "typecheck": "tsc -p tsconfig.json --noEmit",
49
+ "lint": "eslint .",
50
+ "test": "vitest run",
51
+ "test:watch": "vitest",
52
+ "test:live": "TICKWIRE_LIVE=1 vitest run tests/live",
53
+ "fixtures:record": "node scripts/record-fixtures.mjs",
54
+ "prepublishOnly": "npm run typecheck && npm run lint && npm test && npm run build",
55
+ "coverage": "vitest run --coverage",
56
+ "prepare": "npm run build"
57
+ },
58
+ "devDependencies": {
59
+ "@eslint/js": "^10.0.0",
60
+ "@types/node": "^22.0.0",
61
+ "@vitest/coverage-v8": "^5.1.2",
62
+ "eslint": "^10.0.0",
63
+ "typescript": "~6.0.3",
64
+ "typescript-eslint": "^8.74.0",
65
+ "vitest": "^5.1.2"
66
+ },
67
+ "bin": {
68
+ "tickwire": "./dist/cli.js"
69
+ }
70
+ }