· 7 years ago · Dec 29, 2018, 09:14 AM
1const config = require('config');
2const WebSocket = require('ws');
3const log = require('../../../libs/log');
4
5const { secretKey, publicKey } = config.get('hitbtcConfig');
6
7class BequantWS {
8 constructor() {
9 this.connected = false; // Connecting state to avoid dublicates
10 this.subscribed = false;
11 this.lastMessage = '';
12 this.users = []; // Users for broadcasting
13
14 this.connect();
15 }
16
17 // Simple class instance methods using short-hand method
18 // declaration
19 connect() {
20 const bequantWs = new WebSocket('wss://api.bequant.io/api/2/ws');
21 const data = {
22 method: 'login',
23 params: {
24 algo: 'BASIC',
25 pKey: publicKey,
26 sKey: secretKey,
27 },
28 };
29 bequantWs.onopen = () => {
30 bequantWs.send(JSON.stringify(data));
31 this.ws = bequantWs;
32 this.reciever(); // Activating recieving function
33 log.info('Authenticating in Bequant API');
34 };
35 }
36
37 subscribe() {
38 if (this.subscribed) return null;
39 const data = {
40 method: 'subscribeReports',
41 params: {},
42 };
43 log.info('Subscribing to reports');
44 this.ws.send(JSON.stringify(data));
45 return null;
46 }
47
48 unsubscribe() {
49 this.ws.close();
50 }
51
52 update(users) {
53 this.users = users;
54 users.forEach((user) => {
55 user.send(this.lastMessage);
56 });
57 }
58
59 reciever() {
60 this.ws.onmessage = (msg) => {
61 try {
62 const response = JSON.parse(msg.data);
63 if (response.result) {
64 if (this.connected) { // Result for subscription request
65 this.subscribed = true;
66 log.info('Success subscription');
67 } else {
68 log.info('Success authentication');
69 this.subscribe();
70 this.connected = true;
71 }
72 return null;
73 }
74
75 if (response.error) {
76 log.error(response.error);
77 return null;
78 }
79 this.lastMessage = JSON.stringify(response);
80 } catch (e) {
81 log.error(e);
82 }
83 };
84 }
85}
86
87module.exports = BequantWS;