From 987bd3d3f72e11b8d2b18e5b8fbca44a5d561d05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isma=C3=ABl=20Bouya?= Date: Thu, 11 Jan 2018 23:06:12 +0100 Subject: Cache ticker values --- script.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/script.py b/script.py index 4732533..fe0f0de 100644 --- a/script.py +++ b/script.py @@ -1,5 +1,11 @@ import ccxt +def static_var(varname, value): + def decorate(func): + setattr(func, varname, value) + return func + return decorate + max_digits = 18 current_assets = { "ETH": int(2.00000000 * 10**max_digits), @@ -21,18 +27,27 @@ market = ccxt.poloniex() def formatted_price(value): return round(value / 10**max_digits, 8) +@static_var("cache", {}) def get_ticker(c1, c2, market): + def invert(ticker): + return { + "bid": float(1/ticker["ask"]), + "ask": float(1/ticker["bid"]), + } + + if (c1, c2, market.__class__) in get_ticker.cache: + return get_ticker.cache[(c1, c2, market.__class__)] + if (c2, c1, market.__class__) in get_ticker.cache: + return invert(get_ticker.cache[(c2, c1, market.__class__)]) + try: - return market.fetch_ticker("{}/{}".format(c1, c2)) + get_ticker.cache[(c1, c2, market.__class__)] = market.fetch_ticker("{}/{}".format(c1, c2)) except ccxt.ExchangeError: try: - ticker = market.fetch_ticker("{}/{}".format(c2, c1)) - return { - "bid": float(1/ticker["ask"]), - "ask": float(1/ticker["bid"]), - } + get_ticker.cache[(c2, c1, market.__class__)] = market.fetch_ticker("{}/{}".format(c2, c1)) except ccxt.ExchangeError: - return None + get_ticker.cache[(c1, c2, market.__class__)] = None + return get_ticker(c1, c2, market) def assets_value(assets, market, base_currency="BTC"): repartition_in_base_currency = {} -- cgit v1.2.3