-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
645 lines (580 loc) · 19.7 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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
const topTenList = document.querySelector("#top-ten");
const singleChartDiv = document.querySelector("#coins");
const compareChartsDiv = document.querySelector("#comparing-data");
const formSingle = document.querySelector("#single");
const formMultiple = document.querySelector("#multiple");
const twentyFourHours = document.querySelector("#day");
const sevenDays = document.querySelector("#week");
const thirtyDays = document.querySelector("#month");
const oneYear = document.querySelector("#year");
const twentyFourHoursCompare = document.querySelector("#day-compare");
const sevenDaysCompare = document.querySelector("#week-compare");
const thirtyDaysCompare = document.querySelector("#month-compare");
const oneYearCompare = document.querySelector("#year-compare");
const mergeButton = document.querySelector("#merge");
const detailsLeft = document.querySelector("#left");
const detailsRight = document.querySelector("#right");
const chart1 = document.querySelector("#chart-left");
const chart2 = document.querySelector("#chart-right");
const chartMerge = document.querySelector("#chart-merge");
const tooltip = document.getElementById("tooltip");
let merge = false;
let coinLeft = "bitcoin";
let coinRight = "";
let pricesLeft = [];
let pricesRight = [];
let days = 365;
let interval = "daily";
//----------- codes to initizalize the webpage ----------
//to hide all data div when website init
singleChartDiv.style.display = "flex";
compareChartsDiv.style.display = "none";
chartMerge.style.display = "none";
//to show top 10 coins and refresh every 10 secs
getTopCoins(10);
// have to cancel thise because coingecko added rate limit
// const intervalID = setInterval(getTopCoins, 10000, 10);
//to show bitcoin data when page load
getCoinHistory(coinLeft, days, interval, "single", drawGoogleChart);
getCurrentData(coinLeft, "");
//--------------------------------------------------------
//----------- add eventListeners to all buttons ------------------
mergeButton.addEventListener("click", () => {
if (!merge) {
chart1.style.display = "none";
chart2.style.display = "none";
chartMerge.style.display = "block";
drawGoogleChartMerge(pricesLeft, pricesRight, days, interval);
mergeButton.textContent = "Unmerge";
merge = true;
} else {
chartReset();
}
});
//function to reset charts position
function chartReset() {
chart1.style.display = "block";
chart2.style.display = "block";
chartMerge.style.display = "none";
getCoinHistory(coinLeft, days, interval, "left", drawGoogleChart);
if (coinRight) {
getCoinHistory(coinRight, days, interval, "right", drawGoogleChart);
}
merge = false;
mergeButton.textContent = "Merge";
}
// twentyFourHours.addEventListener("click", () => {
// getCoinHistory(coinLeft, 1, "min", "single", drawGoogleChart).then(() => {
// days = 1;
// interval = "min";
// });
// });
sevenDays.addEventListener("click", () => {
getCoinHistory(coinLeft, 7, "daily", "single", drawGoogleChart).then(() => {
days = 7;
interval = "daily";
});
});
thirtyDays.addEventListener("click", () => {
getCoinHistory(coinLeft, 30, "daily", "single", drawGoogleChart).then(() => {
days = 30;
interval = "daily";
});
});
oneYear.addEventListener("click", () => {
getCoinHistory(coinLeft, 365, "daily", "single", drawGoogleChart).then(() => {
days = 365;
interval = "daily";
});
});
// twentyFourHoursCompare.addEventListener("click", () => {
// const promises = [];
// promises.push(getCoinHistory(coinLeft, 1, "min", "left", drawGoogleChart));
// promises.push(getCoinHistory(coinRight, 1, "min", "right", drawGoogleChart));
// Promise.all(promises).then(() => {
// days = 1;
// interval = "min";
// drawGoogleChartMerge(pricesLeft, pricesRight, days, interval);
// });
// });
sevenDaysCompare.addEventListener("click", () => {
const promises = [];
promises.push(getCoinHistory(coinLeft, 7, "daily", "left", drawGoogleChart));
promises.push(
getCoinHistory(coinRight, 7, "daily", "right", drawGoogleChart)
);
Promise.all(promises).then(() => {
days = 7;
interval = "daily";
drawGoogleChartMerge(pricesLeft, pricesRight, days, interval);
});
});
thirtyDaysCompare.addEventListener("click", () => {
const promises = [];
promises.push(getCoinHistory(coinLeft, 30, "daily", "left", drawGoogleChart));
promises.push(
getCoinHistory(coinRight, 30, "daily", "right", drawGoogleChart)
);
Promise.all(promises).then(() => {
days = 30;
interval = "daily";
drawGoogleChartMerge(pricesLeft, pricesRight, days, interval);
});
});
oneYearCompare.addEventListener("click", () => {
const promises = [];
promises.push(
getCoinHistory(coinLeft, 365, "daily", "left", drawGoogleChart)
);
promises.push(
getCoinHistory(coinRight, 365, "daily", "right", drawGoogleChart)
);
Promise.all(promises).then(() => {
days = 365;
interval = "daily";
drawGoogleChartMerge(pricesLeft, pricesRight, days, interval);
});
});
//---------------------------------------------------------------------------------
//fetch real time data for top coins
function getTopCoins(num) {
fetch(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${num}&page=1&sparkline=false`
)
.then((res) => res.json())
.then(showTopTenCoins);
}
//show coin data on the top menu
function showTopTenCoins(coins) {
topTenList.innerHTML = "";
coins.forEach((coin) => {
const div = document.createElement("div");
const img = document.createElement("img");
const priceDiv = document.createElement("div");
const symbol = document.createElement("p");
const price = document.createElement("span");
div.id = "hoverable";
div.style.display = "flex";
img.src = coin.image;
img.style.width = "30px";
img.style.objectFit = "contain";
img.style.margin = "5px";
symbol.textContent = `${coin.symbol.toUpperCase()} : `;
price.textContent =
coin.current_price > 2
? `$${coin.current_price.toFixed(2)}`
: `$${coin.current_price.toFixed(4)}`;
price.style.color = coin.price_change_percentage_24h >= 0 ? "green" : "red";
priceDiv.append(symbol);
symbol.append(price);
div.append(img, priceDiv);
topTenList.append(div);
addListener(div, coin.id);
});
}
//add event listener to top 10 list
function addListener(div, coinId) {
div.addEventListener("click", () => {
coinLeft = coinId;
singleChartDiv.style.display = "flex";
compareChartsDiv.style.display = "none";
days = 1;
interval = 1;
getCoinHistory(coinId, 365, "daily", "single", drawGoogleChart);
getCurrentData(coinId, "");
chartReset();
});
}
//function to check form input
function checkInput(input) {
return fetch(`https://api.coingecko.com/api/v3/search?query=${input}`)
.then((res) => res.json())
.then((data) => {
if (data.coins[0]) {
return data.coins[0].id;
} else {
return false;
}
})
.catch(console.error);
}
//function to get current data for a coin
function getCurrentData(coinId, s) {
fetch(`https://api.coingecko.com/api/v3/coins/${coinId}`)
.then((res) => res.json())
.then((data) => {
// console.log(data)
showDataMain(data, s);
})
.catch(console.error);
}
//function to show current coin data on main
function showDataMain(data, s) {
const coinImg = document.querySelector(`#coinIcon${s}`);
const coinName = document.querySelector(`#coinName${s}`);
const coinRank = document.querySelector(`#rank${s}`);
const coinPrice = document.querySelector(`#price${s}`);
const coinMarketCap = document.querySelector(`#cap${s}`);
const coinAllTimeHigh = document.querySelector(`#ath${s}`);
const coinAllTimeLow = document.querySelector(`#atl${s}`);
const coin24High = document.querySelector(`#high24${s}`);
const coin24Low = document.querySelector(`#low24${s}`);
const coin24Change = document.querySelector(`#change24${s}`);
coinImg.src = data.image.thumb;
coinName.textContent = data.name;
coinRank.textContent = data.market_cap_rank;
coinPrice.textContent = `$${data.market_data.current_price.usd.toLocaleString(
undefined,
{ minimumFractionDigits: 2 }
)}`;
coinMarketCap.textContent = `$${data.market_data.market_cap.usd.toLocaleString(
undefined,
{ maximumFractionDigits: 0 }
)}`;
coin24High.textContent = `$${data.market_data.high_24h.usd.toLocaleString(
undefined,
{ minimumFractionDigits: 2 }
)}`;
coin24Low.textContent = `$${data.market_data.low_24h.usd.toLocaleString(
undefined,
{ minimumFractionDigits: 2 }
)}`;
coinAllTimeHigh.textContent = `$${data.market_data.ath.usd.toLocaleString(
undefined,
{ minimumFractionDigits: 2 }
)}`;
coinAllTimeLow.textContent = `$${data.market_data.atl.usd.toLocaleString(
undefined,
{ minimumFractionDigits: 2 }
)}`;
coin24Change.textContent =
data.market_data.price_change_percentage_24h > 0
? `+${data.market_data.price_change_percentage_24h}%`
: `${data.market_data.price_change_percentage_24h}%`;
coin24Change.style.color =
data.market_data.price_change_percentage_24h >= 0 ? "green" : "red";
}
//function to get historical data
function getCoinHistory(
coinId,
days,
interval = "daily",
position,
f = drawGoogleChart
) {
return fetch(
`https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=usd&days=${
days > 2 ? days - 1 : 1
}&interval=${interval}`
)
.then((res) => res.json())
.then((data) => {
const prices = [];
data.prices.forEach((price) => {
const dateObj = new Date(price[0]);
let year = dateObj.getFullYear();
let month = dateObj.getMonth() + 1;
let day = dateObj.getDate();
let hour = dateObj.toLocaleTimeString("it-IT").slice(0, 5);
prices.push({
year: year,
month: month,
day: day,
hour: hour,
price: price[1],
});
});
if (position === "right") {
pricesRight = [...prices];
} else {
pricesLeft = [...prices];
}
// console.log(prices)
f(prices, coinId, days, interval, position);
})
.catch(console.error);
}
//------------------------------------------------ google chart ------------------------------------------------
//function to draw chart on main, left or right, base on position
function drawGoogleChart(dataArr, coinId, days, interval, position) {
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
const coinName = coinId.substring(0, 1).toUpperCase() + coinId.substring(1);
const output =
interval === "daily"
? [[`${days}days Data`, coinName]]
: [["24 hrs Data", coinName]];
dataArr.forEach((data) => {
if (interval === "daily") {
output.push([`${data.month}/${data.day}`, data.price]);
} else {
output.push([data.hour, data.price]);
}
});
function drawChart() {
const data = google.visualization.arrayToDataTable(output);
const title =
interval === "daily" ? `${days} Days Data` : "Last 24 hrs Data";
const color = position === "right" ? "#e7711b" : "#1c91c0";
const options = {
title: `${coinName} Performance`,
hAxis: { title: title, titleTextStyle: { color: "#333" } },
vAxis: {
minValue: 0,
format: "currency",
},
series: { 0: { color: color } },
};
const chart = new google.visualization.AreaChart(
document.getElementById(`chart-${position}`)
);
chart.draw(data, options);
}
}
//function to draw the merge chart
function drawGoogleChartMerge(pricesLeft, pricesRight, days, interval) {
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
const coinNameLeft =
coinLeft.substring(0, 1).toUpperCase() + coinLeft.substring(1);
const coinNameRight =
coinRight.substring(0, 1).toUpperCase() + coinRight.substring(1);
//-------------------to balance pricesLeft and pricesRight Data length--------------------------
let updatedPricesLeft = [];
let updatedPricesRight = [];
if (interval === "daily") {
if (pricesLeft.length > pricesRight.length) {
const diff = pricesLeft.length - pricesRight.length;
for (let i = 0; i < diff; i++) {
const zeroPrice = { ...pricesLeft[i], price: 0 };
updatedPricesRight.push(zeroPrice);
}
updatedPricesLeft = pricesLeft;
updatedPricesRight = [...updatedPricesRight, ...pricesRight];
} else {
const diff = pricesRight.length - pricesLeft.length;
for (let i = 0; i < diff; i++) {
const zeroPrice = { ...pricesRight[i], price: 0 };
updatedPricesLeft.push(zeroPrice);
}
updatedPricesLeft = [...updatedPricesLeft, ...pricesLeft];
updatedPricesRight = pricesRight;
}
} else {
if (pricesLeft.length > pricesRight.length) {
const diff = pricesLeft.length - pricesRight.length;
updatedPricesLeft = pricesLeft.slice(diff);
updatedPricesRight = pricesRight;
} else {
const diff = pricesRight.length - pricesLeft.length;
updatedPricesLeft = pricesLeft;
updatedPricesRight = pricesRight.slice(diff);
}
}
// console.log(updatedPricesLeft)
// console.log(updatedPricesRight)
//------------------------import updated data into merge chart---------------------------------//
output =
interval === "daily"
? [[`${days}days Data`, coinNameLeft, coinNameRight]]
: [["24 hrs Data", coinNameLeft, coinNameRight]];
for (let i = 0; i < updatedPricesLeft.length; i++) {
if (interval === "daily") {
output.push([
`${updatedPricesLeft[i].month}/${updatedPricesLeft[i].day}`,
updatedPricesLeft[i].price,
updatedPricesRight[i].price,
]);
} else {
output.push([
updatedPricesLeft[i].hour,
updatedPricesLeft[i].price,
updatedPricesRight[i].price,
]);
}
}
function drawChart() {
const data = google.visualization.arrayToDataTable(output);
const title =
interval === "daily" ? `${days} Days Data` : "Last 24 hrs Data";
const options = {
title: `${coinNameLeft} and ${coinNameRight} Performance Compare`,
hAxis: { title: title, titleTextStyle: { color: "#333" } },
vAxis: {
minValue: 0,
format: "currency",
// gridlines: {color: "transparent"}
},
series: {
0: { targetAxisIndex: 0 },
1: { targetAxisIndex: 1 },
},
};
const chart = new google.visualization.AreaChart(
document.getElementById(`chart-merge`)
);
chart.draw(data, options);
}
}
//----------------AUTO COMPLETE----------------//
// fetch("https://api.coingecko.com/api/v3/coins")
// .then((res) => res.json())
// .then(createArray);
let coins = [];
function createArray(data) {
data.forEach((coin) => {
let id = coin.symbol;
if (id.toString().length >= 3) {
id.toUpperCase();
coins.push(id);
} else {
}
});
}
function autocomplete(inp, arr) {
let currentFocus;
inp.addEventListener("input", function (e) {
let a,
b,
i,
val = this.value;
closeAllLists();
if (!val) {
return false;
}
currentFocus = -1;
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
b = document.createElement("div");
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
b.innerHTML += "<input type = 'hidden' value = '" + arr[i] + "'>";
b.addEventListener("click", function (e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
}
}
});
inp.addEventListener("keydown", function (e) {
let x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
currentFocus++;
addActive(x);
} else if (e.keyCode == 38) {
currentFocus--;
addActive(x);
} else if (e.keyCode == 13) {
e.preventDefault();
if (currentFocus > -1) {
if (x) x[currentFocus].click();
}
addActive(x);
}
});
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = x.length - 1;
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
for (let i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
let x = document.getElementsByClassName("autocomplete-items");
for (let i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
// autocomplete(document.getElementById("singleInput"), coins);
// autocomplete(document.getElementById("multipleInput"), coins);
function submitForm(e) {
e.preventDefault();
let input = e.target["singleInput"].value;
checkInput(input).then((result) => {
if (result) {
coinLeft = result;
singleChartDiv.style.display = "flex";
compareChartsDiv.style.display = "none";
getCurrentData(coinLeft, "");
getCoinHistory(coinLeft, 365, "daily", "single", drawGoogleChart);
chartReset();
chart2.style.opacity = "1";
days = 1;
interval = "min";
e.target.reset();
} else {
alert("invalid input");
}
});
}
formSingle.addEventListener("submit", submitForm);
//get input from compare form
formMultiple.addEventListener("submit", (e) => {
e.preventDefault();
let input = e.target["multipleInput"].value;
checkInput(input).then((result) => {
if (result) {
coinRight = result;
singleChartDiv.style.display = "none";
compareChartsDiv.style.display = "block";
getCurrentData(coinLeft, "-left");
getCurrentData(coinRight, "-right");
getCoinHistory(coinLeft, 365, "daily", "left", drawGoogleChart);
getCoinHistory(coinRight, 365, "daily", "right", drawGoogleChart);
days = 1;
interval = "min";
chartReset();
e.target.reset();
} else {
alert("invalid input");
}
});
});
// add tooltip to 24hr buttons
twentyFourHours.addEventListener("mouseover", () => {
// Calculate the position of the tooltip
const buttonRect = twentyFourHours.getBoundingClientRect();
const tooltipWidth = tooltip.offsetWidth;
const tooltipHeight = tooltip.offsetHeight;
const tooltipX = buttonRect.left + buttonRect.width / 2 - tooltipWidth / 2;
const tooltipY = buttonRect.top + window.scrollY - tooltipHeight - 10;
// Position the tooltip and make it visible
tooltip.style.left = tooltipX + "px";
tooltip.style.top = tooltipY + "px";
tooltip.style.display = "block";
});
twentyFourHours.addEventListener("mouseout", () => {
tooltip.style.display = "none";
});
twentyFourHoursCompare.addEventListener("mouseover", () => {
// Calculate the position of the tooltip
const buttonRect = twentyFourHoursCompare.getBoundingClientRect();
const tooltipWidth = tooltip.offsetWidth;
const tooltipHeight = tooltip.offsetHeight;
const tooltipX = buttonRect.left + buttonRect.width / 2 - tooltipWidth / 2;
const tooltipY = buttonRect.top + window.scrollY - tooltipHeight - 10;
// Position the tooltip and make it visible
tooltip.style.left = tooltipX + "px";
tooltip.style.top = tooltipY + "px";
tooltip.style.display = "block";
});
twentyFourHoursCompare.addEventListener("mouseout", () => {
tooltip.style.display = "none";
});