-
Notifications
You must be signed in to change notification settings - Fork 941
Expand file tree
/
Copy pathcoinbase.ts
More file actions
844 lines (692 loc) · 29 KB
/
coinbase.ts
File metadata and controls
844 lines (692 loc) · 29 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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
/// <reference path="../utils.ts" />
/// <reference path="../../common/models.ts" />
/// <reference path="nullgw.ts" />
/// <reference path="../interfaces.ts"/>
import Config = require("../config");
import request = require('request');
import url = require("url");
import querystring = require("querystring");
import NullGateway = require("./nullgw");
import Models = require("../../common/models");
import Utils = require("../utils");
import Interfaces = require("../interfaces");
import io = require("socket.io-client");
import moment = require("moment");
import WebSocket = require('ws');
import _ = require('lodash');
var uuid = require('node-uuid');
import CoinbaseExchange = require("./coinbase-api");
var SortedArrayMap = require("collections/sorted-array-map");
interface StateChange {
old: string;
new: string;
}
interface CoinbaseBase {
type: string;
side: string; // "buy"/"sell"
sequence: number;
}
// A valid order has been received and is now active. This message is emitted for every single valid order as soon as
// the matching engine receives it whether it fills immediately or not.
// The received message does not indicate a resting order on the order book. It simply indicates a new incoming order
// which as been accepted by the matching engine for processing. Received orders may cause match message to follow if
// they are able to begin being filled (taker behavior). Self-trade prevention may also trigger change messages to
// follow if the order size needs to be adjusted. Orders which are not fully filled or canceled due to self-trade
// prevention result in an open message and become resting orders on the order book.
interface CoinbaseReceived extends CoinbaseBase {
client_oid?: string;
order_id: string; // guid
size: string; // "0.00"
price: string; // "0.00"
}
// The order is now open on the order book. This message will only be sent for orders which are not fully filled
// immediately. remaining_size will indicate how much of the order is unfilled and going on the book.
interface CoinbaseOpen extends CoinbaseBase {
order_id: string; // guid
price: string;
remaining_size: string;
}
// The order is no longer on the order book. Sent for all orders for which there was a received message.
// This message can result from an order being canceled or filled. There will be no more messages for this order_id
// after a done message. remaining_size indicates how much of the order went unfilled; this will be 0 for filled orders.
interface CoinbaseDone extends CoinbaseBase {
price: string;
order_id: string;
reason: string; // "filled"??
remaining_size: string;
}
// A trade occurred between two orders. The aggressor or taker order is the one executing immediately after
// being received and the maker order is a resting order on the book. The side field indicates the maker order side.
// If the side is sell this indicates the maker was a sell order and the match is considered an up-tick. A buy side
// match is a down-tick.
interface CoinbaseMatch extends CoinbaseBase {
trade_id: number; //": 10,
maker_order_id: string;
taker_order_id: string;
time: string; // "2014-11-07T08:19:27.028459Z",
size: string;
price: string;
}
// An order has changed in size. This is the result of self-trade prevention adjusting the order size.
// Orders can only decrease in size. change messages are sent anytime an order changes in size;
// this includes resting orders (open) as well as received but not yet open.
interface CoinbaseChange extends CoinbaseBase {
order_id: string;
time: string;
new_size: string;
old_size: string;
price: string;
}
interface CoinbaseEntry {
size: string;
price: string;
id: string;
}
interface CoinbaseBookStorage {
sequence: string;
bids: { [id: string]: CoinbaseEntry };
asks: { [id: string]: CoinbaseEntry };
}
interface CoinbaseOrderEmitter {
on(event: string, cb: Function): CoinbaseOrderEmitter;
on(event: 'statechange', cb: (data: StateChange) => void): CoinbaseOrderEmitter;
on(event: 'received', cd: (msg: Models.Timestamped<CoinbaseReceived>) => void): CoinbaseOrderEmitter;
on(event: 'open', cd: (msg: Models.Timestamped<CoinbaseOpen>) => void): CoinbaseOrderEmitter;
on(event: 'done', cd: (msg: Models.Timestamped<CoinbaseDone>) => void): CoinbaseOrderEmitter;
on(event: 'match', cd: (msg: Models.Timestamped<CoinbaseMatch>) => void): CoinbaseOrderEmitter;
on(event: 'change', cd: (msg: Models.Timestamped<CoinbaseChange>) => void): CoinbaseOrderEmitter;
on(event: 'error', cd: (msg: Models.Timestamped<Error>) => void): CoinbaseOrderEmitter;
state: string;
book: CoinbaseBookStorage;
}
interface CoinbaseOrder {
client_oid?: string;
price?: string;
size: string;
product_id: string;
stp?: string;
time_in_force?: string;
post_only?: boolean;
funds?: string;
type?: string;
}
interface CoinbaseOrderAck {
id: string;
error?: string;
message?: string;
}
interface CoinbaseAccountInformation {
id: string;
balance: string;
hold: string;
available: string;
currency: string;
}
interface CoinbaseRESTTrade {
time: string;
trade_id: number;
price: string;
size: string;
side: string;
}
interface CoinbaseAuthenticatedClient {
buy(order: CoinbaseOrder, cb: (err?: Error, response?: any, ack?: CoinbaseOrderAck) => void);
sell(order: CoinbaseOrder, cb: (err?: Error, response?: any, ack?: CoinbaseOrderAck) => void);
cancelOrder(id: string, cb: (err?: Error, response?: any) => void);
getOrders(cb: (err?: Error, response?: any, ack?: CoinbaseOpen[]) => void);
cancelAllOrders(cb: (err?: Error, response?: string[]) => void);
getProductTrades(product: string, cb: (err?: Error, response?: any, ack?: CoinbaseRESTTrade[]) => void);
getAccounts(cb: (err?: Error, response?: any, info?: CoinbaseAccountInformation[]) => void);
getAccount(accountID: string, cb: (err?: Error, response?: any, info?: CoinbaseAccountInformation) => void);
}
function convertConnectivityStatus(s: StateChange) {
return s.new === "processing" ? Models.ConnectivityStatus.Connected : Models.ConnectivityStatus.Disconnected;
}
function convertSide(msg: CoinbaseBase): Models.Side {
return msg.side === "buy" ? Models.Side.Bid : Models.Side.Ask;
}
function convertPrice(pxStr: string) {
return parseFloat(pxStr);
}
function convertSize(szStr: string) {
return parseFloat(szStr);
}
function convertTime(time: string) {
return moment(time);
}
class PriceLevel {
orders: { [id: string]: number } = {};
marketUpdate = new Models.MarketSide(0, 0);
}
class CoinbaseOrderBook {
private static Eq = (a, b) => Math.abs(a - b) < 1e-4;
private static BidCmp = (a, b) => {
if (CoinbaseOrderBook.Eq(a, b)) return 0;
return a > b ? -1 : 1
};
private static AskCmp = (a, b) => {
if (CoinbaseOrderBook.Eq(a, b)) return 0;
return a > b ? 1 : -1
};
public bids: any = new SortedArrayMap([], CoinbaseOrderBook.Eq, CoinbaseOrderBook.BidCmp);
public asks: any = new SortedArrayMap([], CoinbaseOrderBook.Eq, CoinbaseOrderBook.AskCmp);
private getStorage = (side: Models.Side): any => {
if (side === Models.Side.Bid) return this.bids;
if (side === Models.Side.Ask) return this.asks;
};
private addToOrderBook = (storage: any, price: number, size: number, order_id: string) => {
var priceLevelStorage: PriceLevel = storage.get(price);
if (typeof priceLevelStorage === "undefined") {
var pl = new PriceLevel();
pl.marketUpdate.price = price;
priceLevelStorage = pl;
storage.set(price, pl);
}
priceLevelStorage.marketUpdate.size += size;
priceLevelStorage.orders[order_id] = size;
};
public onReceived = (msg: CoinbaseReceived, t: moment.Moment): boolean => {
var price = convertPrice(msg.price);
var size = convertSize(msg.size);
var side = convertSide(msg);
var otherSide = side === Models.Side.Bid ? Models.Side.Ask : Models.Side.Bid;
var storage = this.getStorage(otherSide);
var changed = false;
var remaining_size = size;
for (var i = 0; i < storage.store.length; i++) {
if (remaining_size <= 0) break;
var kvp = storage.store.array[i];
var price_level = kvp.key;
if (side === Models.Side.Bid && price < price_level) break;
if (side === Models.Side.Ask && price > price_level) break;
var level_size = kvp.value.marketUpdate.size;
if (level_size <= remaining_size) {
storage.delete(price_level);
remaining_size -= level_size;
changed = true;
}
}
return changed;
}
public onOpen = (msg: CoinbaseOpen, t: moment.Moment) => {
var price = convertPrice(msg.price);
var side = convertSide(msg);
var storage = this.getStorage(side);
this.addToOrderBook(storage, price, convertSize(msg.remaining_size), msg.order_id);
};
public onDone = (msg: CoinbaseDone, t: moment.Moment): boolean => {
var price = convertPrice(msg.price);
var side = convertSide(msg);
var storage = this.getStorage(side);
var priceLevelStorage = storage.get(price);
if (typeof priceLevelStorage === "undefined")
return false;
var orderSize = priceLevelStorage.orders[msg.order_id];
if (typeof orderSize === "undefined")
return false;
priceLevelStorage.marketUpdate.size -= orderSize;
delete priceLevelStorage.orders[msg.order_id];
if (_.isEmpty(priceLevelStorage.orders)) {
storage.delete(price);
}
return true;
};
public onMatch = (msg: CoinbaseMatch, t: moment.Moment): boolean => {
var price = convertPrice(msg.price);
var size = convertSize(msg.size);
var side = convertSide(msg);
var makerStorage = this.getStorage(side);
var priceLevelStorage = makerStorage.get(price);
if (typeof priceLevelStorage !== "undefined") {
priceLevelStorage.marketUpdate.size -= size;
priceLevelStorage.orders[msg.maker_order_id] -= size;
if (priceLevelStorage.orders[msg.maker_order_id] < 1e-4)
delete priceLevelStorage.orders[msg.maker_order_id];
if (_.isEmpty(priceLevelStorage.orders)) {
makerStorage.delete(price);
}
return true;
}
return false;
};
public onChange = (msg: CoinbaseChange, t: moment.Moment): boolean => {
var price = convertPrice(msg.price);
var side = convertSide(msg);
var storage = this.getStorage(side);
var priceLevelStorage: PriceLevel = storage.get(convertPrice(msg.price));
if (typeof priceLevelStorage === "undefined")
return false;
var oldSize = priceLevelStorage.orders[msg.order_id];
if (typeof oldSize === "undefined")
return false;
var newSize = convertSize(msg.new_size);
priceLevelStorage.orders[msg.order_id] = newSize;
priceLevelStorage.marketUpdate.size -= (oldSize - newSize);
return true;
};
public clear = () => {
this.asks.clear();
this.bids.clear();
}
public initialize = (book: CoinbaseBookStorage) => {
var add = (st, u) =>
this.addToOrderBook(st, convertPrice(u.price), convertSize(u.size), u.id);
_.forEach(book.asks, a => add(this.asks, a));
_.forEach(book.bids, b => add(this.bids, b));
};
}
class CoinbaseMarketDataGateway implements Interfaces.IMarketDataGateway {
MarketData = new Utils.Evt<Models.Market>();
MarketTrade = new Utils.Evt<Models.MarketSide>();
ConnectChanged = new Utils.Evt<Models.ConnectivityStatus>();
private onReceived = (msg: CoinbaseReceived, t: moment.Moment) => {
if (this._orderBook.onReceived(msg, t)) {
this.reevalBids();
this.reevalAsks();
this.raiseMarketData(t);
}
}
private onOpen = (msg: CoinbaseOpen, t: moment.Moment) => {
var price = convertPrice(msg.price);
var side = convertSide(msg);
this._orderBook.onOpen(msg, t);
this.onOrderBookChanged(t, side, price);
};
private onDone = (msg: CoinbaseDone, t: moment.Moment) => {
var price = convertPrice(msg.price);
var side = convertSide(msg);
if (this._orderBook.onDone(msg, t)) {
this.onOrderBookChanged(t, side, price);
}
};
private onMatch = (msg: CoinbaseMatch, t: moment.Moment) => {
var price = convertPrice(msg.price);
var size = convertSize(msg.size);
var side = convertSide(msg);
if (this._orderBook.onMatch(msg, t)) {
this.onOrderBookChanged(t, side, price);
}
this.MarketTrade.trigger(new Models.GatewayMarketTrade(price, size, convertTime(msg.time), false, side));
};
private onChange = (msg: CoinbaseChange, t: moment.Moment) => {
var price = convertPrice(msg.price);
var side = convertSide(msg);
if (this._orderBook.onChange(msg, t)) {
this.onOrderBookChanged(t, side, price);
}
};
private _cachedBids: Models.MarketSide[] = null;
private _cachedAsks: Models.MarketSide[] = null;
private reevalBids = () => {
this._cachedBids = _.map(this._orderBook.bids.store.slice(0, 3), s => (<any>s).value.marketUpdate);
};
private reevalAsks = () => {
this._cachedAsks = _.map(this._orderBook.asks.store.slice(0, 3), s => (<any>s).value.marketUpdate);
};
private onOrderBookChanged = (t: moment.Moment, side: Models.Side, price: number) => {
if (side === Models.Side.Bid) {
if (this._cachedBids.length > 0 && price < _.last(this._cachedBids).price) return;
else this.reevalBids();
}
if (side === Models.Side.Ask) {
if (this._cachedAsks.length > 0 && price > _.last(this._cachedAsks).price) return;
else this.reevalAsks();
}
this.raiseMarketData(t);
};
private onStateChange = (s: StateChange) => {
var t = this._timeProvider.utcNow();
var status = convertConnectivityStatus(s);
if (status === Models.ConnectivityStatus.Connected) {
this._orderBook.initialize(this._client.book);
}
else {
this._orderBook.clear();
}
this.ConnectChanged.trigger(status);
this.reevalBids();
this.reevalAsks();
this.raiseMarketData(t);
};
private raiseMarketData = (t: moment.Moment) => {
if (typeof this._cachedBids[0] !== "undefined" && typeof this._cachedAsks[0] !== "undefined") {
if (this._cachedBids[0].price > this._cachedAsks[0].price) {
this._log.warn("Crossed Coinbase market detected! bid:", this._cachedBids[0].price, "ask:", this._cachedAsks[0].price);
(<any>this._client).changeState('error');
return;
}
this.MarketData.trigger(new Models.Market(this._cachedBids, this._cachedAsks, t));
}
};
private _log = Utils.log("tribeca:gateway:CoinbaseMD");
constructor(private _orderBook: CoinbaseOrderBook, private _client: CoinbaseOrderEmitter, private _timeProvider: Utils.ITimeProvider) {
this._client.on("statechange", m => this.onStateChange(m));
this._client.on("received", m => this.onReceived(m.data, m.time));
this._client.on("open", m => this.onOpen(m.data, m.time));
this._client.on("done", m => this.onDone(m.data, m.time));
this._client.on("match", m => this.onMatch(m.data, m.time));
this._client.on("change", m => this.onChange(m.data, m.time));
}
}
class CoinbaseOrderEntryGateway implements Interfaces.IOrderEntryGateway {
OrderUpdate = new Utils.Evt<Models.OrderStatusReport>();
supportsCancelAllOpenOrders = () : boolean => { return false; };
cancelAllOpenOrders = () : Q.Promise<number> => {
var d = Q.defer<number>();
this._authClient.cancelAllOrders((err, resp) => {
if (err) d.reject(err);
else {
var t = this._timeProvider.utcNow();
for (let cxl_id of resp) {
this.OrderUpdate.trigger({
exchangeId: cxl_id,
time: t,
orderStatus: Models.OrderStatus.Cancelled,
leavesQuantity: 0
});
}
d.resolve(resp.length);
};
});
return d.promise;
};
generateClientOrderId = (): string => {
return uuid.v1();
}
cancelOrder = (cancel: Models.BrokeredCancel): Models.OrderGatewayActionReport => {
this._authClient.cancelOrder(cancel.exchangeId, (err?: Error, resp?: any, ack?: CoinbaseOrderAck) => {
var status: Models.OrderStatusReport
var t = this._timeProvider.utcNow();
var msg = null;
if (err) {
if (err.message) msg = err.message;
}
else if (ack != null) {
if (ack.message) msg = ack.message;
if (ack.error) msg = ack.error;
}
if (msg !== null) {
status = {
orderId: cancel.clientOrderId,
rejectMessage: msg,
orderStatus: Models.OrderStatus.Rejected,
cancelRejected: true,
time: t,
leavesQuantity: 0
};
if (msg === "You have exceeded your request rate of 5 r/s." || msg === "BadRequest") {
this._timeProvider.setTimeout(() => this.cancelOrder(cancel), moment.duration(500));
}
}
else {
status = {
orderId: cancel.clientOrderId,
orderStatus: Models.OrderStatus.Cancelled,
time: t,
leavesQuantity: 0
};
}
this.OrderUpdate.trigger(status);
});
return new Models.OrderGatewayActionReport(this._timeProvider.utcNow());
};
replaceOrder = (replace: Models.BrokeredReplace): Models.OrderGatewayActionReport => {
this.cancelOrder(new Models.BrokeredCancel(replace.origOrderId, replace.orderId, replace.side, replace.exchangeId));
return this.sendOrder(replace);
};
sendOrder = (order: Models.BrokeredOrder): Models.OrderGatewayActionReport => {
var cb = (err?: Error, resp?: any, ack?: CoinbaseOrderAck) => {
var status: Models.OrderStatusReport
var t = this._timeProvider.utcNow();
if (ack == null || typeof ack.id === "undefined") {
this._log.warn("NO EXCHANGE ID PROVIDED FOR ORDER ID:", order.orderId, err, ack);
}
var msg = null;
if (err) {
if (err.message) msg = err.message;
}
else if (ack != null) {
if (ack.message) msg = ack.message;
if (ack.error) msg = ack.error;
}
else if (ack == null) {
msg = "No ack provided!!"
}
if (msg !== null) {
status = {
orderId: order.orderId,
rejectMessage: msg,
orderStatus: Models.OrderStatus.Rejected,
time: t
};
}
else {
status = {
exchangeId: ack.id,
orderId: order.orderId,
orderStatus: Models.OrderStatus.Working,
time: t
};
}
this.OrderUpdate.trigger(status);
};
var o: CoinbaseOrder = {
client_oid: order.orderId,
size: order.quantity.toString(),
product_id: this._symbolProvider.symbol
};
if (order.type === Models.OrderType.Limit) {
o.price = order.price.toString();
if (order.preferPostOnly)
o.post_only = true;
switch (order.timeInForce) {
case Models.TimeInForce.GTC:
break;
case Models.TimeInForce.FOK:
o.time_in_force = "FOK";
break;
case Models.TimeInForce.IOC:
o.time_in_force = "IOC";
break;
default:
throw new Error("Cannot map " + Models.TimeInForce[order.timeInForce] + " to a coinbase TIF");
}
}
else if (order.type === Models.OrderType.Market) {
o.type = "market";
}
if (order.side === Models.Side.Bid)
this._authClient.buy(o, cb);
else if (order.side === Models.Side.Ask)
this._authClient.sell(o, cb);
return new Models.OrderGatewayActionReport(this._timeProvider.utcNow());
};
public cancelsByClientOrderId = false;
ConnectChanged = new Utils.Evt<Models.ConnectivityStatus>();
private onStateChange = (s: StateChange) => {
var status = convertConnectivityStatus(s);
this.ConnectChanged.trigger(status);
};
private onReceived = (tsMsg: Models.Timestamped<CoinbaseReceived>) => {
var msg = tsMsg.data;
if (typeof msg.client_oid === "undefined" || !this._orderData.allOrders.hasOwnProperty(msg.client_oid))
return;
var status: Models.OrderStatusReport = {
exchangeId: msg.order_id,
orderId: msg.client_oid,
orderStatus: Models.OrderStatus.Working,
time: tsMsg.time,
leavesQuantity: convertSize(msg.size)
};
this.OrderUpdate.trigger(status);
};
private onOpen = (tsMsg: Models.Timestamped<CoinbaseOpen>) => {
var msg = tsMsg.data;
var orderId = this._orderData.exchIdsToClientIds[msg.order_id];
if (typeof orderId === "undefined")
return;
var t = this._timeProvider.utcNow();
var status: Models.OrderStatusReport = {
orderId: orderId,
orderStatus: Models.OrderStatus.Working,
time: tsMsg.time,
leavesQuantity: convertSize(msg.remaining_size)
};
this.OrderUpdate.trigger(status);
};
private onDone = (tsMsg: Models.Timestamped<CoinbaseDone>) => {
var msg = tsMsg.data;
var orderId = this._orderData.exchIdsToClientIds[msg.order_id];
if (typeof orderId === "undefined")
return;
var ordStatus = msg.reason === "filled"
? Models.OrderStatus.Complete
: Models.OrderStatus.Cancelled;
var status: Models.OrderStatusReport = {
orderId: orderId,
orderStatus: ordStatus,
time: tsMsg.time,
leavesQuantity: 0
};
this.OrderUpdate.trigger(status);
};
private onMatch = (tsMsg: Models.Timestamped<CoinbaseMatch>) => {
var msg = tsMsg.data;
var liq: Models.Liquidity = Models.Liquidity.Make;
var client_oid = this._orderData.exchIdsToClientIds[msg.maker_order_id];
if (typeof client_oid === "undefined") {
liq = Models.Liquidity.Take;
client_oid = this._orderData.exchIdsToClientIds[msg.taker_order_id];
}
if (typeof client_oid === "undefined")
return;
var status: Models.OrderStatusReport = {
orderId: client_oid,
orderStatus: Models.OrderStatus.Working,
time: tsMsg.time,
lastQuantity: convertSize(msg.size),
lastPrice: convertPrice(msg.price),
liquidity: liq
};
this.OrderUpdate.trigger(status);
};
private onChange = (tsMsg: Models.Timestamped<CoinbaseChange>) => {
var msg = tsMsg.data;
var orderId = this._orderData.exchIdsToClientIds[msg.order_id];
if (typeof orderId === "undefined")
return;
var status: Models.OrderStatusReport = {
orderId: orderId,
orderStatus: Models.OrderStatus.Working,
time: tsMsg.time,
quantity: convertSize(msg.new_size)
};
this.OrderUpdate.trigger(status);
};
private _log = Utils.log("tribeca:gateway:CoinbaseOE");
constructor(
private _timeProvider: Utils.ITimeProvider,
private _orderData: Interfaces.IOrderStateCache,
private _orderBook: CoinbaseOrderEmitter,
private _authClient: CoinbaseAuthenticatedClient,
private _symbolProvider: CoinbaseSymbolProvider) {
this._orderBook.on("statechange", this.onStateChange);
this._orderBook.on("received", this.onReceived)
this._orderBook.on("open", this.onOpen);
this._orderBook.on("done", this.onDone);
this._orderBook.on("match", this.onMatch);
this._orderBook.on("change", this.onChange);
}
}
class CoinbasePositionGateway implements Interfaces.IPositionGateway {
private _log = Utils.log("tribeca:gateway:CoinbasePG");
PositionUpdate = new Utils.Evt<Models.CurrencyPosition>();
private onTick = () => {
this._authClient.getAccounts((err?: Error, resp?: any, data?: CoinbaseAccountInformation[]) => {
try {
_.forEach(data, d => {
var c = GetCurrencyEnum(d.currency);
var rpt = new Models.CurrencyPosition(convertPrice(d.available), convertPrice(d.hold), c);
this.PositionUpdate.trigger(rpt);
});
} catch (error) {
this._log.error(error, "Exception while downloading Coinbase positions", data)
}
});
};
constructor(
timeProvider: Utils.ITimeProvider,
private _authClient: CoinbaseAuthenticatedClient) {
timeProvider.setInterval(this.onTick, moment.duration(7500));
this.onTick();
}
}
class CoinbaseBaseGateway implements Interfaces.IExchangeDetailsGateway {
public get hasSelfTradePrevention() {
return true;
}
exchange(): Models.Exchange {
return Models.Exchange.Coinbase;
}
makeFee(): number {
return 0;
}
takeFee(): number {
return 0;
}
name(): string {
return "Coinbase";
}
private static AllPairs = [
new Models.CurrencyPair(Models.Currency.BTC, Models.Currency.USD),
new Models.CurrencyPair(Models.Currency.BTC, Models.Currency.EUR),
new Models.CurrencyPair(Models.Currency.BTC, Models.Currency.GBP)
];
public get supportedCurrencyPairs() {
return CoinbaseBaseGateway.AllPairs;
}
}
function GetCurrencyEnum(name: string): Models.Currency {
switch (name.toUpperCase()) {
case "BTC": return Models.Currency.BTC;
case "USD": return Models.Currency.USD;
case "EUR": return Models.Currency.EUR;
case "GBP": return Models.Currency.GBP;
case "ETH": return Models.Currency.ETH;
default: throw new Error("Unsupported currency " + name);
}
}
function GetCurrencySymbol(c: Models.Currency): string {
switch (c) {
case Models.Currency.USD: return "USD";
case Models.Currency.GBP: return "GBP";
case Models.Currency.BTC: return "BTC";
case Models.Currency.EUR: return "EUR";
case Models.Currency.ETH: return "ETH";
default: throw new Error("Unsupported currency " + Models.Currency[c]);
}
}
class CoinbaseSymbolProvider {
public symbol: string;
constructor(pair: Models.CurrencyPair) {
this.symbol = GetCurrencySymbol(pair.base) + "-" + GetCurrencySymbol(pair.quote);
}
}
export class Coinbase extends Interfaces.CombinedGateway {
constructor(config: Config.IConfigProvider, orders: Interfaces.IOrderStateCache, timeProvider: Utils.ITimeProvider, pair: Models.CurrencyPair) {
var symbolProvider = new CoinbaseSymbolProvider(pair);
var orderEventEmitter = new CoinbaseExchange.OrderBook(symbolProvider.symbol, config.GetString("CoinbaseWebsocketUrl"), config.GetString("CoinbaseRestUrl"), timeProvider);
var authClient = new CoinbaseExchange.AuthenticatedClient(config.GetString("CoinbaseApiKey"),
config.GetString("CoinbaseSecret"), config.GetString("CoinbasePassphrase"), config.GetString("CoinbaseRestUrl"));
var orderGateway = config.GetString("CoinbaseOrderDestination") == "Coinbase" ?
<Interfaces.IOrderEntryGateway>new CoinbaseOrderEntryGateway(timeProvider, orders, orderEventEmitter, authClient, symbolProvider)
: new NullGateway.NullOrderGateway();
var positionGateway = new CoinbasePositionGateway(timeProvider, authClient);
var mdGateway = new CoinbaseMarketDataGateway(new CoinbaseOrderBook(), orderEventEmitter, timeProvider);
super(
mdGateway,
orderGateway,
positionGateway,
new CoinbaseBaseGateway());
}
};