]>
Commit | Line | Data |
---|---|---|
1aa7d4fa | 1 | import sys |
dd359bc0 IB |
2 | import portfolio |
3 | import unittest | |
f86ee140 | 4 | import datetime |
5ab23e1c | 5 | from decimal import Decimal as D |
dd359bc0 | 6 | from unittest import mock |
80cdd672 IB |
7 | import requests |
8 | import requests_mock | |
c51687d2 | 9 | from io import StringIO |
f86ee140 | 10 | import portfolio, helper, market |
dd359bc0 | 11 | |
1aa7d4fa IB |
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 | ||
80cdd672 IB |
22 | class WebMockTestCase(unittest.TestCase): |
23 | import time | |
24 | ||
25 | def setUp(self): | |
26 | super(WebMockTestCase, self).setUp() | |
27 | self.wm = requests_mock.Mocker() | |
28 | self.wm.start() | |
29 | ||
f86ee140 IB |
30 | # market |
31 | self.m = mock.Mock(name="Market", spec=market.Market) | |
32 | self.m.debug = False | |
33 | ||
80cdd672 | 34 | self.patchers = [ |
9f54fd9a | 35 | mock.patch.multiple(portfolio.Portfolio, last_date=None, data=None, liquidities={}), |
80cdd672 | 36 | mock.patch.multiple(portfolio.Computation, |
6ca5a1ec | 37 | computations=portfolio.Computation.computations), |
f86ee140 | 38 | mock.patch.multiple(market.Market, |
6ca5a1ec IB |
39 | fees_cache={}, |
40 | ticker_cache={}, | |
41 | ticker_cache_timestamp=self.time.time()), | |
80cdd672 IB |
42 | ] |
43 | for patcher in self.patchers: | |
44 | patcher.start() | |
45 | ||
80cdd672 IB |
46 | def tearDown(self): |
47 | for patcher in self.patchers: | |
48 | patcher.stop() | |
49 | self.wm.stop() | |
50 | super(WebMockTestCase, self).tearDown() | |
51 | ||
1aa7d4fa | 52 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
80cdd672 IB |
53 | class PortfolioTest(WebMockTestCase): |
54 | def fill_data(self): | |
55 | if self.json_response is not None: | |
56 | portfolio.Portfolio.data = self.json_response | |
57 | ||
58 | def setUp(self): | |
59 | super(PortfolioTest, self).setUp() | |
60 | ||
61 | with open("test_portfolio.json") as example: | |
62 | self.json_response = example.read() | |
63 | ||
64 | self.wm.get(portfolio.Portfolio.URL, text=self.json_response) | |
65 | ||
f86ee140 | 66 | def test_get_cryptoportfolio(self): |
80cdd672 IB |
67 | self.wm.get(portfolio.Portfolio.URL, [ |
68 | {"text":'{ "foo": "bar" }', "status_code": 200}, | |
69 | {"text": "System Error", "status_code": 500}, | |
70 | {"exc": requests.exceptions.ConnectTimeout}, | |
71 | ]) | |
f86ee140 | 72 | portfolio.Portfolio.get_cryptoportfolio(self.m) |
80cdd672 IB |
73 | self.assertIn("foo", portfolio.Portfolio.data) |
74 | self.assertEqual("bar", portfolio.Portfolio.data["foo"]) | |
75 | self.assertTrue(self.wm.called) | |
76 | self.assertEqual(1, self.wm.call_count) | |
f86ee140 IB |
77 | self.m.report.log_error.assert_not_called() |
78 | self.m.report.log_http_request.assert_called_once() | |
79 | self.m.report.log_http_request.reset_mock() | |
80cdd672 | 80 | |
f86ee140 | 81 | portfolio.Portfolio.get_cryptoportfolio(self.m) |
80cdd672 IB |
82 | self.assertIsNone(portfolio.Portfolio.data) |
83 | self.assertEqual(2, self.wm.call_count) | |
f86ee140 IB |
84 | self.m.report.log_error.assert_not_called() |
85 | self.m.report.log_http_request.assert_called_once() | |
86 | self.m.report.log_http_request.reset_mock() | |
3d0247f9 | 87 | |
80cdd672 IB |
88 | |
89 | portfolio.Portfolio.data = "Foo" | |
f86ee140 | 90 | portfolio.Portfolio.get_cryptoportfolio(self.m) |
80cdd672 IB |
91 | self.assertEqual("Foo", portfolio.Portfolio.data) |
92 | self.assertEqual(3, self.wm.call_count) | |
f86ee140 | 93 | self.m.report.log_error.assert_called_once_with("get_cryptoportfolio", |
3d0247f9 | 94 | exception=mock.ANY) |
f86ee140 | 95 | self.m.report.log_http_request.assert_not_called() |
80cdd672 | 96 | |
f86ee140 IB |
97 | def test_parse_cryptoportfolio(self): |
98 | portfolio.Portfolio.parse_cryptoportfolio(self.m) | |
80cdd672 IB |
99 | |
100 | self.assertListEqual( | |
101 | ["medium", "high"], | |
102 | list(portfolio.Portfolio.liquidities.keys())) | |
103 | ||
104 | liquidities = portfolio.Portfolio.liquidities | |
105 | self.assertEqual(10, len(liquidities["medium"].keys())) | |
106 | self.assertEqual(10, len(liquidities["high"].keys())) | |
107 | ||
108 | expected = { | |
109 | 'BTC': (D("0.2857"), "long"), | |
110 | 'DGB': (D("0.1015"), "long"), | |
111 | 'DOGE': (D("0.1805"), "long"), | |
112 | 'SC': (D("0.0623"), "long"), | |
113 | 'ZEC': (D("0.3701"), "long"), | |
114 | } | |
9f54fd9a IB |
115 | date = portfolio.datetime(2018, 1, 8) |
116 | self.assertDictEqual(expected, liquidities["high"][date]) | |
80cdd672 IB |
117 | |
118 | expected = { | |
119 | 'BTC': (D("1.1102e-16"), "long"), | |
120 | 'ETC': (D("0.1"), "long"), | |
121 | 'FCT': (D("0.1"), "long"), | |
122 | 'GAS': (D("0.1"), "long"), | |
123 | 'NAV': (D("0.1"), "long"), | |
124 | 'OMG': (D("0.1"), "long"), | |
125 | 'OMNI': (D("0.1"), "long"), | |
126 | 'PPC': (D("0.1"), "long"), | |
127 | 'RIC': (D("0.1"), "long"), | |
128 | 'VIA': (D("0.1"), "long"), | |
129 | 'XCP': (D("0.1"), "long"), | |
130 | } | |
9f54fd9a IB |
131 | self.assertDictEqual(expected, liquidities["medium"][date]) |
132 | self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date) | |
80cdd672 | 133 | |
f86ee140 | 134 | self.m.report.log_http_request.assert_called_once_with("GET", |
3d0247f9 | 135 | portfolio.Portfolio.URL, None, mock.ANY, mock.ANY) |
f86ee140 | 136 | self.m.report.log_http_request.reset_mock() |
3d0247f9 | 137 | |
80cdd672 | 138 | # It doesn't refetch the data when available |
f86ee140 IB |
139 | portfolio.Portfolio.parse_cryptoportfolio(self.m) |
140 | self.m.report.log_http_request.assert_not_called() | |
80cdd672 IB |
141 | |
142 | self.assertEqual(1, self.wm.call_count) | |
143 | ||
f86ee140 | 144 | portfolio.Portfolio.parse_cryptoportfolio(self.m, refetch=True) |
9f54fd9a | 145 | self.assertEqual(2, self.wm.call_count) |
f86ee140 | 146 | self.m.report.log_http_request.assert_called_once() |
9f54fd9a | 147 | |
f86ee140 | 148 | def test_repartition(self): |
80cdd672 IB |
149 | expected_medium = { |
150 | 'BTC': (D("1.1102e-16"), "long"), | |
151 | 'USDT': (D("0.1"), "long"), | |
152 | 'ETC': (D("0.1"), "long"), | |
153 | 'FCT': (D("0.1"), "long"), | |
154 | 'OMG': (D("0.1"), "long"), | |
155 | 'STEEM': (D("0.1"), "long"), | |
156 | 'STRAT': (D("0.1"), "long"), | |
157 | 'XEM': (D("0.1"), "long"), | |
158 | 'XMR': (D("0.1"), "long"), | |
159 | 'XVC': (D("0.1"), "long"), | |
160 | 'ZRX': (D("0.1"), "long"), | |
161 | } | |
162 | expected_high = { | |
163 | 'USDT': (D("0.1226"), "long"), | |
164 | 'BTC': (D("0.1429"), "long"), | |
165 | 'ETC': (D("0.1127"), "long"), | |
166 | 'ETH': (D("0.1569"), "long"), | |
167 | 'FCT': (D("0.3341"), "long"), | |
168 | 'GAS': (D("0.1308"), "long"), | |
169 | } | |
170 | ||
f86ee140 IB |
171 | self.assertEqual(expected_medium, portfolio.Portfolio.repartition(self.m)) |
172 | self.assertEqual(expected_medium, portfolio.Portfolio.repartition(self.m, liquidity="medium")) | |
173 | self.assertEqual(expected_high, portfolio.Portfolio.repartition(self.m, liquidity="high")) | |
80cdd672 | 174 | |
9f54fd9a IB |
175 | self.assertEqual(1, self.wm.call_count) |
176 | ||
f86ee140 | 177 | portfolio.Portfolio.repartition(self.m) |
9f54fd9a IB |
178 | self.assertEqual(1, self.wm.call_count) |
179 | ||
f86ee140 | 180 | portfolio.Portfolio.repartition(self.m, refetch=True) |
9f54fd9a | 181 | self.assertEqual(2, self.wm.call_count) |
f86ee140 IB |
182 | self.m.report.log_http_request.assert_called() |
183 | self.assertEqual(2, self.m.report.log_http_request.call_count) | |
9f54fd9a IB |
184 | |
185 | @mock.patch.object(portfolio.time, "sleep") | |
186 | @mock.patch.object(portfolio.Portfolio, "repartition") | |
187 | def test_wait_for_recent(self, repartition, sleep): | |
188 | self.call_count = 0 | |
f86ee140 IB |
189 | def _repartition(market, refetch): |
190 | self.assertEqual(self.m, market) | |
9f54fd9a IB |
191 | self.assertTrue(refetch) |
192 | self.call_count += 1 | |
193 | portfolio.Portfolio.last_date = portfolio.datetime.now()\ | |
194 | - portfolio.timedelta(10)\ | |
195 | + portfolio.timedelta(self.call_count) | |
196 | repartition.side_effect = _repartition | |
197 | ||
f86ee140 | 198 | portfolio.Portfolio.wait_for_recent(self.m) |
9f54fd9a IB |
199 | sleep.assert_called_with(30) |
200 | self.assertEqual(6, sleep.call_count) | |
201 | self.assertEqual(7, repartition.call_count) | |
f86ee140 | 202 | self.m.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio") |
9f54fd9a IB |
203 | |
204 | sleep.reset_mock() | |
205 | repartition.reset_mock() | |
206 | portfolio.Portfolio.last_date = None | |
207 | self.call_count = 0 | |
f86ee140 | 208 | portfolio.Portfolio.wait_for_recent(self.m, delta=15) |
9f54fd9a IB |
209 | sleep.assert_not_called() |
210 | self.assertEqual(1, repartition.call_count) | |
211 | ||
212 | sleep.reset_mock() | |
213 | repartition.reset_mock() | |
214 | portfolio.Portfolio.last_date = None | |
215 | self.call_count = 0 | |
f86ee140 | 216 | portfolio.Portfolio.wait_for_recent(self.m, delta=1) |
9f54fd9a IB |
217 | sleep.assert_called_with(30) |
218 | self.assertEqual(9, sleep.call_count) | |
219 | self.assertEqual(10, repartition.call_count) | |
220 | ||
1aa7d4fa | 221 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
80cdd672 | 222 | class AmountTest(WebMockTestCase): |
dd359bc0 | 223 | def test_values(self): |
5ab23e1c IB |
224 | amount = portfolio.Amount("BTC", "0.65") |
225 | self.assertEqual(D("0.65"), amount.value) | |
dd359bc0 IB |
226 | self.assertEqual("BTC", amount.currency) |
227 | ||
dd359bc0 IB |
228 | def test_in_currency(self): |
229 | amount = portfolio.Amount("ETC", 10) | |
230 | ||
f86ee140 | 231 | self.assertEqual(amount, amount.in_currency("ETC", self.m)) |
dd359bc0 | 232 | |
f86ee140 IB |
233 | with self.subTest(desc="no ticker for currency"): |
234 | self.m.get_ticker.return_value = None | |
dd359bc0 | 235 | |
f86ee140 | 236 | self.assertRaises(Exception, amount.in_currency, "ETH", self.m) |
dd359bc0 | 237 | |
f86ee140 IB |
238 | with self.subTest(desc="nominal case"): |
239 | self.m.get_ticker.return_value = { | |
deb8924c IB |
240 | "bid": D("0.2"), |
241 | "ask": D("0.4"), | |
5ab23e1c | 242 | "average": D("0.3"), |
dd359bc0 IB |
243 | "foo": "bar", |
244 | } | |
f86ee140 | 245 | converted_amount = amount.in_currency("ETH", self.m) |
dd359bc0 | 246 | |
5ab23e1c | 247 | self.assertEqual(D("3.0"), converted_amount.value) |
dd359bc0 IB |
248 | self.assertEqual("ETH", converted_amount.currency) |
249 | self.assertEqual(amount, converted_amount.linked_to) | |
250 | self.assertEqual("bar", converted_amount.ticker["foo"]) | |
251 | ||
f86ee140 | 252 | converted_amount = amount.in_currency("ETH", self.m, action="bid", compute_value="default") |
deb8924c IB |
253 | self.assertEqual(D("2"), converted_amount.value) |
254 | ||
f86ee140 | 255 | converted_amount = amount.in_currency("ETH", self.m, compute_value="ask") |
deb8924c IB |
256 | self.assertEqual(D("4"), converted_amount.value) |
257 | ||
f86ee140 | 258 | converted_amount = amount.in_currency("ETH", self.m, rate=D("0.02")) |
c2644ba8 IB |
259 | self.assertEqual(D("0.2"), converted_amount.value) |
260 | ||
80cdd672 IB |
261 | def test__round(self): |
262 | amount = portfolio.Amount("BAR", portfolio.D("1.23456789876")) | |
263 | self.assertEqual(D("1.23456789"), round(amount).value) | |
264 | self.assertEqual(D("1.23"), round(amount, 2).value) | |
265 | ||
dd359bc0 IB |
266 | def test__abs(self): |
267 | amount = portfolio.Amount("SC", -120) | |
268 | self.assertEqual(120, abs(amount).value) | |
269 | self.assertEqual("SC", abs(amount).currency) | |
270 | ||
271 | amount = portfolio.Amount("SC", 10) | |
272 | self.assertEqual(10, abs(amount).value) | |
273 | self.assertEqual("SC", abs(amount).currency) | |
274 | ||
275 | def test__add(self): | |
5ab23e1c IB |
276 | amount1 = portfolio.Amount("XVG", "12.9") |
277 | amount2 = portfolio.Amount("XVG", "13.1") | |
dd359bc0 IB |
278 | |
279 | self.assertEqual(26, (amount1 + amount2).value) | |
280 | self.assertEqual("XVG", (amount1 + amount2).currency) | |
281 | ||
5ab23e1c | 282 | amount3 = portfolio.Amount("ETH", "1.6") |
dd359bc0 IB |
283 | with self.assertRaises(Exception): |
284 | amount1 + amount3 | |
285 | ||
286 | amount4 = portfolio.Amount("ETH", 0.0) | |
287 | self.assertEqual(amount1, amount1 + amount4) | |
288 | ||
f320eb8a IB |
289 | self.assertEqual(amount1, amount1 + 0) |
290 | ||
dd359bc0 | 291 | def test__radd(self): |
5ab23e1c | 292 | amount = portfolio.Amount("XVG", "12.9") |
dd359bc0 IB |
293 | |
294 | self.assertEqual(amount, 0 + amount) | |
295 | with self.assertRaises(Exception): | |
296 | 4 + amount | |
297 | ||
298 | def test__sub(self): | |
5ab23e1c IB |
299 | amount1 = portfolio.Amount("XVG", "13.3") |
300 | amount2 = portfolio.Amount("XVG", "13.1") | |
dd359bc0 | 301 | |
5ab23e1c | 302 | self.assertEqual(D("0.2"), (amount1 - amount2).value) |
dd359bc0 IB |
303 | self.assertEqual("XVG", (amount1 - amount2).currency) |
304 | ||
5ab23e1c | 305 | amount3 = portfolio.Amount("ETH", "1.6") |
dd359bc0 IB |
306 | with self.assertRaises(Exception): |
307 | amount1 - amount3 | |
308 | ||
309 | amount4 = portfolio.Amount("ETH", 0.0) | |
310 | self.assertEqual(amount1, amount1 - amount4) | |
311 | ||
f320eb8a IB |
312 | def test__rsub(self): |
313 | amount = portfolio.Amount("ETH", "1.6") | |
314 | with self.assertRaises(Exception): | |
315 | 3 - amount | |
316 | ||
f86ee140 | 317 | self.assertEqual(portfolio.Amount("ETH", "-1.6"), 0-amount) |
f320eb8a | 318 | |
dd359bc0 IB |
319 | def test__mul(self): |
320 | amount = portfolio.Amount("XEM", 11) | |
321 | ||
5ab23e1c IB |
322 | self.assertEqual(D("38.5"), (amount * D("3.5")).value) |
323 | self.assertEqual(D("33"), (amount * 3).value) | |
dd359bc0 IB |
324 | |
325 | with self.assertRaises(Exception): | |
326 | amount * amount | |
327 | ||
328 | def test__rmul(self): | |
329 | amount = portfolio.Amount("XEM", 11) | |
330 | ||
5ab23e1c IB |
331 | self.assertEqual(D("38.5"), (D("3.5") * amount).value) |
332 | self.assertEqual(D("33"), (3 * amount).value) | |
dd359bc0 IB |
333 | |
334 | def test__floordiv(self): | |
335 | amount = portfolio.Amount("XEM", 11) | |
336 | ||
5ab23e1c IB |
337 | self.assertEqual(D("5.5"), (amount / 2).value) |
338 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | |
dd359bc0 | 339 | |
1aa7d4fa IB |
340 | with self.assertRaises(Exception): |
341 | amount / amount | |
342 | ||
80cdd672 | 343 | def test__truediv(self): |
dd359bc0 IB |
344 | amount = portfolio.Amount("XEM", 11) |
345 | ||
5ab23e1c IB |
346 | self.assertEqual(D("5.5"), (amount / 2).value) |
347 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | |
dd359bc0 IB |
348 | |
349 | def test__lt(self): | |
350 | amount1 = portfolio.Amount("BTD", 11.3) | |
351 | amount2 = portfolio.Amount("BTD", 13.1) | |
352 | ||
353 | self.assertTrue(amount1 < amount2) | |
354 | self.assertFalse(amount2 < amount1) | |
355 | self.assertFalse(amount1 < amount1) | |
356 | ||
357 | amount3 = portfolio.Amount("BTC", 1.6) | |
358 | with self.assertRaises(Exception): | |
359 | amount1 < amount3 | |
360 | ||
80cdd672 IB |
361 | def test__le(self): |
362 | amount1 = portfolio.Amount("BTD", 11.3) | |
363 | amount2 = portfolio.Amount("BTD", 13.1) | |
364 | ||
365 | self.assertTrue(amount1 <= amount2) | |
366 | self.assertFalse(amount2 <= amount1) | |
367 | self.assertTrue(amount1 <= amount1) | |
368 | ||
369 | amount3 = portfolio.Amount("BTC", 1.6) | |
370 | with self.assertRaises(Exception): | |
371 | amount1 <= amount3 | |
372 | ||
373 | def test__gt(self): | |
374 | amount1 = portfolio.Amount("BTD", 11.3) | |
375 | amount2 = portfolio.Amount("BTD", 13.1) | |
376 | ||
377 | self.assertTrue(amount2 > amount1) | |
378 | self.assertFalse(amount1 > amount2) | |
379 | self.assertFalse(amount1 > amount1) | |
380 | ||
381 | amount3 = portfolio.Amount("BTC", 1.6) | |
382 | with self.assertRaises(Exception): | |
383 | amount3 > amount1 | |
384 | ||
385 | def test__ge(self): | |
386 | amount1 = portfolio.Amount("BTD", 11.3) | |
387 | amount2 = portfolio.Amount("BTD", 13.1) | |
388 | ||
389 | self.assertTrue(amount2 >= amount1) | |
390 | self.assertFalse(amount1 >= amount2) | |
391 | self.assertTrue(amount1 >= amount1) | |
392 | ||
393 | amount3 = portfolio.Amount("BTC", 1.6) | |
394 | with self.assertRaises(Exception): | |
395 | amount3 >= amount1 | |
396 | ||
dd359bc0 IB |
397 | def test__eq(self): |
398 | amount1 = portfolio.Amount("BTD", 11.3) | |
399 | amount2 = portfolio.Amount("BTD", 13.1) | |
400 | amount3 = portfolio.Amount("BTD", 11.3) | |
401 | ||
402 | self.assertFalse(amount1 == amount2) | |
403 | self.assertFalse(amount2 == amount1) | |
404 | self.assertTrue(amount1 == amount3) | |
405 | self.assertFalse(amount2 == 0) | |
406 | ||
407 | amount4 = portfolio.Amount("BTC", 1.6) | |
408 | with self.assertRaises(Exception): | |
409 | amount1 == amount4 | |
410 | ||
411 | amount5 = portfolio.Amount("BTD", 0) | |
412 | self.assertTrue(amount5 == 0) | |
413 | ||
80cdd672 IB |
414 | def test__ne(self): |
415 | amount1 = portfolio.Amount("BTD", 11.3) | |
416 | amount2 = portfolio.Amount("BTD", 13.1) | |
417 | amount3 = portfolio.Amount("BTD", 11.3) | |
418 | ||
419 | self.assertTrue(amount1 != amount2) | |
420 | self.assertTrue(amount2 != amount1) | |
421 | self.assertFalse(amount1 != amount3) | |
422 | self.assertTrue(amount2 != 0) | |
423 | ||
424 | amount4 = portfolio.Amount("BTC", 1.6) | |
425 | with self.assertRaises(Exception): | |
426 | amount1 != amount4 | |
427 | ||
428 | amount5 = portfolio.Amount("BTD", 0) | |
429 | self.assertFalse(amount5 != 0) | |
430 | ||
431 | def test__neg(self): | |
432 | amount1 = portfolio.Amount("BTD", "11.3") | |
433 | ||
434 | self.assertEqual(portfolio.D("-11.3"), (-amount1).value) | |
435 | ||
dd359bc0 IB |
436 | def test__str(self): |
437 | amount1 = portfolio.Amount("BTX", 32) | |
438 | self.assertEqual("32.00000000 BTX", str(amount1)) | |
439 | ||
440 | amount2 = portfolio.Amount("USDT", 12000) | |
441 | amount1.linked_to = amount2 | |
442 | self.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1)) | |
443 | ||
444 | def test__repr(self): | |
445 | amount1 = portfolio.Amount("BTX", 32) | |
446 | self.assertEqual("Amount(32.00000000 BTX)", repr(amount1)) | |
447 | ||
448 | amount2 = portfolio.Amount("USDT", 12000) | |
449 | amount1.linked_to = amount2 | |
450 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1)) | |
451 | ||
452 | amount3 = portfolio.Amount("BTC", 0.1) | |
453 | amount2.linked_to = amount3 | |
454 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1)) | |
455 | ||
3d0247f9 IB |
456 | def test_as_json(self): |
457 | amount = portfolio.Amount("BTX", 32) | |
458 | self.assertEqual({"currency": "BTX", "value": D("32")}, amount.as_json()) | |
459 | ||
460 | amount = portfolio.Amount("BTX", "1E-10") | |
461 | self.assertEqual({"currency": "BTX", "value": D("0")}, amount.as_json()) | |
462 | ||
463 | amount = portfolio.Amount("BTX", "1E-5") | |
464 | self.assertEqual({"currency": "BTX", "value": D("0.00001")}, amount.as_json()) | |
465 | self.assertEqual("0.00001", str(amount.as_json()["value"])) | |
466 | ||
1aa7d4fa | 467 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
80cdd672 | 468 | class BalanceTest(WebMockTestCase): |
f2da6589 | 469 | def test_values(self): |
80cdd672 IB |
470 | balance = portfolio.Balance("BTC", { |
471 | "exchange_total": "0.65", | |
472 | "exchange_free": "0.35", | |
473 | "exchange_used": "0.30", | |
474 | "margin_total": "-10", | |
475 | "margin_borrowed": "-10", | |
476 | "margin_free": "0", | |
477 | "margin_position_type": "short", | |
478 | "margin_borrowed_base_currency": "USDT", | |
479 | "margin_liquidation_price": "1.20", | |
480 | "margin_pending_gain": "10", | |
481 | "margin_lending_fees": "0.4", | |
482 | "margin_borrowed_base_price": "0.15", | |
483 | }) | |
484 | self.assertEqual(portfolio.D("0.65"), balance.exchange_total.value) | |
485 | self.assertEqual(portfolio.D("0.35"), balance.exchange_free.value) | |
486 | self.assertEqual(portfolio.D("0.30"), balance.exchange_used.value) | |
487 | self.assertEqual("BTC", balance.exchange_total.currency) | |
488 | self.assertEqual("BTC", balance.exchange_free.currency) | |
489 | self.assertEqual("BTC", balance.exchange_total.currency) | |
490 | ||
491 | self.assertEqual(portfolio.D("-10"), balance.margin_total.value) | |
492 | self.assertEqual(portfolio.D("-10"), balance.margin_borrowed.value) | |
493 | self.assertEqual(portfolio.D("0"), balance.margin_free.value) | |
494 | self.assertEqual("BTC", balance.margin_total.currency) | |
495 | self.assertEqual("BTC", balance.margin_borrowed.currency) | |
496 | self.assertEqual("BTC", balance.margin_free.currency) | |
f2da6589 | 497 | |
f2da6589 IB |
498 | self.assertEqual("BTC", balance.currency) |
499 | ||
80cdd672 IB |
500 | self.assertEqual(portfolio.D("0.4"), balance.margin_lending_fees.value) |
501 | self.assertEqual("USDT", balance.margin_lending_fees.currency) | |
502 | ||
6ca5a1ec IB |
503 | def test__repr(self): |
504 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])", | |
505 | repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }))) | |
506 | balance = portfolio.Balance("BTX", { "exchange_total": 3, | |
507 | "exchange_used": 1, "exchange_free": 2 }) | |
508 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | |
f2da6589 | 509 | |
1aa7d4fa IB |
510 | balance = portfolio.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}) |
511 | self.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance)) | |
512 | ||
6ca5a1ec IB |
513 | balance = portfolio.Balance("BTX", { "margin_total": 3, |
514 | "margin_borrowed": 1, "margin_free": 2 }) | |
515 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + borrowed 1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | |
f2da6589 | 516 | |
1aa7d4fa IB |
517 | balance = portfolio.Balance("BTX", { "margin_total": 2, "margin_free": 2 }) |
518 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance)) | |
519 | ||
6ca5a1ec IB |
520 | balance = portfolio.Balance("BTX", { "margin_total": -3, |
521 | "margin_borrowed_base_price": D("0.1"), | |
522 | "margin_borrowed_base_currency": "BTC", | |
523 | "margin_lending_fees": D("0.002") }) | |
524 | self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance)) | |
f2da6589 | 525 | |
1aa7d4fa IB |
526 | balance = portfolio.Balance("BTX", { "margin_total": 1, |
527 | "margin_borrowed": 1, "exchange_free": 2, "exchange_total": 2}) | |
528 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [borrowed 1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance)) | |
529 | ||
3d0247f9 IB |
530 | def test_as_json(self): |
531 | balance = portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }) | |
532 | as_json = balance.as_json() | |
533 | self.assertEqual(set(portfolio.Balance.base_keys), set(as_json.keys())) | |
534 | self.assertEqual(D(0), as_json["total"]) | |
535 | self.assertEqual(D(2), as_json["exchange_total"]) | |
536 | self.assertEqual(D(2), as_json["exchange_free"]) | |
537 | self.assertEqual(D(0), as_json["exchange_used"]) | |
538 | self.assertEqual(D(0), as_json["margin_total"]) | |
539 | self.assertEqual(D(0), as_json["margin_free"]) | |
540 | self.assertEqual(D(0), as_json["margin_borrowed"]) | |
541 | ||
1aa7d4fa | 542 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
f86ee140 IB |
543 | class MarketTest(WebMockTestCase): |
544 | def setUp(self): | |
545 | super(MarketTest, self).setUp() | |
546 | ||
547 | self.ccxt = mock.Mock(spec=market.ccxt.poloniexE) | |
548 | ||
549 | def test_values(self): | |
550 | m = market.Market(self.ccxt) | |
551 | ||
552 | self.assertEqual(self.ccxt, m.ccxt) | |
553 | self.assertFalse(m.debug) | |
554 | self.assertIsInstance(m.report, market.ReportStore) | |
555 | self.assertIsInstance(m.trades, market.TradeStore) | |
556 | self.assertIsInstance(m.balances, market.BalanceStore) | |
557 | self.assertEqual(m, m.report.market) | |
558 | self.assertEqual(m, m.trades.market) | |
559 | self.assertEqual(m, m.balances.market) | |
560 | self.assertEqual(m, m.ccxt._market) | |
561 | ||
562 | m = market.Market(self.ccxt, debug=True) | |
563 | self.assertTrue(m.debug) | |
564 | ||
565 | m = market.Market(self.ccxt, debug=False) | |
566 | self.assertFalse(m.debug) | |
567 | ||
568 | @mock.patch("market.ccxt") | |
569 | def test_from_config(self, ccxt): | |
570 | with mock.patch("market.ReportStore"): | |
571 | ccxt.poloniexE.return_value = self.ccxt | |
572 | self.ccxt.session.request.return_value = "response" | |
573 | ||
574 | m = market.Market.from_config("config") | |
575 | ||
576 | self.assertEqual(self.ccxt, m.ccxt) | |
577 | ||
578 | self.ccxt.session.request("GET", "URL", data="data", | |
579 | headers="headers") | |
580 | m.report.log_http_request.assert_called_with('GET', 'URL', 'data', | |
581 | 'headers', 'response') | |
582 | ||
583 | m = market.Market.from_config("config", debug=True) | |
584 | self.assertEqual(True, m.debug) | |
585 | ||
6ca5a1ec | 586 | def test_get_ticker(self): |
f86ee140 IB |
587 | m = market.Market(self.ccxt) |
588 | self.ccxt.fetch_ticker.side_effect = [ | |
6ca5a1ec | 589 | { "bid": 1, "ask": 3 }, |
f86ee140 | 590 | market.ExchangeError("foo"), |
6ca5a1ec | 591 | { "bid": 10, "ask": 40 }, |
f86ee140 IB |
592 | market.ExchangeError("foo"), |
593 | market.ExchangeError("foo"), | |
6ca5a1ec | 594 | ] |
f2da6589 | 595 | |
f86ee140 IB |
596 | ticker = m.get_ticker("ETH", "ETC") |
597 | self.ccxt.fetch_ticker.assert_called_with("ETH/ETC") | |
6ca5a1ec IB |
598 | self.assertEqual(1, ticker["bid"]) |
599 | self.assertEqual(3, ticker["ask"]) | |
600 | self.assertEqual(2, ticker["average"]) | |
601 | self.assertFalse(ticker["inverted"]) | |
f2da6589 | 602 | |
f86ee140 | 603 | ticker = m.get_ticker("ETH", "XVG") |
6ca5a1ec IB |
604 | self.assertEqual(0.0625, ticker["average"]) |
605 | self.assertTrue(ticker["inverted"]) | |
606 | self.assertIn("original", ticker) | |
607 | self.assertEqual(10, ticker["original"]["bid"]) | |
f2da6589 | 608 | |
f86ee140 | 609 | ticker = m.get_ticker("XVG", "XMR") |
6ca5a1ec | 610 | self.assertIsNone(ticker) |
a9950fd0 | 611 | |
f86ee140 | 612 | self.ccxt.fetch_ticker.assert_has_calls([ |
6ca5a1ec IB |
613 | mock.call("ETH/ETC"), |
614 | mock.call("ETH/XVG"), | |
615 | mock.call("XVG/ETH"), | |
616 | mock.call("XVG/XMR"), | |
617 | mock.call("XMR/XVG"), | |
618 | ]) | |
f2da6589 | 619 | |
f86ee140 IB |
620 | self.ccxt = mock.Mock(spec=market.ccxt.poloniexE) |
621 | m1b = market.Market(self.ccxt) | |
622 | m1b.get_ticker("ETH", "ETC") | |
623 | self.ccxt.fetch_ticker.assert_not_called() | |
624 | ||
625 | self.ccxt = mock.Mock(spec=market.ccxt.poloniex) | |
626 | m2 = market.Market(self.ccxt) | |
627 | self.ccxt.fetch_ticker.side_effect = [ | |
6ca5a1ec IB |
628 | { "bid": 1, "ask": 3 }, |
629 | { "bid": 1.2, "ask": 3.5 }, | |
630 | ] | |
f86ee140 IB |
631 | ticker1 = m2.get_ticker("ETH", "ETC") |
632 | ticker2 = m2.get_ticker("ETH", "ETC") | |
633 | ticker3 = m2.get_ticker("ETC", "ETH") | |
634 | self.ccxt.fetch_ticker.assert_called_once_with("ETH/ETC") | |
6ca5a1ec IB |
635 | self.assertEqual(1, ticker1["bid"]) |
636 | self.assertDictEqual(ticker1, ticker2) | |
637 | self.assertDictEqual(ticker1, ticker3["original"]) | |
f2da6589 | 638 | |
f86ee140 IB |
639 | ticker4 = m2.get_ticker("ETH", "ETC", refresh=True) |
640 | ticker5 = m2.get_ticker("ETH", "ETC") | |
6ca5a1ec IB |
641 | self.assertEqual(1.2, ticker4["bid"]) |
642 | self.assertDictEqual(ticker4, ticker5) | |
f2da6589 | 643 | |
f86ee140 IB |
644 | self.ccxt = mock.Mock(spec=market.ccxt.binance) |
645 | m3 = market.Market(self.ccxt) | |
646 | self.ccxt.fetch_ticker.side_effect = [ | |
6ca5a1ec IB |
647 | { "bid": 1, "ask": 3 }, |
648 | { "bid": 1.2, "ask": 3.5 }, | |
649 | ] | |
f86ee140 IB |
650 | ticker6 = m3.get_ticker("ETH", "ETC") |
651 | m3.ticker_cache_timestamp -= 4 | |
652 | ticker7 = m3.get_ticker("ETH", "ETC") | |
653 | m3.ticker_cache_timestamp -= 2 | |
654 | ticker8 = m3.get_ticker("ETH", "ETC") | |
6ca5a1ec IB |
655 | self.assertDictEqual(ticker6, ticker7) |
656 | self.assertEqual(1.2, ticker8["bid"]) | |
f2da6589 | 657 | |
6ca5a1ec | 658 | def test_fetch_fees(self): |
f86ee140 IB |
659 | m = market.Market(self.ccxt) |
660 | self.ccxt.fetch_fees.return_value = "Foo" | |
661 | self.assertEqual("Foo", m.fetch_fees()) | |
662 | self.ccxt.fetch_fees.assert_called_once() | |
663 | self.ccxt.reset_mock() | |
664 | self.assertEqual("Foo", m.fetch_fees()) | |
665 | self.ccxt.fetch_fees.assert_not_called() | |
f2da6589 | 666 | |
350ed24d | 667 | @mock.patch.object(portfolio.Portfolio, "repartition") |
f86ee140 IB |
668 | @mock.patch.object(market.Market, "get_ticker") |
669 | @mock.patch.object(market.TradeStore, "compute_trades") | |
670 | def test_prepare_trades(self, compute_trades, get_ticker, repartition): | |
f2da6589 | 671 | repartition.return_value = { |
350ed24d IB |
672 | "XEM": (D("0.75"), "long"), |
673 | "BTC": (D("0.25"), "long"), | |
f2da6589 | 674 | } |
f86ee140 | 675 | def _get_ticker(c1, c2): |
deb8924c IB |
676 | if c1 == "USDT" and c2 == "BTC": |
677 | return { "average": D("0.0001") } | |
678 | if c1 == "XVG" and c2 == "BTC": | |
679 | return { "average": D("0.000001") } | |
680 | if c1 == "XEM" and c2 == "BTC": | |
681 | return { "average": D("0.001") } | |
a9950fd0 | 682 | self.fail("Should be called with {}, {}".format(c1, c2)) |
deb8924c IB |
683 | get_ticker.side_effect = _get_ticker |
684 | ||
f86ee140 IB |
685 | with mock.patch("market.ReportStore"): |
686 | m = market.Market(self.ccxt) | |
687 | self.ccxt.fetch_all_balances.return_value = { | |
688 | "USDT": { | |
689 | "exchange_free": D("10000.0"), | |
690 | "exchange_used": D("0.0"), | |
691 | "exchange_total": D("10000.0"), | |
692 | "total": D("10000.0") | |
693 | }, | |
694 | "XVG": { | |
695 | "exchange_free": D("10000.0"), | |
696 | "exchange_used": D("0.0"), | |
697 | "exchange_total": D("10000.0"), | |
698 | "total": D("10000.0") | |
699 | }, | |
700 | } | |
18167a3c | 701 | |
f86ee140 | 702 | m.balances.fetch_balances(tag="tag") |
f2da6589 | 703 | |
f86ee140 IB |
704 | m.prepare_trades() |
705 | compute_trades.assert_called() | |
706 | ||
707 | call = compute_trades.call_args | |
708 | self.assertEqual(1, call[0][0]["USDT"].value) | |
709 | self.assertEqual(D("0.01"), call[0][0]["XVG"].value) | |
710 | self.assertEqual(D("0.2525"), call[0][1]["BTC"].value) | |
711 | self.assertEqual(D("0.7575"), call[0][1]["XEM"].value) | |
712 | m.report.log_stage.assert_called_once_with("prepare_trades") | |
713 | m.report.log_balances.assert_called_once_with(tag="tag") | |
f2da6589 | 714 | |
c51687d2 | 715 | @mock.patch.object(portfolio.Portfolio, "repartition") |
f86ee140 IB |
716 | @mock.patch.object(market.Market, "get_ticker") |
717 | @mock.patch.object(market.TradeStore, "compute_trades") | |
718 | def test_update_trades(self, compute_trades, get_ticker, repartition): | |
c51687d2 IB |
719 | repartition.return_value = { |
720 | "XEM": (D("0.75"), "long"), | |
721 | "BTC": (D("0.25"), "long"), | |
722 | } | |
f86ee140 | 723 | def _get_ticker(c1, c2): |
c51687d2 IB |
724 | if c1 == "USDT" and c2 == "BTC": |
725 | return { "average": D("0.0001") } | |
726 | if c1 == "XVG" and c2 == "BTC": | |
727 | return { "average": D("0.000001") } | |
728 | if c1 == "XEM" and c2 == "BTC": | |
729 | return { "average": D("0.001") } | |
730 | self.fail("Should be called with {}, {}".format(c1, c2)) | |
731 | get_ticker.side_effect = _get_ticker | |
732 | ||
f86ee140 IB |
733 | with mock.patch("market.ReportStore"): |
734 | m = market.Market(self.ccxt) | |
735 | self.ccxt.fetch_all_balances.return_value = { | |
736 | "USDT": { | |
737 | "exchange_free": D("10000.0"), | |
738 | "exchange_used": D("0.0"), | |
739 | "exchange_total": D("10000.0"), | |
740 | "total": D("10000.0") | |
741 | }, | |
742 | "XVG": { | |
743 | "exchange_free": D("10000.0"), | |
744 | "exchange_used": D("0.0"), | |
745 | "exchange_total": D("10000.0"), | |
746 | "total": D("10000.0") | |
747 | }, | |
748 | } | |
749 | ||
750 | m.balances.fetch_balances(tag="tag") | |
18167a3c | 751 | |
f86ee140 IB |
752 | m.update_trades() |
753 | compute_trades.assert_called() | |
c51687d2 | 754 | |
f86ee140 IB |
755 | call = compute_trades.call_args |
756 | self.assertEqual(1, call[0][0]["USDT"].value) | |
757 | self.assertEqual(D("0.01"), call[0][0]["XVG"].value) | |
758 | self.assertEqual(D("0.2525"), call[0][1]["BTC"].value) | |
759 | self.assertEqual(D("0.7575"), call[0][1]["XEM"].value) | |
760 | m.report.log_stage.assert_called_once_with("update_trades") | |
761 | m.report.log_balances.assert_called_once_with(tag="tag") | |
c51687d2 IB |
762 | |
763 | @mock.patch.object(portfolio.Portfolio, "repartition") | |
f86ee140 IB |
764 | @mock.patch.object(market.Market, "get_ticker") |
765 | @mock.patch.object(market.TradeStore, "compute_trades") | |
766 | def test_prepare_trades_to_sell_all(self, compute_trades, get_ticker, repartition): | |
767 | def _get_ticker(c1, c2): | |
c51687d2 IB |
768 | if c1 == "USDT" and c2 == "BTC": |
769 | return { "average": D("0.0001") } | |
770 | if c1 == "XVG" and c2 == "BTC": | |
771 | return { "average": D("0.000001") } | |
772 | self.fail("Should be called with {}, {}".format(c1, c2)) | |
773 | get_ticker.side_effect = _get_ticker | |
774 | ||
f86ee140 IB |
775 | with mock.patch("market.ReportStore"): |
776 | m = market.Market(self.ccxt) | |
777 | self.ccxt.fetch_all_balances.return_value = { | |
778 | "USDT": { | |
779 | "exchange_free": D("10000.0"), | |
780 | "exchange_used": D("0.0"), | |
781 | "exchange_total": D("10000.0"), | |
782 | "total": D("10000.0") | |
783 | }, | |
784 | "XVG": { | |
785 | "exchange_free": D("10000.0"), | |
786 | "exchange_used": D("0.0"), | |
787 | "exchange_total": D("10000.0"), | |
788 | "total": D("10000.0") | |
789 | }, | |
790 | } | |
791 | ||
792 | m.balances.fetch_balances(tag="tag") | |
18167a3c | 793 | |
f86ee140 | 794 | m.prepare_trades_to_sell_all() |
c51687d2 | 795 | |
f86ee140 IB |
796 | repartition.assert_not_called() |
797 | compute_trades.assert_called() | |
798 | ||
799 | call = compute_trades.call_args | |
800 | self.assertEqual(1, call[0][0]["USDT"].value) | |
801 | self.assertEqual(D("0.01"), call[0][0]["XVG"].value) | |
802 | self.assertEqual(D("1.01"), call[0][1]["BTC"].value) | |
803 | m.report.log_stage.assert_called_once_with("prepare_trades_to_sell_all") | |
804 | m.report.log_balances.assert_called_once_with(tag="tag") | |
a9950fd0 | 805 | |
1aa7d4fa | 806 | @mock.patch.object(portfolio.time, "sleep") |
f86ee140 | 807 | @mock.patch.object(market.TradeStore, "all_orders") |
1aa7d4fa | 808 | def test_follow_orders(self, all_orders, time_mock): |
3d0247f9 IB |
809 | for debug, sleep in [ |
810 | (False, None), (True, None), | |
811 | (False, 12), (True, 12)]: | |
812 | with self.subTest(sleep=sleep, debug=debug), \ | |
f86ee140 IB |
813 | mock.patch("market.ReportStore"): |
814 | m = market.Market(self.ccxt, debug=debug) | |
815 | ||
1aa7d4fa IB |
816 | order_mock1 = mock.Mock() |
817 | order_mock2 = mock.Mock() | |
818 | order_mock3 = mock.Mock() | |
819 | all_orders.side_effect = [ | |
820 | [order_mock1, order_mock2], | |
821 | [order_mock1, order_mock2], | |
822 | ||
823 | [order_mock1, order_mock3], | |
824 | [order_mock1, order_mock3], | |
825 | ||
826 | [order_mock1, order_mock3], | |
827 | [order_mock1, order_mock3], | |
828 | ||
829 | [] | |
830 | ] | |
831 | ||
832 | order_mock1.get_status.side_effect = ["open", "open", "closed"] | |
833 | order_mock2.get_status.side_effect = ["open"] | |
834 | order_mock3.get_status.side_effect = ["open", "closed"] | |
835 | ||
836 | order_mock1.trade = mock.Mock() | |
837 | order_mock2.trade = mock.Mock() | |
838 | order_mock3.trade = mock.Mock() | |
839 | ||
f86ee140 | 840 | m.follow_orders(sleep=sleep) |
1aa7d4fa IB |
841 | |
842 | order_mock1.trade.update_order.assert_any_call(order_mock1, 1) | |
843 | order_mock1.trade.update_order.assert_any_call(order_mock1, 2) | |
844 | self.assertEqual(2, order_mock1.trade.update_order.call_count) | |
845 | self.assertEqual(3, order_mock1.get_status.call_count) | |
846 | ||
847 | order_mock2.trade.update_order.assert_any_call(order_mock2, 1) | |
848 | self.assertEqual(1, order_mock2.trade.update_order.call_count) | |
849 | self.assertEqual(1, order_mock2.get_status.call_count) | |
850 | ||
851 | order_mock3.trade.update_order.assert_any_call(order_mock3, 2) | |
852 | self.assertEqual(1, order_mock3.trade.update_order.call_count) | |
853 | self.assertEqual(2, order_mock3.get_status.call_count) | |
f86ee140 | 854 | m.report.log_stage.assert_called() |
3d0247f9 IB |
855 | calls = [ |
856 | mock.call("follow_orders_begin"), | |
857 | mock.call("follow_orders_tick_1"), | |
858 | mock.call("follow_orders_tick_2"), | |
859 | mock.call("follow_orders_tick_3"), | |
860 | mock.call("follow_orders_end"), | |
861 | ] | |
f86ee140 IB |
862 | m.report.log_stage.assert_has_calls(calls) |
863 | m.report.log_orders.assert_called() | |
864 | self.assertEqual(3, m.report.log_orders.call_count) | |
3d0247f9 IB |
865 | calls = [ |
866 | mock.call([order_mock1, order_mock2], tick=1), | |
867 | mock.call([order_mock1, order_mock3], tick=2), | |
868 | mock.call([order_mock1, order_mock3], tick=3), | |
869 | ] | |
f86ee140 | 870 | m.report.log_orders.assert_has_calls(calls) |
3d0247f9 IB |
871 | calls = [ |
872 | mock.call(order_mock1, 3, finished=True), | |
873 | mock.call(order_mock3, 3, finished=True), | |
874 | ] | |
f86ee140 | 875 | m.report.log_order.assert_has_calls(calls) |
1aa7d4fa IB |
876 | |
877 | if sleep is None: | |
878 | if debug: | |
f86ee140 | 879 | m.report.log_debug_action.assert_called_with("Set follow_orders tick to 7s") |
1aa7d4fa IB |
880 | time_mock.assert_called_with(7) |
881 | else: | |
882 | time_mock.assert_called_with(30) | |
883 | else: | |
884 | time_mock.assert_called_with(sleep) | |
885 | ||
f86ee140 | 886 | @mock.patch.object(market.BalanceStore, "fetch_balances") |
5a72ded7 IB |
887 | def test_move_balance(self, fetch_balances): |
888 | for debug in [True, False]: | |
889 | with self.subTest(debug=debug),\ | |
f86ee140 IB |
890 | mock.patch("market.ReportStore"): |
891 | m = market.Market(self.ccxt, debug=debug) | |
892 | ||
5a72ded7 IB |
893 | value_from = portfolio.Amount("BTC", "1.0") |
894 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
895 | value_to = portfolio.Amount("BTC", "10.0") | |
f86ee140 | 896 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) |
5a72ded7 IB |
897 | |
898 | value_from = portfolio.Amount("BTC", "0.0") | |
899 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | |
900 | value_to = portfolio.Amount("BTC", "-3.0") | |
f86ee140 | 901 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) |
5a72ded7 IB |
902 | |
903 | value_from = portfolio.Amount("USDT", "0.0") | |
904 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | |
905 | value_to = portfolio.Amount("USDT", "-50.0") | |
f86ee140 | 906 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) |
5a72ded7 | 907 | |
f86ee140 | 908 | m.trades.all = [trade1, trade2, trade3] |
5a72ded7 IB |
909 | balance1 = portfolio.Balance("BTC", { "margin_free": "0" }) |
910 | balance2 = portfolio.Balance("USDT", { "margin_free": "100" }) | |
0c79fad3 | 911 | balance3 = portfolio.Balance("ETC", { "margin_free": "10" }) |
f86ee140 | 912 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} |
5a72ded7 | 913 | |
f86ee140 | 914 | m.move_balances() |
5a72ded7 | 915 | |
f86ee140 IB |
916 | fetch_balances.assert_called_with() |
917 | m.report.log_move_balances.assert_called_once() | |
3d0247f9 | 918 | |
5a72ded7 | 919 | if debug: |
f86ee140 IB |
920 | m.report.log_debug_action.assert_called() |
921 | self.assertEqual(3, m.report.log_debug_action.call_count) | |
5a72ded7 | 922 | else: |
f86ee140 IB |
923 | self.ccxt.transfer_balance.assert_any_call("BTC", 3, "exchange", "margin") |
924 | self.ccxt.transfer_balance.assert_any_call("USDT", 50, "margin", "exchange") | |
925 | self.ccxt.transfer_balance.assert_any_call("ETC", 10, "margin", "exchange") | |
926 | ||
1aa7d4fa | 927 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
6ca5a1ec | 928 | class TradeStoreTest(WebMockTestCase): |
f86ee140 IB |
929 | def test_compute_trades(self): |
930 | self.m.balances.currencies.return_value = ["XMR", "DASH", "XVG", "BTC", "ETH"] | |
1aa7d4fa IB |
931 | |
932 | values_in_base = { | |
933 | "XMR": portfolio.Amount("BTC", D("0.9")), | |
934 | "DASH": portfolio.Amount("BTC", D("0.4")), | |
935 | "XVG": portfolio.Amount("BTC", D("-0.5")), | |
936 | "BTC": portfolio.Amount("BTC", D("0.5")), | |
937 | } | |
938 | new_repartition = { | |
939 | "DASH": portfolio.Amount("BTC", D("0.5")), | |
940 | "XVG": portfolio.Amount("BTC", D("0.1")), | |
941 | "BTC": portfolio.Amount("BTC", D("0.4")), | |
942 | "ETH": portfolio.Amount("BTC", D("0.3")), | |
943 | } | |
3d0247f9 IB |
944 | side_effect = [ |
945 | (True, 1), | |
946 | (False, 2), | |
947 | (False, 3), | |
948 | (True, 4), | |
949 | (True, 5) | |
950 | ] | |
1aa7d4fa | 951 | |
f86ee140 IB |
952 | with mock.patch.object(market.TradeStore, "trade_if_matching") as trade_if_matching: |
953 | trade_store = market.TradeStore(self.m) | |
954 | trade_if_matching.side_effect = side_effect | |
1aa7d4fa | 955 | |
f86ee140 IB |
956 | trade_store.compute_trades(values_in_base, |
957 | new_repartition, only="only") | |
958 | ||
959 | self.assertEqual(5, trade_if_matching.call_count) | |
960 | self.assertEqual(3, len(trade_store.all)) | |
961 | self.assertEqual([1, 4, 5], trade_store.all) | |
962 | self.m.report.log_trades.assert_called_with(side_effect, "only") | |
1aa7d4fa | 963 | |
3d0247f9 | 964 | def test_trade_if_matching(self): |
f86ee140 IB |
965 | |
966 | with self.subTest(only="nope"): | |
967 | trade_store = market.TradeStore(self.m) | |
968 | result = trade_store.trade_if_matching( | |
969 | portfolio.Amount("BTC", D("0")), | |
970 | portfolio.Amount("BTC", D("0.3")), | |
971 | "ETH", only="nope") | |
972 | self.assertEqual(False, result[0]) | |
973 | self.assertIsInstance(result[1], portfolio.Trade) | |
974 | ||
975 | with self.subTest(only=None): | |
976 | trade_store = market.TradeStore(self.m) | |
977 | result = trade_store.trade_if_matching( | |
978 | portfolio.Amount("BTC", D("0")), | |
979 | portfolio.Amount("BTC", D("0.3")), | |
980 | "ETH", only=None) | |
981 | self.assertEqual(True, result[0]) | |
982 | ||
983 | with self.subTest(only="acquire"): | |
984 | trade_store = market.TradeStore(self.m) | |
985 | result = trade_store.trade_if_matching( | |
986 | portfolio.Amount("BTC", D("0")), | |
987 | portfolio.Amount("BTC", D("0.3")), | |
988 | "ETH", only="acquire") | |
989 | self.assertEqual(True, result[0]) | |
990 | ||
991 | with self.subTest(only="dispose"): | |
992 | trade_store = market.TradeStore(self.m) | |
993 | result = trade_store.trade_if_matching( | |
994 | portfolio.Amount("BTC", D("0")), | |
995 | portfolio.Amount("BTC", D("0.3")), | |
996 | "ETH", only="dispose") | |
997 | self.assertEqual(False, result[0]) | |
998 | ||
999 | def test_prepare_orders(self): | |
1000 | trade_store = market.TradeStore(self.m) | |
1001 | ||
6ca5a1ec IB |
1002 | trade_mock1 = mock.Mock() |
1003 | trade_mock2 = mock.Mock() | |
cfab619d | 1004 | |
3d0247f9 IB |
1005 | trade_mock1.prepare_order.return_value = 1 |
1006 | trade_mock2.prepare_order.return_value = 2 | |
1007 | ||
f86ee140 IB |
1008 | trade_store.all.append(trade_mock1) |
1009 | trade_store.all.append(trade_mock2) | |
6ca5a1ec | 1010 | |
f86ee140 | 1011 | trade_store.prepare_orders() |
6ca5a1ec IB |
1012 | trade_mock1.prepare_order.assert_called_with(compute_value="default") |
1013 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | |
f86ee140 | 1014 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "default") |
3d0247f9 | 1015 | |
f86ee140 | 1016 | self.m.report.log_orders.reset_mock() |
6ca5a1ec | 1017 | |
f86ee140 | 1018 | trade_store.prepare_orders(compute_value="bla") |
6ca5a1ec IB |
1019 | trade_mock1.prepare_order.assert_called_with(compute_value="bla") |
1020 | trade_mock2.prepare_order.assert_called_with(compute_value="bla") | |
f86ee140 | 1021 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "bla") |
6ca5a1ec IB |
1022 | |
1023 | trade_mock1.prepare_order.reset_mock() | |
1024 | trade_mock2.prepare_order.reset_mock() | |
f86ee140 | 1025 | self.m.report.log_orders.reset_mock() |
6ca5a1ec IB |
1026 | |
1027 | trade_mock1.action = "foo" | |
1028 | trade_mock2.action = "bar" | |
f86ee140 | 1029 | trade_store.prepare_orders(only="bar") |
6ca5a1ec IB |
1030 | trade_mock1.prepare_order.assert_not_called() |
1031 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | |
f86ee140 | 1032 | self.m.report.log_orders.assert_called_once_with([2], "bar", "default") |
6ca5a1ec IB |
1033 | |
1034 | def test_print_all_with_order(self): | |
1035 | trade_mock1 = mock.Mock() | |
1036 | trade_mock2 = mock.Mock() | |
1037 | trade_mock3 = mock.Mock() | |
f86ee140 IB |
1038 | trade_store = market.TradeStore(self.m) |
1039 | trade_store.all = [trade_mock1, trade_mock2, trade_mock3] | |
6ca5a1ec | 1040 | |
f86ee140 | 1041 | trade_store.print_all_with_order() |
6ca5a1ec IB |
1042 | |
1043 | trade_mock1.print_with_order.assert_called() | |
1044 | trade_mock2.print_with_order.assert_called() | |
1045 | trade_mock3.print_with_order.assert_called() | |
1046 | ||
f86ee140 IB |
1047 | def test_run_orders(self): |
1048 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | |
1049 | order_mock1 = mock.Mock() | |
1050 | order_mock2 = mock.Mock() | |
1051 | order_mock3 = mock.Mock() | |
1052 | trade_store = market.TradeStore(self.m) | |
1053 | ||
1054 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | |
1055 | ||
1056 | trade_store.run_orders() | |
1057 | ||
1058 | all_orders.assert_called_with(state="pending") | |
6ca5a1ec IB |
1059 | |
1060 | order_mock1.run.assert_called() | |
1061 | order_mock2.run.assert_called() | |
1062 | order_mock3.run.assert_called() | |
1063 | ||
f86ee140 IB |
1064 | self.m.report.log_stage.assert_called_with("run_orders") |
1065 | self.m.report.log_orders.assert_called_with([order_mock1, order_mock2, | |
3d0247f9 IB |
1066 | order_mock3]) |
1067 | ||
6ca5a1ec IB |
1068 | def test_all_orders(self): |
1069 | trade_mock1 = mock.Mock() | |
1070 | trade_mock2 = mock.Mock() | |
1071 | ||
1072 | order_mock1 = mock.Mock() | |
1073 | order_mock2 = mock.Mock() | |
1074 | order_mock3 = mock.Mock() | |
1075 | ||
1076 | trade_mock1.orders = [order_mock1, order_mock2] | |
1077 | trade_mock2.orders = [order_mock3] | |
1078 | ||
1079 | order_mock1.status = "pending" | |
1080 | order_mock2.status = "open" | |
1081 | order_mock3.status = "open" | |
1082 | ||
f86ee140 IB |
1083 | trade_store = market.TradeStore(self.m) |
1084 | trade_store.all.append(trade_mock1) | |
1085 | trade_store.all.append(trade_mock2) | |
6ca5a1ec | 1086 | |
f86ee140 | 1087 | orders = trade_store.all_orders() |
6ca5a1ec IB |
1088 | self.assertEqual(3, len(orders)) |
1089 | ||
f86ee140 | 1090 | open_orders = trade_store.all_orders(state="open") |
6ca5a1ec IB |
1091 | self.assertEqual(2, len(open_orders)) |
1092 | self.assertEqual([order_mock2, order_mock3], open_orders) | |
1093 | ||
f86ee140 IB |
1094 | def test_update_all_orders_status(self): |
1095 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | |
1096 | order_mock1 = mock.Mock() | |
1097 | order_mock2 = mock.Mock() | |
1098 | order_mock3 = mock.Mock() | |
1099 | ||
1100 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | |
1101 | ||
1102 | trade_store = market.TradeStore(self.m) | |
1103 | ||
1104 | trade_store.update_all_orders_status() | |
1105 | all_orders.assert_called_with(state="open") | |
6ca5a1ec | 1106 | |
f86ee140 IB |
1107 | order_mock1.get_status.assert_called() |
1108 | order_mock2.get_status.assert_called() | |
1109 | order_mock3.get_status.assert_called() | |
6ca5a1ec | 1110 | |
3d0247f9 | 1111 | |
1aa7d4fa | 1112 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
6ca5a1ec IB |
1113 | class BalanceStoreTest(WebMockTestCase): |
1114 | def setUp(self): | |
1115 | super(BalanceStoreTest, self).setUp() | |
1116 | ||
1117 | self.fetch_balance = { | |
1118 | "ETC": { | |
1119 | "exchange_free": 0, | |
1120 | "exchange_used": 0, | |
1121 | "exchange_total": 0, | |
1122 | "margin_total": 0, | |
1123 | }, | |
1124 | "USDT": { | |
1125 | "exchange_free": D("6.0"), | |
1126 | "exchange_used": D("1.2"), | |
1127 | "exchange_total": D("7.2"), | |
1128 | "margin_total": 0, | |
1129 | }, | |
1130 | "XVG": { | |
1131 | "exchange_free": 16, | |
1132 | "exchange_used": 0, | |
1133 | "exchange_total": 16, | |
1134 | "margin_total": 0, | |
1135 | }, | |
1136 | "XMR": { | |
1137 | "exchange_free": 0, | |
1138 | "exchange_used": 0, | |
1139 | "exchange_total": 0, | |
1140 | "margin_total": D("-1.0"), | |
1141 | "margin_free": 0, | |
1142 | }, | |
1143 | } | |
1144 | ||
f86ee140 IB |
1145 | def test_in_currency(self): |
1146 | self.m.get_ticker.return_value = { | |
1147 | "bid": D("0.09"), | |
1148 | "ask": D("0.11"), | |
1149 | "average": D("0.1"), | |
1150 | } | |
1151 | ||
1152 | balance_store = market.BalanceStore(self.m) | |
1153 | balance_store.all = { | |
6ca5a1ec IB |
1154 | "BTC": portfolio.Balance("BTC", { |
1155 | "total": "0.65", | |
1156 | "exchange_total":"0.65", | |
1157 | "exchange_free": "0.35", | |
1158 | "exchange_used": "0.30"}), | |
1159 | "ETH": portfolio.Balance("ETH", { | |
1160 | "total": 3, | |
1161 | "exchange_total": 3, | |
1162 | "exchange_free": 3, | |
1163 | "exchange_used": 0}), | |
1164 | } | |
cfab619d | 1165 | |
f86ee140 | 1166 | amounts = balance_store.in_currency("BTC") |
6ca5a1ec IB |
1167 | self.assertEqual("BTC", amounts["ETH"].currency) |
1168 | self.assertEqual(D("0.65"), amounts["BTC"].value) | |
1169 | self.assertEqual(D("0.30"), amounts["ETH"].value) | |
f86ee140 | 1170 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", |
3d0247f9 | 1171 | "average", "total") |
f86ee140 | 1172 | self.m.report.log_tickers.reset_mock() |
cfab619d | 1173 | |
f86ee140 | 1174 | amounts = balance_store.in_currency("BTC", compute_value="bid") |
6ca5a1ec IB |
1175 | self.assertEqual(D("0.65"), amounts["BTC"].value) |
1176 | self.assertEqual(D("0.27"), amounts["ETH"].value) | |
f86ee140 | 1177 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", |
3d0247f9 | 1178 | "bid", "total") |
f86ee140 | 1179 | self.m.report.log_tickers.reset_mock() |
cfab619d | 1180 | |
f86ee140 | 1181 | amounts = balance_store.in_currency("BTC", compute_value="bid", type="exchange_used") |
6ca5a1ec IB |
1182 | self.assertEqual(D("0.30"), amounts["BTC"].value) |
1183 | self.assertEqual(0, amounts["ETH"].value) | |
f86ee140 | 1184 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", |
3d0247f9 | 1185 | "bid", "exchange_used") |
f86ee140 | 1186 | self.m.report.log_tickers.reset_mock() |
cfab619d | 1187 | |
f86ee140 IB |
1188 | def test_fetch_balances(self): |
1189 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | |
cfab619d | 1190 | |
f86ee140 | 1191 | balance_store = market.BalanceStore(self.m) |
cfab619d | 1192 | |
f86ee140 IB |
1193 | balance_store.fetch_balances() |
1194 | self.assertNotIn("ETC", balance_store.currencies()) | |
1195 | self.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store.currencies())) | |
1196 | ||
1197 | balance_store.all["ETC"] = portfolio.Balance("ETC", { | |
6ca5a1ec IB |
1198 | "exchange_total": "1", "exchange_free": "0", |
1199 | "exchange_used": "1" }) | |
f86ee140 IB |
1200 | balance_store.fetch_balances(tag="foo") |
1201 | self.assertEqual(0, balance_store.all["ETC"].total) | |
1202 | self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies())) | |
1203 | self.m.report.log_balances.assert_called_with(tag="foo") | |
cfab619d | 1204 | |
6ca5a1ec | 1205 | @mock.patch.object(portfolio.Portfolio, "repartition") |
f86ee140 IB |
1206 | def test_dispatch_assets(self, repartition): |
1207 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | |
1208 | ||
1209 | balance_store = market.BalanceStore(self.m) | |
1210 | balance_store.fetch_balances() | |
6ca5a1ec | 1211 | |
f86ee140 | 1212 | self.assertNotIn("XEM", balance_store.currencies()) |
6ca5a1ec | 1213 | |
3d0247f9 | 1214 | repartition_hash = { |
6ca5a1ec IB |
1215 | "XEM": (D("0.75"), "long"), |
1216 | "BTC": (D("0.26"), "long"), | |
1aa7d4fa | 1217 | "DASH": (D("0.10"), "short"), |
6ca5a1ec | 1218 | } |
3d0247f9 | 1219 | repartition.return_value = repartition_hash |
6ca5a1ec | 1220 | |
f86ee140 IB |
1221 | amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1")) |
1222 | repartition.assert_called_with(self.m, liquidity="medium") | |
1223 | self.assertIn("XEM", balance_store.currencies()) | |
6ca5a1ec IB |
1224 | self.assertEqual(D("2.6"), amounts["BTC"].value) |
1225 | self.assertEqual(D("7.5"), amounts["XEM"].value) | |
1aa7d4fa | 1226 | self.assertEqual(D("-1.0"), amounts["DASH"].value) |
f86ee140 IB |
1227 | self.m.report.log_balances.assert_called_with(tag=None) |
1228 | self.m.report.log_dispatch.assert_called_once_with(portfolio.Amount("BTC", | |
3d0247f9 | 1229 | "11.1"), amounts, "medium", repartition_hash) |
6ca5a1ec IB |
1230 | |
1231 | def test_currencies(self): | |
f86ee140 IB |
1232 | balance_store = market.BalanceStore(self.m) |
1233 | ||
1234 | balance_store.all = { | |
6ca5a1ec IB |
1235 | "BTC": portfolio.Balance("BTC", { |
1236 | "total": "0.65", | |
1237 | "exchange_total":"0.65", | |
1238 | "exchange_free": "0.35", | |
1239 | "exchange_used": "0.30"}), | |
1240 | "ETH": portfolio.Balance("ETH", { | |
1241 | "total": 3, | |
1242 | "exchange_total": 3, | |
1243 | "exchange_free": 3, | |
1244 | "exchange_used": 0}), | |
1245 | } | |
f86ee140 | 1246 | self.assertListEqual(["BTC", "ETH"], list(balance_store.currencies())) |
6ca5a1ec | 1247 | |
3d0247f9 IB |
1248 | def test_as_json(self): |
1249 | balance_mock1 = mock.Mock() | |
1250 | balance_mock1.as_json.return_value = 1 | |
1251 | ||
1252 | balance_mock2 = mock.Mock() | |
1253 | balance_mock2.as_json.return_value = 2 | |
1254 | ||
f86ee140 IB |
1255 | balance_store = market.BalanceStore(self.m) |
1256 | balance_store.all = { | |
3d0247f9 IB |
1257 | "BTC": balance_mock1, |
1258 | "ETH": balance_mock2, | |
1259 | } | |
1260 | ||
f86ee140 | 1261 | as_json = balance_store.as_json() |
3d0247f9 IB |
1262 | self.assertEqual(1, as_json["BTC"]) |
1263 | self.assertEqual(2, as_json["ETH"]) | |
1264 | ||
1265 | ||
1aa7d4fa | 1266 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
6ca5a1ec IB |
1267 | class ComputationTest(WebMockTestCase): |
1268 | def test_compute_value(self): | |
1269 | compute = mock.Mock() | |
1270 | portfolio.Computation.compute_value("foo", "buy", compute_value=compute) | |
1271 | compute.assert_called_with("foo", "ask") | |
1272 | ||
1273 | compute.reset_mock() | |
1274 | portfolio.Computation.compute_value("foo", "sell", compute_value=compute) | |
1275 | compute.assert_called_with("foo", "bid") | |
1276 | ||
1277 | compute.reset_mock() | |
1278 | portfolio.Computation.compute_value("foo", "ask", compute_value=compute) | |
1279 | compute.assert_called_with("foo", "ask") | |
1280 | ||
1281 | compute.reset_mock() | |
1282 | portfolio.Computation.compute_value("foo", "bid", compute_value=compute) | |
1283 | compute.assert_called_with("foo", "bid") | |
1284 | ||
1285 | compute.reset_mock() | |
1286 | portfolio.Computation.computations["test"] = compute | |
1287 | portfolio.Computation.compute_value("foo", "bid", compute_value="test") | |
1288 | compute.assert_called_with("foo", "bid") | |
1289 | ||
1290 | ||
1aa7d4fa | 1291 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
6ca5a1ec | 1292 | class TradeTest(WebMockTestCase): |
cfab619d | 1293 | |
cfab619d | 1294 | def test_values_assertion(self): |
c51687d2 IB |
1295 | value_from = portfolio.Amount("BTC", "1.0") |
1296 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1297 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1298 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
66c8b3dd IB |
1299 | self.assertEqual("BTC", trade.base_currency) |
1300 | self.assertEqual("ETH", trade.currency) | |
f86ee140 | 1301 | self.assertEqual(self.m, trade.market) |
66c8b3dd IB |
1302 | |
1303 | with self.assertRaises(AssertionError): | |
f86ee140 | 1304 | portfolio.Trade(value_from, value_to, "ETC", self.m) |
66c8b3dd IB |
1305 | with self.assertRaises(AssertionError): |
1306 | value_from.linked_to = None | |
f86ee140 | 1307 | portfolio.Trade(value_from, value_to, "ETH", self.m) |
66c8b3dd IB |
1308 | with self.assertRaises(AssertionError): |
1309 | value_from.currency = "ETH" | |
f86ee140 | 1310 | portfolio.Trade(value_from, value_to, "ETH", self.m) |
cfab619d | 1311 | |
c51687d2 | 1312 | value_from = portfolio.Amount("BTC", 0) |
f86ee140 | 1313 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 | 1314 | self.assertEqual(0, trade.value_from.linked_to) |
cfab619d | 1315 | |
cfab619d | 1316 | def test_action(self): |
c51687d2 IB |
1317 | value_from = portfolio.Amount("BTC", "1.0") |
1318 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1319 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1320 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
cfab619d | 1321 | |
c51687d2 IB |
1322 | self.assertIsNone(trade.action) |
1323 | ||
1324 | value_from = portfolio.Amount("BTC", "1.0") | |
1325 | value_from.linked_to = portfolio.Amount("BTC", "1.0") | |
1aa7d4fa | 1326 | value_to = portfolio.Amount("BTC", "2.0") |
f86ee140 | 1327 | trade = portfolio.Trade(value_from, value_to, "BTC", self.m) |
c51687d2 IB |
1328 | |
1329 | self.assertIsNone(trade.action) | |
1330 | ||
1331 | value_from = portfolio.Amount("BTC", "0.5") | |
1332 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1333 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1334 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1335 | |
1336 | self.assertEqual("acquire", trade.action) | |
1337 | ||
1338 | value_from = portfolio.Amount("BTC", "0") | |
1339 | value_from.linked_to = portfolio.Amount("ETH", "0") | |
1340 | value_to = portfolio.Amount("BTC", "-1.0") | |
f86ee140 | 1341 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 | 1342 | |
5a72ded7 | 1343 | self.assertEqual("acquire", trade.action) |
cfab619d | 1344 | |
cfab619d | 1345 | def test_order_action(self): |
c51687d2 IB |
1346 | value_from = portfolio.Amount("BTC", "0.5") |
1347 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1348 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1349 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1350 | |
1351 | self.assertEqual("buy", trade.order_action(False)) | |
1352 | self.assertEqual("sell", trade.order_action(True)) | |
1353 | ||
1354 | value_from = portfolio.Amount("BTC", "0") | |
1355 | value_from.linked_to = portfolio.Amount("ETH", "0") | |
1356 | value_to = portfolio.Amount("BTC", "-1.0") | |
f86ee140 | 1357 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1358 | |
1359 | self.assertEqual("sell", trade.order_action(False)) | |
1360 | self.assertEqual("buy", trade.order_action(True)) | |
1361 | ||
1362 | def test_trade_type(self): | |
1363 | value_from = portfolio.Amount("BTC", "0.5") | |
1364 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1365 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1366 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1367 | |
1368 | self.assertEqual("long", trade.trade_type) | |
1369 | ||
1370 | value_from = portfolio.Amount("BTC", "0") | |
1371 | value_from.linked_to = portfolio.Amount("ETH", "0") | |
1372 | value_to = portfolio.Amount("BTC", "-1.0") | |
f86ee140 | 1373 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1374 | |
1375 | self.assertEqual("short", trade.trade_type) | |
1376 | ||
1377 | def test_filled_amount(self): | |
1378 | value_from = portfolio.Amount("BTC", "0.5") | |
1379 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1380 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1381 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1382 | |
1383 | order1 = mock.Mock() | |
1aa7d4fa | 1384 | order1.filled_amount.return_value = portfolio.Amount("ETH", "0.3") |
c51687d2 IB |
1385 | |
1386 | order2 = mock.Mock() | |
1aa7d4fa | 1387 | order2.filled_amount.return_value = portfolio.Amount("ETH", "0.01") |
c51687d2 IB |
1388 | trade.orders.append(order1) |
1389 | trade.orders.append(order2) | |
1390 | ||
1aa7d4fa IB |
1391 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount()) |
1392 | order1.filled_amount.assert_called_with(in_base_currency=False) | |
1393 | order2.filled_amount.assert_called_with(in_base_currency=False) | |
c51687d2 | 1394 | |
1aa7d4fa IB |
1395 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=False)) |
1396 | order1.filled_amount.assert_called_with(in_base_currency=False) | |
1397 | order2.filled_amount.assert_called_with(in_base_currency=False) | |
1398 | ||
1399 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=True)) | |
1400 | order1.filled_amount.assert_called_with(in_base_currency=True) | |
1401 | order2.filled_amount.assert_called_with(in_base_currency=True) | |
1402 | ||
1aa7d4fa IB |
1403 | @mock.patch.object(portfolio.Computation, "compute_value") |
1404 | @mock.patch.object(portfolio.Trade, "filled_amount") | |
1405 | @mock.patch.object(portfolio, "Order") | |
f86ee140 | 1406 | def test_prepare_order(self, Order, filled_amount, compute_value): |
1aa7d4fa IB |
1407 | Order.return_value = "Order" |
1408 | ||
1409 | with self.subTest(desc="Nothing to do"): | |
1410 | value_from = portfolio.Amount("BTC", "10") | |
1411 | value_from.rate = D("0.1") | |
1412 | value_from.linked_to = portfolio.Amount("FOO", "100") | |
1413 | value_to = portfolio.Amount("BTC", "10") | |
f86ee140 | 1414 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1415 | |
1416 | trade.prepare_order() | |
1417 | ||
1418 | filled_amount.assert_not_called() | |
1419 | compute_value.assert_not_called() | |
1420 | self.assertEqual(0, len(trade.orders)) | |
1421 | Order.assert_not_called() | |
1422 | ||
f86ee140 IB |
1423 | self.m.get_ticker.return_value = { "inverted": False } |
1424 | with self.subTest(desc="Already filled"): | |
1aa7d4fa IB |
1425 | filled_amount.return_value = portfolio.Amount("FOO", "100") |
1426 | compute_value.return_value = D("0.125") | |
1427 | ||
1428 | value_from = portfolio.Amount("BTC", "10") | |
1429 | value_from.rate = D("0.1") | |
1430 | value_from.linked_to = portfolio.Amount("FOO", "100") | |
1431 | value_to = portfolio.Amount("BTC", "0") | |
f86ee140 | 1432 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1433 | |
1434 | trade.prepare_order() | |
1435 | ||
1436 | filled_amount.assert_called_with(in_base_currency=False) | |
f86ee140 | 1437 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") |
1aa7d4fa | 1438 | self.assertEqual(0, len(trade.orders)) |
f86ee140 | 1439 | self.m.report.log_error.assert_called_with("prepare_order", message=mock.ANY) |
1aa7d4fa IB |
1440 | Order.assert_not_called() |
1441 | ||
1442 | with self.subTest(action="dispose", inverted=False): | |
1443 | filled_amount.return_value = portfolio.Amount("FOO", "60") | |
1444 | compute_value.return_value = D("0.125") | |
1445 | ||
1446 | value_from = portfolio.Amount("BTC", "10") | |
1447 | value_from.rate = D("0.1") | |
1448 | value_from.linked_to = portfolio.Amount("FOO", "100") | |
1449 | value_to = portfolio.Amount("BTC", "1") | |
f86ee140 | 1450 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1451 | |
1452 | trade.prepare_order() | |
1453 | ||
1454 | filled_amount.assert_called_with(in_base_currency=False) | |
f86ee140 | 1455 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") |
1aa7d4fa IB |
1456 | self.assertEqual(1, len(trade.orders)) |
1457 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | |
f86ee140 | 1458 | D("0.125"), "BTC", "long", self.m, |
1aa7d4fa IB |
1459 | trade, close_if_possible=False) |
1460 | ||
1461 | with self.subTest(action="acquire", inverted=False): | |
1462 | filled_amount.return_value = portfolio.Amount("BTC", "3") | |
1463 | compute_value.return_value = D("0.125") | |
1464 | ||
1465 | value_from = portfolio.Amount("BTC", "1") | |
1466 | value_from.rate = D("0.1") | |
1467 | value_from.linked_to = portfolio.Amount("FOO", "10") | |
1468 | value_to = portfolio.Amount("BTC", "10") | |
f86ee140 | 1469 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1470 | |
1471 | trade.prepare_order() | |
1472 | ||
1473 | filled_amount.assert_called_with(in_base_currency=True) | |
f86ee140 | 1474 | compute_value.assert_called_with(self.m.get_ticker.return_value, "buy", compute_value="default") |
1aa7d4fa IB |
1475 | self.assertEqual(1, len(trade.orders)) |
1476 | ||
1477 | Order.assert_called_with("buy", portfolio.Amount("FOO", 48), | |
f86ee140 | 1478 | D("0.125"), "BTC", "long", self.m, |
1aa7d4fa IB |
1479 | trade, close_if_possible=False) |
1480 | ||
1481 | with self.subTest(close_if_possible=True): | |
1482 | filled_amount.return_value = portfolio.Amount("FOO", "0") | |
1483 | compute_value.return_value = D("0.125") | |
1484 | ||
1485 | value_from = portfolio.Amount("BTC", "10") | |
1486 | value_from.rate = D("0.1") | |
1487 | value_from.linked_to = portfolio.Amount("FOO", "100") | |
1488 | value_to = portfolio.Amount("BTC", "0") | |
f86ee140 | 1489 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1490 | |
1491 | trade.prepare_order() | |
1492 | ||
1493 | filled_amount.assert_called_with(in_base_currency=False) | |
f86ee140 | 1494 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") |
1aa7d4fa IB |
1495 | self.assertEqual(1, len(trade.orders)) |
1496 | Order.assert_called_with("sell", portfolio.Amount("FOO", 100), | |
f86ee140 | 1497 | D("0.125"), "BTC", "long", self.m, |
1aa7d4fa IB |
1498 | trade, close_if_possible=True) |
1499 | ||
f86ee140 | 1500 | self.m.get_ticker.return_value = { "inverted": True, "original": {} } |
1aa7d4fa IB |
1501 | with self.subTest(action="dispose", inverted=True): |
1502 | filled_amount.return_value = portfolio.Amount("FOO", "300") | |
1503 | compute_value.return_value = D("125") | |
1504 | ||
1505 | value_from = portfolio.Amount("BTC", "10") | |
1506 | value_from.rate = D("0.01") | |
1507 | value_from.linked_to = portfolio.Amount("FOO", "1000") | |
1508 | value_to = portfolio.Amount("BTC", "1") | |
f86ee140 | 1509 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1510 | |
1511 | trade.prepare_order(compute_value="foo") | |
1512 | ||
1513 | filled_amount.assert_called_with(in_base_currency=True) | |
f86ee140 | 1514 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "buy", compute_value="foo") |
1aa7d4fa IB |
1515 | self.assertEqual(1, len(trade.orders)) |
1516 | Order.assert_called_with("buy", portfolio.Amount("BTC", D("4.8")), | |
f86ee140 | 1517 | D("125"), "FOO", "long", self.m, |
1aa7d4fa IB |
1518 | trade, close_if_possible=False) |
1519 | ||
1520 | with self.subTest(action="acquire", inverted=True): | |
1521 | filled_amount.return_value = portfolio.Amount("BTC", "4") | |
1522 | compute_value.return_value = D("125") | |
1523 | ||
1524 | value_from = portfolio.Amount("BTC", "1") | |
1525 | value_from.rate = D("0.01") | |
1526 | value_from.linked_to = portfolio.Amount("FOO", "100") | |
1527 | value_to = portfolio.Amount("BTC", "10") | |
f86ee140 | 1528 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) |
1aa7d4fa IB |
1529 | |
1530 | trade.prepare_order(compute_value="foo") | |
1531 | ||
1532 | filled_amount.assert_called_with(in_base_currency=False) | |
f86ee140 | 1533 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "sell", compute_value="foo") |
1aa7d4fa IB |
1534 | self.assertEqual(1, len(trade.orders)) |
1535 | Order.assert_called_with("sell", portfolio.Amount("BTC", D("5")), | |
f86ee140 | 1536 | D("125"), "FOO", "long", self.m, |
1aa7d4fa IB |
1537 | trade, close_if_possible=False) |
1538 | ||
1539 | ||
1540 | @mock.patch.object(portfolio.Trade, "prepare_order") | |
1541 | def test_update_order(self, prepare_order): | |
1542 | order_mock = mock.Mock() | |
1543 | new_order_mock = mock.Mock() | |
1544 | ||
1545 | value_from = portfolio.Amount("BTC", "0.5") | |
1546 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1547 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1548 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
5a72ded7 | 1549 | prepare_order.return_value = new_order_mock |
1aa7d4fa IB |
1550 | |
1551 | for i in [0, 1, 3, 4, 6]: | |
f86ee140 | 1552 | with self.subTest(tick=i): |
1aa7d4fa IB |
1553 | trade.update_order(order_mock, i) |
1554 | order_mock.cancel.assert_not_called() | |
1555 | new_order_mock.run.assert_not_called() | |
f86ee140 | 1556 | self.m.report.log_order.assert_called_once_with(order_mock, i, |
3d0247f9 | 1557 | update="waiting", compute_value=None, new_order=None) |
1aa7d4fa IB |
1558 | |
1559 | order_mock.reset_mock() | |
1560 | new_order_mock.reset_mock() | |
1561 | trade.orders = [] | |
f86ee140 IB |
1562 | self.m.report.log_order.reset_mock() |
1563 | ||
1564 | trade.update_order(order_mock, 2) | |
1565 | order_mock.cancel.assert_called() | |
1566 | new_order_mock.run.assert_called() | |
1567 | prepare_order.assert_called() | |
1568 | self.m.report.log_order.assert_called() | |
1569 | self.assertEqual(2, self.m.report.log_order.call_count) | |
1570 | calls = [ | |
1571 | mock.call(order_mock, 2, update="adjusting", | |
1572 | compute_value='lambda x, y: (x[y] + x["average"]) / 2', | |
1573 | new_order=new_order_mock), | |
1574 | mock.call(order_mock, 2, new_order=new_order_mock), | |
1575 | ] | |
1576 | self.m.report.log_order.assert_has_calls(calls) | |
1aa7d4fa IB |
1577 | |
1578 | order_mock.reset_mock() | |
1579 | new_order_mock.reset_mock() | |
1580 | trade.orders = [] | |
f86ee140 IB |
1581 | self.m.report.log_order.reset_mock() |
1582 | ||
1583 | trade.update_order(order_mock, 5) | |
1584 | order_mock.cancel.assert_called() | |
1585 | new_order_mock.run.assert_called() | |
1586 | prepare_order.assert_called() | |
1587 | self.assertEqual(2, self.m.report.log_order.call_count) | |
1588 | self.m.report.log_order.assert_called() | |
1589 | calls = [ | |
1590 | mock.call(order_mock, 5, update="adjusting", | |
1591 | compute_value='lambda x, y: (x[y]*2 + x["average"]) / 3', | |
1592 | new_order=new_order_mock), | |
1593 | mock.call(order_mock, 5, new_order=new_order_mock), | |
1594 | ] | |
1595 | self.m.report.log_order.assert_has_calls(calls) | |
1aa7d4fa IB |
1596 | |
1597 | order_mock.reset_mock() | |
1598 | new_order_mock.reset_mock() | |
1599 | trade.orders = [] | |
f86ee140 IB |
1600 | self.m.report.log_order.reset_mock() |
1601 | ||
1602 | trade.update_order(order_mock, 7) | |
1603 | order_mock.cancel.assert_called() | |
1604 | new_order_mock.run.assert_called() | |
1605 | prepare_order.assert_called_with(compute_value="default") | |
1606 | self.m.report.log_order.assert_called() | |
1607 | self.assertEqual(2, self.m.report.log_order.call_count) | |
1608 | calls = [ | |
1609 | mock.call(order_mock, 7, update="market_fallback", | |
1610 | compute_value='default', | |
1611 | new_order=new_order_mock), | |
1612 | mock.call(order_mock, 7, new_order=new_order_mock), | |
1613 | ] | |
1614 | self.m.report.log_order.assert_has_calls(calls) | |
1aa7d4fa IB |
1615 | |
1616 | order_mock.reset_mock() | |
1617 | new_order_mock.reset_mock() | |
1618 | trade.orders = [] | |
f86ee140 | 1619 | self.m.report.log_order.reset_mock() |
1aa7d4fa IB |
1620 | |
1621 | for i in [10, 13, 16]: | |
f86ee140 | 1622 | with self.subTest(tick=i): |
1aa7d4fa IB |
1623 | trade.update_order(order_mock, i) |
1624 | order_mock.cancel.assert_called() | |
1625 | new_order_mock.run.assert_called() | |
1626 | prepare_order.assert_called_with(compute_value="default") | |
f86ee140 IB |
1627 | self.m.report.log_order.assert_called() |
1628 | self.assertEqual(2, self.m.report.log_order.call_count) | |
3d0247f9 IB |
1629 | calls = [ |
1630 | mock.call(order_mock, i, update="market_adjust", | |
1631 | compute_value='default', | |
1632 | new_order=new_order_mock), | |
1633 | mock.call(order_mock, i, new_order=new_order_mock), | |
1634 | ] | |
f86ee140 | 1635 | self.m.report.log_order.assert_has_calls(calls) |
1aa7d4fa IB |
1636 | |
1637 | order_mock.reset_mock() | |
1638 | new_order_mock.reset_mock() | |
1639 | trade.orders = [] | |
f86ee140 | 1640 | self.m.report.log_order.reset_mock() |
1aa7d4fa IB |
1641 | |
1642 | for i in [8, 9, 11, 12]: | |
f86ee140 | 1643 | with self.subTest(tick=i): |
1aa7d4fa IB |
1644 | trade.update_order(order_mock, i) |
1645 | order_mock.cancel.assert_not_called() | |
1646 | new_order_mock.run.assert_not_called() | |
f86ee140 | 1647 | self.m.report.log_order.assert_called_once_with(order_mock, i, update="waiting", |
3d0247f9 | 1648 | compute_value=None, new_order=None) |
1aa7d4fa IB |
1649 | |
1650 | order_mock.reset_mock() | |
1651 | new_order_mock.reset_mock() | |
1652 | trade.orders = [] | |
f86ee140 | 1653 | self.m.report.log_order.reset_mock() |
cfab619d | 1654 | |
cfab619d | 1655 | |
f86ee140 | 1656 | def test_print_with_order(self): |
c51687d2 IB |
1657 | value_from = portfolio.Amount("BTC", "0.5") |
1658 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1659 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1660 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1661 | |
1662 | order_mock1 = mock.Mock() | |
1663 | order_mock1.__repr__ = mock.Mock() | |
1664 | order_mock1.__repr__.return_value = "Mock 1" | |
1665 | order_mock2 = mock.Mock() | |
1666 | order_mock2.__repr__ = mock.Mock() | |
1667 | order_mock2.__repr__.return_value = "Mock 2" | |
c31df868 IB |
1668 | order_mock1.mouvements = [] |
1669 | mouvement_mock1 = mock.Mock() | |
1670 | mouvement_mock1.__repr__ = mock.Mock() | |
1671 | mouvement_mock1.__repr__.return_value = "Mouvement 1" | |
1672 | mouvement_mock2 = mock.Mock() | |
1673 | mouvement_mock2.__repr__ = mock.Mock() | |
1674 | mouvement_mock2.__repr__.return_value = "Mouvement 2" | |
1675 | order_mock2.mouvements = [ | |
1676 | mouvement_mock1, mouvement_mock2 | |
1677 | ] | |
c51687d2 IB |
1678 | trade.orders.append(order_mock1) |
1679 | trade.orders.append(order_mock2) | |
1680 | ||
1681 | trade.print_with_order() | |
1682 | ||
f86ee140 IB |
1683 | self.m.report.print_log.assert_called() |
1684 | calls = self.m.report.print_log.mock_calls | |
3d0247f9 IB |
1685 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls[0][1][0])) |
1686 | self.assertEqual("\tMock 1", str(calls[1][1][0])) | |
1687 | self.assertEqual("\tMock 2", str(calls[2][1][0])) | |
1688 | self.assertEqual("\t\tMouvement 1", str(calls[3][1][0])) | |
1689 | self.assertEqual("\t\tMouvement 2", str(calls[4][1][0])) | |
c51687d2 | 1690 | |
cfab619d | 1691 | def test__repr(self): |
c51687d2 IB |
1692 | value_from = portfolio.Amount("BTC", "0.5") |
1693 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1694 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1695 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
c51687d2 IB |
1696 | |
1697 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade)) | |
cfab619d | 1698 | |
3d0247f9 IB |
1699 | def test_as_json(self): |
1700 | value_from = portfolio.Amount("BTC", "0.5") | |
1701 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | |
1702 | value_to = portfolio.Amount("BTC", "1.0") | |
f86ee140 | 1703 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) |
3d0247f9 IB |
1704 | |
1705 | as_json = trade.as_json() | |
1706 | self.assertEqual("acquire", as_json["action"]) | |
1707 | self.assertEqual(D("0.5"), as_json["from"]) | |
1708 | self.assertEqual(D("1.0"), as_json["to"]) | |
1709 | self.assertEqual("ETH", as_json["currency"]) | |
1710 | self.assertEqual("BTC", as_json["base_currency"]) | |
1711 | ||
5a72ded7 IB |
1712 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
1713 | class OrderTest(WebMockTestCase): | |
1714 | def test_values(self): | |
1715 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1716 | D("0.1"), "BTC", "long", "market", "trade") | |
1717 | self.assertEqual("buy", order.action) | |
1718 | self.assertEqual(10, order.amount.value) | |
1719 | self.assertEqual("ETH", order.amount.currency) | |
1720 | self.assertEqual(D("0.1"), order.rate) | |
1721 | self.assertEqual("BTC", order.base_currency) | |
1722 | self.assertEqual("market", order.market) | |
1723 | self.assertEqual("long", order.trade_type) | |
1724 | self.assertEqual("pending", order.status) | |
1725 | self.assertEqual("trade", order.trade) | |
1726 | self.assertIsNone(order.id) | |
1727 | self.assertFalse(order.close_if_possible) | |
1728 | ||
1729 | def test__repr(self): | |
1730 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1731 | D("0.1"), "BTC", "long", "market", "trade") | |
1732 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order)) | |
1733 | ||
1734 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1735 | D("0.1"), "BTC", "long", "market", "trade", | |
1736 | close_if_possible=True) | |
1737 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order)) | |
1738 | ||
3d0247f9 IB |
1739 | def test_as_json(self): |
1740 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1741 | D("0.1"), "BTC", "long", "market", "trade") | |
1742 | mouvement_mock1 = mock.Mock() | |
1743 | mouvement_mock1.as_json.return_value = 1 | |
1744 | mouvement_mock2 = mock.Mock() | |
1745 | mouvement_mock2.as_json.return_value = 2 | |
1746 | ||
1747 | order.mouvements = [mouvement_mock1, mouvement_mock2] | |
1748 | as_json = order.as_json() | |
1749 | self.assertEqual("buy", as_json["action"]) | |
1750 | self.assertEqual("long", as_json["trade_type"]) | |
1751 | self.assertEqual(10, as_json["amount"]) | |
1752 | self.assertEqual("ETH", as_json["currency"]) | |
1753 | self.assertEqual("BTC", as_json["base_currency"]) | |
1754 | self.assertEqual(D("0.1"), as_json["rate"]) | |
1755 | self.assertEqual("pending", as_json["status"]) | |
1756 | self.assertEqual(False, as_json["close_if_possible"]) | |
1757 | self.assertIsNone(as_json["id"]) | |
1758 | self.assertEqual([1, 2], as_json["mouvements"]) | |
1759 | ||
5a72ded7 IB |
1760 | def test_account(self): |
1761 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1762 | D("0.1"), "BTC", "long", "market", "trade") | |
1763 | self.assertEqual("exchange", order.account) | |
1764 | ||
1765 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | |
1766 | D("0.1"), "BTC", "short", "market", "trade") | |
1767 | self.assertEqual("margin", order.account) | |
1768 | ||
1769 | def test_pending(self): | |
1770 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1771 | D("0.1"), "BTC", "long", "market", "trade") | |
1772 | self.assertTrue(order.pending) | |
1773 | order.status = "open" | |
1774 | self.assertFalse(order.pending) | |
1775 | ||
1776 | def test_open(self): | |
1777 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1778 | D("0.1"), "BTC", "long", "market", "trade") | |
1779 | self.assertFalse(order.open) | |
1780 | order.status = "open" | |
1781 | self.assertTrue(order.open) | |
1782 | ||
1783 | def test_finished(self): | |
1784 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
1785 | D("0.1"), "BTC", "long", "market", "trade") | |
1786 | self.assertFalse(order.finished) | |
1787 | order.status = "closed" | |
1788 | self.assertTrue(order.finished) | |
1789 | order.status = "canceled" | |
1790 | self.assertTrue(order.finished) | |
1791 | order.status = "error" | |
1792 | self.assertTrue(order.finished) | |
1793 | ||
1794 | @mock.patch.object(portfolio.Order, "fetch") | |
f86ee140 IB |
1795 | def test_cancel(self, fetch): |
1796 | self.m.debug = True | |
5a72ded7 | 1797 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 1798 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
1799 | order.status = "open" |
1800 | ||
1801 | order.cancel() | |
f86ee140 IB |
1802 | self.m.ccxt.cancel_order.assert_not_called() |
1803 | self.m.report.log_debug_action.assert_called_once() | |
1804 | self.m.report.log_debug_action.reset_mock() | |
5a72ded7 IB |
1805 | self.assertEqual("canceled", order.status) |
1806 | ||
f86ee140 | 1807 | self.m.debug = False |
5a72ded7 | 1808 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 1809 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
1810 | order.status = "open" |
1811 | order.id = 42 | |
1812 | ||
1813 | order.cancel() | |
f86ee140 | 1814 | self.m.ccxt.cancel_order.assert_called_with(42) |
5a72ded7 | 1815 | fetch.assert_called_once() |
f86ee140 | 1816 | self.m.report.log_debug_action.assert_not_called() |
5a72ded7 IB |
1817 | |
1818 | def test_dust_amount_remaining(self): | |
1819 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1820 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
1821 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", 1)) |
1822 | self.assertFalse(order.dust_amount_remaining()) | |
1823 | ||
1824 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", D("0.0001"))) | |
1825 | self.assertTrue(order.dust_amount_remaining()) | |
1826 | ||
1827 | @mock.patch.object(portfolio.Order, "fetch") | |
1828 | @mock.patch.object(portfolio.Order, "filled_amount", return_value=portfolio.Amount("ETH", 1)) | |
1829 | def test_remaining_amount(self, filled_amount, fetch): | |
1830 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1831 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
1832 | |
1833 | self.assertEqual(9, order.remaining_amount().value) | |
1834 | order.fetch.assert_not_called() | |
1835 | ||
1836 | order.status = "open" | |
1837 | self.assertEqual(9, order.remaining_amount().value) | |
1838 | fetch.assert_called_once() | |
1839 | ||
1840 | @mock.patch.object(portfolio.Order, "fetch") | |
1841 | def test_filled_amount(self, fetch): | |
1842 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1843 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 | 1844 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { |
df9e4e7f | 1845 | "tradeID": 42, "type": "buy", "fee": "0.0015", |
5a72ded7 IB |
1846 | "date": "2017-12-30 12:00:12", "rate": "0.1", |
1847 | "amount": "3", "total": "0.3" | |
1848 | })) | |
1849 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | |
df9e4e7f | 1850 | "tradeID": 43, "type": "buy", "fee": "0.0015", |
5a72ded7 IB |
1851 | "date": "2017-12-30 13:00:12", "rate": "0.2", |
1852 | "amount": "2", "total": "0.4" | |
1853 | })) | |
1854 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount()) | |
1855 | fetch.assert_not_called() | |
1856 | order.status = "open" | |
1857 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount(in_base_currency=False)) | |
1858 | fetch.assert_called_once() | |
1859 | self.assertEqual(portfolio.Amount("BTC", "0.7"), order.filled_amount(in_base_currency=True)) | |
1860 | ||
1861 | def test_fetch_mouvements(self): | |
f86ee140 | 1862 | self.m.ccxt.privatePostReturnOrderTrades.return_value = [ |
5a72ded7 | 1863 | { |
df9e4e7f | 1864 | "tradeID": 42, "type": "buy", "fee": "0.0015", |
5a72ded7 IB |
1865 | "date": "2017-12-30 12:00:12", "rate": "0.1", |
1866 | "amount": "3", "total": "0.3" | |
1867 | }, | |
1868 | { | |
df9e4e7f | 1869 | "tradeID": 43, "type": "buy", "fee": "0.0015", |
5a72ded7 IB |
1870 | "date": "2017-12-30 13:00:12", "rate": "0.2", |
1871 | "amount": "2", "total": "0.4" | |
1872 | } | |
1873 | ] | |
1874 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1875 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
1876 | order.id = 12 |
1877 | order.mouvements = ["Foo", "Bar", "Baz"] | |
1878 | ||
1879 | order.fetch_mouvements() | |
1880 | ||
f86ee140 | 1881 | self.m.ccxt.privatePostReturnOrderTrades.assert_called_with({"orderNumber": 12}) |
5a72ded7 IB |
1882 | self.assertEqual(2, len(order.mouvements)) |
1883 | self.assertEqual(42, order.mouvements[0].id) | |
1884 | self.assertEqual(43, order.mouvements[1].id) | |
1885 | ||
f86ee140 | 1886 | self.m.ccxt.privatePostReturnOrderTrades.side_effect = portfolio.ExchangeError |
df9e4e7f | 1887 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 1888 | D("0.1"), "BTC", "long", self.m, "trade") |
df9e4e7f IB |
1889 | order.fetch_mouvements() |
1890 | self.assertEqual(0, len(order.mouvements)) | |
1891 | ||
f86ee140 | 1892 | def test_mark_finished_order(self): |
5a72ded7 | 1893 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 1894 | D("0.1"), "BTC", "short", self.m, "trade", |
5a72ded7 IB |
1895 | close_if_possible=True) |
1896 | order.status = "closed" | |
f86ee140 | 1897 | self.m.debug = False |
5a72ded7 IB |
1898 | |
1899 | order.mark_finished_order() | |
f86ee140 IB |
1900 | self.m.ccxt.close_margin_position.assert_called_with("ETH", "BTC") |
1901 | self.m.ccxt.close_margin_position.reset_mock() | |
5a72ded7 IB |
1902 | |
1903 | order.status = "open" | |
1904 | order.mark_finished_order() | |
f86ee140 | 1905 | self.m.ccxt.close_margin_position.assert_not_called() |
5a72ded7 IB |
1906 | |
1907 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1908 | D("0.1"), "BTC", "short", self.m, "trade", |
5a72ded7 IB |
1909 | close_if_possible=False) |
1910 | order.status = "closed" | |
1911 | order.mark_finished_order() | |
f86ee140 | 1912 | self.m.ccxt.close_margin_position.assert_not_called() |
5a72ded7 IB |
1913 | |
1914 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | |
f86ee140 | 1915 | D("0.1"), "BTC", "short", self.m, "trade", |
5a72ded7 IB |
1916 | close_if_possible=True) |
1917 | order.status = "closed" | |
1918 | order.mark_finished_order() | |
f86ee140 | 1919 | self.m.ccxt.close_margin_position.assert_not_called() |
5a72ded7 IB |
1920 | |
1921 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1922 | D("0.1"), "BTC", "long", self.m, "trade", |
5a72ded7 IB |
1923 | close_if_possible=True) |
1924 | order.status = "closed" | |
1925 | order.mark_finished_order() | |
f86ee140 | 1926 | self.m.ccxt.close_margin_position.assert_not_called() |
5a72ded7 | 1927 | |
f86ee140 | 1928 | self.m.debug = True |
5a72ded7 IB |
1929 | |
1930 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | |
f86ee140 | 1931 | D("0.1"), "BTC", "short", self.m, "trade", |
5a72ded7 IB |
1932 | close_if_possible=True) |
1933 | order.status = "closed" | |
1934 | ||
1935 | order.mark_finished_order() | |
f86ee140 IB |
1936 | self.m.ccxt.close_margin_position.assert_not_called() |
1937 | self.m.report.log_debug_action.assert_called_once() | |
5a72ded7 IB |
1938 | |
1939 | @mock.patch.object(portfolio.Order, "fetch_mouvements") | |
f86ee140 | 1940 | def test_fetch(self, fetch_mouvements): |
5a72ded7 IB |
1941 | time = self.time.time() |
1942 | with mock.patch.object(portfolio.time, "time") as time_mock: | |
5a72ded7 | 1943 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 1944 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
1945 | order.id = 45 |
1946 | with self.subTest(debug=True): | |
f86ee140 | 1947 | self.m.debug = True |
5a72ded7 IB |
1948 | order.fetch() |
1949 | time_mock.assert_not_called() | |
f86ee140 IB |
1950 | self.m.report.log_debug_action.assert_called_once() |
1951 | self.m.report.log_debug_action.reset_mock() | |
5a72ded7 IB |
1952 | order.fetch(force=True) |
1953 | time_mock.assert_not_called() | |
f86ee140 | 1954 | self.m.ccxt.fetch_order.assert_not_called() |
5a72ded7 | 1955 | fetch_mouvements.assert_not_called() |
f86ee140 IB |
1956 | self.m.report.log_debug_action.assert_called_once() |
1957 | self.m.report.log_debug_action.reset_mock() | |
5a72ded7 IB |
1958 | self.assertIsNone(order.fetch_cache_timestamp) |
1959 | ||
1960 | with self.subTest(debug=False): | |
f86ee140 | 1961 | self.m.debug = False |
5a72ded7 | 1962 | time_mock.return_value = time |
f86ee140 | 1963 | self.m.ccxt.fetch_order.return_value = { |
5a72ded7 IB |
1964 | "status": "foo", |
1965 | "datetime": "timestamp" | |
1966 | } | |
1967 | order.fetch() | |
1968 | ||
f86ee140 | 1969 | self.m.ccxt.fetch_order.assert_called_once() |
5a72ded7 IB |
1970 | fetch_mouvements.assert_called_once() |
1971 | self.assertEqual("foo", order.status) | |
1972 | self.assertEqual("timestamp", order.timestamp) | |
1973 | self.assertEqual(time, order.fetch_cache_timestamp) | |
1974 | self.assertEqual(1, len(order.results)) | |
1975 | ||
f86ee140 | 1976 | self.m.ccxt.fetch_order.reset_mock() |
5a72ded7 IB |
1977 | fetch_mouvements.reset_mock() |
1978 | ||
1979 | time_mock.return_value = time + 8 | |
1980 | order.fetch() | |
f86ee140 | 1981 | self.m.ccxt.fetch_order.assert_not_called() |
5a72ded7 IB |
1982 | fetch_mouvements.assert_not_called() |
1983 | ||
1984 | order.fetch(force=True) | |
f86ee140 | 1985 | self.m.ccxt.fetch_order.assert_called_once() |
5a72ded7 IB |
1986 | fetch_mouvements.assert_called_once() |
1987 | ||
f86ee140 | 1988 | self.m.ccxt.fetch_order.reset_mock() |
5a72ded7 IB |
1989 | fetch_mouvements.reset_mock() |
1990 | ||
1991 | time_mock.return_value = time + 19 | |
1992 | order.fetch() | |
f86ee140 | 1993 | self.m.ccxt.fetch_order.assert_called_once() |
5a72ded7 | 1994 | fetch_mouvements.assert_called_once() |
f86ee140 | 1995 | self.m.report.log_debug_action.assert_not_called() |
5a72ded7 IB |
1996 | |
1997 | @mock.patch.object(portfolio.Order, "fetch") | |
1998 | @mock.patch.object(portfolio.Order, "mark_finished_order") | |
f86ee140 | 1999 | def test_get_status(self, mark_finished_order, fetch): |
5a72ded7 | 2000 | with self.subTest(debug=True): |
f86ee140 | 2001 | self.m.debug = True |
5a72ded7 | 2002 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 2003 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
2004 | self.assertEqual("pending", order.get_status()) |
2005 | fetch.assert_not_called() | |
f86ee140 | 2006 | self.m.report.log_debug_action.assert_called_once() |
5a72ded7 IB |
2007 | |
2008 | with self.subTest(debug=False, finished=False): | |
f86ee140 | 2009 | self.m.debug = False |
5a72ded7 | 2010 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 2011 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
2012 | def _fetch(order): |
2013 | def update_status(): | |
2014 | order.status = "open" | |
2015 | return update_status | |
2016 | fetch.side_effect = _fetch(order) | |
2017 | self.assertEqual("open", order.get_status()) | |
2018 | mark_finished_order.assert_not_called() | |
2019 | fetch.assert_called_once() | |
2020 | ||
2021 | mark_finished_order.reset_mock() | |
2022 | fetch.reset_mock() | |
2023 | with self.subTest(debug=False, finished=True): | |
f86ee140 | 2024 | self.m.debug = False |
5a72ded7 | 2025 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 2026 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 IB |
2027 | def _fetch(order): |
2028 | def update_status(): | |
2029 | order.status = "closed" | |
2030 | return update_status | |
2031 | fetch.side_effect = _fetch(order) | |
2032 | self.assertEqual("closed", order.get_status()) | |
2033 | mark_finished_order.assert_called_once() | |
2034 | fetch.assert_called_once() | |
2035 | ||
2036 | def test_run(self): | |
f86ee140 IB |
2037 | self.m.ccxt.order_precision.return_value = 4 |
2038 | with self.subTest(debug=True): | |
2039 | self.m.debug = True | |
5a72ded7 | 2040 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 | 2041 | D("0.1"), "BTC", "long", self.m, "trade") |
5a72ded7 | 2042 | order.run() |
f86ee140 IB |
2043 | self.m.ccxt.create_order.assert_not_called() |
2044 | self.m.report.log_debug_action.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)") | |
5a72ded7 IB |
2045 | self.assertEqual("open", order.status) |
2046 | self.assertEqual(1, len(order.results)) | |
2047 | self.assertEqual(-1, order.id) | |
2048 | ||
f86ee140 | 2049 | self.m.ccxt.create_order.reset_mock() |
5a72ded7 | 2050 | with self.subTest(debug=False): |
f86ee140 | 2051 | self.m.debug = False |
5a72ded7 | 2052 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 IB |
2053 | D("0.1"), "BTC", "long", self.m, "trade") |
2054 | self.m.ccxt.create_order.return_value = { "id": 123 } | |
5a72ded7 | 2055 | order.run() |
f86ee140 | 2056 | self.m.ccxt.create_order.assert_called_once() |
5a72ded7 IB |
2057 | self.assertEqual(1, len(order.results)) |
2058 | self.assertEqual("open", order.status) | |
2059 | ||
f86ee140 IB |
2060 | self.m.ccxt.create_order.reset_mock() |
2061 | with self.subTest(exception=True): | |
5a72ded7 | 2062 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), |
f86ee140 IB |
2063 | D("0.1"), "BTC", "long", self.m, "trade") |
2064 | self.m.ccxt.create_order.side_effect = Exception("bouh") | |
5a72ded7 | 2065 | order.run() |
f86ee140 | 2066 | self.m.ccxt.create_order.assert_called_once() |
5a72ded7 IB |
2067 | self.assertEqual(0, len(order.results)) |
2068 | self.assertEqual("error", order.status) | |
f86ee140 | 2069 | self.m.report.log_error.assert_called_once() |
5a72ded7 | 2070 | |
f86ee140 | 2071 | self.m.ccxt.create_order.reset_mock() |
df9e4e7f IB |
2072 | with self.subTest(dust_amount_exception=True),\ |
2073 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | |
2074 | order = portfolio.Order("buy", portfolio.Amount("ETH", 0.001), | |
f86ee140 IB |
2075 | D("0.1"), "BTC", "long", self.m, "trade") |
2076 | self.m.ccxt.create_order.side_effect = portfolio.ExchangeNotAvailable | |
df9e4e7f | 2077 | order.run() |
f86ee140 | 2078 | self.m.ccxt.create_order.assert_called_once() |
df9e4e7f IB |
2079 | self.assertEqual(0, len(order.results)) |
2080 | self.assertEqual("closed", order.status) | |
2081 | mark_finished_order.assert_called_once() | |
2082 | ||
2083 | ||
5a72ded7 IB |
2084 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
2085 | class MouvementTest(WebMockTestCase): | |
2086 | def test_values(self): | |
2087 | mouvement = portfolio.Mouvement("ETH", "BTC", { | |
df9e4e7f | 2088 | "tradeID": 42, "type": "buy", "fee": "0.0015", |
5a72ded7 IB |
2089 | "date": "2017-12-30 12:00:12", "rate": "0.1", |
2090 | "amount": "10", "total": "1" | |
2091 | }) | |
2092 | self.assertEqual("ETH", mouvement.currency) | |
2093 | self.assertEqual("BTC", mouvement.base_currency) | |
2094 | self.assertEqual(42, mouvement.id) | |
2095 | self.assertEqual("buy", mouvement.action) | |
2096 | self.assertEqual(D("0.0015"), mouvement.fee_rate) | |
2097 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), mouvement.date) | |
2098 | self.assertEqual(D("0.1"), mouvement.rate) | |
2099 | self.assertEqual(portfolio.Amount("ETH", "10"), mouvement.total) | |
2100 | self.assertEqual(portfolio.Amount("BTC", "1"), mouvement.total_in_base) | |
2101 | ||
df9e4e7f IB |
2102 | mouvement = portfolio.Mouvement("ETH", "BTC", { "foo": "bar" }) |
2103 | self.assertIsNone(mouvement.date) | |
2104 | self.assertIsNone(mouvement.id) | |
2105 | self.assertIsNone(mouvement.action) | |
2106 | self.assertEqual(-1, mouvement.fee_rate) | |
2107 | self.assertEqual(0, mouvement.rate) | |
2108 | self.assertEqual(portfolio.Amount("ETH", 0), mouvement.total) | |
2109 | self.assertEqual(portfolio.Amount("BTC", 0), mouvement.total_in_base) | |
2110 | ||
c31df868 IB |
2111 | def test__repr(self): |
2112 | mouvement = portfolio.Mouvement("ETH", "BTC", { | |
2113 | "tradeID": 42, "type": "buy", "fee": "0.0015", | |
2114 | "date": "2017-12-30 12:00:12", "rate": "0.1", | |
2115 | "amount": "10", "total": "1" | |
2116 | }) | |
2117 | self.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement)) | |
3d0247f9 | 2118 | |
c31df868 IB |
2119 | mouvement = portfolio.Mouvement("ETH", "BTC", { |
2120 | "tradeID": 42, "type": "buy", | |
2121 | "date": "garbage", "rate": "0.1", | |
2122 | "amount": "10", "total": "1" | |
2123 | }) | |
2124 | self.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement)) | |
2125 | ||
3d0247f9 IB |
2126 | def test_as_json(self): |
2127 | mouvement = portfolio.Mouvement("ETH", "BTC", { | |
2128 | "tradeID": 42, "type": "buy", "fee": "0.0015", | |
2129 | "date": "2017-12-30 12:00:12", "rate": "0.1", | |
2130 | "amount": "10", "total": "1" | |
2131 | }) | |
2132 | as_json = mouvement.as_json() | |
2133 | ||
2134 | self.assertEqual(D("0.0015"), as_json["fee_rate"]) | |
2135 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), as_json["date"]) | |
2136 | self.assertEqual("buy", as_json["action"]) | |
2137 | self.assertEqual(D("10"), as_json["total"]) | |
2138 | self.assertEqual(D("1"), as_json["total_in_base"]) | |
2139 | self.assertEqual("BTC", as_json["base_currency"]) | |
2140 | self.assertEqual("ETH", as_json["currency"]) | |
2141 | ||
2142 | @unittest.skipUnless("unit" in limits, "Unit skipped") | |
2143 | class ReportStoreTest(WebMockTestCase): | |
2144 | def test_add_log(self): | |
f86ee140 IB |
2145 | report_store = market.ReportStore(self.m) |
2146 | report_store.add_log({"foo": "bar"}) | |
3d0247f9 | 2147 | |
f86ee140 | 2148 | self.assertEqual({"foo": "bar", "date": mock.ANY}, report_store.logs[0]) |
3d0247f9 IB |
2149 | |
2150 | def test_set_verbose(self): | |
f86ee140 | 2151 | report_store = market.ReportStore(self.m) |
3d0247f9 | 2152 | with self.subTest(verbose=True): |
f86ee140 IB |
2153 | report_store.set_verbose(True) |
2154 | self.assertTrue(report_store.verbose_print) | |
3d0247f9 IB |
2155 | |
2156 | with self.subTest(verbose=False): | |
f86ee140 IB |
2157 | report_store.set_verbose(False) |
2158 | self.assertFalse(report_store.verbose_print) | |
3d0247f9 IB |
2159 | |
2160 | def test_print_log(self): | |
f86ee140 | 2161 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2162 | with self.subTest(verbose=True),\ |
2163 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
f86ee140 IB |
2164 | report_store.set_verbose(True) |
2165 | report_store.print_log("Coucou") | |
2166 | report_store.print_log(portfolio.Amount("BTC", 1)) | |
3d0247f9 IB |
2167 | self.assertEqual(stdout_mock.getvalue(), "Coucou\n1.00000000 BTC\n") |
2168 | ||
2169 | with self.subTest(verbose=False),\ | |
2170 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
f86ee140 IB |
2171 | report_store.set_verbose(False) |
2172 | report_store.print_log("Coucou") | |
2173 | report_store.print_log(portfolio.Amount("BTC", 1)) | |
3d0247f9 IB |
2174 | self.assertEqual(stdout_mock.getvalue(), "") |
2175 | ||
2176 | def test_to_json(self): | |
f86ee140 IB |
2177 | report_store = market.ReportStore(self.m) |
2178 | report_store.logs.append({"foo": "bar"}) | |
2179 | self.assertEqual('[{"foo": "bar"}]', report_store.to_json()) | |
2180 | report_store.logs.append({"date": portfolio.datetime(2018, 2, 24)}) | |
2181 | self.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}]', report_store.to_json()) | |
2182 | report_store.logs.append({"amount": portfolio.Amount("BTC", 1)}) | |
3d0247f9 | 2183 | with self.assertRaises(TypeError): |
f86ee140 | 2184 | report_store.to_json() |
3d0247f9 | 2185 | |
f86ee140 IB |
2186 | @mock.patch.object(market.ReportStore, "print_log") |
2187 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2188 | def test_log_stage(self, add_log, print_log): |
f86ee140 IB |
2189 | report_store = market.ReportStore(self.m) |
2190 | report_store.log_stage("foo") | |
3d0247f9 IB |
2191 | print_log.assert_has_calls([ |
2192 | mock.call("-----------"), | |
2193 | mock.call("[Stage] foo"), | |
2194 | ]) | |
2195 | add_log.assert_called_once_with({'type': 'stage', 'stage': 'foo'}) | |
2196 | ||
f86ee140 IB |
2197 | @mock.patch.object(market.ReportStore, "print_log") |
2198 | @mock.patch.object(market.ReportStore, "add_log") | |
2199 | def test_log_balances(self, add_log, print_log): | |
2200 | report_store = market.ReportStore(self.m) | |
2201 | self.m.balances.as_json.return_value = "json" | |
2202 | self.m.balances.all = { "FOO": "bar", "BAR": "baz" } | |
3d0247f9 | 2203 | |
f86ee140 | 2204 | report_store.log_balances(tag="tag") |
3d0247f9 IB |
2205 | print_log.assert_has_calls([ |
2206 | mock.call("[Balance]"), | |
2207 | mock.call("\tbar"), | |
2208 | mock.call("\tbaz"), | |
2209 | ]) | |
18167a3c IB |
2210 | add_log.assert_called_once_with({ |
2211 | 'type': 'balance', | |
2212 | 'balances': 'json', | |
2213 | 'tag': 'tag' | |
2214 | }) | |
3d0247f9 | 2215 | |
f86ee140 IB |
2216 | @mock.patch.object(market.ReportStore, "print_log") |
2217 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2218 | def test_log_tickers(self, add_log, print_log): |
f86ee140 | 2219 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2220 | amounts = { |
2221 | "BTC": portfolio.Amount("BTC", 10), | |
2222 | "ETH": portfolio.Amount("BTC", D("0.3")) | |
2223 | } | |
2224 | amounts["ETH"].rate = D("0.1") | |
2225 | ||
f86ee140 | 2226 | report_store.log_tickers(amounts, "BTC", "default", "total") |
3d0247f9 IB |
2227 | print_log.assert_not_called() |
2228 | add_log.assert_called_once_with({ | |
2229 | 'type': 'tickers', | |
2230 | 'compute_value': 'default', | |
2231 | 'balance_type': 'total', | |
2232 | 'currency': 'BTC', | |
2233 | 'balances': { | |
2234 | 'BTC': D('10'), | |
2235 | 'ETH': D('0.3') | |
2236 | }, | |
2237 | 'rates': { | |
2238 | 'BTC': None, | |
2239 | 'ETH': D('0.1') | |
2240 | }, | |
2241 | 'total': D('10.3') | |
2242 | }) | |
2243 | ||
f86ee140 IB |
2244 | @mock.patch.object(market.ReportStore, "print_log") |
2245 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2246 | def test_log_dispatch(self, add_log, print_log): |
f86ee140 | 2247 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2248 | amount = portfolio.Amount("BTC", "10.3") |
2249 | amounts = { | |
2250 | "BTC": portfolio.Amount("BTC", 10), | |
2251 | "ETH": portfolio.Amount("BTC", D("0.3")) | |
2252 | } | |
f86ee140 | 2253 | report_store.log_dispatch(amount, amounts, "medium", "repartition") |
3d0247f9 IB |
2254 | print_log.assert_not_called() |
2255 | add_log.assert_called_once_with({ | |
2256 | 'type': 'dispatch', | |
2257 | 'liquidity': 'medium', | |
2258 | 'repartition_ratio': 'repartition', | |
2259 | 'total_amount': { | |
2260 | 'currency': 'BTC', | |
2261 | 'value': D('10.3') | |
2262 | }, | |
2263 | 'repartition': { | |
2264 | 'BTC': D('10'), | |
2265 | 'ETH': D('0.3') | |
2266 | } | |
2267 | }) | |
2268 | ||
f86ee140 IB |
2269 | @mock.patch.object(market.ReportStore, "print_log") |
2270 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2271 | def test_log_trades(self, add_log, print_log): |
f86ee140 | 2272 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2273 | trade_mock1 = mock.Mock() |
2274 | trade_mock2 = mock.Mock() | |
2275 | trade_mock1.as_json.return_value = { "trade": "1" } | |
2276 | trade_mock2.as_json.return_value = { "trade": "2" } | |
2277 | ||
2278 | matching_and_trades = [ | |
2279 | (True, trade_mock1), | |
2280 | (False, trade_mock2), | |
2281 | ] | |
f86ee140 | 2282 | report_store.log_trades(matching_and_trades, "only") |
3d0247f9 IB |
2283 | |
2284 | print_log.assert_not_called() | |
2285 | add_log.assert_called_with({ | |
2286 | 'type': 'trades', | |
2287 | 'only': 'only', | |
f86ee140 | 2288 | 'debug': False, |
3d0247f9 IB |
2289 | 'trades': [ |
2290 | {'trade': '1', 'skipped': False}, | |
2291 | {'trade': '2', 'skipped': True} | |
2292 | ] | |
2293 | }) | |
2294 | ||
f86ee140 IB |
2295 | @mock.patch.object(market.ReportStore, "print_log") |
2296 | @mock.patch.object(market.ReportStore, "add_log") | |
2297 | def test_log_orders(self, add_log, print_log): | |
2298 | report_store = market.ReportStore(self.m) | |
2299 | ||
3d0247f9 IB |
2300 | order_mock1 = mock.Mock() |
2301 | order_mock2 = mock.Mock() | |
2302 | ||
2303 | order_mock1.as_json.return_value = "order1" | |
2304 | order_mock2.as_json.return_value = "order2" | |
2305 | ||
2306 | orders = [order_mock1, order_mock2] | |
2307 | ||
f86ee140 | 2308 | report_store.log_orders(orders, tick="tick", |
3d0247f9 IB |
2309 | only="only", compute_value="compute_value") |
2310 | ||
2311 | print_log.assert_called_once_with("[Orders]") | |
f86ee140 | 2312 | self.m.trades.print_all_with_order.assert_called_once_with(ind="\t") |
3d0247f9 IB |
2313 | |
2314 | add_log.assert_called_with({ | |
2315 | 'type': 'orders', | |
2316 | 'only': 'only', | |
2317 | 'compute_value': 'compute_value', | |
2318 | 'tick': 'tick', | |
2319 | 'orders': ['order1', 'order2'] | |
2320 | }) | |
2321 | ||
f86ee140 IB |
2322 | @mock.patch.object(market.ReportStore, "print_log") |
2323 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2324 | def test_log_order(self, add_log, print_log): |
f86ee140 | 2325 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2326 | order_mock = mock.Mock() |
2327 | order_mock.as_json.return_value = "order" | |
2328 | new_order_mock = mock.Mock() | |
2329 | new_order_mock.as_json.return_value = "new_order" | |
2330 | order_mock.__repr__ = mock.Mock() | |
2331 | order_mock.__repr__.return_value = "Order Mock" | |
2332 | new_order_mock.__repr__ = mock.Mock() | |
2333 | new_order_mock.__repr__.return_value = "New order Mock" | |
2334 | ||
2335 | with self.subTest(finished=True): | |
f86ee140 | 2336 | report_store.log_order(order_mock, 1, finished=True) |
3d0247f9 IB |
2337 | print_log.assert_called_once_with("[Order] Finished Order Mock") |
2338 | add_log.assert_called_once_with({ | |
2339 | 'type': 'order', | |
2340 | 'tick': 1, | |
2341 | 'update': None, | |
2342 | 'order': 'order', | |
2343 | 'compute_value': None, | |
2344 | 'new_order': None | |
2345 | }) | |
2346 | ||
2347 | add_log.reset_mock() | |
2348 | print_log.reset_mock() | |
2349 | ||
2350 | with self.subTest(update="waiting"): | |
f86ee140 | 2351 | report_store.log_order(order_mock, 1, update="waiting") |
3d0247f9 IB |
2352 | print_log.assert_called_once_with("[Order] Order Mock, tick 1, waiting") |
2353 | add_log.assert_called_once_with({ | |
2354 | 'type': 'order', | |
2355 | 'tick': 1, | |
2356 | 'update': 'waiting', | |
2357 | 'order': 'order', | |
2358 | 'compute_value': None, | |
2359 | 'new_order': None | |
2360 | }) | |
2361 | ||
2362 | add_log.reset_mock() | |
2363 | print_log.reset_mock() | |
2364 | with self.subTest(update="adjusting"): | |
f86ee140 | 2365 | report_store.log_order(order_mock, 3, |
3d0247f9 IB |
2366 | update="adjusting", new_order=new_order_mock, |
2367 | compute_value="default") | |
2368 | print_log.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock") | |
2369 | add_log.assert_called_once_with({ | |
2370 | 'type': 'order', | |
2371 | 'tick': 3, | |
2372 | 'update': 'adjusting', | |
2373 | 'order': 'order', | |
2374 | 'compute_value': "default", | |
2375 | 'new_order': 'new_order' | |
2376 | }) | |
2377 | ||
2378 | add_log.reset_mock() | |
2379 | print_log.reset_mock() | |
2380 | with self.subTest(update="market_fallback"): | |
f86ee140 | 2381 | report_store.log_order(order_mock, 7, |
3d0247f9 IB |
2382 | update="market_fallback", new_order=new_order_mock) |
2383 | print_log.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value") | |
2384 | add_log.assert_called_once_with({ | |
2385 | 'type': 'order', | |
2386 | 'tick': 7, | |
2387 | 'update': 'market_fallback', | |
2388 | 'order': 'order', | |
2389 | 'compute_value': None, | |
2390 | 'new_order': 'new_order' | |
2391 | }) | |
2392 | ||
2393 | add_log.reset_mock() | |
2394 | print_log.reset_mock() | |
2395 | with self.subTest(update="market_adjusting"): | |
f86ee140 | 2396 | report_store.log_order(order_mock, 17, |
3d0247f9 IB |
2397 | update="market_adjust", new_order=new_order_mock) |
2398 | print_log.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock") | |
2399 | add_log.assert_called_once_with({ | |
2400 | 'type': 'order', | |
2401 | 'tick': 17, | |
2402 | 'update': 'market_adjust', | |
2403 | 'order': 'order', | |
2404 | 'compute_value': None, | |
2405 | 'new_order': 'new_order' | |
2406 | }) | |
2407 | ||
f86ee140 IB |
2408 | @mock.patch.object(market.ReportStore, "print_log") |
2409 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2410 | def test_log_move_balances(self, add_log, print_log): |
f86ee140 | 2411 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2412 | needed = { |
2413 | "BTC": portfolio.Amount("BTC", 10), | |
2414 | "USDT": 1 | |
2415 | } | |
2416 | moving = { | |
2417 | "BTC": portfolio.Amount("BTC", 3), | |
2418 | "USDT": -2 | |
2419 | } | |
f86ee140 | 2420 | report_store.log_move_balances(needed, moving) |
3d0247f9 IB |
2421 | print_log.assert_not_called() |
2422 | add_log.assert_called_once_with({ | |
2423 | 'type': 'move_balances', | |
f86ee140 | 2424 | 'debug': False, |
3d0247f9 IB |
2425 | 'needed': { |
2426 | 'BTC': D('10'), | |
2427 | 'USDT': 1 | |
2428 | }, | |
2429 | 'moving': { | |
2430 | 'BTC': D('3'), | |
2431 | 'USDT': -2 | |
2432 | } | |
2433 | }) | |
2434 | ||
f86ee140 IB |
2435 | @mock.patch.object(market.ReportStore, "print_log") |
2436 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2437 | def test_log_http_request(self, add_log, print_log): |
f86ee140 | 2438 | report_store = market.ReportStore(self.m) |
3d0247f9 IB |
2439 | response = mock.Mock() |
2440 | response.status_code = 200 | |
2441 | response.text = "Hey" | |
2442 | ||
f86ee140 | 2443 | report_store.log_http_request("method", "url", "body", |
3d0247f9 IB |
2444 | "headers", response) |
2445 | print_log.assert_not_called() | |
2446 | add_log.assert_called_once_with({ | |
2447 | 'type': 'http_request', | |
2448 | 'method': 'method', | |
2449 | 'url': 'url', | |
2450 | 'body': 'body', | |
2451 | 'headers': 'headers', | |
2452 | 'status': 200, | |
2453 | 'response': 'Hey' | |
2454 | }) | |
2455 | ||
f86ee140 IB |
2456 | @mock.patch.object(market.ReportStore, "print_log") |
2457 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2458 | def test_log_error(self, add_log, print_log): |
f86ee140 | 2459 | report_store = market.ReportStore(self.m) |
3d0247f9 | 2460 | with self.subTest(message=None, exception=None): |
f86ee140 | 2461 | report_store.log_error("action") |
3d0247f9 IB |
2462 | print_log.assert_called_once_with("[Error] action") |
2463 | add_log.assert_called_once_with({ | |
2464 | 'type': 'error', | |
2465 | 'action': 'action', | |
2466 | 'exception_class': None, | |
2467 | 'exception_message': None, | |
2468 | 'message': None | |
2469 | }) | |
2470 | ||
2471 | print_log.reset_mock() | |
2472 | add_log.reset_mock() | |
2473 | with self.subTest(message="Hey", exception=None): | |
f86ee140 | 2474 | report_store.log_error("action", message="Hey") |
3d0247f9 IB |
2475 | print_log.assert_has_calls([ |
2476 | mock.call("[Error] action"), | |
2477 | mock.call("\tHey") | |
2478 | ]) | |
2479 | add_log.assert_called_once_with({ | |
2480 | 'type': 'error', | |
2481 | 'action': 'action', | |
2482 | 'exception_class': None, | |
2483 | 'exception_message': None, | |
2484 | 'message': "Hey" | |
2485 | }) | |
2486 | ||
2487 | print_log.reset_mock() | |
2488 | add_log.reset_mock() | |
2489 | with self.subTest(message=None, exception=Exception("bouh")): | |
f86ee140 | 2490 | report_store.log_error("action", exception=Exception("bouh")) |
3d0247f9 IB |
2491 | print_log.assert_has_calls([ |
2492 | mock.call("[Error] action"), | |
2493 | mock.call("\tException: bouh") | |
2494 | ]) | |
2495 | add_log.assert_called_once_with({ | |
2496 | 'type': 'error', | |
2497 | 'action': 'action', | |
2498 | 'exception_class': "Exception", | |
2499 | 'exception_message': "bouh", | |
2500 | 'message': None | |
2501 | }) | |
2502 | ||
2503 | print_log.reset_mock() | |
2504 | add_log.reset_mock() | |
2505 | with self.subTest(message="Hey", exception=Exception("bouh")): | |
f86ee140 | 2506 | report_store.log_error("action", message="Hey", exception=Exception("bouh")) |
3d0247f9 IB |
2507 | print_log.assert_has_calls([ |
2508 | mock.call("[Error] action"), | |
2509 | mock.call("\tException: bouh"), | |
2510 | mock.call("\tHey") | |
2511 | ]) | |
2512 | add_log.assert_called_once_with({ | |
2513 | 'type': 'error', | |
2514 | 'action': 'action', | |
2515 | 'exception_class': "Exception", | |
2516 | 'exception_message': "bouh", | |
2517 | 'message': "Hey" | |
2518 | }) | |
2519 | ||
f86ee140 IB |
2520 | @mock.patch.object(market.ReportStore, "print_log") |
2521 | @mock.patch.object(market.ReportStore, "add_log") | |
3d0247f9 | 2522 | def test_log_debug_action(self, add_log, print_log): |
f86ee140 IB |
2523 | report_store = market.ReportStore(self.m) |
2524 | report_store.log_debug_action("Hey") | |
3d0247f9 IB |
2525 | |
2526 | print_log.assert_called_once_with("[Debug] Hey") | |
2527 | add_log.assert_called_once_with({ | |
2528 | 'type': 'debug_action', | |
2529 | 'action': 'Hey' | |
2530 | }) | |
2531 | ||
f86ee140 IB |
2532 | @unittest.skipUnless("unit" in limits, "Unit skipped") |
2533 | class HelperTest(WebMockTestCase): | |
2534 | def test_main_store_report(self): | |
2535 | file_open = mock.mock_open() | |
2536 | with self.subTest(file=None), mock.patch("__main__.open", file_open): | |
2537 | helper.main_store_report(None, 1, self.m) | |
2538 | file_open.assert_not_called() | |
2539 | ||
2540 | file_open = mock.mock_open() | |
2541 | with self.subTest(file="present"), mock.patch("helper.open", file_open),\ | |
2542 | mock.patch.object(helper, "datetime") as time_mock: | |
2543 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | |
2544 | self.m.report.to_json.return_value = "json_content" | |
2545 | ||
2546 | helper.main_store_report("present", 1, self.m) | |
2547 | ||
2548 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.json", "w") | |
2549 | file_open().write.assert_called_once_with("json_content") | |
2550 | self.m.report.to_json.assert_called_once_with() | |
2551 | ||
2552 | with self.subTest(file="error"),\ | |
2553 | mock.patch("helper.open") as file_open,\ | |
2554 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
2555 | file_open.side_effect = FileNotFoundError | |
2556 | ||
2557 | helper.main_store_report("error", 1, self.m) | |
2558 | ||
2559 | self.assertRegex(stdout_mock.getvalue(), "impossible to store report file: FileNotFoundError;") | |
2560 | ||
2561 | @mock.patch("helper.process_sell_all__1_all_sell") | |
2562 | @mock.patch("helper.process_sell_all__2_all_buy") | |
2563 | @mock.patch("portfolio.Portfolio.wait_for_recent") | |
2564 | def test_main_process_market(self, wait, buy, sell): | |
2565 | with self.subTest(before=False, after=False): | |
2566 | helper.main_process_market("user") | |
2567 | ||
2568 | wait.assert_not_called() | |
2569 | buy.assert_not_called() | |
2570 | sell.assert_not_called() | |
2571 | ||
2572 | buy.reset_mock() | |
2573 | wait.reset_mock() | |
2574 | sell.reset_mock() | |
2575 | with self.subTest(before=True, after=False): | |
2576 | helper.main_process_market("user", before=True) | |
2577 | ||
2578 | wait.assert_not_called() | |
2579 | buy.assert_not_called() | |
2580 | sell.assert_called_once_with("user") | |
2581 | ||
2582 | buy.reset_mock() | |
2583 | wait.reset_mock() | |
2584 | sell.reset_mock() | |
2585 | with self.subTest(before=False, after=True): | |
2586 | helper.main_process_market("user", after=True) | |
2587 | ||
2588 | wait.assert_called_once_with("user") | |
2589 | buy.assert_called_once_with("user") | |
2590 | sell.assert_not_called() | |
2591 | ||
2592 | buy.reset_mock() | |
2593 | wait.reset_mock() | |
2594 | sell.reset_mock() | |
2595 | with self.subTest(before=True, after=True): | |
2596 | helper.main_process_market("user", before=True, after=True) | |
2597 | ||
2598 | wait.assert_called_once_with("user") | |
2599 | buy.assert_called_once_with("user") | |
2600 | sell.assert_called_once_with("user") | |
2601 | ||
2602 | @mock.patch.object(helper, "psycopg2") | |
2603 | def test_fetch_markets(self, psycopg2): | |
2604 | connect_mock = mock.Mock() | |
2605 | cursor_mock = mock.MagicMock() | |
2606 | cursor_mock.__iter__.return_value = ["row_1", "row_2"] | |
2607 | ||
2608 | connect_mock.cursor.return_value = cursor_mock | |
2609 | psycopg2.connect.return_value = connect_mock | |
2610 | ||
2611 | rows = list(helper.main_fetch_markets({"foo": "bar"})) | |
2612 | ||
2613 | psycopg2.connect.assert_called_once_with(foo="bar") | |
2614 | cursor_mock.execute.assert_called_once_with("SELECT config,user_id FROM market_configs") | |
2615 | ||
2616 | self.assertEqual(["row_1", "row_2"], rows) | |
2617 | ||
2618 | @mock.patch.object(helper.sys, "exit") | |
2619 | def test_main_parse_args(self, exit): | |
2620 | with self.subTest(config="config.ini"): | |
2621 | args = helper.main_parse_args([]) | |
2622 | self.assertEqual("config.ini", args.config) | |
2623 | self.assertFalse(args.before) | |
2624 | self.assertFalse(args.after) | |
2625 | self.assertFalse(args.debug) | |
2626 | ||
2627 | args = helper.main_parse_args(["--before", "--after", "--debug"]) | |
2628 | self.assertTrue(args.before) | |
2629 | self.assertTrue(args.after) | |
2630 | self.assertTrue(args.debug) | |
2631 | ||
2632 | exit.assert_not_called() | |
2633 | ||
2634 | with self.subTest(config="inexistant"),\ | |
2635 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
2636 | args = helper.main_parse_args(["--config", "foo.bar"]) | |
2637 | exit.assert_called_once_with(1) | |
2638 | self.assertEqual("no config file found, exiting\n", stdout_mock.getvalue()) | |
2639 | ||
2640 | @mock.patch.object(helper.sys, "exit") | |
2641 | @mock.patch("helper.configparser") | |
2642 | @mock.patch("helper.os") | |
2643 | def test_main_parse_config(self, os, configparser, exit): | |
2644 | with self.subTest(pg_config=True, report_path=None): | |
2645 | config_mock = mock.MagicMock() | |
2646 | configparser.ConfigParser.return_value = config_mock | |
2647 | def config(element): | |
2648 | return element == "postgresql" | |
2649 | ||
2650 | config_mock.__contains__.side_effect = config | |
2651 | config_mock.__getitem__.return_value = "pg_config" | |
2652 | ||
2653 | result = helper.main_parse_config("configfile") | |
2654 | ||
2655 | config_mock.read.assert_called_with("configfile") | |
2656 | ||
2657 | self.assertEqual(["pg_config", None], result) | |
2658 | ||
2659 | with self.subTest(pg_config=True, report_path="present"): | |
2660 | config_mock = mock.MagicMock() | |
2661 | configparser.ConfigParser.return_value = config_mock | |
2662 | ||
2663 | config_mock.__contains__.return_value = True | |
2664 | config_mock.__getitem__.side_effect = [ | |
2665 | {"report_path": "report_path"}, | |
2666 | {"report_path": "report_path"}, | |
2667 | "pg_config", | |
2668 | ] | |
2669 | ||
2670 | os.path.exists.return_value = False | |
2671 | result = helper.main_parse_config("configfile") | |
2672 | ||
2673 | config_mock.read.assert_called_with("configfile") | |
2674 | self.assertEqual(["pg_config", "report_path"], result) | |
2675 | os.path.exists.assert_called_once_with("report_path") | |
2676 | os.makedirs.assert_called_once_with("report_path") | |
2677 | ||
2678 | with self.subTest(pg_config=False),\ | |
2679 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | |
2680 | config_mock = mock.MagicMock() | |
2681 | configparser.ConfigParser.return_value = config_mock | |
2682 | result = helper.main_parse_config("configfile") | |
2683 | ||
2684 | config_mock.read.assert_called_with("configfile") | |
2685 | exit.assert_called_once_with(1) | |
2686 | self.assertEqual("no configuration for postgresql in config file\n", stdout_mock.getvalue()) | |
2687 | ||
2688 | ||
2689 | def test_print_orders(self): | |
2690 | helper.print_orders(self.m) | |
2691 | ||
2692 | self.m.report.log_stage.assert_called_with("print_orders") | |
2693 | self.m.balances.fetch_balances.assert_called_with(tag="print_orders") | |
2694 | self.m.prepare_trades.assert_called_with(base_currency="BTC", | |
2695 | compute_value="average") | |
2696 | self.m.trades.prepare_orders.assert_called_with(compute_value="average") | |
2697 | ||
2698 | def test_print_balances(self): | |
2699 | self.m.balances.in_currency.return_value = { | |
2700 | "BTC": portfolio.Amount("BTC", "0.65"), | |
2701 | "ETH": portfolio.Amount("BTC", "0.3"), | |
2702 | } | |
2703 | ||
2704 | helper.print_balances(self.m) | |
2705 | ||
2706 | self.m.balances.fetch_balances.assert_called_with() | |
2707 | self.m.report.print_log.assert_has_calls([ | |
2708 | mock.call("total:"), | |
2709 | mock.call(portfolio.Amount("BTC", "0.95")), | |
2710 | ]) | |
2711 | ||
2712 | def test_process_sell_needed__1_sell(self): | |
2713 | helper.process_sell_needed__1_sell(self.m) | |
2714 | ||
2715 | self.m.balances.fetch_balances.assert_has_calls([ | |
2716 | mock.call(tag="process_sell_needed__1_sell_begin"), | |
2717 | mock.call(tag="process_sell_needed__1_sell_end"), | |
2718 | ]) | |
2719 | self.m.prepare_trades.assert_called_with(base_currency="BTC", | |
2720 | liquidity="medium") | |
2721 | self.m.trades.prepare_orders.assert_called_with(compute_value="average", | |
2722 | only="dispose") | |
2723 | self.m.trades.run_orders.assert_called() | |
2724 | self.m.follow_orders.assert_called() | |
2725 | self.m.report.log_stage.assert_has_calls([ | |
2726 | mock.call("process_sell_needed__1_sell_begin"), | |
2727 | mock.call("process_sell_needed__1_sell_end") | |
2728 | ]) | |
2729 | ||
2730 | def test_process_sell_needed__2_buy(self): | |
2731 | helper.process_sell_needed__2_buy(self.m) | |
2732 | ||
2733 | self.m.balances.fetch_balances.assert_has_calls([ | |
2734 | mock.call(tag="process_sell_needed__2_buy_begin"), | |
2735 | mock.call(tag="process_sell_needed__2_buy_end"), | |
2736 | ]) | |
2737 | self.m.update_trades.assert_called_with(base_currency="BTC", | |
2738 | liquidity="medium", only="acquire") | |
2739 | self.m.trades.prepare_orders.assert_called_with(compute_value="average", | |
2740 | only="acquire") | |
2741 | self.m.move_balances.assert_called_with() | |
2742 | self.m.trades.run_orders.assert_called() | |
2743 | self.m.follow_orders.assert_called() | |
2744 | self.m.report.log_stage.assert_has_calls([ | |
2745 | mock.call("process_sell_needed__2_buy_begin"), | |
2746 | mock.call("process_sell_needed__2_buy_end") | |
2747 | ]) | |
2748 | ||
2749 | def test_process_sell_all__1_sell(self): | |
2750 | helper.process_sell_all__1_all_sell(self.m) | |
2751 | ||
2752 | self.m.balances.fetch_balances.assert_has_calls([ | |
2753 | mock.call(tag="process_sell_all__1_all_sell_begin"), | |
2754 | mock.call(tag="process_sell_all__1_all_sell_end"), | |
2755 | ]) | |
2756 | self.m.prepare_trades_to_sell_all.assert_called_with(base_currency="BTC") | |
2757 | self.m.trades.prepare_orders.assert_called_with(compute_value="average") | |
2758 | self.m.trades.run_orders.assert_called() | |
2759 | self.m.follow_orders.assert_called() | |
2760 | self.m.report.log_stage.assert_has_calls([ | |
2761 | mock.call("process_sell_all__1_all_sell_begin"), | |
2762 | mock.call("process_sell_all__1_all_sell_end") | |
2763 | ]) | |
2764 | ||
2765 | def test_process_sell_all__2_all_buy(self): | |
2766 | helper.process_sell_all__2_all_buy(self.m) | |
2767 | ||
2768 | self.m.balances.fetch_balances.assert_has_calls([ | |
2769 | mock.call(tag="process_sell_all__2_all_buy_begin"), | |
2770 | mock.call(tag="process_sell_all__2_all_buy_end"), | |
2771 | ]) | |
2772 | self.m.prepare_trades.assert_called_with(base_currency="BTC", | |
2773 | liquidity="medium") | |
2774 | self.m.trades.prepare_orders.assert_called_with(compute_value="average") | |
2775 | self.m.move_balances.assert_called_with() | |
2776 | self.m.trades.run_orders.assert_called() | |
2777 | self.m.follow_orders.assert_called() | |
2778 | self.m.report.log_stage.assert_has_calls([ | |
2779 | mock.call("process_sell_all__2_all_buy_begin"), | |
2780 | mock.call("process_sell_all__2_all_buy_end") | |
2781 | ]) | |
2782 | ||
1aa7d4fa | 2783 | @unittest.skipUnless("acceptance" in limits, "Acceptance skipped") |
80cdd672 IB |
2784 | class AcceptanceTest(WebMockTestCase): |
2785 | @unittest.expectedFailure | |
a9950fd0 | 2786 | def test_success_sell_only_necessary(self): |
3d0247f9 | 2787 | # FIXME: catch stdout |
f86ee140 | 2788 | self.m.report.verbose_print = False |
a9950fd0 IB |
2789 | fetch_balance = { |
2790 | "ETH": { | |
c51687d2 IB |
2791 | "exchange_free": D("1.0"), |
2792 | "exchange_used": D("0.0"), | |
2793 | "exchange_total": D("1.0"), | |
a9950fd0 IB |
2794 | "total": D("1.0"), |
2795 | }, | |
2796 | "ETC": { | |
c51687d2 IB |
2797 | "exchange_free": D("4.0"), |
2798 | "exchange_used": D("0.0"), | |
2799 | "exchange_total": D("4.0"), | |
a9950fd0 IB |
2800 | "total": D("4.0"), |
2801 | }, | |
2802 | "XVG": { | |
c51687d2 IB |
2803 | "exchange_free": D("1000.0"), |
2804 | "exchange_used": D("0.0"), | |
2805 | "exchange_total": D("1000.0"), | |
a9950fd0 IB |
2806 | "total": D("1000.0"), |
2807 | }, | |
2808 | } | |
2809 | repartition = { | |
350ed24d IB |
2810 | "ETH": (D("0.25"), "long"), |
2811 | "ETC": (D("0.25"), "long"), | |
2812 | "BTC": (D("0.4"), "long"), | |
2813 | "BTD": (D("0.01"), "short"), | |
2814 | "B2X": (D("0.04"), "long"), | |
2815 | "USDT": (D("0.05"), "long"), | |
a9950fd0 IB |
2816 | } |
2817 | ||
2818 | def fetch_ticker(symbol): | |
2819 | if symbol == "ETH/BTC": | |
2820 | return { | |
2821 | "symbol": "ETH/BTC", | |
2822 | "bid": D("0.14"), | |
2823 | "ask": D("0.16") | |
2824 | } | |
2825 | if symbol == "ETC/BTC": | |
2826 | return { | |
2827 | "symbol": "ETC/BTC", | |
2828 | "bid": D("0.002"), | |
2829 | "ask": D("0.003") | |
2830 | } | |
2831 | if symbol == "XVG/BTC": | |
2832 | return { | |
2833 | "symbol": "XVG/BTC", | |
2834 | "bid": D("0.00003"), | |
2835 | "ask": D("0.00005") | |
2836 | } | |
2837 | if symbol == "BTD/BTC": | |
2838 | return { | |
2839 | "symbol": "BTD/BTC", | |
2840 | "bid": D("0.0008"), | |
2841 | "ask": D("0.0012") | |
2842 | } | |
350ed24d IB |
2843 | if symbol == "B2X/BTC": |
2844 | return { | |
2845 | "symbol": "B2X/BTC", | |
2846 | "bid": D("0.0008"), | |
2847 | "ask": D("0.0012") | |
2848 | } | |
a9950fd0 | 2849 | if symbol == "USDT/BTC": |
6ca5a1ec | 2850 | raise helper.ExchangeError |
a9950fd0 IB |
2851 | if symbol == "BTC/USDT": |
2852 | return { | |
2853 | "symbol": "BTC/USDT", | |
2854 | "bid": D("14000"), | |
2855 | "ask": D("16000") | |
2856 | } | |
2857 | self.fail("Shouldn't have been called with {}".format(symbol)) | |
2858 | ||
2859 | market = mock.Mock() | |
c51687d2 | 2860 | market.fetch_all_balances.return_value = fetch_balance |
a9950fd0 | 2861 | market.fetch_ticker.side_effect = fetch_ticker |
350ed24d | 2862 | with mock.patch.object(portfolio.Portfolio, "repartition", return_value=repartition): |
a9950fd0 | 2863 | # Action 1 |
6ca5a1ec | 2864 | helper.prepare_trades(market) |
a9950fd0 | 2865 | |
6ca5a1ec | 2866 | balances = portfolio.BalanceStore.all |
a9950fd0 IB |
2867 | self.assertEqual(portfolio.Amount("ETH", 1), balances["ETH"].total) |
2868 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | |
2869 | self.assertEqual(portfolio.Amount("XVG", 1000), balances["XVG"].total) | |
2870 | ||
2871 | ||
5a72ded7 | 2872 | trades = portfolio.TradeStore.all |
c51687d2 IB |
2873 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) |
2874 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | |
2875 | self.assertEqual("dispose", trades[0].action) | |
a9950fd0 | 2876 | |
c51687d2 IB |
2877 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) |
2878 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | |
2879 | self.assertEqual("acquire", trades[1].action) | |
a9950fd0 | 2880 | |
c51687d2 IB |
2881 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) |
2882 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | |
2883 | self.assertEqual("dispose", trades[2].action) | |
a9950fd0 | 2884 | |
c51687d2 IB |
2885 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) |
2886 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | |
5a72ded7 | 2887 | self.assertEqual("acquire", trades[3].action) |
350ed24d | 2888 | |
c51687d2 IB |
2889 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) |
2890 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | |
2891 | self.assertEqual("acquire", trades[4].action) | |
a9950fd0 | 2892 | |
c51687d2 IB |
2893 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) |
2894 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | |
2895 | self.assertEqual("acquire", trades[5].action) | |
a9950fd0 IB |
2896 | |
2897 | # Action 2 | |
5a72ded7 | 2898 | portfolio.TradeStore.prepare_orders(only="dispose", compute_value=lambda x, y: x["bid"] * D("1.001")) |
a9950fd0 | 2899 | |
5a72ded7 | 2900 | all_orders = portfolio.TradeStore.all_orders(state="pending") |
a9950fd0 IB |
2901 | self.assertEqual(2, len(all_orders)) |
2902 | self.assertEqual(2, 3*all_orders[0].amount.value) | |
2903 | self.assertEqual(D("0.14014"), all_orders[0].rate) | |
2904 | self.assertEqual(1000, all_orders[1].amount.value) | |
2905 | self.assertEqual(D("0.00003003"), all_orders[1].rate) | |
2906 | ||
2907 | ||
ecba1113 | 2908 | def create_order(symbol, type, action, amount, price=None, account="exchange"): |
a9950fd0 IB |
2909 | self.assertEqual("limit", type) |
2910 | if symbol == "ETH/BTC": | |
b83d4897 | 2911 | self.assertEqual("sell", action) |
350ed24d | 2912 | self.assertEqual(D('0.66666666'), amount) |
a9950fd0 IB |
2913 | self.assertEqual(D("0.14014"), price) |
2914 | elif symbol == "XVG/BTC": | |
b83d4897 | 2915 | self.assertEqual("sell", action) |
a9950fd0 IB |
2916 | self.assertEqual(1000, amount) |
2917 | self.assertEqual(D("0.00003003"), price) | |
2918 | else: | |
2919 | self.fail("I shouldn't have been called") | |
2920 | ||
2921 | return { | |
2922 | "id": symbol, | |
2923 | } | |
2924 | market.create_order.side_effect = create_order | |
350ed24d | 2925 | market.order_precision.return_value = 8 |
a9950fd0 IB |
2926 | |
2927 | # Action 3 | |
6ca5a1ec | 2928 | portfolio.TradeStore.run_orders() |
a9950fd0 IB |
2929 | |
2930 | self.assertEqual("open", all_orders[0].status) | |
2931 | self.assertEqual("open", all_orders[1].status) | |
2932 | ||
5a72ded7 IB |
2933 | market.fetch_order.return_value = { "status": "closed", "datetime": "2018-01-20 13:40:00" } |
2934 | market.privatePostReturnOrderTrades.return_value = [ | |
2935 | { | |
df9e4e7f | 2936 | "tradeID": 42, "type": "buy", "fee": "0.0015", |
5a72ded7 IB |
2937 | "date": "2017-12-30 12:00:12", "rate": "0.1", |
2938 | "amount": "10", "total": "1" | |
2939 | } | |
2940 | ] | |
a9950fd0 IB |
2941 | with mock.patch.object(portfolio.time, "sleep") as sleep: |
2942 | # Action 4 | |
6ca5a1ec | 2943 | helper.follow_orders(verbose=False) |
a9950fd0 IB |
2944 | |
2945 | sleep.assert_called_with(30) | |
2946 | ||
2947 | for order in all_orders: | |
2948 | self.assertEqual("closed", order.status) | |
2949 | ||
2950 | fetch_balance = { | |
2951 | "ETH": { | |
5a72ded7 IB |
2952 | "exchange_free": D("1.0") / 3, |
2953 | "exchange_used": D("0.0"), | |
2954 | "exchange_total": D("1.0") / 3, | |
2955 | "margin_total": 0, | |
a9950fd0 IB |
2956 | "total": D("1.0") / 3, |
2957 | }, | |
2958 | "BTC": { | |
5a72ded7 IB |
2959 | "exchange_free": D("0.134"), |
2960 | "exchange_used": D("0.0"), | |
2961 | "exchange_total": D("0.134"), | |
2962 | "margin_total": 0, | |
a9950fd0 IB |
2963 | "total": D("0.134"), |
2964 | }, | |
2965 | "ETC": { | |
5a72ded7 IB |
2966 | "exchange_free": D("4.0"), |
2967 | "exchange_used": D("0.0"), | |
2968 | "exchange_total": D("4.0"), | |
2969 | "margin_total": 0, | |
a9950fd0 IB |
2970 | "total": D("4.0"), |
2971 | }, | |
2972 | "XVG": { | |
5a72ded7 IB |
2973 | "exchange_free": D("0.0"), |
2974 | "exchange_used": D("0.0"), | |
2975 | "exchange_total": D("0.0"), | |
2976 | "margin_total": 0, | |
a9950fd0 IB |
2977 | "total": D("0.0"), |
2978 | }, | |
2979 | } | |
5a72ded7 | 2980 | market.fetch_all_balances.return_value = fetch_balance |
a9950fd0 | 2981 | |
350ed24d | 2982 | with mock.patch.object(portfolio.Portfolio, "repartition", return_value=repartition): |
a9950fd0 | 2983 | # Action 5 |
5a72ded7 | 2984 | helper.update_trades(market, only="acquire", compute_value="average") |
a9950fd0 | 2985 | |
6ca5a1ec | 2986 | balances = portfolio.BalanceStore.all |
a9950fd0 IB |
2987 | self.assertEqual(portfolio.Amount("ETH", 1 / D("3")), balances["ETH"].total) |
2988 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | |
2989 | self.assertEqual(portfolio.Amount("BTC", D("0.134")), balances["BTC"].total) | |
2990 | self.assertEqual(portfolio.Amount("XVG", 0), balances["XVG"].total) | |
2991 | ||
2992 | ||
5a72ded7 IB |
2993 | trades = portfolio.TradeStore.all |
2994 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | |
2995 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | |
2996 | self.assertEqual("dispose", trades[0].action) | |
a9950fd0 | 2997 | |
5a72ded7 IB |
2998 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) |
2999 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | |
3000 | self.assertEqual("acquire", trades[1].action) | |
a9950fd0 IB |
3001 | |
3002 | self.assertNotIn("BTC", trades) | |
3003 | ||
5a72ded7 IB |
3004 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) |
3005 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | |
3006 | self.assertEqual("dispose", trades[2].action) | |
a9950fd0 | 3007 | |
5a72ded7 IB |
3008 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) |
3009 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | |
3010 | self.assertEqual("acquire", trades[3].action) | |
350ed24d | 3011 | |
5a72ded7 IB |
3012 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) |
3013 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | |
3014 | self.assertEqual("acquire", trades[4].action) | |
a9950fd0 | 3015 | |
5a72ded7 IB |
3016 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) |
3017 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | |
3018 | self.assertEqual("acquire", trades[5].action) | |
a9950fd0 IB |
3019 | |
3020 | # Action 6 | |
5a72ded7 | 3021 | portfolio.TradeStore.prepare_orders(only="acquire", compute_value=lambda x, y: x["ask"]) |
b83d4897 | 3022 | |
5a72ded7 | 3023 | all_orders = portfolio.TradeStore.all_orders(state="pending") |
350ed24d IB |
3024 | self.assertEqual(4, len(all_orders)) |
3025 | self.assertEqual(portfolio.Amount("ETC", D("12.83333333")), round(all_orders[0].amount)) | |
b83d4897 IB |
3026 | self.assertEqual(D("0.003"), all_orders[0].rate) |
3027 | self.assertEqual("buy", all_orders[0].action) | |
350ed24d | 3028 | self.assertEqual("long", all_orders[0].trade_type) |
b83d4897 | 3029 | |
350ed24d | 3030 | self.assertEqual(portfolio.Amount("BTD", D("1.61666666")), round(all_orders[1].amount)) |
b83d4897 | 3031 | self.assertEqual(D("0.0012"), all_orders[1].rate) |
350ed24d IB |
3032 | self.assertEqual("sell", all_orders[1].action) |
3033 | self.assertEqual("short", all_orders[1].trade_type) | |
3034 | ||
3035 | diff = portfolio.Amount("B2X", D("19.4")/3) - all_orders[2].amount | |
3036 | self.assertAlmostEqual(0, diff.value) | |
3037 | self.assertEqual(D("0.0012"), all_orders[2].rate) | |
3038 | self.assertEqual("buy", all_orders[2].action) | |
3039 | self.assertEqual("long", all_orders[2].trade_type) | |
3040 | ||
3041 | self.assertEqual(portfolio.Amount("BTC", D("0.0097")), all_orders[3].amount) | |
3042 | self.assertEqual(D("16000"), all_orders[3].rate) | |
3043 | self.assertEqual("sell", all_orders[3].action) | |
3044 | self.assertEqual("long", all_orders[3].trade_type) | |
b83d4897 | 3045 | |
006a2084 IB |
3046 | # Action 6b |
3047 | # TODO: | |
3048 | # Move balances to margin | |
3049 | ||
350ed24d IB |
3050 | # Action 7 |
3051 | # TODO | |
6ca5a1ec | 3052 | # portfolio.TradeStore.run_orders() |
a9950fd0 IB |
3053 | |
3054 | with mock.patch.object(portfolio.time, "sleep") as sleep: | |
350ed24d | 3055 | # Action 8 |
6ca5a1ec | 3056 | helper.follow_orders(verbose=False) |
a9950fd0 IB |
3057 | |
3058 | sleep.assert_called_with(30) | |
3059 | ||
dd359bc0 IB |
3060 | if __name__ == '__main__': |
3061 | unittest.main() |