forked from HpwClifford/Hackathon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
102 lines (79 loc) · 2.96 KB
/
main.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
class AppInstance {
constructor () {
this.check();
this.checkCount = 0;
this.user = {'buyPrice': undefined, 'sellPrice': undefined};
this.alertedUser = false;
// start continuosly cehcking BTC price
setInterval(this.check.bind(this), 3000);
}
// methods...
check () {
this.checkCount += 1;
fetch("https://api.coinbase.com/v2/prices/spot?currency=USD")
.then((data) => data.json())
.then((data) => {
let price = data.data.amount;
this.update(price);
// Check if price is currently higher than sell price
// (below -> or lower than buy price)
if (price >= this.user.sellPrice && !this.alertedUser) {
alert("SELL NOW!");
this.alertedUser = true;
} else if (price <= this.user.buyPrice && !this.alertedUser) {
alert("BUY NOW!");
this.alertedUser = true;
}
if (this.user.sellPrice > price && price > this.user.buyPrice) {
this.alertedUser = false;
}
});
}
update (price) {
// create new html element to store price
// append to body
const priceInfo = document.getElementById("current-price");
priceInfo.innerHTML = `Current BTC Price: $${price}`;
}
inputError () {
console.log('error!!!');
const errorMessage = document.getElementById("error-message");
errorMessage.style.visibility = "visible";
setTimeout(() => errorMessage.style.visibility = "hidden", 3000);
}
areYouSureError () {
const errorMessage = document.getElementById("are-you-sure");
errorMessage.style.visibility = "visible";
setTimeout(() => errorMessage.style.visibility = "hidden", 3000);
}
}
// program initialization
document.addEventListener("DOMContentLoaded", function() {
// Handler when the DOM is fully loaded
const instance = new AppInstance();
const btn = document.getElementById("submit");
btn.addEventListener("click", () => {
// storing buy / sell values
const buyValue = document.getElementById("buyPrice").value;
const sellValue = document.getElementById("sellPrice").value;
// if inputs valid
if (!isNaN(buyValue)
&& !isNaN(sellValue)
&& Number(buyValue) >= 0
&& Number(sellValue) >= 0) {
if (Number(buyValue) > Number(sellValue)) {
instance.areYouSureError();
return;
}
// input into user obj
instance.user.buyPrice = buyValue;
instance.user.sellPrice = sellValue;
// if inputs invalid
} else {
instance.inputError();
}
// clear inputs
document.getElementById("buyPrice").value = null;
document.getElementById("sellPrice").value = null;
});
});