diff options
author | David McMackins II <contact@mcmackins.org> | 2015-09-01 07:08:52 -0500 |
---|---|---|
committer | David McMackins II <contact@mcmackins.org> | 2015-09-01 07:08:52 -0500 |
commit | da5e792d5fe4ae0792e967ac49caf4cdff9b77cf (patch) | |
tree | bd35bee3b08a859b488c845aba9f00cae6b7596e | |
parent | cf89e4e3ec30d58ae96a4432ef61347c01ea4f27 (diff) |
Do some improvements on Ticker internals
-rw-r--r-- | cfetch/__init__.py | 21 | ||||
-rw-r--r-- | cfetch/plugins/bitstamp.py | 6 |
2 files changed, 15 insertions, 12 deletions
diff --git a/cfetch/__init__.py b/cfetch/__init__.py index d7d1876..ab92092 100644 --- a/cfetch/__init__.py +++ b/cfetch/__init__.py @@ -42,8 +42,16 @@ class Ticker(): # @param response Original response from the ticker server. # @param The coin pair as a list/tuple. # @return The data for the selected pair. - def get_pair_data(self, response, pair): - return response.json()[self.get_pair(pair[0], pair[1])] + def get_pair_data(self, response, pair=None): + if type(pair) in (list, tuple): + return response.json()[self.get_pair(pair[0], pair[1])] + else: + raise TypeError('pair cannot be {}'.format(type(pair))) + + def _get_single_rate(self, a, b, amt, power): + r = get(self.path + self.get_pair(a, b)) + res = self.get_pair_data(r, (a, b)) + return (float(res[self.kind]) ** power) * amt ## Calculates the exchange rate between two currencies. # @param a The first currency. @@ -51,16 +59,11 @@ class Ticker(): # @param amt The number quantity of 'a' currency. # @return The exchange rate between 'a' and 'b' currencies. def get_rate(self, a, b, amt=1): - r = get(self.path + self.get_pair(a, b)) - try: - res = self.get_pair_data(r, (a, b)) - return float(res[self.kind]) * amt + return self._get_single_rate(a, b, amt, 1) except (KeyError, TypeError): try: - r = get(self.path + self.get_pair(b, a)) # reverse order - res = self.get_pair_data(r, (b, a)) - return (float(res[self.kind]) ** -1) * amt + return self._get_single_rate(b, a, amt, -1) except (KeyError, TypeError) as e: raise ValueError(str(e)) # currency pair not found diff --git a/cfetch/plugins/bitstamp.py b/cfetch/plugins/bitstamp.py index 85f8f8f..50f81c3 100644 --- a/cfetch/plugins/bitstamp.py +++ b/cfetch/plugins/bitstamp.py @@ -22,17 +22,17 @@ class BitstampTicker(Ticker): def __init__(self, path, kind='vwap'): super().__init__(path, kind) - def get_pair_data(self, response, pair): + def get_pair_data(self, response): return response.json() def get_rate(self, a, b, amt=1): if a == 'btc' and b == 'usd': r = get(self.path) - res = self.get_pair_data(r, (a, b)) + res = self.get_pair_data(r) return float(res[self.kind]) * amt elif a == 'usd' and b == 'btc': r = get(self.path) - res = self.get_pair_data(r, (a, b)) + res = self.get_pair_data(r) return (float(res[self.kind]) ** -1) * amt else: raise ValueError('{}/{}'.format(a, b)) |