]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/commitdiff
Cache ticker values
authorIsmaël Bouya <ismael.bouya@normalesup.org>
Thu, 11 Jan 2018 22:06:12 +0000 (23:06 +0100)
committerIsmaël Bouya <ismael.bouya@normalesup.org>
Thu, 11 Jan 2018 22:06:12 +0000 (23:06 +0100)
script.py

index 473253309441b5da16c5983096f941a05ef20c03..fe0f0ded1e7589c78ec23074c2abf47432b4c971 100644 (file)
--- 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 = {}