~singpolyma/sgx-jmp

ref: 6ead87605043d167e477aa8d7959d6e4b7af7d03 sgx-jmp/lib/btc_sell_prices.rb -rw-r--r-- 1.3 KiB
6ead8760Christopher Vollick Remove BigDecimal.new 2 years ago
                                                                                
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
# frozen_string_literal: true

require "em-http"
require "em_promise"
require "em-synchrony/em-http" # For aget vs get
require "money/bank/open_exchange_rates_bank"
require "nokogiri"

require_relative "em"

class BTCSellPrices
	def initialize(redis, oxr_app_id)
		@redis = redis
		@oxr = Money::Bank::OpenExchangeRatesBank.new(
			Money::RatesStore::Memory.new
		)
		@oxr.app_id = oxr_app_id
	end

	def cad
		fetch_canadianbitcoins.then do |http|
			canadianbitcoins = Nokogiri::HTML.parse(http.response)

			bitcoin_row = canadianbitcoins.at("#ticker > table > tbody > tr")
			raise "Bitcoin row has moved" unless bitcoin_row.at("td").text == "Bitcoin"

			BigDecimal(
				bitcoin_row.at("td:nth-of-type(3)").text.match(/^\$(\d+\.\d+)/)[1]
			)
		end
	end

	def usd
		EMPromise.all([cad, cad_to_usd]).then { |(a, b)| a * b }
	end

protected

	def fetch_canadianbitcoins
		EM::HttpRequest.new(
			"https://www.canadianbitcoins.com",
			tls: { verify_peer: true }
		).aget
	end

	def cad_to_usd
		@redis.get("cad_to_usd").then do |rate|
			next rate.to_f if rate

			EM.promise_defer {
				# OXR gem is not async, so defer to threadpool
				@oxr.update_rates
				@oxr.get_rate("CAD", "USD")
			}.then do |orate|
				@redis.set("cad_to_usd", orate, ex: 60 * 60).then { orate }
			end
		end
	end
end