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
60
|
# File 'lib/cointools/coincap.rb', line 17
def get_price(symbol, time = nil)
raise InvalidSymbolError if symbol.to_s.empty?
if time.nil?
return get_current_price(symbol)
elsif time.is_a?(String)
time = Utils.parse_time(time)
end
(time <= Time.now) or raise InvalidDateError.new('Future date was passed')
(time.year >= 2009) or raise InvalidDateError.new('Too early date was passed')
period = period_for_time(time)
if period
url = URI("#{BASE_URL}/history/#{period}day/#{symbol.upcase}")
else
url = URI("#{BASE_URL}/history/#{symbol.upcase}")
end
response = Request.get(url)
case response
when Net::HTTPSuccess
json = Utils.parse_json(response.body)
raise UnknownCoinError.new(response) if json.nil? || json.empty?
raise JSONError.new(response) unless json.is_a?(Hash)
data = json['price']
raise JSONError.new(response) unless data.is_a?(Array)
unixtime = time.to_i
timestamp, price = best_matching_record(data, unixtime)
raise NoDataError.new(response) if timestamp.nil? || price.nil?
actual_time = Time.at(timestamp / 1000)
return DataPoint.new(time: actual_time, usd_price: price, eur_price: nil, btc_price: nil)
when Net::HTTPClientError
raise BadRequestError.new(response)
else
raise ServiceUnavailableError.new(response)
end
end
|