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 unless bitcoin_row.at("td").text == "Bitcoin"
26 raise "Bitcoin row has moved"
27 end
28
29 BigDecimal(
30 bitcoin_row.at("td:nth-of-type(4)").text.match(/^\$(\d+\.\d+)/)[1]
31 )
32 end
33 end
34
35 def usd
36 EMPromise.all([cad, cad_to_usd]).then { |(a, b)| a * b }
37 end
38
39protected
40
41 def fetch_canadianbitcoins
42 EM::HttpRequest.new(
43 "https://www.canadianbitcoins.com",
44 tls: { verify_peer: true }
45 ).aget
46 end
47
48 def cad_to_usd
49 @redis.get("cad_to_usd").then do |rate|
50 next rate.to_f if rate
51
52 EM.promise_defer {
53 # OXR gem is not async, so defer to threadpool
54 @oxr.update_rates
55 @oxr.get_rate("CAD", "USD")
56 }.then do |orate|
57 @redis.setex("cad_to_usd", 60 * 60, orate).then { orate }
58 end
59 end
60 end
61end