]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/commitdiff
Add compute value lambdas for currency conversion
authorIsmaël Bouya <ismael.bouya@normalesup.org>
Sun, 21 Jan 2018 14:17:48 +0000 (15:17 +0100)
committerIsmaël Bouya <ismael.bouya@normalesup.org>
Sun, 21 Jan 2018 14:37:24 +0000 (15:37 +0100)
portfolio.py
test.py

index 4991dced7d437b63c99ee3b70c6d02d93fbaf98e..5211dd80fb1ffe47d82f9254e43afe8d07961001 100644 (file)
@@ -89,14 +89,14 @@ class Amount:
         self.ticker_cache = {}
         self.ticker_cache_timestamp = time.time()
 
-    def in_currency(self, other_currency, market, action="average"):
+    def in_currency(self, other_currency, market, action=None, compute_value="average"):
         if other_currency == self.currency:
             return self
         asset_ticker = Trade.get_ticker(self.currency, other_currency, market)
         if asset_ticker is not None:
             return Amount(
                     other_currency,
-                    self.value * asset_ticker[action],
+                    self.value * Trade.compute_value(asset_ticker, action, compute_value=compute_value),
                     linked_to=self,
                     ticker=asset_ticker)
         else:
@@ -175,12 +175,12 @@ class Balance:
         return cls(currency, hash_["total"], hash_["free"], hash_["used"])
 
     @classmethod
-    def in_currency(cls, other_currency, market, action="average", type="total"):
+    def in_currency(cls, other_currency, market, compute_value="average", type="total"):
         amounts = {}
         for currency in cls.known_balances:
             balance = cls.known_balances[currency]
             other_currency_amount = getattr(balance, type)\
-                    .in_currency(other_currency, market, action=action)
+                    .in_currency(other_currency, market, compute_value=compute_value)
             amounts[currency] = other_currency_amount
         return amounts
 
@@ -213,16 +213,34 @@ class Balance:
         return amounts
 
     @classmethod
-    def prepare_trades(cls, market, base_currency="BTC"):
+    def prepare_trades(cls, market, base_currency="BTC", compute_value=None):
         cls.fetch_balances(market)
         values_in_base = cls.in_currency(base_currency, market)
         total_base_value = sum(values_in_base.values())
         new_repartition = cls.dispatch_assets(total_base_value)
-        Trade.compute_trades(values_in_base, new_repartition, market=market)
+        # Recompute it in case we have new currencies
+        values_in_base = cls.in_currency(base_currency, market)
+        Trade.compute_trades(values_in_base, new_repartition, market=market, compute_value=compute_value)
 
     def __repr__(self):
         return "Balance({} [{}/{}/{}])".format(self.currency, str(self.free), str(self.used), str(self.total))
 
+class Computation:
+    def average_inverse(ticker, action):
+        if ticker["inverted"]:
+            return 1/ticker["original"]["average"]
+        else:
+            return ticker["average"]
+
+    computations = {
+            "default": lambda x, y: x[y],
+            "average_inverse": average_inverse,
+            "average": lambda x, y: x["average"],
+            "bid": lambda x, y: x["bid"],
+            "ask": lambda x, y: x["ask"],
+            }
+
+
 class Trade:
     trades = {}
 
@@ -282,7 +300,7 @@ class Trade:
         return cls.get_ticker(c1, c2, market)
 
     @classmethod
-    def compute_trades(cls, values_in_base, new_repartition, market=None):
+    def compute_trades(cls, values_in_base, new_repartition, market=None, compute_value=None):
         base_currency = sum(values_in_base.values()).currency
         for currency in Balance.currencies():
             if currency == base_currency:
@@ -293,7 +311,8 @@ class Trade:
                 currency,
                 market=market
                 )
-            cls.trades[currency].prepare_order()
+            if compute_value is not None:
+                cls.trades[currency].prepare_order(compute_value=compute_value)
         return cls.trades
 
     @property
@@ -314,7 +333,7 @@ class Trade:
         else:
             return "bid" if not inverted else "ask"
 
-    def prepare_order(self):
+    def prepare_order(self, compute_value="default"):
         if self.action is None:
             return
         ticker = self.value_from.ticker
@@ -322,7 +341,9 @@ class Trade:
 
         if not inverted:
             value_from = self.value_from.linked_to
-            value_to = self.value_to.in_currency(self.currency, self.market)
+            # The ticker will most probably be inverted, but we want the average
+            # of the initial value
+            value_to = self.value_to.in_currency(self.currency, self.market, compute_value="average_inverse")
             delta = abs(value_to - value_from)
             currency = self.base_currency
         else:
