· 4 years ago · Jun 06, 2021, 12:24 AM
1var sqlite3 = require('sqlite3').verbose();
2// CREATE MEMORY DB
3var db = new sqlite3.Database(':memory:');
4
5// CREATE SQLITE TABLE
6db.serialize(function() {
7 db.run("CREATE TABLE IF NOT EXISTS crypto_data (symbol data_type PRIMARY KEY, value_5, current_value)");
8});
9
10// SET INTERVAL IN MINUTES FOR CRYPTO VALUE CHECK
11const cryptoCheckMinutes = 3;
12const cryptoInterval = cryptoCheckMinutes * 60000;
13
14const minPercentWarn = 0.2;
15
16//LOAD CRYPTOCOMPARE MODULE (needs cryptocompare & node-fetch)
17global.fetch = require('node-fetch')
18const cc = require('cryptocompare')
19//FREE API KEY PERFORMS 100.000 REQUESTS/MONTH
20cc.setApiKey('6ce8e65c53fbb9dae8f068d2a06c6d1857f77f2de8cb4a732b4d61359695de80')
21
22const cryptoArr = ['BTC', 'LTC', 'ETH', 'XCH', 'DOGE']
23let placeholders = cryptoArr.map((crypto) => '(?)').join(',');
24let sql = 'INSERT INTO crypto_data(symbol) VALUES ' + placeholders;
25db.serialize(function() {
26 db.run(sql, cryptoArr);
27})
28
29
30function getCryptoVal(symbols, database) {
31 var promises = [];
32 symbols.forEach(symbol => {
33 promises.push(
34 cc.price(symbol, 'USDT')
35 .then(prices => {
36 doDbStuff(symbol, database, prices.USDT)
37 })
38 .catch(console.error)
39 )
40 });
41
42 Promise.all(promises).then(() =>
43 setTimeout(function() {
44 database.each("SELECT * FROM crypto_data", function(err, row) {
45 if (row.value_5 !== null) {
46 diff = row.current_value - row.value_5;
47 diff < 0 ? direction = "down" : direction = "up";
48 percentCurrent = (diff * 100) / row.value_5;
49 if (Math.abs(percentCurrent) > minPercentWarn) {
50 //OUTPUTS IF SYMBOL MEETS MINIMUM PERCENT VARIANCE REQUIRED
51 console.log(row.symbol + "[" + row.current_value + " USDT]", "is", direction, "$", diff.toFixed(3), "or", percentCurrent.toFixed(3) + "% from", cryptoCheckMinutes, "minutes ago");
52 }
53 } else {
54 // INITIAL OUTPUT
55 console.log(row.symbol, "OLD:", row.value_5, "NEW:", row.current_value);
56 }
57 })
58 },1000)
59 );
60// console.log("\n");
61}
62
63
64
65
66
67
68function doDbStuff(symbol, database, current) {
69 database.serialize(function() {
70 query = 'SELECT current_value FROM crypto_data WHERE symbol = ?';
71 database.all(query, symbol, function(err, rows) {
72 response = rows[0]
73 if (response) {
74 database.run("UPDATE crypto_data set value_5 = ?, current_value = ? WHERE symbol = ?", response.current_value, current, symbol);
75 } else {
76 database.run("UPDATE crypto_data set current_value = ? WHERE symbol = ?", current, symbol);
77 }
78 })
79 })
80}
81
82
83// INITIATE ROUTINE
84setInterval(function() {
85 getCryptoVal(cryptoArr, db);
86}, cryptoInterval);
87