forked from ignaciop000/binance-traderBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinance_ws.js
50 lines (36 loc) · 1.06 KB
/
binance_ws.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
"use strict"
const WebSocket = require('ws');
const baseURL = "wss://stream.binance.com:9443/ws/"; // base url used for websocket
class BinanceWS {
constructor() {
this.sockets = {} // Object to keep socket reference to prevent multiple declaration
}
initSocket (path, callback){
if (!path || typeof path !== "string") {
throw "path is required and should be a string"
}
if (!callback || typeof callback !== "function") {
throw "callback is required and should be a function"
}
if (this.sockets[path]) {// if an reference exist
return this.sockets[path] // return it
} else {
const ws = new WebSocket([ baseURL, path ].join("")) // create websocket instance
ws.on('message', callback) // bind callback with received data
this.sockets[path] = ws // save the reference
return ws
}
}
getSockets() {
return this.sockets;
}
close() {
for (let s in this.sockets){
try{
this.sockets[s].close();
} catch(e){
}
}
}
}
module.exports = BinanceWS