-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
251 lines (195 loc) · 5.68 KB
/
index.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
const WebSocket = require('ws');
const EventEmitter = require('events');
const crypto = require('crypto');
const wait = n => new Promise(r => setTimeout(r, n));
const PONG = '{"type":"pong"}';
const STALE_TIMEOUT = 2000;
// this endpoint is used by the sample code on
// https://github.com/ftexchange/ftx/blob/d387304bcc6f479e0ecae8273ad84eda986f5237/websocket/client.py#L13
const DEFAULT_ENDPOINT = 'ftx.com/ws/';
// pass optional params: { key, secret, subaccount, endpoint }
class Connection extends EventEmitter {
constructor(conf = {}) {
super();
this.key = conf.key;
this.secret = conf.secret;
this.subaccount = conf.subaccount;
this.WSendpoint = conf.endpoint || DEFAULT_ENDPOINT;
this.connected = false;
this.isReadyHook = false;
this.isReady = new Promise((r => this.isReadyHook = r));
this.authenticated = false;
this.reconnecting = false;
this.afterReconnect;
this.subscriptions = [];
this.lastMessageAt = 0;
}
_connect() {
if(this.connected) {
return;
}
return new Promise((resolve, reject) => {
this.ws = new WebSocket(`wss://${this.WSendpoint}`);
this.ws.onmessage = this.handleWSMessage;
this.ws.onopen = () => {
this.connected = true;
clearTimeout(this.openTimeout);
this.heartbeat = setInterval(this.ping, 5 * 1000);
this.isReadyHook();
resolve();
}
this.ws.onerror = e => {
console.log(new Date, '[FTX] WS ERROR', e.message);
}
this.ws.onclose = async e => {
console.log(new Date, '[FTX] CLOSED CON');
this.emit('statusChange', 'close');
this.authenticated = false;
this.connected = false;
clearInterval(this.heartbeat);
this.reconnect();
}
this.openTimeout = setTimeout(() => {
throw new Error('[ftx ws] could not establish connection within 15 seconds.')
}, 1000 * 15);
});
}
terminate = async() => {
console.log(new Date, '[FTX] TERMINATED WS CON');
this.ws.terminate();
this.authenticated = false;
this.connected = false;
}
reconnect = async () => {
this.reconnecting = true;
this.pingAt = false;
this.pongAt = false;
let hook;
this.afterReconnect = new Promise(r => hook = r);
this.isReady = new Promise((r => this.isReadyHook = r));
await wait(500);
console.log(new Date, '[FTX] RECONNECTING...');
await this.connect();
hook();
this.isReadyHook();
this.subscriptions.forEach(sub => {
this._subscribe(sub);
});
}
connect = async () => {
await this._connect();
this.emit('statusChange', 'open');
if(this.key) {
await this.authenticate();
}
}
// not a proper op, but forces a response so
// we know the connection isn't stale
ping = () => {
if(this.pingAt && this.pongAt > this.pingAt && this.pongAt - this.pingAt > STALE_TIMEOUT) {
console.error(new Date, '[FTX] did NOT receive pong in time, reconnecting', {
pingAt: this.pingAt,
pongAt: this.pongAt
});
return this.terminate();
}
this.pingAt = Date.now();
this.sendMessage({op: 'ping'});
}
// note: when this method returns
// we do not know what auth status is
// since FTX doesn't ACK
authenticate = async () => {
if(!this.connected) {
await this.connect();
}
const date = Date.now();
const signature = crypto.createHmac('sha256', this.secret)
.update(date + 'websocket_login').digest('hex');
const message = {
op: 'login',
args: {
key: this.key,
sign: signature,
time: date,
subaccount: this.subaccount
}
}
this.sendMessage(message);
this.authenticated = true;
}
handleWSMessage = e => {
this.lastMessageAt = Date.now();
let payload;
if(e.data === PONG && this.lastMessageAt - this.pingAt < 5000) {
this.pongAt = this.lastMessageAt;
return;
}
try {
payload = JSON.parse(e.data);
} catch(e) {
console.error('ftx send bad json', e.data);
}
if(payload.type === 'subscribed') {
this.subscriptions.forEach(sub => {
if(sub.market === payload.market && sub.channel === payload.channel) {
sub.doneHook();
}
});
}
else if(payload.type === 'update' || payload.type === 'partial') {
const id = this.toId(payload.market, payload.channel);
this.emit(id, payload.data, e.data);
}
else {
console.log(new Date, '[FTX] unhandled WS event', payload);
}
}
toId(market, channel) {
if(!market) {
return channel;
}
return market + '::' + channel;
}
sendMessage = async (payload) => {
if(!this.connected) {
if(!this.reconnecting) {
throw new Error('[ftx ws] Not connected.');
}
await this.afterReconnect;
}
this.ws.send(JSON.stringify(payload));
}
subscribe = async (channel, market = undefined) => {
const id = this.toId(market, channel);
if(!this.connected) {
if(!this.reconnecting) {
throw new Error('[ftx ws] Not connected.');
}
await this.afterReconnect;
}
if(this.subscriptions.map(s => s.id).includes(id)) {
return console.error(new Date, 'refusing to channel subscribe twice', market, channel);
}
const sub = {
id,
channel,
market,
doneHook: false,
done: false
}
this.subscriptions.push(sub);
this._subscribe(sub);
return sub.done;
}
_subscribe(sub) {
sub.done = new Promise(r => sub.doneHook = r);
const message = {
op: 'subscribe',
market: sub.market,
channel: sub.channel
}
this.sendMessage(message);
}
}
module.exports = Connection;