This repository has been archived by the owner on Jan 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 240
/
GDAXFeed.ts
458 lines (435 loc) · 19.5 KB
/
GDAXFeed.ts
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on *
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
* License for the specific language governing permissions and limitations under the License. *
***************************************************************************************************************************/
import { AuthHeaders, GDAXAuthConfig, GDAXExchangeAPI } from './GDAXExchangeAPI';
import { Big } from '../../lib/types';
import {
ChangedOrderMessage,
LevelMessage,
MyOrderPlacedMessage,
NewOrderMessage,
OrderDoneMessage,
SnapshotMessage,
StreamMessage,
TickerMessage,
TradeExecutedMessage,
TradeFinalizedMessage,
TradeMessage,
UnknownMessage
} from '../../core/Messages';
import { OrderPool } from '../../lib/BookBuilder';
import {
GDAXChangeMessage,
GDAXDoneMessage,
GDAXL2UpdateMessage,
GDAXMatchMessage,
GDAXMessage,
GDAXOpenMessage,
GDAXSnapshotMessage,
GDAXTickerMessage
} from './GDAXMessages';
import { AuthenticatedExchangeAPI } from '../AuthenticatedExchangeAPI';
import { Level3Order, PriceLevelWithOrders } from '../../lib/Orderbook';
import { ExchangeFeed, ExchangeFeedConfig } from '../ExchangeFeed';
import { ExchangeAuthConfig } from '../AuthConfig';
export const GDAX_WS_FEED = 'wss://ws-feed.gdax.com';
/**
* Configuration interface for a GDAX websocket feed stream. `wsUrl` is used to override the default websocket URL.
* Usually, you don't need this, but you may want to obtain a feed from the sandbox for testing, or an historical
* message source, for example.
*
* The channels array determines which types of messages are sent back down the feed. Leave this as null to receive
* all messages, or specify any of
* - `level2` - The orderbook messages
* - `matches` - aLl trades
* - `ticker` - Ticker updates (these come after every trade, so specifying both `matches` and `ticker` may be redundant)
* - `user` - If you provided auth credentials, private messages will also be sent
*/
export interface GDAXFeedConfig extends ExchangeFeedConfig {
auth: GDAXAuthConfig;
wsUrl: string;
channels: string[]; // If supplied, the channels to subscribe to. This feature may be deprecated in a future release
apiUrl: string;
}
/**
* The GDAX message feed. Messages are created via a combination of WS and REST calls, which are then sent down the pipe.
* It handles automatically reconnects on errors and tracks the connection by monitoring a heartbeat.
* You can create the feeds from here, but it's preferable to use the `getFeed` or `FeedFactory` functions to get a
* connection from the pool
*/
export class GDAXFeed extends ExchangeFeed {
private products: Set<string>;
private gdaxAPI: GDAXExchangeAPI;
private queue: { [product: string]: any[] } = {};
private queueing: { [product: string]: boolean } = {};
private internalSequence: { [index: string]: number } = {};
private channels: string[];
constructor(config: GDAXFeedConfig) {
super(config);
this.products = new Set<string>();
this.channels = config.channels || ['level2', 'matches', 'ticker', 'user', 'heartbeat'];
if (!(this.channels as any).includes('heartbeat')) {
this.channels.push('heartbeat');
}
this.gdaxAPI = new GDAXExchangeAPI(config);
this.connect();
}
get owner(): string {
return 'GDAX';
}
/**
* Returns the Authenticated API instance if auth credentials were supplied in the constructor; null otherwise
*/
get authenticatedAPI(): AuthenticatedExchangeAPI {
if (this.auth) {
return this.gdaxAPI;
}
return null;
}
/**
* Subscribe to the products given in the `products` array.
*
* `subscribe` returns a Promise that resolves to true if the subscription was successful.
*/
subscribe(products: string[]): Promise<boolean> {
if (!this.isConnected()) {
return Promise.reject(
new Error('Socket is not connected. Have you called connect()? Otherwise the connection may have dropped and is in the process of reconnecting.')
);
}
// To reset, we need to make a call with `product_ids` set
return new Promise((resolve, reject) => {
let subscribeMessage: any = {
type: 'subscribe',
product_ids: products // Use product_id to prevent clearing the other subscriptions
};
subscribeMessage.channels = this.channels;
// Add Signature
if (this.auth) {
subscribeMessage = this.signMessage(subscribeMessage);
}
this.send(subscribeMessage, (err: Error) => {
if (err) {
this.log('error', `The subscription request to ${products.join(',')} on ${this.url} ${this.auth ? '(authenticated)' : ''} failed`, { error: err });
this.emit('error', err);
return reject(err);
}
this.products = new Set<string>();
products.forEach((p) => {
this.products.add(p);
});
return resolve(true);
});
});
}
protected onClose(code: number, reason: string) {
// The feed has been closed by the other party. Wait a few seconds and then reconnect
this.log('info', `The websocket feed to ${this.url} ${this.auth ? '(authenticated)' : ''} has been closed by an external party. We will reconnect in 5 seconds`, {
code: code,
reason: reason
});
this.reconnect(5000);
}
protected validateAuth(auth: ExchangeAuthConfig): ExchangeAuthConfig {
auth = super.validateAuth(auth);
return auth && (auth as GDAXAuthConfig).passphrase ? auth : undefined;
}
/**
* Converts a GDAX feed message into a GTT [[StreamMessage]] instance
*/
protected handleMessage(msg: string): void {
try {
const feedMessage: GDAXMessage = JSON.parse(msg);
let message: StreamMessage;
switch (feedMessage.type) {
case 'heartbeat':
this.confirmAlive();
return;
case 'ticker':
message = this.mapTicker(feedMessage as GDAXTickerMessage);
break;
case 'l2update':
this.processUpdate(feedMessage as GDAXL2UpdateMessage);
return;
case 'snapshot':
this.processSnapshot(this.createSnapshotMessage(feedMessage as GDAXSnapshotMessage));
return;
default:
message = this.mapFullFeed(feedMessage);
}
if (message) {
if ((feedMessage as any).sequence) {
(message as any).sourceSequence = (feedMessage as any).sequence;
}
this.pushMessage(message);
}
} catch (err) {
err.ws_msg = msg;
this.onError(err);
}
}
protected onOpen() {
// If we have any products (this might be a reconnect), then re-subscribe to them
if (this.products.size > 0) {
const products = Array.from(this.products);
this.log('debug', `Resubscribing to ${products.join(' ')}...`);
this.subscribe(products).then((result) => {
if (result) {
this.log('debug', `Reconnection to ${products.join(', ')} successful`);
} else {
this.log('debug', `We were already connected to the feed it seems.`);
}
}, (err) => {
this.log('error', 'An error occurred while reconnecting. Trying again in 30s', { error: err });
this.reconnect(30000);
});
}
}
private signMessage(msg: any): any {
const headers: AuthHeaders = this.gdaxAPI.getSignature('GET', '/users/self', '');
msg.signature = headers['CB-ACCESS-SIGN'];
msg.key = headers['CB-ACCESS-KEY'];
msg.timestamp = headers['CB-ACCESS-TIMESTAMP'];
msg.passphrase = headers['CB-ACCESS-PASSPHRASE'];
return msg;
}
/**
* Returns the current message counter value for the given product. This does not correspond to the
* official sequence numbers of the message feeds (if they exist), but is purely an internal counter value
*/
private getSequence(product: string) {
if (!this.internalSequence[product]) {
this.internalSequence[product] = 1;
}
return this.internalSequence[product];
}
/**
* Marked for deprecation
*/
private pushMessage(message: StreamMessage): void {
const product: string = (message as any).productId;
const needsQueue = (message as any).sequence && this.queueing[product];
// If we're waiting for a snapshot, and the message needs one (i.e. has a sequence number) queue it up, else send it straight on
if (!product || !needsQueue) {
this.push(message);
return;
}
this.queue[product].push(message);
}
private createSnapshotMessage(snapshot: GDAXSnapshotMessage): SnapshotMessage {
const product: string = snapshot.product_id;
const orders: OrderPool = {};
const snapshotMessage: SnapshotMessage = {
type: 'snapshot',
time: new Date(),
productId: product,
sequence: this.getSequence(product),
asks: [],
bids: [],
orderPool: orders
};
['buy', 'sell'].forEach((side: string) => {
const levelArray = side === 'buy' ? 'bids' : 'asks';
snapshot[levelArray].forEach(([price, size]) => {
if (+size === 0) {
return;
}
const newOrder: Level3Order = {
id: price,
price: Big(price),
size: Big(size),
side: side
};
const level: PriceLevelWithOrders = {
price: Big(price),
totalSize: Big(size),
orders: [newOrder]
};
snapshotMessage[levelArray].push(level);
orders[newOrder.id] = newOrder;
});
});
return snapshotMessage;
}
private processUpdate(update: GDAXL2UpdateMessage) {
const product: string = update.product_id;
update.changes.forEach(([side, price, newSize]) => {
this.internalSequence[product] = this.getSequence(product) + 1;
const message: LevelMessage = {
type: 'level',
time: new Date(),
price: price,
size: newSize,
count: 1,
sequence: this.getSequence(product),
productId: update.product_id,
side: side
};
this.pushMessage(message);
});
}
private mapTicker(ticker: GDAXTickerMessage): StreamMessage {
return {
type: 'ticker',
time: new Date(ticker.time),
productId: ticker.product_id,
sequence: ticker.sequence,
price: Big(ticker.price),
bid: Big(ticker.best_bid),
ask: Big(ticker.best_ask),
trade_id: String(ticker.trade_id),
size: Big(ticker.last_size)
} as TickerMessage;
}
private mapFullFeed(feedMessage: GDAXMessage): StreamMessage {
if (feedMessage.user_id) {
return this.mapAuthMessage(feedMessage);
}
const message: StreamMessage = this.mapMessage(feedMessage);
return message;
}
private processSnapshot(snapshot: SnapshotMessage) {
this.push(snapshot);
this.emit('snapshot');
}
/**
* Converts GDAX messages into standardised GTT messages. Unknown messages are passed on as_is
* @param feedMessage
*/
private mapMessage(feedMessage: GDAXMessage): StreamMessage {
switch (feedMessage.type) {
case 'open':
return {
type: 'newOrder',
time: new Date((feedMessage as GDAXOpenMessage).time),
sequence: (feedMessage as GDAXOpenMessage).sequence,
productId: (feedMessage as GDAXOpenMessage).product_id,
orderId: (feedMessage as GDAXOpenMessage).order_id,
side: (feedMessage as GDAXOpenMessage).side,
price: (feedMessage as GDAXOpenMessage).price,
size: (feedMessage as GDAXOpenMessage).remaining_size
} as NewOrderMessage;
case 'done':
// remaining size is usually 0 -- and the corresponding match messages will have adjusted the orderbook
// There are cases when market orders are filled but remaining size is non-zero. This is as a result of STP
// or rounding, but the accounting is nevertheless correct. So if reason is 'filled' we can set the size
// to zero before removing the order. Otherwise if cancelled, remaining_size refers to the size
// that was on the order book
const size = (feedMessage as GDAXDoneMessage).reason === 'filled' ? '0' : (feedMessage as GDAXDoneMessage).remaining_size;
return {
type: 'orderDone',
time: new Date((feedMessage as GDAXDoneMessage).time),
sequence: (feedMessage as GDAXDoneMessage).sequence,
productId: (feedMessage as GDAXDoneMessage).product_id,
orderId: (feedMessage as GDAXDoneMessage).order_id,
remainingSize: size,
price: (feedMessage as GDAXDoneMessage).price,
side: (feedMessage as GDAXDoneMessage).side,
reason: (feedMessage as GDAXDoneMessage).reason
} as OrderDoneMessage;
case 'match':
return this.mapMatchMessage(feedMessage as GDAXMatchMessage);
case 'change':
const change: GDAXChangeMessage = feedMessage as GDAXChangeMessage;
if (change.new_funds && !change.new_size) {
change.new_size = (Big(change.new_funds).div(change.price).toString());
}
return {
type: 'changedOrder',
time: new Date(change.time),
sequence: change.sequence,
productId: change.product_id,
orderId: change.order_id,
side: change.side,
price: change.price,
newSize: change.new_size
} as ChangedOrderMessage;
default:
return {
type: 'unknown',
time: new Date(),
sequence: (feedMessage as any).sequence,
productId: feedMessage.product_id,
message: feedMessage
} as UnknownMessage;
}
}
private mapMatchMessage(msg: GDAXMatchMessage): TradeMessage {
const takerSide: string = msg.side === 'buy' ? 'sell' : 'buy';
const trade: TradeMessage = {
type: 'trade',
time: new Date(msg.time),
productId: msg.product_id,
tradeId: msg.trade_id,
side: takerSide,
price: msg.price,
size: msg.size
};
return trade;
}
/**
* When the user_id field is set, these are authenticated messages only we receive and so deserve special
* consideration
*/
private mapAuthMessage(feedMessage: GDAXMessage): StreamMessage {
switch (feedMessage.type) {
case 'match':
const isTaker: boolean = !!(feedMessage as any).taker_user_id;
const time = (feedMessage as any).time ? new Date((feedMessage as any).time) : new Date();
let side: string;
if (!isTaker) {
side = (feedMessage as GDAXMatchMessage).side;
} else {
side = (feedMessage as GDAXMatchMessage).side === 'buy' ? 'sell' : 'buy';
}
return {
type: 'tradeExecuted',
time: time,
productId: (feedMessage as GDAXMatchMessage).product_id,
orderId: isTaker ? (feedMessage as GDAXMatchMessage).taker_order_id : (feedMessage as GDAXMatchMessage).maker_order_id,
orderType: isTaker ? 'market' : 'limit',
side: side,
tradeSize: (feedMessage as GDAXMatchMessage).size,
remainingSize: null
} as TradeExecutedMessage;
case 'done':
return {
type: 'tradeFinalized',
time: time,
productId: (feedMessage as GDAXDoneMessage).product_id,
orderId: (feedMessage as GDAXDoneMessage).order_id,
reason: (feedMessage as GDAXDoneMessage).reason,
side: (feedMessage as GDAXDoneMessage).side,
filledSize: (feedMessage as GDAXMatchMessage).size,
remainingSize: (feedMessage as GDAXDoneMessage).remaining_size,
} as TradeFinalizedMessage;
case 'open':
return {
type: 'myOrderPlaced',
time: time,
productId: (feedMessage as GDAXOpenMessage).product_id,
orderId: (feedMessage as GDAXOpenMessage).order_id,
side: (feedMessage as GDAXOpenMessage).side,
price: (feedMessage as GDAXOpenMessage).price,
orderType: (feedMessage as GDAXOpenMessage).type,
size: (feedMessage as GDAXOpenMessage).remaining_size,
sequence: (feedMessage as GDAXOpenMessage).sequence
} as MyOrderPlacedMessage;
default:
return {
type: 'unknown',
message: feedMessage
} as UnknownMessage;
}
}
}