Class: CoinTools::Cryptowatch

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

Defined Under Namespace

Classes: BadRequestException, DataPoint, InvalidDateException, InvalidResponseException, NoDataException

Constant Summary collapse

BASE_URL =
"https://api.cryptowat.ch"
USER_AGENT =
"cointools/#{CoinTools::VERSION}"

Instance Method Summary collapse

Instance Method Details

#exchangesObject



32
33
34
# File 'lib/cointools/cryptowatch.rb', line 32

def exchanges
  @exchanges ||= get_exchanges
end

#get_current_price(exchange, market) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/cointools/cryptowatch.rb', line 81

def get_current_price(exchange, market)
  url = URI("#{BASE_URL}/markets/#{exchange}/#{market}/price")

  response = make_request(url)

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

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

#get_markets(exchange) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/cointools/cryptowatch.rb', line 36

def get_markets(exchange)
  url = URI("#{BASE_URL}/markets/#{exchange}")

  response = make_request(url)

  case response
  when Net::HTTPSuccess
    json = JSON.load(response.body)
    return json['result'].select { |m| m['active'] == true }.map { |m| m['pair'] }.sort
  when Net::HTTPBadRequest
    raise BadRequestException.new(response)
  else
    raise InvalidResponseException.new(response)
  end
end

#get_price(exchange, market, time = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/cointools/cryptowatch.rb', line 52

def get_price(exchange, market, time = nil)
  return get_current_price(exchange, market) 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')

  unixtime = time.to_i
  current_time = Time.now.to_i
  url = URI("#{BASE_URL}/markets/#{exchange}/#{market}/ohlc?after=#{unixtime}")

  response = make_request(url)

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

    timestamp, o, h, l, c, volume = best_matching_record(data, unixtime, current_time)
    raise NoDataException.new('No data found for a given time') if timestamp.nil?

    actual_time = Time.at(timestamp)
    return DataPoint.new(o, actual_time)
  when Net::HTTPBadRequest
    raise BadRequestException.new(response)
  else
    raise Exception.new(response)
  end
end