Class: CoinTools::CoinCap

Inherits:
Object
  • Object
show all
Defined in:
lib/cointools/coincap.rb

Defined Under Namespace

Classes: BadRequestException, DataPoint, InvalidDateException, InvalidResponseException

Constant Summary collapse

BASE_URL =
"https://coincap.io"
USER_AGENT =
"cointools/#{CoinTools::VERSION}"
PERIODS =
[1, 7, 30, 90, 180, 365]

Instance Method Summary collapse

Instance Method Details

#get_current_price(symbol) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/cointools/coincap.rb', line 65

def get_current_price(symbol)
  url = URI("#{BASE_URL}/page/#{symbol.upcase}")

  response = make_request(url)

  case response
  when Net::HTTPSuccess
    json = JSON.load(response.body)

    usd_price = json['price_usd']
    eur_price = json['price_eur']
    btc_price = json['price_btc']

    return DataPoint.new(nil, usd_price, eur_price, btc_price)
  when Net::HTTPBadRequest
    raise BadRequestException.new(response)
  else
    raise InvalidResponseException.new(response)
  end
end

#get_price(symbol, time = nil) ⇒ Object



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
61
62
63
# File 'lib/cointools/coincap.rb', line 31

def get_price(symbol, time = nil)
  return get_current_price(symbol) if time.nil?

  (time <= Time.now) or raise InvalidDateException.new('Future date was passed')
  (time.year >= 2009) or raise InvalidDateException.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

  unixtime = time.to_i

  response = make_request(url)

  case response
  when Net::HTTPSuccess
    json = JSON.load(response.body)
    data = json['price']

    timestamp, price = best_matching_record(data, unixtime)
    actual_time = Time.at(timestamp / 1000)

    return DataPoint.new(actual_time, price, nil, nil)
  when Net::HTTPBadRequest
    raise BadRequestException.new(response)
  else
    raise InvalidResponseException.new(response)
  end
end