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.
- package/LICENSE +15 -0
- package/README.md +209 -2
- package/dist/backtest/backtest.d.ts +101 -0
- package/dist/backtest/backtest.js +200 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +179 -0
- package/dist/core/aggregate.d.ts +19 -0
- package/dist/core/aggregate.js +64 -0
- package/dist/core/clock.d.ts +6 -0
- package/dist/core/clock.js +18 -0
- package/dist/core/errors.d.ts +51 -0
- package/dist/core/errors.js +53 -0
- package/dist/core/http.d.ts +38 -0
- package/dist/core/http.js +119 -0
- package/dist/core/instrument.d.ts +14 -0
- package/dist/core/instrument.js +22 -0
- package/dist/core/provider.d.ts +47 -0
- package/dist/core/provider.js +1 -0
- package/dist/core/rate-limiter.d.ts +30 -0
- package/dist/core/rate-limiter.js +68 -0
- package/dist/core/stream.d.ts +90 -0
- package/dist/core/stream.js +224 -0
- package/dist/core/timeframe.d.ts +16 -0
- package/dist/core/timeframe.js +21 -0
- package/dist/core/types.d.ts +52 -0
- package/dist/core/types.js +1 -0
- package/dist/core/util.d.ts +8 -0
- package/dist/core/util.js +24 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +22 -0
- package/dist/indicators/atr.d.ts +21 -0
- package/dist/indicators/atr.js +41 -0
- package/dist/indicators/bollinger.d.ts +22 -0
- package/dist/indicators/bollinger.js +42 -0
- package/dist/indicators/ema.d.ts +16 -0
- package/dist/indicators/ema.js +40 -0
- package/dist/indicators/index.d.ts +8 -0
- package/dist/indicators/index.js +8 -0
- package/dist/indicators/indicator.d.ts +15 -0
- package/dist/indicators/indicator.js +17 -0
- package/dist/indicators/macd.d.ts +31 -0
- package/dist/indicators/macd.js +48 -0
- package/dist/indicators/rsi.d.ts +17 -0
- package/dist/indicators/rsi.js +53 -0
- package/dist/indicators/sma.d.ts +14 -0
- package/dist/indicators/sma.js +43 -0
- package/dist/indicators/vwap.d.ts +25 -0
- package/dist/indicators/vwap.js +37 -0
- package/dist/providers/alpaca.d.ts +44 -0
- package/dist/providers/alpaca.js +227 -0
- package/dist/providers/binance.d.ts +31 -0
- package/dist/providers/binance.js +187 -0
- package/dist/providers/coinbase.d.ts +28 -0
- package/dist/providers/coinbase.js +179 -0
- package/dist/providers/create.d.ts +6 -0
- package/dist/providers/create.js +21 -0
- package/dist/providers/kraken.d.ts +30 -0
- package/dist/providers/kraken.js +203 -0
- package/dist/providers/options.d.ts +22 -0
- package/dist/providers/options.js +1 -0
- package/dist/providers/paging.d.ts +30 -0
- package/dist/providers/paging.js +59 -0
- package/dist/series/check.d.ts +32 -0
- package/dist/series/check.js +63 -0
- package/dist/series/live.d.ts +31 -0
- package/dist/series/live.js +121 -0
- package/dist/series/load.d.ts +35 -0
- package/dist/series/load.js +100 -0
- package/dist/series/store.d.ts +50 -0
- package/dist/series/store.js +148 -0
- package/dist/series/time.d.ts +15 -0
- package/dist/series/time.js +62 -0
- package/dist/watch/sinks.d.ts +7 -0
- package/dist/watch/sinks.js +22 -0
- package/dist/watch/watch.d.ts +78 -0
- package/dist/watch/watch.js +203 -0
- package/docs/agents.md +84 -0
- package/docs/positioning.md +94 -0
- package/docs/providers.md +92 -0
- package/package.json +68 -4
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { systemClock } from './clock.js';
|
|
2
|
+
import { InvalidArgumentError } from './errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* Token bucket shared by every request of a provider instance.
|
|
5
|
+
* Requests wait in FIFO order until enough weight is available, so the provider's limit is never exceeded
|
|
6
|
+
* by this process. A rate-limit answer from the server can also pause the bucket (`pauseFor`).
|
|
7
|
+
*/
|
|
8
|
+
export class RateLimiter {
|
|
9
|
+
capacity;
|
|
10
|
+
refillPerSecond;
|
|
11
|
+
tokens;
|
|
12
|
+
last;
|
|
13
|
+
pausedUntil = 0;
|
|
14
|
+
chain = Promise.resolve();
|
|
15
|
+
clock;
|
|
16
|
+
constructor(options, clock = systemClock) {
|
|
17
|
+
if (!(options.capacity > 0) || !(options.refillPerSecond > 0)) {
|
|
18
|
+
throw new InvalidArgumentError('Rate limit capacity and refillPerSecond must be positive');
|
|
19
|
+
}
|
|
20
|
+
this.capacity = options.capacity;
|
|
21
|
+
this.refillPerSecond = options.refillPerSecond;
|
|
22
|
+
this.tokens = options.capacity;
|
|
23
|
+
this.clock = clock;
|
|
24
|
+
this.last = clock.now();
|
|
25
|
+
}
|
|
26
|
+
/** Weight currently available (after refill). */
|
|
27
|
+
available() {
|
|
28
|
+
this.refill();
|
|
29
|
+
return this.tokens;
|
|
30
|
+
}
|
|
31
|
+
/** Block every request until `ms` from now (used after a 429 with Retry-After). */
|
|
32
|
+
pauseFor(ms) {
|
|
33
|
+
this.pausedUntil = Math.max(this.pausedUntil, this.clock.now() + ms);
|
|
34
|
+
}
|
|
35
|
+
/** Wait until `weight` units are available, then consume them. */
|
|
36
|
+
acquire(weight = 1, signal) {
|
|
37
|
+
if (weight > this.capacity) {
|
|
38
|
+
throw new InvalidArgumentError(`Request weight ${weight} exceeds rate limit capacity ${this.capacity}`);
|
|
39
|
+
}
|
|
40
|
+
const run = this.chain.then(() => this.take(weight, signal));
|
|
41
|
+
// Keep the queue alive even if one waiter is aborted.
|
|
42
|
+
this.chain = run.catch(() => undefined);
|
|
43
|
+
return run;
|
|
44
|
+
}
|
|
45
|
+
refill() {
|
|
46
|
+
const now = this.clock.now();
|
|
47
|
+
const elapsed = Math.max(0, now - this.last) / 1000;
|
|
48
|
+
this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillPerSecond);
|
|
49
|
+
this.last = now;
|
|
50
|
+
}
|
|
51
|
+
async take(weight, signal) {
|
|
52
|
+
for (;;) {
|
|
53
|
+
signal?.throwIfAborted();
|
|
54
|
+
const pause = this.pausedUntil - this.clock.now();
|
|
55
|
+
if (pause > 0) {
|
|
56
|
+
await this.clock.sleep(pause, signal);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
this.refill();
|
|
60
|
+
if (this.tokens >= weight) {
|
|
61
|
+
this.tokens -= weight;
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const waitMs = Math.ceil(((weight - this.tokens) / this.refillPerSecond) * 1000);
|
|
65
|
+
await this.clock.sleep(waitMs, signal);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { type Clock } from './clock.js';
|
|
2
|
+
/** Minimal WebSocket surface used by tickwire (the WHATWG `WebSocket` of Node 22+, browsers, or the `ws` package). */
|
|
3
|
+
export interface WebSocketLike {
|
|
4
|
+
readonly readyState: number;
|
|
5
|
+
send(data: string): void;
|
|
6
|
+
close(code?: number, reason?: string): void;
|
|
7
|
+
onopen: ((event: unknown) => void) | null;
|
|
8
|
+
onmessage: ((event: {
|
|
9
|
+
data: unknown;
|
|
10
|
+
}) => void) | null;
|
|
11
|
+
onclose: ((event: {
|
|
12
|
+
code?: number;
|
|
13
|
+
reason?: string;
|
|
14
|
+
}) => void) | null;
|
|
15
|
+
onerror: ((event: unknown) => void) | null;
|
|
16
|
+
}
|
|
17
|
+
export type WebSocketConstructor = new (url: string) => WebSocketLike;
|
|
18
|
+
export interface BackoffOptions {
|
|
19
|
+
/** First reconnection delay in ms (default 500). */
|
|
20
|
+
initialMs?: number;
|
|
21
|
+
/** Maximum delay in ms (default 30 000). */
|
|
22
|
+
maxMs?: number;
|
|
23
|
+
/** Growth factor (default 2). */
|
|
24
|
+
factor?: number;
|
|
25
|
+
/** Random jitter ratio, 0 to 1 (default 0.2). */
|
|
26
|
+
jitter?: number;
|
|
27
|
+
/** Give up after this many consecutive failed attempts (default: never). */
|
|
28
|
+
maxAttempts?: number;
|
|
29
|
+
}
|
|
30
|
+
export type StreamStatus = {
|
|
31
|
+
type: 'connecting';
|
|
32
|
+
attempt: number;
|
|
33
|
+
} | {
|
|
34
|
+
type: 'open';
|
|
35
|
+
} | {
|
|
36
|
+
type: 'reconnecting';
|
|
37
|
+
attempt: number;
|
|
38
|
+
delayMs: number;
|
|
39
|
+
reason: string;
|
|
40
|
+
} | {
|
|
41
|
+
type: 'dropped';
|
|
42
|
+
count: number;
|
|
43
|
+
} | {
|
|
44
|
+
type: 'closed';
|
|
45
|
+
error?: Error;
|
|
46
|
+
};
|
|
47
|
+
export interface StreamOptions {
|
|
48
|
+
/** Stops the stream when aborted. */
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
/** Connection lifecycle callback (connecting, open, reconnecting, closed…). */
|
|
51
|
+
onStatus?: (status: StreamStatus) => void;
|
|
52
|
+
backoff?: BackoffOptions;
|
|
53
|
+
/** Reconnect when nothing is received for this long, in ms (default 60 000; 0 disables). */
|
|
54
|
+
idleTimeoutMs?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Maximum number of buffered items when the consumer is slower than the feed (default 10 000).
|
|
57
|
+
* The oldest items are dropped beyond it and a `dropped` status is reported.
|
|
58
|
+
*/
|
|
59
|
+
highWaterMark?: number;
|
|
60
|
+
}
|
|
61
|
+
/** A live feed: an async iterable you can stop with `close()`, `break`, or an `AbortSignal`. */
|
|
62
|
+
export interface TickStream<T> extends AsyncIterable<T> {
|
|
63
|
+
close(): void;
|
|
64
|
+
readonly closed: boolean;
|
|
65
|
+
}
|
|
66
|
+
export interface SocketSession<T> {
|
|
67
|
+
/** Called on every (re)connection: send subscribe or auth messages here. */
|
|
68
|
+
onOpen(send: (message: unknown) => void): void;
|
|
69
|
+
/**
|
|
70
|
+
* Turn one decoded message into items. Throw to stop the stream with that error
|
|
71
|
+
* (for example a rejected subscription or credentials).
|
|
72
|
+
*/
|
|
73
|
+
onMessage(message: unknown, send: (message: unknown) => void): T[];
|
|
74
|
+
}
|
|
75
|
+
export interface ReconnectingStreamConfig<T> extends StreamOptions {
|
|
76
|
+
provider: string;
|
|
77
|
+
url: string;
|
|
78
|
+
WebSocket?: WebSocketConstructor;
|
|
79
|
+
clock?: Clock;
|
|
80
|
+
random?: () => number;
|
|
81
|
+
session: SocketSession<T>;
|
|
82
|
+
}
|
|
83
|
+
export declare function resolveWebSocket(ctor?: WebSocketConstructor): WebSocketConstructor;
|
|
84
|
+
/** Delay before reconnection attempt `attempt` (1-based). */
|
|
85
|
+
export declare function backoffDelay(attempt: number, options?: BackoffOptions, random?: () => number): number;
|
|
86
|
+
/**
|
|
87
|
+
* WebSocket feed that reconnects with exponential backoff and re-subscribes on every connection.
|
|
88
|
+
* Exposed as an async iterable with a bounded buffer.
|
|
89
|
+
*/
|
|
90
|
+
export declare function createReconnectingStream<T>(config: ReconnectingStreamConfig<T>): TickStream<T>;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { systemClock } from './clock.js';
|
|
2
|
+
import { TickwireError } from './errors.js';
|
|
3
|
+
const OPEN = 1;
|
|
4
|
+
export function resolveWebSocket(ctor) {
|
|
5
|
+
const impl = ctor ?? globalThis.WebSocket;
|
|
6
|
+
if (!impl) {
|
|
7
|
+
throw new TickwireError('No WebSocket implementation found. Use Node 22+, run Node 20 with --experimental-websocket, ' +
|
|
8
|
+
'or pass one: new BinanceProvider({ WebSocket }) with WebSocket from the "ws" package.');
|
|
9
|
+
}
|
|
10
|
+
return impl;
|
|
11
|
+
}
|
|
12
|
+
function decode(data) {
|
|
13
|
+
let text;
|
|
14
|
+
if (typeof data === 'string')
|
|
15
|
+
text = data;
|
|
16
|
+
else if (data instanceof ArrayBuffer)
|
|
17
|
+
text = new TextDecoder().decode(data);
|
|
18
|
+
else if (ArrayBuffer.isView(data))
|
|
19
|
+
text = new TextDecoder().decode(data);
|
|
20
|
+
else
|
|
21
|
+
text = String(data);
|
|
22
|
+
return JSON.parse(text);
|
|
23
|
+
}
|
|
24
|
+
/** Delay before reconnection attempt `attempt` (1-based). */
|
|
25
|
+
export function backoffDelay(attempt, options = {}, random = Math.random) {
|
|
26
|
+
const { initialMs = 500, maxMs = 30_000, factor = 2, jitter = 0.2 } = options;
|
|
27
|
+
const base = Math.min(maxMs, initialMs * factor ** Math.max(0, attempt - 1));
|
|
28
|
+
const spread = base * jitter;
|
|
29
|
+
return Math.max(0, Math.round(base - spread + random() * 2 * spread));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* WebSocket feed that reconnects with exponential backoff and re-subscribes on every connection.
|
|
33
|
+
* Exposed as an async iterable with a bounded buffer.
|
|
34
|
+
*/
|
|
35
|
+
export function createReconnectingStream(config) {
|
|
36
|
+
const WebSocketImpl = resolveWebSocket(config.WebSocket);
|
|
37
|
+
const clock = config.clock ?? systemClock;
|
|
38
|
+
const random = config.random ?? Math.random;
|
|
39
|
+
const idleTimeoutMs = config.idleTimeoutMs ?? 60_000;
|
|
40
|
+
const highWaterMark = config.highWaterMark ?? 10_000;
|
|
41
|
+
const maxAttempts = config.backoff?.maxAttempts ?? Infinity;
|
|
42
|
+
const buffer = [];
|
|
43
|
+
let waiter = null;
|
|
44
|
+
let finished = false;
|
|
45
|
+
let failure;
|
|
46
|
+
let socket = null;
|
|
47
|
+
let failedAttempts = 0;
|
|
48
|
+
let idleTimer;
|
|
49
|
+
let reconnectAbort = null;
|
|
50
|
+
let dropped = 0;
|
|
51
|
+
const status = (s) => {
|
|
52
|
+
try {
|
|
53
|
+
config.onStatus?.(s);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// a status callback must never break the feed
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const push = (item) => {
|
|
60
|
+
if (finished)
|
|
61
|
+
return;
|
|
62
|
+
if (waiter) {
|
|
63
|
+
const w = waiter;
|
|
64
|
+
waiter = null;
|
|
65
|
+
w.resolve({ value: item, done: false });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
buffer.push(item);
|
|
69
|
+
if (buffer.length > highWaterMark) {
|
|
70
|
+
buffer.shift();
|
|
71
|
+
dropped++;
|
|
72
|
+
if (dropped === 1 || dropped % 1000 === 0)
|
|
73
|
+
status({ type: 'dropped', count: dropped });
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const finish = (error) => {
|
|
77
|
+
if (finished)
|
|
78
|
+
return;
|
|
79
|
+
finished = true;
|
|
80
|
+
failure = error;
|
|
81
|
+
clearTimeout(idleTimer);
|
|
82
|
+
reconnectAbort?.abort();
|
|
83
|
+
config.signal?.removeEventListener('abort', onAbort);
|
|
84
|
+
const s = socket;
|
|
85
|
+
socket = null;
|
|
86
|
+
if (s) {
|
|
87
|
+
s.onopen = s.onmessage = s.onclose = s.onerror = null;
|
|
88
|
+
try {
|
|
89
|
+
s.close(1000, 'closed by client');
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
// ignore
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
status(error ? { type: 'closed', error } : { type: 'closed' });
|
|
96
|
+
if (waiter && buffer.length === 0) {
|
|
97
|
+
const w = waiter;
|
|
98
|
+
waiter = null;
|
|
99
|
+
if (error)
|
|
100
|
+
w.reject(error);
|
|
101
|
+
else
|
|
102
|
+
w.resolve({ value: undefined, done: true });
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const onAbort = () => finish();
|
|
106
|
+
const armIdle = () => {
|
|
107
|
+
clearTimeout(idleTimer);
|
|
108
|
+
if (idleTimeoutMs > 0) {
|
|
109
|
+
idleTimer = setTimeout(() => socket && dropConnection(socket, `no message for ${idleTimeoutMs} ms`), idleTimeoutMs);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const dropConnection = (s, reason) => {
|
|
113
|
+
if (finished || socket !== s)
|
|
114
|
+
return;
|
|
115
|
+
socket = null;
|
|
116
|
+
clearTimeout(idleTimer);
|
|
117
|
+
s.onopen = s.onmessage = s.onclose = s.onerror = null;
|
|
118
|
+
try {
|
|
119
|
+
s.close(4000, 'reconnecting');
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// ignore
|
|
123
|
+
}
|
|
124
|
+
void scheduleReconnect(reason);
|
|
125
|
+
};
|
|
126
|
+
const scheduleReconnect = async (reason) => {
|
|
127
|
+
failedAttempts++;
|
|
128
|
+
if (failedAttempts > maxAttempts) {
|
|
129
|
+
finish(new TickwireError(`${config.provider}: stream gave up after ${maxAttempts} attempts (${reason})`, { provider: config.provider }));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const delayMs = backoffDelay(failedAttempts, config.backoff, random);
|
|
133
|
+
status({ type: 'reconnecting', attempt: failedAttempts, delayMs, reason });
|
|
134
|
+
reconnectAbort = new AbortController();
|
|
135
|
+
try {
|
|
136
|
+
await clock.sleep(delayMs, reconnectAbort.signal);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (!finished)
|
|
142
|
+
connect();
|
|
143
|
+
};
|
|
144
|
+
const connect = () => {
|
|
145
|
+
status({ type: 'connecting', attempt: failedAttempts + 1 });
|
|
146
|
+
let s;
|
|
147
|
+
try {
|
|
148
|
+
s = new WebSocketImpl(config.url);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
void scheduleReconnect(error.message);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
socket = s;
|
|
155
|
+
const send = (message) => {
|
|
156
|
+
if (socket === s && s.readyState === OPEN)
|
|
157
|
+
s.send(typeof message === 'string' ? message : JSON.stringify(message));
|
|
158
|
+
};
|
|
159
|
+
s.onopen = () => {
|
|
160
|
+
if (socket !== s)
|
|
161
|
+
return;
|
|
162
|
+
status({ type: 'open' });
|
|
163
|
+
armIdle();
|
|
164
|
+
try {
|
|
165
|
+
config.session.onOpen(send);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
finish(error);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
s.onmessage = (event) => {
|
|
172
|
+
if (socket !== s)
|
|
173
|
+
return;
|
|
174
|
+
armIdle();
|
|
175
|
+
let items;
|
|
176
|
+
try {
|
|
177
|
+
items = config.session.onMessage(decode(event.data), send);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
finish(error instanceof Error ? error : new TickwireError(String(error), { provider: config.provider }));
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
failedAttempts = 0;
|
|
184
|
+
for (const item of items)
|
|
185
|
+
push(item);
|
|
186
|
+
};
|
|
187
|
+
s.onerror = () => {
|
|
188
|
+
// 'close' always follows; reconnection happens there.
|
|
189
|
+
};
|
|
190
|
+
s.onclose = (event) => {
|
|
191
|
+
dropConnection(s, `connection closed${event?.code ? ` (code ${event.code})` : ''}`);
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
if (config.signal?.aborted) {
|
|
195
|
+
finished = true;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
config.signal?.addEventListener('abort', onAbort, { once: true });
|
|
199
|
+
connect();
|
|
200
|
+
}
|
|
201
|
+
const iterator = {
|
|
202
|
+
next() {
|
|
203
|
+
if (buffer.length > 0)
|
|
204
|
+
return Promise.resolve({ value: buffer.shift(), done: false });
|
|
205
|
+
if (finished)
|
|
206
|
+
return failure ? Promise.reject(failure) : Promise.resolve({ value: undefined, done: true });
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
waiter = { resolve, reject };
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
return() {
|
|
212
|
+
finish();
|
|
213
|
+
buffer.length = 0;
|
|
214
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
[Symbol.asyncIterator]: () => iterator,
|
|
219
|
+
close: () => finish(),
|
|
220
|
+
get closed() {
|
|
221
|
+
return finished;
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Candle period: a count followed by a unit.
|
|
3
|
+
* `s` seconds, `m` minutes, `h` hours, `d` days, `w` weeks, `M` months (calendar).
|
|
4
|
+
* Examples: `1m`, `5m`, `1h`, `4h`, `1d`, `1w`, `1M`.
|
|
5
|
+
*/
|
|
6
|
+
export type Timeframe = `${number}${'s' | 'm' | 'h' | 'd' | 'w' | 'M'}`;
|
|
7
|
+
export type TimeframeUnit = 's' | 'm' | 'h' | 'd' | 'w' | 'M';
|
|
8
|
+
export interface ParsedTimeframe {
|
|
9
|
+
readonly count: number;
|
|
10
|
+
readonly unit: TimeframeUnit;
|
|
11
|
+
/** Duration in ms. Months count as 30 days (only used for paging estimates). */
|
|
12
|
+
readonly ms: number;
|
|
13
|
+
}
|
|
14
|
+
export declare function parseTimeframe(timeframe: string): ParsedTimeframe;
|
|
15
|
+
/** Duration of a timeframe in ms (months count as 30 days). */
|
|
16
|
+
export declare function timeframeToMs(timeframe: string): number;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { InvalidArgumentError } from './errors.js';
|
|
2
|
+
const UNIT_MS = {
|
|
3
|
+
s: 1_000,
|
|
4
|
+
m: 60_000,
|
|
5
|
+
h: 3_600_000,
|
|
6
|
+
d: 86_400_000,
|
|
7
|
+
w: 604_800_000,
|
|
8
|
+
M: 2_592_000_000,
|
|
9
|
+
};
|
|
10
|
+
export function parseTimeframe(timeframe) {
|
|
11
|
+
const match = /^([1-9]\d*)([smhdwM])$/.exec(timeframe);
|
|
12
|
+
if (!match)
|
|
13
|
+
throw new InvalidArgumentError(`Invalid timeframe "${timeframe}" (expected e.g. 1m, 15m, 1h, 1d, 1w, 1M)`);
|
|
14
|
+
const count = Number(match[1]);
|
|
15
|
+
const unit = match[2];
|
|
16
|
+
return { count, unit, ms: count * UNIT_MS[unit] };
|
|
17
|
+
}
|
|
18
|
+
/** Duration of a timeframe in ms (months count as 30 days). */
|
|
19
|
+
export function timeframeToMs(timeframe) {
|
|
20
|
+
return parseTimeframe(timeframe).ms;
|
|
21
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** Asset class of an instrument. */
|
|
2
|
+
export type AssetClass = 'crypto' | 'stock';
|
|
3
|
+
/**
|
|
4
|
+
* A tradable instrument, independent of any provider.
|
|
5
|
+
*
|
|
6
|
+
* Crypto pairs are written `BASE/QUOTE` (`BTC/USD`), stocks by their ticker (`AAPL`).
|
|
7
|
+
* Each provider translates this into its own native symbol; `native` overrides that translation.
|
|
8
|
+
*/
|
|
9
|
+
export interface Instrument {
|
|
10
|
+
/** Canonical symbol: `BTC/USD` or `AAPL`. */
|
|
11
|
+
readonly symbol: string;
|
|
12
|
+
readonly base: string;
|
|
13
|
+
/** Quote currency. Stocks default to `USD`. */
|
|
14
|
+
readonly quote: string;
|
|
15
|
+
readonly assetClass: AssetClass;
|
|
16
|
+
/** Provider-native symbol, used as is when set (for example `XBTUSD` on Kraken). */
|
|
17
|
+
readonly native?: string;
|
|
18
|
+
}
|
|
19
|
+
/** OHLCV candle. `time` is the open time of the period, in milliseconds since the Unix epoch (UTC). */
|
|
20
|
+
export interface Candle {
|
|
21
|
+
readonly time: number;
|
|
22
|
+
readonly open: number;
|
|
23
|
+
readonly high: number;
|
|
24
|
+
readonly low: number;
|
|
25
|
+
readonly close: number;
|
|
26
|
+
/** Volume in base units (shares for stocks). */
|
|
27
|
+
readonly volume: number;
|
|
28
|
+
/** `false` while the period is still running (streamed or most recent candle). */
|
|
29
|
+
readonly closed: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** Best bid/ask snapshot, with the last traded price when the provider gives it. */
|
|
32
|
+
export interface Quote {
|
|
33
|
+
readonly instrument: Instrument;
|
|
34
|
+
/** Time of the snapshot in ms (provider time when available, otherwise local receive time). */
|
|
35
|
+
readonly time: number;
|
|
36
|
+
readonly bid: number;
|
|
37
|
+
readonly ask: number;
|
|
38
|
+
readonly bidSize: number;
|
|
39
|
+
readonly askSize: number;
|
|
40
|
+
readonly last?: number;
|
|
41
|
+
}
|
|
42
|
+
/** Side of the aggressor (taker) of a trade, when known. */
|
|
43
|
+
export type TradeSide = 'buy' | 'sell';
|
|
44
|
+
export interface Trade {
|
|
45
|
+
readonly instrument: Instrument;
|
|
46
|
+
readonly id: string;
|
|
47
|
+
/** Execution time in ms since the Unix epoch. */
|
|
48
|
+
readonly time: number;
|
|
49
|
+
readonly price: number;
|
|
50
|
+
readonly size: number;
|
|
51
|
+
readonly side?: TradeSide;
|
|
52
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A point in time: `Date`, ms since epoch, or an ISO 8601 string. */
|
|
2
|
+
export type TimeInput = Date | number | string;
|
|
3
|
+
export declare function toMs(value: TimeInput, field?: string): number;
|
|
4
|
+
/** Parse a numeric field from a provider payload (numbers are often sent as strings). */
|
|
5
|
+
export declare function num(value: unknown, field: string, provider: string): number;
|
|
6
|
+
/** Parse an ISO 8601 / RFC 3339 timestamp from a provider payload. */
|
|
7
|
+
export declare function isoMs(value: unknown, field: string, provider: string): number;
|
|
8
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { InvalidArgumentError, ProviderError } from './errors.js';
|
|
2
|
+
export function toMs(value, field = 'time') {
|
|
3
|
+
const ms = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : Date.parse(value);
|
|
4
|
+
if (!Number.isFinite(ms))
|
|
5
|
+
throw new InvalidArgumentError(`Invalid ${field}: ${String(value)}`);
|
|
6
|
+
return ms;
|
|
7
|
+
}
|
|
8
|
+
/** Parse a numeric field from a provider payload (numbers are often sent as strings). */
|
|
9
|
+
export function num(value, field, provider) {
|
|
10
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
|
|
11
|
+
if (!Number.isFinite(n))
|
|
12
|
+
throw new ProviderError(`Unexpected ${field} in ${provider} payload: ${JSON.stringify(value)}`, { provider });
|
|
13
|
+
return n;
|
|
14
|
+
}
|
|
15
|
+
/** Parse an ISO 8601 / RFC 3339 timestamp from a provider payload. */
|
|
16
|
+
export function isoMs(value, field, provider) {
|
|
17
|
+
const ms = typeof value === 'string' ? Date.parse(value) : NaN;
|
|
18
|
+
if (!Number.isFinite(ms))
|
|
19
|
+
throw new ProviderError(`Unexpected ${field} in ${provider} payload: ${JSON.stringify(value)}`, { provider });
|
|
20
|
+
return ms;
|
|
21
|
+
}
|
|
22
|
+
export function isRecord(value) {
|
|
23
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type { AssetClass, Candle, Instrument, Quote, Trade, TradeSide } from './core/types.js';
|
|
2
|
+
export { AuthenticationError, InvalidArgumentError, NetworkError, NotSupportedError, ProviderError, RateLimitError, TickwireError, } from './core/errors.js';
|
|
3
|
+
export { parseTimeframe, timeframeToMs, type ParsedTimeframe, type Timeframe, type TimeframeUnit } from './core/timeframe.js';
|
|
4
|
+
export { instrument, type InstrumentLike, type InstrumentOptions } from './core/instrument.js';
|
|
5
|
+
export type { CandleQuery, Provider, ProviderCapabilities, RequestOptions } from './core/provider.js';
|
|
6
|
+
export { RateLimiter, type RateLimitOptions } from './core/rate-limiter.js';
|
|
7
|
+
export { backoffDelay, createReconnectingStream, type BackoffOptions, type ReconnectingStreamConfig, type SocketSession, type StreamOptions, type StreamStatus, type TickStream, type WebSocketConstructor, type WebSocketLike, } from './core/stream.js';
|
|
8
|
+
export { HttpClient, type FetchLike, type HttpClientOptions } from './core/http.js';
|
|
9
|
+
export { systemClock, type Clock } from './core/clock.js';
|
|
10
|
+
export { CandleBuilder, candlesFromTrades, periodStart } from './core/aggregate.js';
|
|
11
|
+
export type { TimeInput } from './core/util.js';
|
|
12
|
+
export type { ProviderOptions } from './providers/options.js';
|
|
13
|
+
export { BinanceProvider } from './providers/binance.js';
|
|
14
|
+
export { CoinbaseProvider } from './providers/coinbase.js';
|
|
15
|
+
export { KrakenProvider } from './providers/kraken.js';
|
|
16
|
+
export { AlpacaProvider, alpacaTimeframe, type AlpacaOptions } from './providers/alpaca.js';
|
|
17
|
+
export { createProvider, PROVIDER_IDS, type ProviderId } from './providers/create.js';
|
|
18
|
+
export { ago, nextPeriod, periodFloor, resolveTime, type Duration } from './series/time.js';
|
|
19
|
+
export { checkCandles, cleanCandles, type Gap, type SeriesReport } from './series/check.js';
|
|
20
|
+
export { defaultCacheDir, FileStore, MemoryStore, mergeRanges, missingRanges, type CandleStore, type SeriesKey, type StoredSeries, } from './series/store.js';
|
|
21
|
+
export { loadCandles, type LoadCandlesOptions } from './series/load.js';
|
|
22
|
+
export { liveCandles, type LiveCandlesOptions } from './series/live.js';
|
|
23
|
+
export { watch, type WatchCondition, type WatchContext, type WatchEvent, type WatchOptions } from './watch/watch.js';
|
|
24
|
+
export { appendJsonl, postJson } from './watch/sinks.js';
|
|
25
|
+
export * from './indicators/index.js';
|
|
26
|
+
export { backtest, maxDrawdown, sharpe, type BacktestMetrics, type BacktestOptions, type BacktestResult, type EquityPoint, type Fill, type RoundTrip, type Strategy, type StrategyContext, } from './backtest/backtest.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export { AuthenticationError, InvalidArgumentError, NetworkError, NotSupportedError, ProviderError, RateLimitError, TickwireError, } from './core/errors.js';
|
|
2
|
+
export { parseTimeframe, timeframeToMs } from './core/timeframe.js';
|
|
3
|
+
export { instrument } from './core/instrument.js';
|
|
4
|
+
export { RateLimiter } from './core/rate-limiter.js';
|
|
5
|
+
export { backoffDelay, createReconnectingStream, } from './core/stream.js';
|
|
6
|
+
export { HttpClient } from './core/http.js';
|
|
7
|
+
export { systemClock } from './core/clock.js';
|
|
8
|
+
export { CandleBuilder, candlesFromTrades, periodStart } from './core/aggregate.js';
|
|
9
|
+
export { BinanceProvider } from './providers/binance.js';
|
|
10
|
+
export { CoinbaseProvider } from './providers/coinbase.js';
|
|
11
|
+
export { KrakenProvider } from './providers/kraken.js';
|
|
12
|
+
export { AlpacaProvider, alpacaTimeframe } from './providers/alpaca.js';
|
|
13
|
+
export { createProvider, PROVIDER_IDS } from './providers/create.js';
|
|
14
|
+
export { ago, nextPeriod, periodFloor, resolveTime } from './series/time.js';
|
|
15
|
+
export { checkCandles, cleanCandles } from './series/check.js';
|
|
16
|
+
export { defaultCacheDir, FileStore, MemoryStore, mergeRanges, missingRanges, } from './series/store.js';
|
|
17
|
+
export { loadCandles } from './series/load.js';
|
|
18
|
+
export { liveCandles } from './series/live.js';
|
|
19
|
+
export { watch } from './watch/watch.js';
|
|
20
|
+
export { appendJsonl, postJson } from './watch/sinks.js';
|
|
21
|
+
export * from './indicators/index.js';
|
|
22
|
+
export { backtest, maxDrawdown, sharpe, } from './backtest/backtest.js';
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type Indicator } from './indicator.js';
|
|
2
|
+
export interface HLC {
|
|
3
|
+
high: number;
|
|
4
|
+
low: number;
|
|
5
|
+
close: number;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Average True Range with Wilder's smoothing (default period 14).
|
|
9
|
+
* The first true range is high - low; the first ATR is the mean of the first `period` true ranges.
|
|
10
|
+
*/
|
|
11
|
+
export declare class ATR implements Indicator<HLC, number> {
|
|
12
|
+
readonly period: number;
|
|
13
|
+
private prevClose;
|
|
14
|
+
private count;
|
|
15
|
+
private sum;
|
|
16
|
+
value: number | undefined;
|
|
17
|
+
constructor(period?: number);
|
|
18
|
+
next(bar: HLC): number | undefined;
|
|
19
|
+
reset(): void;
|
|
20
|
+
}
|
|
21
|
+
export declare function atr(bars: Iterable<HLC>, period?: number): (number | undefined)[];
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { checkNumber, checkPeriod, runBatch } from './indicator.js';
|
|
2
|
+
/**
|
|
3
|
+
* Average True Range with Wilder's smoothing (default period 14).
|
|
4
|
+
* The first true range is high - low; the first ATR is the mean of the first `period` true ranges.
|
|
5
|
+
*/
|
|
6
|
+
export class ATR {
|
|
7
|
+
period;
|
|
8
|
+
prevClose;
|
|
9
|
+
count = 0;
|
|
10
|
+
sum = 0;
|
|
11
|
+
value;
|
|
12
|
+
constructor(period = 14) {
|
|
13
|
+
this.period = period;
|
|
14
|
+
checkPeriod('ATR', period);
|
|
15
|
+
}
|
|
16
|
+
next(bar) {
|
|
17
|
+
checkNumber('ATR', bar.high);
|
|
18
|
+
checkNumber('ATR', bar.low);
|
|
19
|
+
checkNumber('ATR', bar.close);
|
|
20
|
+
const tr = this.prevClose === undefined
|
|
21
|
+
? bar.high - bar.low
|
|
22
|
+
: Math.max(bar.high - bar.low, Math.abs(bar.high - this.prevClose), Math.abs(bar.low - this.prevClose));
|
|
23
|
+
this.prevClose = bar.close;
|
|
24
|
+
this.count++;
|
|
25
|
+
if (this.count < this.period) {
|
|
26
|
+
this.sum += tr;
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
this.value = this.count === this.period ? (this.sum + tr) / this.period : (this.value * (this.period - 1) + tr) / this.period;
|
|
30
|
+
return this.value;
|
|
31
|
+
}
|
|
32
|
+
reset() {
|
|
33
|
+
this.prevClose = undefined;
|
|
34
|
+
this.count = 0;
|
|
35
|
+
this.sum = 0;
|
|
36
|
+
this.value = undefined;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export function atr(bars, period = 14) {
|
|
40
|
+
return runBatch(new ATR(period), bars);
|
|
41
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Indicator } from './indicator.js';
|
|
2
|
+
export interface BollingerValue {
|
|
3
|
+
middle: number;
|
|
4
|
+
upper: number;
|
|
5
|
+
lower: number;
|
|
6
|
+
}
|
|
7
|
+
export interface BollingerOptions {
|
|
8
|
+
period?: number;
|
|
9
|
+
/** Width of the bands in standard deviations (default 2). */
|
|
10
|
+
stdDev?: number;
|
|
11
|
+
}
|
|
12
|
+
/** Bollinger Bands: SMA ± k × population standard deviation over `period` values (defaults 20, 2). */
|
|
13
|
+
export declare class BollingerBands implements Indicator<number, BollingerValue> {
|
|
14
|
+
readonly period: number;
|
|
15
|
+
readonly stdDev: number;
|
|
16
|
+
private readonly window;
|
|
17
|
+
value: BollingerValue | undefined;
|
|
18
|
+
constructor(options?: BollingerOptions);
|
|
19
|
+
next(x: number): BollingerValue | undefined;
|
|
20
|
+
reset(): void;
|
|
21
|
+
}
|
|
22
|
+
export declare function bollinger(values: Iterable<number>, options?: BollingerOptions): (BollingerValue | undefined)[];
|