-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
76 lines (64 loc) · 2.12 KB
/
index.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
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
// Version 2
const WebSocket = require('ws');
class Okex {
constructor() {
this.websocketUri = 'wss://real.okex.com:10441/websocket';
this.connect();
}
connect() {
this.socket = new WebSocket(this.websocketUri);
}
addSubscriptionDepth(pair_names) {
this.addSubscription(pair_names, 'depth')
}
addSubscriptionTicker(pair_names) {
this.addSubscription(pair_names, 'ticker')
}
addSubscriptionDeals(pair_names) {
this.addSubscription(pair_names, 'deals')
}
addSubscriptionKline(pair_names, kline) {
//1min, 3min, 5min, 15min, 30min, 1hour, 2hour, 4hour, 6hour, 12hour, day, 3day, week
this.addSubscription(pair_names, 'kline_'+kline)
}
addSubscription(pair_names, type) {
if (type.indexOf('depth') != -1 || type == 'ticker' || type == 'deals' || type.indexOf('kline') != -1) {
if (this.socket.readyState != this.socket.OPEN) {
this.connect();
}
this.socket.on('open', () => {
for (var i = 0; i < pair_names.length; i++) {
var pair_name = pair_names[i].replace('/', '_').toLowerCase();
var subscription = {
event: 'addChannel',
channel: 'ok_sub_spot_' + pair_name + '_' + type
}
this.socket.send(JSON.stringify(subscription))
}
});
}
}
terminate() {
if (this.socket.readyState == this.socket.OPEN && this.socket.readyState != this.socket.CONNECTING) {
this.socket.terminate();
}
}
onMessage(callback) {
this.socket.on('message', data => {
if (typeof callback === 'function') {
return callback(JSON.parse(data))
}
;
});
this.reconnect(callback);
}
reconnect(callback) {
this.socket.on('close', () => {
setTimeout(() => {
this.connect();
this.onMessage(callback);
}, 3000);
});
}
}
module.exports = Okex