]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/commitdiff
Fix price imprecision due to floats
authorIsmaël Bouya <ismael.bouya@normalesup.org>
Mon, 30 Apr 2018 12:21:41 +0000 (14:21 +0200)
committerIsmaël Bouya <ismael.bouya@normalesup.org>
Mon, 30 Apr 2018 12:21:41 +0000 (14:21 +0200)
ccxt_wrapper.py
main.py
tests/test_ccxt_wrapper.py
tests/test_main.py

index d2c9b4ce26550b0074f6632ddc2bdc972eb17bd2..f30c7d20fd6434e2ae36a22e11676ba27da5235b 100644 (file)
@@ -232,39 +232,9 @@ class poloniexE(poloniex):
 
         return all_balances
 
-    def create_exchange_order(self, symbol, type, side, amount, price=None, params={}):
-        return super().create_order(symbol, type, side, amount, price=price, params=params)
-
-    def create_margin_order(self, symbol, type, side, amount, price=None, lending_rate=None, params={}):
-        if type == 'market':
-            raise ExchangeError(self.id + ' allows limit orders only')
-        self.load_markets()
-        method = 'privatePostMargin' + self.capitalize(side)
-        market = self.market(symbol)
-        price = float(price)
-        amount = float(amount)
-        if lending_rate is not None:
-            params = self.extend({"lendingRate": lending_rate}, params)
-        response = getattr(self, method)(self.extend({
-            'currencyPair': market['id'],
-            'rate': self.price_to_precision(symbol, price),
-            'amount': self.amount_to_precision(symbol, amount),
-        }, params))
-        timestamp = self.milliseconds()
-        order = self.parse_order(self.extend({
-            'timestamp': timestamp,
-            'status': 'open',
-            'type': type,
-            'side': side,
-            'price': price,
-            'amount': amount,
-        }, response), market)
-        id = order['id']
-        self.orders[id] = order
-        return self.extend({'info': response}, order)
-
     def order_precision(self, symbol):
