-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
executable file
·360 lines (300 loc) · 13.3 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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
const colors = require('colors');
const pad = require('pad');
const needle = require('needle');
const moment = require('moment');
const _ = require('lodash');
const os = require('os');
const fs = require('fs');
const yargs = require('yargs');
const pjson = require('./package.json');
let options = require('./options.json');
const args = yargs.argv;
// Configure Needle
needle.defaults({
open_timeout: 3000,
user_agent: `${pjson.name}/${pjson.version}`,
});
// Check for local configuration
if (fs.existsSync(`${os.homedir()}/.${pjson.name}`)) {
options = JSON.parse(fs.readFileSync(`${os.homedir()}/.${pjson.name}`, 'utf8'));
}
// Handle arguments
if (args) {
const apiKey = args.apikey || args['api-key'] || args.apiKey;
// Disable history
if (args.nohistory || args['no-history']) {
options.history.enabled = false;
}
// Set interval
if (parseInt(args.interval, 10)) {
options.pollInterval = parseInt(args.interval, 10);
}
// Set list of markets
if (args.markets && args.markets.length) {
options.markets = args.markets.replace(/\s/g, '').split(',');
}
// Set Cryptowat.ch API key
if (apiKey) {
options.apiKey = apiKey;
}
}
// Legacy support for `app` object within options (moved to root level in 1.6.0)
options = {
...options,
...options.app,
};
delete options.app;
// Utility functions
const utility = {
// Add commas to number
addCommas: string => string.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'),
// Return a rounded number of desired precision
fixed: (number, precision) => Math.round(number * `1e${precision}`) / `1e${precision}`,
};
// Write display to STDOUT
let previousPriceData = {};
const priceDataHistory = {};
const exchangeLookup = {};
let previousPrimaryCurrency = null;
let previousSecondaryCurrency = null;
let statusOutput = '';
let lastUpdate = +Date.now();
let retrievalError = false;
const writeToStdout = (limitReached, priceData, allowance) => {
let outputData = priceData;
// Clear screen
process.stdout.write('\x1Bc');
process.stdout.write('\n');
// Set status message for connectivity or API limit issues
if (!priceData) {
const lastUpdateText = colors.grey(` / Last updated ${moment(lastUpdate).fromNow()}\n\n`);
if (_.keys(previousPriceData).length) {
outputData = previousPriceData;
}
if (limitReached) {
statusOutput = colors.red(' ⚠ API limit has been reached') + lastUpdateText;
} else {
statusOutput = colors.red(' ⚠ Data retrieval error') + lastUpdateText;
}
retrievalError = true;
} else if (allowance && allowance.remaining < 1) {
statusOutput = colors.yellow(' ⚠ API limit is close to being reached\n\n');
retrievalError = false;
} else {
lastUpdate = +Date.now();
statusOutput = '';
retrievalError = false;
}
const sortedPrimaryCurrencies = _.keys(outputData).sort();
_.forEach(sortedPrimaryCurrencies, (primaryCurrency) => {
const sortedSecondaryCurrencies = _.keys(outputData[primaryCurrency]).sort();
_.forEach(sortedSecondaryCurrencies, (secondaryCurrency) => {
const sortedExchanges = _.keys(outputData[primaryCurrency][secondaryCurrency]).sort();
_.forEach(sortedExchanges, (exchange) => {
let changePercentageFixed;
const exchangePriceData = outputData[primaryCurrency][secondaryCurrency][exchange];
const changePercentage = Math.abs(exchangePriceData.price.change.percentage) * 100;
let lastPriceValue = outputData[primaryCurrency][secondaryCurrency][exchange].price.last;
let primaryCurrencyOutput = '';
let secondaryCurrencyOutput = '';
let exchangeOutput = '';
let changeOutput = '';
let historyChangeOutput = '';
// Set precision based on amount
if (changePercentage >= 100) {
changePercentageFixed = changePercentage.toFixed(0);
} else if (changePercentage >= 10) {
changePercentageFixed = changePercentage.toFixed(1);
} else {
changePercentageFixed = changePercentage.toFixed(2);
}
// Show primary currency name
if (previousPrimaryCurrency !== primaryCurrency) {
primaryCurrencyOutput = colors.bold.white(` › ${primaryCurrency}`)
+ pad(outputData.longestPrimaryCurrencyLength - primaryCurrency.length, '')
+ pad(options.padding, '');
previousPrimaryCurrency = primaryCurrency;
} else {
primaryCurrencyOutput = colors.bold(pad(outputData.longestPrimaryCurrencyLength + 3, ''))
+ pad(options.padding, '');
}
// Show secondary currency name
if (previousSecondaryCurrency !== secondaryCurrency) {
secondaryCurrencyOutput = secondaryCurrency
+ pad(outputData.longestSecondaryCurrencyLength - secondaryCurrency.length, '')
+ pad(options.padding, '');
previousSecondaryCurrency = secondaryCurrency;
} else {
secondaryCurrencyOutput = pad(outputData.longestSecondaryCurrencyLength, '')
+ pad(options.padding, '');
}
// Show exchange name
exchangeOutput = pad(exchange, outputData.longestExchangeLength) + pad(options.padding, '');
// Show percent change in last 24 hours
if (utility.fixed(exchangePriceData.price.change.percentage * 100, 2) > 0) {
changeOutput = pad(colors.green(`▲ ${changePercentageFixed.toString()}%`), 15);
} else if (utility.fixed(exchangePriceData.price.change.percentage * 100, 2) < 0) {
changeOutput = pad(colors.red(`▼ ${changePercentageFixed.toString()}%`), 15);
} else {
changeOutput = pad('', 7);
}
// Show history of price updates
if (
options.history.enabled
&& previousPriceData
&& previousPriceData[primaryCurrency]
&& previousPriceData[primaryCurrency][secondaryCurrency]
&& previousPriceData[primaryCurrency][secondaryCurrency][exchange]
&& +(previousPriceData[primaryCurrency][secondaryCurrency][exchange].price.last)
) {
const currentLastPrice = utility.fixed(exchangePriceData.price.last, 6);
const previousExchangeData = previousPriceData[primaryCurrency][secondaryCurrency][exchange];
const previousLastPrice = utility.fixed(previousExchangeData.price.last, 6);
const { majorThreshold } = options.history;
const dataKey = primaryCurrency + secondaryCurrency + exchange;
const percentageChange = utility.fixed((Math.abs(currentLastPrice - previousLastPrice) / previousLastPrice), 8) * 100;
let symbol;
// Determine history symbol
if (percentageChange > majorThreshold) {
symbol = currentLastPrice > previousLastPrice
? options.history.positiveMajorSymbol
: options.history.negativeMajorSymbol;
} else {
symbol = currentLastPrice > previousLastPrice
? options.history.positiveMinorSymbol
: options.history.negativeMinorSymbol;
}
priceDataHistory[dataKey] = priceDataHistory[dataKey] || new Array(options.history.length).fill(' ');
if (
currentLastPrice > previousLastPrice
&& utility.fixed(currentLastPrice - previousLastPrice, 6) > options.history.minorThreshold
) {
// Price has increased since last update and was greater than threshold
priceDataHistory[dataKey].push(colors.green.bold(symbol));
} else if (
currentLastPrice < previousLastPrice
&& utility.fixed(previousLastPrice - currentLastPrice, 6) > options.history.minorThreshold
) {
// Price has decreased since last update and was greater than threshold
priceDataHistory[dataKey].push(colors.red.bold(symbol));
} else {
priceDataHistory[dataKey].push(retrievalError ? ' ' : colors.grey(options.history.neutralSymbol));
}
historyChangeOutput = currentLastPrice - previousLastPrice;
// Format history output, set precision based on amount
if (historyChangeOutput === 0 || options.history.hideAmount) {
historyChangeOutput = '';
} else if (historyChangeOutput > 0) {
if (historyChangeOutput >= 1) {
historyChangeOutput = `+${utility.addCommas(historyChangeOutput.toFixed(2))}`;
} else {
historyChangeOutput = `+${utility.fixed(historyChangeOutput, 6)}`;
}
} else if (historyChangeOutput <= -1) {
historyChangeOutput = `${utility.addCommas(historyChangeOutput.toFixed(2))}`;
} else {
historyChangeOutput = `${utility.fixed(historyChangeOutput, 6)}`;
}
}
// Set precision based on amount
if (lastPriceValue >= 1) {
lastPriceValue = utility.addCommas(lastPriceValue.toFixed(2));
} else {
lastPriceValue = lastPriceValue.toFixed(6);
}
// eslint-disable-next-line prefer-template, no-useless-concat, max-len
process.stdout.write(primaryCurrencyOutput + secondaryCurrencyOutput + exchangeOutput + pad(10, lastPriceValue) + ' ' + changeOutput + ` ${(priceDataHistory[primaryCurrency + secondaryCurrency + exchange] || '') && priceDataHistory[primaryCurrency + secondaryCurrency + exchange].slice(-1 * options.history.length).join('')}` + ` ${colors.grey(historyChangeOutput)}` + '\n');
});
process.stdout.write('\n');
});
previousSecondaryCurrency = null;
});
process.stdout.write(`${statusOutput}`);
previousPrimaryCurrency = null;
previousPriceData = outputData;
return true;
};
// Retrieve pricing information from endpoint
const retrieveMarketData = () => {
const priceData = {};
const primaryCurrencies = [];
const secondaryCurrencies = [];
const exchanges = [];
const apiKeyString = options.apiKey ? `?apikey=${options.apiKey}` : '';
needle.get(`https://api.cryptowat.ch/markets/summaries${apiKeyString}`, (error, response) => {
const body = response && response.body;
if (!error && body && response.statusCode === 200) {
_.forEach(body.result, (data, market) => {
const marketsSlashesReplaced = options.markets.map(marketOption => marketOption.replace('/', ''));
const marketMatchIndex = marketsSlashesReplaced.indexOf(market);
// Disregard any options that do not exist within response
if (marketMatchIndex === -1) {
return;
}
const marketMatch = options.markets[marketMatchIndex];
const [exchange, marketName] = marketMatch.split(':');
let primaryCurrency;
let secondaryCurrency;
// Allow for vanity use of '/' to split primary and secondary currency
if (marketName.includes('/')) {
[primaryCurrency, secondaryCurrency] = marketName.split('/');
} else {
primaryCurrency = marketName.substr(0, 3);
secondaryCurrency = marketName.substr(3, 3);
}
primaryCurrency = primaryCurrency.toUpperCase();
secondaryCurrency = secondaryCurrency.toUpperCase();
primaryCurrencies.push(primaryCurrency);
secondaryCurrencies.push(secondaryCurrency);
exchanges.push(exchangeLookup[exchange]);
priceData[primaryCurrency] = priceData[primaryCurrency] || {};
priceData[primaryCurrency][secondaryCurrency] = priceData[primaryCurrency][secondaryCurrency] || {};
priceData[primaryCurrency][secondaryCurrency][exchangeLookup[exchange]] = body && body.result[market];
});
const sortedPrimaryCurrencies = primaryCurrencies.sort((a, b) => b.length - a.length);
const sortedSecondaryCurrencies = secondaryCurrencies.sort((a, b) => b.length - a.length);
const sortedExchanges = exchanges.sort((a, b) => b.length - a.length);
priceData.longestPrimaryCurrencyLength = sortedPrimaryCurrencies
&& sortedPrimaryCurrencies[0]
&& sortedPrimaryCurrencies[0].length;
priceData.longestSecondaryCurrencyLength = sortedSecondaryCurrencies
&& sortedSecondaryCurrencies[0]
&& sortedSecondaryCurrencies[0].length;
priceData.longestExchangeLength = sortedExchanges
&& sortedExchanges[0]
&& sortedExchanges[0].length;
if (priceData) {
return writeToStdout(null, priceData, response.body.allowance);
}
} else if (response && response.statuscode === 429) {
return writeToStdout(true);
}
return writeToStdout(false, null);
});
};
// Retrieve exchange information from endpoint
const retrieveExchangeData = () => {
const apiKeyString = options.apiKey ? `?apikey=${options.apiKey}` : '';
needle.get(`https://api.cryptowat.ch/exchanges${apiKeyString}`, (error, response) => {
const body = response && response.body;
if (!error && body && response.statusCode === 200) {
body.result.forEach((exchange) => {
exchangeLookup[exchange.symbol] = exchange.name;
});
setInterval(() => {
retrieveMarketData();
}, options.pollInterval);
return retrieveMarketData();
}
if (response && response.statusCode === 429) {
return writeToStdout(true);
}
writeToStdout(false, null);
// Retry on connection failure
return setTimeout(() => {
retrieveExchangeData();
}, options.pollInterval);
});
};
// Kick out the jams
retrieveExchangeData();