This repository has been archived by the owner on May 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathokcoin-api.js
90 lines (69 loc) · 2.32 KB
/
okcoin-api.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// wss://real.okex.com:10440/websocket/okcoinapi – works
// wss://real.okex.com:10441/websocket – works
// wss://real.okex.com:10442/ws/v3 – not supported yet
function OKCoin(apiUrl) {
this.wsUrl = apiUrl
this.channelHandlers = {}
// not supported
this.apiKey = null
this.secretKey = null
}
OKCoin.prototype.addChannelHandler = function (channel, handler) {
this.channelHandlers[channel] = handler
return this
}
OKCoin.prototype.setPrivateKeys = function (apiKey, secretKey) {
this.apiKey = apiKey
this.secretKey = secretKey
return this
}
OKCoin.prototype.start = function () {
var _this = this
_this.init = function () {
_this.ws = new WebSocket(_this.wsUrl)
_this.ws.binaryType = 'arraybuffer'
/* WebSocket opened */
_this.ws.onopen = function (event) {
console.log('Connection opened')
var channels = []
for (channelName in _this.channelHandlers) {
channels.push({ 'event': 'addChannel', 'channel': channelName })
}
_this.ws.send(JSON.stringify(channels))
}
/* Message received */
_this.ws.onmessage = function (event) {
try {
var data = pako.inflateRaw(event.data, { to: 'string' })
JSON.parse(data).forEach(message => {
if (message.channel == 'addChannel') {
console.log(message)
}
else {
// execute channel handler
_this.channelHandlers[message.channel](message)
}
})
}
catch (error) {
console.log(error)
}
}
/* Error received */
_this.ws.onerror = function (event) {
console.log('Error received:')
console.log(event)
var status = _this.ws.readyState
if (status != 1) {
console.log('Connection status was: ' + status + ', restarting connection.')
_this.init()
}
}
/* WebSocket closed */
_this.ws.onclose = function (event) {
console.log('Connection closed, restarting connection.')
_this.init()
}
}
_this.init()
}