diff options
Diffstat (limited to 'tests')
-rw-r--r-- | tests/helper.py | 59 | ||||
-rw-r--r-- | tests/test_acceptance.py | 280 | ||||
-rw-r--r-- | tests/test_ccxt_wrapper.py | 477 | ||||
-rw-r--r-- | tests/test_main.py | 290 | ||||
-rw-r--r-- | tests/test_market.py | 900 | ||||
-rw-r--r-- | tests/test_portfolio.py | 2036 | ||||
-rw-r--r-- | tests/test_store.py | 1203 |
7 files changed, 5245 insertions, 0 deletions
diff --git a/tests/helper.py b/tests/helper.py new file mode 100644 index 0000000..4cf1b41 --- /dev/null +++ b/tests/helper.py | |||
@@ -0,0 +1,59 @@ | |||
1 | import sys | ||
2 | import unittest | ||
3 | from decimal import Decimal as D | ||
4 | from unittest import mock | ||
5 | import requests_mock | ||
6 | from io import StringIO | ||
7 | import portfolio, market, main, store | ||
8 | |||
9 | __all__ = ["limits", "unittest", "WebMockTestCase", "mock", "D", | ||
10 | "StringIO"] | ||
11 | |||
12 | limits = ["acceptance", "unit"] | ||
13 | for test_type in limits: | ||
14 | if "--no{}".format(test_type) in sys.argv: | ||
15 | sys.argv.remove("--no{}".format(test_type)) | ||
16 | limits.remove(test_type) | ||
17 | if "--only{}".format(test_type) in sys.argv: | ||
18 | sys.argv.remove("--only{}".format(test_type)) | ||
19 | limits = [test_type] | ||
20 | break | ||
21 | |||
22 | class WebMockTestCase(unittest.TestCase): | ||
23 | import time | ||
24 | |||
25 | def market_args(self, debug=False, quiet=False, report_path=None, **kwargs): | ||
26 | return main.configargparse.Namespace(report_path=report_path, | ||
27 | debug=debug, quiet=quiet, **kwargs) | ||
28 | |||
29 | def setUp(self): | ||
30 | super().setUp() | ||
31 | self.wm = requests_mock.Mocker() | ||
32 | self.wm.start() | ||
33 | |||
34 | # market | ||
35 | self.m = mock.Mock(name="Market", spec=market.Market) | ||
36 | self.m.debug = False | ||
37 | |||
38 | self.patchers = [ | ||
39 | mock.patch.multiple(market.Portfolio, | ||
40 | data=store.LockedVar(None), | ||
41 | liquidities=store.LockedVar({}), | ||
42 | last_date=store.LockedVar(None), | ||
43 | report=mock.Mock(), | ||
44 | worker=None, | ||
45 | worker_notify=None, | ||
46 | worker_started=False, | ||
47 | callback=None), | ||
48 | mock.patch.multiple(portfolio.Computation, | ||
49 | computations=portfolio.Computation.computations), | ||
50 | ] | ||
51 | for patcher in self.patchers: | ||
52 | patcher.start() | ||
53 | |||
54 | def tearDown(self): | ||
55 | for patcher in self.patchers: | ||
56 | patcher.stop() | ||
57 | self.wm.stop() | ||
58 | super().tearDown() | ||
59 | |||
diff --git a/tests/test_acceptance.py b/tests/test_acceptance.py new file mode 100644 index 0000000..184489e --- /dev/null +++ b/tests/test_acceptance.py | |||
@@ -0,0 +1,280 @@ | |||
1 | from .helper import * | ||
2 | |||
3 | @unittest.skipUnless("acceptance" in limits, "Acceptance skipped") | ||
4 | class AcceptanceTest(WebMockTestCase): | ||
5 | @unittest.expectedFailure | ||
6 | def test_success_sell_only_necessary(self): | ||
7 | # FIXME: catch stdout | ||
8 | self.m.report.verbose_print = False | ||
9 | fetch_balance = { | ||
10 | "ETH": { | ||
11 | "exchange_free": D("1.0"), | ||
12 | "exchange_used": D("0.0"), | ||
13 | "exchange_total": D("1.0"), | ||
14 | "total": D("1.0"), | ||
15 | }, | ||
16 | "ETC": { | ||
17 | "exchange_free": D("4.0"), | ||
18 | "exchange_used": D("0.0"), | ||
19 | "exchange_total": D("4.0"), | ||
20 | "total": D("4.0"), | ||
21 | }, | ||
22 | "XVG": { | ||
23 | "exchange_free": D("1000.0"), | ||
24 | "exchange_used": D("0.0"), | ||
25 | "exchange_total": D("1000.0"), | ||
26 | "total": D("1000.0"), | ||
27 | }, | ||
28 | } | ||
29 | repartition = { | ||
30 | "ETH": (D("0.25"), "long"), | ||
31 | "ETC": (D("0.25"), "long"), | ||
32 | "BTC": (D("0.4"), "long"), | ||
33 | "BTD": (D("0.01"), "short"), | ||
34 | "B2X": (D("0.04"), "long"), | ||
35 | "USDT": (D("0.05"), "long"), | ||
36 | } | ||
37 | |||
38 | def fetch_ticker(symbol): | ||
39 | if symbol == "ETH/BTC": | ||
40 | return { | ||
41 | "symbol": "ETH/BTC", | ||
42 | "bid": D("0.14"), | ||
43 | "ask": D("0.16") | ||
44 | } | ||
45 | if symbol == "ETC/BTC": | ||
46 | return { | ||
47 | "symbol": "ETC/BTC", | ||
48 | "bid": D("0.002"), | ||
49 | "ask": D("0.003") | ||
50 | } | ||
51 | if symbol == "XVG/BTC": | ||
52 | return { | ||
53 | "symbol": "XVG/BTC", | ||
54 | "bid": D("0.00003"), | ||
55 | "ask": D("0.00005") | ||
56 | } | ||
57 | if symbol == "BTD/BTC": | ||
58 | return { | ||
59 | "symbol": "BTD/BTC", | ||
60 | "bid": D("0.0008"), | ||
61 | "ask": D("0.0012") | ||
62 | } | ||
63 | if symbol == "B2X/BTC": | ||
64 | return { | ||
65 | "symbol": "B2X/BTC", | ||
66 | "bid": D("0.0008"), | ||
67 | "ask": D("0.0012") | ||
68 | } | ||
69 | if symbol == "USDT/BTC": | ||
70 | raise helper.ExchangeError | ||
71 | if symbol == "BTC/USDT": | ||
72 | return { | ||
73 | "symbol": "BTC/USDT", | ||
74 | "bid": D("14000"), | ||
75 | "ask": D("16000") | ||
76 | } | ||
77 | self.fail("Shouldn't have been called with {}".format(symbol)) | ||
78 | |||
79 | market = mock.Mock() | ||
80 | market.fetch_all_balances.return_value = fetch_balance | ||
81 | market.fetch_ticker.side_effect = fetch_ticker | ||
82 | with mock.patch.object(market.Portfolio, "repartition", return_value=repartition): | ||
83 | # Action 1 | ||
84 | helper.prepare_trades(market) | ||
85 | |||
86 | balances = portfolio.BalanceStore.all | ||
87 | self.assertEqual(portfolio.Amount("ETH", 1), balances["ETH"].total) | ||
88 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | ||
89 | self.assertEqual(portfolio.Amount("XVG", 1000), balances["XVG"].total) | ||
90 | |||
91 | |||
92 | trades = portfolio.TradeStore.all | ||
93 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | ||
94 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | ||
95 | self.assertEqual("dispose", trades[0].action) | ||
96 | |||
97 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) | ||
98 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | ||
99 | self.assertEqual("acquire", trades[1].action) | ||
100 | |||
101 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) | ||
102 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | ||
103 | self.assertEqual("dispose", trades[2].action) | ||
104 | |||
105 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) | ||
106 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | ||
107 | self.assertEqual("acquire", trades[3].action) | ||
108 | |||
109 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) | ||
110 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | ||
111 | self.assertEqual("acquire", trades[4].action) | ||
112 | |||
113 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) | ||
114 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | ||
115 | self.assertEqual("acquire", trades[5].action) | ||
116 | |||
117 | # Action 2 | ||
118 | portfolio.TradeStore.prepare_orders(only="dispose", compute_value=lambda x, y: x["bid"] * D("1.001")) | ||
119 | |||
120 | all_orders = portfolio.TradeStore.all_orders(state="pending") | ||
121 | self.assertEqual(2, len(all_orders)) | ||
122 | self.assertEqual(2, 3*all_orders[0].amount.value) | ||
123 | self.assertEqual(D("0.14014"), all_orders[0].rate) | ||
124 | self.assertEqual(1000, all_orders[1].amount.value) | ||
125 | self.assertEqual(D("0.00003003"), all_orders[1].rate) | ||
126 | |||
127 | |||
128 | def create_order(symbol, type, action, amount, price=None, account="exchange"): | ||
129 | self.assertEqual("limit", type) | ||
130 | if symbol == "ETH/BTC": | ||
131 | self.assertEqual("sell", action) | ||
132 | self.assertEqual(D('0.66666666'), amount) | ||
133 | self.assertEqual(D("0.14014"), price) | ||
134 | elif symbol == "XVG/BTC": | ||
135 | self.assertEqual("sell", action) | ||
136 | self.assertEqual(1000, amount) | ||
137 | self.assertEqual(D("0.00003003"), price) | ||
138 | else: | ||
139 | self.fail("I shouldn't have been called") | ||
140 | |||
141 | return { | ||
142 | "id": symbol, | ||
143 | } | ||
144 | market.create_order.side_effect = create_order | ||
145 | market.order_precision.return_value = 8 | ||
146 | |||
147 | # Action 3 | ||
148 | portfolio.TradeStore.run_orders() | ||
149 | |||
150 | self.assertEqual("open", all_orders[0].status) | ||
151 | self.assertEqual("open", all_orders[1].status) | ||
152 | |||
153 | market.fetch_order.return_value = { "status": "closed", "datetime": "2018-01-20 13:40:00" } | ||
154 | market.privatePostReturnOrderTrades.return_value = [ | ||
155 | { | ||
156 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
157 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
158 | "amount": "10", "total": "1" | ||
159 | } | ||
160 | ] | ||
161 | with mock.patch.object(market.time, "sleep") as sleep: | ||
162 | # Action 4 | ||
163 | helper.follow_orders(verbose=False) | ||
164 | |||
165 | sleep.assert_called_with(30) | ||
166 | |||
167 | for order in all_orders: | ||
168 | self.assertEqual("closed", order.status) | ||
169 | |||
170 | fetch_balance = { | ||
171 | "ETH": { | ||
172 | "exchange_free": D("1.0") / 3, | ||
173 | "exchange_used": D("0.0"), | ||
174 | "exchange_total": D("1.0") / 3, | ||
175 | "margin_total": 0, | ||
176 | "total": D("1.0") / 3, | ||
177 | }, | ||
178 | "BTC": { | ||
179 | "exchange_free": D("0.134"), | ||
180 | "exchange_used": D("0.0"), | ||
181 | "exchange_total": D("0.134"), | ||
182 | "margin_total": 0, | ||
183 | "total": D("0.134"), | ||
184 | }, | ||
185 | "ETC": { | ||
186 | "exchange_free": D("4.0"), | ||
187 | "exchange_used": D("0.0"), | ||
188 | "exchange_total": D("4.0"), | ||
189 | "margin_total": 0, | ||
190 | "total": D("4.0"), | ||
191 | }, | ||
192 | "XVG": { | ||
193 | "exchange_free": D("0.0"), | ||
194 | "exchange_used": D("0.0"), | ||
195 | "exchange_total": D("0.0"), | ||
196 | "margin_total": 0, | ||
197 | "total": D("0.0"), | ||
198 | }, | ||
199 | } | ||
200 | market.fetch_all_balances.return_value = fetch_balance | ||
201 | |||
202 | with mock.patch.object(market.Portfolio, "repartition", return_value=repartition): | ||
203 | # Action 5 | ||
204 | helper.prepare_trades(market, only="acquire", compute_value="average") | ||
205 | |||
206 | balances = portfolio.BalanceStore.all | ||
207 | self.assertEqual(portfolio.Amount("ETH", 1 / D("3")), balances["ETH"].total) | ||
208 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | ||
209 | self.assertEqual(portfolio.Amount("BTC", D("0.134")), balances["BTC"].total) | ||
210 | self.assertEqual(portfolio.Amount("XVG", 0), balances["XVG"].total) | ||
211 | |||
212 | |||
213 | trades = portfolio.TradeStore.all | ||
214 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | ||
215 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | ||
216 | self.assertEqual("dispose", trades[0].action) | ||
217 | |||
218 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) | ||
219 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | ||
220 | self.assertEqual("acquire", trades[1].action) | ||
221 | |||
222 | self.assertNotIn("BTC", trades) | ||
223 | |||
224 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) | ||
225 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | ||
226 | self.assertEqual("dispose", trades[2].action) | ||
227 | |||
228 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) | ||
229 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | ||
230 | self.assertEqual("acquire", trades[3].action) | ||
231 | |||
232 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) | ||
233 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | ||
234 | self.assertEqual("acquire", trades[4].action) | ||
235 | |||
236 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) | ||
237 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | ||
238 | self.assertEqual("acquire", trades[5].action) | ||
239 | |||
240 | # Action 6 | ||
241 | portfolio.TradeStore.prepare_orders(only="acquire", compute_value=lambda x, y: x["ask"]) | ||
242 | |||
243 | all_orders = portfolio.TradeStore.all_orders(state="pending") | ||
244 | self.assertEqual(4, len(all_orders)) | ||
245 | self.assertEqual(portfolio.Amount("ETC", D("12.83333333")), round(all_orders[0].amount)) | ||
246 | self.assertEqual(D("0.003"), all_orders[0].rate) | ||
247 | self.assertEqual("buy", all_orders[0].action) | ||
248 | self.assertEqual("long", all_orders[0].trade_type) | ||
249 | |||
250 | self.assertEqual(portfolio.Amount("BTD", D("1.61666666")), round(all_orders[1].amount)) | ||
251 | self.assertEqual(D("0.0012"), all_orders[1].rate) | ||
252 | self.assertEqual("sell", all_orders[1].action) | ||
253 | self.assertEqual("short", all_orders[1].trade_type) | ||
254 | |||
255 | diff = portfolio.Amount("B2X", D("19.4")/3) - all_orders[2].amount | ||
256 | self.assertAlmostEqual(0, diff.value) | ||
257 | self.assertEqual(D("0.0012"), all_orders[2].rate) | ||
258 | self.assertEqual("buy", all_orders[2].action) | ||
259 | self.assertEqual("long", all_orders[2].trade_type) | ||
260 | |||
261 | self.assertEqual(portfolio.Amount("BTC", D("0.0097")), all_orders[3].amount) | ||
262 | self.assertEqual(D("16000"), all_orders[3].rate) | ||
263 | self.assertEqual("sell", all_orders[3].action) | ||
264 | self.assertEqual("long", all_orders[3].trade_type) | ||
265 | |||
266 | # Action 6b | ||
267 | # TODO: | ||
268 | # Move balances to margin | ||
269 | |||
270 | # Action 7 | ||
271 | # TODO | ||
272 | # portfolio.TradeStore.run_orders() | ||
273 | |||
274 | with mock.patch.object(market.time, "sleep") as sleep: | ||
275 | # Action 8 | ||
276 | helper.follow_orders(verbose=False) | ||
277 | |||
278 | sleep.assert_called_with(30) | ||
279 | |||
280 | |||
diff --git a/tests/test_ccxt_wrapper.py b/tests/test_ccxt_wrapper.py new file mode 100644 index 0000000..d32469a --- /dev/null +++ b/tests/test_ccxt_wrapper.py | |||
@@ -0,0 +1,477 @@ | |||
1 | from .helper import limits, unittest, mock, D | ||
2 | import requests_mock | ||
3 | import market | ||
4 | |||
5 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
6 | class poloniexETest(unittest.TestCase): | ||
7 | def setUp(self): | ||
8 | super().setUp() | ||
9 | self.wm = requests_mock.Mocker() | ||
10 | self.wm.start() | ||
11 | |||
12 | self.s = market.ccxt.poloniexE() | ||
13 | |||
14 | def tearDown(self): | ||
15 | self.wm.stop() | ||
16 | super().tearDown() | ||
17 | |||
18 | def test__init(self): | ||
19 | with self.subTest("Nominal case"), \ | ||
20 | mock.patch("market.ccxt.poloniexE.session") as session: | ||
21 | session.request.return_value = "response" | ||
22 | ccxt = market.ccxt.poloniexE() | ||
23 | ccxt._market = mock.Mock | ||
24 | ccxt._market.report = mock.Mock() | ||
25 | |||
26 | ccxt.session.request("GET", "URL", data="data", | ||
27 | headers="headers") | ||
28 | ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data', | ||
29 | 'headers', 'response') | ||
30 | |||
31 | with self.subTest("Raising"),\ | ||
32 | mock.patch("market.ccxt.poloniexE.session") as session: | ||
33 | session.request.side_effect = market.ccxt.RequestException("Boo") | ||
34 | |||
35 | ccxt = market.ccxt.poloniexE() | ||
36 | ccxt._market = mock.Mock | ||
37 | ccxt._market.report = mock.Mock() | ||
38 | |||
39 | with self.assertRaises(market.ccxt.RequestException, msg="Boo") as cm: | ||
40 | ccxt.session.request("GET", "URL", data="data", | ||
41 | headers="headers") | ||
42 | ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data', | ||
43 | 'headers', cm.exception) | ||
44 | |||
45 | |||
46 | def test_nanoseconds(self): | ||
47 | with mock.patch.object(market.ccxt.time, "time") as time: | ||
48 | time.return_value = 123456.7890123456 | ||
49 | self.assertEqual(123456789012345, self.s.nanoseconds()) | ||
50 | |||
51 | def test_nonce(self): | ||
52 | with mock.patch.object(market.ccxt.time, "time") as time: | ||
53 | time.return_value = 123456.7890123456 | ||
54 | self.assertEqual(123456789012345, self.s.nonce()) | ||
55 | |||
56 | def test_request(self): | ||
57 | with mock.patch.object(market.ccxt.poloniex, "request") as request,\ | ||
58 | mock.patch("market.ccxt.retry_call") as retry_call: | ||
59 | with self.subTest(wrapped=True): | ||
60 | with self.subTest(desc="public"): | ||
61 | self.s.request("foo") | ||
62 | retry_call.assert_called_with(request, | ||
63 | delay=1, tries=10, fargs=["foo"], | ||
64 | fkwargs={'api': 'public', 'method': 'GET', 'params': {}, 'headers': None, 'body': None}, | ||
65 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
66 | request.assert_not_called() | ||
67 | |||
68 | with self.subTest(desc="private GET"): | ||
69 | self.s.request("foo", api="private") | ||
70 | retry_call.assert_called_with(request, | ||
71 | delay=1, tries=10, fargs=["foo"], | ||
72 | fkwargs={'api': 'private', 'method': 'GET', 'params': {}, 'headers': None, 'body': None}, | ||
73 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
74 | request.assert_not_called() | ||
75 | |||
76 | with self.subTest(desc="private POST regexp"): | ||
77 | self.s.request("returnFoo", api="private", method="POST") | ||
78 | retry_call.assert_called_with(request, | ||
79 | delay=1, tries=10, fargs=["returnFoo"], | ||
80 | fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None}, | ||
81 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
82 | request.assert_not_called() | ||
83 | |||
84 | with self.subTest(desc="private POST non-regexp"): | ||
85 | self.s.request("getMarginPosition", api="private", method="POST") | ||
86 | retry_call.assert_called_with(request, | ||
87 | delay=1, tries=10, fargs=["getMarginPosition"], | ||
88 | fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None}, | ||
89 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
90 | request.assert_not_called() | ||
91 | retry_call.reset_mock() | ||
92 | request.reset_mock() | ||
93 | with self.subTest(wrapped=False): | ||
94 | with self.subTest(desc="private POST non-matching regexp"): | ||
95 | self.s.request("marginBuy", api="private", method="POST") | ||
96 | request.assert_called_with("marginBuy", | ||
97 | api="private", method="POST", params={}, | ||
98 | headers=None, body=None) | ||
99 | retry_call.assert_not_called() | ||
100 | |||
101 | with self.subTest(desc="private POST non-matching non-regexp"): | ||
102 | self.s.request("closeMarginPositionOther", api="private", method="POST") | ||
103 | request.assert_called_with("closeMarginPositionOther", | ||
104 | api="private", method="POST", params={}, | ||
105 | headers=None, body=None) | ||
106 | retry_call.assert_not_called() | ||
107 | |||
108 | def test_order_precision(self): | ||
109 | self.assertEqual(8, self.s.order_precision("FOO")) | ||
110 | |||
111 | def test_transfer_balance(self): | ||
112 | with self.subTest(success=True),\ | ||
113 | mock.patch.object(self.s, "privatePostTransferBalance") as t: | ||
114 | t.return_value = { "success": 1 } | ||
115 | result = self.s.transfer_balance("FOO", 12, "exchange", "margin") | ||
116 | t.assert_called_once_with({ | ||
117 | "currency": "FOO", | ||
118 | "amount": 12, | ||
119 | "fromAccount": "exchange", | ||
120 | "toAccount": "margin", | ||
121 | "confirmed": 1 | ||
122 | }) | ||
123 | self.assertTrue(result) | ||
124 | |||
125 | with self.subTest(success=False),\ | ||
126 | mock.patch.object(self.s, "privatePostTransferBalance") as t: | ||
127 | t.return_value = { "success": 0 } | ||
128 | self.assertFalse(self.s.transfer_balance("FOO", 12, "exchange", "margin")) | ||
129 | |||
130 | def test_close_margin_position(self): | ||
131 | with mock.patch.object(self.s, "privatePostCloseMarginPosition") as c: | ||
132 | self.s.close_margin_position("FOO", "BAR") | ||
133 | c.assert_called_with({"currencyPair": "BAR_FOO"}) | ||
134 | |||
135 | def test_tradable_balances(self): | ||
136 | with mock.patch.object(self.s, "privatePostReturnTradableBalances") as r: | ||
137 | r.return_value = { | ||
138 | "FOO": { "exchange": "12.1234", "margin": "0.0123" }, | ||
139 | "BAR": { "exchange": "1", "margin": "0" }, | ||
140 | } | ||
141 | balances = self.s.tradable_balances() | ||
142 | self.assertEqual(["FOO", "BAR"], list(balances.keys())) | ||
143 | self.assertEqual(["exchange", "margin"], list(balances["FOO"].keys())) | ||
144 | self.assertEqual(D("12.1234"), balances["FOO"]["exchange"]) | ||
145 | self.assertEqual(["exchange", "margin"], list(balances["BAR"].keys())) | ||
146 | |||
147 | def test_margin_summary(self): | ||
148 | with mock.patch.object(self.s, "privatePostReturnMarginAccountSummary") as r: | ||
149 | r.return_value = { | ||
150 | "currentMargin": "1.49680968", | ||
151 | "lendingFees": "0.0000001", | ||
152 | "pl": "0.00008254", | ||
153 | "totalBorrowedValue": "0.00673602", | ||
154 | "totalValue": "0.01000000", | ||
155 | "netValue": "0.01008254", | ||
156 | } | ||
157 | expected = { | ||
158 | 'current_margin': D('1.49680968'), | ||
159 | 'gains': D('0.00008254'), | ||
160 | 'lending_fees': D('0.0000001'), | ||
161 | 'total': D('0.01000000'), | ||
162 | 'total_borrowed': D('0.00673602') | ||
163 | } | ||
164 | self.assertEqual(expected, self.s.margin_summary()) | ||
165 | |||
166 | def test_create_order(self): | ||
167 | with mock.patch.object(self.s, "create_exchange_order") as exchange,\ | ||
168 | mock.patch.object(self.s, "create_margin_order") as margin: | ||
169 | with self.subTest(account="unspecified"): | ||
170 | self.s.create_order("symbol", "type", "side", "amount", price="price", lending_rate="lending_rate", params="params") | ||
171 | exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
172 | margin.assert_not_called() | ||
173 | exchange.reset_mock() | ||
174 | margin.reset_mock() | ||
175 | |||
176 | with self.subTest(account="exchange"): | ||
177 | self.s.create_order("symbol", "type", "side", "amount", account="exchange", price="price", lending_rate="lending_rate", params="params") | ||
178 | exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
179 | margin.assert_not_called() | ||
180 | exchange.reset_mock() | ||
181 | margin.reset_mock() | ||
182 | |||
183 | with self.subTest(account="margin"): | ||
184 | self.s.create_order("symbol", "type", "side", "amount", account="margin", price="price", lending_rate="lending_rate", params="params") | ||
185 | margin.assert_called_once_with("symbol", "type", "side", "amount", lending_rate="lending_rate", price="price", params="params") | ||
186 | exchange.assert_not_called() | ||
187 | exchange.reset_mock() | ||
188 | margin.reset_mock() | ||
189 | |||
190 | with self.subTest(account="unknown"), self.assertRaises(NotImplementedError): | ||
191 | self.s.create_order("symbol", "type", "side", "amount", account="unknown") | ||
192 | |||
193 | def test_parse_ticker(self): | ||
194 | ticker = { | ||
195 | "high24hr": "12", | ||
196 | "low24hr": "10", | ||
197 | "highestBid": "10.5", | ||
198 | "lowestAsk": "11.5", | ||
199 | "last": "11", | ||
200 | "percentChange": "0.1", | ||
201 | "quoteVolume": "10", | ||
202 | "baseVolume": "20" | ||
203 | } | ||
204 | market = { | ||
205 | "symbol": "BTC/ETC" | ||
206 | } | ||
207 | with mock.patch.object(self.s, "milliseconds") as ms: | ||
208 | ms.return_value = 1520292715123 | ||
209 | result = self.s.parse_ticker(ticker, market) | ||
210 | |||
211 | expected = { | ||
212 | "symbol": "BTC/ETC", | ||
213 | "timestamp": 1520292715123, | ||
214 | "datetime": "2018-03-05T23:31:55.123Z", | ||
215 | "high": D("12"), | ||
216 | "low": D("10"), | ||
217 | "bid": D("10.5"), | ||
218 | "ask": D("11.5"), | ||
219 | "vwap": None, | ||
220 | "open": None, | ||
221 | "close": None, | ||
222 | "first": None, | ||
223 | "last": D("11"), | ||
224 | "change": D("0.1"), | ||
225 | "percentage": None, | ||
226 | "average": None, | ||
227 | "baseVolume": D("10"), | ||
228 | "quoteVolume": D("20"), | ||
229 | "info": ticker | ||
230 | } | ||
231 | self.assertEqual(expected, result) | ||
232 | |||
233 | def test_fetch_margin_balance(self): | ||
234 | with mock.patch.object(self.s, "privatePostGetMarginPosition") as get_margin_position: | ||
235 | get_margin_position.return_value = { | ||
236 | "BTC_DASH": { | ||
237 | "amount": "-0.1", | ||
238 | "basePrice": "0.06818560", | ||
239 | "lendingFees": "0.00000001", | ||
240 | "liquidationPrice": "0.15107132", | ||
241 | "pl": "-0.00000371", | ||
242 | "total": "0.00681856", | ||
243 | "type": "short" | ||
244 | }, | ||
245 | "BTC_ETC": { | ||
246 | "amount": "-0.6", | ||
247 | "basePrice": "0.1", | ||
248 | "lendingFees": "0.00000001", | ||
249 | "liquidationPrice": "0.6", | ||
250 | "pl": "0.00000371", | ||
251 | "total": "0.06", | ||
252 | "type": "short" | ||
253 | }, | ||
254 | "BTC_ETH": { | ||
255 | "amount": "0", | ||
256 | "basePrice": "0", | ||
257 | "lendingFees": "0", | ||
258 | "liquidationPrice": "-1", | ||
259 | "pl": "0", | ||
260 | "total": "0", | ||
261 | "type": "none" | ||
262 | } | ||
263 | } | ||
264 | balances = self.s.fetch_margin_balance() | ||
265 | self.assertEqual(2, len(balances)) | ||
266 | expected = { | ||
267 | "DASH": { | ||
268 | "amount": D("-0.1"), | ||
269 | "borrowedPrice": D("0.06818560"), | ||
270 | "lendingFees": D("1E-8"), | ||
271 | "pl": D("-0.00000371"), | ||
272 | "liquidationPrice": D("0.15107132"), | ||
273 | "type": "short", | ||
274 | "total": D("0.00681856"), | ||
275 | "baseCurrency": "BTC" | ||
276 | }, | ||
277 | "ETC": { | ||
278 | "amount": D("-0.6"), | ||
279 | "borrowedPrice": D("0.1"), | ||
280 | "lendingFees": D("1E-8"), | ||
281 | "pl": D("0.00000371"), | ||
282 | "liquidationPrice": D("0.6"), | ||
283 | "type": "short", | ||
284 | "total": D("0.06"), | ||
285 | "baseCurrency": "BTC" | ||
286 | } | ||
287 | } | ||
288 | self.assertEqual(expected, balances) | ||
289 | |||
290 | def test_sum(self): | ||
291 | self.assertEqual(D("1.1"), self.s.sum(D("1"), D("0.1"))) | ||
292 | |||
293 | def test_fetch_balance(self): | ||
294 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
295 | mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balances,\ | ||
296 | mock.patch.object(self.s, "common_currency_code") as ccc: | ||
297 | ccc.side_effect = ["ETH", "BTC", "DASH"] | ||
298 | balances.return_value = { | ||
299 | "ETH": { | ||
300 | "available": "10", | ||
301 | "onOrders": "1", | ||
302 | }, | ||
303 | "BTC": { | ||
304 | "available": "1", | ||
305 | "onOrders": "0", | ||
306 | }, | ||
307 | "DASH": { | ||
308 | "available": "0", | ||
309 | "onOrders": "3" | ||
310 | } | ||
311 | } | ||
312 | |||
313 | expected = { | ||
314 | "info": { | ||
315 | "ETH": {"available": "10", "onOrders": "1"}, | ||
316 | "BTC": {"available": "1", "onOrders": "0"}, | ||
317 | "DASH": {"available": "0", "onOrders": "3"} | ||
318 | }, | ||
319 | "ETH": {"free": D("10"), "used": D("1"), "total": D("11")}, | ||
320 | "BTC": {"free": D("1"), "used": D("0"), "total": D("1")}, | ||
321 | "DASH": {"free": D("0"), "used": D("3"), "total": D("3")}, | ||
322 | "free": {"ETH": D("10"), "BTC": D("1"), "DASH": D("0")}, | ||
323 | "used": {"ETH": D("1"), "BTC": D("0"), "DASH": D("3")}, | ||
324 | "total": {"ETH": D("11"), "BTC": D("1"), "DASH": D("3")} | ||
325 | } | ||
326 | result = self.s.fetch_balance() | ||
327 | load_markets.assert_called_once() | ||
328 | self.assertEqual(expected, result) | ||
329 | |||
330 | def test_fetch_balance_per_type(self): | ||
331 | with mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balances: | ||
332 | balances.return_value = { | ||
333 | "exchange": { | ||
334 | "BLK": "159.83673869", | ||
335 | "BTC": "0.00005959", | ||
336 | "USDT": "0.00002625", | ||
337 | "XMR": "0.18719303" | ||
338 | }, | ||
339 | "margin": { | ||
340 | "BTC": "0.03019227" | ||
341 | } | ||
342 | } | ||
343 | expected = { | ||
344 | "info": { | ||
345 | "exchange": { | ||
346 | "BLK": "159.83673869", | ||
347 | "BTC": "0.00005959", | ||
348 | "USDT": "0.00002625", | ||
349 | "XMR": "0.18719303" | ||
350 | }, | ||
351 | "margin": { | ||
352 | "BTC": "0.03019227" | ||
353 | } | ||
354 | }, | ||
355 | "exchange": { | ||
356 | "BLK": D("159.83673869"), | ||
357 | "BTC": D("0.00005959"), | ||
358 | "USDT": D("0.00002625"), | ||
359 | "XMR": D("0.18719303") | ||
360 | }, | ||
361 | "margin": {"BTC": D("0.03019227")}, | ||
362 | "BLK": {"exchange": D("159.83673869")}, | ||
363 | "BTC": {"exchange": D("0.00005959"), "margin": D("0.03019227")}, | ||
364 | "USDT": {"exchange": D("0.00002625")}, | ||
365 | "XMR": {"exchange": D("0.18719303")} | ||
366 | } | ||
367 | result = self.s.fetch_balance_per_type() | ||
368 | self.assertEqual(expected, result) | ||
369 | |||
370 | def test_fetch_all_balances(self): | ||
371 | import json | ||
372 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
373 | mock.patch.object(self.s, "privatePostGetMarginPosition") as margin_balance,\ | ||
374 | mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balance,\ | ||
375 | mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balance_per_type: | ||
376 | |||
377 | with open("test_samples/poloniexETest.test_fetch_all_balances.1.json") as f: | ||
378 | balance.return_value = json.load(f) | ||
379 | with open("test_samples/poloniexETest.test_fetch_all_balances.2.json") as f: | ||
380 | margin_balance.return_value = json.load(f) | ||
381 | with open("test_samples/poloniexETest.test_fetch_all_balances.3.json") as f: | ||
382 | balance_per_type.return_value = json.load(f) | ||
383 | |||
384 | result = self.s.fetch_all_balances() | ||
385 | expected_doge = { | ||
386 | "total": D("-12779.79821852"), | ||
387 | "exchange_used": D("0E-8"), | ||
388 | "exchange_total": D("0E-8"), | ||
389 | "exchange_free": D("0E-8"), | ||
390 | "margin_available": 0, | ||
391 | "margin_in_position": 0, | ||
392 | "margin_borrowed": D("12779.79821852"), | ||
393 | "margin_total": D("-12779.79821852"), | ||
394 | "margin_pending_gain": 0, | ||
395 | "margin_lending_fees": D("-9E-8"), | ||
396 | "margin_pending_base_gain": D("0.00024059"), | ||
397 | "margin_position_type": "short", | ||
398 | "margin_liquidation_price": D("0.00000246"), | ||
399 | "margin_borrowed_base_price": D("0.00599149"), | ||
400 | "margin_borrowed_base_currency": "BTC" | ||
401 | } | ||
402 | expected_btc = {"total": D("0.05432165"), | ||
403 | "exchange_used": D("0E-8"), | ||
404 | "exchange_total": D("0.00005959"), | ||
405 | "exchange_free": D("0.00005959"), | ||
406 | "margin_available": D("0.03019227"), | ||
407 | "margin_in_position": D("0.02406979"), | ||
408 | "margin_borrowed": 0, | ||
409 | "margin_total": D("0.05426206"), | ||
410 | "margin_pending_gain": D("0.00093955"), | ||
411 | "margin_lending_fees": 0, | ||
412 | "margin_pending_base_gain": 0, | ||
413 | "margin_position_type": None, | ||
414 | "margin_liquidation_price": 0, | ||
415 | "margin_borrowed_base_price": 0, | ||
416 | "margin_borrowed_base_currency": None | ||
417 | } | ||
418 | expected_xmr = {"total": D("0.18719303"), | ||
419 | "exchange_used": D("0E-8"), | ||
420 | "exchange_total": D("0.18719303"), | ||
421 | "exchange_free": D("0.18719303"), | ||
422 | "margin_available": 0, | ||
423 | "margin_in_position": 0, | ||
424 | "margin_borrowed": 0, | ||
425 | "margin_total": 0, | ||
426 | "margin_pending_gain": 0, | ||
427 | "margin_lending_fees": 0, | ||
428 | "margin_pending_base_gain": 0, | ||
429 | "margin_position_type": None, | ||
430 | "margin_liquidation_price": 0, | ||
431 | "margin_borrowed_base_price": 0, | ||
432 | "margin_borrowed_base_currency": None | ||
433 | } | ||
434 | self.assertEqual(expected_xmr, result["XMR"]) | ||
435 | self.assertEqual(expected_doge, result["DOGE"]) | ||
436 | self.assertEqual(expected_btc, result["BTC"]) | ||
437 | |||
438 | def test_create_margin_order(self): | ||
439 | with self.assertRaises(market.ExchangeError): | ||
440 | self.s.create_margin_order("FOO", "market", "buy", "10") | ||
441 | |||
442 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
443 | mock.patch.object(self.s, "privatePostMarginBuy") as margin_buy,\ | ||
444 | mock.patch.object(self.s, "privatePostMarginSell") as margin_sell,\ | ||
445 | mock.patch.object(self.s, "market") as market_mock,\ | ||
446 | mock.patch.object(self.s, "price_to_precision") as ptp,\ | ||
447 | mock.patch.object(self.s, "amount_to_precision") as atp: | ||
448 | |||
449 | margin_buy.return_value = { | ||
450 | "orderNumber": 123 | ||
451 | } | ||
452 | margin_sell.return_value = { | ||
453 | "orderNumber": 456 | ||
454 | } | ||
455 | market_mock.return_value = { "id": "BTC_ETC", "symbol": "BTC_ETC" } | ||
456 | ptp.return_value = D("0.1") | ||
457 | atp.return_value = D("12") | ||
458 | |||
459 | order = self.s.create_margin_order("BTC_ETC", "margin", "buy", "12", price="0.1") | ||
460 | self.assertEqual(123, order["id"]) | ||
461 | margin_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")}) | ||
462 | margin_sell.assert_not_called() | ||
463 | margin_buy.reset_mock() | ||
464 | margin_sell.reset_mock() | ||
465 | |||
466 | order = self.s.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate="0.01", price="0.1") | ||
467 | self.assertEqual(456, order["id"]) | ||
468 | margin_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"}) | ||
469 | margin_buy.assert_not_called() | ||
470 | |||
471 | def test_create_exchange_order(self): | ||
472 | with mock.patch.object(market.ccxt.poloniex, "create_order") as create_order: | ||
473 | self.s.create_order("symbol", "type", "side", "amount", price="price", params="params") | ||
474 | |||
475 | create_order.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
476 | |||
477 | |||
diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..6396c07 --- /dev/null +++ b/tests/test_main.py | |||
@@ -0,0 +1,290 @@ | |||
1 | from .helper import * | ||
2 | import main, market | ||
3 | |||
4 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
5 | class MainTest(WebMockTestCase): | ||
6 | def test_make_order(self): | ||
7 | self.m.get_ticker.return_value = { | ||
8 | "inverted": False, | ||
9 | "average": D("0.1"), | ||
10 | "bid": D("0.09"), | ||
11 | "ask": D("0.11"), | ||
12 | } | ||
13 | |||
14 | with self.subTest(description="nominal case"): | ||
15 | main.make_order(self.m, 10, "ETH") | ||
16 | |||
17 | self.m.report.log_stage.assert_has_calls([ | ||
18 | mock.call("make_order_begin"), | ||
19 | mock.call("make_order_end"), | ||
20 | ]) | ||
21 | self.m.balances.fetch_balances.assert_has_calls([ | ||
22 | mock.call(tag="make_order_begin"), | ||
23 | mock.call(tag="make_order_end"), | ||
24 | ]) | ||
25 | self.m.trades.all.append.assert_called_once() | ||
26 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
27 | self.assertEqual(False, trade.orders[0].close_if_possible) | ||
28 | self.assertEqual(0, trade.value_from) | ||
29 | self.assertEqual("ETH", trade.currency) | ||
30 | self.assertEqual("BTC", trade.base_currency) | ||
31 | self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average") | ||
32 | self.m.trades.run_orders.assert_called_once_with() | ||
33 | self.m.follow_orders.assert_called_once_with() | ||
34 | |||
35 | order = trade.orders[0] | ||
36 | self.assertEqual(D("0.10"), order.rate) | ||
37 | |||
38 | self.m.reset_mock() | ||
39 | with self.subTest(compute_value="default"): | ||
40 | main.make_order(self.m, 10, "ETH", action="dispose", | ||
41 | compute_value="ask") | ||
42 | |||
43 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
44 | order = trade.orders[0] | ||
45 | self.assertEqual(D("0.11"), order.rate) | ||
46 | |||
47 | self.m.reset_mock() | ||
48 | with self.subTest(follow=False): | ||
49 | result = main.make_order(self.m, 10, "ETH", follow=False) | ||
50 | |||
51 | self.m.report.log_stage.assert_has_calls([ | ||
52 | mock.call("make_order_begin"), | ||
53 | mock.call("make_order_end_not_followed"), | ||
54 | ]) | ||
55 | self.m.balances.fetch_balances.assert_called_once_with(tag="make_order_begin") | ||
56 | |||
57 | self.m.trades.all.append.assert_called_once() | ||
58 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
59 | self.assertEqual(0, trade.value_from) | ||
60 | self.assertEqual("ETH", trade.currency) | ||
61 | self.assertEqual("BTC", trade.base_currency) | ||
62 | self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average") | ||
63 | self.m.trades.run_orders.assert_called_once_with() | ||
64 | self.m.follow_orders.assert_not_called() | ||
65 | self.assertEqual(trade.orders[0], result) | ||
66 | |||
67 | self.m.reset_mock() | ||
68 | with self.subTest(base_currency="USDT"): | ||
69 | main.make_order(self.m, 1, "BTC", base_currency="USDT") | ||
70 | |||
71 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
72 | self.assertEqual("BTC", trade.currency) | ||
73 | self.assertEqual("USDT", trade.base_currency) | ||
74 | |||
75 | self.m.reset_mock() | ||
76 | with self.subTest(close_if_possible=True): | ||
77 | main.make_order(self.m, 10, "ETH", close_if_possible=True) | ||
78 | |||
79 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
80 | self.assertEqual(True, trade.orders[0].close_if_possible) | ||
81 | |||
82 | self.m.reset_mock() | ||
83 | with self.subTest(action="dispose"): | ||
84 | main.make_order(self.m, 10, "ETH", action="dispose") | ||
85 | |||
86 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
87 | self.assertEqual(0, trade.value_to) | ||
88 | self.assertEqual(1, trade.value_from.value) | ||
89 | self.assertEqual("ETH", trade.currency) | ||
90 | self.assertEqual("BTC", trade.base_currency) | ||
91 | |||
92 | self.m.reset_mock() | ||
93 | with self.subTest(compute_value="default"): | ||
94 | main.make_order(self.m, 10, "ETH", action="dispose", | ||
95 | compute_value="bid") | ||
96 | |||
97 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
98 | self.assertEqual(D("0.9"), trade.value_from.value) | ||
99 | |||
100 | def test_get_user_market(self): | ||
101 | with mock.patch("main.fetch_markets") as main_fetch_markets,\ | ||
102 | mock.patch("main.parse_args") as main_parse_args,\ | ||
103 | mock.patch("main.parse_config") as main_parse_config: | ||
104 | with self.subTest(debug=False): | ||
105 | main_parse_args.return_value = self.market_args() | ||
106 | main_parse_config.return_value = "pg_config" | ||
107 | main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)] | ||
108 | m = main.get_user_market("config_path.ini", 1) | ||
109 | |||
110 | self.assertIsInstance(m, market.Market) | ||
111 | self.assertFalse(m.debug) | ||
112 | main_parse_args.assert_called_once_with(["--config", "config_path.ini"]) | ||
113 | |||
114 | main_parse_args.reset_mock() | ||
115 | with self.subTest(debug=True): | ||
116 | main_parse_args.return_value = self.market_args(debug=True) | ||
117 | main_parse_config.return_value = "pg_config" | ||
118 | main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)] | ||
119 | m = main.get_user_market("config_path.ini", 1, debug=True) | ||
120 | |||
121 | self.assertIsInstance(m, market.Market) | ||
122 | self.assertTrue(m.debug) | ||
123 | main_parse_args.assert_called_once_with(["--config", "config_path.ini", "--debug"]) | ||
124 | |||
125 | def test_process(self): | ||
126 | with mock.patch("market.Market") as market_mock,\ | ||
127 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
128 | |||
129 | args_mock = mock.Mock() | ||
130 | args_mock.action = "action" | ||
131 | args_mock.config = "config" | ||
132 | args_mock.user = "user" | ||
133 | args_mock.debug = "debug" | ||
134 | args_mock.before = "before" | ||
135 | args_mock.after = "after" | ||
136 | self.assertEqual("", stdout_mock.getvalue()) | ||
137 | |||
138 | main.process("config", 3, 1, args_mock, "pg_config") | ||
139 | |||
140 | market_mock.from_config.assert_has_calls([ | ||
141 | mock.call("config", args_mock, pg_config="pg_config", market_id=3, user_id=1), | ||
142 | mock.call().process("action", before="before", after="after"), | ||
143 | ]) | ||
144 | |||
145 | with self.subTest(exception=True): | ||
146 | market_mock.from_config.side_effect = Exception("boo") | ||
147 | main.process(3, "config", 1, args_mock, "pg_config") | ||
148 | self.assertEqual("Exception: boo\n", stdout_mock.getvalue()) | ||
149 | |||
150 | def test_main(self): | ||
151 | with self.subTest(parallel=False): | ||
152 | with mock.patch("main.parse_args") as parse_args,\ | ||
153 | mock.patch("main.parse_config") as parse_config,\ | ||
154 | mock.patch("main.fetch_markets") as fetch_markets,\ | ||
155 | mock.patch("main.process") as process: | ||
156 | |||
157 | args_mock = mock.Mock() | ||
158 | args_mock.parallel = False | ||
159 | args_mock.user = "user" | ||
160 | parse_args.return_value = args_mock | ||
161 | |||
162 | parse_config.return_value = "pg_config" | ||
163 | |||
164 | fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]] | ||
165 | |||
166 | main.main(["Foo", "Bar"]) | ||
167 | |||
168 | parse_args.assert_called_with(["Foo", "Bar"]) | ||
169 | parse_config.assert_called_with(args_mock) | ||
170 | fetch_markets.assert_called_with("pg_config", "user") | ||
171 | |||
172 | self.assertEqual(2, process.call_count) | ||
173 | process.assert_has_calls([ | ||
174 | mock.call("config1", 3, 1, args_mock, "pg_config"), | ||
175 | mock.call("config2", 1, 2, args_mock, "pg_config"), | ||
176 | ]) | ||
177 | with self.subTest(parallel=True): | ||
178 | with mock.patch("main.parse_args") as parse_args,\ | ||
179 | mock.patch("main.parse_config") as parse_config,\ | ||
180 | mock.patch("main.fetch_markets") as fetch_markets,\ | ||
181 | mock.patch("main.process") as process,\ | ||
182 | mock.patch("store.Portfolio.start_worker") as start: | ||
183 | |||
184 | args_mock = mock.Mock() | ||
185 | args_mock.parallel = True | ||
186 | args_mock.user = "user" | ||
187 | parse_args.return_value = args_mock | ||
188 | |||
189 | parse_config.return_value = "pg_config" | ||
190 | |||
191 | fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]] | ||
192 | |||
193 | main.main(["Foo", "Bar"]) | ||
194 | |||
195 | parse_args.assert_called_with(["Foo", "Bar"]) | ||
196 | parse_config.assert_called_with(args_mock) | ||
197 | fetch_markets.assert_called_with("pg_config", "user") | ||
198 | |||
199 | start.assert_called_once_with() | ||
200 | self.assertEqual(2, process.call_count) | ||
201 | process.assert_has_calls([ | ||
202 | mock.call.__bool__(), | ||
203 | mock.call("config1", 3, 1, args_mock, "pg_config"), | ||
204 | mock.call.__bool__(), | ||
205 | mock.call("config2", 1, 2, args_mock, "pg_config"), | ||
206 | ]) | ||
207 | |||
208 | @mock.patch.object(main.sys, "exit") | ||
209 | @mock.patch("main.os") | ||
210 | def test_parse_config(self, os, exit): | ||
211 | with self.subTest(report_path=None): | ||
212 | args = main.configargparse.Namespace(**{ | ||
213 | "db_host": "host", | ||
214 | "db_port": "port", | ||
215 | "db_user": "user", | ||
216 | "db_password": "password", | ||
217 | "db_database": "database", | ||
218 | "report_path": None, | ||
219 | }) | ||
220 | |||
221 | result = main.parse_config(args) | ||
222 | self.assertEqual({ "host": "host", "port": "port", "user": | ||
223 | "user", "password": "password", "database": "database" | ||
224 | }, result) | ||
225 | with self.assertRaises(AttributeError): | ||
226 | args.db_password | ||
227 | |||
228 | with self.subTest(report_path="present"): | ||
229 | args = main.configargparse.Namespace(**{ | ||
230 | "db_host": "host", | ||
231 | "db_port": "port", | ||
232 | "db_user": "user", | ||
233 | "db_password": "password", | ||
234 | "db_database": "database", | ||
235 | "report_path": "report_path", | ||
236 | }) | ||
237 | |||
238 | os.path.exists.return_value = False | ||
239 | |||
240 | result = main.parse_config(args) | ||
241 | |||
242 | os.path.exists.assert_called_once_with("report_path") | ||
243 | os.makedirs.assert_called_once_with("report_path") | ||
244 | |||
245 | def test_parse_args(self): | ||
246 | with self.subTest(config="config.ini"): | ||
247 | args = main.parse_args([]) | ||
248 | self.assertEqual("config.ini", args.config) | ||
249 | self.assertFalse(args.before) | ||
250 | self.assertFalse(args.after) | ||
251 | self.assertFalse(args.debug) | ||
252 | |||
253 | args = main.parse_args(["--before", "--after", "--debug"]) | ||
254 | self.assertTrue(args.before) | ||
255 | self.assertTrue(args.after) | ||
256 | self.assertTrue(args.debug) | ||
257 | |||
258 | with self.subTest(config="inexistant"), \ | ||
259 | self.assertRaises(SystemExit), \ | ||
260 | mock.patch('sys.stderr', new_callable=StringIO) as stdout_mock: | ||
261 | args = main.parse_args(["--config", "foo.bar"]) | ||
262 | |||
263 | @mock.patch.object(main, "psycopg2") | ||
264 | def test_fetch_markets(self, psycopg2): | ||
265 | connect_mock = mock.Mock() | ||
266 | cursor_mock = mock.MagicMock() | ||
267 | cursor_mock.__iter__.return_value = ["row_1", "row_2"] | ||
268 | |||
269 | connect_mock.cursor.return_value = cursor_mock | ||
270 | psycopg2.connect.return_value = connect_mock | ||
271 | |||
272 | with self.subTest(user=None): | ||
273 | rows = list(main.fetch_markets({"foo": "bar"}, None)) | ||
274 | |||
275 | psycopg2.connect.assert_called_once_with(foo="bar") | ||
276 | cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs") | ||
277 | |||
278 | self.assertEqual(["row_1", "row_2"], rows) | ||
279 | |||
280 | psycopg2.connect.reset_mock() | ||
281 | cursor_mock.execute.reset_mock() | ||
282 | with self.subTest(user=1): | ||
283 | rows = list(main.fetch_markets({"foo": "bar"}, 1)) | ||
284 | |||
285 | psycopg2.connect.assert_called_once_with(foo="bar") | ||
286 | cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs WHERE user_id = %s", 1) | ||
287 | |||
288 | self.assertEqual(["row_1", "row_2"], rows) | ||
289 | |||
290 | |||
diff --git a/tests/test_market.py b/tests/test_market.py new file mode 100644 index 0000000..82eeea8 --- /dev/null +++ b/tests/test_market.py | |||
@@ -0,0 +1,900 @@ | |||
1 | from .helper import * | ||
2 | import market, store, portfolio | ||
3 | import datetime | ||
4 | |||
5 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
6 | class MarketTest(WebMockTestCase): | ||
7 | def setUp(self): | ||
8 | super().setUp() | ||
9 | |||
10 | self.ccxt = mock.Mock(spec=market.ccxt.poloniexE) | ||
11 | |||
12 | def test_values(self): | ||
13 | m = market.Market(self.ccxt, self.market_args()) | ||
14 | |||
15 | self.assertEqual(self.ccxt, m.ccxt) | ||
16 | self.assertFalse(m.debug) | ||
17 | self.assertIsInstance(m.report, market.ReportStore) | ||
18 | self.assertIsInstance(m.trades, market.TradeStore) | ||
19 | self.assertIsInstance(m.balances, market.BalanceStore) | ||
20 | self.assertEqual(m, m.report.market) | ||
21 | self.assertEqual(m, m.trades.market) | ||
22 | self.assertEqual(m, m.balances.market) | ||
23 | self.assertEqual(m, m.ccxt._market) | ||
24 | |||
25 | m = market.Market(self.ccxt, self.market_args(debug=True)) | ||
26 | self.assertTrue(m.debug) | ||
27 | |||
28 | m = market.Market(self.ccxt, self.market_args(debug=False)) | ||
29 | self.assertFalse(m.debug) | ||
30 | |||
31 | with mock.patch("market.ReportStore") as report_store: | ||
32 | with self.subTest(quiet=False): | ||
33 | m = market.Market(self.ccxt, self.market_args(quiet=False)) | ||
34 | report_store.assert_called_with(m, verbose_print=True) | ||
35 | report_store().log_market.assert_called_once() | ||
36 | report_store.reset_mock() | ||
37 | with self.subTest(quiet=True): | ||
38 | m = market.Market(self.ccxt, self.market_args(quiet=True)) | ||
39 | report_store.assert_called_with(m, verbose_print=False) | ||
40 | report_store().log_market.assert_called_once() | ||
41 | |||
42 | @mock.patch("market.ccxt") | ||
43 | def test_from_config(self, ccxt): | ||
44 | with mock.patch("market.ReportStore"): | ||
45 | ccxt.poloniexE.return_value = self.ccxt | ||
46 | |||
47 | m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args()) | ||
48 | |||
49 | self.assertEqual(self.ccxt, m.ccxt) | ||
50 | |||
51 | m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args(debug=True)) | ||
52 | self.assertEqual(True, m.debug) | ||
53 | |||
54 | def test_get_tickers(self): | ||
55 | self.ccxt.fetch_tickers.side_effect = [ | ||
56 | "tickers", | ||
57 | market.NotSupported | ||
58 | ] | ||
59 | |||
60 | m = market.Market(self.ccxt, self.market_args()) | ||
61 | self.assertEqual("tickers", m.get_tickers()) | ||
62 | self.assertEqual("tickers", m.get_tickers()) | ||
63 | self.ccxt.fetch_tickers.assert_called_once() | ||
64 | |||
65 | self.assertIsNone(m.get_tickers(refresh=self.time.time())) | ||
66 | |||
67 | def test_get_ticker(self): | ||
68 | with self.subTest(get_tickers=True): | ||
69 | self.ccxt.fetch_tickers.return_value = { | ||
70 | "ETH/ETC": { "bid": 1, "ask": 3 }, | ||
71 | "XVG/ETH": { "bid": 10, "ask": 40 }, | ||
72 | } | ||
73 | m = market.Market(self.ccxt, self.market_args()) | ||
74 | |||
75 | ticker = m.get_ticker("ETH", "ETC") | ||
76 | self.assertEqual(1, ticker["bid"]) | ||
77 | self.assertEqual(3, ticker["ask"]) | ||
78 | self.assertEqual(2, ticker["average"]) | ||
79 | self.assertFalse(ticker["inverted"]) | ||
80 | |||
81 | ticker = m.get_ticker("ETH", "XVG") | ||
82 | self.assertEqual(0.0625, ticker["average"]) | ||
83 | self.assertTrue(ticker["inverted"]) | ||
84 | self.assertIn("original", ticker) | ||
85 | self.assertEqual(10, ticker["original"]["bid"]) | ||
86 | self.assertEqual(25, ticker["original"]["average"]) | ||
87 | |||
88 | ticker = m.get_ticker("XVG", "XMR") | ||
89 | self.assertIsNone(ticker) | ||
90 | |||
91 | with self.subTest(get_tickers=False): | ||
92 | self.ccxt.fetch_tickers.return_value = None | ||
93 | self.ccxt.fetch_ticker.side_effect = [ | ||
94 | { "bid": 1, "ask": 3 }, | ||
95 | market.ExchangeError("foo"), | ||
96 | { "bid": 10, "ask": 40 }, | ||
97 | market.ExchangeError("foo"), | ||
98 | market.ExchangeError("foo"), | ||
99 | ] | ||
100 | |||
101 | m = market.Market(self.ccxt, self.market_args()) | ||
102 | |||
103 | ticker = m.get_ticker("ETH", "ETC") | ||
104 | self.ccxt.fetch_ticker.assert_called_with("ETH/ETC") | ||
105 | self.assertEqual(1, ticker["bid"]) | ||
106 | self.assertEqual(3, ticker["ask"]) | ||
107 | self.assertEqual(2, ticker["average"]) | ||
108 | self.assertFalse(ticker["inverted"]) | ||
109 | |||
110 | ticker = m.get_ticker("ETH", "XVG") | ||
111 | self.assertEqual(0.0625, ticker["average"]) | ||
112 | self.assertTrue(ticker["inverted"]) | ||
113 | self.assertIn("original", ticker) | ||
114 | self.assertEqual(10, ticker["original"]["bid"]) | ||
115 | self.assertEqual(25, ticker["original"]["average"]) | ||
116 | |||
117 | ticker = m.get_ticker("XVG", "XMR") | ||
118 | self.assertIsNone(ticker) | ||
119 | |||
120 | def test_fetch_fees(self): | ||
121 | m = market.Market(self.ccxt, self.market_args()) | ||
122 | self.ccxt.fetch_fees.return_value = "Foo" | ||
123 | self.assertEqual("Foo", m.fetch_fees()) | ||
124 | self.ccxt.fetch_fees.assert_called_once() | ||
125 | self.ccxt.reset_mock() | ||
126 | self.assertEqual("Foo", m.fetch_fees()) | ||
127 | self.ccxt.fetch_fees.assert_not_called() | ||
128 | |||
129 | @mock.patch.object(market.Portfolio, "repartition") | ||
130 | @mock.patch.object(market.Market, "get_ticker") | ||
131 | @mock.patch.object(market.TradeStore, "compute_trades") | ||
132 | def test_prepare_trades(self, compute_trades, get_ticker, repartition): | ||
133 | repartition.return_value = { | ||
134 | "XEM": (D("0.75"), "long"), | ||
135 | "BTC": (D("0.25"), "long"), | ||
136 | } | ||
137 | def _get_ticker(c1, c2): | ||
138 | if c1 == "USDT" and c2 == "BTC": | ||
139 | return { "average": D("0.0001") } | ||
140 | if c1 == "XVG" and c2 == "BTC": | ||
141 | return { "average": D("0.000001") } | ||
142 | self.fail("Should be called with {}, {}".format(c1, c2)) | ||
143 | get_ticker.side_effect = _get_ticker | ||
144 | |||
145 | with mock.patch("market.ReportStore"): | ||
146 | m = market.Market(self.ccxt, self.market_args()) | ||
147 | self.ccxt.fetch_all_balances.return_value = { | ||
148 | "USDT": { | ||
149 | "exchange_free": D("10000.0"), | ||
150 | "exchange_used": D("0.0"), | ||
151 | "exchange_total": D("10000.0"), | ||
152 | "total": D("10000.0") | ||
153 | }, | ||
154 | "XVG": { | ||
155 | "exchange_free": D("10000.0"), | ||
156 | "exchange_used": D("0.0"), | ||
157 | "exchange_total": D("10000.0"), | ||
158 | "total": D("10000.0") | ||
159 | }, | ||
160 | } | ||
161 | |||
162 | m.balances.fetch_balances(tag="tag") | ||
163 | |||
164 | m.prepare_trades() | ||
165 | compute_trades.assert_called() | ||
166 | |||
167 | call = compute_trades.call_args | ||
168 | self.assertEqual(1, call[0][0]["USDT"].value) | ||
169 | self.assertEqual(D("0.01"), call[0][0]["XVG"].value) | ||
170 | self.assertEqual(D("0.2525"), call[0][1]["BTC"].value) | ||
171 | self.assertEqual(D("0.7575"), call[0][1]["XEM"].value) | ||
172 | m.report.log_stage.assert_called_once_with("prepare_trades", | ||
173 | base_currency='BTC', compute_value='average', | ||
174 | liquidity='medium', only=None, repartition=None) | ||
175 | m.report.log_balances.assert_called_once_with(tag="tag") | ||
176 | |||
177 | |||
178 | @mock.patch.object(market.time, "sleep") | ||
179 | @mock.patch.object(market.TradeStore, "all_orders") | ||
180 | def test_follow_orders(self, all_orders, time_mock): | ||
181 | for debug, sleep in [ | ||
182 | (False, None), (True, None), | ||
183 | (False, 12), (True, 12)]: | ||
184 | with self.subTest(sleep=sleep, debug=debug), \ | ||
185 | mock.patch("market.ReportStore"): | ||
186 | m = market.Market(self.ccxt, self.market_args(debug=debug)) | ||
187 | |||
188 | order_mock1 = mock.Mock() | ||
189 | order_mock2 = mock.Mock() | ||
190 | order_mock3 = mock.Mock() | ||
191 | all_orders.side_effect = [ | ||
192 | [order_mock1, order_mock2], | ||
193 | [order_mock1, order_mock2], | ||
194 | |||
195 | [order_mock1, order_mock3], | ||
196 | [order_mock1, order_mock3], | ||
197 | |||
198 | [order_mock1, order_mock3], | ||
199 | [order_mock1, order_mock3], | ||
200 | |||
201 | [] | ||
202 | ] | ||
203 | |||
204 | order_mock1.get_status.side_effect = ["open", "open", "closed"] | ||
205 | order_mock2.get_status.side_effect = ["open"] | ||
206 | order_mock3.get_status.side_effect = ["open", "closed"] | ||
207 | |||
208 | order_mock1.trade = mock.Mock() | ||
209 | order_mock2.trade = mock.Mock() | ||
210 | order_mock3.trade = mock.Mock() | ||
211 | |||
212 | m.follow_orders(sleep=sleep) | ||
213 | |||
214 | order_mock1.trade.update_order.assert_any_call(order_mock1, 1) | ||
215 | order_mock1.trade.update_order.assert_any_call(order_mock1, 2) | ||
216 | self.assertEqual(2, order_mock1.trade.update_order.call_count) | ||
217 | self.assertEqual(3, order_mock1.get_status.call_count) | ||
218 | |||
219 | order_mock2.trade.update_order.assert_any_call(order_mock2, 1) | ||
220 | self.assertEqual(1, order_mock2.trade.update_order.call_count) | ||
221 | self.assertEqual(1, order_mock2.get_status.call_count) | ||
222 | |||
223 | order_mock3.trade.update_order.assert_any_call(order_mock3, 2) | ||
224 | self.assertEqual(1, order_mock3.trade.update_order.call_count) | ||
225 | self.assertEqual(2, order_mock3.get_status.call_count) | ||
226 | m.report.log_stage.assert_called() | ||
227 | calls = [ | ||
228 | mock.call("follow_orders_begin"), | ||
229 | mock.call("follow_orders_tick_1"), | ||
230 | mock.call("follow_orders_tick_2"), | ||
231 | mock.call("follow_orders_tick_3"), | ||
232 | mock.call("follow_orders_end"), | ||
233 | ] | ||
234 | m.report.log_stage.assert_has_calls(calls) | ||
235 | m.report.log_orders.assert_called() | ||
236 | self.assertEqual(3, m.report.log_orders.call_count) | ||
237 | calls = [ | ||
238 | mock.call([order_mock1, order_mock2], tick=1), | ||
239 | mock.call([order_mock1, order_mock3], tick=2), | ||
240 | mock.call([order_mock1, order_mock3], tick=3), | ||
241 | ] | ||
242 | m.report.log_orders.assert_has_calls(calls) | ||
243 | calls = [ | ||
244 | mock.call(order_mock1, 3, finished=True), | ||
245 | mock.call(order_mock3, 3, finished=True), | ||
246 | ] | ||
247 | m.report.log_order.assert_has_calls(calls) | ||
248 | |||
249 | if sleep is None: | ||
250 | if debug: | ||
251 | m.report.log_debug_action.assert_called_with("Set follow_orders tick to 7s") | ||
252 | time_mock.assert_called_with(7) | ||
253 | else: | ||
254 | time_mock.assert_called_with(30) | ||
255 | else: | ||
256 | time_mock.assert_called_with(sleep) | ||
257 | |||
258 | with self.subTest("disappearing order"), \ | ||
259 | mock.patch("market.ReportStore"): | ||
260 | all_orders.reset_mock() | ||
261 | m = market.Market(self.ccxt, self.market_args()) | ||
262 | |||
263 | order_mock1 = mock.Mock() | ||
264 | order_mock2 = mock.Mock() | ||
265 | all_orders.side_effect = [ | ||
266 | [order_mock1, order_mock2], | ||
267 | [order_mock1, order_mock2], | ||
268 | |||
269 | [order_mock1, order_mock2], | ||
270 | [order_mock1, order_mock2], | ||
271 | |||
272 | [] | ||
273 | ] | ||
274 | |||
275 | order_mock1.get_status.side_effect = ["open", "closed"] | ||
276 | order_mock2.get_status.side_effect = ["open", "error_disappeared"] | ||
277 | |||
278 | order_mock1.trade = mock.Mock() | ||
279 | trade_mock = mock.Mock() | ||
280 | order_mock2.trade = trade_mock | ||
281 | |||
282 | trade_mock.tick_actions_recreate.return_value = "tick1" | ||
283 | |||
284 | m.follow_orders() | ||
285 | |||
286 | trade_mock.tick_actions_recreate.assert_called_once_with(2) | ||
287 | trade_mock.prepare_order.assert_called_once_with(compute_value="tick1") | ||
288 | m.report.log_error.assert_called_once_with("follow_orders", message=mock.ANY) | ||
289 | |||
290 | @mock.patch.object(market.BalanceStore, "fetch_balances") | ||
291 | def test_move_balance(self, fetch_balances): | ||
292 | for debug in [True, False]: | ||
293 | with self.subTest(debug=debug),\ | ||
294 | mock.patch("market.ReportStore"): | ||
295 | m = market.Market(self.ccxt, self.market_args(debug=debug)) | ||
296 | |||
297 | value_from = portfolio.Amount("BTC", "1.0") | ||
298 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
299 | value_to = portfolio.Amount("BTC", "10.0") | ||
300 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
301 | |||
302 | value_from = portfolio.Amount("BTC", "0.0") | ||
303 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
304 | value_to = portfolio.Amount("BTC", "-3.0") | ||
305 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
306 | |||
307 | value_from = portfolio.Amount("USDT", "0.0") | ||
308 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | ||
309 | value_to = portfolio.Amount("USDT", "-50.0") | ||
310 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) | ||
311 | |||
312 | m.trades.all = [trade1, trade2, trade3] | ||
313 | balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
314 | balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }) | ||
315 | balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }) | ||
316 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} | ||
317 | |||
318 | m.move_balances() | ||
319 | |||
320 | fetch_balances.assert_called_with() | ||
321 | m.report.log_move_balances.assert_called_once() | ||
322 | |||
323 | if debug: | ||
324 | m.report.log_debug_action.assert_called() | ||
325 | self.assertEqual(3, m.report.log_debug_action.call_count) | ||
326 | else: | ||
327 | self.ccxt.transfer_balance.assert_any_call("BTC", 3, "exchange", "margin") | ||
328 | self.ccxt.transfer_balance.assert_any_call("USDT", 100, "exchange", "margin") | ||
329 | self.ccxt.transfer_balance.assert_any_call("ETC", 5, "margin", "exchange") | ||
330 | |||
331 | m.report.reset_mock() | ||
332 | fetch_balances.reset_mock() | ||
333 | with self.subTest(retry=True): | ||
334 | with mock.patch("market.ReportStore"): | ||
335 | m = market.Market(self.ccxt, self.market_args()) | ||
336 | |||
337 | value_from = portfolio.Amount("BTC", "0.0") | ||
338 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
339 | value_to = portfolio.Amount("BTC", "-3.0") | ||
340 | trade = portfolio.Trade(value_from, value_to, "ETH", m) | ||
341 | |||
342 | m.trades.all = [trade] | ||
343 | balance = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
344 | m.balances.all = {"BTC": balance} | ||
345 | |||
346 | m.ccxt.transfer_balance.side_effect = [ | ||
347 | market.ccxt.RequestTimeout, | ||
348 | market.ccxt.InvalidNonce, | ||
349 | True | ||
350 | ] | ||
351 | m.move_balances() | ||
352 | self.ccxt.transfer_balance.assert_has_calls([ | ||
353 | mock.call("BTC", 3, "exchange", "margin"), | ||
354 | mock.call("BTC", 3, "exchange", "margin"), | ||
355 | mock.call("BTC", 3, "exchange", "margin") | ||
356 | ]) | ||
357 | self.assertEqual(3, fetch_balances.call_count) | ||
358 | m.report.log_error.assert_called_with(mock.ANY, message="Retrying", exception=mock.ANY) | ||
359 | self.assertEqual(3, m.report.log_move_balances.call_count) | ||
360 | |||
361 | self.ccxt.transfer_balance.reset_mock() | ||
362 | m.report.reset_mock() | ||
363 | fetch_balances.reset_mock() | ||
364 | with self.subTest(retry=True, too_much=True): | ||
365 | with mock.patch("market.ReportStore"): | ||
366 | m = market.Market(self.ccxt, self.market_args()) | ||
367 | |||
368 | value_from = portfolio.Amount("BTC", "0.0") | ||
369 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
370 | value_to = portfolio.Amount("BTC", "-3.0") | ||
371 | trade = portfolio.Trade(value_from, value_to, "ETH", m) | ||
372 | |||
373 | m.trades.all = [trade] | ||
374 | balance = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
375 | m.balances.all = {"BTC": balance} | ||
376 | |||
377 | m.ccxt.transfer_balance.side_effect = [ | ||
378 | market.ccxt.RequestTimeout, | ||
379 | market.ccxt.RequestTimeout, | ||
380 | market.ccxt.RequestTimeout, | ||
381 | market.ccxt.RequestTimeout, | ||
382 | market.ccxt.RequestTimeout, | ||
383 | ] | ||
384 | with self.assertRaises(market.ccxt.RequestTimeout): | ||
385 | m.move_balances() | ||
386 | |||
387 | self.ccxt.transfer_balance.reset_mock() | ||
388 | m.report.reset_mock() | ||
389 | fetch_balances.reset_mock() | ||
390 | with self.subTest(retry=True, partial_result=True): | ||
391 | with mock.patch("market.ReportStore"): | ||
392 | m = market.Market(self.ccxt, self.market_args()) | ||
393 | |||
394 | value_from = portfolio.Amount("BTC", "1.0") | ||
395 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
396 | value_to = portfolio.Amount("BTC", "10.0") | ||
397 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
398 | |||
399 | value_from = portfolio.Amount("BTC", "0.0") | ||
400 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
401 | value_to = portfolio.Amount("BTC", "-3.0") | ||
402 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
403 | |||
404 | value_from = portfolio.Amount("USDT", "0.0") | ||
405 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | ||
406 | value_to = portfolio.Amount("USDT", "-50.0") | ||
407 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) | ||
408 | |||
409 | m.trades.all = [trade1, trade2, trade3] | ||
410 | balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
411 | balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }) | ||
412 | balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }) | ||
413 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} | ||
414 | |||
415 | call_counts = { "BTC": 0, "USDT": 0, "ETC": 0 } | ||
416 | def _transfer_balance(currency, amount, from_, to_): | ||
417 | call_counts[currency] += 1 | ||
418 | if currency == "BTC": | ||
419 | m.balances.all["BTC"] = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "3" }) | ||
420 | if currency == "USDT": | ||
421 | if call_counts["USDT"] == 1: | ||
422 | raise market.ccxt.RequestTimeout | ||
423 | else: | ||
424 | m.balances.all["USDT"] = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "150" }) | ||
425 | if currency == "ETC": | ||
426 | m.balances.all["ETC"] = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "10" }) | ||
427 | |||
428 | |||
429 | m.ccxt.transfer_balance.side_effect = _transfer_balance | ||
430 | |||
431 | m.move_balances() | ||
432 | self.ccxt.transfer_balance.assert_has_calls([ | ||
433 | mock.call("BTC", 3, "exchange", "margin"), | ||
434 | mock.call('USDT', 100, 'exchange', 'margin'), | ||
435 | mock.call('USDT', 100, 'exchange', 'margin'), | ||
436 | mock.call("ETC", 5, "margin", "exchange") | ||
437 | ]) | ||
438 | self.assertEqual(2, fetch_balances.call_count) | ||
439 | m.report.log_error.assert_called_with(mock.ANY, message="Retrying", exception=mock.ANY) | ||
440 | self.assertEqual(2, m.report.log_move_balances.call_count) | ||
441 | m.report.log_move_balances.asser_has_calls([ | ||
442 | mock.call( | ||
443 | { | ||
444 | 'BTC': portfolio.Amount("BTC", "3"), | ||
445 | 'USDT': portfolio.Amount("USDT", "150"), | ||
446 | 'ETC': portfolio.Amount("ETC", "10"), | ||
447 | }, | ||
448 | { | ||
449 | 'BTC': portfolio.Amount("BTC", "3"), | ||
450 | 'USDT': portfolio.Amount("USDT", "100"), | ||
451 | }), | ||
452 | mock.call( | ||
453 | { | ||
454 | 'BTC': portfolio.Amount("BTC", "3"), | ||
455 | 'USDT': portfolio.Amount("USDT", "150"), | ||
456 | 'ETC': portfolio.Amount("ETC", "10"), | ||
457 | }, | ||
458 | { | ||
459 | 'BTC': portfolio.Amount("BTC", "0"), | ||
460 | 'USDT': portfolio.Amount("USDT", "100"), | ||
461 | 'ETC': portfolio.Amount("ETC", "-5"), | ||
462 | }), | ||
463 | ]) | ||
464 | |||
465 | |||
466 | def test_store_file_report(self): | ||
467 | file_open = mock.mock_open() | ||
468 | m = market.Market(self.ccxt, | ||
469 | self.market_args(report_path="present"), user_id=1) | ||
470 | with self.subTest(file="present"),\ | ||
471 | mock.patch("market.open", file_open),\ | ||
472 | mock.patch.object(m, "report") as report,\ | ||
473 | mock.patch.object(market, "datetime") as time_mock: | ||
474 | |||
475 | report.print_logs = [[time_mock.now(), "Foo"], [time_mock.now(), "Bar"]] | ||
476 | report.to_json.return_value = "json_content" | ||
477 | |||
478 | m.store_file_report(datetime.datetime(2018, 2, 25)) | ||
479 | |||
480 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.json", "w") | ||
481 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.log", "w") | ||
482 | file_open().write.assert_any_call("json_content") | ||
483 | file_open().write.assert_any_call("Foo\nBar") | ||
484 | m.report.to_json.assert_called_once_with() | ||
485 | |||
486 | m = market.Market(self.ccxt, self.market_args(report_path="error"), user_id=1) | ||
487 | with self.subTest(file="error"),\ | ||
488 | mock.patch("market.open") as file_open,\ | ||
489 | mock.patch.object(m, "report") as report,\ | ||
490 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
491 | file_open.side_effect = FileNotFoundError | ||
492 | |||
493 | m.store_file_report(datetime.datetime(2018, 2, 25)) | ||
494 | |||
495 | self.assertRegex(stdout_mock.getvalue(), "impossible to store report file: FileNotFoundError;") | ||
496 | |||
497 | @mock.patch.object(market, "psycopg2") | ||
498 | def test_store_database_report(self, psycopg2): | ||
499 | connect_mock = mock.Mock() | ||
500 | cursor_mock = mock.MagicMock() | ||
501 | |||
502 | connect_mock.cursor.return_value = cursor_mock | ||
503 | psycopg2.connect.return_value = connect_mock | ||
504 | m = market.Market(self.ccxt, self.market_args(), | ||
505 | pg_config={"config": "pg_config"}, user_id=1) | ||
506 | cursor_mock.fetchone.return_value = [42] | ||
507 | |||
508 | with self.subTest(error=False),\ | ||
509 | mock.patch.object(m, "report") as report: | ||
510 | report.to_json_array.return_value = [ | ||
511 | ("date1", "type1", "payload1"), | ||
512 | ("date2", "type2", "payload2"), | ||
513 | ] | ||
514 | m.store_database_report(datetime.datetime(2018, 3, 24)) | ||
515 | connect_mock.assert_has_calls([ | ||
516 | mock.call.cursor(), | ||
517 | mock.call.cursor().execute('INSERT INTO reports("date", "market_config_id", "debug") VALUES (%s, %s, %s) RETURNING id;', (datetime.datetime(2018, 3, 24), None, False)), | ||
518 | mock.call.cursor().fetchone(), | ||
519 | mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date1', 42, 'type1', 'payload1')), | ||
520 | mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date2', 42, 'type2', 'payload2')), | ||
521 | mock.call.commit(), | ||
522 | mock.call.cursor().close(), | ||
523 | mock.call.close() | ||
524 | ]) | ||
525 | |||
526 | connect_mock.reset_mock() | ||
527 | with self.subTest(error=True),\ | ||
528 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
529 | psycopg2.connect.side_effect = Exception("Bouh") | ||
530 | m.store_database_report(datetime.datetime(2018, 3, 24)) | ||
531 | self.assertEqual(stdout_mock.getvalue(), "impossible to store report to database: Exception; Bouh\n") | ||
532 | |||
533 | def test_store_report(self): | ||
534 | m = market.Market(self.ccxt, self.market_args(report_db=False), user_id=1) | ||
535 | with self.subTest(file=None, pg_config=None),\ | ||
536 | mock.patch.object(m, "report") as report,\ | ||
537 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
538 | mock.patch.object(m, "store_file_report") as file_report: | ||
539 | m.store_report() | ||
540 | report.merge.assert_called_with(store.Portfolio.report) | ||
541 | |||
542 | file_report.assert_not_called() | ||
543 | db_report.assert_not_called() | ||
544 | |||
545 | report.reset_mock() | ||
546 | m = market.Market(self.ccxt, self.market_args(report_db=False, report_path="present"), user_id=1) | ||
547 | with self.subTest(file="present", pg_config=None),\ | ||
548 | mock.patch.object(m, "report") as report,\ | ||
549 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
550 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
551 | mock.patch.object(market, "datetime") as time_mock: | ||
552 | |||
553 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
554 | |||
555 | m.store_report() | ||
556 | |||
557 | report.merge.assert_called_with(store.Portfolio.report) | ||
558 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
559 | db_report.assert_not_called() | ||
560 | |||
561 | report.reset_mock() | ||
562 | m = market.Market(self.ccxt, self.market_args(report_db=True, report_path="present"), user_id=1) | ||
563 | with self.subTest(file="present", pg_config=None, report_db=True),\ | ||
564 | mock.patch.object(m, "report") as report,\ | ||
565 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
566 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
567 | mock.patch.object(market, "datetime") as time_mock: | ||
568 | |||
569 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
570 | |||
571 | m.store_report() | ||
572 | |||
573 | report.merge.assert_called_with(store.Portfolio.report) | ||
574 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
575 | db_report.assert_not_called() | ||
576 | |||
577 | report.reset_mock() | ||
578 | m = market.Market(self.ccxt, self.market_args(report_db=True), pg_config="present", user_id=1) | ||
579 | with self.subTest(file=None, pg_config="present"),\ | ||
580 | mock.patch.object(m, "report") as report,\ | ||
581 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
582 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
583 | mock.patch.object(market, "datetime") as time_mock: | ||
584 | |||
585 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
586 | |||
587 | m.store_report() | ||
588 | |||
589 | report.merge.assert_called_with(store.Portfolio.report) | ||
590 | file_report.assert_not_called() | ||
591 | db_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
592 | |||
593 | report.reset_mock() | ||
594 | m = market.Market(self.ccxt, self.market_args(report_db=True, report_path="present"), | ||
595 | pg_config="pg_config", user_id=1) | ||
596 | with self.subTest(file="present", pg_config="present"),\ | ||
597 | mock.patch.object(m, "report") as report,\ | ||
598 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
599 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
600 | mock.patch.object(market, "datetime") as time_mock: | ||
601 | |||
602 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
603 | |||
604 | m.store_report() | ||
605 | |||
606 | report.merge.assert_called_with(store.Portfolio.report) | ||
607 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
608 | db_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
609 | |||
610 | def test_print_orders(self): | ||
611 | m = market.Market(self.ccxt, self.market_args()) | ||
612 | with mock.patch.object(m.report, "log_stage") as log_stage,\ | ||
613 | mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\ | ||
614 | mock.patch.object(m, "prepare_trades") as prepare_trades,\ | ||
615 | mock.patch.object(m.trades, "prepare_orders") as prepare_orders: | ||
616 | m.print_orders() | ||
617 | |||
618 | log_stage.assert_called_with("print_orders") | ||
619 | fetch_balances.assert_called_with(tag="print_orders") | ||
620 | prepare_trades.assert_called_with(base_currency="BTC", | ||
621 | compute_value="average") | ||
622 | prepare_orders.assert_called_with(compute_value="average") | ||
623 | |||
624 | def test_print_balances(self): | ||
625 | m = market.Market(self.ccxt, self.market_args()) | ||
626 | |||
627 | with mock.patch.object(m.balances, "in_currency") as in_currency,\ | ||
628 | mock.patch.object(m.report, "log_stage") as log_stage,\ | ||
629 | mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\ | ||
630 | mock.patch.object(m.report, "print_log") as print_log: | ||
631 | |||
632 | in_currency.return_value = { | ||
633 | "BTC": portfolio.Amount("BTC", "0.65"), | ||
634 | "ETH": portfolio.Amount("BTC", "0.3"), | ||
635 | } | ||
636 | |||
637 | m.print_balances() | ||
638 | |||
639 | log_stage.assert_called_once_with("print_balances") | ||
640 | fetch_balances.assert_called_with() | ||
641 | print_log.assert_has_calls([ | ||
642 | mock.call("total:"), | ||
643 | mock.call(portfolio.Amount("BTC", "0.95")), | ||
644 | ]) | ||
645 | |||
646 | @mock.patch("market.Processor.process") | ||
647 | @mock.patch("market.ReportStore.log_error") | ||
648 | @mock.patch("market.Market.store_report") | ||
649 | def test_process(self, store_report, log_error, process): | ||
650 | m = market.Market(self.ccxt, self.market_args()) | ||
651 | with self.subTest(before=False, after=False): | ||
652 | m.process(None) | ||
653 | |||
654 | process.assert_not_called() | ||
655 | store_report.assert_called_once() | ||
656 | log_error.assert_not_called() | ||
657 | |||
658 | process.reset_mock() | ||
659 | log_error.reset_mock() | ||
660 | store_report.reset_mock() | ||
661 | with self.subTest(before=True, after=False): | ||
662 | m.process(None, before=True) | ||
663 | |||
664 | process.assert_called_once_with("sell_all", steps="before") | ||
665 | store_report.assert_called_once() | ||
666 | log_error.assert_not_called() | ||
667 | |||
668 | process.reset_mock() | ||
669 | log_error.reset_mock() | ||
670 | store_report.reset_mock() | ||
671 | with self.subTest(before=False, after=True): | ||
672 | m.process(None, after=True) | ||
673 | |||
674 | process.assert_called_once_with("sell_all", steps="after") | ||
675 | store_report.assert_called_once() | ||
676 | log_error.assert_not_called() | ||
677 | |||
678 | process.reset_mock() | ||
679 | log_error.reset_mock() | ||
680 | store_report.reset_mock() | ||
681 | with self.subTest(before=True, after=True): | ||
682 | m.process(None, before=True, after=True) | ||
683 | |||
684 | process.assert_has_calls([ | ||
685 | mock.call("sell_all", steps="before"), | ||
686 | mock.call("sell_all", steps="after"), | ||
687 | ]) | ||
688 | store_report.assert_called_once() | ||
689 | log_error.assert_not_called() | ||
690 | |||
691 | process.reset_mock() | ||
692 | log_error.reset_mock() | ||
693 | store_report.reset_mock() | ||
694 | with self.subTest(action="print_balances"),\ | ||
695 | mock.patch.object(m, "print_balances") as print_balances: | ||
696 | m.process(["print_balances"]) | ||
697 | |||
698 | process.assert_not_called() | ||
699 | log_error.assert_not_called() | ||
700 | store_report.assert_called_once() | ||
701 | print_balances.assert_called_once_with() | ||
702 | |||
703 | log_error.reset_mock() | ||
704 | store_report.reset_mock() | ||
705 | with self.subTest(action="print_orders"),\ | ||
706 | mock.patch.object(m, "print_orders") as print_orders,\ | ||
707 | mock.patch.object(m, "print_balances") as print_balances: | ||
708 | m.process(["print_orders", "print_balances"]) | ||
709 | |||
710 | process.assert_not_called() | ||
711 | log_error.assert_not_called() | ||
712 | store_report.assert_called_once() | ||
713 | print_orders.assert_called_once_with() | ||
714 | print_balances.assert_called_once_with() | ||
715 | |||
716 | log_error.reset_mock() | ||
717 | store_report.reset_mock() | ||
718 | with self.subTest(action="unknown"): | ||
719 | m.process(["unknown"]) | ||
720 | log_error.assert_called_once_with("market_process", message="Unknown action unknown") | ||
721 | store_report.assert_called_once() | ||
722 | |||
723 | log_error.reset_mock() | ||
724 | store_report.reset_mock() | ||
725 | with self.subTest(unhandled_exception=True): | ||
726 | process.side_effect = Exception("bouh") | ||
727 | |||
728 | m.process(None, before=True) | ||
729 | log_error.assert_called_with("market_process", exception=mock.ANY) | ||
730 | store_report.assert_called_once() | ||
731 | |||
732 | |||
733 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
734 | class ProcessorTest(WebMockTestCase): | ||
735 | def test_values(self): | ||
736 | processor = market.Processor(self.m) | ||
737 | |||
738 | self.assertEqual(self.m, processor.market) | ||
739 | |||
740 | def test_run_action(self): | ||
741 | processor = market.Processor(self.m) | ||
742 | |||
743 | with mock.patch.object(processor, "parse_args") as parse_args: | ||
744 | method_mock = mock.Mock() | ||
745 | parse_args.return_value = [method_mock, { "foo": "bar" }] | ||
746 | |||
747 | processor.run_action("foo", "bar", "baz") | ||
748 | |||
749 | parse_args.assert_called_with("foo", "bar", "baz") | ||
750 | |||
751 | method_mock.assert_called_with(foo="bar") | ||
752 | |||
753 | processor.run_action("wait_for_recent", "bar", "baz") | ||
754 | |||
755 | method_mock.assert_called_with(foo="bar") | ||
756 | |||
757 | def test_select_step(self): | ||
758 | processor = market.Processor(self.m) | ||
759 | |||
760 | scenario = processor.scenarios["sell_all"] | ||
761 | |||
762 | self.assertEqual(scenario, processor.select_steps(scenario, "all")) | ||
763 | self.assertEqual(["all_sell"], list(map(lambda x: x["name"], processor.select_steps(scenario, "before")))) | ||
764 | self.assertEqual(["wait", "all_buy"], list(map(lambda x: x["name"], processor.select_steps(scenario, "after")))) | ||
765 | self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, 2)))) | ||
766 | self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, "wait")))) | ||
767 | |||
768 | with self.assertRaises(TypeError): | ||
769 | processor.select_steps(scenario, ["wait"]) | ||
770 | |||
771 | @mock.patch("market.Processor.process_step") | ||
772 | def test_process(self, process_step): | ||
773 | processor = market.Processor(self.m) | ||
774 | |||
775 | processor.process("sell_all", foo="bar") | ||
776 | self.assertEqual(3, process_step.call_count) | ||
777 | |||
778 | steps = list(map(lambda x: x[1][1]["name"], process_step.mock_calls)) | ||
779 | scenario_names = list(map(lambda x: x[1][0], process_step.mock_calls)) | ||
780 | kwargs = list(map(lambda x: x[1][2], process_step.mock_calls)) | ||
781 | self.assertEqual(["all_sell", "wait", "all_buy"], steps) | ||
782 | self.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names) | ||
783 | self.assertEqual([{"foo":"bar"}, {"foo":"bar"}, {"foo":"bar"}], kwargs) | ||
784 | |||
785 | process_step.reset_mock() | ||
786 | |||
787 | processor.process("sell_needed", steps=["before", "after"]) | ||
788 | self.assertEqual(3, process_step.call_count) | ||
789 | |||
790 | def test_method_arguments(self): | ||
791 | ccxt = mock.Mock(spec=market.ccxt.poloniexE) | ||
792 | m = market.Market(ccxt, self.market_args()) | ||
793 | |||
794 | processor = market.Processor(m) | ||
795 | |||
796 | method, arguments = processor.method_arguments("wait_for_recent") | ||
797 | self.assertEqual(market.Portfolio.wait_for_recent, method) | ||
798 | self.assertEqual(["delta", "poll"], arguments) | ||
799 | |||
800 | method, arguments = processor.method_arguments("prepare_trades") | ||
801 | self.assertEqual(m.prepare_trades, method) | ||
802 | self.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments) | ||
803 | |||
804 | method, arguments = processor.method_arguments("prepare_orders") | ||
805 | self.assertEqual(m.trades.prepare_orders, method) | ||
806 | |||
807 | method, arguments = processor.method_arguments("move_balances") | ||
808 | self.assertEqual(m.move_balances, method) | ||
809 | |||
810 | method, arguments = processor.method_arguments("run_orders") | ||
811 | self.assertEqual(m.trades.run_orders, method) | ||
812 | |||
813 | method, arguments = processor.method_arguments("follow_orders") | ||
814 | self.assertEqual(m.follow_orders, method) | ||
815 | |||
816 | method, arguments = processor.method_arguments("close_trades") | ||
817 | self.assertEqual(m.trades.close_trades, method) | ||
818 | |||
819 | def test_process_step(self): | ||
820 | processor = market.Processor(self.m) | ||
821 | |||
822 | with mock.patch.object(processor, "run_action") as run_action: | ||
823 | step = processor.scenarios["sell_needed"][1] | ||
824 | |||
825 | processor.process_step("foo", step, {"foo":"bar"}) | ||
826 | |||
827 | self.m.report.log_stage.assert_has_calls([ | ||
828 | mock.call("process_foo__1_sell_begin"), | ||
829 | mock.call("process_foo__1_sell_end"), | ||
830 | ]) | ||
831 | self.m.balances.fetch_balances.assert_has_calls([ | ||
832 | mock.call(tag="process_foo__1_sell_begin"), | ||
833 | mock.call(tag="process_foo__1_sell_end"), | ||
834 | ]) | ||
835 | |||
836 | self.assertEqual(5, run_action.call_count) | ||
837 | |||
838 | run_action.assert_has_calls([ | ||
839 | mock.call('prepare_trades', {}, {'foo': 'bar'}), | ||
840 | mock.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}, {'foo': 'bar'}), | ||
841 | mock.call('run_orders', {}, {'foo': 'bar'}), | ||
842 | mock.call('follow_orders', {}, {'foo': 'bar'}), | ||
843 | mock.call('close_trades', {}, {'foo': 'bar'}), | ||
844 | ]) | ||
845 | |||
846 | self.m.reset_mock() | ||
847 | with mock.patch.object(processor, "run_action") as run_action: | ||
848 | step = processor.scenarios["sell_needed"][0] | ||
849 | |||
850 | processor.process_step("foo", step, {"foo":"bar"}) | ||
851 | self.m.balances.fetch_balances.assert_not_called() | ||
852 | |||
853 | def test_parse_args(self): | ||
854 | processor = market.Processor(self.m) | ||
855 | |||
856 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
857 | method_mock = mock.Mock() | ||
858 | method_arguments.return_value = [ | ||
859 | method_mock, | ||
860 | ["foo2", "foo"] | ||
861 | ] | ||
862 | method, args = processor.parse_args("action", {"foo": "bar", "foo2": "bar"}, {"foo": "bar2", "bla": "bla"}) | ||
863 | |||
864 | self.assertEqual(method_mock, method) | ||
865 | self.assertEqual({"foo": "bar2", "foo2": "bar"}, args) | ||
866 | |||
867 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
868 | method_mock = mock.Mock() | ||
869 | method_arguments.return_value = [ | ||
870 | method_mock, | ||
871 | ["repartition"] | ||
872 | ] | ||
873 | method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {}) | ||
874 | |||
875 | self.assertEqual(1, len(args["repartition"])) | ||
876 | self.assertIn("BTC", args["repartition"]) | ||
877 | |||
878 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
879 | method_mock = mock.Mock() | ||
880 | method_arguments.return_value = [ | ||
881 | method_mock, | ||
882 | ["repartition", "base_currency"] | ||
883 | ] | ||
884 | method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {"base_currency": "USDT"}) | ||
885 | |||
886 | self.assertEqual(1, len(args["repartition"])) | ||
887 | self.assertIn("USDT", args["repartition"]) | ||
888 | |||
889 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
890 | method_mock = mock.Mock() | ||
891 | method_arguments.return_value = [ | ||
892 | method_mock, | ||
893 | ["repartition", "base_currency"] | ||
894 | ] | ||
895 | method, args = processor.parse_args("action", {"repartition": { "ETH": 1 }}, {"base_currency": "USDT"}) | ||
896 | |||
897 | self.assertEqual(1, len(args["repartition"])) | ||
898 | self.assertIn("ETH", args["repartition"]) | ||
899 | |||
900 | |||
diff --git a/tests/test_portfolio.py b/tests/test_portfolio.py new file mode 100644 index 0000000..a1b95bf --- /dev/null +++ b/tests/test_portfolio.py | |||
@@ -0,0 +1,2036 @@ | |||
1 | from .helper import * | ||
2 | import portfolio | ||
3 | import datetime | ||
4 | |||
5 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
6 | class ComputationTest(WebMockTestCase): | ||
7 | def test_compute_value(self): | ||
8 | compute = mock.Mock() | ||
9 | portfolio.Computation.compute_value("foo", "buy", compute_value=compute) | ||
10 | compute.assert_called_with("foo", "ask") | ||
11 | |||
12 | compute.reset_mock() | ||
13 | portfolio.Computation.compute_value("foo", "sell", compute_value=compute) | ||
14 | compute.assert_called_with("foo", "bid") | ||
15 | |||
16 | compute.reset_mock() | ||
17 | portfolio.Computation.compute_value("foo", "ask", compute_value=compute) | ||
18 | compute.assert_called_with("foo", "ask") | ||
19 | |||
20 | compute.reset_mock() | ||
21 | portfolio.Computation.compute_value("foo", "bid", compute_value=compute) | ||
22 | compute.assert_called_with("foo", "bid") | ||
23 | |||
24 | compute.reset_mock() | ||
25 | portfolio.Computation.computations["test"] = compute | ||
26 | portfolio.Computation.compute_value("foo", "bid", compute_value="test") | ||
27 | compute.assert_called_with("foo", "bid") | ||
28 | |||
29 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
30 | class TradeTest(WebMockTestCase): | ||
31 | |||
32 | def test_values_assertion(self): | ||
33 | value_from = portfolio.Amount("BTC", "1.0") | ||
34 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
35 | value_to = portfolio.Amount("BTC", "1.0") | ||
36 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
37 | self.assertEqual("BTC", trade.base_currency) | ||
38 | self.assertEqual("ETH", trade.currency) | ||
39 | self.assertEqual(self.m, trade.market) | ||
40 | |||
41 | with self.assertRaises(AssertionError): | ||
42 | portfolio.Trade(value_from, -value_to, "ETH", self.m) | ||
43 | with self.assertRaises(AssertionError): | ||
44 | portfolio.Trade(value_from, value_to, "ETC", self.m) | ||
45 | with self.assertRaises(AssertionError): | ||
46 | value_from.currency = "ETH" | ||
47 | portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
48 | value_from.currency = "BTC" | ||
49 | with self.assertRaises(AssertionError): | ||
50 | value_from2 = portfolio.Amount("BTC", "1.0") | ||
51 | portfolio.Trade(value_from2, value_to, "ETH", self.m) | ||
52 | |||
53 | value_from = portfolio.Amount("BTC", 0) | ||
54 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
55 | self.assertEqual(0, trade.value_from.linked_to) | ||
56 | |||
57 | def test_action(self): | ||
58 | value_from = portfolio.Amount("BTC", "1.0") | ||
59 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
60 | value_to = portfolio.Amount("BTC", "1.0") | ||
61 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
62 | |||
63 | self.assertIsNone(trade.action) | ||
64 | |||
65 | value_from = portfolio.Amount("BTC", "1.0") | ||
66 | value_from.linked_to = portfolio.Amount("BTC", "1.0") | ||
67 | value_to = portfolio.Amount("BTC", "2.0") | ||
68 | trade = portfolio.Trade(value_from, value_to, "BTC", self.m) | ||
69 | |||
70 | self.assertIsNone(trade.action) | ||
71 | |||
72 | value_from = portfolio.Amount("BTC", "0.5") | ||
73 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
74 | value_to = portfolio.Amount("BTC", "1.0") | ||
75 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
76 | |||
77 | self.assertEqual("acquire", trade.action) | ||
78 | |||
79 | value_from = portfolio.Amount("BTC", "0") | ||
80 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
81 | value_to = portfolio.Amount("BTC", "-1.0") | ||
82 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
83 | |||
84 | self.assertEqual("acquire", trade.action) | ||
85 | |||
86 | def test_order_action(self): | ||
87 | value_from = portfolio.Amount("BTC", "0.5") | ||
88 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
89 | value_to = portfolio.Amount("BTC", "1.0") | ||
90 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
91 | |||
92 | trade.inverted = False | ||
93 | self.assertEqual("buy", trade.order_action()) | ||
94 | trade.inverted = True | ||
95 | self.assertEqual("sell", trade.order_action()) | ||
96 | |||
97 | value_from = portfolio.Amount("BTC", "0") | ||
98 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
99 | value_to = portfolio.Amount("BTC", "-1.0") | ||
100 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
101 | |||
102 | trade.inverted = False | ||
103 | self.assertEqual("sell", trade.order_action()) | ||
104 | trade.inverted = True | ||
105 | self.assertEqual("buy", trade.order_action()) | ||
106 | |||
107 | def test_trade_type(self): | ||
108 | value_from = portfolio.Amount("BTC", "0.5") | ||
109 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
110 | value_to = portfolio.Amount("BTC", "1.0") | ||
111 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
112 | |||
113 | self.assertEqual("long", trade.trade_type) | ||
114 | |||
115 | value_from = portfolio.Amount("BTC", "0") | ||
116 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
117 | value_to = portfolio.Amount("BTC", "-1.0") | ||
118 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
119 | |||
120 | self.assertEqual("short", trade.trade_type) | ||
121 | |||
122 | def test_is_fullfiled(self): | ||
123 | with self.subTest(inverted=False): | ||
124 | value_from = portfolio.Amount("BTC", "0.5") | ||
125 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
126 | value_to = portfolio.Amount("BTC", "1.0") | ||
127 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
128 | |||
129 | order1 = mock.Mock() | ||
130 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3") | ||
131 | |||
132 | order2 = mock.Mock() | ||
133 | order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01") | ||
134 | trade.orders.append(order1) | ||
135 | trade.orders.append(order2) | ||
136 | |||
137 | self.assertFalse(trade.is_fullfiled) | ||
138 | |||
139 | order3 = mock.Mock() | ||
140 | order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19") | ||
141 | trade.orders.append(order3) | ||
142 | |||
143 | self.assertTrue(trade.is_fullfiled) | ||
144 | |||
145 | order1.filled_amount.assert_called_with(in_base_currency=True) | ||
146 | order2.filled_amount.assert_called_with(in_base_currency=True) | ||
147 | order3.filled_amount.assert_called_with(in_base_currency=True) | ||
148 | |||
149 | with self.subTest(inverted=True): | ||
150 | value_from = portfolio.Amount("BTC", "0.5") | ||
151 | value_from.linked_to = portfolio.Amount("USDT", "1000.0") | ||
152 | value_to = portfolio.Amount("BTC", "1.0") | ||
153 | trade = portfolio.Trade(value_from, value_to, "USDT", self.m) | ||
154 | trade.inverted = True | ||
155 | |||
156 | order1 = mock.Mock() | ||
157 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3") | ||
158 | |||
159 | order2 = mock.Mock() | ||
160 | order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01") | ||
161 | trade.orders.append(order1) | ||
162 | trade.orders.append(order2) | ||
163 | |||
164 | self.assertFalse(trade.is_fullfiled) | ||
165 | |||
166 | order3 = mock.Mock() | ||
167 | order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19") | ||
168 | trade.orders.append(order3) | ||
169 | |||
170 | self.assertTrue(trade.is_fullfiled) | ||
171 | |||
172 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
173 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
174 | order3.filled_amount.assert_called_with(in_base_currency=False) | ||
175 | |||
176 | |||
177 | def test_filled_amount(self): | ||
178 | value_from = portfolio.Amount("BTC", "0.5") | ||
179 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
180 | value_to = portfolio.Amount("BTC", "1.0") | ||
181 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
182 | |||
183 | order1 = mock.Mock() | ||
184 | order1.filled_amount.return_value = portfolio.Amount("ETH", "0.3") | ||
185 | |||
186 | order2 = mock.Mock() | ||
187 | order2.filled_amount.return_value = portfolio.Amount("ETH", "0.01") | ||
188 | trade.orders.append(order1) | ||
189 | trade.orders.append(order2) | ||
190 | |||
191 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount()) | ||
192 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
193 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
194 | |||
195 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=False)) | ||
196 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
197 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
198 | |||
199 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=True)) | ||
200 | order1.filled_amount.assert_called_with(in_base_currency=True) | ||
201 | order2.filled_amount.assert_called_with(in_base_currency=True) | ||
202 | |||
203 | @mock.patch.object(portfolio.Computation, "compute_value") | ||
204 | @mock.patch.object(portfolio.Trade, "filled_amount") | ||
205 | @mock.patch.object(portfolio, "Order") | ||
206 | def test_prepare_order(self, Order, filled_amount, compute_value): | ||
207 | Order.return_value = "Order" | ||
208 | |||
209 | with self.subTest(desc="Nothing to do"): | ||
210 | value_from = portfolio.Amount("BTC", "10") | ||
211 | value_from.rate = D("0.1") | ||
212 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
213 | value_to = portfolio.Amount("BTC", "10") | ||
214 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
215 | |||
216 | trade.prepare_order() | ||
217 | |||
218 | filled_amount.assert_not_called() | ||
219 | compute_value.assert_not_called() | ||
220 | self.assertEqual(0, len(trade.orders)) | ||
221 | Order.assert_not_called() | ||
222 | |||
223 | self.m.get_ticker.return_value = { "inverted": False } | ||
224 | with self.subTest(desc="Already filled"): | ||
225 | filled_amount.return_value = portfolio.Amount("FOO", "100") | ||
226 | compute_value.return_value = D("0.125") | ||
227 | |||
228 | value_from = portfolio.Amount("BTC", "10") | ||
229 | value_from.rate = D("0.1") | ||
230 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
231 | value_to = portfolio.Amount("BTC", "0") | ||
232 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
233 | |||
234 | trade.prepare_order() | ||
235 | |||
236 | filled_amount.assert_called_with(in_base_currency=False) | ||
237 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
238 | self.assertEqual(0, len(trade.orders)) | ||
239 | self.m.report.log_error.assert_called_with("prepare_order", message=mock.ANY) | ||
240 | Order.assert_not_called() | ||
241 | |||
242 | with self.subTest(action="dispose", inverted=False): | ||
243 | filled_amount.return_value = portfolio.Amount("FOO", "60") | ||
244 | compute_value.return_value = D("0.125") | ||
245 | |||
246 | value_from = portfolio.Amount("BTC", "10") | ||
247 | value_from.rate = D("0.1") | ||
248 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
249 | value_to = portfolio.Amount("BTC", "1") | ||
250 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
251 | |||
252 | trade.prepare_order() | ||
253 | |||
254 | filled_amount.assert_called_with(in_base_currency=False) | ||
255 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
256 | self.assertEqual(1, len(trade.orders)) | ||
257 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | ||
258 | D("0.125"), "BTC", "long", self.m, | ||
259 | trade, close_if_possible=False) | ||
260 | |||
261 | with self.subTest(action="dispose", inverted=False, close_if_possible=True): | ||
262 | filled_amount.return_value = portfolio.Amount("FOO", "60") | ||
263 | compute_value.return_value = D("0.125") | ||
264 | |||
265 | value_from = portfolio.Amount("BTC", "10") | ||
266 | value_from.rate = D("0.1") | ||
267 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
268 | value_to = portfolio.Amount("BTC", "1") | ||
269 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
270 | |||
271 | trade.prepare_order(close_if_possible=True) | ||
272 | |||
273 | filled_amount.assert_called_with(in_base_currency=False) | ||
274 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
275 | self.assertEqual(1, len(trade.orders)) | ||
276 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | ||
277 | D("0.125"), "BTC", "long", self.m, | ||
278 | trade, close_if_possible=True) | ||
279 | |||
280 | with self.subTest(action="acquire", inverted=False): | ||
281 | filled_amount.return_value = portfolio.Amount("BTC", "3") | ||
282 | compute_value.return_value = D("0.125") | ||
283 | |||
284 | value_from = portfolio.Amount("BTC", "1") | ||
285 | value_from.rate = D("0.1") | ||
286 | value_from.linked_to = portfolio.Amount("FOO", "10") | ||
287 | value_to = portfolio.Amount("BTC", "10") | ||
288 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
289 | |||
290 | trade.prepare_order() | ||
291 | |||
292 | filled_amount.assert_called_with(in_base_currency=True) | ||
293 | compute_value.assert_called_with(self.m.get_ticker.return_value, "buy", compute_value="default") | ||
294 | self.assertEqual(1, len(trade.orders)) | ||
295 | |||
296 | Order.assert_called_with("buy", portfolio.Amount("FOO", 48), | ||
297 | D("0.125"), "BTC", "long", self.m, | ||
298 | trade, close_if_possible=False) | ||
299 | |||
300 | with self.subTest(close_if_possible=True): | ||
301 | filled_amount.return_value = portfolio.Amount("FOO", "0") | ||
302 | compute_value.return_value = D("0.125") | ||
303 | |||
304 | value_from = portfolio.Amount("BTC", "10") | ||
305 | value_from.rate = D("0.1") | ||
306 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
307 | value_to = portfolio.Amount("BTC", "0") | ||
308 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
309 | |||
310 | trade.prepare_order() | ||
311 | |||
312 | filled_amount.assert_called_with(in_base_currency=False) | ||
313 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
314 | self.assertEqual(1, len(trade.orders)) | ||
315 | Order.assert_called_with("sell", portfolio.Amount("FOO", 100), | ||
316 | D("0.125"), "BTC", "long", self.m, | ||
317 | trade, close_if_possible=True) | ||
318 | |||
319 | self.m.get_ticker.return_value = { "inverted": True, "original": {} } | ||
320 | with self.subTest(action="dispose", inverted=True): | ||
321 | filled_amount.return_value = portfolio.Amount("FOO", "300") | ||
322 | compute_value.return_value = D("125") | ||
323 | |||
324 | value_from = portfolio.Amount("BTC", "10") | ||
325 | value_from.rate = D("0.01") | ||
326 | value_from.linked_to = portfolio.Amount("FOO", "1000") | ||
327 | value_to = portfolio.Amount("BTC", "1") | ||
328 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
329 | |||
330 | trade.prepare_order(compute_value="foo") | ||
331 | |||
332 | filled_amount.assert_called_with(in_base_currency=True) | ||
333 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "buy", compute_value="foo") | ||
334 | self.assertEqual(1, len(trade.orders)) | ||
335 | Order.assert_called_with("buy", portfolio.Amount("BTC", D("4.8")), | ||
336 | D("125"), "FOO", "long", self.m, | ||
337 | trade, close_if_possible=False) | ||
338 | |||
339 | with self.subTest(action="acquire", inverted=True): | ||
340 | filled_amount.return_value = portfolio.Amount("BTC", "4") | ||
341 | compute_value.return_value = D("125") | ||
342 | |||
343 | value_from = portfolio.Amount("BTC", "1") | ||
344 | value_from.rate = D("0.01") | ||
345 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
346 | value_to = portfolio.Amount("BTC", "10") | ||
347 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
348 | |||
349 | trade.prepare_order(compute_value="foo") | ||
350 | |||
351 | filled_amount.assert_called_with(in_base_currency=False) | ||
352 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "sell", compute_value="foo") | ||
353 | self.assertEqual(1, len(trade.orders)) | ||
354 | Order.assert_called_with("sell", portfolio.Amount("BTC", D("5")), | ||
355 | D("125"), "FOO", "long", self.m, | ||
356 | trade, close_if_possible=False) | ||
357 | |||
358 | def test_tick_actions_recreate(self): | ||
359 | value_from = portfolio.Amount("BTC", "0.5") | ||
360 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
361 | value_to = portfolio.Amount("BTC", "1.0") | ||
362 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
363 | |||
364 | self.assertEqual("average", trade.tick_actions_recreate(0)) | ||
365 | self.assertEqual("foo", trade.tick_actions_recreate(0, default="foo")) | ||
366 | self.assertEqual("average", trade.tick_actions_recreate(1)) | ||
367 | self.assertEqual(trade.tick_actions[2][1], trade.tick_actions_recreate(2)) | ||
368 | self.assertEqual(trade.tick_actions[2][1], trade.tick_actions_recreate(3)) | ||
369 | self.assertEqual(trade.tick_actions[5][1], trade.tick_actions_recreate(5)) | ||
370 | self.assertEqual(trade.tick_actions[5][1], trade.tick_actions_recreate(6)) | ||
371 | self.assertEqual("default", trade.tick_actions_recreate(7)) | ||
372 | self.assertEqual("default", trade.tick_actions_recreate(8)) | ||
373 | |||
374 | @mock.patch.object(portfolio.Trade, "prepare_order") | ||
375 | def test_update_order(self, prepare_order): | ||
376 | order_mock = mock.Mock() | ||
377 | new_order_mock = mock.Mock() | ||
378 | |||
379 | value_from = portfolio.Amount("BTC", "0.5") | ||
380 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
381 | value_to = portfolio.Amount("BTC", "1.0") | ||
382 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
383 | prepare_order.return_value = new_order_mock | ||
384 | |||
385 | for i in [0, 1, 3, 4, 6]: | ||
386 | with self.subTest(tick=i): | ||
387 | trade.update_order(order_mock, i) | ||
388 | order_mock.cancel.assert_not_called() | ||
389 | new_order_mock.run.assert_not_called() | ||
390 | self.m.report.log_order.assert_called_once_with(order_mock, i, | ||
391 | update="waiting", compute_value=None, new_order=None) | ||
392 | |||
393 | order_mock.reset_mock() | ||
394 | new_order_mock.reset_mock() | ||
395 | trade.orders = [] | ||
396 | self.m.report.log_order.reset_mock() | ||
397 | |||
398 | trade.update_order(order_mock, 2) | ||
399 | order_mock.cancel.assert_called() | ||
400 | new_order_mock.run.assert_called() | ||
401 | prepare_order.assert_called() | ||
402 | self.m.report.log_order.assert_called() | ||
403 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
404 | calls = [ | ||
405 | mock.call(order_mock, 2, update="adjusting", | ||
406 | compute_value=mock.ANY, | ||
407 | new_order=new_order_mock), | ||
408 | mock.call(order_mock, 2, new_order=new_order_mock), | ||
409 | ] | ||
410 | self.m.report.log_order.assert_has_calls(calls) | ||
411 | |||
412 | order_mock.reset_mock() | ||
413 | new_order_mock.reset_mock() | ||
414 | trade.orders = [] | ||
415 | self.m.report.log_order.reset_mock() | ||
416 | |||
417 | trade.update_order(order_mock, 5) | ||
418 | order_mock.cancel.assert_called() | ||
419 | new_order_mock.run.assert_called() | ||
420 | prepare_order.assert_called() | ||
421 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
422 | self.m.report.log_order.assert_called() | ||
423 | calls = [ | ||
424 | mock.call(order_mock, 5, update="adjusting", | ||
425 | compute_value=mock.ANY, | ||
426 | new_order=new_order_mock), | ||
427 | mock.call(order_mock, 5, new_order=new_order_mock), | ||
428 | ] | ||
429 | self.m.report.log_order.assert_has_calls(calls) | ||
430 | |||
431 | order_mock.reset_mock() | ||
432 | new_order_mock.reset_mock() | ||
433 | trade.orders = [] | ||
434 | self.m.report.log_order.reset_mock() | ||
435 | |||
436 | trade.update_order(order_mock, 7) | ||
437 | order_mock.cancel.assert_called() | ||
438 | new_order_mock.run.assert_called() | ||
439 | prepare_order.assert_called_with(compute_value="default") | ||
440 | self.m.report.log_order.assert_called() | ||
441 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
442 | calls = [ | ||
443 | mock.call(order_mock, 7, update="market_fallback", | ||
444 | compute_value='default', | ||
445 | new_order=new_order_mock), | ||
446 | mock.call(order_mock, 7, new_order=new_order_mock), | ||
447 | ] | ||
448 | self.m.report.log_order.assert_has_calls(calls) | ||
449 | |||
450 | order_mock.reset_mock() | ||
451 | new_order_mock.reset_mock() | ||
452 | trade.orders = [] | ||
453 | self.m.report.log_order.reset_mock() | ||
454 | |||
455 | for i in [10, 13, 16]: | ||
456 | with self.subTest(tick=i): | ||
457 | trade.update_order(order_mock, i) | ||
458 | order_mock.cancel.assert_called() | ||
459 | new_order_mock.run.assert_called() | ||
460 | prepare_order.assert_called_with(compute_value="default") | ||
461 | self.m.report.log_order.assert_called() | ||
462 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
463 | calls = [ | ||
464 | mock.call(order_mock, i, update="market_adjust", | ||
465 | compute_value='default', | ||
466 | new_order=new_order_mock), | ||
467 | mock.call(order_mock, i, new_order=new_order_mock), | ||
468 | ] | ||
469 | self.m.report.log_order.assert_has_calls(calls) | ||
470 | |||
471 | order_mock.reset_mock() | ||
472 | new_order_mock.reset_mock() | ||
473 | trade.orders = [] | ||
474 | self.m.report.log_order.reset_mock() | ||
475 | |||
476 | for i in [8, 9, 11, 12]: | ||
477 | with self.subTest(tick=i): | ||
478 | trade.update_order(order_mock, i) | ||
479 | order_mock.cancel.assert_not_called() | ||
480 | new_order_mock.run.assert_not_called() | ||
481 | self.m.report.log_order.assert_called_once_with(order_mock, i, update="waiting", | ||
482 | compute_value=None, new_order=None) | ||
483 | |||
484 | order_mock.reset_mock() | ||
485 | new_order_mock.reset_mock() | ||
486 | trade.orders = [] | ||
487 | self.m.report.log_order.reset_mock() | ||
488 | |||
489 | |||
490 | def test_print_with_order(self): | ||
491 | value_from = portfolio.Amount("BTC", "0.5") | ||
492 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
493 | value_to = portfolio.Amount("BTC", "1.0") | ||
494 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
495 | |||
496 | order_mock1 = mock.Mock() | ||
497 | order_mock1.__repr__ = mock.Mock() | ||
498 | order_mock1.__repr__.return_value = "Mock 1" | ||
499 | order_mock2 = mock.Mock() | ||
500 | order_mock2.__repr__ = mock.Mock() | ||
501 | order_mock2.__repr__.return_value = "Mock 2" | ||
502 | order_mock1.mouvements = [] | ||
503 | mouvement_mock1 = mock.Mock() | ||
504 | mouvement_mock1.__repr__ = mock.Mock() | ||
505 | mouvement_mock1.__repr__.return_value = "Mouvement 1" | ||
506 | mouvement_mock2 = mock.Mock() | ||
507 | mouvement_mock2.__repr__ = mock.Mock() | ||
508 | mouvement_mock2.__repr__.return_value = "Mouvement 2" | ||
509 | order_mock2.mouvements = [ | ||
510 | mouvement_mock1, mouvement_mock2 | ||
511 | ] | ||
512 | trade.orders.append(order_mock1) | ||
513 | trade.orders.append(order_mock2) | ||
514 | |||
515 | with mock.patch.object(trade, "filled_amount") as filled: | ||
516 | filled.return_value = portfolio.Amount("BTC", "0.1") | ||
517 | |||
518 | trade.print_with_order() | ||
519 | |||
520 | self.m.report.print_log.assert_called() | ||
521 | calls = self.m.report.print_log.mock_calls | ||
522 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls[0][1][0])) | ||
523 | self.assertEqual("\tMock 1", str(calls[1][1][0])) | ||
524 | self.assertEqual("\tMock 2", str(calls[2][1][0])) | ||
525 | self.assertEqual("\t\tMouvement 1", str(calls[3][1][0])) | ||
526 | self.assertEqual("\t\tMouvement 2", str(calls[4][1][0])) | ||
527 | |||
528 | self.m.report.print_log.reset_mock() | ||
529 | |||
530 | filled.return_value = portfolio.Amount("BTC", "0.5") | ||
531 | trade.print_with_order() | ||
532 | calls = self.m.report.print_log.mock_calls | ||
533 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls[0][1][0])) | ||
534 | |||
535 | self.m.report.print_log.reset_mock() | ||
536 | |||
537 | filled.return_value = portfolio.Amount("BTC", "0.1") | ||
538 | trade.closed = True | ||
539 | trade.print_with_order() | ||
540 | calls = self.m.report.print_log.mock_calls | ||
541 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls[0][1][0])) | ||
542 | |||
543 | def test_close(self): | ||
544 | value_from = portfolio.Amount("BTC", "0.5") | ||
545 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
546 | value_to = portfolio.Amount("BTC", "1.0") | ||
547 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
548 | order1 = mock.Mock() | ||
549 | trade.orders.append(order1) | ||
550 | |||
551 | trade.close() | ||
552 | |||
553 | self.assertEqual(True, trade.closed) | ||
554 | order1.cancel.assert_called_once_with() | ||
555 | |||
556 | def test_pending(self): | ||
557 | value_from = portfolio.Amount("BTC", "0.5") | ||
558 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
559 | value_to = portfolio.Amount("BTC", "1.0") | ||
560 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
561 | |||
562 | trade.closed = True | ||
563 | self.assertEqual(False, trade.pending) | ||
564 | |||
565 | trade.closed = False | ||
566 | self.assertEqual(True, trade.pending) | ||
567 | |||
568 | order1 = mock.Mock() | ||
569 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.5") | ||
570 | trade.orders.append(order1) | ||
571 | self.assertEqual(False, trade.pending) | ||
572 | |||
573 | def test__repr(self): | ||
574 | value_from = portfolio.Amount("BTC", "0.5") | ||
575 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
576 | value_to = portfolio.Amount("BTC", "1.0") | ||
577 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
578 | |||
579 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade)) | ||
580 | |||
581 | def test_as_json(self): | ||
582 | value_from = portfolio.Amount("BTC", "0.5") | ||
583 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
584 | value_to = portfolio.Amount("BTC", "1.0") | ||
585 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
586 | |||
587 | as_json = trade.as_json() | ||
588 | self.assertEqual("acquire", as_json["action"]) | ||
589 | self.assertEqual(D("0.5"), as_json["from"]) | ||
590 | self.assertEqual(D("1.0"), as_json["to"]) | ||
591 | self.assertEqual("ETH", as_json["currency"]) | ||
592 | self.assertEqual("BTC", as_json["base_currency"]) | ||
593 | |||
594 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
595 | class BalanceTest(WebMockTestCase): | ||
596 | def test_values(self): | ||
597 | balance = portfolio.Balance("BTC", { | ||
598 | "exchange_total": "0.65", | ||
599 | "exchange_free": "0.35", | ||
600 | "exchange_used": "0.30", | ||
601 | "margin_total": "-10", | ||
602 | "margin_borrowed": "10", | ||
603 | "margin_available": "0", | ||
604 | "margin_in_position": "0", | ||
605 | "margin_position_type": "short", | ||
606 | "margin_borrowed_base_currency": "USDT", | ||
607 | "margin_liquidation_price": "1.20", | ||
608 | "margin_pending_gain": "10", | ||
609 | "margin_lending_fees": "0.4", | ||
610 | "margin_borrowed_base_price": "0.15", | ||
611 | }) | ||
612 | self.assertEqual(portfolio.D("0.65"), balance.exchange_total.value) | ||
613 | self.assertEqual(portfolio.D("0.35"), balance.exchange_free.value) | ||
614 | self.assertEqual(portfolio.D("0.30"), balance.exchange_used.value) | ||
615 | self.assertEqual("BTC", balance.exchange_total.currency) | ||
616 | self.assertEqual("BTC", balance.exchange_free.currency) | ||
617 | self.assertEqual("BTC", balance.exchange_total.currency) | ||
618 | |||
619 | self.assertEqual(portfolio.D("-10"), balance.margin_total.value) | ||
620 | self.assertEqual(portfolio.D("10"), balance.margin_borrowed.value) | ||
621 | self.assertEqual(portfolio.D("0"), balance.margin_available.value) | ||
622 | self.assertEqual("BTC", balance.margin_total.currency) | ||
623 | self.assertEqual("BTC", balance.margin_borrowed.currency) | ||
624 | self.assertEqual("BTC", balance.margin_available.currency) | ||
625 | |||
626 | self.assertEqual("BTC", balance.currency) | ||
627 | |||
628 | self.assertEqual(portfolio.D("0.4"), balance.margin_lending_fees.value) | ||
629 | self.assertEqual("USDT", balance.margin_lending_fees.currency) | ||
630 | |||
631 | def test__repr(self): | ||
632 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])", | ||
633 | repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }))) | ||
634 | balance = portfolio.Balance("BTX", { "exchange_total": 3, | ||
635 | "exchange_used": 1, "exchange_free": 2 }) | ||
636 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | ||
637 | |||
638 | balance = portfolio.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}) | ||
639 | self.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance)) | ||
640 | |||
641 | balance = portfolio.Balance("BTX", { "margin_total": 3, | ||
642 | "margin_in_position": 1, "margin_available": 2 }) | ||
643 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | ||
644 | |||
645 | balance = portfolio.Balance("BTX", { "margin_total": 2, "margin_available": 2 }) | ||
646 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance)) | ||
647 | |||
648 | balance = portfolio.Balance("BTX", { "margin_total": -3, | ||
649 | "margin_borrowed_base_price": D("0.1"), | ||
650 | "margin_borrowed_base_currency": "BTC", | ||
651 | "margin_lending_fees": D("0.002") }) | ||
652 | self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance)) | ||
653 | |||
654 | balance = portfolio.Balance("BTX", { "margin_total": 1, | ||
655 | "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2}) | ||
656 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance)) | ||
657 | |||
658 | def test_as_json(self): | ||
659 | balance = portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }) | ||
660 | as_json = balance.as_json() | ||
661 | self.assertEqual(set(portfolio.Balance.base_keys), set(as_json.keys())) | ||
662 | self.assertEqual(D(0), as_json["total"]) | ||
663 | self.assertEqual(D(2), as_json["exchange_total"]) | ||
664 | self.assertEqual(D(2), as_json["exchange_free"]) | ||
665 | self.assertEqual(D(0), as_json["exchange_used"]) | ||
666 | self.assertEqual(D(0), as_json["margin_total"]) | ||
667 | self.assertEqual(D(0), as_json["margin_available"]) | ||
668 | self.assertEqual(D(0), as_json["margin_borrowed"]) | ||
669 | |||
670 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
671 | class OrderTest(WebMockTestCase): | ||
672 | def test_values(self): | ||
673 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
674 | D("0.1"), "BTC", "long", "market", "trade") | ||
675 | self.assertEqual("buy", order.action) | ||
676 | self.assertEqual(10, order.amount.value) | ||
677 | self.assertEqual("ETH", order.amount.currency) | ||
678 | self.assertEqual(D("0.1"), order.rate) | ||
679 | self.assertEqual("BTC", order.base_currency) | ||
680 | self.assertEqual("market", order.market) | ||
681 | self.assertEqual("long", order.trade_type) | ||
682 | self.assertEqual("pending", order.status) | ||
683 | self.assertEqual("trade", order.trade) | ||
684 | self.assertIsNone(order.id) | ||
685 | self.assertFalse(order.close_if_possible) | ||
686 | |||
687 | def test__repr(self): | ||
688 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
689 | D("0.1"), "BTC", "long", "market", "trade") | ||
690 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order)) | ||
691 | |||
692 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
693 | D("0.1"), "BTC", "long", "market", "trade", | ||
694 | close_if_possible=True) | ||
695 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order)) | ||
696 | |||
697 | def test_as_json(self): | ||
698 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
699 | D("0.1"), "BTC", "long", "market", "trade") | ||
700 | mouvement_mock1 = mock.Mock() | ||
701 | mouvement_mock1.as_json.return_value = 1 | ||
702 | mouvement_mock2 = mock.Mock() | ||
703 | mouvement_mock2.as_json.return_value = 2 | ||
704 | |||
705 | order.mouvements = [mouvement_mock1, mouvement_mock2] | ||
706 | as_json = order.as_json() | ||
707 | self.assertEqual("buy", as_json["action"]) | ||
708 | self.assertEqual("long", as_json["trade_type"]) | ||
709 | self.assertEqual(10, as_json["amount"]) | ||
710 | self.assertEqual("ETH", as_json["currency"]) | ||
711 | self.assertEqual("BTC", as_json["base_currency"]) | ||
712 | self.assertEqual(D("0.1"), as_json["rate"]) | ||
713 | self.assertEqual("pending", as_json["status"]) | ||
714 | self.assertEqual(False, as_json["close_if_possible"]) | ||
715 | self.assertIsNone(as_json["id"]) | ||
716 | self.assertEqual([1, 2], as_json["mouvements"]) | ||
717 | |||
718 | def test_account(self): | ||
719 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
720 | D("0.1"), "BTC", "long", "market", "trade") | ||
721 | self.assertEqual("exchange", order.account) | ||
722 | |||
723 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | ||
724 | D("0.1"), "BTC", "short", "market", "trade") | ||
725 | self.assertEqual("margin", order.account) | ||
726 | |||
727 | def test_pending(self): | ||
728 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
729 | D("0.1"), "BTC", "long", "market", "trade") | ||
730 | self.assertTrue(order.pending) | ||
731 | order.status = "open" | ||
732 | self.assertFalse(order.pending) | ||
733 | |||
734 | def test_open(self): | ||
735 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
736 | D("0.1"), "BTC", "long", "market", "trade") | ||
737 | self.assertFalse(order.open) | ||
738 | order.status = "open" | ||
739 | self.assertTrue(order.open) | ||
740 | |||
741 | def test_finished(self): | ||
742 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
743 | D("0.1"), "BTC", "long", "market", "trade") | ||
744 | self.assertFalse(order.finished) | ||
745 | order.status = "closed" | ||
746 | self.assertTrue(order.finished) | ||
747 | order.status = "canceled" | ||
748 | self.assertTrue(order.finished) | ||
749 | order.status = "error" | ||
750 | self.assertTrue(order.finished) | ||
751 | |||
752 | @mock.patch.object(portfolio.Order, "fetch") | ||
753 | def test_cancel(self, fetch): | ||
754 | with self.subTest(debug=True): | ||
755 | self.m.debug = True | ||
756 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
757 | D("0.1"), "BTC", "long", self.m, "trade") | ||
758 | order.status = "open" | ||
759 | |||
760 | order.cancel() | ||
761 | self.m.ccxt.cancel_order.assert_not_called() | ||
762 | self.m.report.log_debug_action.assert_called_once() | ||
763 | self.m.report.log_debug_action.reset_mock() | ||
764 | self.assertEqual("canceled", order.status) | ||
765 | |||
766 | with self.subTest(desc="Nominal case"): | ||
767 | self.m.debug = False | ||
768 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
769 | D("0.1"), "BTC", "long", self.m, "trade") | ||
770 | order.status = "open" | ||
771 | order.id = 42 | ||
772 | |||
773 | order.cancel() | ||
774 | self.m.ccxt.cancel_order.assert_called_with(42) | ||
775 | fetch.assert_called_once_with() | ||
776 | self.m.report.log_debug_action.assert_not_called() | ||
777 | |||
778 | with self.subTest(exception=True): | ||
779 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
780 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
781 | D("0.1"), "BTC", "long", self.m, "trade") | ||
782 | order.status = "open" | ||
783 | order.id = 42 | ||
784 | order.cancel() | ||
785 | self.m.ccxt.cancel_order.assert_called_with(42) | ||
786 | self.m.report.log_error.assert_called_once() | ||
787 | |||
788 | self.m.reset_mock() | ||
789 | with self.subTest(id=None): | ||
790 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
791 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
792 | D("0.1"), "BTC", "long", self.m, "trade") | ||
793 | order.status = "open" | ||
794 | order.cancel() | ||
795 | self.m.ccxt.cancel_order.assert_not_called() | ||
796 | |||
797 | self.m.reset_mock() | ||
798 | with self.subTest(open=False): | ||
799 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
800 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
801 | D("0.1"), "BTC", "long", self.m, "trade") | ||
802 | order.status = "closed" | ||
803 | order.cancel() | ||
804 | self.m.ccxt.cancel_order.assert_not_called() | ||
805 | |||
806 | def test_dust_amount_remaining(self): | ||
807 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
808 | D("0.1"), "BTC", "long", self.m, "trade") | ||
809 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", 1)) | ||
810 | self.assertFalse(order.dust_amount_remaining()) | ||
811 | |||
812 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", D("0.0001"))) | ||
813 | self.assertTrue(order.dust_amount_remaining()) | ||
814 | |||
815 | @mock.patch.object(portfolio.Order, "fetch") | ||
816 | @mock.patch.object(portfolio.Order, "filled_amount", return_value=portfolio.Amount("ETH", 1)) | ||
817 | def test_remaining_amount(self, filled_amount, fetch): | ||
818 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
819 | D("0.1"), "BTC", "long", self.m, "trade") | ||
820 | |||
821 | self.assertEqual(9, order.remaining_amount().value) | ||
822 | |||
823 | order.status = "open" | ||
824 | self.assertEqual(9, order.remaining_amount().value) | ||
825 | |||
826 | @mock.patch.object(portfolio.Order, "fetch") | ||
827 | def test_filled_amount(self, fetch): | ||
828 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
829 | D("0.1"), "BTC", "long", self.m, "trade") | ||
830 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | ||
831 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
832 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
833 | "amount": "3", "total": "0.3" | ||
834 | })) | ||
835 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | ||
836 | "tradeID": 43, "type": "buy", "fee": "0.0015", | ||
837 | "date": "2017-12-30 13:00:12", "rate": "0.2", | ||
838 | "amount": "2", "total": "0.4" | ||
839 | })) | ||
840 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount()) | ||
841 | fetch.assert_not_called() | ||
842 | order.status = "open" | ||
843 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount(in_base_currency=False)) | ||
844 | fetch.assert_called_once() | ||
845 | self.assertEqual(portfolio.Amount("BTC", "0.7"), order.filled_amount(in_base_currency=True)) | ||
846 | |||
847 | def test_fetch_mouvements(self): | ||
848 | self.m.ccxt.privatePostReturnOrderTrades.return_value = [ | ||
849 | { | ||
850 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
851 | "date": "2017-12-30 13:00:12", "rate": "0.1", | ||
852 | "amount": "3", "total": "0.3" | ||
853 | }, | ||
854 | { | ||
855 | "tradeID": 43, "type": "buy", "fee": "0.0015", | ||
856 | "date": "2017-12-30 12:00:12", "rate": "0.2", | ||
857 | "amount": "2", "total": "0.4" | ||
858 | } | ||
859 | ] | ||
860 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
861 | D("0.1"), "BTC", "long", self.m, "trade") | ||
862 | order.id = 12 | ||
863 | order.mouvements = ["Foo", "Bar", "Baz"] | ||
864 | |||
865 | order.fetch_mouvements() | ||
866 | |||
867 | self.m.ccxt.privatePostReturnOrderTrades.assert_called_with({"orderNumber": 12}) | ||
868 | self.assertEqual(2, len(order.mouvements)) | ||
869 | self.assertEqual(43, order.mouvements[0].id) | ||
870 | self.assertEqual(42, order.mouvements[1].id) | ||
871 | |||
872 | self.m.ccxt.privatePostReturnOrderTrades.side_effect = portfolio.ExchangeError | ||
873 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
874 | D("0.1"), "BTC", "long", self.m, "trade") | ||
875 | order.fetch_mouvements() | ||
876 | self.assertEqual(0, len(order.mouvements)) | ||
877 | |||
878 | def test_mark_finished_order(self): | ||
879 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
880 | D("0.1"), "BTC", "short", self.m, "trade", | ||
881 | close_if_possible=True) | ||
882 | order.status = "closed" | ||
883 | self.m.debug = False | ||
884 | |||
885 | order.mark_finished_order() | ||
886 | self.m.ccxt.close_margin_position.assert_called_with("ETH", "BTC") | ||
887 | self.m.ccxt.close_margin_position.reset_mock() | ||
888 | |||
889 | order.status = "open" | ||
890 | order.mark_finished_order() | ||
891 | self.m.ccxt.close_margin_position.assert_not_called() | ||
892 | |||
893 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
894 | D("0.1"), "BTC", "short", self.m, "trade", | ||
895 | close_if_possible=False) | ||
896 | order.status = "closed" | ||
897 | order.mark_finished_order() | ||
898 | self.m.ccxt.close_margin_position.assert_not_called() | ||
899 | |||
900 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | ||
901 | D("0.1"), "BTC", "short", self.m, "trade", | ||
902 | close_if_possible=True) | ||
903 | order.status = "closed" | ||
904 | order.mark_finished_order() | ||
905 | self.m.ccxt.close_margin_position.assert_not_called() | ||
906 | |||
907 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
908 | D("0.1"), "BTC", "long", self.m, "trade", | ||
909 | close_if_possible=True) | ||
910 | order.status = "closed" | ||
911 | order.mark_finished_order() | ||
912 | self.m.ccxt.close_margin_position.assert_not_called() | ||
913 | |||
914 | self.m.debug = True | ||
915 | |||
916 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
917 | D("0.1"), "BTC", "short", self.m, "trade", | ||
918 | close_if_possible=True) | ||
919 | order.status = "closed" | ||
920 | |||
921 | order.mark_finished_order() | ||
922 | self.m.ccxt.close_margin_position.assert_not_called() | ||
923 | self.m.report.log_debug_action.assert_called_once() | ||
924 | |||
925 | @mock.patch.object(portfolio.Order, "fetch_mouvements") | ||
926 | @mock.patch.object(portfolio.Order, "mark_disappeared_order") | ||
927 | @mock.patch.object(portfolio.Order, "mark_finished_order") | ||
928 | def test_fetch(self, mark_finished_order, mark_disappeared_order, fetch_mouvements): | ||
929 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
930 | D("0.1"), "BTC", "long", self.m, "trade") | ||
931 | order.id = 45 | ||
932 | with self.subTest(debug=True): | ||
933 | self.m.debug = True | ||
934 | order.fetch() | ||
935 | self.m.report.log_debug_action.assert_called_once() | ||
936 | self.m.report.log_debug_action.reset_mock() | ||
937 | self.m.ccxt.fetch_order.assert_not_called() | ||
938 | mark_finished_order.assert_not_called() | ||
939 | mark_disappeared_order.assert_not_called() | ||
940 | fetch_mouvements.assert_not_called() | ||
941 | |||
942 | with self.subTest(debug=False): | ||
943 | self.m.debug = False | ||
944 | self.m.ccxt.fetch_order.return_value = { | ||
945 | "status": "foo", | ||
946 | "datetime": "timestamp" | ||
947 | } | ||
948 | order.fetch() | ||
949 | |||
950 | self.m.ccxt.fetch_order.assert_called_once_with(45) | ||
951 | fetch_mouvements.assert_called_once() | ||
952 | self.assertEqual("foo", order.status) | ||
953 | self.assertEqual("timestamp", order.timestamp) | ||
954 | self.assertEqual(1, len(order.results)) | ||
955 | self.m.report.log_debug_action.assert_not_called() | ||
956 | mark_finished_order.assert_called_once() | ||
957 | mark_disappeared_order.assert_called_once() | ||
958 | |||
959 | mark_finished_order.reset_mock() | ||
960 | with self.subTest(missing_order=True): | ||
961 | self.m.ccxt.fetch_order.side_effect = [ | ||
962 | portfolio.OrderNotCached, | ||
963 | ] | ||
964 | order.fetch() | ||
965 | self.assertEqual("closed_unknown", order.status) | ||
966 | mark_finished_order.assert_called_once() | ||
967 | |||
968 | def test_mark_disappeared_order(self): | ||
969 | with self.subTest("Open order"): | ||
970 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
971 | D("0.1"), "BTC", "long", self.m, "trade") | ||
972 | order.id = 45 | ||
973 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
974 | "tradeID":21336541, | ||
975 | "currencyPair":"BTC_XRP", | ||
976 | "type":"sell", | ||
977 | "rate":"0.00007013", | ||
978 | "amount":"0.00000222", | ||
979 | "total":"0.00000000", | ||
980 | "fee":"0.00150000", | ||
981 | "date":"2018-04-02 00:09:13" | ||
982 | })) | ||
983 | order.mark_disappeared_order() | ||
984 | self.assertEqual("pending", order.status) | ||
985 | |||
986 | with self.subTest("Non-zero amount"): | ||
987 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
988 | D("0.1"), "BTC", "long", self.m, "trade") | ||
989 | order.id = 45 | ||
990 | order.status = "closed" | ||
991 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
992 | "tradeID":21336541, | ||
993 | "currencyPair":"BTC_XRP", | ||
994 | "type":"sell", | ||
995 | "rate":"0.00007013", | ||
996 | "amount":"0.00000222", | ||
997 | "total":"0.00000010", | ||
998 | "fee":"0.00150000", | ||
999 | "date":"2018-04-02 00:09:13" | ||
1000 | })) | ||
1001 | order.mark_disappeared_order() | ||
1002 | self.assertEqual("closed", order.status) | ||
1003 | |||
1004 | with self.subTest("Other mouvements"): | ||
1005 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1006 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1007 | order.id = 45 | ||
1008 | order.status = "closed" | ||
1009 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
1010 | "tradeID":21336541, | ||
1011 | "currencyPair":"BTC_XRP", | ||
1012 | "type":"sell", | ||
1013 | "rate":"0.00007013", | ||
1014 | "amount":"0.00000222", | ||
1015 | "total":"0.00000001", | ||
1016 | "fee":"0.00150000", | ||
1017 | "date":"2018-04-02 00:09:13" | ||
1018 | })) | ||
1019 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
1020 | "tradeID":21336541, | ||
1021 | "currencyPair":"BTC_XRP", | ||
1022 | "type":"sell", | ||
1023 | "rate":"0.00007013", | ||
1024 | "amount":"0.00000222", | ||
1025 | "total":"0.00000000", | ||
1026 | "fee":"0.00150000", | ||
1027 | "date":"2018-04-02 00:09:13" | ||
1028 | })) | ||
1029 | order.mark_disappeared_order() | ||
1030 | self.assertEqual("error_disappeared", order.status) | ||
1031 | |||
1032 | with self.subTest("Order disappeared"): | ||
1033 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1034 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1035 | order.id = 45 | ||
1036 | order.status = "closed" | ||
1037 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
1038 | "tradeID":21336541, | ||
1039 | "currencyPair":"BTC_XRP", | ||
1040 | "type":"sell", | ||
1041 | "rate":"0.00007013", | ||
1042 | "amount":"0.00000222", | ||
1043 | "total":"0.00000000", | ||
1044 | "fee":"0.00150000", | ||
1045 | "date":"2018-04-02 00:09:13" | ||
1046 | })) | ||
1047 | order.mark_disappeared_order() | ||
1048 | self.assertEqual("error_disappeared", order.status) | ||
1049 | |||
1050 | @mock.patch.object(portfolio.Order, "fetch") | ||
1051 | def test_get_status(self, fetch): | ||
1052 | with self.subTest(debug=True): | ||
1053 | self.m.debug = True | ||
1054 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1055 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1056 | self.assertEqual("pending", order.get_status()) | ||
1057 | fetch.assert_not_called() | ||
1058 | self.m.report.log_debug_action.assert_called_once() | ||
1059 | |||
1060 | with self.subTest(debug=False, finished=False): | ||
1061 | self.m.debug = False | ||
1062 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1063 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1064 | def _fetch(order): | ||
1065 | def update_status(): | ||
1066 | order.status = "open" | ||
1067 | return update_status | ||
1068 | fetch.side_effect = _fetch(order) | ||
1069 | self.assertEqual("open", order.get_status()) | ||
1070 | fetch.assert_called_once() | ||
1071 | |||
1072 | fetch.reset_mock() | ||
1073 | with self.subTest(debug=False, finished=True): | ||
1074 | self.m.debug = False | ||
1075 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1076 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1077 | def _fetch(order): | ||
1078 | def update_status(): | ||
1079 | order.status = "closed" | ||
1080 | return update_status | ||
1081 | fetch.side_effect = _fetch(order) | ||
1082 | self.assertEqual("closed", order.get_status()) | ||
1083 | fetch.assert_called_once() | ||
1084 | |||
1085 | def test_run(self): | ||
1086 | self.m.ccxt.order_precision.return_value = 4 | ||
1087 | with self.subTest(debug=True): | ||
1088 | self.m.debug = True | ||
1089 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1090 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1091 | order.run() | ||
1092 | self.m.ccxt.create_order.assert_not_called() | ||
1093 | self.m.report.log_debug_action.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)") | ||
1094 | self.assertEqual("open", order.status) | ||
1095 | self.assertEqual(1, len(order.results)) | ||
1096 | self.assertEqual(-1, order.id) | ||
1097 | |||
1098 | self.m.ccxt.create_order.reset_mock() | ||
1099 | with self.subTest(debug=False): | ||
1100 | self.m.debug = False | ||
1101 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1102 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1103 | self.m.ccxt.create_order.return_value = { "id": 123 } | ||
1104 | order.run() | ||
1105 | self.m.ccxt.create_order.assert_called_once() | ||
1106 | self.assertEqual(1, len(order.results)) | ||
1107 | self.assertEqual("open", order.status) | ||
1108 | |||
1109 | self.m.ccxt.create_order.reset_mock() | ||
1110 | with self.subTest(exception=True): | ||
1111 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1112 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1113 | self.m.ccxt.create_order.side_effect = Exception("bouh") | ||
1114 | order.run() | ||
1115 | self.m.ccxt.create_order.assert_called_once() | ||
1116 | self.assertEqual(0, len(order.results)) | ||
1117 | self.assertEqual("error", order.status) | ||
1118 | self.m.report.log_error.assert_called_once() | ||
1119 | |||
1120 | self.m.ccxt.create_order.reset_mock() | ||
1121 | with self.subTest(dust_amount_exception=True),\ | ||
1122 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
1123 | order = portfolio.Order("buy", portfolio.Amount("ETH", 0.001), | ||
1124 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1125 | self.m.ccxt.create_order.side_effect = portfolio.InvalidOrder | ||
1126 | order.run() | ||
1127 | self.m.ccxt.create_order.assert_called_once() | ||
1128 | self.assertEqual(0, len(order.results)) | ||
1129 | self.assertEqual("closed", order.status) | ||
1130 | mark_finished_order.assert_called_once() | ||
1131 | |||
1132 | self.m.ccxt.order_precision.return_value = 8 | ||
1133 | self.m.ccxt.create_order.reset_mock() | ||
1134 | with self.subTest(insufficient_funds=True),\ | ||
1135 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
1136 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1137 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1138 | self.m.ccxt.create_order.side_effect = [ | ||
1139 | portfolio.InsufficientFunds, | ||
1140 | portfolio.InsufficientFunds, | ||
1141 | portfolio.InsufficientFunds, | ||
1142 | { "id": 123 }, | ||
1143 | ] | ||
1144 | order.run() | ||
1145 | self.m.ccxt.create_order.assert_has_calls([ | ||
1146 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1147 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')), | ||
1148 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')), | ||
1149 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')), | ||
1150 | ]) | ||
1151 | self.assertEqual(4, self.m.ccxt.create_order.call_count) | ||
1152 | self.assertEqual(1, len(order.results)) | ||
1153 | self.assertEqual("open", order.status) | ||
1154 | self.assertEqual(4, order.tries) | ||
1155 | self.m.report.log_error.assert_called() | ||
1156 | self.assertEqual(4, self.m.report.log_error.call_count) | ||
1157 | |||
1158 | self.m.ccxt.order_precision.return_value = 8 | ||
1159 | self.m.ccxt.create_order.reset_mock() | ||
1160 | self.m.report.log_error.reset_mock() | ||
1161 | with self.subTest(insufficient_funds=True),\ | ||
1162 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
1163 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1164 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1165 | self.m.ccxt.create_order.side_effect = [ | ||
1166 | portfolio.InsufficientFunds, | ||
1167 | portfolio.InsufficientFunds, | ||
1168 | portfolio.InsufficientFunds, | ||
1169 | portfolio.InsufficientFunds, | ||
1170 | portfolio.InsufficientFunds, | ||
1171 | ] | ||
1172 | order.run() | ||
1173 | self.m.ccxt.create_order.assert_has_calls([ | ||
1174 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1175 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')), | ||
1176 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')), | ||
1177 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')), | ||
1178 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account='exchange', price=D('0.1')), | ||
1179 | ]) | ||
1180 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
1181 | self.assertEqual(0, len(order.results)) | ||
1182 | self.assertEqual("error", order.status) | ||
1183 | self.assertEqual(5, order.tries) | ||
1184 | self.m.report.log_error.assert_called() | ||
1185 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
1186 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00096060 ETH at 0.1 BTC [pending])", exception=mock.ANY) | ||
1187 | |||
1188 | self.m.reset_mock() | ||
1189 | with self.subTest(invalid_nonce=True): | ||
1190 | with self.subTest(retry_success=True): | ||
1191 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1192 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1193 | self.m.ccxt.create_order.side_effect = [ | ||
1194 | portfolio.InvalidNonce, | ||
1195 | portfolio.InvalidNonce, | ||
1196 | { "id": 123 }, | ||
1197 | ] | ||
1198 | order.run() | ||
1199 | self.m.ccxt.create_order.assert_has_calls([ | ||
1200 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1201 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1202 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1203 | ]) | ||
1204 | self.assertEqual(3, self.m.ccxt.create_order.call_count) | ||
1205 | self.assertEqual(3, order.tries) | ||
1206 | self.m.report.log_error.assert_called() | ||
1207 | self.assertEqual(2, self.m.report.log_error.call_count) | ||
1208 | self.m.report.log_error.assert_called_with(mock.ANY, message="Retrying after invalid nonce", exception=mock.ANY) | ||
1209 | self.assertEqual(123, order.id) | ||
1210 | |||
1211 | self.m.reset_mock() | ||
1212 | with self.subTest(retry_success=False): | ||
1213 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1214 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1215 | self.m.ccxt.create_order.side_effect = [ | ||
1216 | portfolio.InvalidNonce, | ||
1217 | portfolio.InvalidNonce, | ||
1218 | portfolio.InvalidNonce, | ||
1219 | portfolio.InvalidNonce, | ||
1220 | portfolio.InvalidNonce, | ||
1221 | ] | ||
1222 | order.run() | ||
1223 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
1224 | self.assertEqual(5, order.tries) | ||
1225 | self.m.report.log_error.assert_called() | ||
1226 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
1227 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after invalid nonce", exception=mock.ANY) | ||
1228 | self.assertEqual("error", order.status) | ||
1229 | |||
1230 | self.m.reset_mock() | ||
1231 | with self.subTest(request_timeout=True): | ||
1232 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1233 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1234 | with self.subTest(retrieved=False), \ | ||
1235 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
1236 | self.m.ccxt.create_order.side_effect = [ | ||
1237 | portfolio.RequestTimeout, | ||
1238 | portfolio.RequestTimeout, | ||
1239 | { "id": 123 }, | ||
1240 | ] | ||
1241 | retrieve.return_value = False | ||
1242 | order.run() | ||
1243 | self.m.ccxt.create_order.assert_has_calls([ | ||
1244 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1245 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1246 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1247 | ]) | ||
1248 | self.assertEqual(3, self.m.ccxt.create_order.call_count) | ||
1249 | self.assertEqual(3, order.tries) | ||
1250 | self.m.report.log_error.assert_called() | ||
1251 | self.assertEqual(2, self.m.report.log_error.call_count) | ||
1252 | self.m.report.log_error.assert_called_with(mock.ANY, message="Retrying after timeout", exception=mock.ANY) | ||
1253 | self.assertEqual(123, order.id) | ||
1254 | |||
1255 | self.m.reset_mock() | ||
1256 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1257 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1258 | with self.subTest(retrieved=True), \ | ||
1259 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
1260 | self.m.ccxt.create_order.side_effect = [ | ||
1261 | portfolio.RequestTimeout, | ||
1262 | ] | ||
1263 | def _retrieve(): | ||
1264 | order.results.append({"id": 123}) | ||
1265 | return True | ||
1266 | retrieve.side_effect = _retrieve | ||
1267 | order.run() | ||
1268 | self.m.ccxt.create_order.assert_has_calls([ | ||
1269 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1270 | ]) | ||
1271 | self.assertEqual(1, self.m.ccxt.create_order.call_count) | ||
1272 | self.assertEqual(1, order.tries) | ||
1273 | self.m.report.log_error.assert_called() | ||
1274 | self.assertEqual(1, self.m.report.log_error.call_count) | ||
1275 | self.m.report.log_error.assert_called_with(mock.ANY, message="Timeout, found the order") | ||
1276 | self.assertEqual(123, order.id) | ||
1277 | |||
1278 | self.m.reset_mock() | ||
1279 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1280 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1281 | with self.subTest(retrieved=False), \ | ||
1282 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
1283 | self.m.ccxt.create_order.side_effect = [ | ||
1284 | portfolio.RequestTimeout, | ||
1285 | portfolio.RequestTimeout, | ||
1286 | portfolio.RequestTimeout, | ||
1287 | portfolio.RequestTimeout, | ||
1288 | portfolio.RequestTimeout, | ||
1289 | ] | ||
1290 | retrieve.return_value = False | ||
1291 | order.run() | ||
1292 | self.m.ccxt.create_order.assert_has_calls([ | ||
1293 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1294 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1295 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1296 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1297 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1298 | ]) | ||
1299 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
1300 | self.assertEqual(5, order.tries) | ||
1301 | self.m.report.log_error.assert_called() | ||
1302 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
1303 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after timeouts", exception=mock.ANY) | ||
1304 | self.assertEqual("error", order.status) | ||
1305 | |||
1306 | def test_retrieve_order(self): | ||
1307 | with self.subTest(similar_open_order=True): | ||
1308 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1309 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1310 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
1311 | |||
1312 | self.m.ccxt.order_precision.return_value = 8 | ||
1313 | self.m.ccxt.fetch_orders.return_value = [ | ||
1314 | { # Wrong amount | ||
1315 | 'amount': 0.002, 'cost': 0.1, | ||
1316 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1317 | 'fee': None, 'filled': 0.0, | ||
1318 | 'id': '1', | ||
1319 | 'info': { | ||
1320 | 'amount': '0.002', | ||
1321 | 'date': '2018-03-25 15:15:51', | ||
1322 | 'margin': 0, 'orderNumber': '1', | ||
1323 | 'price': '0.1', 'rate': '0.1', | ||
1324 | 'side': 'buy', 'startingAmount': '0.002', | ||
1325 | 'status': 'open', 'total': '0.0002', | ||
1326 | 'type': 'limit' | ||
1327 | }, | ||
1328 | 'price': 0.1, 'remaining': 0.002, 'side': 'buy', | ||
1329 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1330 | 'timestamp': 1521990951000, 'trades': None, | ||
1331 | 'type': 'limit' | ||
1332 | }, | ||
1333 | { # Margin | ||
1334 | 'amount': 0.001, 'cost': 0.1, | ||
1335 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1336 | 'fee': None, 'filled': 0.0, | ||
1337 | 'id': '2', | ||
1338 | 'info': { | ||
1339 | 'amount': '0.001', | ||
1340 | 'date': '2018-03-25 15:15:51', | ||
1341 | 'margin': 1, 'orderNumber': '2', | ||
1342 | 'price': '0.1', 'rate': '0.1', | ||
1343 | 'side': 'buy', 'startingAmount': '0.001', | ||
1344 | 'status': 'open', 'total': '0.0001', | ||
1345 | 'type': 'limit' | ||
1346 | }, | ||
1347 | 'price': 0.1, 'remaining': 0.001, 'side': 'buy', | ||
1348 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1349 | 'timestamp': 1521990951000, 'trades': None, | ||
1350 | 'type': 'limit' | ||
1351 | }, | ||
1352 | { # selling | ||
1353 | 'amount': 0.001, 'cost': 0.1, | ||
1354 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1355 | 'fee': None, 'filled': 0.0, | ||
1356 | 'id': '3', | ||
1357 | 'info': { | ||
1358 | 'amount': '0.001', | ||
1359 | 'date': '2018-03-25 15:15:51', | ||
1360 | 'margin': 0, 'orderNumber': '3', | ||
1361 | 'price': '0.1', 'rate': '0.1', | ||
1362 | 'side': 'sell', 'startingAmount': '0.001', | ||
1363 | 'status': 'open', 'total': '0.0001', | ||
1364 | 'type': 'limit' | ||
1365 | }, | ||
1366 | 'price': 0.1, 'remaining': 0.001, 'side': 'sell', | ||
1367 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1368 | 'timestamp': 1521990951000, 'trades': None, | ||
1369 | 'type': 'limit' | ||
1370 | }, | ||
1371 | { # Wrong rate | ||
1372 | 'amount': 0.001, 'cost': 0.15, | ||
1373 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1374 | 'fee': None, 'filled': 0.0, | ||
1375 | 'id': '4', | ||
1376 | 'info': { | ||
1377 | 'amount': '0.001', | ||
1378 | 'date': '2018-03-25 15:15:51', | ||
1379 | 'margin': 0, 'orderNumber': '4', | ||
1380 | 'price': '0.15', 'rate': '0.15', | ||
1381 | 'side': 'buy', 'startingAmount': '0.001', | ||
1382 | 'status': 'open', 'total': '0.0001', | ||
1383 | 'type': 'limit' | ||
1384 | }, | ||
1385 | 'price': 0.15, 'remaining': 0.001, 'side': 'buy', | ||
1386 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1387 | 'timestamp': 1521990951000, 'trades': None, | ||
1388 | 'type': 'limit' | ||
1389 | }, | ||
1390 | { # All good | ||
1391 | 'amount': 0.001, 'cost': 0.1, | ||
1392 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1393 | 'fee': None, 'filled': 0.0, | ||
1394 | 'id': '5', | ||
1395 | 'info': { | ||
1396 | 'amount': '0.001', | ||
1397 | 'date': '2018-03-25 15:15:51', | ||
1398 | 'margin': 0, 'orderNumber': '1', | ||
1399 | 'price': '0.1', 'rate': '0.1', | ||
1400 | 'side': 'buy', 'startingAmount': '0.001', | ||
1401 | 'status': 'open', 'total': '0.0001', | ||
1402 | 'type': 'limit' | ||
1403 | }, | ||
1404 | 'price': 0.1, 'remaining': 0.001, 'side': 'buy', | ||
1405 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1406 | 'timestamp': 1521990951000, 'trades': None, | ||
1407 | 'type': 'limit' | ||
1408 | } | ||
1409 | ] | ||
1410 | result = order.retrieve_order() | ||
1411 | self.assertTrue(result) | ||
1412 | self.assertEqual('5', order.results[0]["id"]) | ||
1413 | self.m.ccxt.fetch_my_trades.assert_not_called() | ||
1414 | self.m.ccxt.fetch_orders.assert_called_once_with(symbol="ETH/BTC", since=1521983750) | ||
1415 | |||
1416 | self.m.reset_mock() | ||
1417 | with self.subTest(similar_open_order=False, past_trades=True): | ||
1418 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1419 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1420 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
1421 | |||
1422 | self.m.ccxt.order_precision.return_value = 8 | ||
1423 | self.m.ccxt.fetch_orders.return_value = [] | ||
1424 | self.m.ccxt.fetch_my_trades.return_value = [ | ||
1425 | { # Wrong timestamp 1 | ||
1426 | 'amount': 0.0006, | ||
1427 | 'cost': 0.00006, | ||
1428 | 'datetime': '2018-03-25T15:15:14.000Z', | ||
1429 | 'id': '1-1', | ||
1430 | 'info': { | ||
1431 | 'amount': '0.0006', | ||
1432 | 'category': 'exchange', | ||
1433 | 'date': '2018-03-25 15:15:14', | ||
1434 | 'fee': '0.00150000', | ||
1435 | 'globalTradeID': 1, | ||
1436 | 'orderNumber': '1', | ||
1437 | 'rate': '0.1', | ||
1438 | 'total': '0.00006', | ||
1439 | 'tradeID': '1-1', | ||
1440 | 'type': 'buy' | ||
1441 | }, | ||
1442 | 'order': '1', | ||
1443 | 'price': 0.1, | ||
1444 | 'side': 'buy', | ||
1445 | 'symbol': 'ETH/BTC', | ||
1446 | 'timestamp': 1521983714, | ||
1447 | 'type': 'limit' | ||
1448 | }, | ||
1449 | { # Wrong timestamp 2 | ||
1450 | 'amount': 0.0004, | ||
1451 | 'cost': 0.00004, | ||
1452 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1453 | 'id': '1-2', | ||
1454 | 'info': { | ||
1455 | 'amount': '0.0004', | ||
1456 | 'category': 'exchange', | ||
1457 | 'date': '2018-03-25 15:16:54', | ||
1458 | 'fee': '0.00150000', | ||
1459 | 'globalTradeID': 2, | ||
1460 | 'orderNumber': '1', | ||
1461 | 'rate': '0.1', | ||
1462 | 'total': '0.00004', | ||
1463 | 'tradeID': '1-2', | ||
1464 | 'type': 'buy' | ||
1465 | }, | ||
1466 | 'order': '1', | ||
1467 | 'price': 0.1, | ||
1468 | 'side': 'buy', | ||
1469 | 'symbol': 'ETH/BTC', | ||
1470 | 'timestamp': 1521983814, | ||
1471 | 'type': 'limit' | ||
1472 | }, | ||
1473 | { # Wrong side 1 | ||
1474 | 'amount': 0.0006, | ||
1475 | 'cost': 0.00006, | ||
1476 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1477 | 'id': '2-1', | ||
1478 | 'info': { | ||
1479 | 'amount': '0.0006', | ||
1480 | 'category': 'exchange', | ||
1481 | 'date': '2018-03-25 15:15:54', | ||
1482 | 'fee': '0.00150000', | ||
1483 | 'globalTradeID': 1, | ||
1484 | 'orderNumber': '2', | ||
1485 | 'rate': '0.1', | ||
1486 | 'total': '0.00006', | ||
1487 | 'tradeID': '2-1', | ||
1488 | 'type': 'sell' | ||
1489 | }, | ||
1490 | 'order': '2', | ||
1491 | 'price': 0.1, | ||
1492 | 'side': 'sell', | ||
1493 | 'symbol': 'ETH/BTC', | ||
1494 | 'timestamp': 1521983754, | ||
1495 | 'type': 'limit' | ||
1496 | }, | ||
1497 | { # Wrong side 2 | ||
1498 | 'amount': 0.0004, | ||
1499 | 'cost': 0.00004, | ||
1500 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1501 | 'id': '2-2', | ||
1502 | 'info': { | ||
1503 | 'amount': '0.0004', | ||
1504 | 'category': 'exchange', | ||
1505 | 'date': '2018-03-25 15:16:54', | ||
1506 | 'fee': '0.00150000', | ||
1507 | 'globalTradeID': 2, | ||
1508 | 'orderNumber': '2', | ||
1509 | 'rate': '0.1', | ||
1510 | 'total': '0.00004', | ||
1511 | 'tradeID': '2-2', | ||
1512 | 'type': 'buy' | ||
1513 | }, | ||
1514 | 'order': '2', | ||
1515 | 'price': 0.1, | ||
1516 | 'side': 'buy', | ||
1517 | 'symbol': 'ETH/BTC', | ||
1518 | 'timestamp': 1521983814, | ||
1519 | 'type': 'limit' | ||
1520 | }, | ||
1521 | { # Margin trade 1 | ||
1522 | 'amount': 0.0006, | ||
1523 | 'cost': 0.00006, | ||
1524 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1525 | 'id': '3-1', | ||
1526 | 'info': { | ||
1527 | 'amount': '0.0006', | ||
1528 | 'category': 'marginTrade', | ||
1529 | 'date': '2018-03-25 15:15:54', | ||
1530 | 'fee': '0.00150000', | ||
1531 | 'globalTradeID': 1, | ||
1532 | 'orderNumber': '3', | ||
1533 | 'rate': '0.1', | ||
1534 | 'total': '0.00006', | ||
1535 | 'tradeID': '3-1', | ||
1536 | 'type': 'buy' | ||
1537 | }, | ||
1538 | 'order': '3', | ||
1539 | 'price': 0.1, | ||
1540 | 'side': 'buy', | ||
1541 | 'symbol': 'ETH/BTC', | ||
1542 | 'timestamp': 1521983754, | ||
1543 | 'type': 'limit' | ||
1544 | }, | ||
1545 | { # Margin trade 2 | ||
1546 | 'amount': 0.0004, | ||
1547 | 'cost': 0.00004, | ||
1548 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1549 | 'id': '3-2', | ||
1550 | 'info': { | ||
1551 | 'amount': '0.0004', | ||
1552 | 'category': 'marginTrade', | ||
1553 | 'date': '2018-03-25 15:16:54', | ||
1554 | 'fee': '0.00150000', | ||
1555 | 'globalTradeID': 2, | ||
1556 | 'orderNumber': '3', | ||
1557 | 'rate': '0.1', | ||
1558 | 'total': '0.00004', | ||
1559 | 'tradeID': '3-2', | ||
1560 | 'type': 'buy' | ||
1561 | }, | ||
1562 | 'order': '3', | ||
1563 | 'price': 0.1, | ||
1564 | 'side': 'buy', | ||
1565 | 'symbol': 'ETH/BTC', | ||
1566 | 'timestamp': 1521983814, | ||
1567 | 'type': 'limit' | ||
1568 | }, | ||
1569 | { # Wrong amount 1 | ||
1570 | 'amount': 0.0005, | ||
1571 | 'cost': 0.00005, | ||
1572 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1573 | 'id': '4-1', | ||
1574 | 'info': { | ||
1575 | 'amount': '0.0005', | ||
1576 | 'category': 'exchange', | ||
1577 | 'date': '2018-03-25 15:15:54', | ||
1578 | 'fee': '0.00150000', | ||
1579 | 'globalTradeID': 1, | ||
1580 | 'orderNumber': '4', | ||
1581 | 'rate': '0.1', | ||
1582 | 'total': '0.00005', | ||
1583 | 'tradeID': '4-1', | ||
1584 | 'type': 'buy' | ||
1585 | }, | ||
1586 | 'order': '4', | ||
1587 | 'price': 0.1, | ||
1588 | 'side': 'buy', | ||
1589 | 'symbol': 'ETH/BTC', | ||
1590 | 'timestamp': 1521983754, | ||
1591 | 'type': 'limit' | ||
1592 | }, | ||
1593 | { # Wrong amount 2 | ||
1594 | 'amount': 0.0004, | ||
1595 | 'cost': 0.00004, | ||
1596 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1597 | 'id': '4-2', | ||
1598 | 'info': { | ||
1599 | 'amount': '0.0004', | ||
1600 | 'category': 'exchange', | ||
1601 | 'date': '2018-03-25 15:16:54', | ||
1602 | 'fee': '0.00150000', | ||
1603 | 'globalTradeID': 2, | ||
1604 | 'orderNumber': '4', | ||
1605 | 'rate': '0.1', | ||
1606 | 'total': '0.00004', | ||
1607 | 'tradeID': '4-2', | ||
1608 | 'type': 'buy' | ||
1609 | }, | ||
1610 | 'order': '4', | ||
1611 | 'price': 0.1, | ||
1612 | 'side': 'buy', | ||
1613 | 'symbol': 'ETH/BTC', | ||
1614 | 'timestamp': 1521983814, | ||
1615 | 'type': 'limit' | ||
1616 | }, | ||
1617 | { # Wrong price 1 | ||
1618 | 'amount': 0.0006, | ||
1619 | 'cost': 0.000066, | ||
1620 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1621 | 'id': '5-1', | ||
1622 | 'info': { | ||
1623 | 'amount': '0.0006', | ||
1624 | 'category': 'exchange', | ||
1625 | 'date': '2018-03-25 15:15:54', | ||
1626 | 'fee': '0.00150000', | ||
1627 | 'globalTradeID': 1, | ||
1628 | 'orderNumber': '5', | ||
1629 | 'rate': '0.11', | ||
1630 | 'total': '0.000066', | ||
1631 | 'tradeID': '5-1', | ||
1632 | 'type': 'buy' | ||
1633 | }, | ||
1634 | 'order': '5', | ||
1635 | 'price': 0.11, | ||
1636 | 'side': 'buy', | ||
1637 | 'symbol': 'ETH/BTC', | ||
1638 | 'timestamp': 1521983754, | ||
1639 | 'type': 'limit' | ||
1640 | }, | ||
1641 | { # Wrong price 2 | ||
1642 | 'amount': 0.0004, | ||
1643 | 'cost': 0.00004, | ||
1644 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1645 | 'id': '5-2', | ||
1646 | 'info': { | ||
1647 | 'amount': '0.0004', | ||
1648 | 'category': 'exchange', | ||
1649 | 'date': '2018-03-25 15:16:54', | ||
1650 | 'fee': '0.00150000', | ||
1651 | 'globalTradeID': 2, | ||
1652 | 'orderNumber': '5', | ||
1653 | 'rate': '0.1', | ||
1654 | 'total': '0.00004', | ||
1655 | 'tradeID': '5-2', | ||
1656 | 'type': 'buy' | ||
1657 | }, | ||
1658 | 'order': '5', | ||
1659 | 'price': 0.1, | ||
1660 | 'side': 'buy', | ||
1661 | 'symbol': 'ETH/BTC', | ||
1662 | 'timestamp': 1521983814, | ||
1663 | 'type': 'limit' | ||
1664 | }, | ||
1665 | { # All good 1 | ||
1666 | 'amount': 0.0006, | ||
1667 | 'cost': 0.00006, | ||
1668 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1669 | 'id': '7-1', | ||
1670 | 'info': { | ||
1671 | 'amount': '0.0006', | ||
1672 | 'category': 'exchange', | ||
1673 | 'date': '2018-03-25 15:15:54', | ||
1674 | 'fee': '0.00150000', | ||
1675 | 'globalTradeID': 1, | ||
1676 | 'orderNumber': '7', | ||
1677 | 'rate': '0.1', | ||
1678 | 'total': '0.00006', | ||
1679 | 'tradeID': '7-1', | ||
1680 | 'type': 'buy' | ||
1681 | }, | ||
1682 | 'order': '7', | ||
1683 | 'price': 0.1, | ||
1684 | 'side': 'buy', | ||
1685 | 'symbol': 'ETH/BTC', | ||
1686 | 'timestamp': 1521983754, | ||
1687 | 'type': 'limit' | ||
1688 | }, | ||
1689 | { # All good 2 | ||
1690 | 'amount': 0.0004, | ||
1691 | 'cost': 0.000036, | ||
1692 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1693 | 'id': '7-2', | ||
1694 | 'info': { | ||
1695 | 'amount': '0.0004', | ||
1696 | 'category': 'exchange', | ||
1697 | 'date': '2018-03-25 15:16:54', | ||
1698 | 'fee': '0.00150000', | ||
1699 | 'globalTradeID': 2, | ||
1700 | 'orderNumber': '7', | ||
1701 | 'rate': '0.09', | ||
1702 | 'total': '0.000036', | ||
1703 | 'tradeID': '7-2', | ||
1704 | 'type': 'buy' | ||
1705 | }, | ||
1706 | 'order': '7', | ||
1707 | 'price': 0.09, | ||
1708 | 'side': 'buy', | ||
1709 | 'symbol': 'ETH/BTC', | ||
1710 | 'timestamp': 1521983814, | ||
1711 | 'type': 'limit' | ||
1712 | }, | ||
1713 | ] | ||
1714 | |||
1715 | result = order.retrieve_order() | ||
1716 | self.assertTrue(result) | ||
1717 | self.assertEqual('7', order.results[0]["id"]) | ||
1718 | self.m.ccxt.fetch_orders.assert_called_once_with(symbol="ETH/BTC", since=1521983750) | ||
1719 | |||
1720 | self.m.reset_mock() | ||
1721 | with self.subTest(similar_open_order=False, past_trades=False): | ||
1722 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1723 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1724 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
1725 | |||
1726 | self.m.ccxt.order_precision.return_value = 8 | ||
1727 | self.m.ccxt.fetch_orders.return_value = [] | ||
1728 | self.m.ccxt.fetch_my_trades.return_value = [] | ||
1729 | result = order.retrieve_order() | ||
1730 | self.assertFalse(result) | ||
1731 | |||
1732 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1733 | class MouvementTest(WebMockTestCase): | ||
1734 | def test_values(self): | ||
1735 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1736 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
1737 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
1738 | "amount": "10", "total": "1" | ||
1739 | }) | ||
1740 | self.assertEqual("ETH", mouvement.currency) | ||
1741 | self.assertEqual("BTC", mouvement.base_currency) | ||
1742 | self.assertEqual(42, mouvement.id) | ||
1743 | self.assertEqual("buy", mouvement.action) | ||
1744 | self.assertEqual(D("0.0015"), mouvement.fee_rate) | ||
1745 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), mouvement.date) | ||
1746 | self.assertEqual(D("0.1"), mouvement.rate) | ||
1747 | self.assertEqual(portfolio.Amount("ETH", "10"), mouvement.total) | ||
1748 | self.assertEqual(portfolio.Amount("BTC", "1"), mouvement.total_in_base) | ||
1749 | |||
1750 | mouvement = portfolio.Mouvement("ETH", "BTC", { "foo": "bar" }) | ||
1751 | self.assertIsNone(mouvement.date) | ||
1752 | self.assertIsNone(mouvement.id) | ||
1753 | self.assertIsNone(mouvement.action) | ||
1754 | self.assertEqual(-1, mouvement.fee_rate) | ||
1755 | self.assertEqual(0, mouvement.rate) | ||
1756 | self.assertEqual(portfolio.Amount("ETH", 0), mouvement.total) | ||
1757 | self.assertEqual(portfolio.Amount("BTC", 0), mouvement.total_in_base) | ||
1758 | |||
1759 | def test__repr(self): | ||
1760 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1761 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
1762 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
1763 | "amount": "10", "total": "1" | ||
1764 | }) | ||
1765 | self.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement)) | ||
1766 | |||
1767 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1768 | "tradeID": 42, "type": "buy", | ||
1769 | "date": "garbage", "rate": "0.1", | ||
1770 | "amount": "10", "total": "1" | ||
1771 | }) | ||
1772 | self.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement)) | ||
1773 | |||
1774 | def test_as_json(self): | ||
1775 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1776 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
1777 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
1778 | "amount": "10", "total": "1" | ||
1779 | }) | ||
1780 | as_json = mouvement.as_json() | ||
1781 | |||
1782 | self.assertEqual(D("0.0015"), as_json["fee_rate"]) | ||
1783 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), as_json["date"]) | ||
1784 | self.assertEqual("buy", as_json["action"]) | ||
1785 | self.assertEqual(D("10"), as_json["total"]) | ||
1786 | self.assertEqual(D("1"), as_json["total_in_base"]) | ||
1787 | self.assertEqual("BTC", as_json["base_currency"]) | ||
1788 | self.assertEqual("ETH", as_json["currency"]) | ||
1789 | |||
1790 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1791 | class AmountTest(WebMockTestCase): | ||
1792 | def test_values(self): | ||
1793 | amount = portfolio.Amount("BTC", "0.65") | ||
1794 | self.assertEqual(D("0.65"), amount.value) | ||
1795 | self.assertEqual("BTC", amount.currency) | ||
1796 | |||
1797 | def test_in_currency(self): | ||
1798 | amount = portfolio.Amount("ETC", 10) | ||
1799 | |||
1800 | self.assertEqual(amount, amount.in_currency("ETC", self.m)) | ||
1801 | |||
1802 | with self.subTest(desc="no ticker for currency"): | ||
1803 | self.m.get_ticker.return_value = None | ||
1804 | |||
1805 | self.assertRaises(Exception, amount.in_currency, "ETH", self.m) | ||
1806 | |||
1807 | with self.subTest(desc="nominal case"): | ||
1808 | self.m.get_ticker.return_value = { | ||
1809 | "bid": D("0.2"), | ||
1810 | "ask": D("0.4"), | ||
1811 | "average": D("0.3"), | ||
1812 | "foo": "bar", | ||
1813 | } | ||
1814 | converted_amount = amount.in_currency("ETH", self.m) | ||
1815 | |||
1816 | self.assertEqual(D("3.0"), converted_amount.value) | ||
1817 | self.assertEqual("ETH", converted_amount.currency) | ||
1818 | self.assertEqual(amount, converted_amount.linked_to) | ||
1819 | self.assertEqual("bar", converted_amount.ticker["foo"]) | ||
1820 | |||
1821 | converted_amount = amount.in_currency("ETH", self.m, action="bid", compute_value="default") | ||
1822 | self.assertEqual(D("2"), converted_amount.value) | ||
1823 | |||
1824 | converted_amount = amount.in_currency("ETH", self.m, compute_value="ask") | ||
1825 | self.assertEqual(D("4"), converted_amount.value) | ||
1826 | |||
1827 | converted_amount = amount.in_currency("ETH", self.m, rate=D("0.02")) | ||
1828 | self.assertEqual(D("0.2"), converted_amount.value) | ||
1829 | |||
1830 | def test__round(self): | ||
1831 | amount = portfolio.Amount("BAR", portfolio.D("1.23456789876")) | ||
1832 | self.assertEqual(D("1.23456789"), round(amount).value) | ||
1833 | self.assertEqual(D("1.23"), round(amount, 2).value) | ||
1834 | |||
1835 | def test__abs(self): | ||
1836 | amount = portfolio.Amount("SC", -120) | ||
1837 | self.assertEqual(120, abs(amount).value) | ||
1838 | self.assertEqual("SC", abs(amount).currency) | ||
1839 | |||
1840 | amount = portfolio.Amount("SC", 10) | ||
1841 | self.assertEqual(10, abs(amount).value) | ||
1842 | self.assertEqual("SC", abs(amount).currency) | ||
1843 | |||
1844 | def test__add(self): | ||
1845 | amount1 = portfolio.Amount("XVG", "12.9") | ||
1846 | amount2 = portfolio.Amount("XVG", "13.1") | ||
1847 | |||
1848 | self.assertEqual(26, (amount1 + amount2).value) | ||
1849 | self.assertEqual("XVG", (amount1 + amount2).currency) | ||
1850 | |||
1851 | amount3 = portfolio.Amount("ETH", "1.6") | ||
1852 | with self.assertRaises(Exception): | ||
1853 | amount1 + amount3 | ||
1854 | |||
1855 | amount4 = portfolio.Amount("ETH", 0.0) | ||
1856 | self.assertEqual(amount1, amount1 + amount4) | ||
1857 | |||
1858 | self.assertEqual(amount1, amount1 + 0) | ||
1859 | |||
1860 | def test__radd(self): | ||
1861 | amount = portfolio.Amount("XVG", "12.9") | ||
1862 | |||
1863 | self.assertEqual(amount, 0 + amount) | ||
1864 | with self.assertRaises(Exception): | ||
1865 | 4 + amount | ||
1866 | |||
1867 | def test__sub(self): | ||
1868 | amount1 = portfolio.Amount("XVG", "13.3") | ||
1869 | amount2 = portfolio.Amount("XVG", "13.1") | ||
1870 | |||
1871 | self.assertEqual(D("0.2"), (amount1 - amount2).value) | ||
1872 | self.assertEqual("XVG", (amount1 - amount2).currency) | ||
1873 | |||
1874 | amount3 = portfolio.Amount("ETH", "1.6") | ||
1875 | with self.assertRaises(Exception): | ||
1876 | amount1 - amount3 | ||
1877 | |||
1878 | amount4 = portfolio.Amount("ETH", 0.0) | ||
1879 | self.assertEqual(amount1, amount1 - amount4) | ||
1880 | |||
1881 | def test__rsub(self): | ||
1882 | amount = portfolio.Amount("ETH", "1.6") | ||
1883 | with self.assertRaises(Exception): | ||
1884 | 3 - amount | ||
1885 | |||
1886 | self.assertEqual(portfolio.Amount("ETH", "-1.6"), 0-amount) | ||
1887 | |||
1888 | def test__mul(self): | ||
1889 | amount = portfolio.Amount("XEM", 11) | ||
1890 | |||
1891 | self.assertEqual(D("38.5"), (amount * D("3.5")).value) | ||
1892 | self.assertEqual(D("33"), (amount * 3).value) | ||
1893 | |||
1894 | with self.assertRaises(Exception): | ||
1895 | amount * amount | ||
1896 | |||
1897 | def test__rmul(self): | ||
1898 | amount = portfolio.Amount("XEM", 11) | ||
1899 | |||
1900 | self.assertEqual(D("38.5"), (D("3.5") * amount).value) | ||
1901 | self.assertEqual(D("33"), (3 * amount).value) | ||
1902 | |||
1903 | def test__floordiv(self): | ||
1904 | amount = portfolio.Amount("XEM", 11) | ||
1905 | |||
1906 | self.assertEqual(D("5.5"), (amount / 2).value) | ||
1907 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | ||
1908 | |||
1909 | with self.assertRaises(Exception): | ||
1910 | amount / amount | ||
1911 | |||
1912 | def test__truediv(self): | ||
1913 | amount = portfolio.Amount("XEM", 11) | ||
1914 | |||
1915 | self.assertEqual(D("5.5"), (amount / 2).value) | ||
1916 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | ||
1917 | |||
1918 | def test__lt(self): | ||
1919 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1920 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1921 | |||
1922 | self.assertTrue(amount1 < amount2) | ||
1923 | self.assertFalse(amount2 < amount1) | ||
1924 | self.assertFalse(amount1 < amount1) | ||
1925 | |||
1926 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1927 | with self.assertRaises(Exception): | ||
1928 | amount1 < amount3 | ||
1929 | |||
1930 | def test__le(self): | ||
1931 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1932 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1933 | |||
1934 | self.assertTrue(amount1 <= amount2) | ||
1935 | self.assertFalse(amount2 <= amount1) | ||
1936 | self.assertTrue(amount1 <= amount1) | ||
1937 | |||
1938 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1939 | with self.assertRaises(Exception): | ||
1940 | amount1 <= amount3 | ||
1941 | |||
1942 | def test__gt(self): | ||
1943 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1944 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1945 | |||
1946 | self.assertTrue(amount2 > amount1) | ||
1947 | self.assertFalse(amount1 > amount2) | ||
1948 | self.assertFalse(amount1 > amount1) | ||
1949 | |||
1950 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1951 | with self.assertRaises(Exception): | ||
1952 | amount3 > amount1 | ||
1953 | |||
1954 | def test__ge(self): | ||
1955 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1956 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1957 | |||
1958 | self.assertTrue(amount2 >= amount1) | ||
1959 | self.assertFalse(amount1 >= amount2) | ||
1960 | self.assertTrue(amount1 >= amount1) | ||
1961 | |||
1962 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1963 | with self.assertRaises(Exception): | ||
1964 | amount3 >= amount1 | ||
1965 | |||
1966 | def test__eq(self): | ||
1967 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1968 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1969 | amount3 = portfolio.Amount("BTD", 11.3) | ||
1970 | |||
1971 | self.assertFalse(amount1 == amount2) | ||
1972 | self.assertFalse(amount2 == amount1) | ||
1973 | self.assertTrue(amount1 == amount3) | ||
1974 | self.assertFalse(amount2 == 0) | ||
1975 | |||
1976 | amount4 = portfolio.Amount("BTC", 1.6) | ||
1977 | with self.assertRaises(Exception): | ||
1978 | amount1 == amount4 | ||
1979 | |||
1980 | amount5 = portfolio.Amount("BTD", 0) | ||
1981 | self.assertTrue(amount5 == 0) | ||
1982 | |||
1983 | def test__ne(self): | ||
1984 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1985 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1986 | amount3 = portfolio.Amount("BTD", 11.3) | ||
1987 | |||
1988 | self.assertTrue(amount1 != amount2) | ||
1989 | self.assertTrue(amount2 != amount1) | ||
1990 | self.assertFalse(amount1 != amount3) | ||
1991 | self.assertTrue(amount2 != 0) | ||
1992 | |||
1993 | amount4 = portfolio.Amount("BTC", 1.6) | ||
1994 | with self.assertRaises(Exception): | ||
1995 | amount1 != amount4 | ||
1996 | |||
1997 | amount5 = portfolio.Amount("BTD", 0) | ||
1998 | self.assertFalse(amount5 != 0) | ||
1999 | |||
2000 | def test__neg(self): | ||
2001 | amount1 = portfolio.Amount("BTD", "11.3") | ||
2002 | |||
2003 | self.assertEqual(portfolio.D("-11.3"), (-amount1).value) | ||
2004 | |||
2005 | def test__str(self): | ||
2006 | amount1 = portfolio.Amount("BTX", 32) | ||
2007 | self.assertEqual("32.00000000 BTX", str(amount1)) | ||
2008 | |||
2009 | amount2 = portfolio.Amount("USDT", 12000) | ||
2010 | amount1.linked_to = amount2 | ||
2011 | self.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1)) | ||
2012 | |||
2013 | def test__repr(self): | ||
2014 | amount1 = portfolio.Amount("BTX", 32) | ||
2015 | self.assertEqual("Amount(32.00000000 BTX)", repr(amount1)) | ||
2016 | |||
2017 | amount2 = portfolio.Amount("USDT", 12000) | ||
2018 | amount1.linked_to = amount2 | ||
2019 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1)) | ||
2020 | |||
2021 | amount3 = portfolio.Amount("BTC", 0.1) | ||
2022 | amount2.linked_to = amount3 | ||
2023 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1)) | ||
2024 | |||
2025 | def test_as_json(self): | ||
2026 | amount = portfolio.Amount("BTX", 32) | ||
2027 | self.assertEqual({"currency": "BTX", "value": D("32")}, amount.as_json()) | ||
2028 | |||
2029 | amount = portfolio.Amount("BTX", "1E-10") | ||
2030 | self.assertEqual({"currency": "BTX", "value": D("0")}, amount.as_json()) | ||
2031 | |||
2032 | amount = portfolio.Amount("BTX", "1E-5") | ||
2033 | self.assertEqual({"currency": "BTX", "value": D("0.00001")}, amount.as_json()) | ||
2034 | self.assertEqual("0.00001", str(amount.as_json()["value"])) | ||
2035 | |||
2036 | |||
diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..c0b1fb9 --- /dev/null +++ b/tests/test_store.py | |||
@@ -0,0 +1,1203 @@ | |||
1 | from .helper import * | ||
2 | import requests | ||
3 | import datetime | ||
4 | import threading | ||
5 | import market, portfolio, store | ||
6 | |||
7 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
8 | class NoopLockTest(unittest.TestCase): | ||
9 | def test_with(self): | ||
10 | noop_lock = store.NoopLock() | ||
11 | with noop_lock: | ||
12 | self.assertTrue(True) | ||
13 | |||
14 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
15 | class LockedVarTest(unittest.TestCase): | ||
16 | |||
17 | def test_values(self): | ||
18 | locked_var = store.LockedVar("Foo") | ||
19 | self.assertIsInstance(locked_var.lock, store.NoopLock) | ||
20 | self.assertEqual("Foo", locked_var.val) | ||
21 | |||
22 | def test_get(self): | ||
23 | with self.subTest(desc="Normal case"): | ||
24 | locked_var = store.LockedVar("Foo") | ||
25 | self.assertEqual("Foo", locked_var.get()) | ||
26 | with self.subTest(desc="Dict"): | ||
27 | locked_var = store.LockedVar({"foo": "bar"}) | ||
28 | self.assertEqual({"foo": "bar"}, locked_var.get()) | ||
29 | self.assertEqual("bar", locked_var.get("foo")) | ||
30 | self.assertIsNone(locked_var.get("other")) | ||
31 | |||
32 | def test_set(self): | ||
33 | locked_var = store.LockedVar("Foo") | ||
34 | locked_var.set("Bar") | ||
35 | self.assertEqual("Bar", locked_var.get()) | ||
36 | |||
37 | def test__getattr(self): | ||
38 | dummy = type('Dummy', (object,), {})() | ||
39 | dummy.attribute = "Hey" | ||
40 | |||
41 | locked_var = store.LockedVar(dummy) | ||
42 | self.assertEqual("Hey", locked_var.attribute) | ||
43 | with self.assertRaises(AttributeError): | ||
44 | locked_var.other | ||
45 | |||
46 | def test_start_lock(self): | ||
47 | locked_var = store.LockedVar("Foo") | ||
48 | locked_var.start_lock() | ||
49 | self.assertEqual("lock", locked_var.lock.__class__.__name__) | ||
50 | |||
51 | thread1 = threading.Thread(target=locked_var.set, args=["Bar1"]) | ||
52 | thread2 = threading.Thread(target=locked_var.set, args=["Bar2"]) | ||
53 | thread3 = threading.Thread(target=locked_var.set, args=["Bar3"]) | ||
54 | |||
55 | with locked_var.lock: | ||
56 | thread1.start() | ||
57 | thread2.start() | ||
58 | thread3.start() | ||
59 | |||
60 | self.assertEqual("Foo", locked_var.val) | ||
61 | thread1.join() | ||
62 | thread2.join() | ||
63 | thread3.join() | ||
64 | self.assertEqual("Bar", locked_var.get()[0:3]) | ||
65 | |||
66 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
67 | class TradeStoreTest(WebMockTestCase): | ||
68 | def test_compute_trades(self): | ||
69 | self.m.balances.currencies.return_value = ["XMR", "DASH", "XVG", "BTC", "ETH"] | ||
70 | |||
71 | values_in_base = { | ||
72 | "XMR": portfolio.Amount("BTC", D("0.9")), | ||
73 | "DASH": portfolio.Amount("BTC", D("0.4")), | ||
74 | "XVG": portfolio.Amount("BTC", D("-0.5")), | ||
75 | "BTC": portfolio.Amount("BTC", D("0.5")), | ||
76 | } | ||
77 | new_repartition = { | ||
78 | "DASH": portfolio.Amount("BTC", D("0.5")), | ||
79 | "XVG": portfolio.Amount("BTC", D("0.1")), | ||
80 | "BTC": portfolio.Amount("BTC", D("0.4")), | ||
81 | "ETH": portfolio.Amount("BTC", D("0.3")), | ||
82 | } | ||
83 | side_effect = [ | ||
84 | (True, 1), | ||
85 | (False, 2), | ||
86 | (False, 3), | ||
87 | (True, 4), | ||
88 | (True, 5) | ||
89 | ] | ||
90 | |||
91 | with mock.patch.object(market.TradeStore, "trade_if_matching") as trade_if_matching: | ||
92 | trade_store = market.TradeStore(self.m) | ||
93 | trade_if_matching.side_effect = side_effect | ||
94 | |||
95 | trade_store.compute_trades(values_in_base, | ||
96 | new_repartition, only="only") | ||
97 | |||
98 | self.assertEqual(5, trade_if_matching.call_count) | ||
99 | self.assertEqual(3, len(trade_store.all)) | ||
100 | self.assertEqual([1, 4, 5], trade_store.all) | ||
101 | self.m.report.log_trades.assert_called_with(side_effect, "only") | ||
102 | |||
103 | def test_trade_if_matching(self): | ||
104 | |||
105 | with self.subTest(only="nope"): | ||
106 | trade_store = market.TradeStore(self.m) | ||
107 | result = trade_store.trade_if_matching( | ||
108 | portfolio.Amount("BTC", D("0")), | ||
109 | portfolio.Amount("BTC", D("0.3")), | ||
110 | "ETH", only="nope") | ||
111 | self.assertEqual(False, result[0]) | ||
112 | self.assertIsInstance(result[1], portfolio.Trade) | ||
113 | |||
114 | with self.subTest(only=None): | ||
115 | trade_store = market.TradeStore(self.m) | ||
116 | result = trade_store.trade_if_matching( | ||
117 | portfolio.Amount("BTC", D("0")), | ||
118 | portfolio.Amount("BTC", D("0.3")), | ||
119 | "ETH", only=None) | ||
120 | self.assertEqual(True, result[0]) | ||
121 | |||
122 | with self.subTest(only="acquire"): | ||
123 | trade_store = market.TradeStore(self.m) | ||
124 | result = trade_store.trade_if_matching( | ||
125 | portfolio.Amount("BTC", D("0")), | ||
126 | portfolio.Amount("BTC", D("0.3")), | ||
127 | "ETH", only="acquire") | ||
128 | self.assertEqual(True, result[0]) | ||
129 | |||
130 | with self.subTest(only="dispose"): | ||
131 | trade_store = market.TradeStore(self.m) | ||
132 | result = trade_store.trade_if_matching( | ||
133 | portfolio.Amount("BTC", D("0")), | ||
134 | portfolio.Amount("BTC", D("0.3")), | ||
135 | "ETH", only="dispose") | ||
136 | self.assertEqual(False, result[0]) | ||
137 | |||
138 | def test_prepare_orders(self): | ||
139 | trade_store = market.TradeStore(self.m) | ||
140 | |||
141 | trade_mock1 = mock.Mock() | ||
142 | trade_mock2 = mock.Mock() | ||
143 | trade_mock3 = mock.Mock() | ||
144 | |||
145 | trade_mock1.prepare_order.return_value = 1 | ||
146 | trade_mock2.prepare_order.return_value = 2 | ||
147 | trade_mock3.prepare_order.return_value = 3 | ||
148 | |||
149 | trade_mock1.pending = True | ||
150 | trade_mock2.pending = True | ||
151 | trade_mock3.pending = False | ||
152 | |||
153 | trade_store.all.append(trade_mock1) | ||
154 | trade_store.all.append(trade_mock2) | ||
155 | trade_store.all.append(trade_mock3) | ||
156 | |||
157 | trade_store.prepare_orders() | ||
158 | trade_mock1.prepare_order.assert_called_with(compute_value="default") | ||
159 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | ||
160 | trade_mock3.prepare_order.assert_not_called() | ||
161 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "default") | ||
162 | |||
163 | self.m.report.log_orders.reset_mock() | ||
164 | |||
165 | trade_store.prepare_orders(compute_value="bla") | ||
166 | trade_mock1.prepare_order.assert_called_with(compute_value="bla") | ||
167 | trade_mock2.prepare_order.assert_called_with(compute_value="bla") | ||
168 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "bla") | ||
169 | |||
170 | trade_mock1.prepare_order.reset_mock() | ||
171 | trade_mock2.prepare_order.reset_mock() | ||
172 | self.m.report.log_orders.reset_mock() | ||
173 | |||
174 | trade_mock1.action = "foo" | ||
175 | trade_mock2.action = "bar" | ||
176 | trade_store.prepare_orders(only="bar") | ||
177 | trade_mock1.prepare_order.assert_not_called() | ||
178 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | ||
179 | self.m.report.log_orders.assert_called_once_with([2], "bar", "default") | ||
180 | |||
181 | def test_print_all_with_order(self): | ||
182 | trade_mock1 = mock.Mock() | ||
183 | trade_mock2 = mock.Mock() | ||
184 | trade_mock3 = mock.Mock() | ||
185 | trade_store = market.TradeStore(self.m) | ||
186 | trade_store.all = [trade_mock1, trade_mock2, trade_mock3] | ||
187 | |||
188 | trade_store.print_all_with_order() | ||
189 | |||
190 | trade_mock1.print_with_order.assert_called() | ||
191 | trade_mock2.print_with_order.assert_called() | ||
192 | trade_mock3.print_with_order.assert_called() | ||
193 | |||
194 | def test_run_orders(self): | ||
195 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | ||
196 | order_mock1 = mock.Mock() | ||
197 | order_mock2 = mock.Mock() | ||
198 | order_mock3 = mock.Mock() | ||
199 | trade_store = market.TradeStore(self.m) | ||
200 | |||
201 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | ||
202 | |||
203 | trade_store.run_orders() | ||
204 | |||
205 | all_orders.assert_called_with(state="pending") | ||
206 | |||
207 | order_mock1.run.assert_called() | ||
208 | order_mock2.run.assert_called() | ||
209 | order_mock3.run.assert_called() | ||
210 | |||
211 | self.m.report.log_stage.assert_called_with("run_orders") | ||
212 | self.m.report.log_orders.assert_called_with([order_mock1, order_mock2, | ||
213 | order_mock3]) | ||
214 | |||
215 | def test_all_orders(self): | ||
216 | trade_mock1 = mock.Mock() | ||
217 | trade_mock2 = mock.Mock() | ||
218 | |||
219 | order_mock1 = mock.Mock() | ||
220 | order_mock2 = mock.Mock() | ||
221 | order_mock3 = mock.Mock() | ||
222 | |||
223 | trade_mock1.orders = [order_mock1, order_mock2] | ||
224 | trade_mock2.orders = [order_mock3] | ||
225 | |||
226 | order_mock1.status = "pending" | ||
227 | order_mock2.status = "open" | ||
228 | order_mock3.status = "open" | ||
229 | |||
230 | trade_store = market.TradeStore(self.m) | ||
231 | trade_store.all.append(trade_mock1) | ||
232 | trade_store.all.append(trade_mock2) | ||
233 | |||
234 | orders = trade_store.all_orders() | ||
235 | self.assertEqual(3, len(orders)) | ||
236 | |||
237 | open_orders = trade_store.all_orders(state="open") | ||
238 | self.assertEqual(2, len(open_orders)) | ||
239 | self.assertEqual([order_mock2, order_mock3], open_orders) | ||
240 | |||
241 | def test_update_all_orders_status(self): | ||
242 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | ||
243 | order_mock1 = mock.Mock() | ||
244 | order_mock2 = mock.Mock() | ||
245 | order_mock3 = mock.Mock() | ||
246 | |||
247 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | ||
248 | |||
249 | trade_store = market.TradeStore(self.m) | ||
250 | |||
251 | trade_store.update_all_orders_status() | ||
252 | all_orders.assert_called_with(state="open") | ||
253 | |||
254 | order_mock1.get_status.assert_called() | ||
255 | order_mock2.get_status.assert_called() | ||
256 | order_mock3.get_status.assert_called() | ||
257 | |||
258 | def test_close_trades(self): | ||
259 | trade_mock1 = mock.Mock() | ||
260 | trade_mock2 = mock.Mock() | ||
261 | trade_mock3 = mock.Mock() | ||
262 | |||
263 | trade_store = market.TradeStore(self.m) | ||
264 | |||
265 | trade_store.all.append(trade_mock1) | ||
266 | trade_store.all.append(trade_mock2) | ||
267 | trade_store.all.append(trade_mock3) | ||
268 | |||
269 | trade_store.close_trades() | ||
270 | |||
271 | trade_mock1.close.assert_called_once_with() | ||
272 | trade_mock2.close.assert_called_once_with() | ||
273 | trade_mock3.close.assert_called_once_with() | ||
274 | |||
275 | def test_pending(self): | ||
276 | trade_mock1 = mock.Mock() | ||
277 | trade_mock1.pending = True | ||
278 | trade_mock2 = mock.Mock() | ||
279 | trade_mock2.pending = True | ||
280 | trade_mock3 = mock.Mock() | ||
281 | trade_mock3.pending = False | ||
282 | |||
283 | trade_store = market.TradeStore(self.m) | ||
284 | |||
285 | trade_store.all.append(trade_mock1) | ||
286 | trade_store.all.append(trade_mock2) | ||
287 | trade_store.all.append(trade_mock3) | ||
288 | |||
289 | self.assertEqual([trade_mock1, trade_mock2], trade_store.pending) | ||
290 | |||
291 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
292 | class BalanceStoreTest(WebMockTestCase): | ||
293 | def setUp(self): | ||
294 | super().setUp() | ||
295 | |||
296 | self.fetch_balance = { | ||
297 | "ETC": { | ||
298 | "exchange_free": 0, | ||
299 | "exchange_used": 0, | ||
300 | "exchange_total": 0, | ||
301 | "margin_total": 0, | ||
302 | }, | ||
303 | "USDT": { | ||
304 | "exchange_free": D("6.0"), | ||
305 | "exchange_used": D("1.2"), | ||
306 | "exchange_total": D("7.2"), | ||
307 | "margin_total": 0, | ||
308 | }, | ||
309 | "XVG": { | ||
310 | "exchange_free": 16, | ||
311 | "exchange_used": 0, | ||
312 | "exchange_total": 16, | ||
313 | "margin_total": 0, | ||
314 | }, | ||
315 | "XMR": { | ||
316 | "exchange_free": 0, | ||
317 | "exchange_used": 0, | ||
318 | "exchange_total": 0, | ||
319 | "margin_total": D("-1.0"), | ||
320 | "margin_free": 0, | ||
321 | }, | ||
322 | } | ||
323 | |||
324 | def test_in_currency(self): | ||
325 | self.m.get_ticker.return_value = { | ||
326 | "bid": D("0.09"), | ||
327 | "ask": D("0.11"), | ||
328 | "average": D("0.1"), | ||
329 | } | ||
330 | |||
331 | balance_store = market.BalanceStore(self.m) | ||
332 | balance_store.all = { | ||
333 | "BTC": portfolio.Balance("BTC", { | ||
334 | "total": "0.65", | ||
335 | "exchange_total":"0.65", | ||
336 | "exchange_free": "0.35", | ||
337 | "exchange_used": "0.30"}), | ||
338 | "ETH": portfolio.Balance("ETH", { | ||
339 | "total": 3, | ||
340 | "exchange_total": 3, | ||
341 | "exchange_free": 3, | ||
342 | "exchange_used": 0}), | ||
343 | } | ||
344 | |||
345 | amounts = balance_store.in_currency("BTC") | ||
346 | self.assertEqual("BTC", amounts["ETH"].currency) | ||
347 | self.assertEqual(D("0.65"), amounts["BTC"].value) | ||
348 | self.assertEqual(D("0.30"), amounts["ETH"].value) | ||
349 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
350 | "average", "total") | ||
351 | self.m.report.log_tickers.reset_mock() | ||
352 | |||
353 | amounts = balance_store.in_currency("BTC", compute_value="bid") | ||
354 | self.assertEqual(D("0.65"), amounts["BTC"].value) | ||
355 | self.assertEqual(D("0.27"), amounts["ETH"].value) | ||
356 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
357 | "bid", "total") | ||
358 | self.m.report.log_tickers.reset_mock() | ||
359 | |||
360 | amounts = balance_store.in_currency("BTC", compute_value="bid", type="exchange_used") | ||
361 | self.assertEqual(D("0.30"), amounts["BTC"].value) | ||
362 | self.assertEqual(0, amounts["ETH"].value) | ||
363 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
364 | "bid", "exchange_used") | ||
365 | self.m.report.log_tickers.reset_mock() | ||
366 | |||
367 | def test_fetch_balances(self): | ||
368 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | ||
369 | |||
370 | balance_store = market.BalanceStore(self.m) | ||
371 | |||
372 | balance_store.fetch_balances() | ||
373 | self.assertNotIn("ETC", balance_store.currencies()) | ||
374 | self.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store.currencies())) | ||
375 | |||
376 | balance_store.all["ETC"] = portfolio.Balance("ETC", { | ||
377 | "exchange_total": "1", "exchange_free": "0", | ||
378 | "exchange_used": "1" }) | ||
379 | balance_store.fetch_balances(tag="foo") | ||
380 | self.assertEqual(0, balance_store.all["ETC"].total) | ||
381 | self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies())) | ||
382 | self.m.report.log_balances.assert_called_with(tag="foo") | ||
383 | |||
384 | @mock.patch.object(market.Portfolio, "repartition") | ||
385 | def test_dispatch_assets(self, repartition): | ||
386 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | ||
387 | |||
388 | balance_store = market.BalanceStore(self.m) | ||
389 | balance_store.fetch_balances() | ||
390 | |||
391 | self.assertNotIn("XEM", balance_store.currencies()) | ||
392 | |||
393 | repartition_hash = { | ||
394 | "XEM": (D("0.75"), "long"), | ||
395 | "BTC": (D("0.26"), "long"), | ||
396 | "DASH": (D("0.10"), "short"), | ||
397 | } | ||
398 | repartition.return_value = repartition_hash | ||
399 | |||
400 | amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1")) | ||
401 | repartition.assert_called_with(liquidity="medium") | ||
402 | self.assertIn("XEM", balance_store.currencies()) | ||
403 | self.assertEqual(D("2.6"), amounts["BTC"].value) | ||
404 | self.assertEqual(D("7.5"), amounts["XEM"].value) | ||
405 | self.assertEqual(D("-1.0"), amounts["DASH"].value) | ||
406 | self.m.report.log_balances.assert_called_with(tag=None) | ||
407 | self.m.report.log_dispatch.assert_called_once_with(portfolio.Amount("BTC", | ||
408 | "11.1"), amounts, "medium", repartition_hash) | ||
409 | |||
410 | def test_currencies(self): | ||
411 | balance_store = market.BalanceStore(self.m) | ||
412 | |||
413 | balance_store.all = { | ||
414 | "BTC": portfolio.Balance("BTC", { | ||
415 | "total": "0.65", | ||
416 | "exchange_total":"0.65", | ||
417 | "exchange_free": "0.35", | ||
418 | "exchange_used": "0.30"}), | ||
419 | "ETH": portfolio.Balance("ETH", { | ||
420 | "total": 3, | ||
421 | "exchange_total": 3, | ||
422 | "exchange_free": 3, | ||
423 | "exchange_used": 0}), | ||
424 | } | ||
425 | self.assertListEqual(["BTC", "ETH"], list(balance_store.currencies())) | ||
426 | |||
427 | def test_as_json(self): | ||
428 | balance_mock1 = mock.Mock() | ||
429 | balance_mock1.as_json.return_value = 1 | ||
430 | |||
431 | balance_mock2 = mock.Mock() | ||
432 | balance_mock2.as_json.return_value = 2 | ||
433 | |||
434 | balance_store = market.BalanceStore(self.m) | ||
435 | balance_store.all = { | ||
436 | "BTC": balance_mock1, | ||
437 | "ETH": balance_mock2, | ||
438 | } | ||
439 | |||
440 | as_json = balance_store.as_json() | ||
441 | self.assertEqual(1, as_json["BTC"]) | ||
442 | self.assertEqual(2, as_json["ETH"]) | ||
443 | |||
444 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
445 | class ReportStoreTest(WebMockTestCase): | ||
446 | def test_add_log(self): | ||
447 | report_store = market.ReportStore(self.m) | ||
448 | report_store.add_log({"foo": "bar"}) | ||
449 | |||
450 | self.assertEqual({"foo": "bar", "date": mock.ANY}, report_store.logs[0]) | ||
451 | |||
452 | def test_set_verbose(self): | ||
453 | report_store = market.ReportStore(self.m) | ||
454 | with self.subTest(verbose=True): | ||
455 | report_store.set_verbose(True) | ||
456 | self.assertTrue(report_store.verbose_print) | ||
457 | |||
458 | with self.subTest(verbose=False): | ||
459 | report_store.set_verbose(False) | ||
460 | self.assertFalse(report_store.verbose_print) | ||
461 | |||
462 | def test_merge(self): | ||
463 | report_store1 = market.ReportStore(self.m, verbose_print=False) | ||
464 | report_store2 = market.ReportStore(None, verbose_print=False) | ||
465 | |||
466 | report_store2.log_stage("1") | ||
467 | report_store1.log_stage("2") | ||
468 | report_store2.log_stage("3") | ||
469 | |||
470 | report_store1.merge(report_store2) | ||
471 | |||
472 | self.assertEqual(3, len(report_store1.logs)) | ||
473 | self.assertEqual(["1", "2", "3"], list(map(lambda x: x["stage"], report_store1.logs))) | ||
474 | self.assertEqual(6, len(report_store1.print_logs)) | ||
475 | |||
476 | def test_print_log(self): | ||
477 | report_store = market.ReportStore(self.m) | ||
478 | with self.subTest(verbose=True),\ | ||
479 | mock.patch.object(store, "datetime") as time_mock,\ | ||
480 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
481 | time_mock.now.return_value = datetime.datetime(2018, 2, 25, 2, 20, 10) | ||
482 | report_store.set_verbose(True) | ||
483 | report_store.print_log("Coucou") | ||
484 | report_store.print_log(portfolio.Amount("BTC", 1)) | ||
485 | self.assertEqual(stdout_mock.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n") | ||
486 | |||
487 | with self.subTest(verbose=False),\ | ||
488 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
489 | report_store.set_verbose(False) | ||
490 | report_store.print_log("Coucou") | ||
491 | report_store.print_log(portfolio.Amount("BTC", 1)) | ||
492 | self.assertEqual(stdout_mock.getvalue(), "") | ||
493 | |||
494 | def test_default_json_serial(self): | ||
495 | report_store = market.ReportStore(self.m) | ||
496 | |||
497 | self.assertEqual("2018-02-24T00:00:00", | ||
498 | report_store.default_json_serial(portfolio.datetime(2018, 2, 24))) | ||
499 | self.assertEqual("1.00000000 BTC", | ||
500 | report_store.default_json_serial(portfolio.Amount("BTC", 1))) | ||
501 | |||
502 | def test_to_json(self): | ||
503 | report_store = market.ReportStore(self.m) | ||
504 | report_store.logs.append({"foo": "bar"}) | ||
505 | self.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store.to_json()) | ||
506 | report_store.logs.append({"date": portfolio.datetime(2018, 2, 24)}) | ||
507 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store.to_json()) | ||
508 | report_store.logs.append({"amount": portfolio.Amount("BTC", 1)}) | ||
509 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store.to_json()) | ||
510 | |||
511 | def test_to_json_array(self): | ||
512 | report_store = market.ReportStore(self.m) | ||
513 | report_store.logs.append({ | ||
514 | "date": "date1", "type": "type1", "foo": "bar", "bla": "bla" | ||
515 | }) | ||
516 | report_store.logs.append({ | ||
517 | "date": "date2", "type": "type2", "foo": "bar", "bla": "bla" | ||
518 | }) | ||
519 | logs = list(report_store.to_json_array()) | ||
520 | |||
521 | self.assertEqual(2, len(logs)) | ||
522 | self.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[0]) | ||
523 | self.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[1]) | ||
524 | |||
525 | @mock.patch.object(market.ReportStore, "print_log") | ||
526 | @mock.patch.object(market.ReportStore, "add_log") | ||
527 | def test_log_stage(self, add_log, print_log): | ||
528 | report_store = market.ReportStore(self.m) | ||
529 | c = lambda x: x | ||
530 | report_store.log_stage("foo", bar="baz", c=c, d=portfolio.Amount("BTC", 1)) | ||
531 | print_log.assert_has_calls([ | ||
532 | mock.call("-----------"), | ||
533 | mock.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"), | ||
534 | ]) | ||
535 | add_log.assert_called_once_with({ | ||
536 | 'type': 'stage', | ||
537 | 'stage': 'foo', | ||
538 | 'args': { | ||
539 | 'bar': 'baz', | ||
540 | 'c': 'c = lambda x: x', | ||
541 | 'd': { | ||
542 | 'currency': 'BTC', | ||
543 | 'value': D('1') | ||
544 | } | ||
545 | } | ||
546 | }) | ||
547 | |||
548 | @mock.patch.object(market.ReportStore, "print_log") | ||
549 | @mock.patch.object(market.ReportStore, "add_log") | ||
550 | def test_log_balances(self, add_log, print_log): | ||
551 | report_store = market.ReportStore(self.m) | ||
552 | self.m.balances.as_json.return_value = "json" | ||
553 | self.m.balances.all = { "FOO": "bar", "BAR": "baz" } | ||
554 | |||
555 | report_store.log_balances(tag="tag") | ||
556 | print_log.assert_has_calls([ | ||
557 | mock.call("[Balance]"), | ||
558 | mock.call("\tbar"), | ||
559 | mock.call("\tbaz"), | ||
560 | ]) | ||
561 | add_log.assert_called_once_with({ | ||
562 | 'type': 'balance', | ||
563 | 'balances': 'json', | ||
564 | 'tag': 'tag' | ||
565 | }) | ||
566 | |||
567 | @mock.patch.object(market.ReportStore, "print_log") | ||
568 | @mock.patch.object(market.ReportStore, "add_log") | ||
569 | def test_log_tickers(self, add_log, print_log): | ||
570 | report_store = market.ReportStore(self.m) | ||
571 | amounts = { | ||
572 | "BTC": portfolio.Amount("BTC", 10), | ||
573 | "ETH": portfolio.Amount("BTC", D("0.3")) | ||
574 | } | ||
575 | amounts["ETH"].rate = D("0.1") | ||
576 | |||
577 | report_store.log_tickers(amounts, "BTC", "default", "total") | ||
578 | print_log.assert_not_called() | ||
579 | add_log.assert_called_once_with({ | ||
580 | 'type': 'tickers', | ||
581 | 'compute_value': 'default', | ||
582 | 'balance_type': 'total', | ||
583 | 'currency': 'BTC', | ||
584 | 'balances': { | ||
585 | 'BTC': D('10'), | ||
586 | 'ETH': D('0.3') | ||
587 | }, | ||
588 | 'rates': { | ||
589 | 'BTC': None, | ||
590 | 'ETH': D('0.1') | ||
591 | }, | ||
592 | 'total': D('10.3') | ||
593 | }) | ||
594 | |||
595 | add_log.reset_mock() | ||
596 | compute_value = lambda x: x["bid"] | ||
597 | report_store.log_tickers(amounts, "BTC", compute_value, "total") | ||
598 | add_log.assert_called_once_with({ | ||
599 | 'type': 'tickers', | ||
600 | 'compute_value': 'compute_value = lambda x: x["bid"]', | ||
601 | 'balance_type': 'total', | ||
602 | 'currency': 'BTC', | ||
603 | 'balances': { | ||
604 | 'BTC': D('10'), | ||
605 | 'ETH': D('0.3') | ||
606 | }, | ||
607 | 'rates': { | ||
608 | 'BTC': None, | ||
609 | 'ETH': D('0.1') | ||
610 | }, | ||
611 | 'total': D('10.3') | ||
612 | }) | ||
613 | |||
614 | @mock.patch.object(market.ReportStore, "print_log") | ||
615 | @mock.patch.object(market.ReportStore, "add_log") | ||
616 | def test_log_dispatch(self, add_log, print_log): | ||
617 | report_store = market.ReportStore(self.m) | ||
618 | amount = portfolio.Amount("BTC", "10.3") | ||
619 | amounts = { | ||
620 | "BTC": portfolio.Amount("BTC", 10), | ||
621 | "ETH": portfolio.Amount("BTC", D("0.3")) | ||
622 | } | ||
623 | report_store.log_dispatch(amount, amounts, "medium", "repartition") | ||
624 | print_log.assert_not_called() | ||
625 | add_log.assert_called_once_with({ | ||
626 | 'type': 'dispatch', | ||
627 | 'liquidity': 'medium', | ||
628 | 'repartition_ratio': 'repartition', | ||
629 | 'total_amount': { | ||
630 | 'currency': 'BTC', | ||
631 | 'value': D('10.3') | ||
632 | }, | ||
633 | 'repartition': { | ||
634 | 'BTC': D('10'), | ||
635 | 'ETH': D('0.3') | ||
636 | } | ||
637 | }) | ||
638 | |||
639 | @mock.patch.object(market.ReportStore, "print_log") | ||
640 | @mock.patch.object(market.ReportStore, "add_log") | ||
641 | def test_log_trades(self, add_log, print_log): | ||
642 | report_store = market.ReportStore(self.m) | ||
643 | trade_mock1 = mock.Mock() | ||
644 | trade_mock2 = mock.Mock() | ||
645 | trade_mock1.as_json.return_value = { "trade": "1" } | ||
646 | trade_mock2.as_json.return_value = { "trade": "2" } | ||
647 | |||
648 | matching_and_trades = [ | ||
649 | (True, trade_mock1), | ||
650 | (False, trade_mock2), | ||
651 | ] | ||
652 | report_store.log_trades(matching_and_trades, "only") | ||
653 | |||
654 | print_log.assert_not_called() | ||
655 | add_log.assert_called_with({ | ||
656 | 'type': 'trades', | ||
657 | 'only': 'only', | ||
658 | 'debug': False, | ||
659 | 'trades': [ | ||
660 | {'trade': '1', 'skipped': False}, | ||
661 | {'trade': '2', 'skipped': True} | ||
662 | ] | ||
663 | }) | ||
664 | |||
665 | @mock.patch.object(market.ReportStore, "print_log") | ||
666 | @mock.patch.object(market.ReportStore, "add_log") | ||
667 | def test_log_orders(self, add_log, print_log): | ||
668 | report_store = market.ReportStore(self.m) | ||
669 | |||
670 | order_mock1 = mock.Mock() | ||
671 | order_mock2 = mock.Mock() | ||
672 | |||
673 | order_mock1.as_json.return_value = "order1" | ||
674 | order_mock2.as_json.return_value = "order2" | ||
675 | |||
676 | orders = [order_mock1, order_mock2] | ||
677 | |||
678 | report_store.log_orders(orders, tick="tick", | ||
679 | only="only", compute_value="compute_value") | ||
680 | |||
681 | print_log.assert_called_once_with("[Orders]") | ||
682 | self.m.trades.print_all_with_order.assert_called_once_with(ind="\t") | ||
683 | |||
684 | add_log.assert_called_with({ | ||
685 | 'type': 'orders', | ||
686 | 'only': 'only', | ||
687 | 'compute_value': 'compute_value', | ||
688 | 'tick': 'tick', | ||
689 | 'orders': ['order1', 'order2'] | ||
690 | }) | ||
691 | |||
692 | add_log.reset_mock() | ||
693 | def compute_value(x, y): | ||
694 | return x[y] | ||
695 | report_store.log_orders(orders, tick="tick", | ||
696 | only="only", compute_value=compute_value) | ||
697 | add_log.assert_called_with({ | ||
698 | 'type': 'orders', | ||
699 | 'only': 'only', | ||
700 | 'compute_value': 'def compute_value(x, y):\n return x[y]', | ||
701 | 'tick': 'tick', | ||
702 | 'orders': ['order1', 'order2'] | ||
703 | }) | ||
704 | |||
705 | |||
706 | @mock.patch.object(market.ReportStore, "print_log") | ||
707 | @mock.patch.object(market.ReportStore, "add_log") | ||
708 | def test_log_order(self, add_log, print_log): | ||
709 | report_store = market.ReportStore(self.m) | ||
710 | order_mock = mock.Mock() | ||
711 | order_mock.as_json.return_value = "order" | ||
712 | new_order_mock = mock.Mock() | ||
713 | new_order_mock.as_json.return_value = "new_order" | ||
714 | order_mock.__repr__ = mock.Mock() | ||
715 | order_mock.__repr__.return_value = "Order Mock" | ||
716 | new_order_mock.__repr__ = mock.Mock() | ||
717 | new_order_mock.__repr__.return_value = "New order Mock" | ||
718 | |||
719 | with self.subTest(finished=True): | ||
720 | report_store.log_order(order_mock, 1, finished=True) | ||
721 | print_log.assert_called_once_with("[Order] Finished Order Mock") | ||
722 | add_log.assert_called_once_with({ | ||
723 | 'type': 'order', | ||
724 | 'tick': 1, | ||
725 | 'update': None, | ||
726 | 'order': 'order', | ||
727 | 'compute_value': None, | ||
728 | 'new_order': None | ||
729 | }) | ||
730 | |||
731 | add_log.reset_mock() | ||
732 | print_log.reset_mock() | ||
733 | |||
734 | with self.subTest(update="waiting"): | ||
735 | report_store.log_order(order_mock, 1, update="waiting") | ||
736 | print_log.assert_called_once_with("[Order] Order Mock, tick 1, waiting") | ||
737 | add_log.assert_called_once_with({ | ||
738 | 'type': 'order', | ||
739 | 'tick': 1, | ||
740 | 'update': 'waiting', | ||
741 | 'order': 'order', | ||
742 | 'compute_value': None, | ||
743 | 'new_order': None | ||
744 | }) | ||
745 | |||
746 | add_log.reset_mock() | ||
747 | print_log.reset_mock() | ||
748 | with self.subTest(update="adjusting"): | ||
749 | compute_value = lambda x: (x["bid"] + x["ask"]*2)/3 | ||
750 | report_store.log_order(order_mock, 3, | ||
751 | update="adjusting", new_order=new_order_mock, | ||
752 | compute_value=compute_value) | ||
753 | print_log.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock") | ||
754 | add_log.assert_called_once_with({ | ||
755 | 'type': 'order', | ||
756 | 'tick': 3, | ||
757 | 'update': 'adjusting', | ||
758 | 'order': 'order', | ||
759 | 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3', | ||
760 | 'new_order': 'new_order' | ||
761 | }) | ||
762 | |||
763 | add_log.reset_mock() | ||
764 | print_log.reset_mock() | ||
765 | with self.subTest(update="market_fallback"): | ||
766 | report_store.log_order(order_mock, 7, | ||
767 | update="market_fallback", new_order=new_order_mock) | ||
768 | print_log.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value") | ||
769 | add_log.assert_called_once_with({ | ||
770 | 'type': 'order', | ||
771 | 'tick': 7, | ||
772 | 'update': 'market_fallback', | ||
773 | 'order': 'order', | ||
774 | 'compute_value': None, | ||
775 | 'new_order': 'new_order' | ||
776 | }) | ||
777 | |||
778 | add_log.reset_mock() | ||
779 | print_log.reset_mock() | ||
780 | with self.subTest(update="market_adjusting"): | ||
781 | report_store.log_order(order_mock, 17, | ||
782 | update="market_adjust", new_order=new_order_mock) | ||
783 | print_log.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock") | ||
784 | add_log.assert_called_once_with({ | ||
785 | 'type': 'order', | ||
786 | 'tick': 17, | ||
787 | 'update': 'market_adjust', | ||
788 | 'order': 'order', | ||
789 | 'compute_value': None, | ||
790 | 'new_order': 'new_order' | ||
791 | }) | ||
792 | |||
793 | @mock.patch.object(market.ReportStore, "print_log") | ||
794 | @mock.patch.object(market.ReportStore, "add_log") | ||
795 | def test_log_move_balances(self, add_log, print_log): | ||
796 | report_store = market.ReportStore(self.m) | ||
797 | needed = { | ||
798 | "BTC": portfolio.Amount("BTC", 10), | ||
799 | "USDT": 1 | ||
800 | } | ||
801 | moving = { | ||
802 | "BTC": portfolio.Amount("BTC", 3), | ||
803 | "USDT": -2 | ||
804 | } | ||
805 | report_store.log_move_balances(needed, moving) | ||
806 | print_log.assert_not_called() | ||
807 | add_log.assert_called_once_with({ | ||
808 | 'type': 'move_balances', | ||
809 | 'debug': False, | ||
810 | 'needed': { | ||
811 | 'BTC': D('10'), | ||
812 | 'USDT': 1 | ||
813 | }, | ||
814 | 'moving': { | ||
815 | 'BTC': D('3'), | ||
816 | 'USDT': -2 | ||
817 | } | ||
818 | }) | ||
819 | |||
820 | @mock.patch.object(market.ReportStore, "print_log") | ||
821 | @mock.patch.object(market.ReportStore, "add_log") | ||
822 | def test_log_http_request(self, add_log, print_log): | ||
823 | report_store = market.ReportStore(self.m) | ||
824 | response = mock.Mock() | ||
825 | response.status_code = 200 | ||
826 | response.text = "Hey" | ||
827 | |||
828 | report_store.log_http_request("method", "url", "body", | ||
829 | "headers", response) | ||
830 | print_log.assert_not_called() | ||
831 | add_log.assert_called_once_with({ | ||
832 | 'type': 'http_request', | ||
833 | 'method': 'method', | ||
834 | 'url': 'url', | ||
835 | 'body': 'body', | ||
836 | 'headers': 'headers', | ||
837 | 'status': 200, | ||
838 | 'response': 'Hey' | ||
839 | }) | ||
840 | |||
841 | add_log.reset_mock() | ||
842 | report_store.log_http_request("method", "url", "body", | ||
843 | "headers", ValueError("Foo")) | ||
844 | add_log.assert_called_once_with({ | ||
845 | 'type': 'http_request', | ||
846 | 'method': 'method', | ||
847 | 'url': 'url', | ||
848 | 'body': 'body', | ||
849 | 'headers': 'headers', | ||
850 | 'status': -1, | ||
851 | 'response': None, | ||
852 | 'error': 'ValueError', | ||
853 | 'error_message': 'Foo', | ||
854 | }) | ||
855 | |||
856 | @mock.patch.object(market.ReportStore, "add_log") | ||
857 | def test_log_market(self, add_log): | ||
858 | report_store = market.ReportStore(self.m) | ||
859 | |||
860 | report_store.log_market(self.market_args(debug=True, quiet=False), 4, 1) | ||
861 | add_log.assert_called_once_with({ | ||
862 | "type": "market", | ||
863 | "commit": "$Format:%H$", | ||
864 | "args": { "report_path": None, "debug": True, "quiet": False }, | ||
865 | "user_id": 4, | ||
866 | "market_id": 1, | ||
867 | }) | ||
868 | |||
869 | @mock.patch.object(market.ReportStore, "print_log") | ||
870 | @mock.patch.object(market.ReportStore, "add_log") | ||
871 | def test_log_error(self, add_log, print_log): | ||
872 | report_store = market.ReportStore(self.m) | ||
873 | with self.subTest(message=None, exception=None): | ||
874 | report_store.log_error("action") | ||
875 | print_log.assert_called_once_with("[Error] action") | ||
876 | add_log.assert_called_once_with({ | ||
877 | 'type': 'error', | ||
878 | 'action': 'action', | ||
879 | 'exception_class': None, | ||
880 | 'exception_message': None, | ||
881 | 'message': None | ||
882 | }) | ||
883 | |||
884 | print_log.reset_mock() | ||
885 | add_log.reset_mock() | ||
886 | with self.subTest(message="Hey", exception=None): | ||
887 | report_store.log_error("action", message="Hey") | ||
888 | print_log.assert_has_calls([ | ||
889 | mock.call("[Error] action"), | ||
890 | mock.call("\tHey") | ||
891 | ]) | ||
892 | add_log.assert_called_once_with({ | ||
893 | 'type': 'error', | ||
894 | 'action': 'action', | ||
895 | 'exception_class': None, | ||
896 | 'exception_message': None, | ||
897 | 'message': "Hey" | ||
898 | }) | ||
899 | |||
900 | print_log.reset_mock() | ||
901 | add_log.reset_mock() | ||
902 | with self.subTest(message=None, exception=Exception("bouh")): | ||
903 | report_store.log_error("action", exception=Exception("bouh")) | ||
904 | print_log.assert_has_calls([ | ||
905 | mock.call("[Error] action"), | ||
906 | mock.call("\tException: bouh") | ||
907 | ]) | ||
908 | add_log.assert_called_once_with({ | ||
909 | 'type': 'error', | ||
910 | 'action': 'action', | ||
911 | 'exception_class': "Exception", | ||
912 | 'exception_message': "bouh", | ||
913 | 'message': None | ||
914 | }) | ||
915 | |||
916 | print_log.reset_mock() | ||
917 | add_log.reset_mock() | ||
918 | with self.subTest(message="Hey", exception=Exception("bouh")): | ||
919 | report_store.log_error("action", message="Hey", exception=Exception("bouh")) | ||
920 | print_log.assert_has_calls([ | ||
921 | mock.call("[Error] action"), | ||
922 | mock.call("\tException: bouh"), | ||
923 | mock.call("\tHey") | ||
924 | ]) | ||
925 | add_log.assert_called_once_with({ | ||
926 | 'type': 'error', | ||
927 | 'action': 'action', | ||
928 | 'exception_class': "Exception", | ||
929 | 'exception_message': "bouh", | ||
930 | 'message': "Hey" | ||
931 | }) | ||
932 | |||
933 | @mock.patch.object(market.ReportStore, "print_log") | ||
934 | @mock.patch.object(market.ReportStore, "add_log") | ||
935 | def test_log_debug_action(self, add_log, print_log): | ||
936 | report_store = market.ReportStore(self.m) | ||
937 | report_store.log_debug_action("Hey") | ||
938 | |||
939 | print_log.assert_called_once_with("[Debug] Hey") | ||
940 | add_log.assert_called_once_with({ | ||
941 | 'type': 'debug_action', | ||
942 | 'action': 'Hey' | ||
943 | }) | ||
944 | |||
945 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
946 | class PortfolioTest(WebMockTestCase): | ||
947 | def setUp(self): | ||
948 | super().setUp() | ||
949 | |||
950 | with open("test_samples/test_portfolio.json") as example: | ||
951 | self.json_response = example.read() | ||
952 | |||
953 | self.wm.get(market.Portfolio.URL, text=self.json_response) | ||
954 | |||
955 | @mock.patch.object(market.Portfolio, "parse_cryptoportfolio") | ||
956 | def test_get_cryptoportfolio(self, parse_cryptoportfolio): | ||
957 | with self.subTest(parallel=False): | ||
958 | self.wm.get(market.Portfolio.URL, [ | ||
959 | {"text":'{ "foo": "bar" }', "status_code": 200}, | ||
960 | {"text": "System Error", "status_code": 500}, | ||
961 | {"exc": requests.exceptions.ConnectTimeout}, | ||
962 | ]) | ||
963 | market.Portfolio.get_cryptoportfolio() | ||
964 | self.assertIn("foo", market.Portfolio.data.get()) | ||
965 | self.assertEqual("bar", market.Portfolio.data.get()["foo"]) | ||
966 | self.assertTrue(self.wm.called) | ||
967 | self.assertEqual(1, self.wm.call_count) | ||
968 | market.Portfolio.report.log_error.assert_not_called() | ||
969 | market.Portfolio.report.log_http_request.assert_called_once() | ||
970 | parse_cryptoportfolio.assert_called_once_with() | ||
971 | market.Portfolio.report.log_http_request.reset_mock() | ||
972 | parse_cryptoportfolio.reset_mock() | ||
973 | market.Portfolio.data = store.LockedVar(None) | ||
974 | |||
975 | market.Portfolio.get_cryptoportfolio() | ||
976 | self.assertIsNone(market.Portfolio.data.get()) | ||
977 | self.assertEqual(2, self.wm.call_count) | ||
978 | parse_cryptoportfolio.assert_not_called() | ||
979 | market.Portfolio.report.log_error.assert_not_called() | ||
980 | market.Portfolio.report.log_http_request.assert_called_once() | ||
981 | market.Portfolio.report.log_http_request.reset_mock() | ||
982 | parse_cryptoportfolio.reset_mock() | ||
983 | |||
984 | market.Portfolio.data = store.LockedVar("Foo") | ||
985 | market.Portfolio.get_cryptoportfolio() | ||
986 | self.assertEqual(2, self.wm.call_count) | ||
987 | parse_cryptoportfolio.assert_not_called() | ||
988 | |||
989 | market.Portfolio.get_cryptoportfolio(refetch=True) | ||
990 | self.assertEqual("Foo", market.Portfolio.data.get()) | ||
991 | self.assertEqual(3, self.wm.call_count) | ||
992 | market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio", | ||
993 | exception=mock.ANY) | ||
994 | market.Portfolio.report.log_http_request.assert_not_called() | ||
995 | with self.subTest(parallel=True): | ||
996 | with mock.patch.object(market.Portfolio, "is_worker_thread") as is_worker,\ | ||
997 | mock.patch.object(market.Portfolio, "notify_and_wait") as notify: | ||
998 | with self.subTest(worker=True): | ||
999 | market.Portfolio.data = store.LockedVar(None) | ||
1000 | market.Portfolio.worker = mock.Mock() | ||
1001 | is_worker.return_value = True | ||
1002 | self.wm.get(market.Portfolio.URL, [ | ||
1003 | {"text":'{ "foo": "bar" }', "status_code": 200}, | ||
1004 | ]) | ||
1005 | market.Portfolio.get_cryptoportfolio() | ||
1006 | self.assertIn("foo", market.Portfolio.data.get()) | ||
1007 | parse_cryptoportfolio.reset_mock() | ||
1008 | with self.subTest(worker=False): | ||
1009 | market.Portfolio.data = store.LockedVar(None) | ||
1010 | market.Portfolio.worker = mock.Mock() | ||
1011 | is_worker.return_value = False | ||
1012 | market.Portfolio.get_cryptoportfolio() | ||
1013 | notify.assert_called_once_with() | ||
1014 | parse_cryptoportfolio.assert_not_called() | ||
1015 | |||
1016 | def test_parse_cryptoportfolio(self): | ||
1017 | with self.subTest(description="Normal case"): | ||
1018 | market.Portfolio.data = store.LockedVar(store.json.loads( | ||
1019 | self.json_response, parse_int=D, parse_float=D)) | ||
1020 | market.Portfolio.parse_cryptoportfolio() | ||
1021 | |||
1022 | self.assertListEqual( | ||
1023 | ["medium", "high"], | ||
1024 | list(market.Portfolio.liquidities.get().keys())) | ||
1025 | |||
1026 | liquidities = market.Portfolio.liquidities.get() | ||
1027 | self.assertEqual(10, len(liquidities["medium"].keys())) | ||
1028 | self.assertEqual(10, len(liquidities["high"].keys())) | ||
1029 | |||
1030 | expected = { | ||
1031 | 'BTC': (D("0.2857"), "long"), | ||
1032 | 'DGB': (D("0.1015"), "long"), | ||
1033 | 'DOGE': (D("0.1805"), "long"), | ||
1034 | 'SC': (D("0.0623"), "long"), | ||
1035 | 'ZEC': (D("0.3701"), "long"), | ||
1036 | } | ||
1037 | date = portfolio.datetime(2018, 1, 8) | ||
1038 | self.assertDictEqual(expected, liquidities["high"][date]) | ||
1039 | |||
1040 | expected = { | ||
1041 | 'BTC': (D("1.1102e-16"), "long"), | ||
1042 | 'ETC': (D("0.1"), "long"), | ||
1043 | 'FCT': (D("0.1"), "long"), | ||
1044 | 'GAS': (D("0.1"), "long"), | ||
1045 | 'NAV': (D("0.1"), "long"), | ||
1046 | 'OMG': (D("0.1"), "long"), | ||
1047 | 'OMNI': (D("0.1"), "long"), | ||
1048 | 'PPC': (D("0.1"), "long"), | ||
1049 | 'RIC': (D("0.1"), "long"), | ||
1050 | 'VIA': (D("0.1"), "long"), | ||
1051 | 'XCP': (D("0.1"), "long"), | ||
1052 | } | ||
1053 | self.assertDictEqual(expected, liquidities["medium"][date]) | ||
1054 | self.assertEqual(portfolio.datetime(2018, 1, 15), market.Portfolio.last_date.get()) | ||
1055 | |||
1056 | with self.subTest(description="Missing weight"): | ||
1057 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | ||
1058 | del(data["portfolio_2"]["weights"]) | ||
1059 | market.Portfolio.data = store.LockedVar(data) | ||
1060 | |||
1061 | market.Portfolio.parse_cryptoportfolio() | ||
1062 | self.assertListEqual( | ||
1063 | ["medium", "high"], | ||
1064 | list(market.Portfolio.liquidities.get().keys())) | ||
1065 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | ||
1066 | |||
1067 | with self.subTest(description="All missing weights"): | ||
1068 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | ||
1069 | del(data["portfolio_1"]["weights"]) | ||
1070 | del(data["portfolio_2"]["weights"]) | ||
1071 | market.Portfolio.data = store.LockedVar(data) | ||
1072 | |||
1073 | market.Portfolio.parse_cryptoportfolio() | ||
1074 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | ||
1075 | self.assertEqual({}, market.Portfolio.liquidities.get("high")) | ||
1076 | self.assertEqual(datetime.datetime(1,1,1), market.Portfolio.last_date.get()) | ||
1077 | |||
1078 | |||
1079 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | ||
1080 | def test_repartition(self, get_cryptoportfolio): | ||
1081 | market.Portfolio.liquidities = store.LockedVar({ | ||
1082 | "medium": { | ||
1083 | "2018-03-01": "medium_2018-03-01", | ||
1084 | "2018-03-08": "medium_2018-03-08", | ||
1085 | }, | ||
1086 | "high": { | ||
1087 | "2018-03-01": "high_2018-03-01", | ||
1088 | "2018-03-08": "high_2018-03-08", | ||
1089 | } | ||
1090 | }) | ||
1091 | market.Portfolio.last_date = store.LockedVar("2018-03-08") | ||
1092 | |||
1093 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition()) | ||
1094 | get_cryptoportfolio.assert_called_once_with() | ||
1095 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition(liquidity="medium")) | ||
1096 | self.assertEqual("high_2018-03-08", market.Portfolio.repartition(liquidity="high")) | ||
1097 | |||
1098 | @mock.patch.object(market.time, "sleep") | ||
1099 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | ||
1100 | def test_wait_for_recent(self, get_cryptoportfolio, sleep): | ||
1101 | self.call_count = 0 | ||
1102 | def _get(refetch=False): | ||
1103 | if self.call_count != 0: | ||
1104 | self.assertTrue(refetch) | ||
1105 | else: | ||
1106 | self.assertFalse(refetch) | ||
1107 | self.call_count += 1 | ||
1108 | market.Portfolio.last_date = store.LockedVar(store.datetime.now()\ | ||
1109 | - store.timedelta(10)\ | ||
1110 | + store.timedelta(self.call_count)) | ||
1111 | get_cryptoportfolio.side_effect = _get | ||
1112 | |||
1113 | market.Portfolio.wait_for_recent() | ||
1114 | sleep.assert_called_with(30) | ||
1115 | self.assertEqual(6, sleep.call_count) | ||
1116 | self.assertEqual(7, get_cryptoportfolio.call_count) | ||
1117 | market.Portfolio.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio") | ||
1118 | |||
1119 | sleep.reset_mock() | ||
1120 | get_cryptoportfolio.reset_mock() | ||
1121 | market.Portfolio.last_date = store.LockedVar(None) | ||
1122 | self.call_count = 0 | ||
1123 | market.Portfolio.wait_for_recent(delta=15) | ||
1124 | sleep.assert_not_called() | ||
1125 | self.assertEqual(1, get_cryptoportfolio.call_count) | ||
1126 | |||
1127 | sleep.reset_mock() | ||
1128 | get_cryptoportfolio.reset_mock() | ||
1129 | market.Portfolio.last_date = store.LockedVar(None) | ||
1130 | self.call_count = 0 | ||
1131 | market.Portfolio.wait_for_recent(delta=1) | ||
1132 | sleep.assert_called_with(30) | ||
1133 | self.assertEqual(9, sleep.call_count) | ||
1134 | self.assertEqual(10, get_cryptoportfolio.call_count) | ||
1135 | |||
1136 | def test_is_worker_thread(self): | ||
1137 | with self.subTest(worker=None): | ||
1138 | self.assertFalse(store.Portfolio.is_worker_thread()) | ||
1139 | |||
1140 | with self.subTest(worker="not self"),\ | ||
1141 | mock.patch("threading.current_thread") as current_thread: | ||
1142 | current = mock.Mock() | ||
1143 | current_thread.return_value = current | ||
1144 | store.Portfolio.worker = mock.Mock() | ||
1145 | self.assertFalse(store.Portfolio.is_worker_thread()) | ||
1146 | |||
1147 | with self.subTest(worker="self"),\ | ||
1148 | mock.patch("threading.current_thread") as current_thread: | ||
1149 | current = mock.Mock() | ||
1150 | current_thread.return_value = current | ||
1151 | store.Portfolio.worker = current | ||
1152 | self.assertTrue(store.Portfolio.is_worker_thread()) | ||
1153 | |||
1154 | def test_start_worker(self): | ||
1155 | with mock.patch.object(store.Portfolio, "wait_for_notification") as notification: | ||
1156 | store.Portfolio.start_worker() | ||
1157 | notification.assert_called_once_with(poll=30) | ||
1158 | |||
1159 | self.assertEqual("lock", store.Portfolio.last_date.lock.__class__.__name__) | ||
1160 | self.assertEqual("lock", store.Portfolio.liquidities.lock.__class__.__name__) | ||
1161 | store.Portfolio.report.start_lock.assert_called_once_with() | ||
1162 | |||
1163 | self.assertIsNotNone(store.Portfolio.worker) | ||
1164 | self.assertIsNotNone(store.Portfolio.worker_notify) | ||
1165 | self.assertIsNotNone(store.Portfolio.callback) | ||
1166 | self.assertTrue(store.Portfolio.worker_started) | ||
1167 | |||
1168 | self.assertFalse(store.Portfolio.worker.is_alive()) | ||
1169 | |||
1170 | def test_wait_for_notification(self): | ||
1171 | with self.assertRaises(RuntimeError): | ||
1172 | store.Portfolio.wait_for_notification() | ||
1173 | |||
1174 | with mock.patch.object(store.Portfolio, "get_cryptoportfolio") as get,\ | ||
1175 | mock.patch.object(store.Portfolio, "report") as report,\ | ||
1176 | mock.patch.object(store.time, "sleep") as sleep: | ||
1177 | store.Portfolio.start_worker(poll=3) | ||
1178 | |||
1179 | store.Portfolio.worker_notify.set() | ||
1180 | |||
1181 | store.Portfolio.callback.wait() | ||
1182 | |||
1183 | report.print_log.assert_called_once_with("Fetching cryptoportfolio") | ||
1184 | get.assert_called_once_with(refetch=True) | ||
1185 | sleep.assert_called_once_with(3) | ||
1186 | self.assertFalse(store.Portfolio.worker_notify.is_set()) | ||
1187 | self.assertTrue(store.Portfolio.worker.is_alive()) | ||
1188 | |||
1189 | store.Portfolio.callback.clear() | ||
1190 | store.Portfolio.worker_started = False | ||
1191 | store.Portfolio.worker_notify.set() | ||
1192 | store.Portfolio.callback.wait() | ||
1193 | self.assertFalse(store.Portfolio.worker.is_alive()) | ||
1194 | |||
1195 | def test_notify_and_wait(self): | ||
1196 | with mock.patch.object(store.Portfolio, "callback") as callback,\ | ||
1197 | mock.patch.object(store.Portfolio, "worker_notify") as worker_notify: | ||
1198 | store.Portfolio.notify_and_wait() | ||
1199 | callback.clear.assert_called_once_with() | ||
1200 | worker_notify.set.assert_called_once_with() | ||
1201 | callback.wait.assert_called_once_with() | ||
1202 | |||
1203 | |||