-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathevents.ts
More file actions
43 lines (39 loc) · 1.31 KB
/
events.ts
File metadata and controls
43 lines (39 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import EventSource from 'eventsource';
import { EventEmitter } from 'stream';
export const AlpacaEventStreams: {
[name: string]: string
} = {
ACCOUNT_STATUS: '/events/accounts/status',
TRADES: '/events/trades',
JOURNAL_STATUS: '/events/journals/status',
TRANSFER_STATUS: '/events/transfers/status',
NTA: '/events/nta',
};
export class AlpacaEvents extends EventEmitter {
authToken: string
basePath: string
streams: {[name: string]: EventSource} = {}
constructor ({apiKey, apiSecret, basePath}: {apiKey: string, apiSecret: string, basePath: string}) {
super();
this.authToken = `Basic ${Buffer.from(`${apiKey}:${apiSecret}`).toString("base64")}`;
this.basePath = basePath;
}
subscribe(stream: string, cb?: (data: any) => void) {
const es = new EventSource(this.basePath + stream, {headers: {authorization: this.authToken}});
es.onmessage = (message) => {
try {
const data = JSON.parse(message.data);
this.emit(stream, data);
} catch (error) {
this.emit("error", error);
}
};
es.onerror = (error) => {
this.emit("error", error);
};
if (cb) {
this.on(stream, cb);
}
this.streams[stream] = es;
}
}