@@ -330,10 +351,16 @@ class Trade:
             delta = abs(self.value_to - self.value_from)
             currency = self.currency
 
-        rate = ticker[self.order_action(inverted)]
+        rate = Trade.compute_value(ticker, self.order_action(inverted), compute_value=compute_value)
 
         self.orders.append(Order(self.order_action(inverted), delta, rate, currency))
 
+    @classmethod
+    def compute_value(cls, ticker, action, compute_value="default"):
+        if type(compute_value) == str:
+            compute_value = Computation.computations[compute_value]
+        return compute_value(ticker, action)
+
     @classmethod
     def all_orders(cls):
         return sum(map(lambda v: v.orders, cls.trades.values()), [])
@@ -401,7 +428,7 @@ class Order:
         return self.status
 
 def print_orders(market, base_currency="BTC"):
-    Balance.prepare_trades(market, base_currency=base_currency)
+    Balance.prepare_trades(market, base_currency=base_currency, compute_value="average")
     for currency, balance in Balance.known_balances.items():
         print(balance)
     for currency, trade in Trade.trades.items():
diff --git a/test.py b/test.py
index fde3a0684808c9afc2bf2dd05fa2ddb1b8a9aa96..a9baadff58ee3dda9cefa9fbd2c2f45bb089ddef 100644 (file)
--- a/test.py
+++ b/test.py
@@ -22,6 +22,8 @@ class AmountTest(unittest.TestCase):
 
         with mock.patch.object(portfolio.Trade, 'get_ticker', new=ticker_mock):
             ticker_mock.return_value = {
+                    "bid": D("0.2"),
+                    "ask": D("0.4"),
                     "average": D("0.3"),
                     "foo": "bar",
                     }
@@ -32,6 +34,12 @@ class AmountTest(unittest.TestCase):
             self.assertEqual(amount, converted_amount.linked_to)
             self.assertEqual("bar", converted_amount.ticker["foo"])
 
+            converted_amount = amount.in_currency("ETH", None, action="bid", compute_value="default")
+            self.assertEqual(D("2"), converted_amount.value)
+
+            converted_amount = amount.in_currency("ETH", None, compute_value="ask")
+            self.assertEqual(D("4"), converted_amount.value)
+
     def test__abs(self):
         amount = portfolio.Amount("SC", -120)
         self.assertEqual(120, abs(amount).value)
@@ -295,11 +303,11 @@ class BalanceTest(unittest.TestCase):
         self.assertEqual(D("0.65"), amounts["BTC"].value)
         self.assertEqual(D("0.30"), amounts["ETH"].value)
 
-        amounts = portfolio.Balance.in_currency("BTC", market, action="bid")
+        amounts = portfolio.Balance.in_currency("BTC", market, compute_value="bid")
         self.assertEqual(D("0.65"), amounts["BTC"].value)
         self.assertEqual(D("0.27"), amounts["ETH"].value)
 
-        amounts = portfolio.Balance.in_currency("BTC", market, action="bid", type="used")
+        amounts = portfolio.Balance.in_currency("BTC", market, compute_value="bid", type="used")
         self.assertEqual(D("0.30"), amounts["BTC"].value)
         self.assertEqual(0, amounts["ETH"].value)
 
@@ -344,10 +352,16 @@ class BalanceTest(unittest.TestCase):
                 "XEM": 7500,
                 "BTC": 2500,
                 }
-        get_ticker.side_effect = [
-                { "average": D("0.0001") },
-                { "average": D("0.000001") }
-                ]
+        def _get_ticker(c1, c2, market):
+            if c1 == "USDT" and c2 == "BTC":
+                return { "average": D("0.0001") }
+            if c1 == "XVG" and c2 == "BTC":
+                return { "average": D("0.000001") }
+            if c1 == "XEM" and c2 == "BTC":
+                return { "average": D("0.001") }
+            raise Exception("Should be called with {}, {}".format(c1, c2))
+        get_ticker.side_effect = _get_ticker
+
         market = mock.Mock()
         market.fetch_balance.return_value = {
                 "USDT": {
@@ -492,6 +506,10 @@ class TradeTest(unittest.TestCase):
     def test_follow_orders(self):
         pass
 
+    @unittest.skip("TODO")
+    def test_compute_value(self):
+        pass
+
     @unittest.skip("TODO")
     def test__repr(self):
         pass