]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blobdiff - tests/test_market.py
Don’t raise when some market is disabled
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / tests / test_market.py
index ab3cd5e0aebe83cbacacb822d29b439564ff70d1..93164803b2ed03ff2d7614762eab4249088af3d8 100644 (file)
@@ -174,7 +174,7 @@ class MarketTest(WebMockTestCase):
                     base_currency='BTC', compute_value='average',
                     available_balance_only=False, liquidity='medium',
                     only=None, repartition=None)
-            m.report.log_balances.assert_called_once_with(tag="tag")
+            m.report.log_balances.assert_called_once_with(tag="tag", checkpoint=None)
 
         compute_trades.reset_mock()
         with self.subTest(available_balance_only=True),\
@@ -186,14 +186,17 @@ class MarketTest(WebMockTestCase):
                     return { "average": D("0.000001") }
                 if c1 == "ETH" and c2 == "BTC":
                     return { "average": D("0.1") }
+                if c1 == "FOO" and c2 == "BTC":
+                    return { "average": D("0.1") }
                 self.fail("Should not be called with {}, {}".format(c1, c2))
             get_ticker.side_effect = _get_ticker
 
             repartition.return_value = {
-                    "DOGE": (D("0.25"), "short"),
-                    "BTC": (D("0.25"), "long"),
-                    "ETH": (D("0.25"), "long"),
-                    "XMR": (D("0.25"), "long"),
+                    "DOGE": (D("0.20"), "short"),
+                    "BTC": (D("0.20"), "long"),
+                    "ETH": (D("0.20"), "long"),
+                    "XMR": (D("0.20"), "long"),
+                    "FOO": (D("0.20"), "long"),
                     }
             m = market.Market(self.ccxt, self.market_args())
             self.ccxt.fetch_all_balances.return_value = {
@@ -210,12 +213,12 @@ class MarketTest(WebMockTestCase):
                         "total": D("5.0")
                         },
                     "BTC": {
-                        "exchange_free": D("0.075"),
+                        "exchange_free": D("0.065"),
                         "exchange_used": D("0.02"),
-                        "exchange_total": D("0.095"),
-                        "margin_available": D("0.025"),
+                        "exchange_total": D("0.085"),
+                        "margin_available": D("0.035"),
                         "margin_in_position": D("0.01"),
-                        "margin_total": D("0.035"),
+                        "margin_total": D("0.045"),
                         "total": D("0.13")
                         },
                     "ETH": {
@@ -224,6 +227,12 @@ class MarketTest(WebMockTestCase):
                         "exchange_total": D("1.0"),
                         "total": D("1.0")
                         },
+                    "FOO": {
+                        "exchange_free": D("0.1"),
+                        "exchange_used": D("0.0"),
+                        "exchange_total": D("0.1"),
+                        "total": D("0.1"),
+                        },
                     }
 
             m.balances.fetch_balances(tag="tag")
@@ -236,12 +245,13 @@ class MarketTest(WebMockTestCase):
 
             self.assertEqual(portfolio.Amount("BTC", "-0.025"),
                     new_repartition["DOGE"] - values_in_base["DOGE"])
-            self.assertEqual(portfolio.Amount("BTC", "0.025"),
-                    new_repartition["ETH"] - values_in_base["ETH"])
             self.assertEqual(0,
-                    new_repartition["ZRC"] - values_in_base["ZRC"])
+                    new_repartition["ETH"] - values_in_base["ETH"])
+            self.assertIsNone(new_repartition.get("ZRC"))
             self.assertEqual(portfolio.Amount("BTC", "0.025"),
                     new_repartition["XMR"])
+            self.assertEqual(portfolio.Amount("BTC", "0.015"),
+                    new_repartition["FOO"] - values_in_base["FOO"])
 
         compute_trades.reset_mock()
         with self.subTest(available_balance_only=True, balance=0),\
@@ -381,12 +391,50 @@ class MarketTest(WebMockTestCase):
             order_mock2.trade = trade_mock
 
             trade_mock.tick_actions_recreate.return_value = "tick1"
+            new_order_mock = mock.Mock()
+            trade_mock.prepare_order.return_value = new_order_mock
 
             m.follow_orders()
 
             trade_mock.tick_actions_recreate.assert_called_once_with(2)
             trade_mock.prepare_order.assert_called_once_with(compute_value="tick1")
             m.report.log_error.assert_called_once_with("follow_orders", message=mock.ANY)
