]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/commitdiff
Change integer to decimals
authorIsmaël Bouya <ismael.bouya@normalesup.org>
Sat, 20 Jan 2018 12:44:30 +0000 (13:44 +0100)
committerIsmaël Bouya <ismael.bouya@normalesup.org>
Sat, 20 Jan 2018 13:15:53 +0000 (14:15 +0100)
market.py
portfolio.py
test.py

index a34636eab42aeefcb8e62311e33840a2ae4dee4b..63eff5a87ea089c6043964a72e7af1257422ebe9 100644 (file)
--- a/market.py
+++ b/market.py
@@ -1,5 +1,56 @@
 import ccxt
+import decimal
 
+def exchange_sum(self, *args):
+    return sum([arg for arg in args if isinstance(arg, (float, int, decimal.Decimal))])
+ccxt.Exchange.sum = exchange_sum
+def poloniex_fetch_balance(self, params={}):
+    self.load_markets()
+    balances = self.privatePostReturnCompleteBalances(self.extend({
+        'account': 'all',
+        }, params))
+    result = {'info': balances}
+    currencies = list(balances.keys())
+    for c in range(0, len(currencies)):
+        id = currencies[c]
+        balance = balances[id]
+        currency = self.common_currency_code(id)
+        account = {
+                'free': decimal.Decimal(balance['available']),
+                'used': decimal.Decimal(balance['onOrders']),
+                'total': decimal.Decimal(0.0),
+                }
+        account['total'] = self.sum(account['free'], account['used'])
+        result[currency] = account
+    return self.parse_balance(result)
+ccxt.poloniex.fetch_balance = poloniex_fetch_balance
+
+def poloniex_parse_ticker(self, ticker, market=None):
+    timestamp = self.milliseconds()
+    symbol = None
+    if market:
+        symbol = market['symbol']
+    return {
+        'symbol': symbol,
+        'timestamp': timestamp,
+        'datetime': self.iso8601(timestamp),
+        'high': decimal.Decimal(ticker['high24hr']),
+        'low': decimal.Decimal(ticker['low24hr']),
+        'bid': decimal.Decimal(ticker['highestBid']),
+        'ask': decimal.Decimal(ticker['lowestAsk']),
+        'vwap': None,
+        'open': None,
+        'close': None,
+        'first': None,
+        'last': decimal.Decimal(ticker['last']),
+        'change': decimal.Decimal(ticker['percentChange']),
+        'percentage': None,
+        'average': None,
+        'baseVolume': decimal.Decimal(ticker['quoteVolume']),
+        'quoteVolume': decimal.Decimal(ticker['baseVolume']),
+        'info': ticker,
+    }
+ccxt.poloniex.parse_ticker = poloniex_parse_ticker
 market = ccxt.poloniex({
     "apiKey": "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX",
     "secret": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
index b0f9256e5222ee75a3e43c09ad5b7f5d8fe2c720..e1ee1f8671c4bc9d479b15e01f5e2f14572d7804 100644 (file)
@@ -1,5 +1,6 @@
 import ccxt
 import time
+from decimal import Decimal as D
 # Put your poloniex api key in market.py
 from market import market
 
@@ -37,7 +38,9 @@ class Portfolio:
         except Exception:
             return
         try:
-            cls.data = json.loads(r.data)
+            cls.data = json.loads(r.data,
+                    parse_int=D,
+                    parse_float=D)
         except json.JSONDecodeError:
             cls.data = None
 
@@ -83,22 +86,15 @@ class Portfolio:
 class Amount:
     MAX_DIGITS = 18
 
-    def __init__(self, currency, value, int_val=None, linked_to=None, ticker=None):
+    def __init__(self, currency, value, linked_to=None, ticker=None):
         self.currency = currency
-        if int_val is None:
-            self._value = int(value * 10**self.MAX_DIGITS)
-        else:
-            self._value = int_val
+        self.value = D(value)
         self.linked_to = linked_to
         self.ticker = ticker
 
         self.ticker_cache = {}
         self.ticker_cache_timestamp = time.time()
 
-    @property
-    def value(self):
-        return self._value / 10 ** self.MAX_DIGITS
-
     def in_currency(self, other_currency, market, action="average"):
         if other_currency == self.currency:
             return self
@@ -106,20 +102,19 @@ class Amount:
         if asset_ticker is not None:
             return Amount(
                     other_currency,
-                    0,
-                    int_val=int(self._value * asset_ticker[action]),
+                    self.value * asset_ticker[action],
                     linked_to=self,
                     ticker=asset_ticker)
         else:
             raise Exception("This asset is not available in the chosen market")
 
     def __abs__(self):
-        return Amount(self.currency, 0, int_val=abs(self._value))
+        return Amount(self.currency, abs(self.value))
 
     def __add__(self, other):
-        if other.currency != self.currency and other._value * self._value != 0:
+        if other.currency != self.currency and other.value * self.value != 0:
             raise Exception("Summing amounts must be done with same currencies")
-        return Amount(self.currency, 0, int_val=self._value + other._value)
+        return Amount(self.currency, self.value + other.value)
 
     def __radd__(self, other):
         if other == 0:
@@ -128,25 +123,22 @@ class Amount:
             return self.__add__(other)
 
     def __sub__(self, other):
-        if other.currency != self.currency and other._value * self._value != 0:
+        if other.currency != self.currency and other.value * self.value != 0:
             raise Exception("Summing amounts must be done with same currencies")
-        return Amount(self.currency, 0, int_val=self._value - other._value)
-
-    def __int__(self):
-        return self._value
+        return Amount(self.currency, self.value - other.value)
 
     def __mul__(self, value):
-        if type(value) != int and type(value) != float:
+        if type(value) != int and type(value) != float and type(value) != D:
             raise TypeError("Amount may only be multiplied by numbers")
-        return Amount(self.currency, 0, int_val=(self._value * value))
+        return Amount(self.currency, self.value * value)
 
     def __rmul__(self, value):
         return self.__mul__(value)
 
     def __floordiv__(self, value):
-        if type(value) != int:
+        if type(value) != int and type(value) != float and type(value) != D:
             raise TypeError("Amount may only be multiplied by integers")
-        return Amount(self.currency, 0, int_val=(self._value // value))
+        return Amount(self.currency, self.value / value)
 
     def __truediv__(self, value):
         return self.__floordiv__(value)
@@ -154,14 +146,14 @@ class Amount:
     def __lt__(self, other):
         if self.currency != other.currency:
             raise Exception("Comparing amounts must be done with same currencies")
-        return self._value < other._value
+        return self.value < other.value
 
     def __eq__(self, other):
         if other == 0:
-            return self._value == 0
+            return self.value == 0
         if self.currency != other.currency:
             raise Exception("Comparing amounts must be done with same currencies")
-        return self._value == other._value
+        return self.value == other.value
 
     def __str__(self):
         if self.linked_to is None:
@@ -266,7 +258,7 @@ class Trade:
         def invert(ticker):
             return {
                     "inverted": True,
-                    "average": (float(1/ticker["bid"]) + float(1/ticker["ask"]) ) / 2,
+                    "average": (1/ticker["bid"] + 1/ticker["ask"]) / 2,
                     "original": ticker,
                     }
         def augment_ticker(ticker):
@@ -416,6 +408,8 @@ class Order:
 
 def print_orders(market, base_currency="BTC"):
     Balance.prepare_trades(market, base_currency=base_currency)
+    for currency, balance in Balance.known_balances.items():
+        print(balance)
     for currency, trade in Trade.trades.items():
         print(trade)
         for order in trade.orders:
diff --git a/test.py b/test.py
index 76080619a47a3580d736ca80ff7c604e03069189..fde3a0684808c9afc2bf2dd05fa2ddb1b8a9aa96 100644 (file)
--- a/test.py
+++ b/test.py
@@ -1,16 +1,14 @@
 import portfolio
 import unittest
+from decimal import Decimal as D
 from unittest import mock
 
 class AmountTest(unittest.TestCase):
     def test_values(self):
-        amount = portfolio.Amount("BTC", 0.65)
-        self.assertEqual(0.65, amount.value)
+        amount = portfolio.Amount("BTC", "0.65")
+        self.assertEqual(D("0.65"), amount.value)
         self.assertEqual("BTC", amount.currency)
 
-        amount = portfolio.Amount("BTC", 10, int_val=2000000000000000)
-        self.assertEqual(0.002, amount.value)
-
     def test_in_currency(self):
         amount = portfolio.Amount("ETC", 10)
 
@@ -24,12 +22,12 @@ class AmountTest(unittest.TestCase):
 
         with mock.patch.object(portfolio.Trade, 'get_ticker', new=ticker_mock):
             ticker_mock.return_value = {
-                    "average": 0.3,
+                    "average": D("0.3"),
                     "foo": "bar",
                     }
             converted_amount = amount.in_currency("ETH", None)
 
-            self.assertEqual(3.0, converted_amount.value)
+            self.assertEqual(D("3.0"), converted_amount.value)
             self.assertEqual("ETH", converted_amount.currency)
             self.assertEqual(amount, converted_amount.linked_to)
             self.assertEqual("bar", converted_amount.ticker["foo"])
@@ -44,13 +42,13 @@ class AmountTest(unittest.TestCase):
         self.assertEqual("SC", abs(amount).currency)
 
     def test__add(self):
-        amount1 = portfolio.Amount("XVG", 12.9)
-        amount2 = portfolio.Amount("XVG", 13.1)
+        amount1 = portfolio.Amount("XVG", "12.9")
+        amount2 = portfolio.Amount("XVG", "13.1")
 
         self.assertEqual(26, (amount1 + amount2).value)
         self.assertEqual("XVG", (amount1 + amount2).currency)
 
-        amount3 = portfolio.Amount("ETH", 1.6)
+        amount3 = portfolio.Amount("ETH", "1.6")
         with self.assertRaises(Exception):
             amount1 + amount3
 
@@ -58,35 +56,31 @@ class AmountTest(unittest.TestCase):
         self.assertEqual(amount1, amount1 + amount4)
 
     def test__radd(self):
-        amount = portfolio.Amount("XVG", 12.9)
+        amount = portfolio.Amount("XVG", "12.9")
 
         self.assertEqual(amount, 0 + amount)
         with self.assertRaises(Exception):
             4 + amount
 
     def test__sub(self):
-        amount1 = portfolio.Amount("XVG", 13.3)
-        amount2 = portfolio.Amount("XVG", 13.1)
+        amount1 = portfolio.Amount("XVG", "13.3")
+        amount2 = portfolio.Amount("XVG", "13.1")
 
-        self.assertEqual(0.2, (amount1 - amount2).value)
+        self.assertEqual(D("0.2"), (amount1 - amount2).value)
         self.assertEqual("XVG", (amount1 - amount2).currency)
 
-        amount3 = portfolio.Amount("ETH", 1.6)
+        amount3 = portfolio.Amount("ETH", "1.6")
         with self.assertRaises(Exception):
             amount1 - amount3
 
         amount4 = portfolio.Amount("ETH", 0.0)
         self.assertEqual(amount1, amount1 - amount4)
 
-    def test__int(self):
-        amount = portfolio.Amount("XMR", 0.1)
-        self.assertEqual(100000000000000000, int(amount))
-
     def test__mul(self):
         amount = portfolio.Amount("XEM", 11)
 
-        self.assertEqual(38.5, (amount * 3.5).value)
-        self.assertEqual(33, (amount * 3).value)
+        self.assertEqual(D("38.5"), (amount * D("3.5")).value)
+        self.assertEqual(D("33"), (amount * 3).value)
 
         with self.assertRaises(Exception):
             amount * amount
@@ -94,24 +88,20 @@ class AmountTest(unittest.TestCase):
     def test__rmul(self):
         amount = portfolio.Amount("XEM", 11)
 
-        self.assertEqual(38.5, (3.5 * amount).value)
-        self.assertEqual(33, (3 * amount).value)
+        self.assertEqual(D("38.5"), (D("3.5") * amount).value)
+        self.assertEqual(D("33"), (3 * amount).value)
 
     def test__floordiv(self):
         amount = portfolio.Amount("XEM", 11)
 
-        self.assertEqual(5.5, (amount // 2).value)
-        with self.assertRaises(TypeError):
-            amount // 2.5
-        self.assertEqual(1571428571428571428, (amount // 7)._value)
+        self.assertEqual(D("5.5"), (amount / 2).value)
+        self.assertEqual(D("4.4"), (amount / D("2.5")).value)
 
     def test__div(self):
         amount = portfolio.Amount("XEM", 11)
 
-        with self.assertRaises(TypeError):
-            amount / 2.5
-        self.assertEqual(5.5, (amount / 2).value)
-        self.assertEqual(1571428571428571428, (amount / 7)._value)
+        self.assertEqual(D("5.5"), (amount / 2).value)
+        self.assertEqual(D("4.4"), (amount / D("2.5")).value)
 
     def test__lt(self):
         amount1 = portfolio.Amount("BTD", 11.3)
@@ -290,32 +280,32 @@ class BalanceTest(unittest.TestCase):
     @mock.patch.object(portfolio.Trade, "get_ticker")
     def test_in_currency(self, get_ticker):
         portfolio.Balance.known_balances = {
-                "BTC": portfolio.Balance("BTC", 0.65, 0.35, 0.30),
+                "BTC": portfolio.Balance("BTC", "0.65", "0.35", "0.30"),
                 "ETH": portfolio.Balance("ETH", 3, 3, 0),
                 }
         market = mock.Mock()
         get_ticker.return_value = {
-                "bid": 0.09,
-                "ask": 0.11,
-                "average": 0.1,
+                "bid": D("0.09"),
+                "ask": D("0.11"),
+                "average": D("0.1"),
                 }
 
         amounts = portfolio.Balance.in_currency("BTC", market)
         self.assertEqual("BTC", amounts["ETH"].currency)
-        self.assertEqual(0.65, amounts["BTC"].value)
-        self.assertEqual(0.30, amounts["ETH"].value)
+        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")
-        self.assertEqual(0.65, amounts["BTC"].value)
-        self.assertEqual(0.27, amounts["ETH"].value)
+        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")
-        self.assertEqual(0.30, amounts["BTC"].value)
+        self.assertEqual(D("0.30"), amounts["BTC"].value)
         self.assertEqual(0, amounts["ETH"].value)
 
     def test_currencies(self):
         portfolio.Balance.known_balances = {
-                "BTC": portfolio.Balance("BTC", 0.65, 0.35, 0.30),
+                "BTC": portfolio.Balance("BTC", "0.65", "0.35", "0.30"),
                 "ETH": portfolio.Balance("ETH", 3, 3, 0),
                 }
         self.assertListEqual(["BTC", "ETH"], list(portfolio.Balance.currencies()))
@@ -341,10 +331,10 @@ class BalanceTest(unittest.TestCase):
                 "BTC": 2600,
                 }
 
-        amounts = portfolio.Balance.dispatch_assets(portfolio.Amount("BTC", 10.1))
+        amounts = portfolio.Balance.dispatch_assets(portfolio.Amount("BTC", "10.1"))
         self.assertIn("XEM", portfolio.Balance.currencies())
-        self.assertEqual(2.6, amounts["BTC"].value)
-        self.assertEqual(7.5, amounts["XEM"].value)
+        self.assertEqual(D("2.6"), amounts["BTC"].value)
+        self.assertEqual(D("7.5"), amounts["XEM"].value)
 
     @mock.patch.object(portfolio.Portfolio, "repartition_pertenthousand")
     @mock.patch.object(portfolio.Trade, "get_ticker")
@@ -355,20 +345,20 @@ class BalanceTest(unittest.TestCase):
                 "BTC": 2500,
                 }
         get_ticker.side_effect = [
-                { "average": 0.0001 },
-                { "average": 0.000001 }
+                { "average": D("0.0001") },
+                { "average": D("0.000001") }
                 ]
         market = mock.Mock()
         market.fetch_balance.return_value = {
                 "USDT": {
-                    "free": 10000.0,
-                    "used": 0.0,
-                    "total": 10000.0
+                    "free": D("10000.0"),
+                    "used": D("0.0"),
+                    "total": D("10000.0")
                     },
                 "XVG": {
-                    "free": 10000.0,
-                    "used": 0.0,
-                    "total": 10000.0
+                    "free": D("10000.0"),
+                    "used": D("0.0"),
+                    "total": D("10000.0")
                     },
                 }
         portfolio.Balance.prepare_trades(market)
@@ -377,9 +367,9 @@ class BalanceTest(unittest.TestCase):
         call = compute_trades.call_args
         self.assertEqual(market, call[1]["market"])
         self.assertEqual(1, call[0][0]["USDT"].value)
-        self.assertEqual(0.01, call[0][0]["XVG"].value)
-        self.assertEqual(0.2525, call[0][1]["BTC"].value)
-        self.assertEqual(0.7575, call[0][1]["XEM"].value)
+        self.assertEqual(D("0.01"), call[0][0]["XVG"].value)
+        self.assertEqual(D("0.2525"), call[0][1]["BTC"].value)
+        self.assertEqual(D("0.7575"), call[0][1]["XEM"].value)
 
     def test__repr(self):
         balance = portfolio.Balance("BTX", 3, 1, 2)