-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTHONG NGO
1224 lines (862 loc) · 34.4 KB
/
THONG NGO
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# THONG NGO
[![travis](https://travis-ci.org/blinktrade/BlinkTradeJS.svg?branch=master)](https://travis-ci.org/blinktrade/BlinkTradeJS)
[![npm version](https://badge.fury.io/js/blinktrade.svg)](https://badge.fury.io/js/blinktrade)
[![Known Vulnerabilities](https://snyk.io/test/github/blinktrade/blinktradejs/badge.svg)](https://snyk.io/test/github/blinktrade/blinktradejs)
BlinkTradeJS WebSocket and REST Official JavasScript client for node.js and browser.
# Getting Started
BlinkTrade provides a simple and robust WebSocket API to integrate our platform, we strongly recommend you to use it over the RESTful API.
## Install
`$ yarn add blinktrade`
using npm.
`$ npm install blinktrade`
# Documentation
You can also check our [Full API Documentation](https://blinktrade.com/docs).
# Examples
More examples can be found in the [examples directory.](./examples)
# Usage
All SDK supports either promises and callbacks, if a callback is provided as the last argument, it will be called as `callback(error, result)`,
otherwise it will just return the original promise, we also provide event emitters that you can use to get realtime updates through our WebSocket API,
you can check the [Event Emitters section.](#event-emitters)
**NOTE** We impose cross origin policy (cors), even though our SDK can work on the browser, it won’t work due our origin policy, so and we recommend you use on server side instead.
Only the public rest is available on the browser, and other environments only works on testnet and you won’t be able use to use production environment on the browser, this might change in the future.
## Public REST API
The most simple way to get the ticker, orderbook and trades, is through our public RESTful API, which doesn't require authentication.
### Ticker
```js
const BlinkTradeRest = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({ currency: "BRL" });
blinktrade.ticker().then((ticker) => {
console.log(ticker)
})
```
> Response
```json
{
"high": 1900,
"vol": 4.87859418,
"buy": 1891.89,
"last": 1891.89,
"low": 1891.89,
"pair": "BTCBRL",
"sell": 1910,
"vol_brl": 9250.19572651
}
```
### OrderBook
```js
const BlinkTradeRest = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({ currency: "BRL" });
blinktrade.orderbook().then((orderbook) => {
console.log(orderbook)
})
```
> Response
```json
{
"pair": "BTCBRL",
"bids": [
[ 1891.89, 0.16314699, 90800027 ],
[ 1880, 0.20712, 90800027 ]
],
"asks": [
[ 1910, 3.28046533, 90800027 ],
[ 1919.99, 1.95046354, 90800027 ]
]
}
```
### Last Trades
```js
const BlinkTradeRest = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({ currency: "BRL" });
blinktrade.trades().then((trades) => {
console.log(trades)
})
```
> Response
```json
[{
"tid": 16093,
"date": 1472278473,
"price": 1891.89,
"amount": 0.1,
"side": "sell"
}, {
"tid": 16094,
"date": 1472278477,
"price": 1891.89,
"amount": 0.1,
"side": "sell"
}, {
"tid": 16095,
"date": 1472278668,
"price": 1891.89,
"amount": 0.1,
"side": "sell"
}]
```
## Trade REST / WebSocket
On our RESTful API, we provide a trade endpoint that you're allowed to send and cancel orders,
request deposits and withdrawals. You need to [create an API Key](https://blinktrade.com/docs#create-api-key) through our platform and set their respective permission that gives you access to it.
The Trade endpoint is internaly a bridge to our `WebSocket` API, so you can access it both on `REST` and `WebSocket` API.
Be aware that our RESTful trade endpoint can be changed at any time, we strongly recommend using the `WebSocket` API over the `RESTful` API.
> **NOTE** that when generate the API Key and the API Secret, it will be only shown once, you should save it securely. The API Password is only used in the WebSocket API.
```js
const BlinkTradeRest = require("blinktrade").BlinkTradeRest;
const blinktrade = new BlinkTradeRest({
prod: false,
key: "YOUR_API_KEY_GENERATED_IN_API_MODULE",
secret: "YOUR_SECRET_KEY_GENERATED_IN_API_MODULE",
currency: "BRL",
});
blinktrade.sendOrder({
side: "BUY",
price: parseInt(1800 * 1e8).toFixed(0),
amount: parseInt(0.5 * 1e8).toFixed(0),
symbol: "BTCBRL",
}).then((order) => {
console.log(order)
})
```
> Response
```json
{
"OrderID": 1459028830811,
"ExecID": 740972,
"ExecType": "0",
"OrdStatus": "0",
"CumQty": 0,
"Symbol": "BTCUSD",
"OrderQty": 5000000,
"LastShares": 0,
"LastPx": 0,
"Price": 180000000000,
"TimeInForce": "1",
"LeavesQty": 50000000,
"MsgType": "8",
"ExecSide": "1",
"OrdType": "2",
"CxlQty": 0,
"Side": "1",
"ClOrdID": 3251968,
"AvgPx": 0
}
```
## Usage WebSocket
### Authenticating
Make sure that you're connected to send messages through WebSocket, most of the message also require that you're authenticated.
```js
const BlinkTradeWS = require("blinktrade").BlinkTradeWS;
const blinktrade = new BlinkTradeWS({ prod: true });
blinktrade.connect().then(() => {
// Connected
return blinktrade.login({ username: "<API_KEY>", password: "<API_SECRET>" });
}).then((logged) => {});
```
### Requesting Balance
Will request your balance for each broker.
```js
blinktrade.balance().then((balance) => {
console.log(balance);
});
```
You can pass a callback to receive balance updates.
```js
blinktrade.balance(null, (err, balance) => {
console.log(balance);
});
```
#### EXAMPLE RESPONSE
```json
{
"5": {
"BTC_locked": 0,
"USD": 177911657052760,
"BTC": 1468038442214,
"USD_locked": 96750050000
},
"MsgType": "U3",
"ClientID": 90800003,
"BalanceReqID": 5019624
}
```
### Subscribe to OrderBook
```js
blinktrade.subscribeMarketData(["BTCBRL"]).then((orderbook) => {
console.log(orderbook)
})
```
#### EXAMPLE RESPONSE
```json
{
"MDReqID": 9894272,
"Symbol": "BTCUSD",
"MsgType": "W",
"MarketDepth": 0,
"MDFullGrp": {
"BTCUSD": {
"bids": [{
"MDEntryPositionNo": 1,
"MDEntrySize": 50000000,
"MDEntryPx": 1150600000000,
"MDEntryID": 1459030492064,
"MDEntryTime": "05:50:13",
"MDEntryDate": "2018-02-03",
"UserID": 90800000,
"OrderID": 1459000000000,
"MDEntryType": "0",
}],
"asks": [{
"MDEntryPositionNo": 1,
"MDEntrySize": 50000000,
"MDEntryPx": 1150700000000,
"MDEntryID": 1459030492064,
"MDEntryTime": "05:50:13",
"MDEntryDate": "2018-02-03",
"UserID": 90800000,
"OrderID": 1459000000000,
"MDEntryType": "1",
}]
}
}
}
```
To unsubscribe from orderbook, you should pass the `MDReqID` on `unSubscribeOrderbook()`.
```js
blinktrade.subscribeMarketData(["BTCBRL"]).then((orderbook) => {
blinktrade.unSubscribeOrderbook(orderbook.MDReqID);
});
```
> Note that there's no return when unsubscribe from orderbook.
### Syncronize orderbook
The `syncOrderbook` function automatically handles the event system to keep the order book syncronized
for you, you can access the order book at anywhere in your application with `blinktrade.orderbook`
```js
blinktrade.syncOrderbook(["BTCBRL"]).then(() => {
console.log(blinktrade.orderbook);
})
```
The `blinktrade.orderbook` is a object like this
```json
{
"BTCUSD": {
"bids": [{
"MDEntryPositionNo": 1,
"MDEntrySize": 50000000,
"MDEntryPx": 1150600000000,
"MDEntryID": 1459030492064,
"MDEntryTime": "05:50:13",
"MDEntryDate": "2018-02-03",
"UserID": 90800000,
"OrderID": 1459000000000,
"MDEntryType": "0",
}],
"asks": [{
"MDEntryPositionNo": 1,
"MDEntrySize": 50000000,
"MDEntryPx": 1150700000000,
"MDEntryID": 1459030492064,
"MDEntryTime": "05:50:13",
"MDEntryDate": "2018-02-03",
"UserID": 90800000,
"OrderID": 1459000000000,
"MDEntryType": "1",
}]
}
}
```
### Subscribe to ticker
You can subscribe on one or more market symbols.
```js
blinktrade.subscribeTicker(["BLINK:BTCBRL"]).then((ticker) => {
console.log(ticker);
});
```
To unsubscribe from ticker, you do the same as `unSubscribeOrderbook`, but passing `SecurityStatusReqID` to `unSubscribeTicker()`.
```js
blinktrade.subscribeTicker(["BLINK:BTCBRL"]).then((ticker) => {
blinktrade.unSubscribeTicker(ticker.SecurityStatusReqID);
});
```
### Send and cancelling orders
##### [Floats are Evil!](http://floating-point-gui.de/basic/)
Converting Floats to Integers can be dangerous. Different programming languages can get weird rounding errors and imprecisions,
so all API returns prices and bitcoin values as Integers and in "satoshis" format. We also expect Integers as input,
make sure that you're formatting the values properly to avoid precision issues.
e.g.:
```
// Wrong
0.57 * 1e8 => 56999999.99999999
// Correct
parseInt((0.57 * 1e8).toFixed(0)) => 57000000
```
```js
blinktrade.sendOrder({
side: "BUY",
price: parseInt((550 * 1e8).toFixed(0)),
amount: parseInt((0.05 * 1e8).toFixed(0)),
symbol: "BTCUSD",
}).then((order) => {
// Sent
});
```
### Advanced Orders (MARKET, LIMIT, STOP)
### Market
Market orders automatically execute your order at the current price.
```js
blinktrade.sendOrder({
side: 'BUY',
type: 'MARKET',
symbol: 'BTCBRL',
amount: parseInt(0.01 * 1e8),
})
```
**NOTE** Market orders will execute indenpendently of the price of the other side, so be careful on low liquidity scenarios.
### Limit
Limit order allows you specified your own price.
```js
blinktrade.sendOrder({
side: 'SELL',
type: 'LIMIT',
symbol: 'BTCBRL',
price: parseInt(16000 * 1e8),
amount: parseInt(0.01 * 1e8),
})
```
#### Post Only
Post Only ensures that your order will be added to the order book and not match with a existing order.
```js
blinktrade.sendOrder({
side: 'BUY',
type: 'LIMIT',
symbol: 'BTCBRL',
price: parseInt(16000 * 1e8),
amount: parseInt(0.01 * 1e8),
postOnly: true,
})
```
### Stop
Stop order allow you place an order only when the price reaches the stop price,
your order won't be visible on the book until it triggered.
```js
blinktrade.sendOrder({
side: 'SELL',
type: 'STOP',
symbol: 'BTCBRL',
stopPrice: parseInt(16000 * 1e8), // Price bellow the best bid
amount: parseInt(0.01 * 1e8),
})
```
**NOTE** STOP order will act as a MARKET order, if you want yo specify a limit price use STOP_LIMIT instead.
### Stop Limit
Stop Limit order allow you specified a limit price toghether with the stop price.
```js
blinktrade.sendOrder({
side: 'SELL',
type: 'STOP_LIMIT',
symbol: 'BTCBRL',
price: parseInt(15900 * 1e8), // Limit price
stopPrice: parseInt(16000 * 1e8), // Price bellow the best bid
amount: parseInt(0.01 * 1e8),
})
```
> Response
The response is the same as the [Execution Report](#executionreport-websocket), if you're using it with rest transport, it will response as an array together with the balance response.
```json
{
"OrderID": 1459028830811,
"ExecID": 740972,
"ExecType": "0",
"OrdStatus": "0",
"CumQty": 0,
"Symbol": "BTCUSD",
"OrderQty": 5000000,
"LastShares": 0,
"LastPx": 0,
"Price": 55000000000,
"TimeInForce": "1",
"LeavesQty": 5000000,
"MsgType": "8",
"ExecSide": "1",
"OrdType": "2",
"CxlQty": 0,
"Side": "1",
"ClOrdID": 3251968,
"AvgPx": 0
}
```
To cancel a order, you need to pass the `orderId`, you'll also need to pass the `clientId` in order to get a response,
if you didn't provide `orderId`, all open orders will be cancelled.
```js
blinktrade.cancelOrder({ orderId: order.OrderID, clientId: order.ClOrdID }).then((order) => {
console.log("Order Cancelled");
})
```
> The response will be the same as the sendOrder with `ExecType: "4"`
### Last Trades
List the latest trades executed on an exchange since a chosen date.
```js
blinktrade.trades({ limit: 100, since: 2270000 }).then((data) => {
console.log("Trades", data);
})
```
### Requesting Deposits
You can generate either bitcoin or FIAT deposits, if any arguments was passed, it will generate a bitcoin deposit along with the address.
#### Generate bitcoin address to deposit
```js
blinktrade.requestDeposit().then((deposit) => {
console.log(deposit)
})
```
#### Fiat deposit
To generate a FIAT deposit, you need to pass the `depositMethodId` which correspond the method of deposit of your broker, you can get these informations calling [`requestDepositMethods()`](requestDepositMethods)
```js
blinktrade.requestDeposit({
value: parseInt(200 * 1e8),
currency: "BRL",
depositMethodId: 502,
}).then((deposit) => {
console.log(deposit)
})
```
> Response
Both responses for bitcoin and fiat deposits are quite similar.
```json
{
"DepositMethodName": "deposit_btc",
"UserID": 90800003,
"ControlNumber": null,
"State": "UNCONFIRMED",
"Type": "CRY",
"PercentFee": 0,
"Username": "user",
"CreditProvided": 0,
"DepositReqID": 7302188,
"DepositID": "2a6b5e322fd24574a4d9f988681a542f",
"Reason": null,
"AccountID": 90800003,
"Data": {
"InputAddress": "mjjVMr8WcYQwVGzYc8HpaRyAZc89ngTdKV",
"Destination": "n19ZAH1WGoUkQhubQw71fH11BenifxpBxf"
},
"ClOrdID": "7302188",
"Status": "0",
"Created": "2016-09-03 23:08:26",
"DepositMethodID": null,
"Value": 0,
"BrokerID": 5,
"PaidValue": 0,
"Currency": "BTC",
"ReasonID": null,
"MsgType": "U23",
"FixedFee": 0
}
```
**NOTE** The `Data.InputAddress` is the address that you have to deposit. **DO NOT DEPOSIT** on `Data.Destination` address.
### Requesting Withdraws
To request withdraws, you need to pass a "data" information, which represents the information to your withdraw,
it's related to bank accounts, numbers, or a bitcoin address. This information is dynamically and different for every broker.
```js
blinktrade.requestWithdraw({
amount: parseInt(400 * 1e8),
currency: "BRL",
method: "bradesco",
data: {
AccountBranch: "111",
AccountNumber: "4444-5",
AccountType: "corrente",
CPF_CNPJ: "00000000000"
}
})
```
### Confirm Withdraws (two-factor)
After requesting a withdraw, you might get an error asking for two factor authentication,
you should call `confirmWithdraw` passing the `confirmationToken` that was sent to your email,
or `secondFactor` if needed.
```js
blinktrade.confirmWithdraw({
withdrawId: 523,
confirmationToken: 'TOKEN'
})
```
> Response
```json
{
"Username": "user",
"Status": "1",
"SecondFactorType": "",
"Created": "2016-09-03 23:42:06",
"PaidAmount": 50000000,
"UserID": 90800003,
"Reason": null,
"Currency": "BRL",
"Amount": 50000000,
"ReasonID": null,
"BrokerID": 5,
"ClOrdID": "3332623",
"WithdrawID": 523,
"WithdrawReqID": 3332623,
"MsgType": "U7",
"Data": {
"Instant": "NO",
"AccountBranch": "111",
"AccountNumber": "4444-5",
"AccountType": "corrente",
"CPF_CNPJ": "00000000000"
},
"Method": "bradesco",
"FixedFee": 0,
"PercentFee": 0
}
```
## Event Emitters
Using event emitters is easy and expressive way to keep you updated through our `WebSocket` API,
you can listen to individual events to match your needs, you can listen to new orders, execution reports, tickers and balance changes.
Event emitters can also be used as promises to keep it chained, event emitters are implemented with [`EventEmitter2`](https://github.com/asyncly/EventEmitter2),
which gives you more flexibility to match events with multi-level wildcards and extends events such as `.onAny`, `.once`, `.many` and so on.
### Connection Events
You can listem to `OPEN`, `CLOSE`, and `ERROR` events to get WebSocket events and error handling.
```js
blinktrade.connect()
.on('OPEN', (e) => {})
.on('CLOSE', (e, lastMessageSent) => {})
.on('ERROR', (error, lastMessageSent) => {})
.then(() => {
console.log('Connected')
})
```
The `OPEN` event is useful to handle reconnections, since the promise is already resolved.
The `ERROR` event is where you can do all the error handling, both from WebSocket errors or an
error raised by the backend due some invalid message, both `CLOSE` and `ERROR` will give you
the last message that you sent as the second argument.
You can also listen them by just `blinktrade.on('OPEN', (e) => {})` that works just fine.
### Event Ticker
To keep ticker update on new events, you can return a event emitter and match with the market.
```js
blinktrade.subscribeTicker(["UOL:USDBRT", "BLINK:BTCUSD", "BLINK:BTCBRL"])
.on("UOL:USDBRT", (usdbrt) => {})
.on("BLINK:BTCUSD", (btcusd) => {})
.on("BLINK:BTCBRL", (btcbrl) => {})
```
You can easily match all symbols at the same listener.
```js
blinktrade.subscribeTicker(["UOL:USDBRT", "BLINK:BTCUSD", "BLINK:BTCBRL"])
.on("BLINK:*", (ticker) => {})
```
### Event Market Data
To get realtime updates on order book, you should listen to the following events.
```js
blinktrade.subscribeMarketData(["BTCUSD"])
.on("OB:NEW_ORDER", (order) => {})
.on("OB:UPDATE_ORDER", (order) => {})
.on("OB:DELETE_ORDER", (order) => {})
.on("OB:DELETE_ORDERS_THRU", (order) => {})
.on("OB:TRADE_NEW", (order) => {})
```
You can still return a promise when listen events.
```js
blinktrade.subscribeMarketData(["BTCBRL"])
.on("OB:NEW_ORDER", (order) => {
console.log("New order received")
}).then((orderbook) => {
console.log("Full orderbook", orderbook)
})
```
### Event Balance
You listen to the `BALANCE` event to receive balance updates.
```js
blinktrade.balance().on("BALANCE", (balance) => console.log(balance))
```
### Execution Reports
In order the get when a order is executed, you can listen to the execution report.
```js
blinktrade.executionReport()
.on("EXECUTION_REPORT:NEW", (data) => {})
.on("EXECUTION_REPORT:PARTIAL", (data) => {})
.on("EXECUTION_REPORT:EXECUTION", (data) => {})
.on("EXECUTION_REPORT:CANCELED", (data) => {})
.on("EXECUTION_REPORT:REJECTED", (data) => {})
```
### Withdraw and Deposit Refresh
To get deposit and withdraw updates, you can listen to `DEPOSIT_REFRESH` and `WITHDRAW_REFRESH` respectively.
```js
blinktrade.requestDeposit().on('DEPOSIT_REFRESH', (deposit) => {
console.log(deposit)
})
blinktrade.requestWithdraw().on('WITHDRAW_REFRESH', (withdraw) => {
console.log(withdraw)
})
```
**NOTE** that these events will only be called to the current deposit / withdraw created.
If you want to listen to any deposit / withdraw updates, you should use `onDepositRefresh(callback)` and `onWithdrawRefresh()` instead.
```js
blinktrade.onDepositRefresh((deposit) => {
console.log(deposit)
})
blinktrade.onWithdrawRefresh((withdraw) => {
console.log(withdraw)
})
```
## Handling WebSocket Reconnections
A simple connection pool
```js
const blinktrade = new BlinkTradeWS({
prod: false,
brokerId: 11,
reconnect: true,
reconnectInterval: 3000,
})
blinktrade.connect().on('OPEN', () => {
console.log('connected');
blinktrade.login({
username: '<API_KEY>'
password: '<API_PASSWORD>'
}).then(() => {
// Manually disconnect WebSocket connection
blinktrade.disconnect()
})
})
```
# API
## Public REST API
* [Ticker](#ticker-rest)
* [Trades](#trades-rest)
* [Orderbook](#orderbook-rest)
## WebSocket
* [connect](#connect-websocket)
* [heartbeat](#heartbeat-websocket)
* [login](#login-websocket)
* [logout](#logout-websocket)
* [profile](#profile-websocket)
* [subscribeTicker](#ticker-websocket)
* [unSubscribeTicker](#ticker-websocket)
* [subscribeMarketData](#orderbook-websocket)
* [unSubscribeOrderbook](#orderbook-websocket)
* [executionReport](#executionreport-websocket)
* [tradeHistory](#tradehistory-websocket)
## Trade Rest / Websocket
* [balance](#balance-websocket-rest)
* [sendOrder](#sendorder-websocket-rest)
* [cancelOrder](#cancelorder-websocket-rest)
* [myOrders](#myorders-websocket-rest)
* [requestLedger](#requestledger-websocket-rest)
* [requestWithdrawList](#requestwithdrawlist-websocket-rest)
* [requestWithdraw](#requestwithdraw-websocket-rest)
* [confirmWithdraw](#confirmwithdraw-websocket-rest)
* [cancelWithdraw](#cancelwithdraw-websocket-rest)
* [onWithdrawRefresh](#onwithdrawrefresh-websocket)
* [requestDepositList](#requestdepositList-websocket-rest)
* [requestDeposit](#requestdeposit-websocket-rest)
* [requestDepositMethods](#requestdeposit-websocket-rest)
* [onDepositRefresh](#ondepositrefresh-websocket)
## Public REST
### Constructor [rest]
`new BlinkTradeRest(params: Object)`
#### Arguments
| Name | Type | Description |
|----------|---------|----------------------------------------------------------------------------|
| prod | Boolean | Production environment, default to false |
| brokerId | Number | [see brokers list](https://blinktrade.com/docs/#brokers) |
| key | String | API Key generated on our platform, it only needed on the Trade endpoint |
| secret | String | API Secret generated on our platform, it only needed on the Trade endpoint |
| currency | String | Currency symbol to fetch public endpoint |
### ticker [rest]
`ticker(callback?: Function)` => Promise / callback
### trades [rest]
`trades(params: Object, callback?: Function)` => Promise / callback
#### Arguments
| Name | Type | Description |
|-------|--------|----------------------------------------------------------------------------|
| limit | Number | Limit of trades that will be returned. <NUMBER> should be a positive integer. Optional; defaults to 100 trades |
| since | Number | tid (TradeID) which must be fetched from. Optional; defaults to the date of the first executed trade |
### orderbook [rest]
`orderbook(callback?: Function)` => Promise / callback
## WebSocket
### constructor [websocket]
`new BlinkTradeWS(params?: Object)`
#### Arguments
| Name | Type | Description |
|-------------------|---------|------------------------------------------|
| prod | Boolean | Production environment, default to false |
| brokerId | Number | [see brokers list](https://blinktrade.com/docs/#brokers) |
| url | String | Custom url in case if you're using a custom backend url |
| headers | String | Custom headers to pass to WebSocket constructor if it supported, (useful on react-native) |
| fingerPrint | String | Custom fingerprint if you are not using in either a browser or node (useful on react-native) |
| reconnect | Boolean | Automatically reconnects WebSocket after disconnected, to receive the reconnection event you should listen to the `OPEN` since the promise is already resolved |
| reconnectInterval | Number | Reconnection Interval in miliseconds |
### connect [websocket]
Connect to our WebSocket.
`connect(callback?: Function)` => Promise / callback
### Connection Events
| Event | Description |
|-------|-------------|
| OPEN | Callback when WebSocket connects, by using this approach instead of a promise, you can benefit of reconnection events |
| CLOSE | Callback when WebSocket closes |
| ERROR | Callback when an error occured on both WebSocket or an error raised by the backend |
### heartbeat [websocket]
Used as test request to check the latency connection.
`heartbeat(callback?: Function)` => Promise / callback
### login [websocket]
`login(params: Object, callback?: Function)` => Promise / callback
#### Arguments
| Name | Type | Description |
|--------------------|---------|------------------|
| username | String | Account username or API_Key |
| password | String | Account password or API_Password |
| secondFactor | String | Optional. If the authentication require second factor, you'll receive an error with `NeedSecondFactor = true`, **NOTE**: Is recommended that you use an API Key / API Password instead, which don't required second factor |
| brokerId | Number | Optional. Overwrites the broker id provided by the constructor |
| cancelOnDisconnect | Boolean | Optional. If it's true, all orders sent by the session will be cancelled when the WebSocket disconnects |
### logout [websocket]
`logout(callback?: Function)` => Promise / callback
### profile [websocket]
Available only on `WebSocket`.
`profile(callback?: Function)` => Promise / callback
### subscribeTicker [websocket]
`subscribeTicker(Array<string> symbols, Function? callback)` => Promise / callback