-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMM-crypto-portfolio.js
521 lines (469 loc) · 17.9 KB
/
MMM-crypto-portfolio.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
Module.register('MMM-crypto-portfolio', {
result: {},
defaults: {
currency: [{name:'bitcoin', portf: 2},
{name:'ripple', portf: 1.688014},
{name:'litecoin', portf: 0.382885},
{name:'ethereum', portf: 3.771212}],
conversion: 'EUR',
showUSD: false,
showPortfolio: true,
showAssets: true,
showAgainstBTC:true,
displayLongNames: false,
headers: [],
displayType: 'detail',
showGraphs: false,
logoHeaderText: 'My Crypto portfolio',
significantDigits: 2,
coloredLogos: false,
fontSize: 'small',
limit: '50'
},
sparklineIds: {
bitcoin: 1,
ethereum: 1027,
ripple: 52,
litecoin: 2,
'ethereum-classic': 1321,
nem: 873,
stratis: 1343,
'bitcoin-cash': 1831,
'bitcoin-gold': 2083,
cardano: 2010,
dash: 131,
eos: 1765,
monero: 328,
neo: 1376,
stellar: 512,
iota: 1720,
tron: 1958,
qtum: 1684,
omisego: 1808,
airswap: 2058,
aelf: 2299,
aeternity: 1700,
aion: 2062,
ardor: 1320,
ark: 1586,
augur: 1104,
bancor: 1727,
'basic-attention-token': 1697,
'binance-coin': 1839,
bitcoin: 1,
'bitcoin-cash': 1831,
'bitcoin-gold': 2083,
bitshares: 463,
byteball: 1492,
'bytecoin-bcn': 372,
bytom: 1866,
cardano: 2010,
chainlink: 1975,
cindicator: 2043,
cryptonex: 2027,
dash: 131,
decred: 1168,
dent: 1886,
dentacoin: 1876,
digibyte: 109,
digixdao: 1229,
dogecoin: 74,
dragonchain: 2243,
electroneum: 2137,
emercoin: 558,
'enigma-project': 2044,
eos: 1765,
ethereum: 1027,
'ethereum-classic': 1321,
ethos: 1817,
'experience-points': 1367,
factom: 1087,
funfair: 1757,
gas: 1785,
'golem-network-tokens': 1455,
gxshares: 1750,
hshare: 1903,
icon: 2099,
iota: 1720,
kin: 1993,
komodo: 1521,
'kucoin-shares': 2087,
'kyber-network': 1982,
lisk: 1214,
litecoin: 2,
loopring: 1934,
maidsafecoin: 291,
maker: 1518,
medibloc: 2303,
monacoin: 213,
monero: 328,
neblio: 1955,
'nebulas-token': 1908,
nem: 873,
neo: 1376,
nexus: 789,
nxt: 66,
omisego: 1808,
particl: 1826,
pillar: 1834,
pivx: 1169,
populous: 1789,
'power-ledger': 2132,
qash: 2213,
qtum: 1684,
quantstamp: 2212,
raiblocks: 1567,
rchain: 2021,
reddcoin: 118,
'request-network': 2071,
ripple: 52,
salt: 1996,
siacoin: 1042,
'sirin-labs-token': 2313,
smartcash: 1828,
status: 1759,
steem: 1230,
stellar: 512,
stratis: 1343,
substratum: 1984,
syscoin: 541,
tenx: 1758,
tether: 825,
'time-new-bank': 2235,
tron: 1958,
vechain: 1904,
verge: 693,
veritaseum: 1710,
walton: 1925,
waves: 1274,
wax: 2300,
zcash: 1437,
zclassic: 1447,
zcoin: 1414
},
start: function() {
this.getTicker()
this.scheduleUpdate()
},
getStyles: function() {
return ['MMM-crypto-portfolio.css',
'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css']
},
getTicker: function() {
var conversion = this.config.conversion
var url = 'https://api.coinmarketcap.com/v1/ticker/?convert=' + conversion + '&limit=' + this.config.limit
this.sendSocketNotification('READ_COINS', url)
},
scheduleUpdate: function() {
var self = this
// Refresh time should not be less than 5 minutes
var delay = 300000
setInterval(function() {
self.getTicker()
}, delay)
},
getDom: function() {
if (this.config.displayType == 'logo' || this.config.displayType == 'logoWithChanges') {
this.folder = (this.config.coloredLogos ? 'colored/' : 'black-white/')
return this.buildIconView(this.result, this.config.displayType)
}
var data = this.result
var wrapper = document.createElement('table')
wrapper.className = 'small MMM-crypto-portfolio'
var tableHeader = document.createElement('tr')
tableHeader.className = 'header-row'
var tableHeaderValues = [
this.translate('CURRENCY'),
this.translate('PRICE')
]
if (this.config.showAgainstBTC){tableHeaderValues.push('BTC')}
if (this.config.showAssets){tableHeaderValues.push(this.translate('ASSETS'))}
if (this.config.showPortfolio){tableHeaderValues.push(this.translate('PORTFOLIO'))}
if (this.config.headers.indexOf('change1h') > -1) {
tableHeaderValues.push(this.translate('CHANGE') + ' '+this.translate('ONEHOUR'))
}
if (this.config.headers.indexOf('change24h') > -1) {
tableHeaderValues.push(this.translate('CHANGE') + ' '+this.translate('ONEDAY'))
}
if (this.config.headers.indexOf('change7d') > -1) {
tableHeaderValues.push(this.translate('CHANGE') + ' '+this.translate('ONEWEEK'))
}
for (var i = 0; i < tableHeaderValues.length; i++) {
var tableHeadSetup = document.createElement('th')
tableHeadSetup.innerHTML = tableHeaderValues[i]
tableHeader.appendChild(tableHeadSetup)
}
tableHeader.style.textAlign="right";
wrapper.appendChild(tableHeader)
var marketCapMyWallet = 0;
var myTotalAsset = 0;
for (i = 0; i < data.length; i++) {
var currentCurrency = data[i]
var trWrapper = document.createElement('tr')
trWrapper.className = 'currency'
var name
if (this.config.displayLongNames) {
name = currentCurrency.name
} else {
name = currentCurrency.symbol
}
marketCapMyWallet += parseFloat(currentCurrency.market_cap_eur);
var cPrice= currentCurrency.price.replace("€", "").trim();
cPrice= parseFloat(cPrice.replace(",","."));
myTotalAsset += cPrice * this.config.currency[i].portf
var myWallet='€ '+(this.config.currency[i].portf * cPrice ).toFixed(2);
var tdValues = [
name,
currentCurrency.price
]
if (this.config.showAgainstBTC){
tdValues.push('<i class="fa fa-bitcoin"></i> '+currentCurrency.price_btc)
}
if (this.config.showAssets) {
tdValues.push(myWallet);
}
if (this.config.showPortfolio){
tdValues.push(''+this.config.currency[i].portf )
}
if (this.config.headers.indexOf('change1h') > -1) {
tdValues.push(currentCurrency.percent_change_1h + '%')
}
if (this.config.headers.indexOf('change24h') > -1) {
tdValues.push(currentCurrency.percent_change_24h + '%')
}
if (this.config.headers.indexOf('change7d') > -1) {
tdValues.push(currentCurrency.percent_change_7d + '%')
}
for (var j = 0; j < tdValues.length; j++) {
var tdWrapper = document.createElement('td')
let currValue = tdValues[j]
// If I am showing value then set color
if (currValue.includes('%')) {
tdWrapper.style.color = this.colorizeChange(currValue.slice(0,-1))
}
tdWrapper.style.textAlign=(j>0?"right":"left");
tdWrapper.innerHTML = currValue
trWrapper.appendChild(tdWrapper)
}
wrapper.appendChild(trWrapper)
}
if (this.config.showAssets){
// add tr for totals
var trWrapper = document.createElement('tr')
trWrapper.className = 'currency'
var tdWrapper = document.createElement('td')
tdWrapper.style.textAlign="left";
tdWrapper.innerHTML = this.translate('TOTAL');
tdWrapper.colSpan=(this.config.showAgainstBTC?3:2);
trWrapper.appendChild(tdWrapper)
wrapper.appendChild(trWrapper)
var tdWrapper = document.createElement('td')
tdWrapper.style.textAlign="right";
tdWrapper.innerHTML = "€ " + myTotalAsset.toFixed(2)
trWrapper.appendChild(tdWrapper)
wrapper.appendChild(trWrapper)
}
var tableCaption = document.createElement('caption');
tableCaption.innerHTML = this.translate('MARKCAP')+": € " + this.formatMoney(marketCapMyWallet,0,',','.');
wrapper.appendChild(tableCaption);
return wrapper
},
socketNotificationReceived: function(notification, payload) {
if (notification === 'COINS_DATA') {
//info.log(this.config.currency[0].name)
this.result = this.getWantedCurrencies(this.config.currency, payload)
this.updateDom()
}
},
/**
* Returns configured currencies
*
* @param chosenCurrencies
* @param apiResult
* @returns {Array}
*/
getWantedCurrencies: function(chosenCurrencies, apiResult) {
var filteredCurrencies = []
for (var i = 0; i < chosenCurrencies.length; i++) {
for (var j = 0; j < apiResult.length; j++) {
var userCurrency = chosenCurrencies[i]
var remoteCurrency = apiResult[j]
if (userCurrency.name == remoteCurrency.id) {
remoteCurrency = this.formatPrice(remoteCurrency)
filteredCurrencies.push(remoteCurrency)
}
}
}
return filteredCurrencies
},
/**
* Formats the price of the API result and adds it to the object with simply .price as key
* instead of price_eur
*
* @param apiResult
* @returns {*}
*/
formatPrice: function(apiResult) {
var rightCurrencyFormat = this.config.conversion.toLowerCase()
// rounding the price in Conversion
var unroundedPrice = apiResult['price_' + rightCurrencyFormat]
var digitsBeforeDecimalPoint = Math.floor(unroundedPrice).toString().length
var requiredDigitsAfterDecimalPoint = Math.max(this.config.significantDigits - digitsBeforeDecimalPoint, 2)
var price = this.roundNumber(unroundedPrice, requiredDigitsAfterDecimalPoint)
console.log("config.language: " + config.language);
// add the currency string
apiResult['price'] = price.toLocaleString(config.language, { style: 'currency', currency: this.config.conversion })
if (rightCurrencyFormat != 'usd' && this.config.showUSD) {
// rounding the priceUSD
var unroundedPriceUSD = apiResult['price_usd']
var digitsBeforeDecimalPointUSD = Math.floor(unroundedPriceUSD).toString().length
var requiredDigitsAfterDecimalPointUSD = Math.max(this.config.significantDigits - digitsBeforeDecimalPointUSD, 2)
var priceUSD = this.roundNumber(unroundedPriceUSD, requiredDigitsAfterDecimalPointUSD)
apiResult['price'] += ' / ' + priceUSD.toLocaleString(config.language, { style: 'currency', currency: 'USD' })
}
return apiResult
},
/**
* Rounds a number to a given number of digits after the decimal point
*
* @param number
* @param precision
* @returns {number}
*/
roundNumber: function(number, precision) {
var factor = Math.pow(10, precision)
var tempNumber = number * factor
var roundedTempNumber = Math.round(tempNumber)
return roundedTempNumber / factor
},
/**
* Creates the icon view type
*
* @param apiResult
* @param displayType
* @returns {Element}
*/
buildIconView: function(apiResult, displayType) {
var wrapper = document.createElement('div')
var header = document.createElement('header')
header.className = 'module-header'
header.innerHTML = this.config.logoHeaderText
if (this.config.logoHeaderText !== '') {
wrapper.appendChild(header)
}
var table = document.createElement('table')
table.className = 'medium MMM-crypto-portfolio-icon'
for (var j = 0; j < apiResult.length; j++) {
var tr = document.createElement('tr')
tr.className = 'icon-row'
var logoWrapper = document.createElement('td')
logoWrapper.className = 'icon-field'
//logoWrapper.colSpan=5;
if (this.imageExists(apiResult[j].id)) {
var logo = new Image()
logo.src = '/MMM-crypto-portfolio/' + this.folder + apiResult[j].id + '.png'
logo.style.maxWidth="50px";
logo.style.maxHeight="50px";
logoWrapper.appendChild(logo)
} else {
this.sendNotification('SHOW_ALERT', {
timer: 5000,
title: 'MMM-crypto-portfolio',
message: '' +
this.translate('IMAGE') + ' ' + apiResult[j].id + '.png ' + this.translate('NOTFOUND') + ' /MMM-crypto-portfolio/public/' + this.folder
})
}
cPrice= apiResult[j].price.replace("€", "");
cPrice= cPrice.replace(",",".");
var myWallet=(this.config.currency[j].portf * cPrice).toFixed(2);
var priceWrapper = document.createElement('td')
var price = document.createElement('price')
price.style.fontSize = this.config.fontSize
price.innerHTML = this.config.currency[j].portf + ' @ ' + apiResult[j].price.replace("EUR", "€") + ' = € ' + myWallet;
priceWrapper.appendChild(price)
if (displayType == 'logoWithChanges') {
let changesWrapper = document.createElement('div')
var change_1h = document.createElement('change_1h')
change_1h.style.color = this.colorizeChange(apiResult[j].percent_change_1h)
change_1h.style.fontSize = 'medium'
change_1h.innerHTML = 'h: ' + apiResult[j].percent_change_1h + '%'
change_1h.style.marginRight = '12px'
var change_24h = document.createElement('change_24h')
change_24h.style.color = this.colorizeChange(apiResult[j].percent_change_24h)
change_24h.style.fontSize = 'medium'
change_24h.innerHTML = 'd: ' + apiResult[j].percent_change_24h + '%'
change_24h.style.marginRight = '12px'
var change_7d = document.createElement('change_7d')
change_7d.style.color = this.colorizeChange(apiResult[j].percent_change_7d)
change_7d.style.fontSize = 'medium'
change_7d.innerHTML = 'w: ' + apiResult[j].percent_change_7d + '%'
changesWrapper.appendChild(change_1h)
changesWrapper.appendChild(change_24h)
changesWrapper.appendChild(change_7d)
priceWrapper.appendChild(changesWrapper)
} else {
priceWrapper.className = 'price'
}
tr.appendChild(logoWrapper)
tr.appendChild(priceWrapper)
if (this.config.showGraphs) {
var graphWrapper = document.createElement('td')
graphWrapper.className = 'graph'
if (this.sparklineIds[apiResult[j].id]) {
var graph = document.createElement('img')
graph.src = 'https://files.coinmarketcap.com/generated/sparklines/' + this.sparklineIds[apiResult[j].id] + '.png?cachePrevention=' + Math.random()
console.log(graph.src)
graph.style.maxWidth="150px";
graphWrapper.appendChild(graph)
}
tr.appendChild(graphWrapper)
}
table.appendChild(tr)
}
wrapper.appendChild(table)
return wrapper
},
/**
* Checks if an image with the passed name exists
*
* @param currencyName
* @returns {boolean}
*/
imageExists: function(currencyName) {
var imgPath = '/MMM-crypto-portfolio/' + this.folder + currencyName + '.png'
var http = new XMLHttpRequest()
http.open('HEAD', imgPath, false)
http.send()
return http.status != 404
},
colorizeChange: function(change) {
if (change < 0) {
return 'Red'
} else if (change > 0) {
return 'Green'
} else {
return 'White'
}
},
/**
* Load translations files
* @returns {{en: string, de: string, it: string}}
*/
getTranslations: function() {
return {
en: 'translations/en.json',
de: 'translations/de.json',
it: 'translations/it.json',
nl: 'translations/nl.json'
}
},
formatMoney: function(n,c, d, t){
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
})