| 1 | import log |
| 2 | import term |
| 3 | import time |
| 4 | import x.json2 |
| 5 | import net.http |
| 6 | |
| 7 | const url = 'https://api.coinbase.com/v2/prices/BTC-USD/spot' |
| 8 | |
| 9 | struct JsonResult { |
| 10 | mut: |
| 11 | data PriceResult |
| 12 | } |
| 13 | |
| 14 | struct PriceResult { |
| 15 | mut: |
| 16 | amount f64 |
| 17 | base string |
| 18 | currency string |
| 19 | } |
| 20 | |
| 21 | fn 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 | |
| 44 | fn 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 | |