-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
113 lines (98 loc) · 3.32 KB
/
app.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
const serve = require('koa-static')
const Koa = require('koa')
const Router = require('@koa/router')
const Binance = require('node-binance-api')
const moment = require('moment')
require('dotenv').config()
const binance = new Binance().options({
APIKEY: process.env.BINANCE_API_KEY,
APISECRET: process.env.BINANCE_SECRET_KEY
})
let lastApiHit = moment()
let lastAssets = []
const updateAssets = async () => {
if (moment().subtract(10, 'seconds') > lastApiHit) {
try {
const balances = await binance.balance()
const ticker = await binance.prices()
const assets = []
Object.entries(balances).filter(
([key, val]) => {
if (val.available > 0 || val.onOrder > 0) {
if (key === 'USDT') {
assets.push({
currency: key,
amount: (parseFloat(val.available) + parseFloat(val.onOrder)).toFixed(8),
rate: '1.00000000',
usd_amount: ((parseFloat(val.available) + parseFloat(val.onOrder))).toFixed(8),
})
} else if (ticker[`${key}USDT`]) {
assets.push({
currency: key,
amount: (parseFloat(val.available) + parseFloat(val.onOrder)).toFixed(8),
rate: (ticker[`${key}USDT`]),
usd_amount: ((parseFloat(val.available) + parseFloat(val.onOrder)) * ticker[`${key}USDT`]).toFixed(8),
})
} else if (ticker[`${key}BUSD`]) {
assets.push({
currency: key,
amount: (parseFloat(val.available) + parseFloat(val.onOrder)).toFixed(8),
rate: (ticker[`${key}BUSD`]),
usd_amount: ((parseFloat(val.available) + parseFloat(val.onOrder)) * ticker[`${key}BUSD`]).toFixed(8),
})
}
}
}
)
const usdSum = assets.map(
item => item.usd_amount
).reduce(
(lhs, rhs) => parseFloat(lhs) + parseFloat(rhs),
0
)
assets.map(asset => {
asset.percentage = ((parseFloat(asset.usd_amount)) / usdSum * 100).toFixed(2)
})
assets.sort((lhs, rhs) => {
if (parseFloat(lhs.usd_amount) > parseFloat(rhs.usd_amount)) {
return -1;
}
if (parseFloat(lhs.usd_amount) < parseFloat(rhs.usd_amount)) {
return 1;
}
return 0;
})
lastAssets = assets
} catch (err) {
console.log(err)
}
lastApiHit = moment()
}
}
/* ======================================================= */
/* Server */
/* ======================================================= */
const app = new Koa()
const router = new Router();
router.prefix('/api')
router.get('/', async (ctx, next) => {
await updateAssets()
ctx.body = lastAssets.map(asset => {