+            m.report.log_order.assert_called_with(order_mock2, 2, new_order=new_order_mock)
+            new_order_mock.run.assert_called_once_with()
+
+        with self.subTest("disappearing order no action to do"), \
+                mock.patch("market.ReportStore"):
+            all_orders.reset_mock()
+            m = market.Market(self.ccxt, self.market_args())
+
+            order_mock1 = mock.Mock()
+            order_mock2 = mock.Mock()
+            all_orders.side_effect = [
+                    [order_mock1, order_mock2],
+                    [order_mock1, order_mock2],
+
+                    [order_mock1, order_mock2],
+                    [order_mock1, order_mock2],
+
+                    []
+                    ]
+
+            order_mock1.get_status.side_effect = ["open", "closed"]
+            order_mock2.get_status.side_effect = ["open", "error_disappeared"]
+
+            order_mock1.trade = mock.Mock()
+            trade_mock = mock.Mock()
+            order_mock2.trade = trade_mock
+
+            trade_mock.tick_actions_recreate.return_value = "tick1"
+            trade_mock.prepare_order.return_value = None
+
+            m.follow_orders()
+
+            trade_mock.tick_actions_recreate.assert_called_once_with(2)
+            trade_mock.prepare_order.assert_called_once_with(compute_value="tick1")
+            m.report.log_error.assert_called_once_with("follow_orders", message=mock.ANY)
+            m.report.log_order.assert_called_with(order_mock2, 2, finished=True)
 
     @mock.patch.object(market.BalanceStore, "fetch_balances")
     def test_move_balance(self, fetch_balances):
@@ -835,7 +883,7 @@ class MarketTest(WebMockTestCase):
     @mock.patch("market.ReportStore.log_error")
     @mock.patch("market.Market.store_report")
     def test_process(self, store_report, log_error, process):
-        m = market.Market(self.ccxt, self.market_args())
+        m = market.Market(self.ccxt, self.market_args(), options={"foo": "bar"})
         with self.subTest(actions=[], before=False, after=False):
             m.process([])
 
@@ -849,7 +897,7 @@ class MarketTest(WebMockTestCase):
         with self.subTest(before=True, after=False):
             m.process(["foo"], before=True)
 
-            process.assert_called_once_with("foo", steps="before")
+            process.assert_called_once_with("foo", options={"foo": "bar"}, steps="before")
             store_report.assert_called_once()
             log_error.assert_not_called()
 
@@ -859,7 +907,7 @@ class MarketTest(WebMockTestCase):
         with self.subTest(before=False, after=True):
             m.process(["sell_all"], after=True)
 
-            process.assert_called_once_with("sell_all", steps="after")
+            process.assert_called_once_with("sell_all", options={"foo": "bar"}, steps="after")
             store_report.assert_called_once()
             log_error.assert_not_called()
 
@@ -869,7 +917,7 @@ class MarketTest(WebMockTestCase):
         with self.subTest(before=False, after=False):
             m.process(["foo"])
 
-            process.assert_called_once_with("foo", steps="all")
+            process.assert_called_once_with("foo", options={"foo": "bar"}, steps="all")
             store_report.assert_called_once()
             log_error.assert_not_called()
 
@@ -879,10 +927,21 @@ class MarketTest(WebMockTestCase):
         with self.subTest(before=True, after=True):
             m.process(["sell_all"], before=True, after=True)
 
-            process.assert_called_once_with("sell_all", steps="all")
+            process.assert_called_once_with("sell_all", options={"foo": "bar"}, steps="all")
             store_report.assert_called_once()
             log_error.assert_not_called()
 
+        process.reset_mock()
+        log_error.reset_mock()
+        store_report.reset_mock()
+        with self.subTest(authentication_error=True):
+            m.ccxt.check_required_credentials.side_effect = market.ccxt.AuthenticationError
+
+            m.process(["some_action"], before=True)
+            log_error.assert_called_with("market_authentication", message="Impossible to authenticate to market")
+            store_report.assert_called_once()
+
+        m.ccxt.check_required_credentials.side_effect = True
         process.reset_mock()
         log_error.reset_mock()
         store_report.reset_mock()
@@ -890,7 +949,7 @@ class MarketTest(WebMockTestCase):
             process.side_effect = Exception("bouh")
 
             m.process(["some_action"], before=True)
-            log_error.assert_called_with("market_process", exception=mock.ANY)
+            log_error.assert_called_with("market_process", exception=mock.ANY, message=mock.ANY)
             store_report.assert_called_once()
  
 
@@ -951,7 +1010,7 @@ class ProcessorTest(WebMockTestCase):
         with self.subTest("nominal case"):
             processor = market.Processor(self.m)
 
-            processor.process("sell_all", foo="bar")
+            processor.process("sell_all", options="bar")
             self.assertEqual(3, process_step.call_count)
 
             steps = list(map(lambda x: x[1][1]["name"], process_step.mock_calls))
