-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriceChecker.js
98 lines (75 loc) · 2.62 KB
/
priceChecker.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
const got = require("got")
/**
*
* Uses Uphold API to detect price swings
*
*/
class PriceCheck {
constructor() {
//the previous price tick to compare with
this.lastTick;
this.requestTimerHandle;
this.url = 'https://api.uphold.com/v0/ticker/';
//bind so we can use "this" context
this.absolutePercentDiff = this.absolutePercentDiff.bind(this);
this.updateDifference = this.updateDifference.bind(this);
this.requestRateInterval = this.requestRateInterval.bind(this);
this.requestRate = this.requestRate.bind(this);
this.getPrice = this.getPrice.bind(this);
}
/**
*
* get the absolute percent difference between two numbers
*
* @param {*} firstNum
* @param {*} secondNum
* @returns
*/
absolutePercentDiff(firstNum, secondNum) {
return ( Math.abs(firstNum - secondNum) / ((firstNum + secondNum) /2) ) * 100
}
/**
* update the last tick and calculate the percent change
*
* @param {*} currentTick
* @param {*} threshold - a percent
*/
updateDifference(currentTick) {
let diff = 0;
if (this.lastTick != undefined) {
let lastPrice = Number(this.lastTick.ask);
let currentPrice = Number(currentTick.ask);
diff = this.absolutePercentDiff(lastPrice, currentPrice);
}
this.lastTick = currentTick;
return diff;
}
/**
*
* @param {*} first first currency
* @param {*} second second currency
* @param {*} threshold % difference in prices from last retreival to send alert
* @param {*} interval how long to wait before retreiving price again
*/
requestRateInterval = function(first, second, threshold, interval) {
if (typeof this.requestTimerHandle != 'undefined') {
clearInterval(this.requestTimerHandle)
}
this.requestTimerHandle = setInterval(this.requestRate, interval, first, second, threshold)
}
async getPrice(url) {
const response = await got(url);
const data = await response.body;
return data;
}
async requestRate(first, second, threshold) {
let currentTickData = await this.getPrice(this.url + first + '-' + second)
let currentTick = JSON.parse(currentTickData);
console.log(first + " is " + currentTick.ask + " " + second);
let diff = this.updateDifference(currentTick);
if (diff >= threshold) {
console.log(first + " changed " + diff + " percent");
}
}
}
module.exports = { PriceCheck : PriceCheck}