v / examples / poll_coindesk_bitcoin_vs_usd_rate.v
58 lines · 53 sloc · 1.07 KB · dea01ffe0318881b897331f26fd1c889b73d175c
Raw
1import log
2import term
3import time
4import x.json2
5import net.http
6
7const url = 'https://api.coinbase.com/v2/prices/BTC-USD/spot'
8
9struct JsonResult {
10mut:
11 data PriceResult
12}
13
14struct PriceResult {
15mut:
16 amount f64
17 base string
18 currency string
19}
20
21fn main() {
22 log.use_stdout()
23 mut old_rate := f64(0)
24 for i := u64(1); true; i++ {
25 data := http.get(url) or {
26 log.error('polling ${url} failed')
27 time.sleep(10 * time.second)
28 continue
29 }
30 if data.status_code == 200 {
31 res := json2.decode[JsonResult](data.body) or {
32 log.error('can not decode data: ${data.body}')
33 time.sleep(10 * time.second)
34 continue
35 }
36 new_rate := res.data.amount
37 show_result(i, res.data, new_rate - old_rate)
38 old_rate = new_rate
39 }
40 time.sleep(3 * time.second)
41 }
42}
43
44fn show_result(i u64, res PriceResult, delta f64) {
45 if delta == 0 {
46 return
47 }
48 mut sdelta := '${delta:10.3f}'
49 color := if delta > 0 {
50 term.green
51 } else if delta == 0 {
52 term.white
53 } else {
54 term.red
55 }
56 cdelta := term.colorize(color, sdelta)
57 log.info('${cdelta}, ${res.amount:10.3f} USD/BTC, cycle: ${i:5}')
58}
59