@@ -959,12 +1018,12 @@ class ProcessorTest(WebMockTestCase):
             kwargs = list(map(lambda x: x[1][2], process_step.mock_calls))
             self.assertEqual(["all_sell", "wait", "all_buy"], steps)
             self.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names)
-            self.assertEqual([{"foo":"bar"}, {"foo":"bar"}, {"foo":"bar"}], kwargs)
+            self.assertEqual(["bar", "bar", "bar"], kwargs)
 
             process_step.reset_mock()
 
             processor.process("sell_needed", steps=["before", "after"])
-            self.assertEqual(3, process_step.call_count)
+            self.assertEqual(4, process_step.call_count)
 
     def test_method_arguments(self):
         ccxt = mock.Mock(spec=market.ccxt.poloniexE)
@@ -974,7 +1033,7 @@ class ProcessorTest(WebMockTestCase):
 
         method, arguments = processor.method_arguments("wait_for_recent")
         self.assertEqual(market.Portfolio.wait_for_recent, method)
-        self.assertEqual(["delta", "poll"], arguments)
+        self.assertEqual(["delta"], arguments)
 
         method, arguments = processor.method_arguments("prepare_trades")
         self.assertEqual(m.prepare_trades, method)
@@ -998,31 +1057,32 @@ class ProcessorTest(WebMockTestCase):
         method, arguments = processor.method_arguments("print_tickers")
         self.assertEqual(m.print_tickers, method)
 
+        method, arguments = processor.method_arguments("fetch_balances")
+        self.assertEqual(m.balances.fetch_balances, method)
+
     def test_process_step(self):
         processor = market.Processor(self.m)
 
         with mock.patch.object(processor, "run_action") as run_action:
-            step = processor.scenarios["sell_needed"][1]
+            step = processor.scenarios["sell_needed"][2]
 
             processor.process_step("foo", step, {"foo":"bar"})
 
             self.m.report.log_stage.assert_has_calls([
-                mock.call("process_foo__1_sell_begin"),
-                mock.call("process_foo__1_sell_end"),
-                ])
-            self.m.balances.fetch_balances.assert_has_calls([
-                mock.call(tag="process_foo__1_sell_begin", log_tickers=True),
-                mock.call(tag="process_foo__1_sell_end", log_tickers=True),
+                mock.call("process_foo__2_sell_begin"),
+                mock.call("process_foo__2_sell_end"),
                 ])
 
-            self.assertEqual(5, run_action.call_count)
+            self.assertEqual(7, run_action.call_count)
 
             run_action.assert_has_calls([
+                mock.call('fetch_balances', {}, {'foo': 'bar', 'tag': 'process_foo__2_sell_begin'}),
                 mock.call('prepare_trades', {}, {'foo': 'bar'}),
                 mock.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}, {'foo': 'bar'}),
                 mock.call('run_orders', {}, {'foo': 'bar'}),
                 mock.call('follow_orders', {}, {'foo': 'bar'}),
                 mock.call('close_trades', {}, {'foo': 'bar'}),
+                mock.call('fetch_balances', {}, {'foo': 'bar', 'tag': 'process_foo__2_sell_end'}),
                 ])
 
         self.m.reset_mock()
@@ -1030,7 +1090,36 @@ class ProcessorTest(WebMockTestCase):
             step = processor.scenarios["sell_needed"][0]
 
             processor.process_step("foo", step, {"foo":"bar"})
-            self.m.balances.fetch_balances.assert_not_called()
+
+            self.m.report.log_stage.assert_has_calls([
+                mock.call("process_foo__0_print_balances_begin"),
+                mock.call("process_foo__0_print_balances_end"),
+                ])
+
+            self.assertEqual(1, run_action.call_count)
+            run_action.assert_has_calls([
+                mock.call('fetch_balances',
+                    {'checkpoint': 'end', 'log_tickers': True, 'add_usdt': True, 'add_portfolio': True},
+                    {'foo': 'bar', 'tag': 'process_foo__0_print_balances_begin'}),
+                ])
+
+        self.m.reset_mock()
+        with mock.patch.object(processor, "run_action") as run_action:
+            step = processor.scenarios["sell_needed"][1]
+
+            processor.process_step("foo", step, {"foo":"bar"})
+            self.assertEqual(1, run_action.call_count)
+
+        self.m.reset_mock()
+        with mock.patch.object(processor, "run_action") as run_action:
+            step = processor.scenarios["print_balances"][0]
+
+            processor.process_step("foo", step, {"foo":"bar"})
+            run_action.assert_has_calls([
+                mock.call('fetch_balances',
+                    {'log_tickers': True, 'add_usdt': True, 'add_portfolio': True},
+                    {'foo': 'bar', 'tag': 'process_foo__1_print_balances_begin'}),
+                ])
 
     def test_parse_args(self):
         processor = market.Processor(self.m)