-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitfinex.js
229 lines (213 loc) · 6.17 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
const crypto = require('crypto');
const request = require('request');
function rest (key, secret, opts= {}) {
this.url = 'https://api.bitfinex.com';
this.version = 'v1';
this.key = key;
this.secret = secret;
this.nonce = Date.now();
this.generateNonce = (typeof opts.nonceGenerator === 'function')
? opts.nonceGenerator
: function () {
// noinspection JSPotentiallyInvalidUsageOfThis
return ++this.nonce;
};
}
rest.prototype.make_request = function(path, params, cb) {
var headers, key, nonce, path, payload, signature, url, value;
if (!this.key || !this.secret) {
return cb(new Error('API key and secret is invalid'));
}
url = `${this.url}/${this.version}/${path}`;
nonce = JSON.stringify(this.generateNonce());
payload = {
request: `/${this.version}/${path}`,
nonce
};
for (key in params) {
value = params[key];
payload[key] = value;
}
payload = new Buffer(JSON.stringify(payload)).toString('base64');
signature = crypto.createHmac('sha384', this.secret).update(payload).digest('hex');
headers = {
'X-BFX-APIKEY' : this.key,
'X-BFX-PAYLOAD' : payload,
'X-BFX-SIGNATURE' : signature,
};
return request({
url,
method: 'POST',
headers,
timeout: 15000
}, (err, response, body) => {
let result;
if (err || (response.statusCode !== 200 && response.statusCode !== 400)) {
return cb(new Error(err != null ? err : response.statusCode))
}
try {
result = JSON.parse(body);
} catch (e) {
return cb(e, { text: body.toString() });
}
if (result.message != null) {
if (/Nonce is too small/.test(result.message)) {
result.message += ' refer to API document';
}
return cb(new Error(result.message));
}
// result.message is empty if request successfully
return cb(null, result);
});
}
rest.prototype.make_public_request = function(path, cb) {
const url = `${this.url}/${this.version}/${path}`;
return request({
url,
method: 'GET',
timeout: 15000
}, (err, response, body) => {
let result;
if (err || (response.statusCode !== 200 && response.statusCode !== 400)) {
return cb(new Error(err != null ? err : response.statusCode));
}
try {
result = JSON.parse(body);
} catch (e) {
return cb(e, { text: body.toString() });
}
if (result.message != null) {
return cb(new Error(result.message));
} else {
return cb(null, result);
}
});
}
// ticker values
rest.prototype.ticker = function(symbol, cb) {
if (arguments.length == 0) {
symbol = 'BTCUSD';
cb = function(error, data) {
console.log(data);
}
}
return this.make_public_request('pubticker/' + symbol, cb);
}
// high and low prices
rest.prototype.today = function (symbol, cb) {
return this.make_public_request('today/' + symbol, cb);
}
// trade volumes by day period
rest.prototype.stats = function (symbol, cb) {
return this.make_public_request('stats/' + symbol, cb);
}
// do implement this self, no needs to export class
//module.exports = rest;
// public API no needs to register token and secret
const pubicApi = null;
const tickers = {};
function tickerCallback(pair, data) {
if (pair == undefined || data == undefined) {
return;
}
// fill data to tickers struct
if (tickers[pair] == undefined) {
tickers[pair] = {};
console.log('Ticker initialized:' + pair);
}
try {
tickers[pair].pair = pair;
tickers[pair].last = data.last_price;
tickers[pair].ask = data.ask;
tickers[pair].bid = data.bid;
tickers[pair].volume = data.volume;
tickers[pair].highest = data.high;
tickers[pair].lowest = data.low;
tickers[pair].updatetime = new Date(data.timestamp * 1000); // seconds number to milliseconds
console.log('Ticker updated:' + pair);
} catch (e) {
console.log(e);
}
}
function httpsGetTickers() {
publicApi.ticker('iotusd', (error, data) => {
if (error == null) {
tickerCallback('iotusd', data);
} else {
console.log(error);
}
});
publicApi.ticker('iotbtc', (error, data) => {
if (error == null) {
tickerCallback('iotbtc', data);
} else {
console.log(error);
}
});
}
function routineUpdateFunction() {
httpsGetTickers();
routineUpdatetime = new Date();
}
function initModule() {
// Public API does not needs key and secret
publicApi = new rest('','');
}
var routineUpdatetime = null;
var routineInterval = null;
function startRoutineInterval() {
console.log('Start trace bitfinex price');
// Update current tickers data
httpsGetTickers();
routineUpdatetime = new Date();
if (routineInterval == undefined || routineInterval == null) {
// Use public API get tickers data for each 5 minutes
routineInterval = setInterval(routineUpdateFunction, 5 * 60 * 1000);
} else {
console.log('Routine interval has been exist, should be stopped before start again');
}
}
function stopRoutineInterval() {
if (routineInterval == undefined || routineInterval == null) {
console.log('Routine interval is not exists, should be started to stop');
} else {
// Clear interval timer
clearInterval(routineInterval);
routineInterval = null;
}
}
module.exports = {
init: initModule,
start: startRoutineInterval,
stop: stopRoutineInterval,
getTicker: (pair) => {
// bitfinex pair format: btcusd
pair = pair.toLowerCase();
var ticker = tickers[pair];
return ticker;
},
getCurrencyInfo: (currency, withTimestamp = true) => {
currency = currency.toLowerCase();
var response;
// for-in loop will looping within key(in this case, key is pair)
for (pair in tickers) {
if (pair.indexOf(currency) !== 0) {
continue;
}
var price = currency.toUpperCase() + '->' + pair.replace(currency, '').toUpperCase() + ': ' + tickers[pair].last;
if (response == undefined) {
if (withTimestamp == true) {
response = tickers[pair].updatetime.toISOString() + '\n' + price;
} else {
response = price;
}
} else {
response += '\n' + price;
}
}
// if tickers does not have given currency, return empty
if (response == undefined)
response = '';
return response;
}
};