-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitfinex.js
332 lines (318 loc) · 10.8 KB
/
bitfinex.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
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
module.exports = function (RED) {
'use strict'
var util = require('util')
var vm = require('vm')
var BFX = require('bitfinex-api-node')
function BitfinexConfigNode (config) {
RED.nodes.createNode(this, config)
var node = this
node.status({})
node.bitfinex = require('bitfinex-api-node')
if (!node.credentials ||
!node.credentials.apiKey ||
!node.credentials.apiSecret) {
console.error('Missing bitfinex API credentials')
node.error(RED._('bitfinex.errors.missing-conf'))
}
}
RED.nodes.registerType('bitfinex-credentials', BitfinexConfigNode, {
credentials: {
apiKey: { type: 'password' },
apiSecret: { type: 'password' }
}
})
// function node from https://github.com/node-red/node-red/blob/master/packages/node_modules/%40node-red/nodes/core/function/10-function.js
function sendResults (node, _msgid, msgs) {
if (msgs == null) {
return
} else if (!Array.isArray(msgs)) {
msgs = [msgs]
}
var msgCount = 0
for (var m = 0; m < msgs.length; m++) {
if (msgs[m]) {
if (!Array.isArray(msgs[m])) {
msgs[m] = [msgs[m]]
}
for (var n = 0; n < msgs[m].length; n++) {
var msg = msgs[m][n]
if (msg !== null && msg !== undefined) {
if (typeof msg === 'object' && !Buffer.isBuffer(msg) && !Array.isArray(msg)) {
msg._msgid = _msgid
msgCount++
} else {
var type = typeof msg
if (type === 'object') {
type = Buffer.isBuffer(msg) ? 'Buffer' : (Array.isArray(msg) ? 'Array' : 'Date')
}
node.error(RED._('function.error.non-message-returned', { type: type }))
}
}
}
}
}
if (msgCount > 0) {
node.send(msgs)
}
};
function BfxFuncNode (config) {
RED.nodes.createNode(this, config)
var node = this
this.name = config.name
this.func = config.func
var handleNodeDoneCall = true
// Check to see if the Function appears to call `node.done()`. If so,
// we will assume it is well written and does actually call node.done().
// Otherwise, we will call node.done() after the function returns regardless.
if (/node\.done\s*\(\s*\)/.test(this.func)) {
handleNodeDoneCall = false
}
this.bfxConfig = RED.nodes.getNode(config.config)
const { apiKey, apiSecret } = this.bfxConfig
const bfx = this.bfxConfig
? new BFX({ apiKey, apiSecret })
: new BFX()
var functionText = 'var results = null;' +
'results = (function(msg){ ' +
'var __msgid__ = msg._msgid;' +
'var node = {' +
'id:__node__.id,' +
'name:__node__.name,' +
'log:__node__.log,' +
'error:__node__.error,' +
'warn:__node__.warn,' +
'debug:__node__.debug,' +
'trace:__node__.trace,' +
'on:__node__.on,' +
'status:__node__.status,' +
'send:function(msgs){ __node__.send(__msgid__,msgs);}' +
'};\n' +
this.func + '\n' +
'})(msg);'
this.topic = config.topic
this.outstandingTimers = []
this.outstandingIntervals = []
var sandbox = {
callback: function (results) {
sendResults(node, node.name, results)
},
console,
util,
Buffer,
Date,
RED: {
util: RED.util
},
bfx,
rest: bfx.rest(2, { transform: true }),
ws: bfx.ws(2, { transform: true }),
__node__: {
id: node.id,
name: node.name,
log: function () {
node.log.apply(node, arguments)
},
error: function () {
node.error.apply(node, arguments)
},
warn: function () {
node.warn.apply(node, arguments)
},
debug: function () {
node.debug.apply(node, arguments)
},
trace: function () {
node.trace.apply(node, arguments)
},
send: function (id, msgs) {
sendResults(node, id, msgs)
},
on: function () {
if (arguments[0] === 'input') {
throw new Error(RED._('function.error.inputListener'))
}
node.on.apply(node, arguments)
},
status: function () {
node.status.apply(node, arguments)
}
},
context: {
set: function () {
node.context().set.apply(node, arguments)
},
get: function () {
return node.context().get.apply(node, arguments)
},
keys: function () {
return node.context().keys.apply(node, arguments)
},
get global () {
return node.context().global
},
get flow () {
return node.context().flow
}
},
flow: {
set: function () {
node.context().flow.set.apply(node, arguments)
},
get: function () {
return node.context().flow.get.apply(node, arguments)
},
keys: function () {
return node.context().flow.keys.apply(node, arguments)
}
},
global: {
set: function () {
node.context().global.set.apply(node, arguments)
},
get: function () {
return node.context().global.get.apply(node, arguments)
},
keys: function () {
return node.context().global.keys.apply(node, arguments)
}
},
env: {
get: function (envVar) {
var flow = node._flow
return flow.getSetting(envVar)
}
},
setTimeout: function () {
var func = arguments[0]
var timerId
arguments[0] = function () {
sandbox.clearTimeout(timerId)
try {
func.apply(this, arguments)
} catch (err) {
node.error(err, {})
}
}
timerId = setTimeout.apply(this, arguments)
node.outstandingTimers.push(timerId)
return timerId
},
clearTimeout: function (id) {
clearTimeout(id)
var index = node.outstandingTimers.indexOf(id)
if (index > -1) {
node.outstandingTimers.splice(index, 1)
}
},
setInterval: function () {
var func = arguments[0]
var timerId
arguments[0] = function () {
try {
func.apply(this, arguments)
} catch (err) {
node.error(err, {})
}
}
timerId = setInterval.apply(this, arguments)
node.outstandingIntervals.push(timerId)
return timerId
},
clearInterval: function (id) {
clearInterval(id)
var index = node.outstandingIntervals.indexOf(id)
if (index > -1) {
node.outstandingIntervals.splice(index, 1)
}
}
}
/* eslint-disable-next-line no-prototype-builtins */
if (util.hasOwnProperty('promisify')) {
sandbox.setTimeout[util.promisify.custom] = function (after, value) {
return new Promise(function (resolve, reject) {
sandbox.setTimeout(function () { resolve(value) }, after)
})
}
}
var context = vm.createContext(sandbox)
try {
this.script = vm.createScript(functionText, {
filename: 'Function node:' + this.id + (this.name ? ' [' + this.name + ']' : ''), // filename for stack traces
displayErrors: true
// Using the following options causes node 4/6 to not include the line number
// in the stack output. So don't use them.
// lineOffset: -11, // line number offset to be used for stack traces
// columnOffset: 0, // column number offset to be used for stack traces
})
this.on('input', function (msg, send, done) {
try {
var start = process.hrtime()
context.msg = msg
node.script.runInContext(context)
sendResults(node, msg._msgid, context.results)
if (handleNodeDoneCall) {
done()
}
var duration = process.hrtime(start)
var converted = Math.floor((duration[0] * 1e9 + duration[1]) / 10000) / 100
node.metric('duration', msg, converted)
if (process.env.NODE_RED_FUNCTION_TIME) {
node.status({
fill: 'yellow',
shape: 'dot',
text: '' + converted
})
}
} catch (err) {
/* eslint-disable-next-line no-prototype-builtins */
if ((typeof err === 'object') && err.hasOwnProperty('stack')) {
// remove unwanted part
var index = err.stack.search(/\n\s*at ContextifyScript.Script.runInContext/)
err.stack = err.stack.slice(0, index).split('\n').slice(0, -1).join('\n')
var stack = err.stack.split(/\r?\n/)
// store the error in msg to be used in flows
msg.error = err
var line = 0
var errorMessage
if (stack && stack.length > 0) {
while (line < stack.length && stack[line].indexOf('ReferenceError') !== 0) {
line++
}
if (line < stack.length) {
errorMessage = stack[line]
var m = /:(\d+):(\d+)$/.exec(stack[line + 1])
if (m) {
var lineno = Number(m[1]) - 1
var cha = m[2]
errorMessage += ' (line ' + lineno + ', col ' + cha + ')'
}
}
}
if (!errorMessage) {
errorMessage = err.toString()
}
node.error(errorMessage, msg)
} else if (typeof err === 'string') {
done(err)
} else {
done(JSON.stringify(err))
}
}
})
this.on('close', function () {
while (node.outstandingTimers.length > 0) {
clearTimeout(node.outstandingTimers.pop())
}
while (node.outstandingIntervals.length > 0) {
clearInterval(node.outstandingIntervals.pop())
}
this.status({})
})
} catch (err) {
// eg SyntaxError - which v8 doesn't include line number information
// so we can't do better than this
this.error(err)
}
}
RED.nodes.registerType('Bitfinex function', BfxFuncNode)
}