1# frozen_string_literal: true
2
3require "em-http"
4require "em_promise"
5require "em-synchrony/em-http" # For aget vs get
6require "money/bank/open_exchange_rates_bank"
7require "nokogiri"
8
9require_relative "em"
10
11class BTCSellPrices
12 def initialize(redis, oxr_app_id)
13 @redis = redis
14 @oxr = Money::Bank::OpenExchangeRatesBank.new(
15 Money::RatesStore::Memory.new
16 )
17 @oxr.app_id = oxr_app_id
18 end
19
20 def cad
21 fetch_canadianbitcoins.then do |http|
22 canadianbitcoins = Nokogiri::HTML.parse(http.response)
23
24 bitcoin_row = canadianbitcoins.at("#ticker > table > tbody > tr")
25 raise "Bitcoin row has moved" unless bitcoin_row.at("td").text == "Bitcoin"
26
27 BigDecimal.new(
28 bitcoin_row.at("td:nth-of-type(3)").text.match(/^\$(\d+\.\d+)/)[1]
29 )
30 end
31 end
32
33 def usd
34 EMPromise.all([cad, cad_to_usd]).then { |(a, b)| a * b }
35 end
36
37protected
38
39 def fetch_canadianbitcoins
40 EM::HttpRequest.new(
41 "https://www.canadianbitcoins.com",
42 tls: { verify_peer: true }
43 ).aget
44 end
45
46 def cad_to_usd
47 @redis.get("cad_to_usd").then do |rate|
48 next rate.to_f if rate
49
50 EM.promise_defer {
51 # OXR gem is not async, so defer to threadpool
52 oxr.update_rates
53 oxr.get_rate("CAD", "USD")
54 }.then do |orate|
55 @redis.set("cad_to_usd", orate, ex: 60 * 60).then { orate }
56 end
57 end
58 end
59end