-        return 8
+        self.load_markets()
+        return self.markets[symbol]['precision']['price']
 
     def transfer_balance(self, currency, amount, from_account, to_account):
         result = self.privatePostTransferBalance({
@@ -382,14 +352,49 @@ class poloniexE(poloniex):
 
     def create_order(self, symbol, type, side, amount, price=None, account="exchange", lending_rate=None, params={}):
         """
-        Wrapped to handle margin and exchange accounts
+        Wrapped to handle margin and exchange accounts, and get decimals
         """
+        if type == 'market':
+            raise ExchangeError(self.id + ' allows limit orders only')
+        self.load_markets()
         if account == "exchange":
-            return self.create_exchange_order(symbol, type, side, amount, price=price, params=params)
+            method = 'privatePost' + self.capitalize(side)
         elif account == "margin":
-            return self.create_margin_order(symbol, type, side, amount, price=price, lending_rate=lending_rate, params=params)
+            method = 'privatePostMargin' + self.capitalize(side)
+            if lending_rate is not None:
+                params = self.extend({"lendingRate": lending_rate}, params)
         else:
             raise NotImplementedError
+        market = self.market(symbol)
+        response = getattr(self, method)(self.extend({
+            'currencyPair': market['id'],
+            'rate': self.price_to_precision(symbol, price),
+            'amount': self.amount_to_precision(symbol, amount),
+        }, params))
+        timestamp = self.milliseconds()
+        order = self.parse_order(self.extend({
+            'timestamp': timestamp,
+            'status': 'open',
+            'type': type,
+            'side': side,
+            'price': price,
+            'amount': amount,
+        }, response), market)
+        id = order['id']
+        self.orders[id] = order
+        return self.extend({'info': response}, order)
+
+    def price_to_precision(self, symbol, price):
+        """
+        Wrapped to avoid float
+        """
+        return ('{:.' + str(self.markets[symbol]['precision']['price']) + 'f}').format(price).rstrip("0").rstrip(".")
+
+    def amount_to_precision(self, symbol, amount):
+        """
+        Wrapped to avoid float
+        """
+        return ('{:.' + str(self.markets[symbol]['precision']['amount']) + 'f}').format(amount).rstrip("0").rstrip(".")
 
     def common_currency_code(self, currency):
         """
diff --git a/main.py b/main.py
index 13c22409188a34bd10138b308d766287ada0671b..a4612075e53cae929e4b5906b61d8a630345ac85 100644 (file)
--- a/main.py
+++ b/main.py
@@ -63,7 +63,7 @@ def get_user_market(config_path, user_id, debug=False):
     if debug:
         args.append("--debug")
     args = parse_args(args)
-    pg_config = parse_config(args)
+    pg_config, redis_config = parse_config(args)
     market_id, market_config, user_id = list(fetch_markets(pg_config, str(user_id)))[0]
     return market.Market.from_config(market_config, args,
             pg_config=pg_config, market_id=market_id,
index 10e334daee0d102aa3997d46201da8c6ee9cc40d..9ddfbc12963b80f386444432549d4ecb09ca7d43 100644 (file)
@@ -110,7 +110,23 @@ class poloniexETest(unittest.TestCase):
                     retry_call.assert_not_called()
 
     def test_order_precision(self):
-        self.assertEqual(8, self.s.order_precision("FOO"))
+        self.s.markets = {
+                "FOO": {
+                    "precision": {
+                        "price": 5,
+                        "amount": 6,
+                        }
+                    },
+                "BAR": {
+                    "precision": {
+                        "price": 7,
+                        "amount": 8,
+                        }
+                    }
+                }
+        with mock.patch.object(self.s, "load_markets") as load_markets:
+            self.assertEqual(5, self.s.order_precision("FOO"))
+            load_markets.assert_called_once()
 
     def test_transfer_balance(self):
         with self.subTest(success=True),\
@@ -167,33 +183,6 @@ class poloniexETest(unittest.TestCase):
                     }
             self.assertEqual(expected, self.s.margin_summary())
 
-    def test_create_order(self):
-        with mock.patch.object(self.s, "create_exchange_order") as exchange,\
-                mock.patch.object(self.s, "create_margin_order") as margin:
-            with self.subTest(account="unspecified"):
-                self.s.create_order("symbol", "type", "side", "amount", price="price", lending_rate="lending_rate", params="params")
-                exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
-                margin.assert_not_called()
-                exchange.reset_mock()
-                margin.reset_mock()
-
-            with self.subTest(account="exchange"):
-                self.s.create_order("symbol", "type", "side", "amount", account="exchange", price="price", lending_rate="lending_rate", params="params")
-                exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
-                margin.assert_not_called()
-                exchange.reset_mock()
-                margin.reset_mock()
-
-            with self.subTest(account="margin"):
-                self.s.create_order("symbol", "type", "side", "amount", account="margin", price="price", lending_rate="lending_rate", params="params")
-                margin.assert_called_once_with("symbol", "type", "side", "amount", lending_rate="lending_rate", price="price", params="params")
-                exchange.assert_not_called()
-                exchange.reset_mock()
-                margin.reset_mock()
-
-            with self.subTest(account="unknown"), self.assertRaises(NotImplementedError):
-                self.s.create_order("symbol", "type", "side", "amount", account="unknown")
-
     def test_parse_ticker(self):
         ticker = {
                 "high24hr": "12",
@@ -439,11 +428,13 @@ class poloniexETest(unittest.TestCase):
             self.assertEqual(expected_doge, result["DOGE"])
             self.assertEqual(expected_btc, result["BTC"])
 
-    def test_create_margin_order(self):
-        with self.assertRaises(market.ExchangeError):
-            self.s.create_margin_order("FOO", "market", "buy", "10")
+    def test_create_order(self):
+        with self.subTest(type="market"),\
+                self.assertRaises(market.ExchangeError):
+            self.s.create_order("FOO", "market", "buy", "10")
 
-        with mock.patch.object(self.s, "load_markets") as load_markets,\
+        with self.subTest(type="limit", account="margin"),\
+                mock.patch.object(self.s, "load_markets") as load_markets,\
                 mock.patch.object(self.s, "privatePostMarginBuy") as margin_buy,\
                 mock.patch.object(self.s, "privatePostMarginSell") as margin_sell,\
                 mock.patch.object(self.s, "market") as market_mock,\
@@ -460,26 +451,97 @@ class poloniexETest(unittest.TestCase):
             ptp.return_value = D("0.1")
             atp.return_value = D("12")
 
-            order = self.s.create_margin_order("BTC_ETC", "margin", "buy", "12", price="0.1")
+            order = self.s.create_order("BTC_ETC", "limit", "buy", "12",
+                    account="margin", price="0.1")
             self.assertEqual(123, order["id"])
             margin_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")})
             margin_sell.assert_not_called()
             margin_buy.reset_mock()
             margin_sell.reset_mock()
 
-            order = self.s.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate="0.01", price="0.1")
+            order = self.s.create_order("BTC_ETC", "limit", "sell",
+                    "12", account="margin", lending_rate="0.01", price="0.1")
             self.assertEqual(456, order["id"])
             margin_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"})
             margin_buy.assert_not_called()
 
-    def test_create_exchange_order(self):
-        with mock.patch.object(market.ccxt.poloniex, "create_order") as create_order:
-            self.s.create_order("symbol", "type", "side", "amount", price="price", params="params")
+        with self.subTest(type="limit", account="exchange"),\
+                mock.patch.object(self.s, "load_markets") as load_markets,\
+                mock.patch.object(self.s, "privatePostBuy") as exchange_buy,\
+                mock.patch.object(self.s, "privatePostSell") as exchange_sell,\
+                mock.patch.object(self.s, "market") as market_mock,\
+                mock.patch.object(self.s, "price_to_precision") as ptp,\
+                mock.patch.object(self.s, "amount_to_precision") as atp:
 
-            create_order.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
+            exchange_buy.return_value = {
+                    "orderNumber": 123
+                    }
+            exchange_sell.return_value = {
+                    "orderNumber": 456
+                    }
+            market_mock.return_value = { "id": "BTC_ETC", "symbol": "BTC_ETC" }
+            ptp.return_value = D("0.1")
+            atp.return_value = D("12")
+
+            order = self.s.create_order("BTC_ETC", "limit", "buy", "12",
+                    account="exchange", price="0.1")
+            self.assertEqual(123, order["id"])
+            exchange_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")})
+            exchange_sell.assert_not_called()
+            exchange_buy.reset_mock()
+            exchange_sell.reset_mock()
+
+            order = self.s.create_order("BTC_ETC", "limit", "sell",
+                    "12", account="exchange", lending_rate="0.01", price="0.1")
+            self.assertEqual(456, order["id"])
+            exchange_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")})
+            exchange_buy.assert_not_called()
+
+        with self.subTest(account="unknown"), self.assertRaises(NotImplementedError),\
+                mock.patch.object(self.s, "load_markets") as load_markets:
+            self.s.create_order("symbol", "type", "side", "amount", account="unknown")
 
     def test_common_currency_code(self):
         self.assertEqual("FOO", self.s.common_currency_code("FOO"))
 
     def test_currency_id(self):
         self.assertEqual("FOO", self.s.currency_id("FOO"))
+
+    def test_amount_to_precision(self):
+        self.s.markets = {
+                "FOO": {
+                    "precision": {
+                        "price": 5,
+                        "amount": 6,
+                        }
+                    },
+                "BAR": {
+                    "precision": {
+                        "price": 7,
+                        "amount": 8,
+                        }
+                    }
+                }
+        self.assertEqual("0.0001", self.s.amount_to_precision("FOO", D("0.0001")))
+        self.assertEqual("0.0000001", self.s.amount_to_precision("BAR", D("0.0000001")))
+        self.assertEqual("0.000001", self.s.amount_to_precision("FOO", D("0.000001")))
+
+    def test_price_to_precision(self):
+        self.s.markets = {
+                "FOO": {
+                    "precision": {
+                        "price": 5,
+                        "amount": 6,
+                        }
+                    },
+                "BAR": {
+                    "precision": {
+                        "price": 7,
+                        "amount": 8,
+                        }
+                    }
+                }
+        self.assertEqual("0.0001", self.s.price_to_precision("FOO", D("0.0001")))
+        self.assertEqual("0.0000001", self.s.price_to_precision("BAR", D("0.0000001")))
+        self.assertEqual("0", self.s.price_to_precision("FOO", D("0.000001")))
+
index b650870ba59729ab9ff55bd78fbb390009cf8259..55b1382551aa34da39ec9b35fcd8b4bd7e8c7ee5 100644 (file)
@@ -103,7 +103,7 @@ class MainTest(WebMockTestCase):
                 mock.patch("main.parse_config") as main_parse_config:
             with self.subTest(debug=False):
                 main_parse_args.return_value = self.market_args()
-                main_parse_config.return_value = "pg_config"
+                main_parse_config.return_value = ["pg_config", "redis_config"]
                 main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)]
                 m = main.get_user_market("config_path.ini", 1)
 
@@ -114,7 +114,7 @@ class MainTest(WebMockTestCase):
             main_parse_args.reset_mock()
             with self.subTest(debug=True):
                 main_parse_args.return_value = self.market_args(debug=True)
-                main_parse_config.return_value = "pg_config"
+                main_parse_config.return_value = ["pg_config", "redis_config"]
                 main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)]
                 m = main.get_user_market("config_path.ini", 1, debug=True)