diff options
-rw-r--r-- | Makefile | 8 | ||||
-rw-r--r-- | test.py | 5223 | ||||
-rw-r--r-- | tests/helper.py | 59 | ||||
-rw-r--r-- | tests/test_acceptance.py | 280 | ||||
-rw-r--r-- | tests/test_ccxt_wrapper.py | 477 | ||||
-rw-r--r-- | tests/test_main.py | 290 | ||||
-rw-r--r-- | tests/test_market.py | 900 | ||||
-rw-r--r-- | tests/test_portfolio.py | 2036 | ||||
-rw-r--r-- | tests/test_store.py | 1203 |
9 files changed, 5255 insertions, 5221 deletions
@@ -15,6 +15,8 @@ release_version = $(shell git describe --tags --always) | |||
15 | release_file = trader_$(release_version).tar.gz | 15 | release_file = trader_$(release_version).tar.gz |
16 | folder = ~/.no_backup/projets/git.immae.eu/releases/cryptoportfolio/trader | 16 | folder = ~/.no_backup/projets/git.immae.eu/releases/cryptoportfolio/trader |
17 | 17 | ||
18 | coverage_omit = "tests/*.py,test.py" | ||
19 | |||
18 | build_release: | 20 | build_release: |
19 | git archive HEAD -o $(release_file) | 21 | git archive HEAD -o $(release_file) |
20 | mv $(release_file) $(folder) | 22 | mv $(release_file) $(folder) |
@@ -25,7 +27,7 @@ build_release: | |||
25 | @echo "=================================" | 27 | @echo "=================================" |
26 | 28 | ||
27 | test_coverage_unit: | 29 | test_coverage_unit: |
28 | coverage run --source=. --omit=test.py test.py --onlyunit | 30 | coverage run --source=. --omit="$(coverage_omit)" test.py --onlyunit |
29 | coverage report -m | 31 | coverage report -m |
30 | 32 | ||
31 | test_coverage_unit_html: test_coverage_unit | 33 | test_coverage_unit_html: test_coverage_unit |
@@ -34,7 +36,7 @@ test_coverage_unit_html: test_coverage_unit | |||
34 | @echo "coverage in https://www.immae.eu/htmlcov" | 36 | @echo "coverage in https://www.immae.eu/htmlcov" |
35 | 37 | ||
36 | test_coverage_acceptance: | 38 | test_coverage_acceptance: |
37 | coverage run --source=. --omit=test.py test.py --onlyacceptance | 39 | coverage run --source=. --omit="$(coverage_omit)" test.py --onlyacceptance |
38 | coverage report -m | 40 | coverage report -m |
39 | 41 | ||
40 | test_coverage_acceptance_html: test_coverage_acceptance | 42 | test_coverage_acceptance_html: test_coverage_acceptance |
@@ -43,7 +45,7 @@ test_coverage_acceptance_html: test_coverage_acceptance | |||
43 | @echo "coverage in https://www.immae.eu/htmlcov" | 45 | @echo "coverage in https://www.immae.eu/htmlcov" |
44 | 46 | ||
45 | test_coverage_all: | 47 | test_coverage_all: |
46 | coverage run --source=. --omit=test.py test.py | 48 | coverage run --source=. --omit="$(coverage_omit)" test.py |
47 | coverage report -m | 49 | coverage report -m |
48 | 50 | ||
49 | test_coverage_all_html: test_coverage_all | 51 | test_coverage_all_html: test_coverage_all |
@@ -1,5223 +1,10 @@ | |||
1 | import sys | ||
2 | import portfolio | ||
3 | import unittest | 1 | import unittest |
4 | import datetime | ||
5 | from decimal import Decimal as D | ||
6 | from unittest import mock | ||
7 | import requests | ||
8 | import requests_mock | ||
9 | from io import StringIO | ||
10 | import threading | ||
11 | import portfolio, market, main, store | ||
12 | 2 | ||
13 | limits = ["acceptance", "unit"] | 3 | from tests.test_ccxt_wrapper import * |
14 | for test_type in limits: | 4 | from tests.test_main import * |
15 | if "--no{}".format(test_type) in sys.argv: | 5 | from tests.test_market import * |
16 | sys.argv.remove("--no{}".format(test_type)) | 6 | from tests.test_store import * |
17 | limits.remove(test_type) | 7 | from tests.test_portfolio import * |
18 | if "--only{}".format(test_type) in sys.argv: | ||
19 | sys.argv.remove("--only{}".format(test_type)) | ||
20 | limits = [test_type] | ||
21 | break | ||
22 | |||
23 | class WebMockTestCase(unittest.TestCase): | ||
24 | import time | ||
25 | |||
26 | def market_args(self, debug=False, quiet=False, report_path=None, **kwargs): | ||
27 | return main.configargparse.Namespace(report_path=report_path, | ||
28 | debug=debug, quiet=quiet, **kwargs) | ||
29 | |||
30 | def setUp(self): | ||
31 | super().setUp() | ||
32 | self.wm = requests_mock.Mocker() | ||
33 | self.wm.start() | ||
34 | |||
35 | # market | ||
36 | self.m = mock.Mock(name="Market", spec=market.Market) | ||
37 | self.m.debug = False | ||
38 | |||
39 | self.patchers = [ | ||
40 | mock.patch.multiple(market.Portfolio, | ||
41 | data=store.LockedVar(None), | ||
42 | liquidities=store.LockedVar({}), | ||
43 | last_date=store.LockedVar(None), | ||
44 | report=mock.Mock(), | ||
45 | worker=None, | ||
46 | worker_notify=None, | ||
47 | worker_started=False, | ||
48 | callback=None), | ||
49 | mock.patch.multiple(portfolio.Computation, | ||
50 | computations=portfolio.Computation.computations), | ||
51 | ] | ||
52 | for patcher in self.patchers: | ||
53 | patcher.start() | ||
54 | |||
55 | def tearDown(self): | ||
56 | for patcher in self.patchers: | ||
57 | patcher.stop() | ||
58 | self.wm.stop() | ||
59 | super().tearDown() | ||
60 | |||
61 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
62 | class poloniexETest(unittest.TestCase): | ||
63 | def setUp(self): | ||
64 | super().setUp() | ||
65 | self.wm = requests_mock.Mocker() | ||
66 | self.wm.start() | ||
67 | |||
68 | self.s = market.ccxt.poloniexE() | ||
69 | |||
70 | def tearDown(self): | ||
71 | self.wm.stop() | ||
72 | super().tearDown() | ||
73 | |||
74 | def test__init(self): | ||
75 | with self.subTest("Nominal case"), \ | ||
76 | mock.patch("market.ccxt.poloniexE.session") as session: | ||
77 | session.request.return_value = "response" | ||
78 | ccxt = market.ccxt.poloniexE() | ||
79 | ccxt._market = mock.Mock | ||
80 | ccxt._market.report = mock.Mock() | ||
81 | |||
82 | ccxt.session.request("GET", "URL", data="data", | ||
83 | headers="headers") | ||
84 | ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data', | ||
85 | 'headers', 'response') | ||
86 | |||
87 | with self.subTest("Raising"),\ | ||
88 | mock.patch("market.ccxt.poloniexE.session") as session: | ||
89 | session.request.side_effect = market.ccxt.RequestException("Boo") | ||
90 | |||
91 | ccxt = market.ccxt.poloniexE() | ||
92 | ccxt._market = mock.Mock | ||
93 | ccxt._market.report = mock.Mock() | ||
94 | |||
95 | with self.assertRaises(market.ccxt.RequestException, msg="Boo") as cm: | ||
96 | ccxt.session.request("GET", "URL", data="data", | ||
97 | headers="headers") | ||
98 | ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data', | ||
99 | 'headers', cm.exception) | ||
100 | |||
101 | |||
102 | def test_nanoseconds(self): | ||
103 | with mock.patch.object(market.ccxt.time, "time") as time: | ||
104 | time.return_value = 123456.7890123456 | ||
105 | self.assertEqual(123456789012345, self.s.nanoseconds()) | ||
106 | |||
107 | def test_nonce(self): | ||
108 | with mock.patch.object(market.ccxt.time, "time") as time: | ||
109 | time.return_value = 123456.7890123456 | ||
110 | self.assertEqual(123456789012345, self.s.nonce()) | ||
111 | |||
112 | def test_request(self): | ||
113 | with mock.patch.object(market.ccxt.poloniex, "request") as request,\ | ||
114 | mock.patch("market.ccxt.retry_call") as retry_call: | ||
115 | with self.subTest(wrapped=True): | ||
116 | with self.subTest(desc="public"): | ||
117 | self.s.request("foo") | ||
118 | retry_call.assert_called_with(request, | ||
119 | delay=1, tries=10, fargs=["foo"], | ||
120 | fkwargs={'api': 'public', 'method': 'GET', 'params': {}, 'headers': None, 'body': None}, | ||
121 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
122 | request.assert_not_called() | ||
123 | |||
124 | with self.subTest(desc="private GET"): | ||
125 | self.s.request("foo", api="private") | ||
126 | retry_call.assert_called_with(request, | ||
127 | delay=1, tries=10, fargs=["foo"], | ||
128 | fkwargs={'api': 'private', 'method': 'GET', 'params': {}, 'headers': None, 'body': None}, | ||
129 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
130 | request.assert_not_called() | ||
131 | |||
132 | with self.subTest(desc="private POST regexp"): | ||
133 | self.s.request("returnFoo", api="private", method="POST") | ||
134 | retry_call.assert_called_with(request, | ||
135 | delay=1, tries=10, fargs=["returnFoo"], | ||
136 | fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None}, | ||
137 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
138 | request.assert_not_called() | ||
139 | |||
140 | with self.subTest(desc="private POST non-regexp"): | ||
141 | self.s.request("getMarginPosition", api="private", method="POST") | ||
142 | retry_call.assert_called_with(request, | ||
143 | delay=1, tries=10, fargs=["getMarginPosition"], | ||
144 | fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None}, | ||
145 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
146 | request.assert_not_called() | ||
147 | retry_call.reset_mock() | ||
148 | request.reset_mock() | ||
149 | with self.subTest(wrapped=False): | ||
150 | with self.subTest(desc="private POST non-matching regexp"): | ||
151 | self.s.request("marginBuy", api="private", method="POST") | ||
152 | request.assert_called_with("marginBuy", | ||
153 | api="private", method="POST", params={}, | ||
154 | headers=None, body=None) | ||
155 | retry_call.assert_not_called() | ||
156 | |||
157 | with self.subTest(desc="private POST non-matching non-regexp"): | ||
158 | self.s.request("closeMarginPositionOther", api="private", method="POST") | ||
159 | request.assert_called_with("closeMarginPositionOther", | ||
160 | api="private", method="POST", params={}, | ||
161 | headers=None, body=None) | ||
162 | retry_call.assert_not_called() | ||
163 | |||
164 | def test_order_precision(self): | ||
165 | self.assertEqual(8, self.s.order_precision("FOO")) | ||
166 | |||
167 | def test_transfer_balance(self): | ||
168 | with self.subTest(success=True),\ | ||
169 | mock.patch.object(self.s, "privatePostTransferBalance") as t: | ||
170 | t.return_value = { "success": 1 } | ||
171 | result = self.s.transfer_balance("FOO", 12, "exchange", "margin") | ||
172 | t.assert_called_once_with({ | ||
173 | "currency": "FOO", | ||
174 | "amount": 12, | ||
175 | "fromAccount": "exchange", | ||
176 | "toAccount": "margin", | ||
177 | "confirmed": 1 | ||
178 | }) | ||
179 | self.assertTrue(result) | ||
180 | |||
181 | with self.subTest(success=False),\ | ||
182 | mock.patch.object(self.s, "privatePostTransferBalance") as t: | ||
183 | t.return_value = { "success": 0 } | ||
184 | self.assertFalse(self.s.transfer_balance("FOO", 12, "exchange", "margin")) | ||
185 | |||
186 | def test_close_margin_position(self): | ||
187 | with mock.patch.object(self.s, "privatePostCloseMarginPosition") as c: | ||
188 | self.s.close_margin_position("FOO", "BAR") | ||
189 | c.assert_called_with({"currencyPair": "BAR_FOO"}) | ||
190 | |||
191 | def test_tradable_balances(self): | ||
192 | with mock.patch.object(self.s, "privatePostReturnTradableBalances") as r: | ||
193 | r.return_value = { | ||
194 | "FOO": { "exchange": "12.1234", "margin": "0.0123" }, | ||
195 | "BAR": { "exchange": "1", "margin": "0" }, | ||
196 | } | ||
197 | balances = self.s.tradable_balances() | ||
198 | self.assertEqual(["FOO", "BAR"], list(balances.keys())) | ||
199 | self.assertEqual(["exchange", "margin"], list(balances["FOO"].keys())) | ||
200 | self.assertEqual(D("12.1234"), balances["FOO"]["exchange"]) | ||
201 | self.assertEqual(["exchange", "margin"], list(balances["BAR"].keys())) | ||
202 | |||
203 | def test_margin_summary(self): | ||
204 | with mock.patch.object(self.s, "privatePostReturnMarginAccountSummary") as r: | ||
205 | r.return_value = { | ||
206 | "currentMargin": "1.49680968", | ||
207 | "lendingFees": "0.0000001", | ||
208 | "pl": "0.00008254", | ||
209 | "totalBorrowedValue": "0.00673602", | ||
210 | "totalValue": "0.01000000", | ||
211 | "netValue": "0.01008254", | ||
212 | } | ||
213 | expected = { | ||
214 | 'current_margin': D('1.49680968'), | ||
215 | 'gains': D('0.00008254'), | ||
216 | 'lending_fees': D('0.0000001'), | ||
217 | 'total': D('0.01000000'), | ||
218 | 'total_borrowed': D('0.00673602') | ||
219 | } | ||
220 | self.assertEqual(expected, self.s.margin_summary()) | ||
221 | |||
222 | def test_create_order(self): | ||
223 | with mock.patch.object(self.s, "create_exchange_order") as exchange,\ | ||
224 | mock.patch.object(self.s, "create_margin_order") as margin: | ||
225 | with self.subTest(account="unspecified"): | ||
226 | self.s.create_order("symbol", "type", "side", "amount", price="price", lending_rate="lending_rate", params="params") | ||
227 | exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
228 | margin.assert_not_called() | ||
229 | exchange.reset_mock() | ||
230 | margin.reset_mock() | ||
231 | |||
232 | with self.subTest(account="exchange"): | ||
233 | self.s.create_order("symbol", "type", "side", "amount", account="exchange", price="price", lending_rate="lending_rate", params="params") | ||
234 | exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
235 | margin.assert_not_called() | ||
236 | exchange.reset_mock() | ||
237 | margin.reset_mock() | ||
238 | |||
239 | with self.subTest(account="margin"): | ||
240 | self.s.create_order("symbol", "type", "side", "amount", account="margin", price="price", lending_rate="lending_rate", params="params") | ||
241 | margin.assert_called_once_with("symbol", "type", "side", "amount", lending_rate="lending_rate", price="price", params="params") | ||
242 | exchange.assert_not_called() | ||
243 | exchange.reset_mock() | ||
244 | margin.reset_mock() | ||
245 | |||
246 | with self.subTest(account="unknown"), self.assertRaises(NotImplementedError): | ||
247 | self.s.create_order("symbol", "type", "side", "amount", account="unknown") | ||
248 | |||
249 | def test_parse_ticker(self): | ||
250 | ticker = { | ||
251 | "high24hr": "12", | ||
252 | "low24hr": "10", | ||
253 | "highestBid": "10.5", | ||
254 | "lowestAsk": "11.5", | ||
255 | "last": "11", | ||
256 | "percentChange": "0.1", | ||
257 | "quoteVolume": "10", | ||
258 | "baseVolume": "20" | ||
259 | } | ||
260 | market = { | ||
261 | "symbol": "BTC/ETC" | ||
262 | } | ||
263 | with mock.patch.object(self.s, "milliseconds") as ms: | ||
264 | ms.return_value = 1520292715123 | ||
265 | result = self.s.parse_ticker(ticker, market) | ||
266 | |||
267 | expected = { | ||
268 | "symbol": "BTC/ETC", | ||
269 | "timestamp": 1520292715123, | ||
270 | "datetime": "2018-03-05T23:31:55.123Z", | ||
271 | "high": D("12"), | ||
272 | "low": D("10"), | ||
273 | "bid": D("10.5"), | ||
274 | "ask": D("11.5"), | ||
275 | "vwap": None, | ||
276 | "open": None, | ||
277 | "close": None, | ||
278 | "first": None, | ||
279 | "last": D("11"), | ||
280 | "change": D("0.1"), | ||
281 | "percentage": None, | ||
282 | "average": None, | ||
283 | "baseVolume": D("10"), | ||
284 | "quoteVolume": D("20"), | ||
285 | "info": ticker | ||
286 | } | ||
287 | self.assertEqual(expected, result) | ||
288 | |||
289 | def test_fetch_margin_balance(self): | ||
290 | with mock.patch.object(self.s, "privatePostGetMarginPosition") as get_margin_position: | ||
291 | get_margin_position.return_value = { | ||
292 | "BTC_DASH": { | ||
293 | "amount": "-0.1", | ||
294 | "basePrice": "0.06818560", | ||
295 | "lendingFees": "0.00000001", | ||
296 | "liquidationPrice": "0.15107132", | ||
297 | "pl": "-0.00000371", | ||
298 | "total": "0.00681856", | ||
299 | "type": "short" | ||
300 | }, | ||
301 | "BTC_ETC": { | ||
302 | "amount": "-0.6", | ||
303 | "basePrice": "0.1", | ||
304 | "lendingFees": "0.00000001", | ||
305 | "liquidationPrice": "0.6", | ||
306 | "pl": "0.00000371", | ||
307 | "total": "0.06", | ||
308 | "type": "short" | ||
309 | }, | ||
310 | "BTC_ETH": { | ||
311 | "amount": "0", | ||
312 | "basePrice": "0", | ||
313 | "lendingFees": "0", | ||
314 | "liquidationPrice": "-1", | ||
315 | "pl": "0", | ||
316 | "total": "0", | ||
317 | "type": "none" | ||
318 | } | ||
319 | } | ||
320 | balances = self.s.fetch_margin_balance() | ||
321 | self.assertEqual(2, len(balances)) | ||
322 | expected = { | ||
323 | "DASH": { | ||
324 | "amount": D("-0.1"), | ||
325 | "borrowedPrice": D("0.06818560"), | ||
326 | "lendingFees": D("1E-8"), | ||
327 | "pl": D("-0.00000371"), | ||
328 | "liquidationPrice": D("0.15107132"), | ||
329 | "type": "short", | ||
330 | "total": D("0.00681856"), | ||
331 | "baseCurrency": "BTC" | ||
332 | }, | ||
333 | "ETC": { | ||
334 | "amount": D("-0.6"), | ||
335 | "borrowedPrice": D("0.1"), | ||
336 | "lendingFees": D("1E-8"), | ||
337 | "pl": D("0.00000371"), | ||
338 | "liquidationPrice": D("0.6"), | ||
339 | "type": "short", | ||
340 | "total": D("0.06"), | ||
341 | "baseCurrency": "BTC" | ||
342 | } | ||
343 | } | ||
344 | self.assertEqual(expected, balances) | ||
345 | |||
346 | def test_sum(self): | ||
347 | self.assertEqual(D("1.1"), self.s.sum(D("1"), D("0.1"))) | ||
348 | |||
349 | def test_fetch_balance(self): | ||
350 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
351 | mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balances,\ | ||
352 | mock.patch.object(self.s, "common_currency_code") as ccc: | ||
353 | ccc.side_effect = ["ETH", "BTC", "DASH"] | ||
354 | balances.return_value = { | ||
355 | "ETH": { | ||
356 | "available": "10", | ||
357 | "onOrders": "1", | ||
358 | }, | ||
359 | "BTC": { | ||
360 | "available": "1", | ||
361 | "onOrders": "0", | ||
362 | }, | ||
363 | "DASH": { | ||
364 | "available": "0", | ||
365 | "onOrders": "3" | ||
366 | } | ||
367 | } | ||
368 | |||
369 | expected = { | ||
370 | "info": { | ||
371 | "ETH": {"available": "10", "onOrders": "1"}, | ||
372 | "BTC": {"available": "1", "onOrders": "0"}, | ||
373 | "DASH": {"available": "0", "onOrders": "3"} | ||
374 | }, | ||
375 | "ETH": {"free": D("10"), "used": D("1"), "total": D("11")}, | ||
376 | "BTC": {"free": D("1"), "used": D("0"), "total": D("1")}, | ||
377 | "DASH": {"free": D("0"), "used": D("3"), "total": D("3")}, | ||
378 | "free": {"ETH": D("10"), "BTC": D("1"), "DASH": D("0")}, | ||
379 | "used": {"ETH": D("1"), "BTC": D("0"), "DASH": D("3")}, | ||
380 | "total": {"ETH": D("11"), "BTC": D("1"), "DASH": D("3")} | ||
381 | } | ||
382 | result = self.s.fetch_balance() | ||
383 | load_markets.assert_called_once() | ||
384 | self.assertEqual(expected, result) | ||
385 | |||
386 | def test_fetch_balance_per_type(self): | ||
387 | with mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balances: | ||
388 | balances.return_value = { | ||
389 | "exchange": { | ||
390 | "BLK": "159.83673869", | ||
391 | "BTC": "0.00005959", | ||
392 | "USDT": "0.00002625", | ||
393 | "XMR": "0.18719303" | ||
394 | }, | ||
395 | "margin": { | ||
396 | "BTC": "0.03019227" | ||
397 | } | ||
398 | } | ||
399 | expected = { | ||
400 | "info": { | ||
401 | "exchange": { | ||
402 | "BLK": "159.83673869", | ||
403 | "BTC": "0.00005959", | ||
404 | "USDT": "0.00002625", | ||
405 | "XMR": "0.18719303" | ||
406 | }, | ||
407 | "margin": { | ||
408 | "BTC": "0.03019227" | ||
409 | } | ||
410 | }, | ||
411 | "exchange": { | ||
412 | "BLK": D("159.83673869"), | ||
413 | "BTC": D("0.00005959"), | ||
414 | "USDT": D("0.00002625"), | ||
415 | "XMR": D("0.18719303") | ||
416 | }, | ||
417 | "margin": {"BTC": D("0.03019227")}, | ||
418 | "BLK": {"exchange": D("159.83673869")}, | ||
419 | "BTC": {"exchange": D("0.00005959"), "margin": D("0.03019227")}, | ||
420 | "USDT": {"exchange": D("0.00002625")}, | ||
421 | "XMR": {"exchange": D("0.18719303")} | ||
422 | } | ||
423 | result = self.s.fetch_balance_per_type() | ||
424 | self.assertEqual(expected, result) | ||
425 | |||
426 | def test_fetch_all_balances(self): | ||
427 | import json | ||
428 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
429 | mock.patch.object(self.s, "privatePostGetMarginPosition") as margin_balance,\ | ||
430 | mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balance,\ | ||
431 | mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balance_per_type: | ||
432 | |||
433 | with open("test_samples/poloniexETest.test_fetch_all_balances.1.json") as f: | ||
434 | balance.return_value = json.load(f) | ||
435 | with open("test_samples/poloniexETest.test_fetch_all_balances.2.json") as f: | ||
436 | margin_balance.return_value = json.load(f) | ||
437 | with open("test_samples/poloniexETest.test_fetch_all_balances.3.json") as f: | ||
438 | balance_per_type.return_value = json.load(f) | ||
439 | |||
440 | result = self.s.fetch_all_balances() | ||
441 | expected_doge = { | ||
442 | "total": D("-12779.79821852"), | ||
443 | "exchange_used": D("0E-8"), | ||
444 | "exchange_total": D("0E-8"), | ||
445 | "exchange_free": D("0E-8"), | ||
446 | "margin_available": 0, | ||
447 | "margin_in_position": 0, | ||
448 | "margin_borrowed": D("12779.79821852"), | ||
449 | "margin_total": D("-12779.79821852"), | ||
450 | "margin_pending_gain": 0, | ||
451 | "margin_lending_fees": D("-9E-8"), | ||
452 | "margin_pending_base_gain": D("0.00024059"), | ||
453 | "margin_position_type": "short", | ||
454 | "margin_liquidation_price": D("0.00000246"), | ||
455 | "margin_borrowed_base_price": D("0.00599149"), | ||
456 | "margin_borrowed_base_currency": "BTC" | ||
457 | } | ||
458 | expected_btc = {"total": D("0.05432165"), | ||
459 | "exchange_used": D("0E-8"), | ||
460 | "exchange_total": D("0.00005959"), | ||
461 | "exchange_free": D("0.00005959"), | ||
462 | "margin_available": D("0.03019227"), | ||
463 | "margin_in_position": D("0.02406979"), | ||
464 | "margin_borrowed": 0, | ||
465 | "margin_total": D("0.05426206"), | ||
466 | "margin_pending_gain": D("0.00093955"), | ||
467 | "margin_lending_fees": 0, | ||
468 | "margin_pending_base_gain": 0, | ||
469 | "margin_position_type": None, | ||
470 | "margin_liquidation_price": 0, | ||
471 | "margin_borrowed_base_price": 0, | ||
472 | "margin_borrowed_base_currency": None | ||
473 | } | ||
474 | expected_xmr = {"total": D("0.18719303"), | ||
475 | "exchange_used": D("0E-8"), | ||
476 | "exchange_total": D("0.18719303"), | ||
477 | "exchange_free": D("0.18719303"), | ||
478 | "margin_available": 0, | ||
479 | "margin_in_position": 0, | ||
480 | "margin_borrowed": 0, | ||
481 | "margin_total": 0, | ||
482 | "margin_pending_gain": 0, | ||
483 | "margin_lending_fees": 0, | ||
484 | "margin_pending_base_gain": 0, | ||
485 | "margin_position_type": None, | ||
486 | "margin_liquidation_price": 0, | ||
487 | "margin_borrowed_base_price": 0, | ||
488 | "margin_borrowed_base_currency": None | ||
489 | } | ||
490 | self.assertEqual(expected_xmr, result["XMR"]) | ||
491 | self.assertEqual(expected_doge, result["DOGE"]) | ||
492 | self.assertEqual(expected_btc, result["BTC"]) | ||
493 | |||
494 | def test_create_margin_order(self): | ||
495 | with self.assertRaises(market.ExchangeError): | ||
496 | self.s.create_margin_order("FOO", "market", "buy", "10") | ||
497 | |||
498 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
499 | mock.patch.object(self.s, "privatePostMarginBuy") as margin_buy,\ | ||
500 | mock.patch.object(self.s, "privatePostMarginSell") as margin_sell,\ | ||
501 | mock.patch.object(self.s, "market") as market_mock,\ | ||
502 | mock.patch.object(self.s, "price_to_precision") as ptp,\ | ||
503 | mock.patch.object(self.s, "amount_to_precision") as atp: | ||
504 | |||
505 | margin_buy.return_value = { | ||
506 | "orderNumber": 123 | ||
507 | } | ||
508 | margin_sell.return_value = { | ||
509 | "orderNumber": 456 | ||
510 | } | ||
511 | market_mock.return_value = { "id": "BTC_ETC", "symbol": "BTC_ETC" } | ||
512 | ptp.return_value = D("0.1") | ||
513 | atp.return_value = D("12") | ||
514 | |||
515 | order = self.s.create_margin_order("BTC_ETC", "margin", "buy", "12", price="0.1") | ||
516 | self.assertEqual(123, order["id"]) | ||
517 | margin_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")}) | ||
518 | margin_sell.assert_not_called() | ||
519 | margin_buy.reset_mock() | ||
520 | margin_sell.reset_mock() | ||
521 | |||
522 | order = self.s.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate="0.01", price="0.1") | ||
523 | self.assertEqual(456, order["id"]) | ||
524 | margin_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"}) | ||
525 | margin_buy.assert_not_called() | ||
526 | |||
527 | def test_create_exchange_order(self): | ||
528 | with mock.patch.object(market.ccxt.poloniex, "create_order") as create_order: | ||
529 | self.s.create_order("symbol", "type", "side", "amount", price="price", params="params") | ||
530 | |||
531 | create_order.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
532 | |||
533 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
534 | class NoopLockTest(unittest.TestCase): | ||
535 | def test_with(self): | ||
536 | noop_lock = store.NoopLock() | ||
537 | with noop_lock: | ||
538 | self.assertTrue(True) | ||
539 | |||
540 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
541 | class LockedVar(unittest.TestCase): | ||
542 | |||
543 | def test_values(self): | ||
544 | locked_var = store.LockedVar("Foo") | ||
545 | self.assertIsInstance(locked_var.lock, store.NoopLock) | ||
546 | self.assertEqual("Foo", locked_var.val) | ||
547 | |||
548 | def test_get(self): | ||
549 | with self.subTest(desc="Normal case"): | ||
550 | locked_var = store.LockedVar("Foo") | ||
551 | self.assertEqual("Foo", locked_var.get()) | ||
552 | with self.subTest(desc="Dict"): | ||
553 | locked_var = store.LockedVar({"foo": "bar"}) | ||
554 | self.assertEqual({"foo": "bar"}, locked_var.get()) | ||
555 | self.assertEqual("bar", locked_var.get("foo")) | ||
556 | self.assertIsNone(locked_var.get("other")) | ||
557 | |||
558 | def test_set(self): | ||
559 | locked_var = store.LockedVar("Foo") | ||
560 | locked_var.set("Bar") | ||
561 | self.assertEqual("Bar", locked_var.get()) | ||
562 | |||
563 | def test__getattr(self): | ||
564 | dummy = type('Dummy', (object,), {})() | ||
565 | dummy.attribute = "Hey" | ||
566 | |||
567 | locked_var = store.LockedVar(dummy) | ||
568 | self.assertEqual("Hey", locked_var.attribute) | ||
569 | with self.assertRaises(AttributeError): | ||
570 | locked_var.other | ||
571 | |||
572 | def test_start_lock(self): | ||
573 | locked_var = store.LockedVar("Foo") | ||
574 | locked_var.start_lock() | ||
575 | self.assertEqual("lock", locked_var.lock.__class__.__name__) | ||
576 | |||
577 | thread1 = threading.Thread(target=locked_var.set, args=["Bar1"]) | ||
578 | thread2 = threading.Thread(target=locked_var.set, args=["Bar2"]) | ||
579 | thread3 = threading.Thread(target=locked_var.set, args=["Bar3"]) | ||
580 | |||
581 | with locked_var.lock: | ||
582 | thread1.start() | ||
583 | thread2.start() | ||
584 | thread3.start() | ||
585 | |||
586 | self.assertEqual("Foo", locked_var.val) | ||
587 | thread1.join() | ||
588 | thread2.join() | ||
589 | thread3.join() | ||
590 | self.assertEqual("Bar", locked_var.get()[0:3]) | ||
591 | |||
592 | def test_wait_for_notification(self): | ||
593 | with self.assertRaises(RuntimeError): | ||
594 | store.Portfolio.wait_for_notification() | ||
595 | |||
596 | with mock.patch.object(store.Portfolio, "get_cryptoportfolio") as get,\ | ||
597 | mock.patch.object(store.Portfolio, "report") as report,\ | ||
598 | mock.patch.object(store.time, "sleep") as sleep: | ||
599 | store.Portfolio.start_worker(poll=3) | ||
600 | |||
601 | store.Portfolio.worker_notify.set() | ||
602 | |||
603 | store.Portfolio.callback.wait() | ||
604 | |||
605 | report.print_log.assert_called_once_with("Fetching cryptoportfolio") | ||
606 | get.assert_called_once_with(refetch=True) | ||
607 | sleep.assert_called_once_with(3) | ||
608 | self.assertFalse(store.Portfolio.worker_notify.is_set()) | ||
609 | self.assertTrue(store.Portfolio.worker.is_alive()) | ||
610 | |||
611 | store.Portfolio.callback.clear() | ||
612 | store.Portfolio.worker_started = False | ||
613 | store.Portfolio.worker_notify.set() | ||
614 | store.Portfolio.callback.wait() | ||
615 | |||
616 | self.assertFalse(store.Portfolio.worker.is_alive()) | ||
617 | |||
618 | def test_notify_and_wait(self): | ||
619 | with mock.patch.object(store.Portfolio, "callback") as callback,\ | ||
620 | mock.patch.object(store.Portfolio, "worker_notify") as worker_notify: | ||
621 | store.Portfolio.notify_and_wait() | ||
622 | callback.clear.assert_called_once_with() | ||
623 | worker_notify.set.assert_called_once_with() | ||
624 | callback.wait.assert_called_once_with() | ||
625 | |||
626 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
627 | class PortfolioTest(WebMockTestCase): | ||
628 | def setUp(self): | ||
629 | super().setUp() | ||
630 | |||
631 | with open("test_samples/test_portfolio.json") as example: | ||
632 | self.json_response = example.read() | ||
633 | |||
634 | self.wm.get(market.Portfolio.URL, text=self.json_response) | ||
635 | |||
636 | @mock.patch.object(market.Portfolio, "parse_cryptoportfolio") | ||
637 | def test_get_cryptoportfolio(self, parse_cryptoportfolio): | ||
638 | with self.subTest(parallel=False): | ||
639 | self.wm.get(market.Portfolio.URL, [ | ||
640 | {"text":'{ "foo": "bar" }', "status_code": 200}, | ||
641 | {"text": "System Error", "status_code": 500}, | ||
642 | {"exc": requests.exceptions.ConnectTimeout}, | ||
643 | ]) | ||
644 | market.Portfolio.get_cryptoportfolio() | ||
645 | self.assertIn("foo", market.Portfolio.data.get()) | ||
646 | self.assertEqual("bar", market.Portfolio.data.get()["foo"]) | ||
647 | self.assertTrue(self.wm.called) | ||
648 | self.assertEqual(1, self.wm.call_count) | ||
649 | market.Portfolio.report.log_error.assert_not_called() | ||
650 | market.Portfolio.report.log_http_request.assert_called_once() | ||
651 | parse_cryptoportfolio.assert_called_once_with() | ||
652 | market.Portfolio.report.log_http_request.reset_mock() | ||
653 | parse_cryptoportfolio.reset_mock() | ||
654 | market.Portfolio.data = store.LockedVar(None) | ||
655 | |||
656 | market.Portfolio.get_cryptoportfolio() | ||
657 | self.assertIsNone(market.Portfolio.data.get()) | ||
658 | self.assertEqual(2, self.wm.call_count) | ||
659 | parse_cryptoportfolio.assert_not_called() | ||
660 | market.Portfolio.report.log_error.assert_not_called() | ||
661 | market.Portfolio.report.log_http_request.assert_called_once() | ||
662 | market.Portfolio.report.log_http_request.reset_mock() | ||
663 | parse_cryptoportfolio.reset_mock() | ||
664 | |||
665 | market.Portfolio.data = store.LockedVar("Foo") | ||
666 | market.Portfolio.get_cryptoportfolio() | ||
667 | self.assertEqual(2, self.wm.call_count) | ||
668 | parse_cryptoportfolio.assert_not_called() | ||
669 | |||
670 | market.Portfolio.get_cryptoportfolio(refetch=True) | ||
671 | self.assertEqual("Foo", market.Portfolio.data.get()) | ||
672 | self.assertEqual(3, self.wm.call_count) | ||
673 | market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio", | ||
674 | exception=mock.ANY) | ||
675 | market.Portfolio.report.log_http_request.assert_not_called() | ||
676 | with self.subTest(parallel=True): | ||
677 | with mock.patch.object(market.Portfolio, "is_worker_thread") as is_worker,\ | ||
678 | mock.patch.object(market.Portfolio, "notify_and_wait") as notify: | ||
679 | with self.subTest(worker=True): | ||
680 | market.Portfolio.data = store.LockedVar(None) | ||
681 | market.Portfolio.worker = mock.Mock() | ||
682 | is_worker.return_value = True | ||
683 | self.wm.get(market.Portfolio.URL, [ | ||
684 | {"text":'{ "foo": "bar" }', "status_code": 200}, | ||
685 | ]) | ||
686 | market.Portfolio.get_cryptoportfolio() | ||
687 | self.assertIn("foo", market.Portfolio.data.get()) | ||
688 | parse_cryptoportfolio.reset_mock() | ||
689 | with self.subTest(worker=False): | ||
690 | market.Portfolio.data = store.LockedVar(None) | ||
691 | market.Portfolio.worker = mock.Mock() | ||
692 | is_worker.return_value = False | ||
693 | market.Portfolio.get_cryptoportfolio() | ||
694 | notify.assert_called_once_with() | ||
695 | parse_cryptoportfolio.assert_not_called() | ||
696 | |||
697 | def test_parse_cryptoportfolio(self): | ||
698 | with self.subTest(description="Normal case"): | ||
699 | market.Portfolio.data = store.LockedVar(store.json.loads( | ||
700 | self.json_response, parse_int=D, parse_float=D)) | ||
701 | market.Portfolio.parse_cryptoportfolio() | ||
702 | |||
703 | self.assertListEqual( | ||
704 | ["medium", "high"], | ||
705 | list(market.Portfolio.liquidities.get().keys())) | ||
706 | |||
707 | liquidities = market.Portfolio.liquidities.get() | ||
708 | self.assertEqual(10, len(liquidities["medium"].keys())) | ||
709 | self.assertEqual(10, len(liquidities["high"].keys())) | ||
710 | |||
711 | expected = { | ||
712 | 'BTC': (D("0.2857"), "long"), | ||
713 | 'DGB': (D("0.1015"), "long"), | ||
714 | 'DOGE': (D("0.1805"), "long"), | ||
715 | 'SC': (D("0.0623"), "long"), | ||
716 | 'ZEC': (D("0.3701"), "long"), | ||
717 | } | ||
718 | date = portfolio.datetime(2018, 1, 8) | ||
719 | self.assertDictEqual(expected, liquidities["high"][date]) | ||
720 | |||
721 | expected = { | ||
722 | 'BTC': (D("1.1102e-16"), "long"), | ||
723 | 'ETC': (D("0.1"), "long"), | ||
724 | 'FCT': (D("0.1"), "long"), | ||
725 | 'GAS': (D("0.1"), "long"), | ||
726 | 'NAV': (D("0.1"), "long"), | ||
727 | 'OMG': (D("0.1"), "long"), | ||
728 | 'OMNI': (D("0.1"), "long"), | ||
729 | 'PPC': (D("0.1"), "long"), | ||
730 | 'RIC': (D("0.1"), "long"), | ||
731 | 'VIA': (D("0.1"), "long"), | ||
732 | 'XCP': (D("0.1"), "long"), | ||
733 | } | ||
734 | self.assertDictEqual(expected, liquidities["medium"][date]) | ||
735 | self.assertEqual(portfolio.datetime(2018, 1, 15), market.Portfolio.last_date.get()) | ||
736 | |||
737 | with self.subTest(description="Missing weight"): | ||
738 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | ||
739 | del(data["portfolio_2"]["weights"]) | ||
740 | market.Portfolio.data = store.LockedVar(data) | ||
741 | |||
742 | market.Portfolio.parse_cryptoportfolio() | ||
743 | self.assertListEqual( | ||
744 | ["medium", "high"], | ||
745 | list(market.Portfolio.liquidities.get().keys())) | ||
746 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | ||
747 | |||
748 | with self.subTest(description="All missing weights"): | ||
749 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | ||
750 | del(data["portfolio_1"]["weights"]) | ||
751 | del(data["portfolio_2"]["weights"]) | ||
752 | market.Portfolio.data = store.LockedVar(data) | ||
753 | |||
754 | market.Portfolio.parse_cryptoportfolio() | ||
755 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | ||
756 | self.assertEqual({}, market.Portfolio.liquidities.get("high")) | ||
757 | self.assertEqual(datetime.datetime(1,1,1), market.Portfolio.last_date.get()) | ||
758 | |||
759 | |||
760 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | ||
761 | def test_repartition(self, get_cryptoportfolio): | ||
762 | market.Portfolio.liquidities = store.LockedVar({ | ||
763 | "medium": { | ||
764 | "2018-03-01": "medium_2018-03-01", | ||
765 | "2018-03-08": "medium_2018-03-08", | ||
766 | }, | ||
767 | "high": { | ||
768 | "2018-03-01": "high_2018-03-01", | ||
769 | "2018-03-08": "high_2018-03-08", | ||
770 | } | ||
771 | }) | ||
772 | market.Portfolio.last_date = store.LockedVar("2018-03-08") | ||
773 | |||
774 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition()) | ||
775 | get_cryptoportfolio.assert_called_once_with() | ||
776 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition(liquidity="medium")) | ||
777 | self.assertEqual("high_2018-03-08", market.Portfolio.repartition(liquidity="high")) | ||
778 | |||
779 | @mock.patch.object(market.time, "sleep") | ||
780 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | ||
781 | def test_wait_for_recent(self, get_cryptoportfolio, sleep): | ||
782 | self.call_count = 0 | ||
783 | def _get(refetch=False): | ||
784 | if self.call_count != 0: | ||
785 | self.assertTrue(refetch) | ||
786 | else: | ||
787 | self.assertFalse(refetch) | ||
788 | self.call_count += 1 | ||
789 | market.Portfolio.last_date = store.LockedVar(store.datetime.now()\ | ||
790 | - store.timedelta(10)\ | ||
791 | + store.timedelta(self.call_count)) | ||
792 | get_cryptoportfolio.side_effect = _get | ||
793 | |||
794 | market.Portfolio.wait_for_recent() | ||
795 | sleep.assert_called_with(30) | ||
796 | self.assertEqual(6, sleep.call_count) | ||
797 | self.assertEqual(7, get_cryptoportfolio.call_count) | ||
798 | market.Portfolio.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio") | ||
799 | |||
800 | sleep.reset_mock() | ||
801 | get_cryptoportfolio.reset_mock() | ||
802 | market.Portfolio.last_date = store.LockedVar(None) | ||
803 | self.call_count = 0 | ||
804 | market.Portfolio.wait_for_recent(delta=15) | ||
805 | sleep.assert_not_called() | ||
806 | self.assertEqual(1, get_cryptoportfolio.call_count) | ||
807 | |||
808 | sleep.reset_mock() | ||
809 | get_cryptoportfolio.reset_mock() | ||
810 | market.Portfolio.last_date = store.LockedVar(None) | ||
811 | self.call_count = 0 | ||
812 | market.Portfolio.wait_for_recent(delta=1) | ||
813 | sleep.assert_called_with(30) | ||
814 | self.assertEqual(9, sleep.call_count) | ||
815 | self.assertEqual(10, get_cryptoportfolio.call_count) | ||
816 | |||
817 | def test_is_worker_thread(self): | ||
818 | with self.subTest(worker=None): | ||
819 | self.assertFalse(store.Portfolio.is_worker_thread()) | ||
820 | |||
821 | with self.subTest(worker="not self"),\ | ||
822 | mock.patch("threading.current_thread") as current_thread: | ||
823 | current = mock.Mock() | ||
824 | current_thread.return_value = current | ||
825 | store.Portfolio.worker = mock.Mock() | ||
826 | self.assertFalse(store.Portfolio.is_worker_thread()) | ||
827 | |||
828 | with self.subTest(worker="self"),\ | ||
829 | mock.patch("threading.current_thread") as current_thread: | ||
830 | current = mock.Mock() | ||
831 | current_thread.return_value = current | ||
832 | store.Portfolio.worker = current | ||
833 | self.assertTrue(store.Portfolio.is_worker_thread()) | ||
834 | |||
835 | def test_start_worker(self): | ||
836 | with mock.patch.object(store.Portfolio, "wait_for_notification") as notification: | ||
837 | store.Portfolio.start_worker() | ||
838 | notification.assert_called_once_with(poll=30) | ||
839 | |||
840 | self.assertEqual("lock", store.Portfolio.last_date.lock.__class__.__name__) | ||
841 | self.assertEqual("lock", store.Portfolio.liquidities.lock.__class__.__name__) | ||
842 | store.Portfolio.report.start_lock.assert_called_once_with() | ||
843 | |||
844 | self.assertIsNotNone(store.Portfolio.worker) | ||
845 | self.assertIsNotNone(store.Portfolio.worker_notify) | ||
846 | self.assertIsNotNone(store.Portfolio.callback) | ||
847 | self.assertTrue(store.Portfolio.worker_started) | ||
848 | |||
849 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
850 | class AmountTest(WebMockTestCase): | ||
851 | def test_values(self): | ||
852 | amount = portfolio.Amount("BTC", "0.65") | ||
853 | self.assertEqual(D("0.65"), amount.value) | ||
854 | self.assertEqual("BTC", amount.currency) | ||
855 | |||
856 | def test_in_currency(self): | ||
857 | amount = portfolio.Amount("ETC", 10) | ||
858 | |||
859 | self.assertEqual(amount, amount.in_currency("ETC", self.m)) | ||
860 | |||
861 | with self.subTest(desc="no ticker for currency"): | ||
862 | self.m.get_ticker.return_value = None | ||
863 | |||
864 | self.assertRaises(Exception, amount.in_currency, "ETH", self.m) | ||
865 | |||
866 | with self.subTest(desc="nominal case"): | ||
867 | self.m.get_ticker.return_value = { | ||
868 | "bid": D("0.2"), | ||
869 | "ask": D("0.4"), | ||
870 | "average": D("0.3"), | ||
871 | "foo": "bar", | ||
872 | } | ||
873 | converted_amount = amount.in_currency("ETH", self.m) | ||
874 | |||
875 | self.assertEqual(D("3.0"), converted_amount.value) | ||
876 | self.assertEqual("ETH", converted_amount.currency) | ||
877 | self.assertEqual(amount, converted_amount.linked_to) | ||
878 | self.assertEqual("bar", converted_amount.ticker["foo"]) | ||
879 | |||
880 | converted_amount = amount.in_currency("ETH", self.m, action="bid", compute_value="default") | ||
881 | self.assertEqual(D("2"), converted_amount.value) | ||
882 | |||
883 | converted_amount = amount.in_currency("ETH", self.m, compute_value="ask") | ||
884 | self.assertEqual(D("4"), converted_amount.value) | ||
885 | |||
886 | converted_amount = amount.in_currency("ETH", self.m, rate=D("0.02")) | ||
887 | self.assertEqual(D("0.2"), converted_amount.value) | ||
888 | |||
889 | def test__round(self): | ||
890 | amount = portfolio.Amount("BAR", portfolio.D("1.23456789876")) | ||
891 | self.assertEqual(D("1.23456789"), round(amount).value) | ||
892 | self.assertEqual(D("1.23"), round(amount, 2).value) | ||
893 | |||
894 | def test__abs(self): | ||
895 | amount = portfolio.Amount("SC", -120) | ||
896 | self.assertEqual(120, abs(amount).value) | ||
897 | self.assertEqual("SC", abs(amount).currency) | ||
898 | |||
899 | amount = portfolio.Amount("SC", 10) | ||
900 | self.assertEqual(10, abs(amount).value) | ||
901 | self.assertEqual("SC", abs(amount).currency) | ||
902 | |||
903 | def test__add(self): | ||
904 | amount1 = portfolio.Amount("XVG", "12.9") | ||
905 | amount2 = portfolio.Amount("XVG", "13.1") | ||
906 | |||
907 | self.assertEqual(26, (amount1 + amount2).value) | ||
908 | self.assertEqual("XVG", (amount1 + amount2).currency) | ||
909 | |||
910 | amount3 = portfolio.Amount("ETH", "1.6") | ||
911 | with self.assertRaises(Exception): | ||
912 | amount1 + amount3 | ||
913 | |||
914 | amount4 = portfolio.Amount("ETH", 0.0) | ||
915 | self.assertEqual(amount1, amount1 + amount4) | ||
916 | |||
917 | self.assertEqual(amount1, amount1 + 0) | ||
918 | |||
919 | def test__radd(self): | ||
920 | amount = portfolio.Amount("XVG", "12.9") | ||
921 | |||
922 | self.assertEqual(amount, 0 + amount) | ||
923 | with self.assertRaises(Exception): | ||
924 | 4 + amount | ||
925 | |||
926 | def test__sub(self): | ||
927 | amount1 = portfolio.Amount("XVG", "13.3") | ||
928 | amount2 = portfolio.Amount("XVG", "13.1") | ||
929 | |||
930 | self.assertEqual(D("0.2"), (amount1 - amount2).value) | ||
931 | self.assertEqual("XVG", (amount1 - amount2).currency) | ||
932 | |||
933 | amount3 = portfolio.Amount("ETH", "1.6") | ||
934 | with self.assertRaises(Exception): | ||
935 | amount1 - amount3 | ||
936 | |||
937 | amount4 = portfolio.Amount("ETH", 0.0) | ||
938 | self.assertEqual(amount1, amount1 - amount4) | ||
939 | |||
940 | def test__rsub(self): | ||
941 | amount = portfolio.Amount("ETH", "1.6") | ||
942 | with self.assertRaises(Exception): | ||
943 | 3 - amount | ||
944 | |||
945 | self.assertEqual(portfolio.Amount("ETH", "-1.6"), 0-amount) | ||
946 | |||
947 | def test__mul(self): | ||
948 | amount = portfolio.Amount("XEM", 11) | ||
949 | |||
950 | self.assertEqual(D("38.5"), (amount * D("3.5")).value) | ||
951 | self.assertEqual(D("33"), (amount * 3).value) | ||
952 | |||
953 | with self.assertRaises(Exception): | ||
954 | amount * amount | ||
955 | |||
956 | def test__rmul(self): | ||
957 | amount = portfolio.Amount("XEM", 11) | ||
958 | |||
959 | self.assertEqual(D("38.5"), (D("3.5") * amount).value) | ||
960 | self.assertEqual(D("33"), (3 * amount).value) | ||
961 | |||
962 | def test__floordiv(self): | ||
963 | amount = portfolio.Amount("XEM", 11) | ||
964 | |||
965 | self.assertEqual(D("5.5"), (amount / 2).value) | ||
966 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | ||
967 | |||
968 | with self.assertRaises(Exception): | ||
969 | amount / amount | ||
970 | |||
971 | def test__truediv(self): | ||
972 | amount = portfolio.Amount("XEM", 11) | ||
973 | |||
974 | self.assertEqual(D("5.5"), (amount / 2).value) | ||
975 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | ||
976 | |||
977 | def test__lt(self): | ||
978 | amount1 = portfolio.Amount("BTD", 11.3) | ||
979 | amount2 = portfolio.Amount("BTD", 13.1) | ||
980 | |||
981 | self.assertTrue(amount1 < amount2) | ||
982 | self.assertFalse(amount2 < amount1) | ||
983 | self.assertFalse(amount1 < amount1) | ||
984 | |||
985 | amount3 = portfolio.Amount("BTC", 1.6) | ||
986 | with self.assertRaises(Exception): | ||
987 | amount1 < amount3 | ||
988 | |||
989 | def test__le(self): | ||
990 | amount1 = portfolio.Amount("BTD", 11.3) | ||
991 | amount2 = portfolio.Amount("BTD", 13.1) | ||
992 | |||
993 | self.assertTrue(amount1 <= amount2) | ||
994 | self.assertFalse(amount2 <= amount1) | ||
995 | self.assertTrue(amount1 <= amount1) | ||
996 | |||
997 | amount3 = portfolio.Amount("BTC", 1.6) | ||
998 | with self.assertRaises(Exception): | ||
999 | amount1 <= amount3 | ||
1000 | |||
1001 | def test__gt(self): | ||
1002 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1003 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1004 | |||
1005 | self.assertTrue(amount2 > amount1) | ||
1006 | self.assertFalse(amount1 > amount2) | ||
1007 | self.assertFalse(amount1 > amount1) | ||
1008 | |||
1009 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1010 | with self.assertRaises(Exception): | ||
1011 | amount3 > amount1 | ||
1012 | |||
1013 | def test__ge(self): | ||
1014 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1015 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1016 | |||
1017 | self.assertTrue(amount2 >= amount1) | ||
1018 | self.assertFalse(amount1 >= amount2) | ||
1019 | self.assertTrue(amount1 >= amount1) | ||
1020 | |||
1021 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1022 | with self.assertRaises(Exception): | ||
1023 | amount3 >= amount1 | ||
1024 | |||
1025 | def test__eq(self): | ||
1026 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1027 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1028 | amount3 = portfolio.Amount("BTD", 11.3) | ||
1029 | |||
1030 | self.assertFalse(amount1 == amount2) | ||
1031 | self.assertFalse(amount2 == amount1) | ||
1032 | self.assertTrue(amount1 == amount3) | ||
1033 | self.assertFalse(amount2 == 0) | ||
1034 | |||
1035 | amount4 = portfolio.Amount("BTC", 1.6) | ||
1036 | with self.assertRaises(Exception): | ||
1037 | amount1 == amount4 | ||
1038 | |||
1039 | amount5 = portfolio.Amount("BTD", 0) | ||
1040 | self.assertTrue(amount5 == 0) | ||
1041 | |||
1042 | def test__ne(self): | ||
1043 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1044 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1045 | amount3 = portfolio.Amount("BTD", 11.3) | ||
1046 | |||
1047 | self.assertTrue(amount1 != amount2) | ||
1048 | self.assertTrue(amount2 != amount1) | ||
1049 | self.assertFalse(amount1 != amount3) | ||
1050 | self.assertTrue(amount2 != 0) | ||
1051 | |||
1052 | amount4 = portfolio.Amount("BTC", 1.6) | ||
1053 | with self.assertRaises(Exception): | ||
1054 | amount1 != amount4 | ||
1055 | |||
1056 | amount5 = portfolio.Amount("BTD", 0) | ||
1057 | self.assertFalse(amount5 != 0) | ||
1058 | |||
1059 | def test__neg(self): | ||
1060 | amount1 = portfolio.Amount("BTD", "11.3") | ||
1061 | |||
1062 | self.assertEqual(portfolio.D("-11.3"), (-amount1).value) | ||
1063 | |||
1064 | def test__str(self): | ||
1065 | amount1 = portfolio.Amount("BTX", 32) | ||
1066 | self.assertEqual("32.00000000 BTX", str(amount1)) | ||
1067 | |||
1068 | amount2 = portfolio.Amount("USDT", 12000) | ||
1069 | amount1.linked_to = amount2 | ||
1070 | self.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1)) | ||
1071 | |||
1072 | def test__repr(self): | ||
1073 | amount1 = portfolio.Amount("BTX", 32) | ||
1074 | self.assertEqual("Amount(32.00000000 BTX)", repr(amount1)) | ||
1075 | |||
1076 | amount2 = portfolio.Amount("USDT", 12000) | ||
1077 | amount1.linked_to = amount2 | ||
1078 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1)) | ||
1079 | |||
1080 | amount3 = portfolio.Amount("BTC", 0.1) | ||
1081 | amount2.linked_to = amount3 | ||
1082 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1)) | ||
1083 | |||
1084 | def test_as_json(self): | ||
1085 | amount = portfolio.Amount("BTX", 32) | ||
1086 | self.assertEqual({"currency": "BTX", "value": D("32")}, amount.as_json()) | ||
1087 | |||
1088 | amount = portfolio.Amount("BTX", "1E-10") | ||
1089 | self.assertEqual({"currency": "BTX", "value": D("0")}, amount.as_json()) | ||
1090 | |||
1091 | amount = portfolio.Amount("BTX", "1E-5") | ||
1092 | self.assertEqual({"currency": "BTX", "value": D("0.00001")}, amount.as_json()) | ||
1093 | self.assertEqual("0.00001", str(amount.as_json()["value"])) | ||
1094 | |||
1095 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1096 | class BalanceTest(WebMockTestCase): | ||
1097 | def test_values(self): | ||
1098 | balance = portfolio.Balance("BTC", { | ||
1099 | "exchange_total": "0.65", | ||
1100 | "exchange_free": "0.35", | ||
1101 | "exchange_used": "0.30", | ||
1102 | "margin_total": "-10", | ||
1103 | "margin_borrowed": "10", | ||
1104 | "margin_available": "0", | ||
1105 | "margin_in_position": "0", | ||
1106 | "margin_position_type": "short", | ||
1107 | "margin_borrowed_base_currency": "USDT", | ||
1108 | "margin_liquidation_price": "1.20", | ||
1109 | "margin_pending_gain": "10", | ||
1110 | "margin_lending_fees": "0.4", | ||
1111 | "margin_borrowed_base_price": "0.15", | ||
1112 | }) | ||
1113 | self.assertEqual(portfolio.D("0.65"), balance.exchange_total.value) | ||
1114 | self.assertEqual(portfolio.D("0.35"), balance.exchange_free.value) | ||
1115 | self.assertEqual(portfolio.D("0.30"), balance.exchange_used.value) | ||
1116 | self.assertEqual("BTC", balance.exchange_total.currency) | ||
1117 | self.assertEqual("BTC", balance.exchange_free.currency) | ||
1118 | self.assertEqual("BTC", balance.exchange_total.currency) | ||
1119 | |||
1120 | self.assertEqual(portfolio.D("-10"), balance.margin_total.value) | ||
1121 | self.assertEqual(portfolio.D("10"), balance.margin_borrowed.value) | ||
1122 | self.assertEqual(portfolio.D("0"), balance.margin_available.value) | ||
1123 | self.assertEqual("BTC", balance.margin_total.currency) | ||
1124 | self.assertEqual("BTC", balance.margin_borrowed.currency) | ||
1125 | self.assertEqual("BTC", balance.margin_available.currency) | ||
1126 | |||
1127 | self.assertEqual("BTC", balance.currency) | ||
1128 | |||
1129 | self.assertEqual(portfolio.D("0.4"), balance.margin_lending_fees.value) | ||
1130 | self.assertEqual("USDT", balance.margin_lending_fees.currency) | ||
1131 | |||
1132 | def test__repr(self): | ||
1133 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])", | ||
1134 | repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }))) | ||
1135 | balance = portfolio.Balance("BTX", { "exchange_total": 3, | ||
1136 | "exchange_used": 1, "exchange_free": 2 }) | ||
1137 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | ||
1138 | |||
1139 | balance = portfolio.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}) | ||
1140 | self.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance)) | ||
1141 | |||
1142 | balance = portfolio.Balance("BTX", { "margin_total": 3, | ||
1143 | "margin_in_position": 1, "margin_available": 2 }) | ||
1144 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | ||
1145 | |||
1146 | balance = portfolio.Balance("BTX", { "margin_total": 2, "margin_available": 2 }) | ||
1147 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance)) | ||
1148 | |||
1149 | balance = portfolio.Balance("BTX", { "margin_total": -3, | ||
1150 | "margin_borrowed_base_price": D("0.1"), | ||
1151 | "margin_borrowed_base_currency": "BTC", | ||
1152 | "margin_lending_fees": D("0.002") }) | ||
1153 | self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance)) | ||
1154 | |||
1155 | balance = portfolio.Balance("BTX", { "margin_total": 1, | ||
1156 | "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2}) | ||
1157 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance)) | ||
1158 | |||
1159 | def test_as_json(self): | ||
1160 | balance = portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }) | ||
1161 | as_json = balance.as_json() | ||
1162 | self.assertEqual(set(portfolio.Balance.base_keys), set(as_json.keys())) | ||
1163 | self.assertEqual(D(0), as_json["total"]) | ||
1164 | self.assertEqual(D(2), as_json["exchange_total"]) | ||
1165 | self.assertEqual(D(2), as_json["exchange_free"]) | ||
1166 | self.assertEqual(D(0), as_json["exchange_used"]) | ||
1167 | self.assertEqual(D(0), as_json["margin_total"]) | ||
1168 | self.assertEqual(D(0), as_json["margin_available"]) | ||
1169 | self.assertEqual(D(0), as_json["margin_borrowed"]) | ||
1170 | |||
1171 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1172 | class MarketTest(WebMockTestCase): | ||
1173 | def setUp(self): | ||
1174 | super().setUp() | ||
1175 | |||
1176 | self.ccxt = mock.Mock(spec=market.ccxt.poloniexE) | ||
1177 | |||
1178 | def test_values(self): | ||
1179 | m = market.Market(self.ccxt, self.market_args()) | ||
1180 | |||
1181 | self.assertEqual(self.ccxt, m.ccxt) | ||
1182 | self.assertFalse(m.debug) | ||
1183 | self.assertIsInstance(m.report, market.ReportStore) | ||
1184 | self.assertIsInstance(m.trades, market.TradeStore) | ||
1185 | self.assertIsInstance(m.balances, market.BalanceStore) | ||
1186 | self.assertEqual(m, m.report.market) | ||
1187 | self.assertEqual(m, m.trades.market) | ||
1188 | self.assertEqual(m, m.balances.market) | ||
1189 | self.assertEqual(m, m.ccxt._market) | ||
1190 | |||
1191 | m = market.Market(self.ccxt, self.market_args(debug=True)) | ||
1192 | self.assertTrue(m.debug) | ||
1193 | |||
1194 | m = market.Market(self.ccxt, self.market_args(debug=False)) | ||
1195 | self.assertFalse(m.debug) | ||
1196 | |||
1197 | with mock.patch("market.ReportStore") as report_store: | ||
1198 | with self.subTest(quiet=False): | ||
1199 | m = market.Market(self.ccxt, self.market_args(quiet=False)) | ||
1200 | report_store.assert_called_with(m, verbose_print=True) | ||
1201 | report_store().log_market.assert_called_once() | ||
1202 | report_store.reset_mock() | ||
1203 | with self.subTest(quiet=True): | ||
1204 | m = market.Market(self.ccxt, self.market_args(quiet=True)) | ||
1205 | report_store.assert_called_with(m, verbose_print=False) | ||
1206 | report_store().log_market.assert_called_once() | ||
1207 | |||
1208 | @mock.patch("market.ccxt") | ||
1209 | def test_from_config(self, ccxt): | ||
1210 | with mock.patch("market.ReportStore"): | ||
1211 | ccxt.poloniexE.return_value = self.ccxt | ||
1212 | |||
1213 | m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args()) | ||
1214 | |||
1215 | self.assertEqual(self.ccxt, m.ccxt) | ||
1216 | |||
1217 | m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args(debug=True)) | ||
1218 | self.assertEqual(True, m.debug) | ||
1219 | |||
1220 | def test_get_tickers(self): | ||
1221 | self.ccxt.fetch_tickers.side_effect = [ | ||
1222 | "tickers", | ||
1223 | market.NotSupported | ||
1224 | ] | ||
1225 | |||
1226 | m = market.Market(self.ccxt, self.market_args()) | ||
1227 | self.assertEqual("tickers", m.get_tickers()) | ||
1228 | self.assertEqual("tickers", m.get_tickers()) | ||
1229 | self.ccxt.fetch_tickers.assert_called_once() | ||
1230 | |||
1231 | self.assertIsNone(m.get_tickers(refresh=self.time.time())) | ||
1232 | |||
1233 | def test_get_ticker(self): | ||
1234 | with self.subTest(get_tickers=True): | ||
1235 | self.ccxt.fetch_tickers.return_value = { | ||
1236 | "ETH/ETC": { "bid": 1, "ask": 3 }, | ||
1237 | "XVG/ETH": { "bid": 10, "ask": 40 }, | ||
1238 | } | ||
1239 | m = market.Market(self.ccxt, self.market_args()) | ||
1240 | |||
1241 | ticker = m.get_ticker("ETH", "ETC") | ||
1242 | self.assertEqual(1, ticker["bid"]) | ||
1243 | self.assertEqual(3, ticker["ask"]) | ||
1244 | self.assertEqual(2, ticker["average"]) | ||
1245 | self.assertFalse(ticker["inverted"]) | ||
1246 | |||
1247 | ticker = m.get_ticker("ETH", "XVG") | ||
1248 | self.assertEqual(0.0625, ticker["average"]) | ||
1249 | self.assertTrue(ticker["inverted"]) | ||
1250 | self.assertIn("original", ticker) | ||
1251 | self.assertEqual(10, ticker["original"]["bid"]) | ||
1252 | self.assertEqual(25, ticker["original"]["average"]) | ||
1253 | |||
1254 | ticker = m.get_ticker("XVG", "XMR") | ||
1255 | self.assertIsNone(ticker) | ||
1256 | |||
1257 | with self.subTest(get_tickers=False): | ||
1258 | self.ccxt.fetch_tickers.return_value = None | ||
1259 | self.ccxt.fetch_ticker.side_effect = [ | ||
1260 | { "bid": 1, "ask": 3 }, | ||
1261 | market.ExchangeError("foo"), | ||
1262 | { "bid": 10, "ask": 40 }, | ||
1263 | market.ExchangeError("foo"), | ||
1264 | market.ExchangeError("foo"), | ||
1265 | ] | ||
1266 | |||
1267 | m = market.Market(self.ccxt, self.market_args()) | ||
1268 | |||
1269 | ticker = m.get_ticker("ETH", "ETC") | ||
1270 | self.ccxt.fetch_ticker.assert_called_with("ETH/ETC") | ||
1271 | self.assertEqual(1, ticker["bid"]) | ||
1272 | self.assertEqual(3, ticker["ask"]) | ||
1273 | self.assertEqual(2, ticker["average"]) | ||
1274 | self.assertFalse(ticker["inverted"]) | ||
1275 | |||
1276 | ticker = m.get_ticker("ETH", "XVG") | ||
1277 | self.assertEqual(0.0625, ticker["average"]) | ||
1278 | self.assertTrue(ticker["inverted"]) | ||
1279 | self.assertIn("original", ticker) | ||
1280 | self.assertEqual(10, ticker["original"]["bid"]) | ||
1281 | self.assertEqual(25, ticker["original"]["average"]) | ||
1282 | |||
1283 | ticker = m.get_ticker("XVG", "XMR") | ||
1284 | self.assertIsNone(ticker) | ||
1285 | |||
1286 | def test_fetch_fees(self): | ||
1287 | m = market.Market(self.ccxt, self.market_args()) | ||
1288 | self.ccxt.fetch_fees.return_value = "Foo" | ||
1289 | self.assertEqual("Foo", m.fetch_fees()) | ||
1290 | self.ccxt.fetch_fees.assert_called_once() | ||
1291 | self.ccxt.reset_mock() | ||
1292 | self.assertEqual("Foo", m.fetch_fees()) | ||
1293 | self.ccxt.fetch_fees.assert_not_called() | ||
1294 | |||
1295 | @mock.patch.object(market.Portfolio, "repartition") | ||
1296 | @mock.patch.object(market.Market, "get_ticker") | ||
1297 | @mock.patch.object(market.TradeStore, "compute_trades") | ||
1298 | def test_prepare_trades(self, compute_trades, get_ticker, repartition): | ||
1299 | repartition.return_value = { | ||
1300 | "XEM": (D("0.75"), "long"), | ||
1301 | "BTC": (D("0.25"), "long"), | ||
1302 | } | ||
1303 | def _get_ticker(c1, c2): | ||
1304 | if c1 == "USDT" and c2 == "BTC": | ||
1305 | return { "average": D("0.0001") } | ||
1306 | if c1 == "XVG" and c2 == "BTC": | ||
1307 | return { "average": D("0.000001") } | ||
1308 | if c1 == "XEM" and c2 == "BTC": | ||
1309 | return { "average": D("0.001") } | ||
1310 | self.fail("Should be called with {}, {}".format(c1, c2)) | ||
1311 | get_ticker.side_effect = _get_ticker | ||
1312 | |||
1313 | with mock.patch("market.ReportStore"): | ||
1314 | m = market.Market(self.ccxt, self.market_args()) | ||
1315 | self.ccxt.fetch_all_balances.return_value = { | ||
1316 | "USDT": { | ||
1317 | "exchange_free": D("10000.0"), | ||
1318 | "exchange_used": D("0.0"), | ||
1319 | "exchange_total": D("10000.0"), | ||
1320 | "total": D("10000.0") | ||
1321 | }, | ||
1322 | "XVG": { | ||
1323 | "exchange_free": D("10000.0"), | ||
1324 | "exchange_used": D("0.0"), | ||
1325 | "exchange_total": D("10000.0"), | ||
1326 | "total": D("10000.0") | ||
1327 | }, | ||
1328 | } | ||
1329 | |||
1330 | m.balances.fetch_balances(tag="tag") | ||
1331 | |||
1332 | m.prepare_trades() | ||
1333 | compute_trades.assert_called() | ||
1334 | |||
1335 | call = compute_trades.call_args | ||
1336 | self.assertEqual(1, call[0][0]["USDT"].value) | ||
1337 | self.assertEqual(D("0.01"), call[0][0]["XVG"].value) | ||
1338 | self.assertEqual(D("0.2525"), call[0][1]["BTC"].value) | ||
1339 | self.assertEqual(D("0.7575"), call[0][1]["XEM"].value) | ||
1340 | m.report.log_stage.assert_called_once_with("prepare_trades", | ||
1341 | base_currency='BTC', compute_value='average', | ||
1342 | liquidity='medium', only=None, repartition=None) | ||
1343 | m.report.log_balances.assert_called_once_with(tag="tag") | ||
1344 | |||
1345 | |||
1346 | @mock.patch.object(market.time, "sleep") | ||
1347 | @mock.patch.object(market.TradeStore, "all_orders") | ||
1348 | def test_follow_orders(self, all_orders, time_mock): | ||
1349 | for debug, sleep in [ | ||
1350 | (False, None), (True, None), | ||
1351 | (False, 12), (True, 12)]: | ||
1352 | with self.subTest(sleep=sleep, debug=debug), \ | ||
1353 | mock.patch("market.ReportStore"): | ||
1354 | m = market.Market(self.ccxt, self.market_args(debug=debug)) | ||
1355 | |||
1356 | order_mock1 = mock.Mock() | ||
1357 | order_mock2 = mock.Mock() | ||
1358 | order_mock3 = mock.Mock() | ||
1359 | all_orders.side_effect = [ | ||
1360 | [order_mock1, order_mock2], | ||
1361 | [order_mock1, order_mock2], | ||
1362 | |||
1363 | [order_mock1, order_mock3], | ||
1364 | [order_mock1, order_mock3], | ||
1365 | |||
1366 | [order_mock1, order_mock3], | ||
1367 | [order_mock1, order_mock3], | ||
1368 | |||
1369 | [] | ||
1370 | ] | ||
1371 | |||
1372 | order_mock1.get_status.side_effect = ["open", "open", "closed"] | ||
1373 | order_mock2.get_status.side_effect = ["open"] | ||
1374 | order_mock3.get_status.side_effect = ["open", "closed"] | ||
1375 | |||
1376 | order_mock1.trade = mock.Mock() | ||
1377 | order_mock2.trade = mock.Mock() | ||
1378 | order_mock3.trade = mock.Mock() | ||
1379 | |||
1380 | m.follow_orders(sleep=sleep) | ||
1381 | |||
1382 | order_mock1.trade.update_order.assert_any_call(order_mock1, 1) | ||
1383 | order_mock1.trade.update_order.assert_any_call(order_mock1, 2) | ||
1384 | self.assertEqual(2, order_mock1.trade.update_order.call_count) | ||
1385 | self.assertEqual(3, order_mock1.get_status.call_count) | ||
1386 | |||
1387 | order_mock2.trade.update_order.assert_any_call(order_mock2, 1) | ||
1388 | self.assertEqual(1, order_mock2.trade.update_order.call_count) | ||
1389 | self.assertEqual(1, order_mock2.get_status.call_count) | ||
1390 | |||
1391 | order_mock3.trade.update_order.assert_any_call(order_mock3, 2) | ||
1392 | self.assertEqual(1, order_mock3.trade.update_order.call_count) | ||
1393 | self.assertEqual(2, order_mock3.get_status.call_count) | ||
1394 | m.report.log_stage.assert_called() | ||
1395 | calls = [ | ||
1396 | mock.call("follow_orders_begin"), | ||
1397 | mock.call("follow_orders_tick_1"), | ||
1398 | mock.call("follow_orders_tick_2"), | ||
1399 | mock.call("follow_orders_tick_3"), | ||
1400 | mock.call("follow_orders_end"), | ||
1401 | ] | ||
1402 | m.report.log_stage.assert_has_calls(calls) | ||
1403 | m.report.log_orders.assert_called() | ||
1404 | self.assertEqual(3, m.report.log_orders.call_count) | ||
1405 | calls = [ | ||
1406 | mock.call([order_mock1, order_mock2], tick=1), | ||
1407 | mock.call([order_mock1, order_mock3], tick=2), | ||
1408 | mock.call([order_mock1, order_mock3], tick=3), | ||
1409 | ] | ||
1410 | m.report.log_orders.assert_has_calls(calls) | ||
1411 | calls = [ | ||
1412 | mock.call(order_mock1, 3, finished=True), | ||
1413 | mock.call(order_mock3, 3, finished=True), | ||
1414 | ] | ||
1415 | m.report.log_order.assert_has_calls(calls) | ||
1416 | |||
1417 | if sleep is None: | ||
1418 | if debug: | ||
1419 | m.report.log_debug_action.assert_called_with("Set follow_orders tick to 7s") | ||
1420 | time_mock.assert_called_with(7) | ||
1421 | else: | ||
1422 | time_mock.assert_called_with(30) | ||
1423 | else: | ||
1424 | time_mock.assert_called_with(sleep) | ||
1425 | |||
1426 | with self.subTest("disappearing order"), \ | ||
1427 | mock.patch("market.ReportStore"): | ||
1428 | all_orders.reset_mock() | ||
1429 | m = market.Market(self.ccxt, self.market_args()) | ||
1430 | |||
1431 | order_mock1 = mock.Mock() | ||
1432 | order_mock2 = mock.Mock() | ||
1433 | all_orders.side_effect = [ | ||
1434 | [order_mock1, order_mock2], | ||
1435 | [order_mock1, order_mock2], | ||
1436 | |||
1437 | [order_mock1, order_mock2], | ||
1438 | [order_mock1, order_mock2], | ||
1439 | |||
1440 | [] | ||
1441 | ] | ||
1442 | |||
1443 | order_mock1.get_status.side_effect = ["open", "closed"] | ||
1444 | order_mock2.get_status.side_effect = ["open", "error_disappeared"] | ||
1445 | |||
1446 | order_mock1.trade = mock.Mock() | ||
1447 | trade_mock = mock.Mock() | ||
1448 | order_mock2.trade = trade_mock | ||
1449 | |||
1450 | trade_mock.tick_actions_recreate.return_value = "tick1" | ||
1451 | |||
1452 | m.follow_orders() | ||
1453 | |||
1454 | trade_mock.tick_actions_recreate.assert_called_once_with(2) | ||
1455 | trade_mock.prepare_order.assert_called_once_with(compute_value="tick1") | ||
1456 | m.report.log_error.assert_called_once_with("follow_orders", message=mock.ANY) | ||
1457 | |||
1458 | @mock.patch.object(market.BalanceStore, "fetch_balances") | ||
1459 | def test_move_balance(self, fetch_balances): | ||
1460 | for debug in [True, False]: | ||
1461 | with self.subTest(debug=debug),\ | ||
1462 | mock.patch("market.ReportStore"): | ||
1463 | m = market.Market(self.ccxt, self.market_args(debug=debug)) | ||
1464 | |||
1465 | value_from = portfolio.Amount("BTC", "1.0") | ||
1466 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
1467 | value_to = portfolio.Amount("BTC", "10.0") | ||
1468 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
1469 | |||
1470 | value_from = portfolio.Amount("BTC", "0.0") | ||
1471 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
1472 | value_to = portfolio.Amount("BTC", "-3.0") | ||
1473 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
1474 | |||
1475 | value_from = portfolio.Amount("USDT", "0.0") | ||
1476 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | ||
1477 | value_to = portfolio.Amount("USDT", "-50.0") | ||
1478 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) | ||
1479 | |||
1480 | m.trades.all = [trade1, trade2, trade3] | ||
1481 | balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
1482 | balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }) | ||
1483 | balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }) | ||
1484 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} | ||
1485 | |||
1486 | m.move_balances() | ||
1487 | |||
1488 | fetch_balances.assert_called_with() | ||
1489 | m.report.log_move_balances.assert_called_once() | ||
1490 | |||
1491 | if debug: | ||
1492 | m.report.log_debug_action.assert_called() | ||
1493 | self.assertEqual(3, m.report.log_debug_action.call_count) | ||
1494 | else: | ||
1495 | self.ccxt.transfer_balance.assert_any_call("BTC", 3, "exchange", "margin") | ||
1496 | self.ccxt.transfer_balance.assert_any_call("USDT", 100, "exchange", "margin") | ||
1497 | self.ccxt.transfer_balance.assert_any_call("ETC", 5, "margin", "exchange") | ||
1498 | |||
1499 | m.report.reset_mock() | ||
1500 | fetch_balances.reset_mock() | ||
1501 | with self.subTest(retry=True): | ||
1502 | with mock.patch("market.ReportStore"): | ||
1503 | m = market.Market(self.ccxt, self.market_args()) | ||
1504 | |||
1505 | value_from = portfolio.Amount("BTC", "0.0") | ||
1506 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
1507 | value_to = portfolio.Amount("BTC", "-3.0") | ||
1508 | trade = portfolio.Trade(value_from, value_to, "ETH", m) | ||
1509 | |||
1510 | m.trades.all = [trade] | ||
1511 | balance = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
1512 | m.balances.all = {"BTC": balance} | ||
1513 | |||
1514 | m.ccxt.transfer_balance.side_effect = [ | ||
1515 | market.ccxt.RequestTimeout, | ||
1516 | market.ccxt.InvalidNonce, | ||
1517 | True | ||
1518 | ] | ||
1519 | m.move_balances() | ||
1520 | self.ccxt.transfer_balance.assert_has_calls([ | ||
1521 | mock.call("BTC", 3, "exchange", "margin"), | ||
1522 | mock.call("BTC", 3, "exchange", "margin"), | ||
1523 | mock.call("BTC", 3, "exchange", "margin") | ||
1524 | ]) | ||
1525 | self.assertEqual(3, fetch_balances.call_count) | ||
1526 | m.report.log_error.assert_called_with(mock.ANY, message="Retrying", exception=mock.ANY) | ||
1527 | self.assertEqual(3, m.report.log_move_balances.call_count) | ||
1528 | |||
1529 | self.ccxt.transfer_balance.reset_mock() | ||
1530 | m.report.reset_mock() | ||
1531 | fetch_balances.reset_mock() | ||
1532 | with self.subTest(retry=True, too_much=True): | ||
1533 | with mock.patch("market.ReportStore"): | ||
1534 | m = market.Market(self.ccxt, self.market_args()) | ||
1535 | |||
1536 | value_from = portfolio.Amount("BTC", "0.0") | ||
1537 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
1538 | value_to = portfolio.Amount("BTC", "-3.0") | ||
1539 | trade = portfolio.Trade(value_from, value_to, "ETH", m) | ||
1540 | |||
1541 | m.trades.all = [trade] | ||
1542 | balance = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
1543 | m.balances.all = {"BTC": balance} | ||
1544 | |||
1545 | m.ccxt.transfer_balance.side_effect = [ | ||
1546 | market.ccxt.RequestTimeout, | ||
1547 | market.ccxt.RequestTimeout, | ||
1548 | market.ccxt.RequestTimeout, | ||
1549 | market.ccxt.RequestTimeout, | ||
1550 | market.ccxt.RequestTimeout, | ||
1551 | ] | ||
1552 | with self.assertRaises(market.ccxt.RequestTimeout): | ||
1553 | m.move_balances() | ||
1554 | |||
1555 | self.ccxt.transfer_balance.reset_mock() | ||
1556 | m.report.reset_mock() | ||
1557 | fetch_balances.reset_mock() | ||
1558 | with self.subTest(retry=True, partial_result=True): | ||
1559 | with mock.patch("market.ReportStore"): | ||
1560 | m = market.Market(self.ccxt, self.market_args()) | ||
1561 | |||
1562 | value_from = portfolio.Amount("BTC", "1.0") | ||
1563 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
1564 | value_to = portfolio.Amount("BTC", "10.0") | ||
1565 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
1566 | |||
1567 | value_from = portfolio.Amount("BTC", "0.0") | ||
1568 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
1569 | value_to = portfolio.Amount("BTC", "-3.0") | ||
1570 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
1571 | |||
1572 | value_from = portfolio.Amount("USDT", "0.0") | ||
1573 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | ||
1574 | value_to = portfolio.Amount("USDT", "-50.0") | ||
1575 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) | ||
1576 | |||
1577 | m.trades.all = [trade1, trade2, trade3] | ||
1578 | balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
1579 | balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }) | ||
1580 | balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }) | ||
1581 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} | ||
1582 | |||
1583 | call_counts = { "BTC": 0, "USDT": 0, "ETC": 0 } | ||
1584 | def _transfer_balance(currency, amount, from_, to_): | ||
1585 | call_counts[currency] += 1 | ||
1586 | if currency == "BTC": | ||
1587 | m.balances.all["BTC"] = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "3" }) | ||
1588 | if currency == "USDT": | ||
1589 | if call_counts["USDT"] == 1: | ||
1590 | raise market.ccxt.RequestTimeout | ||
1591 | else: | ||
1592 | m.balances.all["USDT"] = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "150" }) | ||
1593 | if currency == "ETC": | ||
1594 | m.balances.all["ETC"] = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "10" }) | ||
1595 | |||
1596 | |||
1597 | m.ccxt.transfer_balance.side_effect = _transfer_balance | ||
1598 | |||
1599 | m.move_balances() | ||
1600 | self.ccxt.transfer_balance.assert_has_calls([ | ||
1601 | mock.call("BTC", 3, "exchange", "margin"), | ||
1602 | mock.call('USDT', 100, 'exchange', 'margin'), | ||
1603 | mock.call('USDT', 100, 'exchange', 'margin'), | ||
1604 | mock.call("ETC", 5, "margin", "exchange") | ||
1605 | ]) | ||
1606 | self.assertEqual(2, fetch_balances.call_count) | ||
1607 | m.report.log_error.assert_called_with(mock.ANY, message="Retrying", exception=mock.ANY) | ||
1608 | self.assertEqual(2, m.report.log_move_balances.call_count) | ||
1609 | m.report.log_move_balances.asser_has_calls([ | ||
1610 | mock.call( | ||
1611 | { | ||
1612 | 'BTC': portfolio.Amount("BTC", "3"), | ||
1613 | 'USDT': portfolio.Amount("USDT", "150"), | ||
1614 | 'ETC': portfolio.Amount("ETC", "10"), | ||
1615 | }, | ||
1616 | { | ||
1617 | 'BTC': portfolio.Amount("BTC", "3"), | ||
1618 | 'USDT': portfolio.Amount("USDT", "100"), | ||
1619 | }), | ||
1620 | mock.call( | ||
1621 | { | ||
1622 | 'BTC': portfolio.Amount("BTC", "3"), | ||
1623 | 'USDT': portfolio.Amount("USDT", "150"), | ||
1624 | 'ETC': portfolio.Amount("ETC", "10"), | ||
1625 | }, | ||
1626 | { | ||
1627 | 'BTC': portfolio.Amount("BTC", "0"), | ||
1628 | 'USDT': portfolio.Amount("USDT", "100"), | ||
1629 | 'ETC': portfolio.Amount("ETC", "-5"), | ||
1630 | }), | ||
1631 | ]) | ||
1632 | |||
1633 | |||
1634 | def test_store_file_report(self): | ||
1635 | file_open = mock.mock_open() | ||
1636 | m = market.Market(self.ccxt, | ||
1637 | self.market_args(report_path="present"), user_id=1) | ||
1638 | with self.subTest(file="present"),\ | ||
1639 | mock.patch("market.open", file_open),\ | ||
1640 | mock.patch.object(m, "report") as report,\ | ||
1641 | mock.patch.object(market, "datetime") as time_mock: | ||
1642 | |||
1643 | report.print_logs = [[time_mock.now(), "Foo"], [time_mock.now(), "Bar"]] | ||
1644 | report.to_json.return_value = "json_content" | ||
1645 | |||
1646 | m.store_file_report(datetime.datetime(2018, 2, 25)) | ||
1647 | |||
1648 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.json", "w") | ||
1649 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.log", "w") | ||
1650 | file_open().write.assert_any_call("json_content") | ||
1651 | file_open().write.assert_any_call("Foo\nBar") | ||
1652 | m.report.to_json.assert_called_once_with() | ||
1653 | |||
1654 | m = market.Market(self.ccxt, self.market_args(report_path="error"), user_id=1) | ||
1655 | with self.subTest(file="error"),\ | ||
1656 | mock.patch("market.open") as file_open,\ | ||
1657 | mock.patch.object(m, "report") as report,\ | ||
1658 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
1659 | file_open.side_effect = FileNotFoundError | ||
1660 | |||
1661 | m.store_file_report(datetime.datetime(2018, 2, 25)) | ||
1662 | |||
1663 | self.assertRegex(stdout_mock.getvalue(), "impossible to store report file: FileNotFoundError;") | ||
1664 | |||
1665 | @mock.patch.object(market, "psycopg2") | ||
1666 | def test_store_database_report(self, psycopg2): | ||
1667 | connect_mock = mock.Mock() | ||
1668 | cursor_mock = mock.MagicMock() | ||
1669 | |||
1670 | connect_mock.cursor.return_value = cursor_mock | ||
1671 | psycopg2.connect.return_value = connect_mock | ||
1672 | m = market.Market(self.ccxt, self.market_args(), | ||
1673 | pg_config={"config": "pg_config"}, user_id=1) | ||
1674 | cursor_mock.fetchone.return_value = [42] | ||
1675 | |||
1676 | with self.subTest(error=False),\ | ||
1677 | mock.patch.object(m, "report") as report: | ||
1678 | report.to_json_array.return_value = [ | ||
1679 | ("date1", "type1", "payload1"), | ||
1680 | ("date2", "type2", "payload2"), | ||
1681 | ] | ||
1682 | m.store_database_report(datetime.datetime(2018, 3, 24)) | ||
1683 | connect_mock.assert_has_calls([ | ||
1684 | mock.call.cursor(), | ||
1685 | mock.call.cursor().execute('INSERT INTO reports("date", "market_config_id", "debug") VALUES (%s, %s, %s) RETURNING id;', (datetime.datetime(2018, 3, 24), None, False)), | ||
1686 | mock.call.cursor().fetchone(), | ||
1687 | mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date1', 42, 'type1', 'payload1')), | ||
1688 | mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date2', 42, 'type2', 'payload2')), | ||
1689 | mock.call.commit(), | ||
1690 | mock.call.cursor().close(), | ||
1691 | mock.call.close() | ||
1692 | ]) | ||
1693 | |||
1694 | connect_mock.reset_mock() | ||
1695 | with self.subTest(error=True),\ | ||
1696 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
1697 | psycopg2.connect.side_effect = Exception("Bouh") | ||
1698 | m.store_database_report(datetime.datetime(2018, 3, 24)) | ||
1699 | self.assertEqual(stdout_mock.getvalue(), "impossible to store report to database: Exception; Bouh\n") | ||
1700 | |||
1701 | def test_store_report(self): | ||
1702 | m = market.Market(self.ccxt, self.market_args(report_db=False), user_id=1) | ||
1703 | with self.subTest(file=None, pg_config=None),\ | ||
1704 | mock.patch.object(m, "report") as report,\ | ||
1705 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
1706 | mock.patch.object(m, "store_file_report") as file_report: | ||
1707 | m.store_report() | ||
1708 | report.merge.assert_called_with(store.Portfolio.report) | ||
1709 | |||
1710 | file_report.assert_not_called() | ||
1711 | db_report.assert_not_called() | ||
1712 | |||
1713 | report.reset_mock() | ||
1714 | m = market.Market(self.ccxt, self.market_args(report_db=False, report_path="present"), user_id=1) | ||
1715 | with self.subTest(file="present", pg_config=None),\ | ||
1716 | mock.patch.object(m, "report") as report,\ | ||
1717 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
1718 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
1719 | mock.patch.object(market, "datetime") as time_mock: | ||
1720 | |||
1721 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
1722 | |||
1723 | m.store_report() | ||
1724 | |||
1725 | report.merge.assert_called_with(store.Portfolio.report) | ||
1726 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
1727 | db_report.assert_not_called() | ||
1728 | |||
1729 | report.reset_mock() | ||
1730 | m = market.Market(self.ccxt, self.market_args(report_db=True, report_path="present"), user_id=1) | ||
1731 | with self.subTest(file="present", pg_config=None, report_db=True),\ | ||
1732 | mock.patch.object(m, "report") as report,\ | ||
1733 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
1734 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
1735 | mock.patch.object(market, "datetime") as time_mock: | ||
1736 | |||
1737 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
1738 | |||
1739 | m.store_report() | ||
1740 | |||
1741 | report.merge.assert_called_with(store.Portfolio.report) | ||
1742 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
1743 | db_report.assert_not_called() | ||
1744 | |||
1745 | report.reset_mock() | ||
1746 | m = market.Market(self.ccxt, self.market_args(report_db=True), pg_config="present", user_id=1) | ||
1747 | with self.subTest(file=None, pg_config="present"),\ | ||
1748 | mock.patch.object(m, "report") as report,\ | ||
1749 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
1750 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
1751 | mock.patch.object(market, "datetime") as time_mock: | ||
1752 | |||
1753 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
1754 | |||
1755 | m.store_report() | ||
1756 | |||
1757 | report.merge.assert_called_with(store.Portfolio.report) | ||
1758 | file_report.assert_not_called() | ||
1759 | db_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
1760 | |||
1761 | report.reset_mock() | ||
1762 | m = market.Market(self.ccxt, self.market_args(report_db=True, report_path="present"), | ||
1763 | pg_config="pg_config", user_id=1) | ||
1764 | with self.subTest(file="present", pg_config="present"),\ | ||
1765 | mock.patch.object(m, "report") as report,\ | ||
1766 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
1767 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
1768 | mock.patch.object(market, "datetime") as time_mock: | ||
1769 | |||
1770 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
1771 | |||
1772 | m.store_report() | ||
1773 | |||
1774 | report.merge.assert_called_with(store.Portfolio.report) | ||
1775 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
1776 | db_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
1777 | |||
1778 | def test_print_orders(self): | ||
1779 | m = market.Market(self.ccxt, self.market_args()) | ||
1780 | with mock.patch.object(m.report, "log_stage") as log_stage,\ | ||
1781 | mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\ | ||
1782 | mock.patch.object(m, "prepare_trades") as prepare_trades,\ | ||
1783 | mock.patch.object(m.trades, "prepare_orders") as prepare_orders: | ||
1784 | m.print_orders() | ||
1785 | |||
1786 | log_stage.assert_called_with("print_orders") | ||
1787 | fetch_balances.assert_called_with(tag="print_orders") | ||
1788 | prepare_trades.assert_called_with(base_currency="BTC", | ||
1789 | compute_value="average") | ||
1790 | prepare_orders.assert_called_with(compute_value="average") | ||
1791 | |||
1792 | def test_print_balances(self): | ||
1793 | m = market.Market(self.ccxt, self.market_args()) | ||
1794 | |||
1795 | with mock.patch.object(m.balances, "in_currency") as in_currency,\ | ||
1796 | mock.patch.object(m.report, "log_stage") as log_stage,\ | ||
1797 | mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\ | ||
1798 | mock.patch.object(m.report, "print_log") as print_log: | ||
1799 | |||
1800 | in_currency.return_value = { | ||
1801 | "BTC": portfolio.Amount("BTC", "0.65"), | ||
1802 | "ETH": portfolio.Amount("BTC", "0.3"), | ||
1803 | } | ||
1804 | |||
1805 | m.print_balances() | ||
1806 | |||
1807 | log_stage.assert_called_once_with("print_balances") | ||
1808 | fetch_balances.assert_called_with() | ||
1809 | print_log.assert_has_calls([ | ||
1810 | mock.call("total:"), | ||
1811 | mock.call(portfolio.Amount("BTC", "0.95")), | ||
1812 | ]) | ||
1813 | |||
1814 | @mock.patch("market.Processor.process") | ||
1815 | @mock.patch("market.ReportStore.log_error") | ||
1816 | @mock.patch("market.Market.store_report") | ||
1817 | def test_process(self, store_report, log_error, process): | ||
1818 | m = market.Market(self.ccxt, self.market_args()) | ||
1819 | with self.subTest(before=False, after=False): | ||
1820 | m.process(None) | ||
1821 | |||
1822 | process.assert_not_called() | ||
1823 | store_report.assert_called_once() | ||
1824 | log_error.assert_not_called() | ||
1825 | |||
1826 | process.reset_mock() | ||
1827 | log_error.reset_mock() | ||
1828 | store_report.reset_mock() | ||
1829 | with self.subTest(before=True, after=False): | ||
1830 | m.process(None, before=True) | ||
1831 | |||
1832 | process.assert_called_once_with("sell_all", steps="before") | ||
1833 | store_report.assert_called_once() | ||
1834 | log_error.assert_not_called() | ||
1835 | |||
1836 | process.reset_mock() | ||
1837 | log_error.reset_mock() | ||
1838 | store_report.reset_mock() | ||
1839 | with self.subTest(before=False, after=True): | ||
1840 | m.process(None, after=True) | ||
1841 | |||
1842 | process.assert_called_once_with("sell_all", steps="after") | ||
1843 | store_report.assert_called_once() | ||
1844 | log_error.assert_not_called() | ||
1845 | |||
1846 | process.reset_mock() | ||
1847 | log_error.reset_mock() | ||
1848 | store_report.reset_mock() | ||
1849 | with self.subTest(before=True, after=True): | ||
1850 | m.process(None, before=True, after=True) | ||
1851 | |||
1852 | process.assert_has_calls([ | ||
1853 | mock.call("sell_all", steps="before"), | ||
1854 | mock.call("sell_all", steps="after"), | ||
1855 | ]) | ||
1856 | store_report.assert_called_once() | ||
1857 | log_error.assert_not_called() | ||
1858 | |||
1859 | process.reset_mock() | ||
1860 | log_error.reset_mock() | ||
1861 | store_report.reset_mock() | ||
1862 | with self.subTest(action="print_balances"),\ | ||
1863 | mock.patch.object(m, "print_balances") as print_balances: | ||
1864 | m.process(["print_balances"]) | ||
1865 | |||
1866 | process.assert_not_called() | ||
1867 | log_error.assert_not_called() | ||
1868 | store_report.assert_called_once() | ||
1869 | print_balances.assert_called_once_with() | ||
1870 | |||
1871 | log_error.reset_mock() | ||
1872 | store_report.reset_mock() | ||
1873 | with self.subTest(action="print_orders"),\ | ||
1874 | mock.patch.object(m, "print_orders") as print_orders,\ | ||
1875 | mock.patch.object(m, "print_balances") as print_balances: | ||
1876 | m.process(["print_orders", "print_balances"]) | ||
1877 | |||
1878 | process.assert_not_called() | ||
1879 | log_error.assert_not_called() | ||
1880 | store_report.assert_called_once() | ||
1881 | print_orders.assert_called_once_with() | ||
1882 | print_balances.assert_called_once_with() | ||
1883 | |||
1884 | log_error.reset_mock() | ||
1885 | store_report.reset_mock() | ||
1886 | with self.subTest(action="unknown"): | ||
1887 | m.process(["unknown"]) | ||
1888 | log_error.assert_called_once_with("market_process", message="Unknown action unknown") | ||
1889 | store_report.assert_called_once() | ||
1890 | |||
1891 | log_error.reset_mock() | ||
1892 | store_report.reset_mock() | ||
1893 | with self.subTest(unhandled_exception=True): | ||
1894 | process.side_effect = Exception("bouh") | ||
1895 | |||
1896 | m.process(None, before=True) | ||
1897 | log_error.assert_called_with("market_process", exception=mock.ANY) | ||
1898 | store_report.assert_called_once() | ||
1899 | |||
1900 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1901 | class TradeStoreTest(WebMockTestCase): | ||
1902 | def test_compute_trades(self): | ||
1903 | self.m.balances.currencies.return_value = ["XMR", "DASH", "XVG", "BTC", "ETH"] | ||
1904 | |||
1905 | values_in_base = { | ||
1906 | "XMR": portfolio.Amount("BTC", D("0.9")), | ||
1907 | "DASH": portfolio.Amount("BTC", D("0.4")), | ||
1908 | "XVG": portfolio.Amount("BTC", D("-0.5")), | ||
1909 | "BTC": portfolio.Amount("BTC", D("0.5")), | ||
1910 | } | ||
1911 | new_repartition = { | ||
1912 | "DASH": portfolio.Amount("BTC", D("0.5")), | ||
1913 | "XVG": portfolio.Amount("BTC", D("0.1")), | ||
1914 | "BTC": portfolio.Amount("BTC", D("0.4")), | ||
1915 | "ETH": portfolio.Amount("BTC", D("0.3")), | ||
1916 | } | ||
1917 | side_effect = [ | ||
1918 | (True, 1), | ||
1919 | (False, 2), | ||
1920 | (False, 3), | ||
1921 | (True, 4), | ||
1922 | (True, 5) | ||
1923 | ] | ||
1924 | |||
1925 | with mock.patch.object(market.TradeStore, "trade_if_matching") as trade_if_matching: | ||
1926 | trade_store = market.TradeStore(self.m) | ||
1927 | trade_if_matching.side_effect = side_effect | ||
1928 | |||
1929 | trade_store.compute_trades(values_in_base, | ||
1930 | new_repartition, only="only") | ||
1931 | |||
1932 | self.assertEqual(5, trade_if_matching.call_count) | ||
1933 | self.assertEqual(3, len(trade_store.all)) | ||
1934 | self.assertEqual([1, 4, 5], trade_store.all) | ||
1935 | self.m.report.log_trades.assert_called_with(side_effect, "only") | ||
1936 | |||
1937 | def test_trade_if_matching(self): | ||
1938 | |||
1939 | with self.subTest(only="nope"): | ||
1940 | trade_store = market.TradeStore(self.m) | ||
1941 | result = trade_store.trade_if_matching( | ||
1942 | portfolio.Amount("BTC", D("0")), | ||
1943 | portfolio.Amount("BTC", D("0.3")), | ||
1944 | "ETH", only="nope") | ||
1945 | self.assertEqual(False, result[0]) | ||
1946 | self.assertIsInstance(result[1], portfolio.Trade) | ||
1947 | |||
1948 | with self.subTest(only=None): | ||
1949 | trade_store = market.TradeStore(self.m) | ||
1950 | result = trade_store.trade_if_matching( | ||
1951 | portfolio.Amount("BTC", D("0")), | ||
1952 | portfolio.Amount("BTC", D("0.3")), | ||
1953 | "ETH", only=None) | ||
1954 | self.assertEqual(True, result[0]) | ||
1955 | |||
1956 | with self.subTest(only="acquire"): | ||
1957 | trade_store = market.TradeStore(self.m) | ||
1958 | result = trade_store.trade_if_matching( | ||
1959 | portfolio.Amount("BTC", D("0")), | ||
1960 | portfolio.Amount("BTC", D("0.3")), | ||
1961 | "ETH", only="acquire") | ||
1962 | self.assertEqual(True, result[0]) | ||
1963 | |||
1964 | with self.subTest(only="dispose"): | ||
1965 | trade_store = market.TradeStore(self.m) | ||
1966 | result = trade_store.trade_if_matching( | ||
1967 | portfolio.Amount("BTC", D("0")), | ||
1968 | portfolio.Amount("BTC", D("0.3")), | ||
1969 | "ETH", only="dispose") | ||
1970 | self.assertEqual(False, result[0]) | ||
1971 | |||
1972 | def test_prepare_orders(self): | ||
1973 | trade_store = market.TradeStore(self.m) | ||
1974 | |||
1975 | trade_mock1 = mock.Mock() | ||
1976 | trade_mock2 = mock.Mock() | ||
1977 | trade_mock3 = mock.Mock() | ||
1978 | |||
1979 | trade_mock1.prepare_order.return_value = 1 | ||
1980 | trade_mock2.prepare_order.return_value = 2 | ||
1981 | trade_mock3.prepare_order.return_value = 3 | ||
1982 | |||
1983 | trade_mock1.pending = True | ||
1984 | trade_mock2.pending = True | ||
1985 | trade_mock3.pending = False | ||
1986 | |||
1987 | trade_store.all.append(trade_mock1) | ||
1988 | trade_store.all.append(trade_mock2) | ||
1989 | trade_store.all.append(trade_mock3) | ||
1990 | |||
1991 | trade_store.prepare_orders() | ||
1992 | trade_mock1.prepare_order.assert_called_with(compute_value="default") | ||
1993 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | ||
1994 | trade_mock3.prepare_order.assert_not_called() | ||
1995 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "default") | ||
1996 | |||
1997 | self.m.report.log_orders.reset_mock() | ||
1998 | |||
1999 | trade_store.prepare_orders(compute_value="bla") | ||
2000 | trade_mock1.prepare_order.assert_called_with(compute_value="bla") | ||
2001 | trade_mock2.prepare_order.assert_called_with(compute_value="bla") | ||
2002 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "bla") | ||
2003 | |||
2004 | trade_mock1.prepare_order.reset_mock() | ||
2005 | trade_mock2.prepare_order.reset_mock() | ||
2006 | self.m.report.log_orders.reset_mock() | ||
2007 | |||
2008 | trade_mock1.action = "foo" | ||
2009 | trade_mock2.action = "bar" | ||
2010 | trade_store.prepare_orders(only="bar") | ||
2011 | trade_mock1.prepare_order.assert_not_called() | ||
2012 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | ||
2013 | self.m.report.log_orders.assert_called_once_with([2], "bar", "default") | ||
2014 | |||
2015 | def test_print_all_with_order(self): | ||
2016 | trade_mock1 = mock.Mock() | ||
2017 | trade_mock2 = mock.Mock() | ||
2018 | trade_mock3 = mock.Mock() | ||
2019 | trade_store = market.TradeStore(self.m) | ||
2020 | trade_store.all = [trade_mock1, trade_mock2, trade_mock3] | ||
2021 | |||
2022 | trade_store.print_all_with_order() | ||
2023 | |||
2024 | trade_mock1.print_with_order.assert_called() | ||
2025 | trade_mock2.print_with_order.assert_called() | ||
2026 | trade_mock3.print_with_order.assert_called() | ||
2027 | |||
2028 | def test_run_orders(self): | ||
2029 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | ||
2030 | order_mock1 = mock.Mock() | ||
2031 | order_mock2 = mock.Mock() | ||
2032 | order_mock3 = mock.Mock() | ||
2033 | trade_store = market.TradeStore(self.m) | ||
2034 | |||
2035 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | ||
2036 | |||
2037 | trade_store.run_orders() | ||
2038 | |||
2039 | all_orders.assert_called_with(state="pending") | ||
2040 | |||
2041 | order_mock1.run.assert_called() | ||
2042 | order_mock2.run.assert_called() | ||
2043 | order_mock3.run.assert_called() | ||
2044 | |||
2045 | self.m.report.log_stage.assert_called_with("run_orders") | ||
2046 | self.m.report.log_orders.assert_called_with([order_mock1, order_mock2, | ||
2047 | order_mock3]) | ||
2048 | |||
2049 | def test_all_orders(self): | ||
2050 | trade_mock1 = mock.Mock() | ||
2051 | trade_mock2 = mock.Mock() | ||
2052 | |||
2053 | order_mock1 = mock.Mock() | ||
2054 | order_mock2 = mock.Mock() | ||
2055 | order_mock3 = mock.Mock() | ||
2056 | |||
2057 | trade_mock1.orders = [order_mock1, order_mock2] | ||
2058 | trade_mock2.orders = [order_mock3] | ||
2059 | |||
2060 | order_mock1.status = "pending" | ||
2061 | order_mock2.status = "open" | ||
2062 | order_mock3.status = "open" | ||
2063 | |||
2064 | trade_store = market.TradeStore(self.m) | ||
2065 | trade_store.all.append(trade_mock1) | ||
2066 | trade_store.all.append(trade_mock2) | ||
2067 | |||
2068 | orders = trade_store.all_orders() | ||
2069 | self.assertEqual(3, len(orders)) | ||
2070 | |||
2071 | open_orders = trade_store.all_orders(state="open") | ||
2072 | self.assertEqual(2, len(open_orders)) | ||
2073 | self.assertEqual([order_mock2, order_mock3], open_orders) | ||
2074 | |||
2075 | def test_update_all_orders_status(self): | ||
2076 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | ||
2077 | order_mock1 = mock.Mock() | ||
2078 | order_mock2 = mock.Mock() | ||
2079 | order_mock3 = mock.Mock() | ||
2080 | |||
2081 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | ||
2082 | |||
2083 | trade_store = market.TradeStore(self.m) | ||
2084 | |||
2085 | trade_store.update_all_orders_status() | ||
2086 | all_orders.assert_called_with(state="open") | ||
2087 | |||
2088 | order_mock1.get_status.assert_called() | ||
2089 | order_mock2.get_status.assert_called() | ||
2090 | order_mock3.get_status.assert_called() | ||
2091 | |||
2092 | def test_close_trades(self): | ||
2093 | trade_mock1 = mock.Mock() | ||
2094 | trade_mock2 = mock.Mock() | ||
2095 | trade_mock3 = mock.Mock() | ||
2096 | |||
2097 | trade_store = market.TradeStore(self.m) | ||
2098 | |||
2099 | trade_store.all.append(trade_mock1) | ||
2100 | trade_store.all.append(trade_mock2) | ||
2101 | trade_store.all.append(trade_mock3) | ||
2102 | |||
2103 | trade_store.close_trades() | ||
2104 | |||
2105 | trade_mock1.close.assert_called_once_with() | ||
2106 | trade_mock2.close.assert_called_once_with() | ||
2107 | trade_mock3.close.assert_called_once_with() | ||
2108 | |||
2109 | def test_pending(self): | ||
2110 | trade_mock1 = mock.Mock() | ||
2111 | trade_mock1.pending = True | ||
2112 | trade_mock2 = mock.Mock() | ||
2113 | trade_mock2.pending = True | ||
2114 | trade_mock3 = mock.Mock() | ||
2115 | trade_mock3.pending = False | ||
2116 | |||
2117 | trade_store = market.TradeStore(self.m) | ||
2118 | |||
2119 | trade_store.all.append(trade_mock1) | ||
2120 | trade_store.all.append(trade_mock2) | ||
2121 | trade_store.all.append(trade_mock3) | ||
2122 | |||
2123 | self.assertEqual([trade_mock1, trade_mock2], trade_store.pending) | ||
2124 | |||
2125 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
2126 | class BalanceStoreTest(WebMockTestCase): | ||
2127 | def setUp(self): | ||
2128 | super().setUp() | ||
2129 | |||
2130 | self.fetch_balance = { | ||
2131 | "ETC": { | ||
2132 | "exchange_free": 0, | ||
2133 | "exchange_used": 0, | ||
2134 | "exchange_total": 0, | ||
2135 | "margin_total": 0, | ||
2136 | }, | ||
2137 | "USDT": { | ||
2138 | "exchange_free": D("6.0"), | ||
2139 | "exchange_used": D("1.2"), | ||
2140 | "exchange_total": D("7.2"), | ||
2141 | "margin_total": 0, | ||
2142 | }, | ||
2143 | "XVG": { | ||
2144 | "exchange_free": 16, | ||
2145 | "exchange_used": 0, | ||
2146 | "exchange_total": 16, | ||
2147 | "margin_total": 0, | ||
2148 | }, | ||
2149 | "XMR": { | ||
2150 | "exchange_free": 0, | ||
2151 | "exchange_used": 0, | ||
2152 | "exchange_total": 0, | ||
2153 | "margin_total": D("-1.0"), | ||
2154 | "margin_free": 0, | ||
2155 | }, | ||
2156 | } | ||
2157 | |||
2158 | def test_in_currency(self): | ||
2159 | self.m.get_ticker.return_value = { | ||
2160 | "bid": D("0.09"), | ||
2161 | "ask": D("0.11"), | ||
2162 | "average": D("0.1"), | ||
2163 | } | ||
2164 | |||
2165 | balance_store = market.BalanceStore(self.m) | ||
2166 | balance_store.all = { | ||
2167 | "BTC": portfolio.Balance("BTC", { | ||
2168 | "total": "0.65", | ||
2169 | "exchange_total":"0.65", | ||
2170 | "exchange_free": "0.35", | ||
2171 | "exchange_used": "0.30"}), | ||
2172 | "ETH": portfolio.Balance("ETH", { | ||
2173 | "total": 3, | ||
2174 | "exchange_total": 3, | ||
2175 | "exchange_free": 3, | ||
2176 | "exchange_used": 0}), | ||
2177 | } | ||
2178 | |||
2179 | amounts = balance_store.in_currency("BTC") | ||
2180 | self.assertEqual("BTC", amounts["ETH"].currency) | ||
2181 | self.assertEqual(D("0.65"), amounts["BTC"].value) | ||
2182 | self.assertEqual(D("0.30"), amounts["ETH"].value) | ||
2183 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
2184 | "average", "total") | ||
2185 | self.m.report.log_tickers.reset_mock() | ||
2186 | |||
2187 | amounts = balance_store.in_currency("BTC", compute_value="bid") | ||
2188 | self.assertEqual(D("0.65"), amounts["BTC"].value) | ||
2189 | self.assertEqual(D("0.27"), amounts["ETH"].value) | ||
2190 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
2191 | "bid", "total") | ||
2192 | self.m.report.log_tickers.reset_mock() | ||
2193 | |||
2194 | amounts = balance_store.in_currency("BTC", compute_value="bid", type="exchange_used") | ||
2195 | self.assertEqual(D("0.30"), amounts["BTC"].value) | ||
2196 | self.assertEqual(0, amounts["ETH"].value) | ||
2197 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
2198 | "bid", "exchange_used") | ||
2199 | self.m.report.log_tickers.reset_mock() | ||
2200 | |||
2201 | def test_fetch_balances(self): | ||
2202 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | ||
2203 | |||
2204 | balance_store = market.BalanceStore(self.m) | ||
2205 | |||
2206 | balance_store.fetch_balances() | ||
2207 | self.assertNotIn("ETC", balance_store.currencies()) | ||
2208 | self.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store.currencies())) | ||
2209 | |||
2210 | balance_store.all["ETC"] = portfolio.Balance("ETC", { | ||
2211 | "exchange_total": "1", "exchange_free": "0", | ||
2212 | "exchange_used": "1" }) | ||
2213 | balance_store.fetch_balances(tag="foo") | ||
2214 | self.assertEqual(0, balance_store.all["ETC"].total) | ||
2215 | self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies())) | ||
2216 | self.m.report.log_balances.assert_called_with(tag="foo") | ||
2217 | |||
2218 | @mock.patch.object(market.Portfolio, "repartition") | ||
2219 | def test_dispatch_assets(self, repartition): | ||
2220 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | ||
2221 | |||
2222 | balance_store = market.BalanceStore(self.m) | ||
2223 | balance_store.fetch_balances() | ||
2224 | |||
2225 | self.assertNotIn("XEM", balance_store.currencies()) | ||
2226 | |||
2227 | repartition_hash = { | ||
2228 | "XEM": (D("0.75"), "long"), | ||
2229 | "BTC": (D("0.26"), "long"), | ||
2230 | "DASH": (D("0.10"), "short"), | ||
2231 | } | ||
2232 | repartition.return_value = repartition_hash | ||
2233 | |||
2234 | amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1")) | ||
2235 | repartition.assert_called_with(liquidity="medium") | ||
2236 | self.assertIn("XEM", balance_store.currencies()) | ||
2237 | self.assertEqual(D("2.6"), amounts["BTC"].value) | ||
2238 | self.assertEqual(D("7.5"), amounts["XEM"].value) | ||
2239 | self.assertEqual(D("-1.0"), amounts["DASH"].value) | ||
2240 | self.m.report.log_balances.assert_called_with(tag=None) | ||
2241 | self.m.report.log_dispatch.assert_called_once_with(portfolio.Amount("BTC", | ||
2242 | "11.1"), amounts, "medium", repartition_hash) | ||
2243 | |||
2244 | def test_currencies(self): | ||
2245 | balance_store = market.BalanceStore(self.m) | ||
2246 | |||
2247 | balance_store.all = { | ||
2248 | "BTC": portfolio.Balance("BTC", { | ||
2249 | "total": "0.65", | ||
2250 | "exchange_total":"0.65", | ||
2251 | "exchange_free": "0.35", | ||
2252 | "exchange_used": "0.30"}), | ||
2253 | "ETH": portfolio.Balance("ETH", { | ||
2254 | "total": 3, | ||
2255 | "exchange_total": 3, | ||
2256 | "exchange_free": 3, | ||
2257 | "exchange_used": 0}), | ||
2258 | } | ||
2259 | self.assertListEqual(["BTC", "ETH"], list(balance_store.currencies())) | ||
2260 | |||
2261 | def test_as_json(self): | ||
2262 | balance_mock1 = mock.Mock() | ||
2263 | balance_mock1.as_json.return_value = 1 | ||
2264 | |||
2265 | balance_mock2 = mock.Mock() | ||
2266 | balance_mock2.as_json.return_value = 2 | ||
2267 | |||
2268 | balance_store = market.BalanceStore(self.m) | ||
2269 | balance_store.all = { | ||
2270 | "BTC": balance_mock1, | ||
2271 | "ETH": balance_mock2, | ||
2272 | } | ||
2273 | |||
2274 | as_json = balance_store.as_json() | ||
2275 | self.assertEqual(1, as_json["BTC"]) | ||
2276 | self.assertEqual(2, as_json["ETH"]) | ||
2277 | |||
2278 | |||
2279 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
2280 | class ComputationTest(WebMockTestCase): | ||
2281 | def test_compute_value(self): | ||
2282 | compute = mock.Mock() | ||
2283 | portfolio.Computation.compute_value("foo", "buy", compute_value=compute) | ||
2284 | compute.assert_called_with("foo", "ask") | ||
2285 | |||
2286 | compute.reset_mock() | ||
2287 | portfolio.Computation.compute_value("foo", "sell", compute_value=compute) | ||
2288 | compute.assert_called_with("foo", "bid") | ||
2289 | |||
2290 | compute.reset_mock() | ||
2291 | portfolio.Computation.compute_value("foo", "ask", compute_value=compute) | ||
2292 | compute.assert_called_with("foo", "ask") | ||
2293 | |||
2294 | compute.reset_mock() | ||
2295 | portfolio.Computation.compute_value("foo", "bid", compute_value=compute) | ||
2296 | compute.assert_called_with("foo", "bid") | ||
2297 | |||
2298 | compute.reset_mock() | ||
2299 | portfolio.Computation.computations["test"] = compute | ||
2300 | portfolio.Computation.compute_value("foo", "bid", compute_value="test") | ||
2301 | compute.assert_called_with("foo", "bid") | ||
2302 | |||
2303 | |||
2304 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
2305 | class TradeTest(WebMockTestCase): | ||
2306 | |||
2307 | def test_values_assertion(self): | ||
2308 | value_from = portfolio.Amount("BTC", "1.0") | ||
2309 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2310 | value_to = portfolio.Amount("BTC", "1.0") | ||
2311 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2312 | self.assertEqual("BTC", trade.base_currency) | ||
2313 | self.assertEqual("ETH", trade.currency) | ||
2314 | self.assertEqual(self.m, trade.market) | ||
2315 | |||
2316 | with self.assertRaises(AssertionError): | ||
2317 | portfolio.Trade(value_from, -value_to, "ETH", self.m) | ||
2318 | with self.assertRaises(AssertionError): | ||
2319 | portfolio.Trade(value_from, value_to, "ETC", self.m) | ||
2320 | with self.assertRaises(AssertionError): | ||
2321 | value_from.currency = "ETH" | ||
2322 | portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2323 | value_from.currency = "BTC" | ||
2324 | with self.assertRaises(AssertionError): | ||
2325 | value_from2 = portfolio.Amount("BTC", "1.0") | ||
2326 | portfolio.Trade(value_from2, value_to, "ETH", self.m) | ||
2327 | |||
2328 | value_from = portfolio.Amount("BTC", 0) | ||
2329 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2330 | self.assertEqual(0, trade.value_from.linked_to) | ||
2331 | |||
2332 | def test_action(self): | ||
2333 | value_from = portfolio.Amount("BTC", "1.0") | ||
2334 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2335 | value_to = portfolio.Amount("BTC", "1.0") | ||
2336 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2337 | |||
2338 | self.assertIsNone(trade.action) | ||
2339 | |||
2340 | value_from = portfolio.Amount("BTC", "1.0") | ||
2341 | value_from.linked_to = portfolio.Amount("BTC", "1.0") | ||
2342 | value_to = portfolio.Amount("BTC", "2.0") | ||
2343 | trade = portfolio.Trade(value_from, value_to, "BTC", self.m) | ||
2344 | |||
2345 | self.assertIsNone(trade.action) | ||
2346 | |||
2347 | value_from = portfolio.Amount("BTC", "0.5") | ||
2348 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2349 | value_to = portfolio.Amount("BTC", "1.0") | ||
2350 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2351 | |||
2352 | self.assertEqual("acquire", trade.action) | ||
2353 | |||
2354 | value_from = portfolio.Amount("BTC", "0") | ||
2355 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
2356 | value_to = portfolio.Amount("BTC", "-1.0") | ||
2357 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2358 | |||
2359 | self.assertEqual("acquire", trade.action) | ||
2360 | |||
2361 | def test_order_action(self): | ||
2362 | value_from = portfolio.Amount("BTC", "0.5") | ||
2363 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2364 | value_to = portfolio.Amount("BTC", "1.0") | ||
2365 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2366 | |||
2367 | trade.inverted = False | ||
2368 | self.assertEqual("buy", trade.order_action()) | ||
2369 | trade.inverted = True | ||
2370 | self.assertEqual("sell", trade.order_action()) | ||
2371 | |||
2372 | value_from = portfolio.Amount("BTC", "0") | ||
2373 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
2374 | value_to = portfolio.Amount("BTC", "-1.0") | ||
2375 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2376 | |||
2377 | trade.inverted = False | ||
2378 | self.assertEqual("sell", trade.order_action()) | ||
2379 | trade.inverted = True | ||
2380 | self.assertEqual("buy", trade.order_action()) | ||
2381 | |||
2382 | def test_trade_type(self): | ||
2383 | value_from = portfolio.Amount("BTC", "0.5") | ||
2384 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2385 | value_to = portfolio.Amount("BTC", "1.0") | ||
2386 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2387 | |||
2388 | self.assertEqual("long", trade.trade_type) | ||
2389 | |||
2390 | value_from = portfolio.Amount("BTC", "0") | ||
2391 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
2392 | value_to = portfolio.Amount("BTC", "-1.0") | ||
2393 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2394 | |||
2395 | self.assertEqual("short", trade.trade_type) | ||
2396 | |||
2397 | def test_is_fullfiled(self): | ||
2398 | with self.subTest(inverted=False): | ||
2399 | value_from = portfolio.Amount("BTC", "0.5") | ||
2400 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2401 | value_to = portfolio.Amount("BTC", "1.0") | ||
2402 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2403 | |||
2404 | order1 = mock.Mock() | ||
2405 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3") | ||
2406 | |||
2407 | order2 = mock.Mock() | ||
2408 | order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01") | ||
2409 | trade.orders.append(order1) | ||
2410 | trade.orders.append(order2) | ||
2411 | |||
2412 | self.assertFalse(trade.is_fullfiled) | ||
2413 | |||
2414 | order3 = mock.Mock() | ||
2415 | order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19") | ||
2416 | trade.orders.append(order3) | ||
2417 | |||
2418 | self.assertTrue(trade.is_fullfiled) | ||
2419 | |||
2420 | order1.filled_amount.assert_called_with(in_base_currency=True) | ||
2421 | order2.filled_amount.assert_called_with(in_base_currency=True) | ||
2422 | order3.filled_amount.assert_called_with(in_base_currency=True) | ||
2423 | |||
2424 | with self.subTest(inverted=True): | ||
2425 | value_from = portfolio.Amount("BTC", "0.5") | ||
2426 | value_from.linked_to = portfolio.Amount("USDT", "1000.0") | ||
2427 | value_to = portfolio.Amount("BTC", "1.0") | ||
2428 | trade = portfolio.Trade(value_from, value_to, "USDT", self.m) | ||
2429 | trade.inverted = True | ||
2430 | |||
2431 | order1 = mock.Mock() | ||
2432 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3") | ||
2433 | |||
2434 | order2 = mock.Mock() | ||
2435 | order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01") | ||
2436 | trade.orders.append(order1) | ||
2437 | trade.orders.append(order2) | ||
2438 | |||
2439 | self.assertFalse(trade.is_fullfiled) | ||
2440 | |||
2441 | order3 = mock.Mock() | ||
2442 | order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19") | ||
2443 | trade.orders.append(order3) | ||
2444 | |||
2445 | self.assertTrue(trade.is_fullfiled) | ||
2446 | |||
2447 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
2448 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
2449 | order3.filled_amount.assert_called_with(in_base_currency=False) | ||
2450 | |||
2451 | |||
2452 | def test_filled_amount(self): | ||
2453 | value_from = portfolio.Amount("BTC", "0.5") | ||
2454 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2455 | value_to = portfolio.Amount("BTC", "1.0") | ||
2456 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2457 | |||
2458 | order1 = mock.Mock() | ||
2459 | order1.filled_amount.return_value = portfolio.Amount("ETH", "0.3") | ||
2460 | |||
2461 | order2 = mock.Mock() | ||
2462 | order2.filled_amount.return_value = portfolio.Amount("ETH", "0.01") | ||
2463 | trade.orders.append(order1) | ||
2464 | trade.orders.append(order2) | ||
2465 | |||
2466 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount()) | ||
2467 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
2468 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
2469 | |||
2470 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=False)) | ||
2471 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
2472 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
2473 | |||
2474 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=True)) | ||
2475 | order1.filled_amount.assert_called_with(in_base_currency=True) | ||
2476 | order2.filled_amount.assert_called_with(in_base_currency=True) | ||
2477 | |||
2478 | @mock.patch.object(portfolio.Computation, "compute_value") | ||
2479 | @mock.patch.object(portfolio.Trade, "filled_amount") | ||
2480 | @mock.patch.object(portfolio, "Order") | ||
2481 | def test_prepare_order(self, Order, filled_amount, compute_value): | ||
2482 | Order.return_value = "Order" | ||
2483 | |||
2484 | with self.subTest(desc="Nothing to do"): | ||
2485 | value_from = portfolio.Amount("BTC", "10") | ||
2486 | value_from.rate = D("0.1") | ||
2487 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
2488 | value_to = portfolio.Amount("BTC", "10") | ||
2489 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2490 | |||
2491 | trade.prepare_order() | ||
2492 | |||
2493 | filled_amount.assert_not_called() | ||
2494 | compute_value.assert_not_called() | ||
2495 | self.assertEqual(0, len(trade.orders)) | ||
2496 | Order.assert_not_called() | ||
2497 | |||
2498 | self.m.get_ticker.return_value = { "inverted": False } | ||
2499 | with self.subTest(desc="Already filled"): | ||
2500 | filled_amount.return_value = portfolio.Amount("FOO", "100") | ||
2501 | compute_value.return_value = D("0.125") | ||
2502 | |||
2503 | value_from = portfolio.Amount("BTC", "10") | ||
2504 | value_from.rate = D("0.1") | ||
2505 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
2506 | value_to = portfolio.Amount("BTC", "0") | ||
2507 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2508 | |||
2509 | trade.prepare_order() | ||
2510 | |||
2511 | filled_amount.assert_called_with(in_base_currency=False) | ||
2512 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
2513 | self.assertEqual(0, len(trade.orders)) | ||
2514 | self.m.report.log_error.assert_called_with("prepare_order", message=mock.ANY) | ||
2515 | Order.assert_not_called() | ||
2516 | |||
2517 | with self.subTest(action="dispose", inverted=False): | ||
2518 | filled_amount.return_value = portfolio.Amount("FOO", "60") | ||
2519 | compute_value.return_value = D("0.125") | ||
2520 | |||
2521 | value_from = portfolio.Amount("BTC", "10") | ||
2522 | value_from.rate = D("0.1") | ||
2523 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
2524 | value_to = portfolio.Amount("BTC", "1") | ||
2525 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2526 | |||
2527 | trade.prepare_order() | ||
2528 | |||
2529 | filled_amount.assert_called_with(in_base_currency=False) | ||
2530 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
2531 | self.assertEqual(1, len(trade.orders)) | ||
2532 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | ||
2533 | D("0.125"), "BTC", "long", self.m, | ||
2534 | trade, close_if_possible=False) | ||
2535 | |||
2536 | with self.subTest(action="dispose", inverted=False, close_if_possible=True): | ||
2537 | filled_amount.return_value = portfolio.Amount("FOO", "60") | ||
2538 | compute_value.return_value = D("0.125") | ||
2539 | |||
2540 | value_from = portfolio.Amount("BTC", "10") | ||
2541 | value_from.rate = D("0.1") | ||
2542 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
2543 | value_to = portfolio.Amount("BTC", "1") | ||
2544 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2545 | |||
2546 | trade.prepare_order(close_if_possible=True) | ||
2547 | |||
2548 | filled_amount.assert_called_with(in_base_currency=False) | ||
2549 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
2550 | self.assertEqual(1, len(trade.orders)) | ||
2551 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | ||
2552 | D("0.125"), "BTC", "long", self.m, | ||
2553 | trade, close_if_possible=True) | ||
2554 | |||
2555 | with self.subTest(action="acquire", inverted=False): | ||
2556 | filled_amount.return_value = portfolio.Amount("BTC", "3") | ||
2557 | compute_value.return_value = D("0.125") | ||
2558 | |||
2559 | value_from = portfolio.Amount("BTC", "1") | ||
2560 | value_from.rate = D("0.1") | ||
2561 | value_from.linked_to = portfolio.Amount("FOO", "10") | ||
2562 | value_to = portfolio.Amount("BTC", "10") | ||
2563 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2564 | |||
2565 | trade.prepare_order() | ||
2566 | |||
2567 | filled_amount.assert_called_with(in_base_currency=True) | ||
2568 | compute_value.assert_called_with(self.m.get_ticker.return_value, "buy", compute_value="default") | ||
2569 | self.assertEqual(1, len(trade.orders)) | ||
2570 | |||
2571 | Order.assert_called_with("buy", portfolio.Amount("FOO", 48), | ||
2572 | D("0.125"), "BTC", "long", self.m, | ||
2573 | trade, close_if_possible=False) | ||
2574 | |||
2575 | with self.subTest(close_if_possible=True): | ||
2576 | filled_amount.return_value = portfolio.Amount("FOO", "0") | ||
2577 | compute_value.return_value = D("0.125") | ||
2578 | |||
2579 | value_from = portfolio.Amount("BTC", "10") | ||
2580 | value_from.rate = D("0.1") | ||
2581 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
2582 | value_to = portfolio.Amount("BTC", "0") | ||
2583 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2584 | |||
2585 | trade.prepare_order() | ||
2586 | |||
2587 | filled_amount.assert_called_with(in_base_currency=False) | ||
2588 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
2589 | self.assertEqual(1, len(trade.orders)) | ||
2590 | Order.assert_called_with("sell", portfolio.Amount("FOO", 100), | ||
2591 | D("0.125"), "BTC", "long", self.m, | ||
2592 | trade, close_if_possible=True) | ||
2593 | |||
2594 | self.m.get_ticker.return_value = { "inverted": True, "original": {} } | ||
2595 | with self.subTest(action="dispose", inverted=True): | ||
2596 | filled_amount.return_value = portfolio.Amount("FOO", "300") | ||
2597 | compute_value.return_value = D("125") | ||
2598 | |||
2599 | value_from = portfolio.Amount("BTC", "10") | ||
2600 | value_from.rate = D("0.01") | ||
2601 | value_from.linked_to = portfolio.Amount("FOO", "1000") | ||
2602 | value_to = portfolio.Amount("BTC", "1") | ||
2603 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2604 | |||
2605 | trade.prepare_order(compute_value="foo") | ||
2606 | |||
2607 | filled_amount.assert_called_with(in_base_currency=True) | ||
2608 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "buy", compute_value="foo") | ||
2609 | self.assertEqual(1, len(trade.orders)) | ||
2610 | Order.assert_called_with("buy", portfolio.Amount("BTC", D("4.8")), | ||
2611 | D("125"), "FOO", "long", self.m, | ||
2612 | trade, close_if_possible=False) | ||
2613 | |||
2614 | with self.subTest(action="acquire", inverted=True): | ||
2615 | filled_amount.return_value = portfolio.Amount("BTC", "4") | ||
2616 | compute_value.return_value = D("125") | ||
2617 | |||
2618 | value_from = portfolio.Amount("BTC", "1") | ||
2619 | value_from.rate = D("0.01") | ||
2620 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
2621 | value_to = portfolio.Amount("BTC", "10") | ||
2622 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
2623 | |||
2624 | trade.prepare_order(compute_value="foo") | ||
2625 | |||
2626 | filled_amount.assert_called_with(in_base_currency=False) | ||
2627 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "sell", compute_value="foo") | ||
2628 | self.assertEqual(1, len(trade.orders)) | ||
2629 | Order.assert_called_with("sell", portfolio.Amount("BTC", D("5")), | ||
2630 | D("125"), "FOO", "long", self.m, | ||
2631 | trade, close_if_possible=False) | ||
2632 | |||
2633 | def test_tick_actions_recreate(self): | ||
2634 | value_from = portfolio.Amount("BTC", "0.5") | ||
2635 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2636 | value_to = portfolio.Amount("BTC", "1.0") | ||
2637 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2638 | |||
2639 | self.assertEqual("average", trade.tick_actions_recreate(0)) | ||
2640 | self.assertEqual("foo", trade.tick_actions_recreate(0, default="foo")) | ||
2641 | self.assertEqual("average", trade.tick_actions_recreate(1)) | ||
2642 | self.assertEqual(trade.tick_actions[2][1], trade.tick_actions_recreate(2)) | ||
2643 | self.assertEqual(trade.tick_actions[2][1], trade.tick_actions_recreate(3)) | ||
2644 | self.assertEqual(trade.tick_actions[5][1], trade.tick_actions_recreate(5)) | ||
2645 | self.assertEqual(trade.tick_actions[5][1], trade.tick_actions_recreate(6)) | ||
2646 | self.assertEqual("default", trade.tick_actions_recreate(7)) | ||
2647 | self.assertEqual("default", trade.tick_actions_recreate(8)) | ||
2648 | |||
2649 | @mock.patch.object(portfolio.Trade, "prepare_order") | ||
2650 | def test_update_order(self, prepare_order): | ||
2651 | order_mock = mock.Mock() | ||
2652 | new_order_mock = mock.Mock() | ||
2653 | |||
2654 | value_from = portfolio.Amount("BTC", "0.5") | ||
2655 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2656 | value_to = portfolio.Amount("BTC", "1.0") | ||
2657 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2658 | prepare_order.return_value = new_order_mock | ||
2659 | |||
2660 | for i in [0, 1, 3, 4, 6]: | ||
2661 | with self.subTest(tick=i): | ||
2662 | trade.update_order(order_mock, i) | ||
2663 | order_mock.cancel.assert_not_called() | ||
2664 | new_order_mock.run.assert_not_called() | ||
2665 | self.m.report.log_order.assert_called_once_with(order_mock, i, | ||
2666 | update="waiting", compute_value=None, new_order=None) | ||
2667 | |||
2668 | order_mock.reset_mock() | ||
2669 | new_order_mock.reset_mock() | ||
2670 | trade.orders = [] | ||
2671 | self.m.report.log_order.reset_mock() | ||
2672 | |||
2673 | trade.update_order(order_mock, 2) | ||
2674 | order_mock.cancel.assert_called() | ||
2675 | new_order_mock.run.assert_called() | ||
2676 | prepare_order.assert_called() | ||
2677 | self.m.report.log_order.assert_called() | ||
2678 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
2679 | calls = [ | ||
2680 | mock.call(order_mock, 2, update="adjusting", | ||
2681 | compute_value=mock.ANY, | ||
2682 | new_order=new_order_mock), | ||
2683 | mock.call(order_mock, 2, new_order=new_order_mock), | ||
2684 | ] | ||
2685 | self.m.report.log_order.assert_has_calls(calls) | ||
2686 | |||
2687 | order_mock.reset_mock() | ||
2688 | new_order_mock.reset_mock() | ||
2689 | trade.orders = [] | ||
2690 | self.m.report.log_order.reset_mock() | ||
2691 | |||
2692 | trade.update_order(order_mock, 5) | ||
2693 | order_mock.cancel.assert_called() | ||
2694 | new_order_mock.run.assert_called() | ||
2695 | prepare_order.assert_called() | ||
2696 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
2697 | self.m.report.log_order.assert_called() | ||
2698 | calls = [ | ||
2699 | mock.call(order_mock, 5, update="adjusting", | ||
2700 | compute_value=mock.ANY, | ||
2701 | new_order=new_order_mock), | ||
2702 | mock.call(order_mock, 5, new_order=new_order_mock), | ||
2703 | ] | ||
2704 | self.m.report.log_order.assert_has_calls(calls) | ||
2705 | |||
2706 | order_mock.reset_mock() | ||
2707 | new_order_mock.reset_mock() | ||
2708 | trade.orders = [] | ||
2709 | self.m.report.log_order.reset_mock() | ||
2710 | |||
2711 | trade.update_order(order_mock, 7) | ||
2712 | order_mock.cancel.assert_called() | ||
2713 | new_order_mock.run.assert_called() | ||
2714 | prepare_order.assert_called_with(compute_value="default") | ||
2715 | self.m.report.log_order.assert_called() | ||
2716 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
2717 | calls = [ | ||
2718 | mock.call(order_mock, 7, update="market_fallback", | ||
2719 | compute_value='default', | ||
2720 | new_order=new_order_mock), | ||
2721 | mock.call(order_mock, 7, new_order=new_order_mock), | ||
2722 | ] | ||
2723 | self.m.report.log_order.assert_has_calls(calls) | ||
2724 | |||
2725 | order_mock.reset_mock() | ||
2726 | new_order_mock.reset_mock() | ||
2727 | trade.orders = [] | ||
2728 | self.m.report.log_order.reset_mock() | ||
2729 | |||
2730 | for i in [10, 13, 16]: | ||
2731 | with self.subTest(tick=i): | ||
2732 | trade.update_order(order_mock, i) | ||
2733 | order_mock.cancel.assert_called() | ||
2734 | new_order_mock.run.assert_called() | ||
2735 | prepare_order.assert_called_with(compute_value="default") | ||
2736 | self.m.report.log_order.assert_called() | ||
2737 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
2738 | calls = [ | ||
2739 | mock.call(order_mock, i, update="market_adjust", | ||
2740 | compute_value='default', | ||
2741 | new_order=new_order_mock), | ||
2742 | mock.call(order_mock, i, new_order=new_order_mock), | ||
2743 | ] | ||
2744 | self.m.report.log_order.assert_has_calls(calls) | ||
2745 | |||
2746 | order_mock.reset_mock() | ||
2747 | new_order_mock.reset_mock() | ||
2748 | trade.orders = [] | ||
2749 | self.m.report.log_order.reset_mock() | ||
2750 | |||
2751 | for i in [8, 9, 11, 12]: | ||
2752 | with self.subTest(tick=i): | ||
2753 | trade.update_order(order_mock, i) | ||
2754 | order_mock.cancel.assert_not_called() | ||
2755 | new_order_mock.run.assert_not_called() | ||
2756 | self.m.report.log_order.assert_called_once_with(order_mock, i, update="waiting", | ||
2757 | compute_value=None, new_order=None) | ||
2758 | |||
2759 | order_mock.reset_mock() | ||
2760 | new_order_mock.reset_mock() | ||
2761 | trade.orders = [] | ||
2762 | self.m.report.log_order.reset_mock() | ||
2763 | |||
2764 | |||
2765 | def test_print_with_order(self): | ||
2766 | value_from = portfolio.Amount("BTC", "0.5") | ||
2767 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2768 | value_to = portfolio.Amount("BTC", "1.0") | ||
2769 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2770 | |||
2771 | order_mock1 = mock.Mock() | ||
2772 | order_mock1.__repr__ = mock.Mock() | ||
2773 | order_mock1.__repr__.return_value = "Mock 1" | ||
2774 | order_mock2 = mock.Mock() | ||
2775 | order_mock2.__repr__ = mock.Mock() | ||
2776 | order_mock2.__repr__.return_value = "Mock 2" | ||
2777 | order_mock1.mouvements = [] | ||
2778 | mouvement_mock1 = mock.Mock() | ||
2779 | mouvement_mock1.__repr__ = mock.Mock() | ||
2780 | mouvement_mock1.__repr__.return_value = "Mouvement 1" | ||
2781 | mouvement_mock2 = mock.Mock() | ||
2782 | mouvement_mock2.__repr__ = mock.Mock() | ||
2783 | mouvement_mock2.__repr__.return_value = "Mouvement 2" | ||
2784 | order_mock2.mouvements = [ | ||
2785 | mouvement_mock1, mouvement_mock2 | ||
2786 | ] | ||
2787 | trade.orders.append(order_mock1) | ||
2788 | trade.orders.append(order_mock2) | ||
2789 | |||
2790 | with mock.patch.object(trade, "filled_amount") as filled: | ||
2791 | filled.return_value = portfolio.Amount("BTC", "0.1") | ||
2792 | |||
2793 | trade.print_with_order() | ||
2794 | |||
2795 | self.m.report.print_log.assert_called() | ||
2796 | calls = self.m.report.print_log.mock_calls | ||
2797 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls[0][1][0])) | ||
2798 | self.assertEqual("\tMock 1", str(calls[1][1][0])) | ||
2799 | self.assertEqual("\tMock 2", str(calls[2][1][0])) | ||
2800 | self.assertEqual("\t\tMouvement 1", str(calls[3][1][0])) | ||
2801 | self.assertEqual("\t\tMouvement 2", str(calls[4][1][0])) | ||
2802 | |||
2803 | self.m.report.print_log.reset_mock() | ||
2804 | |||
2805 | filled.return_value = portfolio.Amount("BTC", "0.5") | ||
2806 | trade.print_with_order() | ||
2807 | calls = self.m.report.print_log.mock_calls | ||
2808 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls[0][1][0])) | ||
2809 | |||
2810 | self.m.report.print_log.reset_mock() | ||
2811 | |||
2812 | filled.return_value = portfolio.Amount("BTC", "0.1") | ||
2813 | trade.closed = True | ||
2814 | trade.print_with_order() | ||
2815 | calls = self.m.report.print_log.mock_calls | ||
2816 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls[0][1][0])) | ||
2817 | |||
2818 | def test_close(self): | ||
2819 | value_from = portfolio.Amount("BTC", "0.5") | ||
2820 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2821 | value_to = portfolio.Amount("BTC", "1.0") | ||
2822 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2823 | order1 = mock.Mock() | ||
2824 | trade.orders.append(order1) | ||
2825 | |||
2826 | trade.close() | ||
2827 | |||
2828 | self.assertEqual(True, trade.closed) | ||
2829 | order1.cancel.assert_called_once_with() | ||
2830 | |||
2831 | def test_pending(self): | ||
2832 | value_from = portfolio.Amount("BTC", "0.5") | ||
2833 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2834 | value_to = portfolio.Amount("BTC", "1.0") | ||
2835 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2836 | |||
2837 | trade.closed = True | ||
2838 | self.assertEqual(False, trade.pending) | ||
2839 | |||
2840 | trade.closed = False | ||
2841 | self.assertEqual(True, trade.pending) | ||
2842 | |||
2843 | order1 = mock.Mock() | ||
2844 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.5") | ||
2845 | trade.orders.append(order1) | ||
2846 | self.assertEqual(False, trade.pending) | ||
2847 | |||
2848 | def test__repr(self): | ||
2849 | value_from = portfolio.Amount("BTC", "0.5") | ||
2850 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2851 | value_to = portfolio.Amount("BTC", "1.0") | ||
2852 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2853 | |||
2854 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade)) | ||
2855 | |||
2856 | def test_as_json(self): | ||
2857 | value_from = portfolio.Amount("BTC", "0.5") | ||
2858 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
2859 | value_to = portfolio.Amount("BTC", "1.0") | ||
2860 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
2861 | |||
2862 | as_json = trade.as_json() | ||
2863 | self.assertEqual("acquire", as_json["action"]) | ||
2864 | self.assertEqual(D("0.5"), as_json["from"]) | ||
2865 | self.assertEqual(D("1.0"), as_json["to"]) | ||
2866 | self.assertEqual("ETH", as_json["currency"]) | ||
2867 | self.assertEqual("BTC", as_json["base_currency"]) | ||
2868 | |||
2869 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
2870 | class OrderTest(WebMockTestCase): | ||
2871 | def test_values(self): | ||
2872 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2873 | D("0.1"), "BTC", "long", "market", "trade") | ||
2874 | self.assertEqual("buy", order.action) | ||
2875 | self.assertEqual(10, order.amount.value) | ||
2876 | self.assertEqual("ETH", order.amount.currency) | ||
2877 | self.assertEqual(D("0.1"), order.rate) | ||
2878 | self.assertEqual("BTC", order.base_currency) | ||
2879 | self.assertEqual("market", order.market) | ||
2880 | self.assertEqual("long", order.trade_type) | ||
2881 | self.assertEqual("pending", order.status) | ||
2882 | self.assertEqual("trade", order.trade) | ||
2883 | self.assertIsNone(order.id) | ||
2884 | self.assertFalse(order.close_if_possible) | ||
2885 | |||
2886 | def test__repr(self): | ||
2887 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2888 | D("0.1"), "BTC", "long", "market", "trade") | ||
2889 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order)) | ||
2890 | |||
2891 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2892 | D("0.1"), "BTC", "long", "market", "trade", | ||
2893 | close_if_possible=True) | ||
2894 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order)) | ||
2895 | |||
2896 | def test_as_json(self): | ||
2897 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2898 | D("0.1"), "BTC", "long", "market", "trade") | ||
2899 | mouvement_mock1 = mock.Mock() | ||
2900 | mouvement_mock1.as_json.return_value = 1 | ||
2901 | mouvement_mock2 = mock.Mock() | ||
2902 | mouvement_mock2.as_json.return_value = 2 | ||
2903 | |||
2904 | order.mouvements = [mouvement_mock1, mouvement_mock2] | ||
2905 | as_json = order.as_json() | ||
2906 | self.assertEqual("buy", as_json["action"]) | ||
2907 | self.assertEqual("long", as_json["trade_type"]) | ||
2908 | self.assertEqual(10, as_json["amount"]) | ||
2909 | self.assertEqual("ETH", as_json["currency"]) | ||
2910 | self.assertEqual("BTC", as_json["base_currency"]) | ||
2911 | self.assertEqual(D("0.1"), as_json["rate"]) | ||
2912 | self.assertEqual("pending", as_json["status"]) | ||
2913 | self.assertEqual(False, as_json["close_if_possible"]) | ||
2914 | self.assertIsNone(as_json["id"]) | ||
2915 | self.assertEqual([1, 2], as_json["mouvements"]) | ||
2916 | |||
2917 | def test_account(self): | ||
2918 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2919 | D("0.1"), "BTC", "long", "market", "trade") | ||
2920 | self.assertEqual("exchange", order.account) | ||
2921 | |||
2922 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | ||
2923 | D("0.1"), "BTC", "short", "market", "trade") | ||
2924 | self.assertEqual("margin", order.account) | ||
2925 | |||
2926 | def test_pending(self): | ||
2927 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2928 | D("0.1"), "BTC", "long", "market", "trade") | ||
2929 | self.assertTrue(order.pending) | ||
2930 | order.status = "open" | ||
2931 | self.assertFalse(order.pending) | ||
2932 | |||
2933 | def test_open(self): | ||
2934 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2935 | D("0.1"), "BTC", "long", "market", "trade") | ||
2936 | self.assertFalse(order.open) | ||
2937 | order.status = "open" | ||
2938 | self.assertTrue(order.open) | ||
2939 | |||
2940 | def test_finished(self): | ||
2941 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2942 | D("0.1"), "BTC", "long", "market", "trade") | ||
2943 | self.assertFalse(order.finished) | ||
2944 | order.status = "closed" | ||
2945 | self.assertTrue(order.finished) | ||
2946 | order.status = "canceled" | ||
2947 | self.assertTrue(order.finished) | ||
2948 | order.status = "error" | ||
2949 | self.assertTrue(order.finished) | ||
2950 | |||
2951 | @mock.patch.object(portfolio.Order, "fetch") | ||
2952 | def test_cancel(self, fetch): | ||
2953 | with self.subTest(debug=True): | ||
2954 | self.m.debug = True | ||
2955 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2956 | D("0.1"), "BTC", "long", self.m, "trade") | ||
2957 | order.status = "open" | ||
2958 | |||
2959 | order.cancel() | ||
2960 | self.m.ccxt.cancel_order.assert_not_called() | ||
2961 | self.m.report.log_debug_action.assert_called_once() | ||
2962 | self.m.report.log_debug_action.reset_mock() | ||
2963 | self.assertEqual("canceled", order.status) | ||
2964 | |||
2965 | with self.subTest(desc="Nominal case"): | ||
2966 | self.m.debug = False | ||
2967 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2968 | D("0.1"), "BTC", "long", self.m, "trade") | ||
2969 | order.status = "open" | ||
2970 | order.id = 42 | ||
2971 | |||
2972 | order.cancel() | ||
2973 | self.m.ccxt.cancel_order.assert_called_with(42) | ||
2974 | fetch.assert_called_once_with() | ||
2975 | self.m.report.log_debug_action.assert_not_called() | ||
2976 | |||
2977 | with self.subTest(exception=True): | ||
2978 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
2979 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2980 | D("0.1"), "BTC", "long", self.m, "trade") | ||
2981 | order.status = "open" | ||
2982 | order.id = 42 | ||
2983 | order.cancel() | ||
2984 | self.m.ccxt.cancel_order.assert_called_with(42) | ||
2985 | self.m.report.log_error.assert_called_once() | ||
2986 | |||
2987 | self.m.reset_mock() | ||
2988 | with self.subTest(id=None): | ||
2989 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
2990 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
2991 | D("0.1"), "BTC", "long", self.m, "trade") | ||
2992 | order.status = "open" | ||
2993 | order.cancel() | ||
2994 | self.m.ccxt.cancel_order.assert_not_called() | ||
2995 | |||
2996 | self.m.reset_mock() | ||
2997 | with self.subTest(open=False): | ||
2998 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
2999 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3000 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3001 | order.status = "closed" | ||
3002 | order.cancel() | ||
3003 | self.m.ccxt.cancel_order.assert_not_called() | ||
3004 | |||
3005 | def test_dust_amount_remaining(self): | ||
3006 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3007 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3008 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", 1)) | ||
3009 | self.assertFalse(order.dust_amount_remaining()) | ||
3010 | |||
3011 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", D("0.0001"))) | ||
3012 | self.assertTrue(order.dust_amount_remaining()) | ||
3013 | |||
3014 | @mock.patch.object(portfolio.Order, "fetch") | ||
3015 | @mock.patch.object(portfolio.Order, "filled_amount", return_value=portfolio.Amount("ETH", 1)) | ||
3016 | def test_remaining_amount(self, filled_amount, fetch): | ||
3017 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3018 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3019 | |||
3020 | self.assertEqual(9, order.remaining_amount().value) | ||
3021 | |||
3022 | order.status = "open" | ||
3023 | self.assertEqual(9, order.remaining_amount().value) | ||
3024 | |||
3025 | @mock.patch.object(portfolio.Order, "fetch") | ||
3026 | def test_filled_amount(self, fetch): | ||
3027 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3028 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3029 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | ||
3030 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
3031 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
3032 | "amount": "3", "total": "0.3" | ||
3033 | })) | ||
3034 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | ||
3035 | "tradeID": 43, "type": "buy", "fee": "0.0015", | ||
3036 | "date": "2017-12-30 13:00:12", "rate": "0.2", | ||
3037 | "amount": "2", "total": "0.4" | ||
3038 | })) | ||
3039 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount()) | ||
3040 | fetch.assert_not_called() | ||
3041 | order.status = "open" | ||
3042 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount(in_base_currency=False)) | ||
3043 | fetch.assert_called_once() | ||
3044 | self.assertEqual(portfolio.Amount("BTC", "0.7"), order.filled_amount(in_base_currency=True)) | ||
3045 | |||
3046 | def test_fetch_mouvements(self): | ||
3047 | self.m.ccxt.privatePostReturnOrderTrades.return_value = [ | ||
3048 | { | ||
3049 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
3050 | "date": "2017-12-30 13:00:12", "rate": "0.1", | ||
3051 | "amount": "3", "total": "0.3" | ||
3052 | }, | ||
3053 | { | ||
3054 | "tradeID": 43, "type": "buy", "fee": "0.0015", | ||
3055 | "date": "2017-12-30 12:00:12", "rate": "0.2", | ||
3056 | "amount": "2", "total": "0.4" | ||
3057 | } | ||
3058 | ] | ||
3059 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3060 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3061 | order.id = 12 | ||
3062 | order.mouvements = ["Foo", "Bar", "Baz"] | ||
3063 | |||
3064 | order.fetch_mouvements() | ||
3065 | |||
3066 | self.m.ccxt.privatePostReturnOrderTrades.assert_called_with({"orderNumber": 12}) | ||
3067 | self.assertEqual(2, len(order.mouvements)) | ||
3068 | self.assertEqual(43, order.mouvements[0].id) | ||
3069 | self.assertEqual(42, order.mouvements[1].id) | ||
3070 | |||
3071 | self.m.ccxt.privatePostReturnOrderTrades.side_effect = portfolio.ExchangeError | ||
3072 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3073 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3074 | order.fetch_mouvements() | ||
3075 | self.assertEqual(0, len(order.mouvements)) | ||
3076 | |||
3077 | def test_mark_finished_order(self): | ||
3078 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3079 | D("0.1"), "BTC", "short", self.m, "trade", | ||
3080 | close_if_possible=True) | ||
3081 | order.status = "closed" | ||
3082 | self.m.debug = False | ||
3083 | |||
3084 | order.mark_finished_order() | ||
3085 | self.m.ccxt.close_margin_position.assert_called_with("ETH", "BTC") | ||
3086 | self.m.ccxt.close_margin_position.reset_mock() | ||
3087 | |||
3088 | order.status = "open" | ||
3089 | order.mark_finished_order() | ||
3090 | self.m.ccxt.close_margin_position.assert_not_called() | ||
3091 | |||
3092 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3093 | D("0.1"), "BTC", "short", self.m, "trade", | ||
3094 | close_if_possible=False) | ||
3095 | order.status = "closed" | ||
3096 | order.mark_finished_order() | ||
3097 | self.m.ccxt.close_margin_position.assert_not_called() | ||
3098 | |||
3099 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | ||
3100 | D("0.1"), "BTC", "short", self.m, "trade", | ||
3101 | close_if_possible=True) | ||
3102 | order.status = "closed" | ||
3103 | order.mark_finished_order() | ||
3104 | self.m.ccxt.close_margin_position.assert_not_called() | ||
3105 | |||
3106 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3107 | D("0.1"), "BTC", "long", self.m, "trade", | ||
3108 | close_if_possible=True) | ||
3109 | order.status = "closed" | ||
3110 | order.mark_finished_order() | ||
3111 | self.m.ccxt.close_margin_position.assert_not_called() | ||
3112 | |||
3113 | self.m.debug = True | ||
3114 | |||
3115 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3116 | D("0.1"), "BTC", "short", self.m, "trade", | ||
3117 | close_if_possible=True) | ||
3118 | order.status = "closed" | ||
3119 | |||
3120 | order.mark_finished_order() | ||
3121 | self.m.ccxt.close_margin_position.assert_not_called() | ||
3122 | self.m.report.log_debug_action.assert_called_once() | ||
3123 | |||
3124 | @mock.patch.object(portfolio.Order, "fetch_mouvements") | ||
3125 | @mock.patch.object(portfolio.Order, "mark_disappeared_order") | ||
3126 | @mock.patch.object(portfolio.Order, "mark_finished_order") | ||
3127 | def test_fetch(self, mark_finished_order, mark_disappeared_order, fetch_mouvements): | ||
3128 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3129 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3130 | order.id = 45 | ||
3131 | with self.subTest(debug=True): | ||
3132 | self.m.debug = True | ||
3133 | order.fetch() | ||
3134 | self.m.report.log_debug_action.assert_called_once() | ||
3135 | self.m.report.log_debug_action.reset_mock() | ||
3136 | self.m.ccxt.fetch_order.assert_not_called() | ||
3137 | mark_finished_order.assert_not_called() | ||
3138 | mark_disappeared_order.assert_not_called() | ||
3139 | fetch_mouvements.assert_not_called() | ||
3140 | |||
3141 | with self.subTest(debug=False): | ||
3142 | self.m.debug = False | ||
3143 | self.m.ccxt.fetch_order.return_value = { | ||
3144 | "status": "foo", | ||
3145 | "datetime": "timestamp" | ||
3146 | } | ||
3147 | order.fetch() | ||
3148 | |||
3149 | self.m.ccxt.fetch_order.assert_called_once_with(45) | ||
3150 | fetch_mouvements.assert_called_once() | ||
3151 | self.assertEqual("foo", order.status) | ||
3152 | self.assertEqual("timestamp", order.timestamp) | ||
3153 | self.assertEqual(1, len(order.results)) | ||
3154 | self.m.report.log_debug_action.assert_not_called() | ||
3155 | mark_finished_order.assert_called_once() | ||
3156 | mark_disappeared_order.assert_called_once() | ||
3157 | |||
3158 | mark_finished_order.reset_mock() | ||
3159 | with self.subTest(missing_order=True): | ||
3160 | self.m.ccxt.fetch_order.side_effect = [ | ||
3161 | portfolio.OrderNotCached, | ||
3162 | ] | ||
3163 | order.fetch() | ||
3164 | self.assertEqual("closed_unknown", order.status) | ||
3165 | mark_finished_order.assert_called_once() | ||
3166 | |||
3167 | def test_mark_disappeared_order(self): | ||
3168 | with self.subTest("Open order"): | ||
3169 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3170 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3171 | order.id = 45 | ||
3172 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
3173 | "tradeID":21336541, | ||
3174 | "currencyPair":"BTC_XRP", | ||
3175 | "type":"sell", | ||
3176 | "rate":"0.00007013", | ||
3177 | "amount":"0.00000222", | ||
3178 | "total":"0.00000000", | ||
3179 | "fee":"0.00150000", | ||
3180 | "date":"2018-04-02 00:09:13" | ||
3181 | })) | ||
3182 | order.mark_disappeared_order() | ||
3183 | self.assertEqual("pending", order.status) | ||
3184 | |||
3185 | with self.subTest("Non-zero amount"): | ||
3186 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3187 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3188 | order.id = 45 | ||
3189 | order.status = "closed" | ||
3190 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
3191 | "tradeID":21336541, | ||
3192 | "currencyPair":"BTC_XRP", | ||
3193 | "type":"sell", | ||
3194 | "rate":"0.00007013", | ||
3195 | "amount":"0.00000222", | ||
3196 | "total":"0.00000010", | ||
3197 | "fee":"0.00150000", | ||
3198 | "date":"2018-04-02 00:09:13" | ||
3199 | })) | ||
3200 | order.mark_disappeared_order() | ||
3201 | self.assertEqual("closed", order.status) | ||
3202 | |||
3203 | with self.subTest("Other mouvements"): | ||
3204 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3205 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3206 | order.id = 45 | ||
3207 | order.status = "closed" | ||
3208 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
3209 | "tradeID":21336541, | ||
3210 | "currencyPair":"BTC_XRP", | ||
3211 | "type":"sell", | ||
3212 | "rate":"0.00007013", | ||
3213 | "amount":"0.00000222", | ||
3214 | "total":"0.00000001", | ||
3215 | "fee":"0.00150000", | ||
3216 | "date":"2018-04-02 00:09:13" | ||
3217 | })) | ||
3218 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
3219 | "tradeID":21336541, | ||
3220 | "currencyPair":"BTC_XRP", | ||
3221 | "type":"sell", | ||
3222 | "rate":"0.00007013", | ||
3223 | "amount":"0.00000222", | ||
3224 | "total":"0.00000000", | ||
3225 | "fee":"0.00150000", | ||
3226 | "date":"2018-04-02 00:09:13" | ||
3227 | })) | ||
3228 | order.mark_disappeared_order() | ||
3229 | self.assertEqual("error_disappeared", order.status) | ||
3230 | |||
3231 | with self.subTest("Order disappeared"): | ||
3232 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3233 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3234 | order.id = 45 | ||
3235 | order.status = "closed" | ||
3236 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
3237 | "tradeID":21336541, | ||
3238 | "currencyPair":"BTC_XRP", | ||
3239 | "type":"sell", | ||
3240 | "rate":"0.00007013", | ||
3241 | "amount":"0.00000222", | ||
3242 | "total":"0.00000000", | ||
3243 | "fee":"0.00150000", | ||
3244 | "date":"2018-04-02 00:09:13" | ||
3245 | })) | ||
3246 | order.mark_disappeared_order() | ||
3247 | self.assertEqual("error_disappeared", order.status) | ||
3248 | |||
3249 | @mock.patch.object(portfolio.Order, "fetch") | ||
3250 | def test_get_status(self, fetch): | ||
3251 | with self.subTest(debug=True): | ||
3252 | self.m.debug = True | ||
3253 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3254 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3255 | self.assertEqual("pending", order.get_status()) | ||
3256 | fetch.assert_not_called() | ||
3257 | self.m.report.log_debug_action.assert_called_once() | ||
3258 | |||
3259 | with self.subTest(debug=False, finished=False): | ||
3260 | self.m.debug = False | ||
3261 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3262 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3263 | def _fetch(order): | ||
3264 | def update_status(): | ||
3265 | order.status = "open" | ||
3266 | return update_status | ||
3267 | fetch.side_effect = _fetch(order) | ||
3268 | self.assertEqual("open", order.get_status()) | ||
3269 | fetch.assert_called_once() | ||
3270 | |||
3271 | fetch.reset_mock() | ||
3272 | with self.subTest(debug=False, finished=True): | ||
3273 | self.m.debug = False | ||
3274 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3275 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3276 | def _fetch(order): | ||
3277 | def update_status(): | ||
3278 | order.status = "closed" | ||
3279 | return update_status | ||
3280 | fetch.side_effect = _fetch(order) | ||
3281 | self.assertEqual("closed", order.get_status()) | ||
3282 | fetch.assert_called_once() | ||
3283 | |||
3284 | def test_run(self): | ||
3285 | self.m.ccxt.order_precision.return_value = 4 | ||
3286 | with self.subTest(debug=True): | ||
3287 | self.m.debug = True | ||
3288 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3289 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3290 | order.run() | ||
3291 | self.m.ccxt.create_order.assert_not_called() | ||
3292 | self.m.report.log_debug_action.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)") | ||
3293 | self.assertEqual("open", order.status) | ||
3294 | self.assertEqual(1, len(order.results)) | ||
3295 | self.assertEqual(-1, order.id) | ||
3296 | |||
3297 | self.m.ccxt.create_order.reset_mock() | ||
3298 | with self.subTest(debug=False): | ||
3299 | self.m.debug = False | ||
3300 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3301 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3302 | self.m.ccxt.create_order.return_value = { "id": 123 } | ||
3303 | order.run() | ||
3304 | self.m.ccxt.create_order.assert_called_once() | ||
3305 | self.assertEqual(1, len(order.results)) | ||
3306 | self.assertEqual("open", order.status) | ||
3307 | |||
3308 | self.m.ccxt.create_order.reset_mock() | ||
3309 | with self.subTest(exception=True): | ||
3310 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
3311 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3312 | self.m.ccxt.create_order.side_effect = Exception("bouh") | ||
3313 | order.run() | ||
3314 | self.m.ccxt.create_order.assert_called_once() | ||
3315 | self.assertEqual(0, len(order.results)) | ||
3316 | self.assertEqual("error", order.status) | ||
3317 | self.m.report.log_error.assert_called_once() | ||
3318 | |||
3319 | self.m.ccxt.create_order.reset_mock() | ||
3320 | with self.subTest(dust_amount_exception=True),\ | ||
3321 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
3322 | order = portfolio.Order("buy", portfolio.Amount("ETH", 0.001), | ||
3323 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3324 | self.m.ccxt.create_order.side_effect = portfolio.InvalidOrder | ||
3325 | order.run() | ||
3326 | self.m.ccxt.create_order.assert_called_once() | ||
3327 | self.assertEqual(0, len(order.results)) | ||
3328 | self.assertEqual("closed", order.status) | ||
3329 | mark_finished_order.assert_called_once() | ||
3330 | |||
3331 | self.m.ccxt.order_precision.return_value = 8 | ||
3332 | self.m.ccxt.create_order.reset_mock() | ||
3333 | with self.subTest(insufficient_funds=True),\ | ||
3334 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
3335 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3336 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3337 | self.m.ccxt.create_order.side_effect = [ | ||
3338 | portfolio.InsufficientFunds, | ||
3339 | portfolio.InsufficientFunds, | ||
3340 | portfolio.InsufficientFunds, | ||
3341 | { "id": 123 }, | ||
3342 | ] | ||
3343 | order.run() | ||
3344 | self.m.ccxt.create_order.assert_has_calls([ | ||
3345 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3346 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')), | ||
3347 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')), | ||
3348 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')), | ||
3349 | ]) | ||
3350 | self.assertEqual(4, self.m.ccxt.create_order.call_count) | ||
3351 | self.assertEqual(1, len(order.results)) | ||
3352 | self.assertEqual("open", order.status) | ||
3353 | self.assertEqual(4, order.tries) | ||
3354 | self.m.report.log_error.assert_called() | ||
3355 | self.assertEqual(4, self.m.report.log_error.call_count) | ||
3356 | |||
3357 | self.m.ccxt.order_precision.return_value = 8 | ||
3358 | self.m.ccxt.create_order.reset_mock() | ||
3359 | self.m.report.log_error.reset_mock() | ||
3360 | with self.subTest(insufficient_funds=True),\ | ||
3361 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
3362 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3363 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3364 | self.m.ccxt.create_order.side_effect = [ | ||
3365 | portfolio.InsufficientFunds, | ||
3366 | portfolio.InsufficientFunds, | ||
3367 | portfolio.InsufficientFunds, | ||
3368 | portfolio.InsufficientFunds, | ||
3369 | portfolio.InsufficientFunds, | ||
3370 | ] | ||
3371 | order.run() | ||
3372 | self.m.ccxt.create_order.assert_has_calls([ | ||
3373 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3374 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')), | ||
3375 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')), | ||
3376 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')), | ||
3377 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account='exchange', price=D('0.1')), | ||
3378 | ]) | ||
3379 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
3380 | self.assertEqual(0, len(order.results)) | ||
3381 | self.assertEqual("error", order.status) | ||
3382 | self.assertEqual(5, order.tries) | ||
3383 | self.m.report.log_error.assert_called() | ||
3384 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
3385 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00096060 ETH at 0.1 BTC [pending])", exception=mock.ANY) | ||
3386 | |||
3387 | self.m.reset_mock() | ||
3388 | with self.subTest(invalid_nonce=True): | ||
3389 | with self.subTest(retry_success=True): | ||
3390 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3391 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3392 | self.m.ccxt.create_order.side_effect = [ | ||
3393 | portfolio.InvalidNonce, | ||
3394 | portfolio.InvalidNonce, | ||
3395 | { "id": 123 }, | ||
3396 | ] | ||
3397 | order.run() | ||
3398 | self.m.ccxt.create_order.assert_has_calls([ | ||
3399 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3400 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3401 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3402 | ]) | ||
3403 | self.assertEqual(3, self.m.ccxt.create_order.call_count) | ||
3404 | self.assertEqual(3, order.tries) | ||
3405 | self.m.report.log_error.assert_called() | ||
3406 | self.assertEqual(2, self.m.report.log_error.call_count) | ||
3407 | self.m.report.log_error.assert_called_with(mock.ANY, message="Retrying after invalid nonce", exception=mock.ANY) | ||
3408 | self.assertEqual(123, order.id) | ||
3409 | |||
3410 | self.m.reset_mock() | ||
3411 | with self.subTest(retry_success=False): | ||
3412 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3413 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3414 | self.m.ccxt.create_order.side_effect = [ | ||
3415 | portfolio.InvalidNonce, | ||
3416 | portfolio.InvalidNonce, | ||
3417 | portfolio.InvalidNonce, | ||
3418 | portfolio.InvalidNonce, | ||
3419 | portfolio.InvalidNonce, | ||
3420 | ] | ||
3421 | order.run() | ||
3422 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
3423 | self.assertEqual(5, order.tries) | ||
3424 | self.m.report.log_error.assert_called() | ||
3425 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
3426 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after invalid nonce", exception=mock.ANY) | ||
3427 | self.assertEqual("error", order.status) | ||
3428 | |||
3429 | self.m.reset_mock() | ||
3430 | with self.subTest(request_timeout=True): | ||
3431 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3432 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3433 | with self.subTest(retrieved=False), \ | ||
3434 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
3435 | self.m.ccxt.create_order.side_effect = [ | ||
3436 | portfolio.RequestTimeout, | ||
3437 | portfolio.RequestTimeout, | ||
3438 | { "id": 123 }, | ||
3439 | ] | ||
3440 | retrieve.return_value = False | ||
3441 | order.run() | ||
3442 | self.m.ccxt.create_order.assert_has_calls([ | ||
3443 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3444 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3445 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3446 | ]) | ||
3447 | self.assertEqual(3, self.m.ccxt.create_order.call_count) | ||
3448 | self.assertEqual(3, order.tries) | ||
3449 | self.m.report.log_error.assert_called() | ||
3450 | self.assertEqual(2, self.m.report.log_error.call_count) | ||
3451 | self.m.report.log_error.assert_called_with(mock.ANY, message="Retrying after timeout", exception=mock.ANY) | ||
3452 | self.assertEqual(123, order.id) | ||
3453 | |||
3454 | self.m.reset_mock() | ||
3455 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3456 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3457 | with self.subTest(retrieved=True), \ | ||
3458 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
3459 | self.m.ccxt.create_order.side_effect = [ | ||
3460 | portfolio.RequestTimeout, | ||
3461 | ] | ||
3462 | def _retrieve(): | ||
3463 | order.results.append({"id": 123}) | ||
3464 | return True | ||
3465 | retrieve.side_effect = _retrieve | ||
3466 | order.run() | ||
3467 | self.m.ccxt.create_order.assert_has_calls([ | ||
3468 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3469 | ]) | ||
3470 | self.assertEqual(1, self.m.ccxt.create_order.call_count) | ||
3471 | self.assertEqual(1, order.tries) | ||
3472 | self.m.report.log_error.assert_called() | ||
3473 | self.assertEqual(1, self.m.report.log_error.call_count) | ||
3474 | self.m.report.log_error.assert_called_with(mock.ANY, message="Timeout, found the order") | ||
3475 | self.assertEqual(123, order.id) | ||
3476 | |||
3477 | self.m.reset_mock() | ||
3478 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3479 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3480 | with self.subTest(retrieved=False), \ | ||
3481 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
3482 | self.m.ccxt.create_order.side_effect = [ | ||
3483 | portfolio.RequestTimeout, | ||
3484 | portfolio.RequestTimeout, | ||
3485 | portfolio.RequestTimeout, | ||
3486 | portfolio.RequestTimeout, | ||
3487 | portfolio.RequestTimeout, | ||
3488 | ] | ||
3489 | retrieve.return_value = False | ||
3490 | order.run() | ||
3491 | self.m.ccxt.create_order.assert_has_calls([ | ||
3492 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3493 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3494 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3495 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3496 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
3497 | ]) | ||
3498 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
3499 | self.assertEqual(5, order.tries) | ||
3500 | self.m.report.log_error.assert_called() | ||
3501 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
3502 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after timeouts", exception=mock.ANY) | ||
3503 | self.assertEqual("error", order.status) | ||
3504 | |||
3505 | def test_retrieve_order(self): | ||
3506 | with self.subTest(similar_open_order=True): | ||
3507 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3508 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3509 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
3510 | |||
3511 | self.m.ccxt.order_precision.return_value = 8 | ||
3512 | self.m.ccxt.fetch_orders.return_value = [ | ||
3513 | { # Wrong amount | ||
3514 | 'amount': 0.002, 'cost': 0.1, | ||
3515 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
3516 | 'fee': None, 'filled': 0.0, | ||
3517 | 'id': '1', | ||
3518 | 'info': { | ||
3519 | 'amount': '0.002', | ||
3520 | 'date': '2018-03-25 15:15:51', | ||
3521 | 'margin': 0, 'orderNumber': '1', | ||
3522 | 'price': '0.1', 'rate': '0.1', | ||
3523 | 'side': 'buy', 'startingAmount': '0.002', | ||
3524 | 'status': 'open', 'total': '0.0002', | ||
3525 | 'type': 'limit' | ||
3526 | }, | ||
3527 | 'price': 0.1, 'remaining': 0.002, 'side': 'buy', | ||
3528 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
3529 | 'timestamp': 1521990951000, 'trades': None, | ||
3530 | 'type': 'limit' | ||
3531 | }, | ||
3532 | { # Margin | ||
3533 | 'amount': 0.001, 'cost': 0.1, | ||
3534 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
3535 | 'fee': None, 'filled': 0.0, | ||
3536 | 'id': '2', | ||
3537 | 'info': { | ||
3538 | 'amount': '0.001', | ||
3539 | 'date': '2018-03-25 15:15:51', | ||
3540 | 'margin': 1, 'orderNumber': '2', | ||
3541 | 'price': '0.1', 'rate': '0.1', | ||
3542 | 'side': 'buy', 'startingAmount': '0.001', | ||
3543 | 'status': 'open', 'total': '0.0001', | ||
3544 | 'type': 'limit' | ||
3545 | }, | ||
3546 | 'price': 0.1, 'remaining': 0.001, 'side': 'buy', | ||
3547 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
3548 | 'timestamp': 1521990951000, 'trades': None, | ||
3549 | 'type': 'limit' | ||
3550 | }, | ||
3551 | { # selling | ||
3552 | 'amount': 0.001, 'cost': 0.1, | ||
3553 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
3554 | 'fee': None, 'filled': 0.0, | ||
3555 | 'id': '3', | ||
3556 | 'info': { | ||
3557 | 'amount': '0.001', | ||
3558 | 'date': '2018-03-25 15:15:51', | ||
3559 | 'margin': 0, 'orderNumber': '3', | ||
3560 | 'price': '0.1', 'rate': '0.1', | ||
3561 | 'side': 'sell', 'startingAmount': '0.001', | ||
3562 | 'status': 'open', 'total': '0.0001', | ||
3563 | 'type': 'limit' | ||
3564 | }, | ||
3565 | 'price': 0.1, 'remaining': 0.001, 'side': 'sell', | ||
3566 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
3567 | 'timestamp': 1521990951000, 'trades': None, | ||
3568 | 'type': 'limit' | ||
3569 | }, | ||
3570 | { # Wrong rate | ||
3571 | 'amount': 0.001, 'cost': 0.15, | ||
3572 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
3573 | 'fee': None, 'filled': 0.0, | ||
3574 | 'id': '4', | ||
3575 | 'info': { | ||
3576 | 'amount': '0.001', | ||
3577 | 'date': '2018-03-25 15:15:51', | ||
3578 | 'margin': 0, 'orderNumber': '4', | ||
3579 | 'price': '0.15', 'rate': '0.15', | ||
3580 | 'side': 'buy', 'startingAmount': '0.001', | ||
3581 | 'status': 'open', 'total': '0.0001', | ||
3582 | 'type': 'limit' | ||
3583 | }, | ||
3584 | 'price': 0.15, 'remaining': 0.001, 'side': 'buy', | ||
3585 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
3586 | 'timestamp': 1521990951000, 'trades': None, | ||
3587 | 'type': 'limit' | ||
3588 | }, | ||
3589 | { # All good | ||
3590 | 'amount': 0.001, 'cost': 0.1, | ||
3591 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
3592 | 'fee': None, 'filled': 0.0, | ||
3593 | 'id': '5', | ||
3594 | 'info': { | ||
3595 | 'amount': '0.001', | ||
3596 | 'date': '2018-03-25 15:15:51', | ||
3597 | 'margin': 0, 'orderNumber': '1', | ||
3598 | 'price': '0.1', 'rate': '0.1', | ||
3599 | 'side': 'buy', 'startingAmount': '0.001', | ||
3600 | 'status': 'open', 'total': '0.0001', | ||
3601 | 'type': 'limit' | ||
3602 | }, | ||
3603 | 'price': 0.1, 'remaining': 0.001, 'side': 'buy', | ||
3604 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
3605 | 'timestamp': 1521990951000, 'trades': None, | ||
3606 | 'type': 'limit' | ||
3607 | } | ||
3608 | ] | ||
3609 | result = order.retrieve_order() | ||
3610 | self.assertTrue(result) | ||
3611 | self.assertEqual('5', order.results[0]["id"]) | ||
3612 | self.m.ccxt.fetch_my_trades.assert_not_called() | ||
3613 | self.m.ccxt.fetch_orders.assert_called_once_with(symbol="ETH/BTC", since=1521983750) | ||
3614 | |||
3615 | self.m.reset_mock() | ||
3616 | with self.subTest(similar_open_order=False, past_trades=True): | ||
3617 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3618 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3619 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
3620 | |||
3621 | self.m.ccxt.order_precision.return_value = 8 | ||
3622 | self.m.ccxt.fetch_orders.return_value = [] | ||
3623 | self.m.ccxt.fetch_my_trades.return_value = [ | ||
3624 | { # Wrong timestamp 1 | ||
3625 | 'amount': 0.0006, | ||
3626 | 'cost': 0.00006, | ||
3627 | 'datetime': '2018-03-25T15:15:14.000Z', | ||
3628 | 'id': '1-1', | ||
3629 | 'info': { | ||
3630 | 'amount': '0.0006', | ||
3631 | 'category': 'exchange', | ||
3632 | 'date': '2018-03-25 15:15:14', | ||
3633 | 'fee': '0.00150000', | ||
3634 | 'globalTradeID': 1, | ||
3635 | 'orderNumber': '1', | ||
3636 | 'rate': '0.1', | ||
3637 | 'total': '0.00006', | ||
3638 | 'tradeID': '1-1', | ||
3639 | 'type': 'buy' | ||
3640 | }, | ||
3641 | 'order': '1', | ||
3642 | 'price': 0.1, | ||
3643 | 'side': 'buy', | ||
3644 | 'symbol': 'ETH/BTC', | ||
3645 | 'timestamp': 1521983714, | ||
3646 | 'type': 'limit' | ||
3647 | }, | ||
3648 | { # Wrong timestamp 2 | ||
3649 | 'amount': 0.0004, | ||
3650 | 'cost': 0.00004, | ||
3651 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
3652 | 'id': '1-2', | ||
3653 | 'info': { | ||
3654 | 'amount': '0.0004', | ||
3655 | 'category': 'exchange', | ||
3656 | 'date': '2018-03-25 15:16:54', | ||
3657 | 'fee': '0.00150000', | ||
3658 | 'globalTradeID': 2, | ||
3659 | 'orderNumber': '1', | ||
3660 | 'rate': '0.1', | ||
3661 | 'total': '0.00004', | ||
3662 | 'tradeID': '1-2', | ||
3663 | 'type': 'buy' | ||
3664 | }, | ||
3665 | 'order': '1', | ||
3666 | 'price': 0.1, | ||
3667 | 'side': 'buy', | ||
3668 | 'symbol': 'ETH/BTC', | ||
3669 | 'timestamp': 1521983814, | ||
3670 | 'type': 'limit' | ||
3671 | }, | ||
3672 | { # Wrong side 1 | ||
3673 | 'amount': 0.0006, | ||
3674 | 'cost': 0.00006, | ||
3675 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
3676 | 'id': '2-1', | ||
3677 | 'info': { | ||
3678 | 'amount': '0.0006', | ||
3679 | 'category': 'exchange', | ||
3680 | 'date': '2018-03-25 15:15:54', | ||
3681 | 'fee': '0.00150000', | ||
3682 | 'globalTradeID': 1, | ||
3683 | 'orderNumber': '2', | ||
3684 | 'rate': '0.1', | ||
3685 | 'total': '0.00006', | ||
3686 | 'tradeID': '2-1', | ||
3687 | 'type': 'sell' | ||
3688 | }, | ||
3689 | 'order': '2', | ||
3690 | 'price': 0.1, | ||
3691 | 'side': 'sell', | ||
3692 | 'symbol': 'ETH/BTC', | ||
3693 | 'timestamp': 1521983754, | ||
3694 | 'type': 'limit' | ||
3695 | }, | ||
3696 | { # Wrong side 2 | ||
3697 | 'amount': 0.0004, | ||
3698 | 'cost': 0.00004, | ||
3699 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
3700 | 'id': '2-2', | ||
3701 | 'info': { | ||
3702 | 'amount': '0.0004', | ||
3703 | 'category': 'exchange', | ||
3704 | 'date': '2018-03-25 15:16:54', | ||
3705 | 'fee': '0.00150000', | ||
3706 | 'globalTradeID': 2, | ||
3707 | 'orderNumber': '2', | ||
3708 | 'rate': '0.1', | ||
3709 | 'total': '0.00004', | ||
3710 | 'tradeID': '2-2', | ||
3711 | 'type': 'buy' | ||
3712 | }, | ||
3713 | 'order': '2', | ||
3714 | 'price': 0.1, | ||
3715 | 'side': 'buy', | ||
3716 | 'symbol': 'ETH/BTC', | ||
3717 | 'timestamp': 1521983814, | ||
3718 | 'type': 'limit' | ||
3719 | }, | ||
3720 | { # Margin trade 1 | ||
3721 | 'amount': 0.0006, | ||
3722 | 'cost': 0.00006, | ||
3723 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
3724 | 'id': '3-1', | ||
3725 | 'info': { | ||
3726 | 'amount': '0.0006', | ||
3727 | 'category': 'marginTrade', | ||
3728 | 'date': '2018-03-25 15:15:54', | ||
3729 | 'fee': '0.00150000', | ||
3730 | 'globalTradeID': 1, | ||
3731 | 'orderNumber': '3', | ||
3732 | 'rate': '0.1', | ||
3733 | 'total': '0.00006', | ||
3734 | 'tradeID': '3-1', | ||
3735 | 'type': 'buy' | ||
3736 | }, | ||
3737 | 'order': '3', | ||
3738 | 'price': 0.1, | ||
3739 | 'side': 'buy', | ||
3740 | 'symbol': 'ETH/BTC', | ||
3741 | 'timestamp': 1521983754, | ||
3742 | 'type': 'limit' | ||
3743 | }, | ||
3744 | { # Margin trade 2 | ||
3745 | 'amount': 0.0004, | ||
3746 | 'cost': 0.00004, | ||
3747 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
3748 | 'id': '3-2', | ||
3749 | 'info': { | ||
3750 | 'amount': '0.0004', | ||
3751 | 'category': 'marginTrade', | ||
3752 | 'date': '2018-03-25 15:16:54', | ||
3753 | 'fee': '0.00150000', | ||
3754 | 'globalTradeID': 2, | ||
3755 | 'orderNumber': '3', | ||
3756 | 'rate': '0.1', | ||
3757 | 'total': '0.00004', | ||
3758 | 'tradeID': '3-2', | ||
3759 | 'type': 'buy' | ||
3760 | }, | ||
3761 | 'order': '3', | ||
3762 | 'price': 0.1, | ||
3763 | 'side': 'buy', | ||
3764 | 'symbol': 'ETH/BTC', | ||
3765 | 'timestamp': 1521983814, | ||
3766 | 'type': 'limit' | ||
3767 | }, | ||
3768 | { # Wrong amount 1 | ||
3769 | 'amount': 0.0005, | ||
3770 | 'cost': 0.00005, | ||
3771 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
3772 | 'id': '4-1', | ||
3773 | 'info': { | ||
3774 | 'amount': '0.0005', | ||
3775 | 'category': 'exchange', | ||
3776 | 'date': '2018-03-25 15:15:54', | ||
3777 | 'fee': '0.00150000', | ||
3778 | 'globalTradeID': 1, | ||
3779 | 'orderNumber': '4', | ||
3780 | 'rate': '0.1', | ||
3781 | 'total': '0.00005', | ||
3782 | 'tradeID': '4-1', | ||
3783 | 'type': 'buy' | ||
3784 | }, | ||
3785 | 'order': '4', | ||
3786 | 'price': 0.1, | ||
3787 | 'side': 'buy', | ||
3788 | 'symbol': 'ETH/BTC', | ||
3789 | 'timestamp': 1521983754, | ||
3790 | 'type': 'limit' | ||
3791 | }, | ||
3792 | { # Wrong amount 2 | ||
3793 | 'amount': 0.0004, | ||
3794 | 'cost': 0.00004, | ||
3795 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
3796 | 'id': '4-2', | ||
3797 | 'info': { | ||
3798 | 'amount': '0.0004', | ||
3799 | 'category': 'exchange', | ||
3800 | 'date': '2018-03-25 15:16:54', | ||
3801 | 'fee': '0.00150000', | ||
3802 | 'globalTradeID': 2, | ||
3803 | 'orderNumber': '4', | ||
3804 | 'rate': '0.1', | ||
3805 | 'total': '0.00004', | ||
3806 | 'tradeID': '4-2', | ||
3807 | 'type': 'buy' | ||
3808 | }, | ||
3809 | 'order': '4', | ||
3810 | 'price': 0.1, | ||
3811 | 'side': 'buy', | ||
3812 | 'symbol': 'ETH/BTC', | ||
3813 | 'timestamp': 1521983814, | ||
3814 | 'type': 'limit' | ||
3815 | }, | ||
3816 | { # Wrong price 1 | ||
3817 | 'amount': 0.0006, | ||
3818 | 'cost': 0.000066, | ||
3819 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
3820 | 'id': '5-1', | ||
3821 | 'info': { | ||
3822 | 'amount': '0.0006', | ||
3823 | 'category': 'exchange', | ||
3824 | 'date': '2018-03-25 15:15:54', | ||
3825 | 'fee': '0.00150000', | ||
3826 | 'globalTradeID': 1, | ||
3827 | 'orderNumber': '5', | ||
3828 | 'rate': '0.11', | ||
3829 | 'total': '0.000066', | ||
3830 | 'tradeID': '5-1', | ||
3831 | 'type': 'buy' | ||
3832 | }, | ||
3833 | 'order': '5', | ||
3834 | 'price': 0.11, | ||
3835 | 'side': 'buy', | ||
3836 | 'symbol': 'ETH/BTC', | ||
3837 | 'timestamp': 1521983754, | ||
3838 | 'type': 'limit' | ||
3839 | }, | ||
3840 | { # Wrong price 2 | ||
3841 | 'amount': 0.0004, | ||
3842 | 'cost': 0.00004, | ||
3843 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
3844 | 'id': '5-2', | ||
3845 | 'info': { | ||
3846 | 'amount': '0.0004', | ||
3847 | 'category': 'exchange', | ||
3848 | 'date': '2018-03-25 15:16:54', | ||
3849 | 'fee': '0.00150000', | ||
3850 | 'globalTradeID': 2, | ||
3851 | 'orderNumber': '5', | ||
3852 | 'rate': '0.1', | ||
3853 | 'total': '0.00004', | ||
3854 | 'tradeID': '5-2', | ||
3855 | 'type': 'buy' | ||
3856 | }, | ||
3857 | 'order': '5', | ||
3858 | 'price': 0.1, | ||
3859 | 'side': 'buy', | ||
3860 | 'symbol': 'ETH/BTC', | ||
3861 | 'timestamp': 1521983814, | ||
3862 | 'type': 'limit' | ||
3863 | }, | ||
3864 | { # All good 1 | ||
3865 | 'amount': 0.0006, | ||
3866 | 'cost': 0.00006, | ||
3867 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
3868 | 'id': '7-1', | ||
3869 | 'info': { | ||
3870 | 'amount': '0.0006', | ||
3871 | 'category': 'exchange', | ||
3872 | 'date': '2018-03-25 15:15:54', | ||
3873 | 'fee': '0.00150000', | ||
3874 | 'globalTradeID': 1, | ||
3875 | 'orderNumber': '7', | ||
3876 | 'rate': '0.1', | ||
3877 | 'total': '0.00006', | ||
3878 | 'tradeID': '7-1', | ||
3879 | 'type': 'buy' | ||
3880 | }, | ||
3881 | 'order': '7', | ||
3882 | 'price': 0.1, | ||
3883 | 'side': 'buy', | ||
3884 | 'symbol': 'ETH/BTC', | ||
3885 | 'timestamp': 1521983754, | ||
3886 | 'type': 'limit' | ||
3887 | }, | ||
3888 | { # All good 2 | ||
3889 | 'amount': 0.0004, | ||
3890 | 'cost': 0.000036, | ||
3891 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
3892 | 'id': '7-2', | ||
3893 | 'info': { | ||
3894 | 'amount': '0.0004', | ||
3895 | 'category': 'exchange', | ||
3896 | 'date': '2018-03-25 15:16:54', | ||
3897 | 'fee': '0.00150000', | ||
3898 | 'globalTradeID': 2, | ||
3899 | 'orderNumber': '7', | ||
3900 | 'rate': '0.09', | ||
3901 | 'total': '0.000036', | ||
3902 | 'tradeID': '7-2', | ||
3903 | 'type': 'buy' | ||
3904 | }, | ||
3905 | 'order': '7', | ||
3906 | 'price': 0.09, | ||
3907 | 'side': 'buy', | ||
3908 | 'symbol': 'ETH/BTC', | ||
3909 | 'timestamp': 1521983814, | ||
3910 | 'type': 'limit' | ||
3911 | }, | ||
3912 | ] | ||
3913 | |||
3914 | result = order.retrieve_order() | ||
3915 | self.assertTrue(result) | ||
3916 | self.assertEqual('7', order.results[0]["id"]) | ||
3917 | self.m.ccxt.fetch_orders.assert_called_once_with(symbol="ETH/BTC", since=1521983750) | ||
3918 | |||
3919 | self.m.reset_mock() | ||
3920 | with self.subTest(similar_open_order=False, past_trades=False): | ||
3921 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
3922 | D("0.1"), "BTC", "long", self.m, "trade") | ||
3923 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
3924 | |||
3925 | self.m.ccxt.order_precision.return_value = 8 | ||
3926 | self.m.ccxt.fetch_orders.return_value = [] | ||
3927 | self.m.ccxt.fetch_my_trades.return_value = [] | ||
3928 | result = order.retrieve_order() | ||
3929 | self.assertFalse(result) | ||
3930 | |||
3931 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
3932 | class MouvementTest(WebMockTestCase): | ||
3933 | def test_values(self): | ||
3934 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
3935 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
3936 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
3937 | "amount": "10", "total": "1" | ||
3938 | }) | ||
3939 | self.assertEqual("ETH", mouvement.currency) | ||
3940 | self.assertEqual("BTC", mouvement.base_currency) | ||
3941 | self.assertEqual(42, mouvement.id) | ||
3942 | self.assertEqual("buy", mouvement.action) | ||
3943 | self.assertEqual(D("0.0015"), mouvement.fee_rate) | ||
3944 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), mouvement.date) | ||
3945 | self.assertEqual(D("0.1"), mouvement.rate) | ||
3946 | self.assertEqual(portfolio.Amount("ETH", "10"), mouvement.total) | ||
3947 | self.assertEqual(portfolio.Amount("BTC", "1"), mouvement.total_in_base) | ||
3948 | |||
3949 | mouvement = portfolio.Mouvement("ETH", "BTC", { "foo": "bar" }) | ||
3950 | self.assertIsNone(mouvement.date) | ||
3951 | self.assertIsNone(mouvement.id) | ||
3952 | self.assertIsNone(mouvement.action) | ||
3953 | self.assertEqual(-1, mouvement.fee_rate) | ||
3954 | self.assertEqual(0, mouvement.rate) | ||
3955 | self.assertEqual(portfolio.Amount("ETH", 0), mouvement.total) | ||
3956 | self.assertEqual(portfolio.Amount("BTC", 0), mouvement.total_in_base) | ||
3957 | |||
3958 | def test__repr(self): | ||
3959 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
3960 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
3961 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
3962 | "amount": "10", "total": "1" | ||
3963 | }) | ||
3964 | self.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement)) | ||
3965 | |||
3966 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
3967 | "tradeID": 42, "type": "buy", | ||
3968 | "date": "garbage", "rate": "0.1", | ||
3969 | "amount": "10", "total": "1" | ||
3970 | }) | ||
3971 | self.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement)) | ||
3972 | |||
3973 | def test_as_json(self): | ||
3974 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
3975 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
3976 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
3977 | "amount": "10", "total": "1" | ||
3978 | }) | ||
3979 | as_json = mouvement.as_json() | ||
3980 | |||
3981 | self.assertEqual(D("0.0015"), as_json["fee_rate"]) | ||
3982 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), as_json["date"]) | ||
3983 | self.assertEqual("buy", as_json["action"]) | ||
3984 | self.assertEqual(D("10"), as_json["total"]) | ||
3985 | self.assertEqual(D("1"), as_json["total_in_base"]) | ||
3986 | self.assertEqual("BTC", as_json["base_currency"]) | ||
3987 | self.assertEqual("ETH", as_json["currency"]) | ||
3988 | |||
3989 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
3990 | class ReportStoreTest(WebMockTestCase): | ||
3991 | def test_add_log(self): | ||
3992 | report_store = market.ReportStore(self.m) | ||
3993 | report_store.add_log({"foo": "bar"}) | ||
3994 | |||
3995 | self.assertEqual({"foo": "bar", "date": mock.ANY}, report_store.logs[0]) | ||
3996 | |||
3997 | def test_set_verbose(self): | ||
3998 | report_store = market.ReportStore(self.m) | ||
3999 | with self.subTest(verbose=True): | ||
4000 | report_store.set_verbose(True) | ||
4001 | self.assertTrue(report_store.verbose_print) | ||
4002 | |||
4003 | with self.subTest(verbose=False): | ||
4004 | report_store.set_verbose(False) | ||
4005 | self.assertFalse(report_store.verbose_print) | ||
4006 | |||
4007 | def test_merge(self): | ||
4008 | report_store1 = market.ReportStore(self.m, verbose_print=False) | ||
4009 | report_store2 = market.ReportStore(None, verbose_print=False) | ||
4010 | |||
4011 | report_store2.log_stage("1") | ||
4012 | report_store1.log_stage("2") | ||
4013 | report_store2.log_stage("3") | ||
4014 | |||
4015 | report_store1.merge(report_store2) | ||
4016 | |||
4017 | self.assertEqual(3, len(report_store1.logs)) | ||
4018 | self.assertEqual(["1", "2", "3"], list(map(lambda x: x["stage"], report_store1.logs))) | ||
4019 | self.assertEqual(6, len(report_store1.print_logs)) | ||
4020 | |||
4021 | def test_print_log(self): | ||
4022 | report_store = market.ReportStore(self.m) | ||
4023 | with self.subTest(verbose=True),\ | ||
4024 | mock.patch.object(store, "datetime") as time_mock,\ | ||
4025 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
4026 | time_mock.now.return_value = datetime.datetime(2018, 2, 25, 2, 20, 10) | ||
4027 | report_store.set_verbose(True) | ||
4028 | report_store.print_log("Coucou") | ||
4029 | report_store.print_log(portfolio.Amount("BTC", 1)) | ||
4030 | self.assertEqual(stdout_mock.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n") | ||
4031 | |||
4032 | with self.subTest(verbose=False),\ | ||
4033 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
4034 | report_store.set_verbose(False) | ||
4035 | report_store.print_log("Coucou") | ||
4036 | report_store.print_log(portfolio.Amount("BTC", 1)) | ||
4037 | self.assertEqual(stdout_mock.getvalue(), "") | ||
4038 | |||
4039 | def test_default_json_serial(self): | ||
4040 | report_store = market.ReportStore(self.m) | ||
4041 | |||
4042 | self.assertEqual("2018-02-24T00:00:00", | ||
4043 | report_store.default_json_serial(portfolio.datetime(2018, 2, 24))) | ||
4044 | self.assertEqual("1.00000000 BTC", | ||
4045 | report_store.default_json_serial(portfolio.Amount("BTC", 1))) | ||
4046 | |||
4047 | def test_to_json(self): | ||
4048 | report_store = market.ReportStore(self.m) | ||
4049 | report_store.logs.append({"foo": "bar"}) | ||
4050 | self.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store.to_json()) | ||
4051 | report_store.logs.append({"date": portfolio.datetime(2018, 2, 24)}) | ||
4052 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store.to_json()) | ||
4053 | report_store.logs.append({"amount": portfolio.Amount("BTC", 1)}) | ||
4054 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store.to_json()) | ||
4055 | |||
4056 | def test_to_json_array(self): | ||
4057 | report_store = market.ReportStore(self.m) | ||
4058 | report_store.logs.append({ | ||
4059 | "date": "date1", "type": "type1", "foo": "bar", "bla": "bla" | ||
4060 | }) | ||
4061 | report_store.logs.append({ | ||
4062 | "date": "date2", "type": "type2", "foo": "bar", "bla": "bla" | ||
4063 | }) | ||
4064 | logs = list(report_store.to_json_array()) | ||
4065 | |||
4066 | self.assertEqual(2, len(logs)) | ||
4067 | self.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[0]) | ||
4068 | self.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[1]) | ||
4069 | |||
4070 | @mock.patch.object(market.ReportStore, "print_log") | ||
4071 | @mock.patch.object(market.ReportStore, "add_log") | ||
4072 | def test_log_stage(self, add_log, print_log): | ||
4073 | report_store = market.ReportStore(self.m) | ||
4074 | c = lambda x: x | ||
4075 | report_store.log_stage("foo", bar="baz", c=c, d=portfolio.Amount("BTC", 1)) | ||
4076 | print_log.assert_has_calls([ | ||
4077 | mock.call("-----------"), | ||
4078 | mock.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"), | ||
4079 | ]) | ||
4080 | add_log.assert_called_once_with({ | ||
4081 | 'type': 'stage', | ||
4082 | 'stage': 'foo', | ||
4083 | 'args': { | ||
4084 | 'bar': 'baz', | ||
4085 | 'c': 'c = lambda x: x', | ||
4086 | 'd': { | ||
4087 | 'currency': 'BTC', | ||
4088 | 'value': D('1') | ||
4089 | } | ||
4090 | } | ||
4091 | }) | ||
4092 | |||
4093 | @mock.patch.object(market.ReportStore, "print_log") | ||
4094 | @mock.patch.object(market.ReportStore, "add_log") | ||
4095 | def test_log_balances(self, add_log, print_log): | ||
4096 | report_store = market.ReportStore(self.m) | ||
4097 | self.m.balances.as_json.return_value = "json" | ||
4098 | self.m.balances.all = { "FOO": "bar", "BAR": "baz" } | ||
4099 | |||
4100 | report_store.log_balances(tag="tag") | ||
4101 | print_log.assert_has_calls([ | ||
4102 | mock.call("[Balance]"), | ||
4103 | mock.call("\tbar"), | ||
4104 | mock.call("\tbaz"), | ||
4105 | ]) | ||
4106 | add_log.assert_called_once_with({ | ||
4107 | 'type': 'balance', | ||
4108 | 'balances': 'json', | ||
4109 | 'tag': 'tag' | ||
4110 | }) | ||
4111 | |||
4112 | @mock.patch.object(market.ReportStore, "print_log") | ||
4113 | @mock.patch.object(market.ReportStore, "add_log") | ||
4114 | def test_log_tickers(self, add_log, print_log): | ||
4115 | report_store = market.ReportStore(self.m) | ||
4116 | amounts = { | ||
4117 | "BTC": portfolio.Amount("BTC", 10), | ||
4118 | "ETH": portfolio.Amount("BTC", D("0.3")) | ||
4119 | } | ||
4120 | amounts["ETH"].rate = D("0.1") | ||
4121 | |||
4122 | report_store.log_tickers(amounts, "BTC", "default", "total") | ||
4123 | print_log.assert_not_called() | ||
4124 | add_log.assert_called_once_with({ | ||
4125 | 'type': 'tickers', | ||
4126 | 'compute_value': 'default', | ||
4127 | 'balance_type': 'total', | ||
4128 | 'currency': 'BTC', | ||
4129 | 'balances': { | ||
4130 | 'BTC': D('10'), | ||
4131 | 'ETH': D('0.3') | ||
4132 | }, | ||
4133 | 'rates': { | ||
4134 | 'BTC': None, | ||
4135 | 'ETH': D('0.1') | ||
4136 | }, | ||
4137 | 'total': D('10.3') | ||
4138 | }) | ||
4139 | |||
4140 | add_log.reset_mock() | ||
4141 | compute_value = lambda x: x["bid"] | ||
4142 | report_store.log_tickers(amounts, "BTC", compute_value, "total") | ||
4143 | add_log.assert_called_once_with({ | ||
4144 | 'type': 'tickers', | ||
4145 | 'compute_value': 'compute_value = lambda x: x["bid"]', | ||
4146 | 'balance_type': 'total', | ||
4147 | 'currency': 'BTC', | ||
4148 | 'balances': { | ||
4149 | 'BTC': D('10'), | ||
4150 | 'ETH': D('0.3') | ||
4151 | }, | ||
4152 | 'rates': { | ||
4153 | 'BTC': None, | ||
4154 | 'ETH': D('0.1') | ||
4155 | }, | ||
4156 | 'total': D('10.3') | ||
4157 | }) | ||
4158 | |||
4159 | @mock.patch.object(market.ReportStore, "print_log") | ||
4160 | @mock.patch.object(market.ReportStore, "add_log") | ||
4161 | def test_log_dispatch(self, add_log, print_log): | ||
4162 | report_store = market.ReportStore(self.m) | ||
4163 | amount = portfolio.Amount("BTC", "10.3") | ||
4164 | amounts = { | ||
4165 | "BTC": portfolio.Amount("BTC", 10), | ||
4166 | "ETH": portfolio.Amount("BTC", D("0.3")) | ||
4167 | } | ||
4168 | report_store.log_dispatch(amount, amounts, "medium", "repartition") | ||
4169 | print_log.assert_not_called() | ||
4170 | add_log.assert_called_once_with({ | ||
4171 | 'type': 'dispatch', | ||
4172 | 'liquidity': 'medium', | ||
4173 | 'repartition_ratio': 'repartition', | ||
4174 | 'total_amount': { | ||
4175 | 'currency': 'BTC', | ||
4176 | 'value': D('10.3') | ||
4177 | }, | ||
4178 | 'repartition': { | ||
4179 | 'BTC': D('10'), | ||
4180 | 'ETH': D('0.3') | ||
4181 | } | ||
4182 | }) | ||
4183 | |||
4184 | @mock.patch.object(market.ReportStore, "print_log") | ||
4185 | @mock.patch.object(market.ReportStore, "add_log") | ||
4186 | def test_log_trades(self, add_log, print_log): | ||
4187 | report_store = market.ReportStore(self.m) | ||
4188 | trade_mock1 = mock.Mock() | ||
4189 | trade_mock2 = mock.Mock() | ||
4190 | trade_mock1.as_json.return_value = { "trade": "1" } | ||
4191 | trade_mock2.as_json.return_value = { "trade": "2" } | ||
4192 | |||
4193 | matching_and_trades = [ | ||
4194 | (True, trade_mock1), | ||
4195 | (False, trade_mock2), | ||
4196 | ] | ||
4197 | report_store.log_trades(matching_and_trades, "only") | ||
4198 | |||
4199 | print_log.assert_not_called() | ||
4200 | add_log.assert_called_with({ | ||
4201 | 'type': 'trades', | ||
4202 | 'only': 'only', | ||
4203 | 'debug': False, | ||
4204 | 'trades': [ | ||
4205 | {'trade': '1', 'skipped': False}, | ||
4206 | {'trade': '2', 'skipped': True} | ||
4207 | ] | ||
4208 | }) | ||
4209 | |||
4210 | @mock.patch.object(market.ReportStore, "print_log") | ||
4211 | @mock.patch.object(market.ReportStore, "add_log") | ||
4212 | def test_log_orders(self, add_log, print_log): | ||
4213 | report_store = market.ReportStore(self.m) | ||
4214 | |||
4215 | order_mock1 = mock.Mock() | ||
4216 | order_mock2 = mock.Mock() | ||
4217 | |||
4218 | order_mock1.as_json.return_value = "order1" | ||
4219 | order_mock2.as_json.return_value = "order2" | ||
4220 | |||
4221 | orders = [order_mock1, order_mock2] | ||
4222 | |||
4223 | report_store.log_orders(orders, tick="tick", | ||
4224 | only="only", compute_value="compute_value") | ||
4225 | |||
4226 | print_log.assert_called_once_with("[Orders]") | ||
4227 | self.m.trades.print_all_with_order.assert_called_once_with(ind="\t") | ||
4228 | |||
4229 | add_log.assert_called_with({ | ||
4230 | 'type': 'orders', | ||
4231 | 'only': 'only', | ||
4232 | 'compute_value': 'compute_value', | ||
4233 | 'tick': 'tick', | ||
4234 | 'orders': ['order1', 'order2'] | ||
4235 | }) | ||
4236 | |||
4237 | add_log.reset_mock() | ||
4238 | def compute_value(x, y): | ||
4239 | return x[y] | ||
4240 | report_store.log_orders(orders, tick="tick", | ||
4241 | only="only", compute_value=compute_value) | ||
4242 | add_log.assert_called_with({ | ||
4243 | 'type': 'orders', | ||
4244 | 'only': 'only', | ||
4245 | 'compute_value': 'def compute_value(x, y):\n return x[y]', | ||
4246 | 'tick': 'tick', | ||
4247 | 'orders': ['order1', 'order2'] | ||
4248 | }) | ||
4249 | |||
4250 | |||
4251 | @mock.patch.object(market.ReportStore, "print_log") | ||
4252 | @mock.patch.object(market.ReportStore, "add_log") | ||
4253 | def test_log_order(self, add_log, print_log): | ||
4254 | report_store = market.ReportStore(self.m) | ||
4255 | order_mock = mock.Mock() | ||
4256 | order_mock.as_json.return_value = "order" | ||
4257 | new_order_mock = mock.Mock() | ||
4258 | new_order_mock.as_json.return_value = "new_order" | ||
4259 | order_mock.__repr__ = mock.Mock() | ||
4260 | order_mock.__repr__.return_value = "Order Mock" | ||
4261 | new_order_mock.__repr__ = mock.Mock() | ||
4262 | new_order_mock.__repr__.return_value = "New order Mock" | ||
4263 | |||
4264 | with self.subTest(finished=True): | ||
4265 | report_store.log_order(order_mock, 1, finished=True) | ||
4266 | print_log.assert_called_once_with("[Order] Finished Order Mock") | ||
4267 | add_log.assert_called_once_with({ | ||
4268 | 'type': 'order', | ||
4269 | 'tick': 1, | ||
4270 | 'update': None, | ||
4271 | 'order': 'order', | ||
4272 | 'compute_value': None, | ||
4273 | 'new_order': None | ||
4274 | }) | ||
4275 | |||
4276 | add_log.reset_mock() | ||
4277 | print_log.reset_mock() | ||
4278 | |||
4279 | with self.subTest(update="waiting"): | ||
4280 | report_store.log_order(order_mock, 1, update="waiting") | ||
4281 | print_log.assert_called_once_with("[Order] Order Mock, tick 1, waiting") | ||
4282 | add_log.assert_called_once_with({ | ||
4283 | 'type': 'order', | ||
4284 | 'tick': 1, | ||
4285 | 'update': 'waiting', | ||
4286 | 'order': 'order', | ||
4287 | 'compute_value': None, | ||
4288 | 'new_order': None | ||
4289 | }) | ||
4290 | |||
4291 | add_log.reset_mock() | ||
4292 | print_log.reset_mock() | ||
4293 | with self.subTest(update="adjusting"): | ||
4294 | compute_value = lambda x: (x["bid"] + x["ask"]*2)/3 | ||
4295 | report_store.log_order(order_mock, 3, | ||
4296 | update="adjusting", new_order=new_order_mock, | ||
4297 | compute_value=compute_value) | ||
4298 | print_log.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock") | ||
4299 | add_log.assert_called_once_with({ | ||
4300 | 'type': 'order', | ||
4301 | 'tick': 3, | ||
4302 | 'update': 'adjusting', | ||
4303 | 'order': 'order', | ||
4304 | 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3', | ||
4305 | 'new_order': 'new_order' | ||
4306 | }) | ||
4307 | |||
4308 | add_log.reset_mock() | ||
4309 | print_log.reset_mock() | ||
4310 | with self.subTest(update="market_fallback"): | ||
4311 | report_store.log_order(order_mock, 7, | ||
4312 | update="market_fallback", new_order=new_order_mock) | ||
4313 | print_log.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value") | ||
4314 | add_log.assert_called_once_with({ | ||
4315 | 'type': 'order', | ||
4316 | 'tick': 7, | ||
4317 | 'update': 'market_fallback', | ||
4318 | 'order': 'order', | ||
4319 | 'compute_value': None, | ||
4320 | 'new_order': 'new_order' | ||
4321 | }) | ||
4322 | |||
4323 | add_log.reset_mock() | ||
4324 | print_log.reset_mock() | ||
4325 | with self.subTest(update="market_adjusting"): | ||
4326 | report_store.log_order(order_mock, 17, | ||
4327 | update="market_adjust", new_order=new_order_mock) | ||
4328 | print_log.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock") | ||
4329 | add_log.assert_called_once_with({ | ||
4330 | 'type': 'order', | ||
4331 | 'tick': 17, | ||
4332 | 'update': 'market_adjust', | ||
4333 | 'order': 'order', | ||
4334 | 'compute_value': None, | ||
4335 | 'new_order': 'new_order' | ||
4336 | }) | ||
4337 | |||
4338 | @mock.patch.object(market.ReportStore, "print_log") | ||
4339 | @mock.patch.object(market.ReportStore, "add_log") | ||
4340 | def test_log_move_balances(self, add_log, print_log): | ||
4341 | report_store = market.ReportStore(self.m) | ||
4342 | needed = { | ||
4343 | "BTC": portfolio.Amount("BTC", 10), | ||
4344 | "USDT": 1 | ||
4345 | } | ||
4346 | moving = { | ||
4347 | "BTC": portfolio.Amount("BTC", 3), | ||
4348 | "USDT": -2 | ||
4349 | } | ||
4350 | report_store.log_move_balances(needed, moving) | ||
4351 | print_log.assert_not_called() | ||
4352 | add_log.assert_called_once_with({ | ||
4353 | 'type': 'move_balances', | ||
4354 | 'debug': False, | ||
4355 | 'needed': { | ||
4356 | 'BTC': D('10'), | ||
4357 | 'USDT': 1 | ||
4358 | }, | ||
4359 | 'moving': { | ||
4360 | 'BTC': D('3'), | ||
4361 | 'USDT': -2 | ||
4362 | } | ||
4363 | }) | ||
4364 | |||
4365 | @mock.patch.object(market.ReportStore, "print_log") | ||
4366 | @mock.patch.object(market.ReportStore, "add_log") | ||
4367 | def test_log_http_request(self, add_log, print_log): | ||
4368 | report_store = market.ReportStore(self.m) | ||
4369 | response = mock.Mock() | ||
4370 | response.status_code = 200 | ||
4371 | response.text = "Hey" | ||
4372 | |||
4373 | report_store.log_http_request("method", "url", "body", | ||
4374 | "headers", response) | ||
4375 | print_log.assert_not_called() | ||
4376 | add_log.assert_called_once_with({ | ||
4377 | 'type': 'http_request', | ||
4378 | 'method': 'method', | ||
4379 | 'url': 'url', | ||
4380 | 'body': 'body', | ||
4381 | 'headers': 'headers', | ||
4382 | 'status': 200, | ||
4383 | 'response': 'Hey' | ||
4384 | }) | ||
4385 | |||
4386 | add_log.reset_mock() | ||
4387 | report_store.log_http_request("method", "url", "body", | ||
4388 | "headers", ValueError("Foo")) | ||
4389 | add_log.assert_called_once_with({ | ||
4390 | 'type': 'http_request', | ||
4391 | 'method': 'method', | ||
4392 | 'url': 'url', | ||
4393 | 'body': 'body', | ||
4394 | 'headers': 'headers', | ||
4395 | 'status': -1, | ||
4396 | 'response': None, | ||
4397 | 'error': 'ValueError', | ||
4398 | 'error_message': 'Foo', | ||
4399 | }) | ||
4400 | |||
4401 | @mock.patch.object(market.ReportStore, "add_log") | ||
4402 | def test_log_market(self, add_log): | ||
4403 | report_store = market.ReportStore(self.m) | ||
4404 | |||
4405 | report_store.log_market(self.market_args(debug=True, quiet=False), 4, 1) | ||
4406 | add_log.assert_called_once_with({ | ||
4407 | "type": "market", | ||
4408 | "commit": "$Format:%H$", | ||
4409 | "args": { "report_path": None, "debug": True, "quiet": False }, | ||
4410 | "user_id": 4, | ||
4411 | "market_id": 1, | ||
4412 | }) | ||
4413 | |||
4414 | @mock.patch.object(market.ReportStore, "print_log") | ||
4415 | @mock.patch.object(market.ReportStore, "add_log") | ||
4416 | def test_log_error(self, add_log, print_log): | ||
4417 | report_store = market.ReportStore(self.m) | ||
4418 | with self.subTest(message=None, exception=None): | ||
4419 | report_store.log_error("action") | ||
4420 | print_log.assert_called_once_with("[Error] action") | ||
4421 | add_log.assert_called_once_with({ | ||
4422 | 'type': 'error', | ||
4423 | 'action': 'action', | ||
4424 | 'exception_class': None, | ||
4425 | 'exception_message': None, | ||
4426 | 'message': None | ||
4427 | }) | ||
4428 | |||
4429 | print_log.reset_mock() | ||
4430 | add_log.reset_mock() | ||
4431 | with self.subTest(message="Hey", exception=None): | ||
4432 | report_store.log_error("action", message="Hey") | ||
4433 | print_log.assert_has_calls([ | ||
4434 | mock.call("[Error] action"), | ||
4435 | mock.call("\tHey") | ||
4436 | ]) | ||
4437 | add_log.assert_called_once_with({ | ||
4438 | 'type': 'error', | ||
4439 | 'action': 'action', | ||
4440 | 'exception_class': None, | ||
4441 | 'exception_message': None, | ||
4442 | 'message': "Hey" | ||
4443 | }) | ||
4444 | |||
4445 | print_log.reset_mock() | ||
4446 | add_log.reset_mock() | ||
4447 | with self.subTest(message=None, exception=Exception("bouh")): | ||
4448 | report_store.log_error("action", exception=Exception("bouh")) | ||
4449 | print_log.assert_has_calls([ | ||
4450 | mock.call("[Error] action"), | ||
4451 | mock.call("\tException: bouh") | ||
4452 | ]) | ||
4453 | add_log.assert_called_once_with({ | ||
4454 | 'type': 'error', | ||
4455 | 'action': 'action', | ||
4456 | 'exception_class': "Exception", | ||
4457 | 'exception_message': "bouh", | ||
4458 | 'message': None | ||
4459 | }) | ||
4460 | |||
4461 | print_log.reset_mock() | ||
4462 | add_log.reset_mock() | ||
4463 | with self.subTest(message="Hey", exception=Exception("bouh")): | ||
4464 | report_store.log_error("action", message="Hey", exception=Exception("bouh")) | ||
4465 | print_log.assert_has_calls([ | ||
4466 | mock.call("[Error] action"), | ||
4467 | mock.call("\tException: bouh"), | ||
4468 | mock.call("\tHey") | ||
4469 | ]) | ||
4470 | add_log.assert_called_once_with({ | ||
4471 | 'type': 'error', | ||
4472 | 'action': 'action', | ||
4473 | 'exception_class': "Exception", | ||
4474 | 'exception_message': "bouh", | ||
4475 | 'message': "Hey" | ||
4476 | }) | ||
4477 | |||
4478 | @mock.patch.object(market.ReportStore, "print_log") | ||
4479 | @mock.patch.object(market.ReportStore, "add_log") | ||
4480 | def test_log_debug_action(self, add_log, print_log): | ||
4481 | report_store = market.ReportStore(self.m) | ||
4482 | report_store.log_debug_action("Hey") | ||
4483 | |||
4484 | print_log.assert_called_once_with("[Debug] Hey") | ||
4485 | add_log.assert_called_once_with({ | ||
4486 | 'type': 'debug_action', | ||
4487 | 'action': 'Hey' | ||
4488 | }) | ||
4489 | |||
4490 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
4491 | class MainTest(WebMockTestCase): | ||
4492 | def test_make_order(self): | ||
4493 | self.m.get_ticker.return_value = { | ||
4494 | "inverted": False, | ||
4495 | "average": D("0.1"), | ||
4496 | "bid": D("0.09"), | ||
4497 | "ask": D("0.11"), | ||
4498 | } | ||
4499 | |||
4500 | with self.subTest(description="nominal case"): | ||
4501 | main.make_order(self.m, 10, "ETH") | ||
4502 | |||
4503 | self.m.report.log_stage.assert_has_calls([ | ||
4504 | mock.call("make_order_begin"), | ||
4505 | mock.call("make_order_end"), | ||
4506 | ]) | ||
4507 | self.m.balances.fetch_balances.assert_has_calls([ | ||
4508 | mock.call(tag="make_order_begin"), | ||
4509 | mock.call(tag="make_order_end"), | ||
4510 | ]) | ||
4511 | self.m.trades.all.append.assert_called_once() | ||
4512 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4513 | self.assertEqual(False, trade.orders[0].close_if_possible) | ||
4514 | self.assertEqual(0, trade.value_from) | ||
4515 | self.assertEqual("ETH", trade.currency) | ||
4516 | self.assertEqual("BTC", trade.base_currency) | ||
4517 | self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average") | ||
4518 | self.m.trades.run_orders.assert_called_once_with() | ||
4519 | self.m.follow_orders.assert_called_once_with() | ||
4520 | |||
4521 | order = trade.orders[0] | ||
4522 | self.assertEqual(D("0.10"), order.rate) | ||
4523 | |||
4524 | self.m.reset_mock() | ||
4525 | with self.subTest(compute_value="default"): | ||
4526 | main.make_order(self.m, 10, "ETH", action="dispose", | ||
4527 | compute_value="ask") | ||
4528 | |||
4529 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4530 | order = trade.orders[0] | ||
4531 | self.assertEqual(D("0.11"), order.rate) | ||
4532 | |||
4533 | self.m.reset_mock() | ||
4534 | with self.subTest(follow=False): | ||
4535 | result = main.make_order(self.m, 10, "ETH", follow=False) | ||
4536 | |||
4537 | self.m.report.log_stage.assert_has_calls([ | ||
4538 | mock.call("make_order_begin"), | ||
4539 | mock.call("make_order_end_not_followed"), | ||
4540 | ]) | ||
4541 | self.m.balances.fetch_balances.assert_called_once_with(tag="make_order_begin") | ||
4542 | |||
4543 | self.m.trades.all.append.assert_called_once() | ||
4544 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4545 | self.assertEqual(0, trade.value_from) | ||
4546 | self.assertEqual("ETH", trade.currency) | ||
4547 | self.assertEqual("BTC", trade.base_currency) | ||
4548 | self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average") | ||
4549 | self.m.trades.run_orders.assert_called_once_with() | ||
4550 | self.m.follow_orders.assert_not_called() | ||
4551 | self.assertEqual(trade.orders[0], result) | ||
4552 | |||
4553 | self.m.reset_mock() | ||
4554 | with self.subTest(base_currency="USDT"): | ||
4555 | main.make_order(self.m, 1, "BTC", base_currency="USDT") | ||
4556 | |||
4557 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4558 | self.assertEqual("BTC", trade.currency) | ||
4559 | self.assertEqual("USDT", trade.base_currency) | ||
4560 | |||
4561 | self.m.reset_mock() | ||
4562 | with self.subTest(close_if_possible=True): | ||
4563 | main.make_order(self.m, 10, "ETH", close_if_possible=True) | ||
4564 | |||
4565 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4566 | self.assertEqual(True, trade.orders[0].close_if_possible) | ||
4567 | |||
4568 | self.m.reset_mock() | ||
4569 | with self.subTest(action="dispose"): | ||
4570 | main.make_order(self.m, 10, "ETH", action="dispose") | ||
4571 | |||
4572 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4573 | self.assertEqual(0, trade.value_to) | ||
4574 | self.assertEqual(1, trade.value_from.value) | ||
4575 | self.assertEqual("ETH", trade.currency) | ||
4576 | self.assertEqual("BTC", trade.base_currency) | ||
4577 | |||
4578 | self.m.reset_mock() | ||
4579 | with self.subTest(compute_value="default"): | ||
4580 | main.make_order(self.m, 10, "ETH", action="dispose", | ||
4581 | compute_value="bid") | ||
4582 | |||
4583 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
4584 | self.assertEqual(D("0.9"), trade.value_from.value) | ||
4585 | |||
4586 | def test_get_user_market(self): | ||
4587 | with mock.patch("main.fetch_markets") as main_fetch_markets,\ | ||
4588 | mock.patch("main.parse_args") as main_parse_args,\ | ||
4589 | mock.patch("main.parse_config") as main_parse_config: | ||
4590 | with self.subTest(debug=False): | ||
4591 | main_parse_args.return_value = self.market_args() | ||
4592 | main_parse_config.return_value = "pg_config" | ||
4593 | main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)] | ||
4594 | m = main.get_user_market("config_path.ini", 1) | ||
4595 | |||
4596 | self.assertIsInstance(m, market.Market) | ||
4597 | self.assertFalse(m.debug) | ||
4598 | main_parse_args.assert_called_once_with(["--config", "config_path.ini"]) | ||
4599 | |||
4600 | main_parse_args.reset_mock() | ||
4601 | with self.subTest(debug=True): | ||
4602 | main_parse_args.return_value = self.market_args(debug=True) | ||
4603 | main_parse_config.return_value = "pg_config" | ||
4604 | main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)] | ||
4605 | m = main.get_user_market("config_path.ini", 1, debug=True) | ||
4606 | |||
4607 | self.assertIsInstance(m, market.Market) | ||
4608 | self.assertTrue(m.debug) | ||
4609 | main_parse_args.assert_called_once_with(["--config", "config_path.ini", "--debug"]) | ||
4610 | |||
4611 | def test_process(self): | ||
4612 | with mock.patch("market.Market") as market_mock,\ | ||
4613 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
4614 | |||
4615 | args_mock = mock.Mock() | ||
4616 | args_mock.action = "action" | ||
4617 | args_mock.config = "config" | ||
4618 | args_mock.user = "user" | ||
4619 | args_mock.debug = "debug" | ||
4620 | args_mock.before = "before" | ||
4621 | args_mock.after = "after" | ||
4622 | self.assertEqual("", stdout_mock.getvalue()) | ||
4623 | |||
4624 | main.process("config", 3, 1, args_mock, "pg_config") | ||
4625 | |||
4626 | market_mock.from_config.assert_has_calls([ | ||
4627 | mock.call("config", args_mock, pg_config="pg_config", market_id=3, user_id=1), | ||
4628 | mock.call().process("action", before="before", after="after"), | ||
4629 | ]) | ||
4630 | |||
4631 | with self.subTest(exception=True): | ||
4632 | market_mock.from_config.side_effect = Exception("boo") | ||
4633 | main.process(3, "config", 1, args_mock, "pg_config") | ||
4634 | self.assertEqual("Exception: boo\n", stdout_mock.getvalue()) | ||
4635 | |||
4636 | def test_main(self): | ||
4637 | with self.subTest(parallel=False): | ||
4638 | with mock.patch("main.parse_args") as parse_args,\ | ||
4639 | mock.patch("main.parse_config") as parse_config,\ | ||
4640 | mock.patch("main.fetch_markets") as fetch_markets,\ | ||
4641 | mock.patch("main.process") as process: | ||
4642 | |||
4643 | args_mock = mock.Mock() | ||
4644 | args_mock.parallel = False | ||
4645 | args_mock.user = "user" | ||
4646 | parse_args.return_value = args_mock | ||
4647 | |||
4648 | parse_config.return_value = "pg_config" | ||
4649 | |||
4650 | fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]] | ||
4651 | |||
4652 | main.main(["Foo", "Bar"]) | ||
4653 | |||
4654 | parse_args.assert_called_with(["Foo", "Bar"]) | ||
4655 | parse_config.assert_called_with(args_mock) | ||
4656 | fetch_markets.assert_called_with("pg_config", "user") | ||
4657 | |||
4658 | self.assertEqual(2, process.call_count) | ||
4659 | process.assert_has_calls([ | ||
4660 | mock.call("config1", 3, 1, args_mock, "pg_config"), | ||
4661 | mock.call("config2", 1, 2, args_mock, "pg_config"), | ||
4662 | ]) | ||
4663 | with self.subTest(parallel=True): | ||
4664 | with mock.patch("main.parse_args") as parse_args,\ | ||
4665 | mock.patch("main.parse_config") as parse_config,\ | ||
4666 | mock.patch("main.fetch_markets") as fetch_markets,\ | ||
4667 | mock.patch("main.process") as process,\ | ||
4668 | mock.patch("store.Portfolio.start_worker") as start: | ||
4669 | |||
4670 | args_mock = mock.Mock() | ||
4671 | args_mock.parallel = True | ||
4672 | args_mock.user = "user" | ||
4673 | parse_args.return_value = args_mock | ||
4674 | |||
4675 | parse_config.return_value = "pg_config" | ||
4676 | |||
4677 | fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]] | ||
4678 | |||
4679 | main.main(["Foo", "Bar"]) | ||
4680 | |||
4681 | parse_args.assert_called_with(["Foo", "Bar"]) | ||
4682 | parse_config.assert_called_with(args_mock) | ||
4683 | fetch_markets.assert_called_with("pg_config", "user") | ||
4684 | |||
4685 | start.assert_called_once_with() | ||
4686 | self.assertEqual(2, process.call_count) | ||
4687 | process.assert_has_calls([ | ||
4688 | mock.call.__bool__(), | ||
4689 | mock.call("config1", 3, 1, args_mock, "pg_config"), | ||
4690 | mock.call.__bool__(), | ||
4691 | mock.call("config2", 1, 2, args_mock, "pg_config"), | ||
4692 | ]) | ||
4693 | |||
4694 | @mock.patch.object(main.sys, "exit") | ||
4695 | @mock.patch("main.os") | ||
4696 | def test_parse_config(self, os, exit): | ||
4697 | with self.subTest(report_path=None): | ||
4698 | args = main.configargparse.Namespace(**{ | ||
4699 | "db_host": "host", | ||
4700 | "db_port": "port", | ||
4701 | "db_user": "user", | ||
4702 | "db_password": "password", | ||
4703 | "db_database": "database", | ||
4704 | "report_path": None, | ||
4705 | }) | ||
4706 | |||
4707 | result = main.parse_config(args) | ||
4708 | self.assertEqual({ "host": "host", "port": "port", "user": | ||
4709 | "user", "password": "password", "database": "database" | ||
4710 | }, result) | ||
4711 | with self.assertRaises(AttributeError): | ||
4712 | args.db_password | ||
4713 | |||
4714 | with self.subTest(report_path="present"): | ||
4715 | args = main.configargparse.Namespace(**{ | ||
4716 | "db_host": "host", | ||
4717 | "db_port": "port", | ||
4718 | "db_user": "user", | ||
4719 | "db_password": "password", | ||
4720 | "db_database": "database", | ||
4721 | "report_path": "report_path", | ||
4722 | }) | ||
4723 | |||
4724 | os.path.exists.return_value = False | ||
4725 | |||
4726 | result = main.parse_config(args) | ||
4727 | |||
4728 | os.path.exists.assert_called_once_with("report_path") | ||
4729 | os.makedirs.assert_called_once_with("report_path") | ||
4730 | |||
4731 | def test_parse_args(self): | ||
4732 | with self.subTest(config="config.ini"): | ||
4733 | args = main.parse_args([]) | ||
4734 | self.assertEqual("config.ini", args.config) | ||
4735 | self.assertFalse(args.before) | ||
4736 | self.assertFalse(args.after) | ||
4737 | self.assertFalse(args.debug) | ||
4738 | |||
4739 | args = main.parse_args(["--before", "--after", "--debug"]) | ||
4740 | self.assertTrue(args.before) | ||
4741 | self.assertTrue(args.after) | ||
4742 | self.assertTrue(args.debug) | ||
4743 | |||
4744 | with self.subTest(config="inexistant"), \ | ||
4745 | self.assertRaises(SystemExit), \ | ||
4746 | mock.patch('sys.stderr', new_callable=StringIO) as stdout_mock: | ||
4747 | args = main.parse_args(["--config", "foo.bar"]) | ||
4748 | |||
4749 | @mock.patch.object(main, "psycopg2") | ||
4750 | def test_fetch_markets(self, psycopg2): | ||
4751 | connect_mock = mock.Mock() | ||
4752 | cursor_mock = mock.MagicMock() | ||
4753 | cursor_mock.__iter__.return_value = ["row_1", "row_2"] | ||
4754 | |||
4755 | connect_mock.cursor.return_value = cursor_mock | ||
4756 | psycopg2.connect.return_value = connect_mock | ||
4757 | |||
4758 | with self.subTest(user=None): | ||
4759 | rows = list(main.fetch_markets({"foo": "bar"}, None)) | ||
4760 | |||
4761 | psycopg2.connect.assert_called_once_with(foo="bar") | ||
4762 | cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs") | ||
4763 | |||
4764 | self.assertEqual(["row_1", "row_2"], rows) | ||
4765 | |||
4766 | psycopg2.connect.reset_mock() | ||
4767 | cursor_mock.execute.reset_mock() | ||
4768 | with self.subTest(user=1): | ||
4769 | rows = list(main.fetch_markets({"foo": "bar"}, 1)) | ||
4770 | |||
4771 | psycopg2.connect.assert_called_once_with(foo="bar") | ||
4772 | cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs WHERE user_id = %s", 1) | ||
4773 | |||
4774 | self.assertEqual(["row_1", "row_2"], rows) | ||
4775 | |||
4776 | |||
4777 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
4778 | class ProcessorTest(WebMockTestCase): | ||
4779 | def test_values(self): | ||
4780 | processor = market.Processor(self.m) | ||
4781 | |||
4782 | self.assertEqual(self.m, processor.market) | ||
4783 | |||
4784 | def test_run_action(self): | ||
4785 | processor = market.Processor(self.m) | ||
4786 | |||
4787 | with mock.patch.object(processor, "parse_args") as parse_args: | ||
4788 | method_mock = mock.Mock() | ||
4789 | parse_args.return_value = [method_mock, { "foo": "bar" }] | ||
4790 | |||
4791 | processor.run_action("foo", "bar", "baz") | ||
4792 | |||
4793 | parse_args.assert_called_with("foo", "bar", "baz") | ||
4794 | |||
4795 | method_mock.assert_called_with(foo="bar") | ||
4796 | |||
4797 | processor.run_action("wait_for_recent", "bar", "baz") | ||
4798 | |||
4799 | method_mock.assert_called_with(foo="bar") | ||
4800 | |||
4801 | def test_select_step(self): | ||
4802 | processor = market.Processor(self.m) | ||
4803 | |||
4804 | scenario = processor.scenarios["sell_all"] | ||
4805 | |||
4806 | self.assertEqual(scenario, processor.select_steps(scenario, "all")) | ||
4807 | self.assertEqual(["all_sell"], list(map(lambda x: x["name"], processor.select_steps(scenario, "before")))) | ||
4808 | self.assertEqual(["wait", "all_buy"], list(map(lambda x: x["name"], processor.select_steps(scenario, "after")))) | ||
4809 | self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, 2)))) | ||
4810 | self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, "wait")))) | ||
4811 | |||
4812 | with self.assertRaises(TypeError): | ||
4813 | processor.select_steps(scenario, ["wait"]) | ||
4814 | |||
4815 | @mock.patch("market.Processor.process_step") | ||
4816 | def test_process(self, process_step): | ||
4817 | processor = market.Processor(self.m) | ||
4818 | |||
4819 | processor.process("sell_all", foo="bar") | ||
4820 | self.assertEqual(3, process_step.call_count) | ||
4821 | |||
4822 | steps = list(map(lambda x: x[1][1]["name"], process_step.mock_calls)) | ||
4823 | scenario_names = list(map(lambda x: x[1][0], process_step.mock_calls)) | ||
4824 | kwargs = list(map(lambda x: x[1][2], process_step.mock_calls)) | ||
4825 | self.assertEqual(["all_sell", "wait", "all_buy"], steps) | ||
4826 | self.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names) | ||
4827 | self.assertEqual([{"foo":"bar"}, {"foo":"bar"}, {"foo":"bar"}], kwargs) | ||
4828 | |||
4829 | process_step.reset_mock() | ||
4830 | |||
4831 | processor.process("sell_needed", steps=["before", "after"]) | ||
4832 | self.assertEqual(3, process_step.call_count) | ||
4833 | |||
4834 | def test_method_arguments(self): | ||
4835 | ccxt = mock.Mock(spec=market.ccxt.poloniexE) | ||
4836 | m = market.Market(ccxt, self.market_args()) | ||
4837 | |||
4838 | processor = market.Processor(m) | ||
4839 | |||
4840 | method, arguments = processor.method_arguments("wait_for_recent") | ||
4841 | self.assertEqual(market.Portfolio.wait_for_recent, method) | ||
4842 | self.assertEqual(["delta", "poll"], arguments) | ||
4843 | |||
4844 | method, arguments = processor.method_arguments("prepare_trades") | ||
4845 | self.assertEqual(m.prepare_trades, method) | ||
4846 | self.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments) | ||
4847 | |||
4848 | method, arguments = processor.method_arguments("prepare_orders") | ||
4849 | self.assertEqual(m.trades.prepare_orders, method) | ||
4850 | |||
4851 | method, arguments = processor.method_arguments("move_balances") | ||
4852 | self.assertEqual(m.move_balances, method) | ||
4853 | |||
4854 | method, arguments = processor.method_arguments("run_orders") | ||
4855 | self.assertEqual(m.trades.run_orders, method) | ||
4856 | |||
4857 | method, arguments = processor.method_arguments("follow_orders") | ||
4858 | self.assertEqual(m.follow_orders, method) | ||
4859 | |||
4860 | method, arguments = processor.method_arguments("close_trades") | ||
4861 | self.assertEqual(m.trades.close_trades, method) | ||
4862 | |||
4863 | def test_process_step(self): | ||
4864 | processor = market.Processor(self.m) | ||
4865 | |||
4866 | with mock.patch.object(processor, "run_action") as run_action: | ||
4867 | step = processor.scenarios["sell_needed"][1] | ||
4868 | |||
4869 | processor.process_step("foo", step, {"foo":"bar"}) | ||
4870 | |||
4871 | self.m.report.log_stage.assert_has_calls([ | ||
4872 | mock.call("process_foo__1_sell_begin"), | ||
4873 | mock.call("process_foo__1_sell_end"), | ||
4874 | ]) | ||
4875 | self.m.balances.fetch_balances.assert_has_calls([ | ||
4876 | mock.call(tag="process_foo__1_sell_begin"), | ||
4877 | mock.call(tag="process_foo__1_sell_end"), | ||
4878 | ]) | ||
4879 | |||
4880 | self.assertEqual(5, run_action.call_count) | ||
4881 | |||
4882 | run_action.assert_has_calls([ | ||
4883 | mock.call('prepare_trades', {}, {'foo': 'bar'}), | ||
4884 | mock.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}, {'foo': 'bar'}), | ||
4885 | mock.call('run_orders', {}, {'foo': 'bar'}), | ||
4886 | mock.call('follow_orders', {}, {'foo': 'bar'}), | ||
4887 | mock.call('close_trades', {}, {'foo': 'bar'}), | ||
4888 | ]) | ||
4889 | |||
4890 | self.m.reset_mock() | ||
4891 | with mock.patch.object(processor, "run_action") as run_action: | ||
4892 | step = processor.scenarios["sell_needed"][0] | ||
4893 | |||
4894 | processor.process_step("foo", step, {"foo":"bar"}) | ||
4895 | self.m.balances.fetch_balances.assert_not_called() | ||
4896 | |||
4897 | def test_parse_args(self): | ||
4898 | processor = market.Processor(self.m) | ||
4899 | |||
4900 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
4901 | method_mock = mock.Mock() | ||
4902 | method_arguments.return_value = [ | ||
4903 | method_mock, | ||
4904 | ["foo2", "foo"] | ||
4905 | ] | ||
4906 | method, args = processor.parse_args("action", {"foo": "bar", "foo2": "bar"}, {"foo": "bar2", "bla": "bla"}) | ||
4907 | |||
4908 | self.assertEqual(method_mock, method) | ||
4909 | self.assertEqual({"foo": "bar2", "foo2": "bar"}, args) | ||
4910 | |||
4911 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
4912 | method_mock = mock.Mock() | ||
4913 | method_arguments.return_value = [ | ||
4914 | method_mock, | ||
4915 | ["repartition"] | ||
4916 | ] | ||
4917 | method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {}) | ||
4918 | |||
4919 | self.assertEqual(1, len(args["repartition"])) | ||
4920 | self.assertIn("BTC", args["repartition"]) | ||
4921 | |||
4922 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
4923 | method_mock = mock.Mock() | ||
4924 | method_arguments.return_value = [ | ||
4925 | method_mock, | ||
4926 | ["repartition", "base_currency"] | ||
4927 | ] | ||
4928 | method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {"base_currency": "USDT"}) | ||
4929 | |||
4930 | self.assertEqual(1, len(args["repartition"])) | ||
4931 | self.assertIn("USDT", args["repartition"]) | ||
4932 | |||
4933 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
4934 | method_mock = mock.Mock() | ||
4935 | method_arguments.return_value = [ | ||
4936 | method_mock, | ||
4937 | ["repartition", "base_currency"] | ||
4938 | ] | ||
4939 | method, args = processor.parse_args("action", {"repartition": { "ETH": 1 }}, {"base_currency": "USDT"}) | ||
4940 | |||
4941 | self.assertEqual(1, len(args["repartition"])) | ||
4942 | self.assertIn("ETH", args["repartition"]) | ||
4943 | |||
4944 | |||
4945 | @unittest.skipUnless("acceptance" in limits, "Acceptance skipped") | ||
4946 | class AcceptanceTest(WebMockTestCase): | ||
4947 | @unittest.expectedFailure | ||
4948 | def test_success_sell_only_necessary(self): | ||
4949 | # FIXME: catch stdout | ||
4950 | self.m.report.verbose_print = False | ||
4951 | fetch_balance = { | ||
4952 | "ETH": { | ||
4953 | "exchange_free": D("1.0"), | ||
4954 | "exchange_used": D("0.0"), | ||
4955 | "exchange_total": D("1.0"), | ||
4956 | "total": D("1.0"), | ||
4957 | }, | ||
4958 | "ETC": { | ||
4959 | "exchange_free": D("4.0"), | ||
4960 | "exchange_used": D("0.0"), | ||
4961 | "exchange_total": D("4.0"), | ||
4962 | "total": D("4.0"), | ||
4963 | }, | ||
4964 | "XVG": { | ||
4965 | "exchange_free": D("1000.0"), | ||
4966 | "exchange_used": D("0.0"), | ||
4967 | "exchange_total": D("1000.0"), | ||
4968 | "total": D("1000.0"), | ||
4969 | }, | ||
4970 | } | ||
4971 | repartition = { | ||
4972 | "ETH": (D("0.25"), "long"), | ||
4973 | "ETC": (D("0.25"), "long"), | ||
4974 | "BTC": (D("0.4"), "long"), | ||
4975 | "BTD": (D("0.01"), "short"), | ||
4976 | "B2X": (D("0.04"), "long"), | ||
4977 | "USDT": (D("0.05"), "long"), | ||
4978 | } | ||
4979 | |||
4980 | def fetch_ticker(symbol): | ||
4981 | if symbol == "ETH/BTC": | ||
4982 | return { | ||
4983 | "symbol": "ETH/BTC", | ||
4984 | "bid": D("0.14"), | ||
4985 | "ask": D("0.16") | ||
4986 | } | ||
4987 | if symbol == "ETC/BTC": | ||
4988 | return { | ||
4989 | "symbol": "ETC/BTC", | ||
4990 | "bid": D("0.002"), | ||
4991 | "ask": D("0.003") | ||
4992 | } | ||
4993 | if symbol == "XVG/BTC": | ||
4994 | return { | ||
4995 | "symbol": "XVG/BTC", | ||
4996 | "bid": D("0.00003"), | ||
4997 | "ask": D("0.00005") | ||
4998 | } | ||
4999 | if symbol == "BTD/BTC": | ||
5000 | return { | ||
5001 | "symbol": "BTD/BTC", | ||
5002 | "bid": D("0.0008"), | ||
5003 | "ask": D("0.0012") | ||
5004 | } | ||
5005 | if symbol == "B2X/BTC": | ||
5006 | return { | ||
5007 | "symbol": "B2X/BTC", | ||
5008 | "bid": D("0.0008"), | ||
5009 | "ask": D("0.0012") | ||
5010 | } | ||
5011 | if symbol == "USDT/BTC": | ||
5012 | raise helper.ExchangeError | ||
5013 | if symbol == "BTC/USDT": | ||
5014 | return { | ||
5015 | "symbol": "BTC/USDT", | ||
5016 | "bid": D("14000"), | ||
5017 | "ask": D("16000") | ||
5018 | } | ||
5019 | self.fail("Shouldn't have been called with {}".format(symbol)) | ||
5020 | |||
5021 | market = mock.Mock() | ||
5022 | market.fetch_all_balances.return_value = fetch_balance | ||
5023 | market.fetch_ticker.side_effect = fetch_ticker | ||
5024 | with mock.patch.object(market.Portfolio, "repartition", return_value=repartition): | ||
5025 | # Action 1 | ||
5026 | helper.prepare_trades(market) | ||
5027 | |||
5028 | balances = portfolio.BalanceStore.all | ||
5029 | self.assertEqual(portfolio.Amount("ETH", 1), balances["ETH"].total) | ||
5030 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | ||
5031 | self.assertEqual(portfolio.Amount("XVG", 1000), balances["XVG"].total) | ||
5032 | |||
5033 | |||
5034 | trades = portfolio.TradeStore.all | ||
5035 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | ||
5036 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | ||
5037 | self.assertEqual("dispose", trades[0].action) | ||
5038 | |||
5039 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) | ||
5040 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | ||
5041 | self.assertEqual("acquire", trades[1].action) | ||
5042 | |||
5043 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) | ||
5044 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | ||
5045 | self.assertEqual("dispose", trades[2].action) | ||
5046 | |||
5047 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) | ||
5048 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | ||
5049 | self.assertEqual("acquire", trades[3].action) | ||
5050 | |||
5051 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) | ||
5052 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | ||
5053 | self.assertEqual("acquire", trades[4].action) | ||
5054 | |||
5055 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) | ||
5056 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | ||
5057 | self.assertEqual("acquire", trades[5].action) | ||
5058 | |||
5059 | # Action 2 | ||
5060 | portfolio.TradeStore.prepare_orders(only="dispose", compute_value=lambda x, y: x["bid"] * D("1.001")) | ||
5061 | |||
5062 | all_orders = portfolio.TradeStore.all_orders(state="pending") | ||
5063 | self.assertEqual(2, len(all_orders)) | ||
5064 | self.assertEqual(2, 3*all_orders[0].amount.value) | ||
5065 | self.assertEqual(D("0.14014"), all_orders[0].rate) | ||
5066 | self.assertEqual(1000, all_orders[1].amount.value) | ||
5067 | self.assertEqual(D("0.00003003"), all_orders[1].rate) | ||
5068 | |||
5069 | |||
5070 | def create_order(symbol, type, action, amount, price=None, account="exchange"): | ||
5071 | self.assertEqual("limit", type) | ||
5072 | if symbol == "ETH/BTC": | ||
5073 | self.assertEqual("sell", action) | ||
5074 | self.assertEqual(D('0.66666666'), amount) | ||
5075 | self.assertEqual(D("0.14014"), price) | ||
5076 | elif symbol == "XVG/BTC": | ||
5077 | self.assertEqual("sell", action) | ||
5078 | self.assertEqual(1000, amount) | ||
5079 | self.assertEqual(D("0.00003003"), price) | ||
5080 | else: | ||
5081 | self.fail("I shouldn't have been called") | ||
5082 | |||
5083 | return { | ||
5084 | "id": symbol, | ||
5085 | } | ||
5086 | market.create_order.side_effect = create_order | ||
5087 | market.order_precision.return_value = 8 | ||
5088 | |||
5089 | # Action 3 | ||
5090 | portfolio.TradeStore.run_orders() | ||
5091 | |||
5092 | self.assertEqual("open", all_orders[0].status) | ||
5093 | self.assertEqual("open", all_orders[1].status) | ||
5094 | |||
5095 | market.fetch_order.return_value = { "status": "closed", "datetime": "2018-01-20 13:40:00" } | ||
5096 | market.privatePostReturnOrderTrades.return_value = [ | ||
5097 | { | ||
5098 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
5099 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
5100 | "amount": "10", "total": "1" | ||
5101 | } | ||
5102 | ] | ||
5103 | with mock.patch.object(market.time, "sleep") as sleep: | ||
5104 | # Action 4 | ||
5105 | helper.follow_orders(verbose=False) | ||
5106 | |||
5107 | sleep.assert_called_with(30) | ||
5108 | |||
5109 | for order in all_orders: | ||
5110 | self.assertEqual("closed", order.status) | ||
5111 | |||
5112 | fetch_balance = { | ||
5113 | "ETH": { | ||
5114 | "exchange_free": D("1.0") / 3, | ||
5115 | "exchange_used": D("0.0"), | ||
5116 | "exchange_total": D("1.0") / 3, | ||
5117 | "margin_total": 0, | ||
5118 | "total": D("1.0") / 3, | ||
5119 | }, | ||
5120 | "BTC": { | ||
5121 | "exchange_free": D("0.134"), | ||
5122 | "exchange_used": D("0.0"), | ||
5123 | "exchange_total": D("0.134"), | ||
5124 | "margin_total": 0, | ||
5125 | "total": D("0.134"), | ||
5126 | }, | ||
5127 | "ETC": { | ||
5128 | "exchange_free": D("4.0"), | ||
5129 | "exchange_used": D("0.0"), | ||
5130 | "exchange_total": D("4.0"), | ||
5131 | "margin_total": 0, | ||
5132 | "total": D("4.0"), | ||
5133 | }, | ||
5134 | "XVG": { | ||
5135 | "exchange_free": D("0.0"), | ||
5136 | "exchange_used": D("0.0"), | ||
5137 | "exchange_total": D("0.0"), | ||
5138 | "margin_total": 0, | ||
5139 | "total": D("0.0"), | ||
5140 | }, | ||
5141 | } | ||
5142 | market.fetch_all_balances.return_value = fetch_balance | ||
5143 | |||
5144 | with mock.patch.object(market.Portfolio, "repartition", return_value=repartition): | ||
5145 | # Action 5 | ||
5146 | helper.prepare_trades(market, only="acquire", compute_value="average") | ||
5147 | |||
5148 | balances = portfolio.BalanceStore.all | ||
5149 | self.assertEqual(portfolio.Amount("ETH", 1 / D("3")), balances["ETH"].total) | ||
5150 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | ||
5151 | self.assertEqual(portfolio.Amount("BTC", D("0.134")), balances["BTC"].total) | ||
5152 | self.assertEqual(portfolio.Amount("XVG", 0), balances["XVG"].total) | ||
5153 | |||
5154 | |||
5155 | trades = portfolio.TradeStore.all | ||
5156 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | ||
5157 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | ||
5158 | self.assertEqual("dispose", trades[0].action) | ||
5159 | |||
5160 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) | ||
5161 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | ||
5162 | self.assertEqual("acquire", trades[1].action) | ||
5163 | |||
5164 | self.assertNotIn("BTC", trades) | ||
5165 | |||
5166 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) | ||
5167 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | ||
5168 | self.assertEqual("dispose", trades[2].action) | ||
5169 | |||
5170 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) | ||
5171 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | ||
5172 | self.assertEqual("acquire", trades[3].action) | ||
5173 | |||
5174 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) | ||
5175 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | ||
5176 | self.assertEqual("acquire", trades[4].action) | ||
5177 | |||
5178 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) | ||
5179 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | ||
5180 | self.assertEqual("acquire", trades[5].action) | ||
5181 | |||
5182 | # Action 6 | ||
5183 | portfolio.TradeStore.prepare_orders(only="acquire", compute_value=lambda x, y: x["ask"]) | ||
5184 | |||
5185 | all_orders = portfolio.TradeStore.all_orders(state="pending") | ||
5186 | self.assertEqual(4, len(all_orders)) | ||
5187 | self.assertEqual(portfolio.Amount("ETC", D("12.83333333")), round(all_orders[0].amount)) | ||
5188 | self.assertEqual(D("0.003"), all_orders[0].rate) | ||
5189 | self.assertEqual("buy", all_orders[0].action) | ||
5190 | self.assertEqual("long", all_orders[0].trade_type) | ||
5191 | |||
5192 | self.assertEqual(portfolio.Amount("BTD", D("1.61666666")), round(all_orders[1].amount)) | ||
5193 | self.assertEqual(D("0.0012"), all_orders[1].rate) | ||
5194 | self.assertEqual("sell", all_orders[1].action) | ||
5195 | self.assertEqual("short", all_orders[1].trade_type) | ||
5196 | |||
5197 | diff = portfolio.Amount("B2X", D("19.4")/3) - all_orders[2].amount | ||
5198 | self.assertAlmostEqual(0, diff.value) | ||
5199 | self.assertEqual(D("0.0012"), all_orders[2].rate) | ||
5200 | self.assertEqual("buy", all_orders[2].action) | ||
5201 | self.assertEqual("long", all_orders[2].trade_type) | ||
5202 | |||
5203 | self.assertEqual(portfolio.Amount("BTC", D("0.0097")), all_orders[3].amount) | ||
5204 | self.assertEqual(D("16000"), all_orders[3].rate) | ||
5205 | self.assertEqual("sell", all_orders[3].action) | ||
5206 | self.assertEqual("long", all_orders[3].trade_type) | ||
5207 | |||
5208 | # Action 6b | ||
5209 | # TODO: | ||
5210 | # Move balances to margin | ||
5211 | |||
5212 | # Action 7 | ||
5213 | # TODO | ||
5214 | # portfolio.TradeStore.run_orders() | ||
5215 | |||
5216 | with mock.patch.object(market.time, "sleep") as sleep: | ||
5217 | # Action 8 | ||
5218 | helper.follow_orders(verbose=False) | ||
5219 | |||
5220 | sleep.assert_called_with(30) | ||
5221 | 8 | ||
5222 | if __name__ == '__main__': | 9 | if __name__ == '__main__': |
5223 | unittest.main() | 10 | unittest.main() |
diff --git a/tests/helper.py b/tests/helper.py new file mode 100644 index 0000000..4cf1b41 --- /dev/null +++ b/tests/helper.py | |||
@@ -0,0 +1,59 @@ | |||
1 | import sys | ||
2 | import unittest | ||
3 | from decimal import Decimal as D | ||
4 | from unittest import mock | ||
5 | import requests_mock | ||
6 | from io import StringIO | ||
7 | import portfolio, market, main, store | ||
8 | |||
9 | __all__ = ["limits", "unittest", "WebMockTestCase", "mock", "D", | ||
10 | "StringIO"] | ||
11 | |||
12 | limits = ["acceptance", "unit"] | ||
13 | for test_type in limits: | ||
14 | if "--no{}".format(test_type) in sys.argv: | ||
15 | sys.argv.remove("--no{}".format(test_type)) | ||
16 | limits.remove(test_type) | ||
17 | if "--only{}".format(test_type) in sys.argv: | ||
18 | sys.argv.remove("--only{}".format(test_type)) | ||
19 | limits = [test_type] | ||
20 | break | ||
21 | |||
22 | class WebMockTestCase(unittest.TestCase): | ||
23 | import time | ||
24 | |||
25 | def market_args(self, debug=False, quiet=False, report_path=None, **kwargs): | ||
26 | return main.configargparse.Namespace(report_path=report_path, | ||
27 | debug=debug, quiet=quiet, **kwargs) | ||
28 | |||
29 | def setUp(self): | ||
30 | super().setUp() | ||
31 | self.wm = requests_mock.Mocker() | ||
32 | self.wm.start() | ||
33 | |||
34 | # market | ||
35 | self.m = mock.Mock(name="Market", spec=market.Market) | ||
36 | self.m.debug = False | ||
37 | |||
38 | self.patchers = [ | ||
39 | mock.patch.multiple(market.Portfolio, | ||
40 | data=store.LockedVar(None), | ||
41 | liquidities=store.LockedVar({}), | ||
42 | last_date=store.LockedVar(None), | ||
43 | report=mock.Mock(), | ||
44 | worker=None, | ||
45 | worker_notify=None, | ||
46 | worker_started=False, | ||
47 | callback=None), | ||
48 | mock.patch.multiple(portfolio.Computation, | ||
49 | computations=portfolio.Computation.computations), | ||
50 | ] | ||
51 | for patcher in self.patchers: | ||
52 | patcher.start() | ||
53 | |||
54 | def tearDown(self): | ||
55 | for patcher in self.patchers: | ||
56 | patcher.stop() | ||
57 | self.wm.stop() | ||
58 | super().tearDown() | ||
59 | |||
diff --git a/tests/test_acceptance.py b/tests/test_acceptance.py new file mode 100644 index 0000000..184489e --- /dev/null +++ b/tests/test_acceptance.py | |||
@@ -0,0 +1,280 @@ | |||
1 | from .helper import * | ||
2 | |||
3 | @unittest.skipUnless("acceptance" in limits, "Acceptance skipped") | ||
4 | class AcceptanceTest(WebMockTestCase): | ||
5 | @unittest.expectedFailure | ||
6 | def test_success_sell_only_necessary(self): | ||
7 | # FIXME: catch stdout | ||
8 | self.m.report.verbose_print = False | ||
9 | fetch_balance = { | ||
10 | "ETH": { | ||
11 | "exchange_free": D("1.0"), | ||
12 | "exchange_used": D("0.0"), | ||
13 | "exchange_total": D("1.0"), | ||
14 | "total": D("1.0"), | ||
15 | }, | ||
16 | "ETC": { | ||
17 | "exchange_free": D("4.0"), | ||
18 | "exchange_used": D("0.0"), | ||
19 | "exchange_total": D("4.0"), | ||
20 | "total": D("4.0"), | ||
21 | }, | ||
22 | "XVG": { | ||
23 | "exchange_free": D("1000.0"), | ||
24 | "exchange_used": D("0.0"), | ||
25 | "exchange_total": D("1000.0"), | ||
26 | "total": D("1000.0"), | ||
27 | }, | ||
28 | } | ||
29 | repartition = { | ||
30 | "ETH": (D("0.25"), "long"), | ||
31 | "ETC": (D("0.25"), "long"), | ||
32 | "BTC": (D("0.4"), "long"), | ||
33 | "BTD": (D("0.01"), "short"), | ||
34 | "B2X": (D("0.04"), "long"), | ||
35 | "USDT": (D("0.05"), "long"), | ||
36 | } | ||
37 | |||
38 | def fetch_ticker(symbol): | ||
39 | if symbol == "ETH/BTC": | ||
40 | return { | ||
41 | "symbol": "ETH/BTC", | ||
42 | "bid": D("0.14"), | ||
43 | "ask": D("0.16") | ||
44 | } | ||
45 | if symbol == "ETC/BTC": | ||
46 | return { | ||
47 | "symbol": "ETC/BTC", | ||
48 | "bid": D("0.002"), | ||
49 | "ask": D("0.003") | ||
50 | } | ||
51 | if symbol == "XVG/BTC": | ||
52 | return { | ||
53 | "symbol": "XVG/BTC", | ||
54 | "bid": D("0.00003"), | ||
55 | "ask": D("0.00005") | ||
56 | } | ||
57 | if symbol == "BTD/BTC": | ||
58 | return { | ||
59 | "symbol": "BTD/BTC", | ||
60 | "bid": D("0.0008"), | ||
61 | "ask": D("0.0012") | ||
62 | } | ||
63 | if symbol == "B2X/BTC": | ||
64 | return { | ||
65 | "symbol": "B2X/BTC", | ||
66 | "bid": D("0.0008"), | ||
67 | "ask": D("0.0012") | ||
68 | } | ||
69 | if symbol == "USDT/BTC": | ||
70 | raise helper.ExchangeError | ||
71 | if symbol == "BTC/USDT": | ||
72 | return { | ||
73 | "symbol": "BTC/USDT", | ||
74 | "bid": D("14000"), | ||
75 | "ask": D("16000") | ||
76 | } | ||
77 | self.fail("Shouldn't have been called with {}".format(symbol)) | ||
78 | |||
79 | market = mock.Mock() | ||
80 | market.fetch_all_balances.return_value = fetch_balance | ||
81 | market.fetch_ticker.side_effect = fetch_ticker | ||
82 | with mock.patch.object(market.Portfolio, "repartition", return_value=repartition): | ||
83 | # Action 1 | ||
84 | helper.prepare_trades(market) | ||
85 | |||
86 | balances = portfolio.BalanceStore.all | ||
87 | self.assertEqual(portfolio.Amount("ETH", 1), balances["ETH"].total) | ||
88 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | ||
89 | self.assertEqual(portfolio.Amount("XVG", 1000), balances["XVG"].total) | ||
90 | |||
91 | |||
92 | trades = portfolio.TradeStore.all | ||
93 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | ||
94 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | ||
95 | self.assertEqual("dispose", trades[0].action) | ||
96 | |||
97 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) | ||
98 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | ||
99 | self.assertEqual("acquire", trades[1].action) | ||
100 | |||
101 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) | ||
102 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | ||
103 | self.assertEqual("dispose", trades[2].action) | ||
104 | |||
105 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) | ||
106 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | ||
107 | self.assertEqual("acquire", trades[3].action) | ||
108 | |||
109 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) | ||
110 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | ||
111 | self.assertEqual("acquire", trades[4].action) | ||
112 | |||
113 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) | ||
114 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | ||
115 | self.assertEqual("acquire", trades[5].action) | ||
116 | |||
117 | # Action 2 | ||
118 | portfolio.TradeStore.prepare_orders(only="dispose", compute_value=lambda x, y: x["bid"] * D("1.001")) | ||
119 | |||
120 | all_orders = portfolio.TradeStore.all_orders(state="pending") | ||
121 | self.assertEqual(2, len(all_orders)) | ||
122 | self.assertEqual(2, 3*all_orders[0].amount.value) | ||
123 | self.assertEqual(D("0.14014"), all_orders[0].rate) | ||
124 | self.assertEqual(1000, all_orders[1].amount.value) | ||
125 | self.assertEqual(D("0.00003003"), all_orders[1].rate) | ||
126 | |||
127 | |||
128 | def create_order(symbol, type, action, amount, price=None, account="exchange"): | ||
129 | self.assertEqual("limit", type) | ||
130 | if symbol == "ETH/BTC": | ||
131 | self.assertEqual("sell", action) | ||
132 | self.assertEqual(D('0.66666666'), amount) | ||
133 | self.assertEqual(D("0.14014"), price) | ||
134 | elif symbol == "XVG/BTC": | ||
135 | self.assertEqual("sell", action) | ||
136 | self.assertEqual(1000, amount) | ||
137 | self.assertEqual(D("0.00003003"), price) | ||
138 | else: | ||
139 | self.fail("I shouldn't have been called") | ||
140 | |||
141 | return { | ||
142 | "id": symbol, | ||
143 | } | ||
144 | market.create_order.side_effect = create_order | ||
145 | market.order_precision.return_value = 8 | ||
146 | |||
147 | # Action 3 | ||
148 | portfolio.TradeStore.run_orders() | ||
149 | |||
150 | self.assertEqual("open", all_orders[0].status) | ||
151 | self.assertEqual("open", all_orders[1].status) | ||
152 | |||
153 | market.fetch_order.return_value = { "status": "closed", "datetime": "2018-01-20 13:40:00" } | ||
154 | market.privatePostReturnOrderTrades.return_value = [ | ||
155 | { | ||
156 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
157 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
158 | "amount": "10", "total": "1" | ||
159 | } | ||
160 | ] | ||
161 | with mock.patch.object(market.time, "sleep") as sleep: | ||
162 | # Action 4 | ||
163 | helper.follow_orders(verbose=False) | ||
164 | |||
165 | sleep.assert_called_with(30) | ||
166 | |||
167 | for order in all_orders: | ||
168 | self.assertEqual("closed", order.status) | ||
169 | |||
170 | fetch_balance = { | ||
171 | "ETH": { | ||
172 | "exchange_free": D("1.0") / 3, | ||
173 | "exchange_used": D("0.0"), | ||
174 | "exchange_total": D("1.0") / 3, | ||
175 | "margin_total": 0, | ||
176 | "total": D("1.0") / 3, | ||
177 | }, | ||
178 | "BTC": { | ||
179 | "exchange_free": D("0.134"), | ||
180 | "exchange_used": D("0.0"), | ||
181 | "exchange_total": D("0.134"), | ||
182 | "margin_total": 0, | ||
183 | "total": D("0.134"), | ||
184 | }, | ||
185 | "ETC": { | ||
186 | "exchange_free": D("4.0"), | ||
187 | "exchange_used": D("0.0"), | ||
188 | "exchange_total": D("4.0"), | ||
189 | "margin_total": 0, | ||
190 | "total": D("4.0"), | ||
191 | }, | ||
192 | "XVG": { | ||
193 | "exchange_free": D("0.0"), | ||
194 | "exchange_used": D("0.0"), | ||
195 | "exchange_total": D("0.0"), | ||
196 | "margin_total": 0, | ||
197 | "total": D("0.0"), | ||
198 | }, | ||
199 | } | ||
200 | market.fetch_all_balances.return_value = fetch_balance | ||
201 | |||
202 | with mock.patch.object(market.Portfolio, "repartition", return_value=repartition): | ||
203 | # Action 5 | ||
204 | helper.prepare_trades(market, only="acquire", compute_value="average") | ||
205 | |||
206 | balances = portfolio.BalanceStore.all | ||
207 | self.assertEqual(portfolio.Amount("ETH", 1 / D("3")), balances["ETH"].total) | ||
208 | self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total) | ||
209 | self.assertEqual(portfolio.Amount("BTC", D("0.134")), balances["BTC"].total) | ||
210 | self.assertEqual(portfolio.Amount("XVG", 0), balances["XVG"].total) | ||
211 | |||
212 | |||
213 | trades = portfolio.TradeStore.all | ||
214 | self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from) | ||
215 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to) | ||
216 | self.assertEqual("dispose", trades[0].action) | ||
217 | |||
218 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from) | ||
219 | self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to) | ||
220 | self.assertEqual("acquire", trades[1].action) | ||
221 | |||
222 | self.assertNotIn("BTC", trades) | ||
223 | |||
224 | self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from) | ||
225 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to) | ||
226 | self.assertEqual("dispose", trades[2].action) | ||
227 | |||
228 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from) | ||
229 | self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to) | ||
230 | self.assertEqual("acquire", trades[3].action) | ||
231 | |||
232 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from) | ||
233 | self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to) | ||
234 | self.assertEqual("acquire", trades[4].action) | ||
235 | |||
236 | self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from) | ||
237 | self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to) | ||
238 | self.assertEqual("acquire", trades[5].action) | ||
239 | |||
240 | # Action 6 | ||
241 | portfolio.TradeStore.prepare_orders(only="acquire", compute_value=lambda x, y: x["ask"]) | ||
242 | |||
243 | all_orders = portfolio.TradeStore.all_orders(state="pending") | ||
244 | self.assertEqual(4, len(all_orders)) | ||
245 | self.assertEqual(portfolio.Amount("ETC", D("12.83333333")), round(all_orders[0].amount)) | ||
246 | self.assertEqual(D("0.003"), all_orders[0].rate) | ||
247 | self.assertEqual("buy", all_orders[0].action) | ||
248 | self.assertEqual("long", all_orders[0].trade_type) | ||
249 | |||
250 | self.assertEqual(portfolio.Amount("BTD", D("1.61666666")), round(all_orders[1].amount)) | ||
251 | self.assertEqual(D("0.0012"), all_orders[1].rate) | ||
252 | self.assertEqual("sell", all_orders[1].action) | ||
253 | self.assertEqual("short", all_orders[1].trade_type) | ||
254 | |||
255 | diff = portfolio.Amount("B2X", D("19.4")/3) - all_orders[2].amount | ||
256 | self.assertAlmostEqual(0, diff.value) | ||
257 | self.assertEqual(D("0.0012"), all_orders[2].rate) | ||
258 | self.assertEqual("buy", all_orders[2].action) | ||
259 | self.assertEqual("long", all_orders[2].trade_type) | ||
260 | |||
261 | self.assertEqual(portfolio.Amount("BTC", D("0.0097")), all_orders[3].amount) | ||
262 | self.assertEqual(D("16000"), all_orders[3].rate) | ||
263 | self.assertEqual("sell", all_orders[3].action) | ||
264 | self.assertEqual("long", all_orders[3].trade_type) | ||
265 | |||
266 | # Action 6b | ||
267 | # TODO: | ||
268 | # Move balances to margin | ||
269 | |||
270 | # Action 7 | ||
271 | # TODO | ||
272 | # portfolio.TradeStore.run_orders() | ||
273 | |||
274 | with mock.patch.object(market.time, "sleep") as sleep: | ||
275 | # Action 8 | ||
276 | helper.follow_orders(verbose=False) | ||
277 | |||
278 | sleep.assert_called_with(30) | ||
279 | |||
280 | |||
diff --git a/tests/test_ccxt_wrapper.py b/tests/test_ccxt_wrapper.py new file mode 100644 index 0000000..d32469a --- /dev/null +++ b/tests/test_ccxt_wrapper.py | |||
@@ -0,0 +1,477 @@ | |||
1 | from .helper import limits, unittest, mock, D | ||
2 | import requests_mock | ||
3 | import market | ||
4 | |||
5 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
6 | class poloniexETest(unittest.TestCase): | ||
7 | def setUp(self): | ||
8 | super().setUp() | ||
9 | self.wm = requests_mock.Mocker() | ||
10 | self.wm.start() | ||
11 | |||
12 | self.s = market.ccxt.poloniexE() | ||
13 | |||
14 | def tearDown(self): | ||
15 | self.wm.stop() | ||
16 | super().tearDown() | ||
17 | |||
18 | def test__init(self): | ||
19 | with self.subTest("Nominal case"), \ | ||
20 | mock.patch("market.ccxt.poloniexE.session") as session: | ||
21 | session.request.return_value = "response" | ||
22 | ccxt = market.ccxt.poloniexE() | ||
23 | ccxt._market = mock.Mock | ||
24 | ccxt._market.report = mock.Mock() | ||
25 | |||
26 | ccxt.session.request("GET", "URL", data="data", | ||
27 | headers="headers") | ||
28 | ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data', | ||
29 | 'headers', 'response') | ||
30 | |||
31 | with self.subTest("Raising"),\ | ||
32 | mock.patch("market.ccxt.poloniexE.session") as session: | ||
33 | session.request.side_effect = market.ccxt.RequestException("Boo") | ||
34 | |||
35 | ccxt = market.ccxt.poloniexE() | ||
36 | ccxt._market = mock.Mock | ||
37 | ccxt._market.report = mock.Mock() | ||
38 | |||
39 | with self.assertRaises(market.ccxt.RequestException, msg="Boo") as cm: | ||
40 | ccxt.session.request("GET", "URL", data="data", | ||
41 | headers="headers") | ||
42 | ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data', | ||
43 | 'headers', cm.exception) | ||
44 | |||
45 | |||
46 | def test_nanoseconds(self): | ||
47 | with mock.patch.object(market.ccxt.time, "time") as time: | ||
48 | time.return_value = 123456.7890123456 | ||
49 | self.assertEqual(123456789012345, self.s.nanoseconds()) | ||
50 | |||
51 | def test_nonce(self): | ||
52 | with mock.patch.object(market.ccxt.time, "time") as time: | ||
53 | time.return_value = 123456.7890123456 | ||
54 | self.assertEqual(123456789012345, self.s.nonce()) | ||
55 | |||
56 | def test_request(self): | ||
57 | with mock.patch.object(market.ccxt.poloniex, "request") as request,\ | ||
58 | mock.patch("market.ccxt.retry_call") as retry_call: | ||
59 | with self.subTest(wrapped=True): | ||
60 | with self.subTest(desc="public"): | ||
61 | self.s.request("foo") | ||
62 | retry_call.assert_called_with(request, | ||
63 | delay=1, tries=10, fargs=["foo"], | ||
64 | fkwargs={'api': 'public', 'method': 'GET', 'params': {}, 'headers': None, 'body': None}, | ||
65 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
66 | request.assert_not_called() | ||
67 | |||
68 | with self.subTest(desc="private GET"): | ||
69 | self.s.request("foo", api="private") | ||
70 | retry_call.assert_called_with(request, | ||
71 | delay=1, tries=10, fargs=["foo"], | ||
72 | fkwargs={'api': 'private', 'method': 'GET', 'params': {}, 'headers': None, 'body': None}, | ||
73 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
74 | request.assert_not_called() | ||
75 | |||
76 | with self.subTest(desc="private POST regexp"): | ||
77 | self.s.request("returnFoo", api="private", method="POST") | ||
78 | retry_call.assert_called_with(request, | ||
79 | delay=1, tries=10, fargs=["returnFoo"], | ||
80 | fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None}, | ||
81 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
82 | request.assert_not_called() | ||
83 | |||
84 | with self.subTest(desc="private POST non-regexp"): | ||
85 | self.s.request("getMarginPosition", api="private", method="POST") | ||
86 | retry_call.assert_called_with(request, | ||
87 | delay=1, tries=10, fargs=["getMarginPosition"], | ||
88 | fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None}, | ||
89 | exceptions=(market.ccxt.RequestTimeout, market.ccxt.InvalidNonce)) | ||
90 | request.assert_not_called() | ||
91 | retry_call.reset_mock() | ||
92 | request.reset_mock() | ||
93 | with self.subTest(wrapped=False): | ||
94 | with self.subTest(desc="private POST non-matching regexp"): | ||
95 | self.s.request("marginBuy", api="private", method="POST") | ||
96 | request.assert_called_with("marginBuy", | ||
97 | api="private", method="POST", params={}, | ||
98 | headers=None, body=None) | ||
99 | retry_call.assert_not_called() | ||
100 | |||
101 | with self.subTest(desc="private POST non-matching non-regexp"): | ||
102 | self.s.request("closeMarginPositionOther", api="private", method="POST") | ||
103 | request.assert_called_with("closeMarginPositionOther", | ||
104 | api="private", method="POST", params={}, | ||
105 | headers=None, body=None) | ||
106 | retry_call.assert_not_called() | ||
107 | |||
108 | def test_order_precision(self): | ||
109 | self.assertEqual(8, self.s.order_precision("FOO")) | ||
110 | |||
111 | def test_transfer_balance(self): | ||
112 | with self.subTest(success=True),\ | ||
113 | mock.patch.object(self.s, "privatePostTransferBalance") as t: | ||
114 | t.return_value = { "success": 1 } | ||
115 | result = self.s.transfer_balance("FOO", 12, "exchange", "margin") | ||
116 | t.assert_called_once_with({ | ||
117 | "currency": "FOO", | ||
118 | "amount": 12, | ||
119 | "fromAccount": "exchange", | ||
120 | "toAccount": "margin", | ||
121 | "confirmed": 1 | ||
122 | }) | ||
123 | self.assertTrue(result) | ||
124 | |||
125 | with self.subTest(success=False),\ | ||
126 | mock.patch.object(self.s, "privatePostTransferBalance") as t: | ||
127 | t.return_value = { "success": 0 } | ||
128 | self.assertFalse(self.s.transfer_balance("FOO", 12, "exchange", "margin")) | ||
129 | |||
130 | def test_close_margin_position(self): | ||
131 | with mock.patch.object(self.s, "privatePostCloseMarginPosition") as c: | ||
132 | self.s.close_margin_position("FOO", "BAR") | ||
133 | c.assert_called_with({"currencyPair": "BAR_FOO"}) | ||
134 | |||
135 | def test_tradable_balances(self): | ||
136 | with mock.patch.object(self.s, "privatePostReturnTradableBalances") as r: | ||
137 | r.return_value = { | ||
138 | "FOO": { "exchange": "12.1234", "margin": "0.0123" }, | ||
139 | "BAR": { "exchange": "1", "margin": "0" }, | ||
140 | } | ||
141 | balances = self.s.tradable_balances() | ||
142 | self.assertEqual(["FOO", "BAR"], list(balances.keys())) | ||
143 | self.assertEqual(["exchange", "margin"], list(balances["FOO"].keys())) | ||
144 | self.assertEqual(D("12.1234"), balances["FOO"]["exchange"]) | ||
145 | self.assertEqual(["exchange", "margin"], list(balances["BAR"].keys())) | ||
146 | |||
147 | def test_margin_summary(self): | ||
148 | with mock.patch.object(self.s, "privatePostReturnMarginAccountSummary") as r: | ||
149 | r.return_value = { | ||
150 | "currentMargin": "1.49680968", | ||
151 | "lendingFees": "0.0000001", | ||
152 | "pl": "0.00008254", | ||
153 | "totalBorrowedValue": "0.00673602", | ||
154 | "totalValue": "0.01000000", | ||
155 | "netValue": "0.01008254", | ||
156 | } | ||
157 | expected = { | ||
158 | 'current_margin': D('1.49680968'), | ||
159 | 'gains': D('0.00008254'), | ||
160 | 'lending_fees': D('0.0000001'), | ||
161 | 'total': D('0.01000000'), | ||
162 | 'total_borrowed': D('0.00673602') | ||
163 | } | ||
164 | self.assertEqual(expected, self.s.margin_summary()) | ||
165 | |||
166 | def test_create_order(self): | ||
167 | with mock.patch.object(self.s, "create_exchange_order") as exchange,\ | ||
168 | mock.patch.object(self.s, "create_margin_order") as margin: | ||
169 | with self.subTest(account="unspecified"): | ||
170 | self.s.create_order("symbol", "type", "side", "amount", price="price", lending_rate="lending_rate", params="params") | ||
171 | exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
172 | margin.assert_not_called() | ||
173 | exchange.reset_mock() | ||
174 | margin.reset_mock() | ||
175 | |||
176 | with self.subTest(account="exchange"): | ||
177 | self.s.create_order("symbol", "type", "side", "amount", account="exchange", price="price", lending_rate="lending_rate", params="params") | ||
178 | exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
179 | margin.assert_not_called() | ||
180 | exchange.reset_mock() | ||
181 | margin.reset_mock() | ||
182 | |||
183 | with self.subTest(account="margin"): | ||
184 | self.s.create_order("symbol", "type", "side", "amount", account="margin", price="price", lending_rate="lending_rate", params="params") | ||
185 | margin.assert_called_once_with("symbol", "type", "side", "amount", lending_rate="lending_rate", price="price", params="params") | ||
186 | exchange.assert_not_called() | ||
187 | exchange.reset_mock() | ||
188 | margin.reset_mock() | ||
189 | |||
190 | with self.subTest(account="unknown"), self.assertRaises(NotImplementedError): | ||
191 | self.s.create_order("symbol", "type", "side", "amount", account="unknown") | ||
192 | |||
193 | def test_parse_ticker(self): | ||
194 | ticker = { | ||
195 | "high24hr": "12", | ||
196 | "low24hr": "10", | ||
197 | "highestBid": "10.5", | ||
198 | "lowestAsk": "11.5", | ||
199 | "last": "11", | ||
200 | "percentChange": "0.1", | ||
201 | "quoteVolume": "10", | ||
202 | "baseVolume": "20" | ||
203 | } | ||
204 | market = { | ||
205 | "symbol": "BTC/ETC" | ||
206 | } | ||
207 | with mock.patch.object(self.s, "milliseconds") as ms: | ||
208 | ms.return_value = 1520292715123 | ||
209 | result = self.s.parse_ticker(ticker, market) | ||
210 | |||
211 | expected = { | ||
212 | "symbol": "BTC/ETC", | ||
213 | "timestamp": 1520292715123, | ||
214 | "datetime": "2018-03-05T23:31:55.123Z", | ||
215 | "high": D("12"), | ||
216 | "low": D("10"), | ||
217 | "bid": D("10.5"), | ||
218 | "ask": D("11.5"), | ||
219 | "vwap": None, | ||
220 | "open": None, | ||
221 | "close": None, | ||
222 | "first": None, | ||
223 | "last": D("11"), | ||
224 | "change": D("0.1"), | ||
225 | "percentage": None, | ||
226 | "average": None, | ||
227 | "baseVolume": D("10"), | ||
228 | "quoteVolume": D("20"), | ||
229 | "info": ticker | ||
230 | } | ||
231 | self.assertEqual(expected, result) | ||
232 | |||
233 | def test_fetch_margin_balance(self): | ||
234 | with mock.patch.object(self.s, "privatePostGetMarginPosition") as get_margin_position: | ||
235 | get_margin_position.return_value = { | ||
236 | "BTC_DASH": { | ||
237 | "amount": "-0.1", | ||
238 | "basePrice": "0.06818560", | ||
239 | "lendingFees": "0.00000001", | ||
240 | "liquidationPrice": "0.15107132", | ||
241 | "pl": "-0.00000371", | ||
242 | "total": "0.00681856", | ||
243 | "type": "short" | ||
244 | }, | ||
245 | "BTC_ETC": { | ||
246 | "amount": "-0.6", | ||
247 | "basePrice": "0.1", | ||
248 | "lendingFees": "0.00000001", | ||
249 | "liquidationPrice": "0.6", | ||
250 | "pl": "0.00000371", | ||
251 | "total": "0.06", | ||
252 | "type": "short" | ||
253 | }, | ||
254 | "BTC_ETH": { | ||
255 | "amount": "0", | ||
256 | "basePrice": "0", | ||
257 | "lendingFees": "0", | ||
258 | "liquidationPrice": "-1", | ||
259 | "pl": "0", | ||
260 | "total": "0", | ||
261 | "type": "none" | ||
262 | } | ||
263 | } | ||
264 | balances = self.s.fetch_margin_balance() | ||
265 | self.assertEqual(2, len(balances)) | ||
266 | expected = { | ||
267 | "DASH": { | ||
268 | "amount": D("-0.1"), | ||
269 | "borrowedPrice": D("0.06818560"), | ||
270 | "lendingFees": D("1E-8"), | ||
271 | "pl": D("-0.00000371"), | ||
272 | "liquidationPrice": D("0.15107132"), | ||
273 | "type": "short", | ||
274 | "total": D("0.00681856"), | ||
275 | "baseCurrency": "BTC" | ||
276 | }, | ||
277 | "ETC": { | ||
278 | "amount": D("-0.6"), | ||
279 | "borrowedPrice": D("0.1"), | ||
280 | "lendingFees": D("1E-8"), | ||
281 | "pl": D("0.00000371"), | ||
282 | "liquidationPrice": D("0.6"), | ||
283 | "type": "short", | ||
284 | "total": D("0.06"), | ||
285 | "baseCurrency": "BTC" | ||
286 | } | ||
287 | } | ||
288 | self.assertEqual(expected, balances) | ||
289 | |||
290 | def test_sum(self): | ||
291 | self.assertEqual(D("1.1"), self.s.sum(D("1"), D("0.1"))) | ||
292 | |||
293 | def test_fetch_balance(self): | ||
294 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
295 | mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balances,\ | ||
296 | mock.patch.object(self.s, "common_currency_code") as ccc: | ||
297 | ccc.side_effect = ["ETH", "BTC", "DASH"] | ||
298 | balances.return_value = { | ||
299 | "ETH": { | ||
300 | "available": "10", | ||
301 | "onOrders": "1", | ||
302 | }, | ||
303 | "BTC": { | ||
304 | "available": "1", | ||
305 | "onOrders": "0", | ||
306 | }, | ||
307 | "DASH": { | ||
308 | "available": "0", | ||
309 | "onOrders": "3" | ||
310 | } | ||
311 | } | ||
312 | |||
313 | expected = { | ||
314 | "info": { | ||
315 | "ETH": {"available": "10", "onOrders": "1"}, | ||
316 | "BTC": {"available": "1", "onOrders": "0"}, | ||
317 | "DASH": {"available": "0", "onOrders": "3"} | ||
318 | }, | ||
319 | "ETH": {"free": D("10"), "used": D("1"), "total": D("11")}, | ||
320 | "BTC": {"free": D("1"), "used": D("0"), "total": D("1")}, | ||
321 | "DASH": {"free": D("0"), "used": D("3"), "total": D("3")}, | ||
322 | "free": {"ETH": D("10"), "BTC": D("1"), "DASH": D("0")}, | ||
323 | "used": {"ETH": D("1"), "BTC": D("0"), "DASH": D("3")}, | ||
324 | "total": {"ETH": D("11"), "BTC": D("1"), "DASH": D("3")} | ||
325 | } | ||
326 | result = self.s.fetch_balance() | ||
327 | load_markets.assert_called_once() | ||
328 | self.assertEqual(expected, result) | ||
329 | |||
330 | def test_fetch_balance_per_type(self): | ||
331 | with mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balances: | ||
332 | balances.return_value = { | ||
333 | "exchange": { | ||
334 | "BLK": "159.83673869", | ||
335 | "BTC": "0.00005959", | ||
336 | "USDT": "0.00002625", | ||
337 | "XMR": "0.18719303" | ||
338 | }, | ||
339 | "margin": { | ||
340 | "BTC": "0.03019227" | ||
341 | } | ||
342 | } | ||
343 | expected = { | ||
344 | "info": { | ||
345 | "exchange": { | ||
346 | "BLK": "159.83673869", | ||
347 | "BTC": "0.00005959", | ||
348 | "USDT": "0.00002625", | ||
349 | "XMR": "0.18719303" | ||
350 | }, | ||
351 | "margin": { | ||
352 | "BTC": "0.03019227" | ||
353 | } | ||
354 | }, | ||
355 | "exchange": { | ||
356 | "BLK": D("159.83673869"), | ||
357 | "BTC": D("0.00005959"), | ||
358 | "USDT": D("0.00002625"), | ||
359 | "XMR": D("0.18719303") | ||
360 | }, | ||
361 | "margin": {"BTC": D("0.03019227")}, | ||
362 | "BLK": {"exchange": D("159.83673869")}, | ||
363 | "BTC": {"exchange": D("0.00005959"), "margin": D("0.03019227")}, | ||
364 | "USDT": {"exchange": D("0.00002625")}, | ||
365 | "XMR": {"exchange": D("0.18719303")} | ||
366 | } | ||
367 | result = self.s.fetch_balance_per_type() | ||
368 | self.assertEqual(expected, result) | ||
369 | |||
370 | def test_fetch_all_balances(self): | ||
371 | import json | ||
372 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
373 | mock.patch.object(self.s, "privatePostGetMarginPosition") as margin_balance,\ | ||
374 | mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balance,\ | ||
375 | mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balance_per_type: | ||
376 | |||
377 | with open("test_samples/poloniexETest.test_fetch_all_balances.1.json") as f: | ||
378 | balance.return_value = json.load(f) | ||
379 | with open("test_samples/poloniexETest.test_fetch_all_balances.2.json") as f: | ||
380 | margin_balance.return_value = json.load(f) | ||
381 | with open("test_samples/poloniexETest.test_fetch_all_balances.3.json") as f: | ||
382 | balance_per_type.return_value = json.load(f) | ||
383 | |||
384 | result = self.s.fetch_all_balances() | ||
385 | expected_doge = { | ||
386 | "total": D("-12779.79821852"), | ||
387 | "exchange_used": D("0E-8"), | ||
388 | "exchange_total": D("0E-8"), | ||
389 | "exchange_free": D("0E-8"), | ||
390 | "margin_available": 0, | ||
391 | "margin_in_position": 0, | ||
392 | "margin_borrowed": D("12779.79821852"), | ||
393 | "margin_total": D("-12779.79821852"), | ||
394 | "margin_pending_gain": 0, | ||
395 | "margin_lending_fees": D("-9E-8"), | ||
396 | "margin_pending_base_gain": D("0.00024059"), | ||
397 | "margin_position_type": "short", | ||
398 | "margin_liquidation_price": D("0.00000246"), | ||
399 | "margin_borrowed_base_price": D("0.00599149"), | ||
400 | "margin_borrowed_base_currency": "BTC" | ||
401 | } | ||
402 | expected_btc = {"total": D("0.05432165"), | ||
403 | "exchange_used": D("0E-8"), | ||
404 | "exchange_total": D("0.00005959"), | ||
405 | "exchange_free": D("0.00005959"), | ||
406 | "margin_available": D("0.03019227"), | ||
407 | "margin_in_position": D("0.02406979"), | ||
408 | "margin_borrowed": 0, | ||
409 | "margin_total": D("0.05426206"), | ||
410 | "margin_pending_gain": D("0.00093955"), | ||
411 | "margin_lending_fees": 0, | ||
412 | "margin_pending_base_gain": 0, | ||
413 | "margin_position_type": None, | ||
414 | "margin_liquidation_price": 0, | ||
415 | "margin_borrowed_base_price": 0, | ||
416 | "margin_borrowed_base_currency": None | ||
417 | } | ||
418 | expected_xmr = {"total": D("0.18719303"), | ||
419 | "exchange_used": D("0E-8"), | ||
420 | "exchange_total": D("0.18719303"), | ||
421 | "exchange_free": D("0.18719303"), | ||
422 | "margin_available": 0, | ||
423 | "margin_in_position": 0, | ||
424 | "margin_borrowed": 0, | ||
425 | "margin_total": 0, | ||
426 | "margin_pending_gain": 0, | ||
427 | "margin_lending_fees": 0, | ||
428 | "margin_pending_base_gain": 0, | ||
429 | "margin_position_type": None, | ||
430 | "margin_liquidation_price": 0, | ||
431 | "margin_borrowed_base_price": 0, | ||
432 | "margin_borrowed_base_currency": None | ||
433 | } | ||
434 | self.assertEqual(expected_xmr, result["XMR"]) | ||
435 | self.assertEqual(expected_doge, result["DOGE"]) | ||
436 | self.assertEqual(expected_btc, result["BTC"]) | ||
437 | |||
438 | def test_create_margin_order(self): | ||
439 | with self.assertRaises(market.ExchangeError): | ||
440 | self.s.create_margin_order("FOO", "market", "buy", "10") | ||
441 | |||
442 | with mock.patch.object(self.s, "load_markets") as load_markets,\ | ||
443 | mock.patch.object(self.s, "privatePostMarginBuy") as margin_buy,\ | ||
444 | mock.patch.object(self.s, "privatePostMarginSell") as margin_sell,\ | ||
445 | mock.patch.object(self.s, "market") as market_mock,\ | ||
446 | mock.patch.object(self.s, "price_to_precision") as ptp,\ | ||
447 | mock.patch.object(self.s, "amount_to_precision") as atp: | ||
448 | |||
449 | margin_buy.return_value = { | ||
450 | "orderNumber": 123 | ||
451 | } | ||
452 | margin_sell.return_value = { | ||
453 | "orderNumber": 456 | ||
454 | } | ||
455 | market_mock.return_value = { "id": "BTC_ETC", "symbol": "BTC_ETC" } | ||
456 | ptp.return_value = D("0.1") | ||
457 | atp.return_value = D("12") | ||
458 | |||
459 | order = self.s.create_margin_order("BTC_ETC", "margin", "buy", "12", price="0.1") | ||
460 | self.assertEqual(123, order["id"]) | ||
461 | margin_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")}) | ||
462 | margin_sell.assert_not_called() | ||
463 | margin_buy.reset_mock() | ||
464 | margin_sell.reset_mock() | ||
465 | |||
466 | order = self.s.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate="0.01", price="0.1") | ||
467 | self.assertEqual(456, order["id"]) | ||
468 | margin_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"}) | ||
469 | margin_buy.assert_not_called() | ||
470 | |||
471 | def test_create_exchange_order(self): | ||
472 | with mock.patch.object(market.ccxt.poloniex, "create_order") as create_order: | ||
473 | self.s.create_order("symbol", "type", "side", "amount", price="price", params="params") | ||
474 | |||
475 | create_order.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params") | ||
476 | |||
477 | |||
diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..6396c07 --- /dev/null +++ b/tests/test_main.py | |||
@@ -0,0 +1,290 @@ | |||
1 | from .helper import * | ||
2 | import main, market | ||
3 | |||
4 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
5 | class MainTest(WebMockTestCase): | ||
6 | def test_make_order(self): | ||
7 | self.m.get_ticker.return_value = { | ||
8 | "inverted": False, | ||
9 | "average": D("0.1"), | ||
10 | "bid": D("0.09"), | ||
11 | "ask": D("0.11"), | ||
12 | } | ||
13 | |||
14 | with self.subTest(description="nominal case"): | ||
15 | main.make_order(self.m, 10, "ETH") | ||
16 | |||
17 | self.m.report.log_stage.assert_has_calls([ | ||
18 | mock.call("make_order_begin"), | ||
19 | mock.call("make_order_end"), | ||
20 | ]) | ||
21 | self.m.balances.fetch_balances.assert_has_calls([ | ||
22 | mock.call(tag="make_order_begin"), | ||
23 | mock.call(tag="make_order_end"), | ||
24 | ]) | ||
25 | self.m.trades.all.append.assert_called_once() | ||
26 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
27 | self.assertEqual(False, trade.orders[0].close_if_possible) | ||
28 | self.assertEqual(0, trade.value_from) | ||
29 | self.assertEqual("ETH", trade.currency) | ||
30 | self.assertEqual("BTC", trade.base_currency) | ||
31 | self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average") | ||
32 | self.m.trades.run_orders.assert_called_once_with() | ||
33 | self.m.follow_orders.assert_called_once_with() | ||
34 | |||
35 | order = trade.orders[0] | ||
36 | self.assertEqual(D("0.10"), order.rate) | ||
37 | |||
38 | self.m.reset_mock() | ||
39 | with self.subTest(compute_value="default"): | ||
40 | main.make_order(self.m, 10, "ETH", action="dispose", | ||
41 | compute_value="ask") | ||
42 | |||
43 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
44 | order = trade.orders[0] | ||
45 | self.assertEqual(D("0.11"), order.rate) | ||
46 | |||
47 | self.m.reset_mock() | ||
48 | with self.subTest(follow=False): | ||
49 | result = main.make_order(self.m, 10, "ETH", follow=False) | ||
50 | |||
51 | self.m.report.log_stage.assert_has_calls([ | ||
52 | mock.call("make_order_begin"), | ||
53 | mock.call("make_order_end_not_followed"), | ||
54 | ]) | ||
55 | self.m.balances.fetch_balances.assert_called_once_with(tag="make_order_begin") | ||
56 | |||
57 | self.m.trades.all.append.assert_called_once() | ||
58 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
59 | self.assertEqual(0, trade.value_from) | ||
60 | self.assertEqual("ETH", trade.currency) | ||
61 | self.assertEqual("BTC", trade.base_currency) | ||
62 | self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average") | ||
63 | self.m.trades.run_orders.assert_called_once_with() | ||
64 | self.m.follow_orders.assert_not_called() | ||
65 | self.assertEqual(trade.orders[0], result) | ||
66 | |||
67 | self.m.reset_mock() | ||
68 | with self.subTest(base_currency="USDT"): | ||
69 | main.make_order(self.m, 1, "BTC", base_currency="USDT") | ||
70 | |||
71 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
72 | self.assertEqual("BTC", trade.currency) | ||
73 | self.assertEqual("USDT", trade.base_currency) | ||
74 | |||
75 | self.m.reset_mock() | ||
76 | with self.subTest(close_if_possible=True): | ||
77 | main.make_order(self.m, 10, "ETH", close_if_possible=True) | ||
78 | |||
79 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
80 | self.assertEqual(True, trade.orders[0].close_if_possible) | ||
81 | |||
82 | self.m.reset_mock() | ||
83 | with self.subTest(action="dispose"): | ||
84 | main.make_order(self.m, 10, "ETH", action="dispose") | ||
85 | |||
86 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
87 | self.assertEqual(0, trade.value_to) | ||
88 | self.assertEqual(1, trade.value_from.value) | ||
89 | self.assertEqual("ETH", trade.currency) | ||
90 | self.assertEqual("BTC", trade.base_currency) | ||
91 | |||
92 | self.m.reset_mock() | ||
93 | with self.subTest(compute_value="default"): | ||
94 | main.make_order(self.m, 10, "ETH", action="dispose", | ||
95 | compute_value="bid") | ||
96 | |||
97 | trade = self.m.trades.all.append.mock_calls[0][1][0] | ||
98 | self.assertEqual(D("0.9"), trade.value_from.value) | ||
99 | |||
100 | def test_get_user_market(self): | ||
101 | with mock.patch("main.fetch_markets") as main_fetch_markets,\ | ||
102 | mock.patch("main.parse_args") as main_parse_args,\ | ||
103 | mock.patch("main.parse_config") as main_parse_config: | ||
104 | with self.subTest(debug=False): | ||
105 | main_parse_args.return_value = self.market_args() | ||
106 | main_parse_config.return_value = "pg_config" | ||
107 | main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)] | ||
108 | m = main.get_user_market("config_path.ini", 1) | ||
109 | |||
110 | self.assertIsInstance(m, market.Market) | ||
111 | self.assertFalse(m.debug) | ||
112 | main_parse_args.assert_called_once_with(["--config", "config_path.ini"]) | ||
113 | |||
114 | main_parse_args.reset_mock() | ||
115 | with self.subTest(debug=True): | ||
116 | main_parse_args.return_value = self.market_args(debug=True) | ||
117 | main_parse_config.return_value = "pg_config" | ||
118 | main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)] | ||
119 | m = main.get_user_market("config_path.ini", 1, debug=True) | ||
120 | |||
121 | self.assertIsInstance(m, market.Market) | ||
122 | self.assertTrue(m.debug) | ||
123 | main_parse_args.assert_called_once_with(["--config", "config_path.ini", "--debug"]) | ||
124 | |||
125 | def test_process(self): | ||
126 | with mock.patch("market.Market") as market_mock,\ | ||
127 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
128 | |||
129 | args_mock = mock.Mock() | ||
130 | args_mock.action = "action" | ||
131 | args_mock.config = "config" | ||
132 | args_mock.user = "user" | ||
133 | args_mock.debug = "debug" | ||
134 | args_mock.before = "before" | ||
135 | args_mock.after = "after" | ||
136 | self.assertEqual("", stdout_mock.getvalue()) | ||
137 | |||
138 | main.process("config", 3, 1, args_mock, "pg_config") | ||
139 | |||
140 | market_mock.from_config.assert_has_calls([ | ||
141 | mock.call("config", args_mock, pg_config="pg_config", market_id=3, user_id=1), | ||
142 | mock.call().process("action", before="before", after="after"), | ||
143 | ]) | ||
144 | |||
145 | with self.subTest(exception=True): | ||
146 | market_mock.from_config.side_effect = Exception("boo") | ||
147 | main.process(3, "config", 1, args_mock, "pg_config") | ||
148 | self.assertEqual("Exception: boo\n", stdout_mock.getvalue()) | ||
149 | |||
150 | def test_main(self): | ||
151 | with self.subTest(parallel=False): | ||
152 | with mock.patch("main.parse_args") as parse_args,\ | ||
153 | mock.patch("main.parse_config") as parse_config,\ | ||
154 | mock.patch("main.fetch_markets") as fetch_markets,\ | ||
155 | mock.patch("main.process") as process: | ||
156 | |||
157 | args_mock = mock.Mock() | ||
158 | args_mock.parallel = False | ||
159 | args_mock.user = "user" | ||
160 | parse_args.return_value = args_mock | ||
161 | |||
162 | parse_config.return_value = "pg_config" | ||
163 | |||
164 | fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]] | ||
165 | |||
166 | main.main(["Foo", "Bar"]) | ||
167 | |||
168 | parse_args.assert_called_with(["Foo", "Bar"]) | ||
169 | parse_config.assert_called_with(args_mock) | ||
170 | fetch_markets.assert_called_with("pg_config", "user") | ||
171 | |||
172 | self.assertEqual(2, process.call_count) | ||
173 | process.assert_has_calls([ | ||
174 | mock.call("config1", 3, 1, args_mock, "pg_config"), | ||
175 | mock.call("config2", 1, 2, args_mock, "pg_config"), | ||
176 | ]) | ||
177 | with self.subTest(parallel=True): | ||
178 | with mock.patch("main.parse_args") as parse_args,\ | ||
179 | mock.patch("main.parse_config") as parse_config,\ | ||
180 | mock.patch("main.fetch_markets") as fetch_markets,\ | ||
181 | mock.patch("main.process") as process,\ | ||
182 | mock.patch("store.Portfolio.start_worker") as start: | ||
183 | |||
184 | args_mock = mock.Mock() | ||
185 | args_mock.parallel = True | ||
186 | args_mock.user = "user" | ||
187 | parse_args.return_value = args_mock | ||
188 | |||
189 | parse_config.return_value = "pg_config" | ||
190 | |||
191 | fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]] | ||
192 | |||
193 | main.main(["Foo", "Bar"]) | ||
194 | |||
195 | parse_args.assert_called_with(["Foo", "Bar"]) | ||
196 | parse_config.assert_called_with(args_mock) | ||
197 | fetch_markets.assert_called_with("pg_config", "user") | ||
198 | |||
199 | start.assert_called_once_with() | ||
200 | self.assertEqual(2, process.call_count) | ||
201 | process.assert_has_calls([ | ||
202 | mock.call.__bool__(), | ||
203 | mock.call("config1", 3, 1, args_mock, "pg_config"), | ||
204 | mock.call.__bool__(), | ||
205 | mock.call("config2", 1, 2, args_mock, "pg_config"), | ||
206 | ]) | ||
207 | |||
208 | @mock.patch.object(main.sys, "exit") | ||
209 | @mock.patch("main.os") | ||
210 | def test_parse_config(self, os, exit): | ||
211 | with self.subTest(report_path=None): | ||
212 | args = main.configargparse.Namespace(**{ | ||
213 | "db_host": "host", | ||
214 | "db_port": "port", | ||
215 | "db_user": "user", | ||
216 | "db_password": "password", | ||
217 | "db_database": "database", | ||
218 | "report_path": None, | ||
219 | }) | ||
220 | |||
221 | result = main.parse_config(args) | ||
222 | self.assertEqual({ "host": "host", "port": "port", "user": | ||
223 | "user", "password": "password", "database": "database" | ||
224 | }, result) | ||
225 | with self.assertRaises(AttributeError): | ||
226 | args.db_password | ||
227 | |||
228 | with self.subTest(report_path="present"): | ||
229 | args = main.configargparse.Namespace(**{ | ||
230 | "db_host": "host", | ||
231 | "db_port": "port", | ||
232 | "db_user": "user", | ||
233 | "db_password": "password", | ||
234 | "db_database": "database", | ||
235 | "report_path": "report_path", | ||
236 | }) | ||
237 | |||
238 | os.path.exists.return_value = False | ||
239 | |||
240 | result = main.parse_config(args) | ||
241 | |||
242 | os.path.exists.assert_called_once_with("report_path") | ||
243 | os.makedirs.assert_called_once_with("report_path") | ||
244 | |||
245 | def test_parse_args(self): | ||
246 | with self.subTest(config="config.ini"): | ||
247 | args = main.parse_args([]) | ||
248 | self.assertEqual("config.ini", args.config) | ||
249 | self.assertFalse(args.before) | ||
250 | self.assertFalse(args.after) | ||
251 | self.assertFalse(args.debug) | ||
252 | |||
253 | args = main.parse_args(["--before", "--after", "--debug"]) | ||
254 | self.assertTrue(args.before) | ||
255 | self.assertTrue(args.after) | ||
256 | self.assertTrue(args.debug) | ||
257 | |||
258 | with self.subTest(config="inexistant"), \ | ||
259 | self.assertRaises(SystemExit), \ | ||
260 | mock.patch('sys.stderr', new_callable=StringIO) as stdout_mock: | ||
261 | args = main.parse_args(["--config", "foo.bar"]) | ||
262 | |||
263 | @mock.patch.object(main, "psycopg2") | ||
264 | def test_fetch_markets(self, psycopg2): | ||
265 | connect_mock = mock.Mock() | ||
266 | cursor_mock = mock.MagicMock() | ||
267 | cursor_mock.__iter__.return_value = ["row_1", "row_2"] | ||
268 | |||
269 | connect_mock.cursor.return_value = cursor_mock | ||
270 | psycopg2.connect.return_value = connect_mock | ||
271 | |||
272 | with self.subTest(user=None): | ||
273 | rows = list(main.fetch_markets({"foo": "bar"}, None)) | ||
274 | |||
275 | psycopg2.connect.assert_called_once_with(foo="bar") | ||
276 | cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs") | ||
277 | |||
278 | self.assertEqual(["row_1", "row_2"], rows) | ||
279 | |||
280 | psycopg2.connect.reset_mock() | ||
281 | cursor_mock.execute.reset_mock() | ||
282 | with self.subTest(user=1): | ||
283 | rows = list(main.fetch_markets({"foo": "bar"}, 1)) | ||
284 | |||
285 | psycopg2.connect.assert_called_once_with(foo="bar") | ||
286 | cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs WHERE user_id = %s", 1) | ||
287 | |||
288 | self.assertEqual(["row_1", "row_2"], rows) | ||
289 | |||
290 | |||
diff --git a/tests/test_market.py b/tests/test_market.py new file mode 100644 index 0000000..82eeea8 --- /dev/null +++ b/tests/test_market.py | |||
@@ -0,0 +1,900 @@ | |||
1 | from .helper import * | ||
2 | import market, store, portfolio | ||
3 | import datetime | ||
4 | |||
5 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
6 | class MarketTest(WebMockTestCase): | ||
7 | def setUp(self): | ||
8 | super().setUp() | ||
9 | |||
10 | self.ccxt = mock.Mock(spec=market.ccxt.poloniexE) | ||
11 | |||
12 | def test_values(self): | ||
13 | m = market.Market(self.ccxt, self.market_args()) | ||
14 | |||
15 | self.assertEqual(self.ccxt, m.ccxt) | ||
16 | self.assertFalse(m.debug) | ||
17 | self.assertIsInstance(m.report, market.ReportStore) | ||
18 | self.assertIsInstance(m.trades, market.TradeStore) | ||
19 | self.assertIsInstance(m.balances, market.BalanceStore) | ||
20 | self.assertEqual(m, m.report.market) | ||
21 | self.assertEqual(m, m.trades.market) | ||
22 | self.assertEqual(m, m.balances.market) | ||
23 | self.assertEqual(m, m.ccxt._market) | ||
24 | |||
25 | m = market.Market(self.ccxt, self.market_args(debug=True)) | ||
26 | self.assertTrue(m.debug) | ||
27 | |||
28 | m = market.Market(self.ccxt, self.market_args(debug=False)) | ||
29 | self.assertFalse(m.debug) | ||
30 | |||
31 | with mock.patch("market.ReportStore") as report_store: | ||
32 | with self.subTest(quiet=False): | ||
33 | m = market.Market(self.ccxt, self.market_args(quiet=False)) | ||
34 | report_store.assert_called_with(m, verbose_print=True) | ||
35 | report_store().log_market.assert_called_once() | ||
36 | report_store.reset_mock() | ||
37 | with self.subTest(quiet=True): | ||
38 | m = market.Market(self.ccxt, self.market_args(quiet=True)) | ||
39 | report_store.assert_called_with(m, verbose_print=False) | ||
40 | report_store().log_market.assert_called_once() | ||
41 | |||
42 | @mock.patch("market.ccxt") | ||
43 | def test_from_config(self, ccxt): | ||
44 | with mock.patch("market.ReportStore"): | ||
45 | ccxt.poloniexE.return_value = self.ccxt | ||
46 | |||
47 | m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args()) | ||
48 | |||
49 | self.assertEqual(self.ccxt, m.ccxt) | ||
50 | |||
51 | m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args(debug=True)) | ||
52 | self.assertEqual(True, m.debug) | ||
53 | |||
54 | def test_get_tickers(self): | ||
55 | self.ccxt.fetch_tickers.side_effect = [ | ||
56 | "tickers", | ||
57 | market.NotSupported | ||
58 | ] | ||
59 | |||
60 | m = market.Market(self.ccxt, self.market_args()) | ||
61 | self.assertEqual("tickers", m.get_tickers()) | ||
62 | self.assertEqual("tickers", m.get_tickers()) | ||
63 | self.ccxt.fetch_tickers.assert_called_once() | ||
64 | |||
65 | self.assertIsNone(m.get_tickers(refresh=self.time.time())) | ||
66 | |||
67 | def test_get_ticker(self): | ||
68 | with self.subTest(get_tickers=True): | ||
69 | self.ccxt.fetch_tickers.return_value = { | ||
70 | "ETH/ETC": { "bid": 1, "ask": 3 }, | ||
71 | "XVG/ETH": { "bid": 10, "ask": 40 }, | ||
72 | } | ||
73 | m = market.Market(self.ccxt, self.market_args()) | ||
74 | |||
75 | ticker = m.get_ticker("ETH", "ETC") | ||
76 | self.assertEqual(1, ticker["bid"]) | ||
77 | self.assertEqual(3, ticker["ask"]) | ||
78 | self.assertEqual(2, ticker["average"]) | ||
79 | self.assertFalse(ticker["inverted"]) | ||
80 | |||
81 | ticker = m.get_ticker("ETH", "XVG") | ||
82 | self.assertEqual(0.0625, ticker["average"]) | ||
83 | self.assertTrue(ticker["inverted"]) | ||
84 | self.assertIn("original", ticker) | ||
85 | self.assertEqual(10, ticker["original"]["bid"]) | ||
86 | self.assertEqual(25, ticker["original"]["average"]) | ||
87 | |||
88 | ticker = m.get_ticker("XVG", "XMR") | ||
89 | self.assertIsNone(ticker) | ||
90 | |||
91 | with self.subTest(get_tickers=False): | ||
92 | self.ccxt.fetch_tickers.return_value = None | ||
93 | self.ccxt.fetch_ticker.side_effect = [ | ||
94 | { "bid": 1, "ask": 3 }, | ||
95 | market.ExchangeError("foo"), | ||
96 | { "bid": 10, "ask": 40 }, | ||
97 | market.ExchangeError("foo"), | ||
98 | market.ExchangeError("foo"), | ||
99 | ] | ||
100 | |||
101 | m = market.Market(self.ccxt, self.market_args()) | ||
102 | |||
103 | ticker = m.get_ticker("ETH", "ETC") | ||
104 | self.ccxt.fetch_ticker.assert_called_with("ETH/ETC") | ||
105 | self.assertEqual(1, ticker["bid"]) | ||
106 | self.assertEqual(3, ticker["ask"]) | ||
107 | self.assertEqual(2, ticker["average"]) | ||
108 | self.assertFalse(ticker["inverted"]) | ||
109 | |||
110 | ticker = m.get_ticker("ETH", "XVG") | ||
111 | self.assertEqual(0.0625, ticker["average"]) | ||
112 | self.assertTrue(ticker["inverted"]) | ||
113 | self.assertIn("original", ticker) | ||
114 | self.assertEqual(10, ticker["original"]["bid"]) | ||
115 | self.assertEqual(25, ticker["original"]["average"]) | ||
116 | |||
117 | ticker = m.get_ticker("XVG", "XMR") | ||
118 | self.assertIsNone(ticker) | ||
119 | |||
120 | def test_fetch_fees(self): | ||
121 | m = market.Market(self.ccxt, self.market_args()) | ||
122 | self.ccxt.fetch_fees.return_value = "Foo" | ||
123 | self.assertEqual("Foo", m.fetch_fees()) | ||
124 | self.ccxt.fetch_fees.assert_called_once() | ||
125 | self.ccxt.reset_mock() | ||
126 | self.assertEqual("Foo", m.fetch_fees()) | ||
127 | self.ccxt.fetch_fees.assert_not_called() | ||
128 | |||
129 | @mock.patch.object(market.Portfolio, "repartition") | ||
130 | @mock.patch.object(market.Market, "get_ticker") | ||
131 | @mock.patch.object(market.TradeStore, "compute_trades") | ||
132 | def test_prepare_trades(self, compute_trades, get_ticker, repartition): | ||
133 | repartition.return_value = { | ||
134 | "XEM": (D("0.75"), "long"), | ||
135 | "BTC": (D("0.25"), "long"), | ||
136 | } | ||
137 | def _get_ticker(c1, c2): | ||
138 | if c1 == "USDT" and c2 == "BTC": | ||
139 | return { "average": D("0.0001") } | ||
140 | if c1 == "XVG" and c2 == "BTC": | ||
141 | return { "average": D("0.000001") } | ||
142 | self.fail("Should be called with {}, {}".format(c1, c2)) | ||
143 | get_ticker.side_effect = _get_ticker | ||
144 | |||
145 | with mock.patch("market.ReportStore"): | ||
146 | m = market.Market(self.ccxt, self.market_args()) | ||
147 | self.ccxt.fetch_all_balances.return_value = { | ||
148 | "USDT": { | ||
149 | "exchange_free": D("10000.0"), | ||
150 | "exchange_used": D("0.0"), | ||
151 | "exchange_total": D("10000.0"), | ||
152 | "total": D("10000.0") | ||
153 | }, | ||
154 | "XVG": { | ||
155 | "exchange_free": D("10000.0"), | ||
156 | "exchange_used": D("0.0"), | ||
157 | "exchange_total": D("10000.0"), | ||
158 | "total": D("10000.0") | ||
159 | }, | ||
160 | } | ||
161 | |||
162 | m.balances.fetch_balances(tag="tag") | ||
163 | |||
164 | m.prepare_trades() | ||
165 | compute_trades.assert_called() | ||
166 | |||
167 | call = compute_trades.call_args | ||
168 | self.assertEqual(1, call[0][0]["USDT"].value) | ||
169 | self.assertEqual(D("0.01"), call[0][0]["XVG"].value) | ||
170 | self.assertEqual(D("0.2525"), call[0][1]["BTC"].value) | ||
171 | self.assertEqual(D("0.7575"), call[0][1]["XEM"].value) | ||
172 | m.report.log_stage.assert_called_once_with("prepare_trades", | ||
173 | base_currency='BTC', compute_value='average', | ||
174 | liquidity='medium', only=None, repartition=None) | ||
175 | m.report.log_balances.assert_called_once_with(tag="tag") | ||
176 | |||
177 | |||
178 | @mock.patch.object(market.time, "sleep") | ||
179 | @mock.patch.object(market.TradeStore, "all_orders") | ||
180 | def test_follow_orders(self, all_orders, time_mock): | ||
181 | for debug, sleep in [ | ||
182 | (False, None), (True, None), | ||
183 | (False, 12), (True, 12)]: | ||
184 | with self.subTest(sleep=sleep, debug=debug), \ | ||
185 | mock.patch("market.ReportStore"): | ||
186 | m = market.Market(self.ccxt, self.market_args(debug=debug)) | ||
187 | |||
188 | order_mock1 = mock.Mock() | ||
189 | order_mock2 = mock.Mock() | ||
190 | order_mock3 = mock.Mock() | ||
191 | all_orders.side_effect = [ | ||
192 | [order_mock1, order_mock2], | ||
193 | [order_mock1, order_mock2], | ||
194 | |||
195 | [order_mock1, order_mock3], | ||
196 | [order_mock1, order_mock3], | ||
197 | |||
198 | [order_mock1, order_mock3], | ||
199 | [order_mock1, order_mock3], | ||
200 | |||
201 | [] | ||
202 | ] | ||
203 | |||
204 | order_mock1.get_status.side_effect = ["open", "open", "closed"] | ||
205 | order_mock2.get_status.side_effect = ["open"] | ||
206 | order_mock3.get_status.side_effect = ["open", "closed"] | ||
207 | |||
208 | order_mock1.trade = mock.Mock() | ||
209 | order_mock2.trade = mock.Mock() | ||
210 | order_mock3.trade = mock.Mock() | ||
211 | |||
212 | m.follow_orders(sleep=sleep) | ||
213 | |||
214 | order_mock1.trade.update_order.assert_any_call(order_mock1, 1) | ||
215 | order_mock1.trade.update_order.assert_any_call(order_mock1, 2) | ||
216 | self.assertEqual(2, order_mock1.trade.update_order.call_count) | ||
217 | self.assertEqual(3, order_mock1.get_status.call_count) | ||
218 | |||
219 | order_mock2.trade.update_order.assert_any_call(order_mock2, 1) | ||
220 | self.assertEqual(1, order_mock2.trade.update_order.call_count) | ||
221 | self.assertEqual(1, order_mock2.get_status.call_count) | ||
222 | |||
223 | order_mock3.trade.update_order.assert_any_call(order_mock3, 2) | ||
224 | self.assertEqual(1, order_mock3.trade.update_order.call_count) | ||
225 | self.assertEqual(2, order_mock3.get_status.call_count) | ||
226 | m.report.log_stage.assert_called() | ||
227 | calls = [ | ||
228 | mock.call("follow_orders_begin"), | ||
229 | mock.call("follow_orders_tick_1"), | ||
230 | mock.call("follow_orders_tick_2"), | ||
231 | mock.call("follow_orders_tick_3"), | ||
232 | mock.call("follow_orders_end"), | ||
233 | ] | ||
234 | m.report.log_stage.assert_has_calls(calls) | ||
235 | m.report.log_orders.assert_called() | ||
236 | self.assertEqual(3, m.report.log_orders.call_count) | ||
237 | calls = [ | ||
238 | mock.call([order_mock1, order_mock2], tick=1), | ||
239 | mock.call([order_mock1, order_mock3], tick=2), | ||
240 | mock.call([order_mock1, order_mock3], tick=3), | ||
241 | ] | ||
242 | m.report.log_orders.assert_has_calls(calls) | ||
243 | calls = [ | ||
244 | mock.call(order_mock1, 3, finished=True), | ||
245 | mock.call(order_mock3, 3, finished=True), | ||
246 | ] | ||
247 | m.report.log_order.assert_has_calls(calls) | ||
248 | |||
249 | if sleep is None: | ||
250 | if debug: | ||
251 | m.report.log_debug_action.assert_called_with("Set follow_orders tick to 7s") | ||
252 | time_mock.assert_called_with(7) | ||
253 | else: | ||
254 | time_mock.assert_called_with(30) | ||
255 | else: | ||
256 | time_mock.assert_called_with(sleep) | ||
257 | |||
258 | with self.subTest("disappearing order"), \ | ||
259 | mock.patch("market.ReportStore"): | ||
260 | all_orders.reset_mock() | ||
261 | m = market.Market(self.ccxt, self.market_args()) | ||
262 | |||
263 | order_mock1 = mock.Mock() | ||
264 | order_mock2 = mock.Mock() | ||
265 | all_orders.side_effect = [ | ||
266 | [order_mock1, order_mock2], | ||
267 | [order_mock1, order_mock2], | ||
268 | |||
269 | [order_mock1, order_mock2], | ||
270 | [order_mock1, order_mock2], | ||
271 | |||
272 | [] | ||
273 | ] | ||
274 | |||
275 | order_mock1.get_status.side_effect = ["open", "closed"] | ||
276 | order_mock2.get_status.side_effect = ["open", "error_disappeared"] | ||
277 | |||
278 | order_mock1.trade = mock.Mock() | ||
279 | trade_mock = mock.Mock() | ||
280 | order_mock2.trade = trade_mock | ||
281 | |||
282 | trade_mock.tick_actions_recreate.return_value = "tick1" | ||
283 | |||
284 | m.follow_orders() | ||
285 | |||
286 | trade_mock.tick_actions_recreate.assert_called_once_with(2) | ||
287 | trade_mock.prepare_order.assert_called_once_with(compute_value="tick1") | ||
288 | m.report.log_error.assert_called_once_with("follow_orders", message=mock.ANY) | ||
289 | |||
290 | @mock.patch.object(market.BalanceStore, "fetch_balances") | ||
291 | def test_move_balance(self, fetch_balances): | ||
292 | for debug in [True, False]: | ||
293 | with self.subTest(debug=debug),\ | ||
294 | mock.patch("market.ReportStore"): | ||
295 | m = market.Market(self.ccxt, self.market_args(debug=debug)) | ||
296 | |||
297 | value_from = portfolio.Amount("BTC", "1.0") | ||
298 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
299 | value_to = portfolio.Amount("BTC", "10.0") | ||
300 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
301 | |||
302 | value_from = portfolio.Amount("BTC", "0.0") | ||
303 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
304 | value_to = portfolio.Amount("BTC", "-3.0") | ||
305 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
306 | |||
307 | value_from = portfolio.Amount("USDT", "0.0") | ||
308 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | ||
309 | value_to = portfolio.Amount("USDT", "-50.0") | ||
310 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) | ||
311 | |||
312 | m.trades.all = [trade1, trade2, trade3] | ||
313 | balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
314 | balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }) | ||
315 | balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }) | ||
316 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} | ||
317 | |||
318 | m.move_balances() | ||
319 | |||
320 | fetch_balances.assert_called_with() | ||
321 | m.report.log_move_balances.assert_called_once() | ||
322 | |||
323 | if debug: | ||
324 | m.report.log_debug_action.assert_called() | ||
325 | self.assertEqual(3, m.report.log_debug_action.call_count) | ||
326 | else: | ||
327 | self.ccxt.transfer_balance.assert_any_call("BTC", 3, "exchange", "margin") | ||
328 | self.ccxt.transfer_balance.assert_any_call("USDT", 100, "exchange", "margin") | ||
329 | self.ccxt.transfer_balance.assert_any_call("ETC", 5, "margin", "exchange") | ||
330 | |||
331 | m.report.reset_mock() | ||
332 | fetch_balances.reset_mock() | ||
333 | with self.subTest(retry=True): | ||
334 | with mock.patch("market.ReportStore"): | ||
335 | m = market.Market(self.ccxt, self.market_args()) | ||
336 | |||
337 | value_from = portfolio.Amount("BTC", "0.0") | ||
338 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
339 | value_to = portfolio.Amount("BTC", "-3.0") | ||
340 | trade = portfolio.Trade(value_from, value_to, "ETH", m) | ||
341 | |||
342 | m.trades.all = [trade] | ||
343 | balance = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
344 | m.balances.all = {"BTC": balance} | ||
345 | |||
346 | m.ccxt.transfer_balance.side_effect = [ | ||
347 | market.ccxt.RequestTimeout, | ||
348 | market.ccxt.InvalidNonce, | ||
349 | True | ||
350 | ] | ||
351 | m.move_balances() | ||
352 | self.ccxt.transfer_balance.assert_has_calls([ | ||
353 | mock.call("BTC", 3, "exchange", "margin"), | ||
354 | mock.call("BTC", 3, "exchange", "margin"), | ||
355 | mock.call("BTC", 3, "exchange", "margin") | ||
356 | ]) | ||
357 | self.assertEqual(3, fetch_balances.call_count) | ||
358 | m.report.log_error.assert_called_with(mock.ANY, message="Retrying", exception=mock.ANY) | ||
359 | self.assertEqual(3, m.report.log_move_balances.call_count) | ||
360 | |||
361 | self.ccxt.transfer_balance.reset_mock() | ||
362 | m.report.reset_mock() | ||
363 | fetch_balances.reset_mock() | ||
364 | with self.subTest(retry=True, too_much=True): | ||
365 | with mock.patch("market.ReportStore"): | ||
366 | m = market.Market(self.ccxt, self.market_args()) | ||
367 | |||
368 | value_from = portfolio.Amount("BTC", "0.0") | ||
369 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
370 | value_to = portfolio.Amount("BTC", "-3.0") | ||
371 | trade = portfolio.Trade(value_from, value_to, "ETH", m) | ||
372 | |||
373 | m.trades.all = [trade] | ||
374 | balance = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
375 | m.balances.all = {"BTC": balance} | ||
376 | |||
377 | m.ccxt.transfer_balance.side_effect = [ | ||
378 | market.ccxt.RequestTimeout, | ||
379 | market.ccxt.RequestTimeout, | ||
380 | market.ccxt.RequestTimeout, | ||
381 | market.ccxt.RequestTimeout, | ||
382 | market.ccxt.RequestTimeout, | ||
383 | ] | ||
384 | with self.assertRaises(market.ccxt.RequestTimeout): | ||
385 | m.move_balances() | ||
386 | |||
387 | self.ccxt.transfer_balance.reset_mock() | ||
388 | m.report.reset_mock() | ||
389 | fetch_balances.reset_mock() | ||
390 | with self.subTest(retry=True, partial_result=True): | ||
391 | with mock.patch("market.ReportStore"): | ||
392 | m = market.Market(self.ccxt, self.market_args()) | ||
393 | |||
394 | value_from = portfolio.Amount("BTC", "1.0") | ||
395 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
396 | value_to = portfolio.Amount("BTC", "10.0") | ||
397 | trade1 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
398 | |||
399 | value_from = portfolio.Amount("BTC", "0.0") | ||
400 | value_from.linked_to = portfolio.Amount("ETH", "0.0") | ||
401 | value_to = portfolio.Amount("BTC", "-3.0") | ||
402 | trade2 = portfolio.Trade(value_from, value_to, "ETH", m) | ||
403 | |||
404 | value_from = portfolio.Amount("USDT", "0.0") | ||
405 | value_from.linked_to = portfolio.Amount("XVG", "0.0") | ||
406 | value_to = portfolio.Amount("USDT", "-50.0") | ||
407 | trade3 = portfolio.Trade(value_from, value_to, "XVG", m) | ||
408 | |||
409 | m.trades.all = [trade1, trade2, trade3] | ||
410 | balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }) | ||
411 | balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }) | ||
412 | balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }) | ||
413 | m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3} | ||
414 | |||
415 | call_counts = { "BTC": 0, "USDT": 0, "ETC": 0 } | ||
416 | def _transfer_balance(currency, amount, from_, to_): | ||
417 | call_counts[currency] += 1 | ||
418 | if currency == "BTC": | ||
419 | m.balances.all["BTC"] = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "3" }) | ||
420 | if currency == "USDT": | ||
421 | if call_counts["USDT"] == 1: | ||
422 | raise market.ccxt.RequestTimeout | ||
423 | else: | ||
424 | m.balances.all["USDT"] = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "150" }) | ||
425 | if currency == "ETC": | ||
426 | m.balances.all["ETC"] = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "10" }) | ||
427 | |||
428 | |||
429 | m.ccxt.transfer_balance.side_effect = _transfer_balance | ||
430 | |||
431 | m.move_balances() | ||
432 | self.ccxt.transfer_balance.assert_has_calls([ | ||
433 | mock.call("BTC", 3, "exchange", "margin"), | ||
434 | mock.call('USDT', 100, 'exchange', 'margin'), | ||
435 | mock.call('USDT', 100, 'exchange', 'margin'), | ||
436 | mock.call("ETC", 5, "margin", "exchange") | ||
437 | ]) | ||
438 | self.assertEqual(2, fetch_balances.call_count) | ||
439 | m.report.log_error.assert_called_with(mock.ANY, message="Retrying", exception=mock.ANY) | ||
440 | self.assertEqual(2, m.report.log_move_balances.call_count) | ||
441 | m.report.log_move_balances.asser_has_calls([ | ||
442 | mock.call( | ||
443 | { | ||
444 | 'BTC': portfolio.Amount("BTC", "3"), | ||
445 | 'USDT': portfolio.Amount("USDT", "150"), | ||
446 | 'ETC': portfolio.Amount("ETC", "10"), | ||
447 | }, | ||
448 | { | ||
449 | 'BTC': portfolio.Amount("BTC", "3"), | ||
450 | 'USDT': portfolio.Amount("USDT", "100"), | ||
451 | }), | ||
452 | mock.call( | ||
453 | { | ||
454 | 'BTC': portfolio.Amount("BTC", "3"), | ||
455 | 'USDT': portfolio.Amount("USDT", "150"), | ||
456 | 'ETC': portfolio.Amount("ETC", "10"), | ||
457 | }, | ||
458 | { | ||
459 | 'BTC': portfolio.Amount("BTC", "0"), | ||
460 | 'USDT': portfolio.Amount("USDT", "100"), | ||
461 | 'ETC': portfolio.Amount("ETC", "-5"), | ||
462 | }), | ||
463 | ]) | ||
464 | |||
465 | |||
466 | def test_store_file_report(self): | ||
467 | file_open = mock.mock_open() | ||
468 | m = market.Market(self.ccxt, | ||
469 | self.market_args(report_path="present"), user_id=1) | ||
470 | with self.subTest(file="present"),\ | ||
471 | mock.patch("market.open", file_open),\ | ||
472 | mock.patch.object(m, "report") as report,\ | ||
473 | mock.patch.object(market, "datetime") as time_mock: | ||
474 | |||
475 | report.print_logs = [[time_mock.now(), "Foo"], [time_mock.now(), "Bar"]] | ||
476 | report.to_json.return_value = "json_content" | ||
477 | |||
478 | m.store_file_report(datetime.datetime(2018, 2, 25)) | ||
479 | |||
480 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.json", "w") | ||
481 | file_open.assert_any_call("present/2018-02-25T00:00:00_1.log", "w") | ||
482 | file_open().write.assert_any_call("json_content") | ||
483 | file_open().write.assert_any_call("Foo\nBar") | ||
484 | m.report.to_json.assert_called_once_with() | ||
485 | |||
486 | m = market.Market(self.ccxt, self.market_args(report_path="error"), user_id=1) | ||
487 | with self.subTest(file="error"),\ | ||
488 | mock.patch("market.open") as file_open,\ | ||
489 | mock.patch.object(m, "report") as report,\ | ||
490 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
491 | file_open.side_effect = FileNotFoundError | ||
492 | |||
493 | m.store_file_report(datetime.datetime(2018, 2, 25)) | ||
494 | |||
495 | self.assertRegex(stdout_mock.getvalue(), "impossible to store report file: FileNotFoundError;") | ||
496 | |||
497 | @mock.patch.object(market, "psycopg2") | ||
498 | def test_store_database_report(self, psycopg2): | ||
499 | connect_mock = mock.Mock() | ||
500 | cursor_mock = mock.MagicMock() | ||
501 | |||
502 | connect_mock.cursor.return_value = cursor_mock | ||
503 | psycopg2.connect.return_value = connect_mock | ||
504 | m = market.Market(self.ccxt, self.market_args(), | ||
505 | pg_config={"config": "pg_config"}, user_id=1) | ||
506 | cursor_mock.fetchone.return_value = [42] | ||
507 | |||
508 | with self.subTest(error=False),\ | ||
509 | mock.patch.object(m, "report") as report: | ||
510 | report.to_json_array.return_value = [ | ||
511 | ("date1", "type1", "payload1"), | ||
512 | ("date2", "type2", "payload2"), | ||
513 | ] | ||
514 | m.store_database_report(datetime.datetime(2018, 3, 24)) | ||
515 | connect_mock.assert_has_calls([ | ||
516 | mock.call.cursor(), | ||
517 | mock.call.cursor().execute('INSERT INTO reports("date", "market_config_id", "debug") VALUES (%s, %s, %s) RETURNING id;', (datetime.datetime(2018, 3, 24), None, False)), | ||
518 | mock.call.cursor().fetchone(), | ||
519 | mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date1', 42, 'type1', 'payload1')), | ||
520 | mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date2', 42, 'type2', 'payload2')), | ||
521 | mock.call.commit(), | ||
522 | mock.call.cursor().close(), | ||
523 | mock.call.close() | ||
524 | ]) | ||
525 | |||
526 | connect_mock.reset_mock() | ||
527 | with self.subTest(error=True),\ | ||
528 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
529 | psycopg2.connect.side_effect = Exception("Bouh") | ||
530 | m.store_database_report(datetime.datetime(2018, 3, 24)) | ||
531 | self.assertEqual(stdout_mock.getvalue(), "impossible to store report to database: Exception; Bouh\n") | ||
532 | |||
533 | def test_store_report(self): | ||
534 | m = market.Market(self.ccxt, self.market_args(report_db=False), user_id=1) | ||
535 | with self.subTest(file=None, pg_config=None),\ | ||
536 | mock.patch.object(m, "report") as report,\ | ||
537 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
538 | mock.patch.object(m, "store_file_report") as file_report: | ||
539 | m.store_report() | ||
540 | report.merge.assert_called_with(store.Portfolio.report) | ||
541 | |||
542 | file_report.assert_not_called() | ||
543 | db_report.assert_not_called() | ||
544 | |||
545 | report.reset_mock() | ||
546 | m = market.Market(self.ccxt, self.market_args(report_db=False, report_path="present"), user_id=1) | ||
547 | with self.subTest(file="present", pg_config=None),\ | ||
548 | mock.patch.object(m, "report") as report,\ | ||
549 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
550 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
551 | mock.patch.object(market, "datetime") as time_mock: | ||
552 | |||
553 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
554 | |||
555 | m.store_report() | ||
556 | |||
557 | report.merge.assert_called_with(store.Portfolio.report) | ||
558 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
559 | db_report.assert_not_called() | ||
560 | |||
561 | report.reset_mock() | ||
562 | m = market.Market(self.ccxt, self.market_args(report_db=True, report_path="present"), user_id=1) | ||
563 | with self.subTest(file="present", pg_config=None, report_db=True),\ | ||
564 | mock.patch.object(m, "report") as report,\ | ||
565 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
566 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
567 | mock.patch.object(market, "datetime") as time_mock: | ||
568 | |||
569 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
570 | |||
571 | m.store_report() | ||
572 | |||
573 | report.merge.assert_called_with(store.Portfolio.report) | ||
574 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
575 | db_report.assert_not_called() | ||
576 | |||
577 | report.reset_mock() | ||
578 | m = market.Market(self.ccxt, self.market_args(report_db=True), pg_config="present", user_id=1) | ||
579 | with self.subTest(file=None, pg_config="present"),\ | ||
580 | mock.patch.object(m, "report") as report,\ | ||
581 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
582 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
583 | mock.patch.object(market, "datetime") as time_mock: | ||
584 | |||
585 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
586 | |||
587 | m.store_report() | ||
588 | |||
589 | report.merge.assert_called_with(store.Portfolio.report) | ||
590 | file_report.assert_not_called() | ||
591 | db_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
592 | |||
593 | report.reset_mock() | ||
594 | m = market.Market(self.ccxt, self.market_args(report_db=True, report_path="present"), | ||
595 | pg_config="pg_config", user_id=1) | ||
596 | with self.subTest(file="present", pg_config="present"),\ | ||
597 | mock.patch.object(m, "report") as report,\ | ||
598 | mock.patch.object(m, "store_file_report") as file_report,\ | ||
599 | mock.patch.object(m, "store_database_report") as db_report,\ | ||
600 | mock.patch.object(market, "datetime") as time_mock: | ||
601 | |||
602 | time_mock.now.return_value = datetime.datetime(2018, 2, 25) | ||
603 | |||
604 | m.store_report() | ||
605 | |||
606 | report.merge.assert_called_with(store.Portfolio.report) | ||
607 | file_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
608 | db_report.assert_called_once_with(datetime.datetime(2018, 2, 25)) | ||
609 | |||
610 | def test_print_orders(self): | ||
611 | m = market.Market(self.ccxt, self.market_args()) | ||
612 | with mock.patch.object(m.report, "log_stage") as log_stage,\ | ||
613 | mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\ | ||
614 | mock.patch.object(m, "prepare_trades") as prepare_trades,\ | ||
615 | mock.patch.object(m.trades, "prepare_orders") as prepare_orders: | ||
616 | m.print_orders() | ||
617 | |||
618 | log_stage.assert_called_with("print_orders") | ||
619 | fetch_balances.assert_called_with(tag="print_orders") | ||
620 | prepare_trades.assert_called_with(base_currency="BTC", | ||
621 | compute_value="average") | ||
622 | prepare_orders.assert_called_with(compute_value="average") | ||
623 | |||
624 | def test_print_balances(self): | ||
625 | m = market.Market(self.ccxt, self.market_args()) | ||
626 | |||
627 | with mock.patch.object(m.balances, "in_currency") as in_currency,\ | ||
628 | mock.patch.object(m.report, "log_stage") as log_stage,\ | ||
629 | mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\ | ||
630 | mock.patch.object(m.report, "print_log") as print_log: | ||
631 | |||
632 | in_currency.return_value = { | ||
633 | "BTC": portfolio.Amount("BTC", "0.65"), | ||
634 | "ETH": portfolio.Amount("BTC", "0.3"), | ||
635 | } | ||
636 | |||
637 | m.print_balances() | ||
638 | |||
639 | log_stage.assert_called_once_with("print_balances") | ||
640 | fetch_balances.assert_called_with() | ||
641 | print_log.assert_has_calls([ | ||
642 | mock.call("total:"), | ||
643 | mock.call(portfolio.Amount("BTC", "0.95")), | ||
644 | ]) | ||
645 | |||
646 | @mock.patch("market.Processor.process") | ||
647 | @mock.patch("market.ReportStore.log_error") | ||
648 | @mock.patch("market.Market.store_report") | ||
649 | def test_process(self, store_report, log_error, process): | ||
650 | m = market.Market(self.ccxt, self.market_args()) | ||
651 | with self.subTest(before=False, after=False): | ||
652 | m.process(None) | ||
653 | |||
654 | process.assert_not_called() | ||
655 | store_report.assert_called_once() | ||
656 | log_error.assert_not_called() | ||
657 | |||
658 | process.reset_mock() | ||
659 | log_error.reset_mock() | ||
660 | store_report.reset_mock() | ||
661 | with self.subTest(before=True, after=False): | ||
662 | m.process(None, before=True) | ||
663 | |||
664 | process.assert_called_once_with("sell_all", steps="before") | ||
665 | store_report.assert_called_once() | ||
666 | log_error.assert_not_called() | ||
667 | |||
668 | process.reset_mock() | ||
669 | log_error.reset_mock() | ||
670 | store_report.reset_mock() | ||
671 | with self.subTest(before=False, after=True): | ||
672 | m.process(None, after=True) | ||
673 | |||
674 | process.assert_called_once_with("sell_all", steps="after") | ||
675 | store_report.assert_called_once() | ||
676 | log_error.assert_not_called() | ||
677 | |||
678 | process.reset_mock() | ||
679 | log_error.reset_mock() | ||
680 | store_report.reset_mock() | ||
681 | with self.subTest(before=True, after=True): | ||
682 | m.process(None, before=True, after=True) | ||
683 | |||
684 | process.assert_has_calls([ | ||
685 | mock.call("sell_all", steps="before"), | ||
686 | mock.call("sell_all", steps="after"), | ||
687 | ]) | ||
688 | store_report.assert_called_once() | ||
689 | log_error.assert_not_called() | ||
690 | |||
691 | process.reset_mock() | ||
692 | log_error.reset_mock() | ||
693 | store_report.reset_mock() | ||
694 | with self.subTest(action="print_balances"),\ | ||
695 | mock.patch.object(m, "print_balances") as print_balances: | ||
696 | m.process(["print_balances"]) | ||
697 | |||
698 | process.assert_not_called() | ||
699 | log_error.assert_not_called() | ||
700 | store_report.assert_called_once() | ||
701 | print_balances.assert_called_once_with() | ||
702 | |||
703 | log_error.reset_mock() | ||
704 | store_report.reset_mock() | ||
705 | with self.subTest(action="print_orders"),\ | ||
706 | mock.patch.object(m, "print_orders") as print_orders,\ | ||
707 | mock.patch.object(m, "print_balances") as print_balances: | ||
708 | m.process(["print_orders", "print_balances"]) | ||
709 | |||
710 | process.assert_not_called() | ||
711 | log_error.assert_not_called() | ||
712 | store_report.assert_called_once() | ||
713 | print_orders.assert_called_once_with() | ||
714 | print_balances.assert_called_once_with() | ||
715 | |||
716 | log_error.reset_mock() | ||
717 | store_report.reset_mock() | ||
718 | with self.subTest(action="unknown"): | ||
719 | m.process(["unknown"]) | ||
720 | log_error.assert_called_once_with("market_process", message="Unknown action unknown") | ||
721 | store_report.assert_called_once() | ||
722 | |||
723 | log_error.reset_mock() | ||
724 | store_report.reset_mock() | ||
725 | with self.subTest(unhandled_exception=True): | ||
726 | process.side_effect = Exception("bouh") | ||
727 | |||
728 | m.process(None, before=True) | ||
729 | log_error.assert_called_with("market_process", exception=mock.ANY) | ||
730 | store_report.assert_called_once() | ||
731 | |||
732 | |||
733 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
734 | class ProcessorTest(WebMockTestCase): | ||
735 | def test_values(self): | ||
736 | processor = market.Processor(self.m) | ||
737 | |||
738 | self.assertEqual(self.m, processor.market) | ||
739 | |||
740 | def test_run_action(self): | ||
741 | processor = market.Processor(self.m) | ||
742 | |||
743 | with mock.patch.object(processor, "parse_args") as parse_args: | ||
744 | method_mock = mock.Mock() | ||
745 | parse_args.return_value = [method_mock, { "foo": "bar" }] | ||
746 | |||
747 | processor.run_action("foo", "bar", "baz") | ||
748 | |||
749 | parse_args.assert_called_with("foo", "bar", "baz") | ||
750 | |||
751 | method_mock.assert_called_with(foo="bar") | ||
752 | |||
753 | processor.run_action("wait_for_recent", "bar", "baz") | ||
754 | |||
755 | method_mock.assert_called_with(foo="bar") | ||
756 | |||
757 | def test_select_step(self): | ||
758 | processor = market.Processor(self.m) | ||
759 | |||
760 | scenario = processor.scenarios["sell_all"] | ||
761 | |||
762 | self.assertEqual(scenario, processor.select_steps(scenario, "all")) | ||
763 | self.assertEqual(["all_sell"], list(map(lambda x: x["name"], processor.select_steps(scenario, "before")))) | ||
764 | self.assertEqual(["wait", "all_buy"], list(map(lambda x: x["name"], processor.select_steps(scenario, "after")))) | ||
765 | self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, 2)))) | ||
766 | self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, "wait")))) | ||
767 | |||
768 | with self.assertRaises(TypeError): | ||
769 | processor.select_steps(scenario, ["wait"]) | ||
770 | |||
771 | @mock.patch("market.Processor.process_step") | ||
772 | def test_process(self, process_step): | ||
773 | processor = market.Processor(self.m) | ||
774 | |||
775 | processor.process("sell_all", foo="bar") | ||
776 | self.assertEqual(3, process_step.call_count) | ||
777 | |||
778 | steps = list(map(lambda x: x[1][1]["name"], process_step.mock_calls)) | ||
779 | scenario_names = list(map(lambda x: x[1][0], process_step.mock_calls)) | ||
780 | kwargs = list(map(lambda x: x[1][2], process_step.mock_calls)) | ||
781 | self.assertEqual(["all_sell", "wait", "all_buy"], steps) | ||
782 | self.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names) | ||
783 | self.assertEqual([{"foo":"bar"}, {"foo":"bar"}, {"foo":"bar"}], kwargs) | ||
784 | |||
785 | process_step.reset_mock() | ||
786 | |||
787 | processor.process("sell_needed", steps=["before", "after"]) | ||
788 | self.assertEqual(3, process_step.call_count) | ||
789 | |||
790 | def test_method_arguments(self): | ||
791 | ccxt = mock.Mock(spec=market.ccxt.poloniexE) | ||
792 | m = market.Market(ccxt, self.market_args()) | ||
793 | |||
794 | processor = market.Processor(m) | ||
795 | |||
796 | method, arguments = processor.method_arguments("wait_for_recent") | ||
797 | self.assertEqual(market.Portfolio.wait_for_recent, method) | ||
798 | self.assertEqual(["delta", "poll"], arguments) | ||
799 | |||
800 | method, arguments = processor.method_arguments("prepare_trades") | ||
801 | self.assertEqual(m.prepare_trades, method) | ||
802 | self.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments) | ||
803 | |||
804 | method, arguments = processor.method_arguments("prepare_orders") | ||
805 | self.assertEqual(m.trades.prepare_orders, method) | ||
806 | |||
807 | method, arguments = processor.method_arguments("move_balances") | ||
808 | self.assertEqual(m.move_balances, method) | ||
809 | |||
810 | method, arguments = processor.method_arguments("run_orders") | ||
811 | self.assertEqual(m.trades.run_orders, method) | ||
812 | |||
813 | method, arguments = processor.method_arguments("follow_orders") | ||
814 | self.assertEqual(m.follow_orders, method) | ||
815 | |||
816 | method, arguments = processor.method_arguments("close_trades") | ||
817 | self.assertEqual(m.trades.close_trades, method) | ||
818 | |||
819 | def test_process_step(self): | ||
820 | processor = market.Processor(self.m) | ||
821 | |||
822 | with mock.patch.object(processor, "run_action") as run_action: | ||
823 | step = processor.scenarios["sell_needed"][1] | ||
824 | |||
825 | processor.process_step("foo", step, {"foo":"bar"}) | ||
826 | |||
827 | self.m.report.log_stage.assert_has_calls([ | ||
828 | mock.call("process_foo__1_sell_begin"), | ||
829 | mock.call("process_foo__1_sell_end"), | ||
830 | ]) | ||
831 | self.m.balances.fetch_balances.assert_has_calls([ | ||
832 | mock.call(tag="process_foo__1_sell_begin"), | ||
833 | mock.call(tag="process_foo__1_sell_end"), | ||
834 | ]) | ||
835 | |||
836 | self.assertEqual(5, run_action.call_count) | ||
837 | |||
838 | run_action.assert_has_calls([ | ||
839 | mock.call('prepare_trades', {}, {'foo': 'bar'}), | ||
840 | mock.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}, {'foo': 'bar'}), | ||
841 | mock.call('run_orders', {}, {'foo': 'bar'}), | ||
842 | mock.call('follow_orders', {}, {'foo': 'bar'}), | ||
843 | mock.call('close_trades', {}, {'foo': 'bar'}), | ||
844 | ]) | ||
845 | |||
846 | self.m.reset_mock() | ||
847 | with mock.patch.object(processor, "run_action") as run_action: | ||
848 | step = processor.scenarios["sell_needed"][0] | ||
849 | |||
850 | processor.process_step("foo", step, {"foo":"bar"}) | ||
851 | self.m.balances.fetch_balances.assert_not_called() | ||
852 | |||
853 | def test_parse_args(self): | ||
854 | processor = market.Processor(self.m) | ||
855 | |||
856 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
857 | method_mock = mock.Mock() | ||
858 | method_arguments.return_value = [ | ||
859 | method_mock, | ||
860 | ["foo2", "foo"] | ||
861 | ] | ||
862 | method, args = processor.parse_args("action", {"foo": "bar", "foo2": "bar"}, {"foo": "bar2", "bla": "bla"}) | ||
863 | |||
864 | self.assertEqual(method_mock, method) | ||
865 | self.assertEqual({"foo": "bar2", "foo2": "bar"}, args) | ||
866 | |||
867 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
868 | method_mock = mock.Mock() | ||
869 | method_arguments.return_value = [ | ||
870 | method_mock, | ||
871 | ["repartition"] | ||
872 | ] | ||
873 | method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {}) | ||
874 | |||
875 | self.assertEqual(1, len(args["repartition"])) | ||
876 | self.assertIn("BTC", args["repartition"]) | ||
877 | |||
878 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
879 | method_mock = mock.Mock() | ||
880 | method_arguments.return_value = [ | ||
881 | method_mock, | ||
882 | ["repartition", "base_currency"] | ||
883 | ] | ||
884 | method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {"base_currency": "USDT"}) | ||
885 | |||
886 | self.assertEqual(1, len(args["repartition"])) | ||
887 | self.assertIn("USDT", args["repartition"]) | ||
888 | |||
889 | with mock.patch.object(processor, "method_arguments") as method_arguments: | ||
890 | method_mock = mock.Mock() | ||
891 | method_arguments.return_value = [ | ||
892 | method_mock, | ||
893 | ["repartition", "base_currency"] | ||
894 | ] | ||
895 | method, args = processor.parse_args("action", {"repartition": { "ETH": 1 }}, {"base_currency": "USDT"}) | ||
896 | |||
897 | self.assertEqual(1, len(args["repartition"])) | ||
898 | self.assertIn("ETH", args["repartition"]) | ||
899 | |||
900 | |||
diff --git a/tests/test_portfolio.py b/tests/test_portfolio.py new file mode 100644 index 0000000..a1b95bf --- /dev/null +++ b/tests/test_portfolio.py | |||
@@ -0,0 +1,2036 @@ | |||
1 | from .helper import * | ||
2 | import portfolio | ||
3 | import datetime | ||
4 | |||
5 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
6 | class ComputationTest(WebMockTestCase): | ||
7 | def test_compute_value(self): | ||
8 | compute = mock.Mock() | ||
9 | portfolio.Computation.compute_value("foo", "buy", compute_value=compute) | ||
10 | compute.assert_called_with("foo", "ask") | ||
11 | |||
12 | compute.reset_mock() | ||
13 | portfolio.Computation.compute_value("foo", "sell", compute_value=compute) | ||
14 | compute.assert_called_with("foo", "bid") | ||
15 | |||
16 | compute.reset_mock() | ||
17 | portfolio.Computation.compute_value("foo", "ask", compute_value=compute) | ||
18 | compute.assert_called_with("foo", "ask") | ||
19 | |||
20 | compute.reset_mock() | ||
21 | portfolio.Computation.compute_value("foo", "bid", compute_value=compute) | ||
22 | compute.assert_called_with("foo", "bid") | ||
23 | |||
24 | compute.reset_mock() | ||
25 | portfolio.Computation.computations["test"] = compute | ||
26 | portfolio.Computation.compute_value("foo", "bid", compute_value="test") | ||
27 | compute.assert_called_with("foo", "bid") | ||
28 | |||
29 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
30 | class TradeTest(WebMockTestCase): | ||
31 | |||
32 | def test_values_assertion(self): | ||
33 | value_from = portfolio.Amount("BTC", "1.0") | ||
34 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
35 | value_to = portfolio.Amount("BTC", "1.0") | ||
36 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
37 | self.assertEqual("BTC", trade.base_currency) | ||
38 | self.assertEqual("ETH", trade.currency) | ||
39 | self.assertEqual(self.m, trade.market) | ||
40 | |||
41 | with self.assertRaises(AssertionError): | ||
42 | portfolio.Trade(value_from, -value_to, "ETH", self.m) | ||
43 | with self.assertRaises(AssertionError): | ||
44 | portfolio.Trade(value_from, value_to, "ETC", self.m) | ||
45 | with self.assertRaises(AssertionError): | ||
46 | value_from.currency = "ETH" | ||
47 | portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
48 | value_from.currency = "BTC" | ||
49 | with self.assertRaises(AssertionError): | ||
50 | value_from2 = portfolio.Amount("BTC", "1.0") | ||
51 | portfolio.Trade(value_from2, value_to, "ETH", self.m) | ||
52 | |||
53 | value_from = portfolio.Amount("BTC", 0) | ||
54 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
55 | self.assertEqual(0, trade.value_from.linked_to) | ||
56 | |||
57 | def test_action(self): | ||
58 | value_from = portfolio.Amount("BTC", "1.0") | ||
59 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
60 | value_to = portfolio.Amount("BTC", "1.0") | ||
61 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
62 | |||
63 | self.assertIsNone(trade.action) | ||
64 | |||
65 | value_from = portfolio.Amount("BTC", "1.0") | ||
66 | value_from.linked_to = portfolio.Amount("BTC", "1.0") | ||
67 | value_to = portfolio.Amount("BTC", "2.0") | ||
68 | trade = portfolio.Trade(value_from, value_to, "BTC", self.m) | ||
69 | |||
70 | self.assertIsNone(trade.action) | ||
71 | |||
72 | value_from = portfolio.Amount("BTC", "0.5") | ||
73 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
74 | value_to = portfolio.Amount("BTC", "1.0") | ||
75 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
76 | |||
77 | self.assertEqual("acquire", trade.action) | ||
78 | |||
79 | value_from = portfolio.Amount("BTC", "0") | ||
80 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
81 | value_to = portfolio.Amount("BTC", "-1.0") | ||
82 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
83 | |||
84 | self.assertEqual("acquire", trade.action) | ||
85 | |||
86 | def test_order_action(self): | ||
87 | value_from = portfolio.Amount("BTC", "0.5") | ||
88 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
89 | value_to = portfolio.Amount("BTC", "1.0") | ||
90 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
91 | |||
92 | trade.inverted = False | ||
93 | self.assertEqual("buy", trade.order_action()) | ||
94 | trade.inverted = True | ||
95 | self.assertEqual("sell", trade.order_action()) | ||
96 | |||
97 | value_from = portfolio.Amount("BTC", "0") | ||
98 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
99 | value_to = portfolio.Amount("BTC", "-1.0") | ||
100 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
101 | |||
102 | trade.inverted = False | ||
103 | self.assertEqual("sell", trade.order_action()) | ||
104 | trade.inverted = True | ||
105 | self.assertEqual("buy", trade.order_action()) | ||
106 | |||
107 | def test_trade_type(self): | ||
108 | value_from = portfolio.Amount("BTC", "0.5") | ||
109 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
110 | value_to = portfolio.Amount("BTC", "1.0") | ||
111 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
112 | |||
113 | self.assertEqual("long", trade.trade_type) | ||
114 | |||
115 | value_from = portfolio.Amount("BTC", "0") | ||
116 | value_from.linked_to = portfolio.Amount("ETH", "0") | ||
117 | value_to = portfolio.Amount("BTC", "-1.0") | ||
118 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
119 | |||
120 | self.assertEqual("short", trade.trade_type) | ||
121 | |||
122 | def test_is_fullfiled(self): | ||
123 | with self.subTest(inverted=False): | ||
124 | value_from = portfolio.Amount("BTC", "0.5") | ||
125 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
126 | value_to = portfolio.Amount("BTC", "1.0") | ||
127 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
128 | |||
129 | order1 = mock.Mock() | ||
130 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3") | ||
131 | |||
132 | order2 = mock.Mock() | ||
133 | order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01") | ||
134 | trade.orders.append(order1) | ||
135 | trade.orders.append(order2) | ||
136 | |||
137 | self.assertFalse(trade.is_fullfiled) | ||
138 | |||
139 | order3 = mock.Mock() | ||
140 | order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19") | ||
141 | trade.orders.append(order3) | ||
142 | |||
143 | self.assertTrue(trade.is_fullfiled) | ||
144 | |||
145 | order1.filled_amount.assert_called_with(in_base_currency=True) | ||
146 | order2.filled_amount.assert_called_with(in_base_currency=True) | ||
147 | order3.filled_amount.assert_called_with(in_base_currency=True) | ||
148 | |||
149 | with self.subTest(inverted=True): | ||
150 | value_from = portfolio.Amount("BTC", "0.5") | ||
151 | value_from.linked_to = portfolio.Amount("USDT", "1000.0") | ||
152 | value_to = portfolio.Amount("BTC", "1.0") | ||
153 | trade = portfolio.Trade(value_from, value_to, "USDT", self.m) | ||
154 | trade.inverted = True | ||
155 | |||
156 | order1 = mock.Mock() | ||
157 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3") | ||
158 | |||
159 | order2 = mock.Mock() | ||
160 | order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01") | ||
161 | trade.orders.append(order1) | ||
162 | trade.orders.append(order2) | ||
163 | |||
164 | self.assertFalse(trade.is_fullfiled) | ||
165 | |||
166 | order3 = mock.Mock() | ||
167 | order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19") | ||
168 | trade.orders.append(order3) | ||
169 | |||
170 | self.assertTrue(trade.is_fullfiled) | ||
171 | |||
172 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
173 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
174 | order3.filled_amount.assert_called_with(in_base_currency=False) | ||
175 | |||
176 | |||
177 | def test_filled_amount(self): | ||
178 | value_from = portfolio.Amount("BTC", "0.5") | ||
179 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
180 | value_to = portfolio.Amount("BTC", "1.0") | ||
181 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
182 | |||
183 | order1 = mock.Mock() | ||
184 | order1.filled_amount.return_value = portfolio.Amount("ETH", "0.3") | ||
185 | |||
186 | order2 = mock.Mock() | ||
187 | order2.filled_amount.return_value = portfolio.Amount("ETH", "0.01") | ||
188 | trade.orders.append(order1) | ||
189 | trade.orders.append(order2) | ||
190 | |||
191 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount()) | ||
192 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
193 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
194 | |||
195 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=False)) | ||
196 | order1.filled_amount.assert_called_with(in_base_currency=False) | ||
197 | order2.filled_amount.assert_called_with(in_base_currency=False) | ||
198 | |||
199 | self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=True)) | ||
200 | order1.filled_amount.assert_called_with(in_base_currency=True) | ||
201 | order2.filled_amount.assert_called_with(in_base_currency=True) | ||
202 | |||
203 | @mock.patch.object(portfolio.Computation, "compute_value") | ||
204 | @mock.patch.object(portfolio.Trade, "filled_amount") | ||
205 | @mock.patch.object(portfolio, "Order") | ||
206 | def test_prepare_order(self, Order, filled_amount, compute_value): | ||
207 | Order.return_value = "Order" | ||
208 | |||
209 | with self.subTest(desc="Nothing to do"): | ||
210 | value_from = portfolio.Amount("BTC", "10") | ||
211 | value_from.rate = D("0.1") | ||
212 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
213 | value_to = portfolio.Amount("BTC", "10") | ||
214 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
215 | |||
216 | trade.prepare_order() | ||
217 | |||
218 | filled_amount.assert_not_called() | ||
219 | compute_value.assert_not_called() | ||
220 | self.assertEqual(0, len(trade.orders)) | ||
221 | Order.assert_not_called() | ||
222 | |||
223 | self.m.get_ticker.return_value = { "inverted": False } | ||
224 | with self.subTest(desc="Already filled"): | ||
225 | filled_amount.return_value = portfolio.Amount("FOO", "100") | ||
226 | compute_value.return_value = D("0.125") | ||
227 | |||
228 | value_from = portfolio.Amount("BTC", "10") | ||
229 | value_from.rate = D("0.1") | ||
230 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
231 | value_to = portfolio.Amount("BTC", "0") | ||
232 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
233 | |||
234 | trade.prepare_order() | ||
235 | |||
236 | filled_amount.assert_called_with(in_base_currency=False) | ||
237 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
238 | self.assertEqual(0, len(trade.orders)) | ||
239 | self.m.report.log_error.assert_called_with("prepare_order", message=mock.ANY) | ||
240 | Order.assert_not_called() | ||
241 | |||
242 | with self.subTest(action="dispose", inverted=False): | ||
243 | filled_amount.return_value = portfolio.Amount("FOO", "60") | ||
244 | compute_value.return_value = D("0.125") | ||
245 | |||
246 | value_from = portfolio.Amount("BTC", "10") | ||
247 | value_from.rate = D("0.1") | ||
248 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
249 | value_to = portfolio.Amount("BTC", "1") | ||
250 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
251 | |||
252 | trade.prepare_order() | ||
253 | |||
254 | filled_amount.assert_called_with(in_base_currency=False) | ||
255 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
256 | self.assertEqual(1, len(trade.orders)) | ||
257 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | ||
258 | D("0.125"), "BTC", "long", self.m, | ||
259 | trade, close_if_possible=False) | ||
260 | |||
261 | with self.subTest(action="dispose", inverted=False, close_if_possible=True): | ||
262 | filled_amount.return_value = portfolio.Amount("FOO", "60") | ||
263 | compute_value.return_value = D("0.125") | ||
264 | |||
265 | value_from = portfolio.Amount("BTC", "10") | ||
266 | value_from.rate = D("0.1") | ||
267 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
268 | value_to = portfolio.Amount("BTC", "1") | ||
269 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
270 | |||
271 | trade.prepare_order(close_if_possible=True) | ||
272 | |||
273 | filled_amount.assert_called_with(in_base_currency=False) | ||
274 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
275 | self.assertEqual(1, len(trade.orders)) | ||
276 | Order.assert_called_with("sell", portfolio.Amount("FOO", 30), | ||
277 | D("0.125"), "BTC", "long", self.m, | ||
278 | trade, close_if_possible=True) | ||
279 | |||
280 | with self.subTest(action="acquire", inverted=False): | ||
281 | filled_amount.return_value = portfolio.Amount("BTC", "3") | ||
282 | compute_value.return_value = D("0.125") | ||
283 | |||
284 | value_from = portfolio.Amount("BTC", "1") | ||
285 | value_from.rate = D("0.1") | ||
286 | value_from.linked_to = portfolio.Amount("FOO", "10") | ||
287 | value_to = portfolio.Amount("BTC", "10") | ||
288 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
289 | |||
290 | trade.prepare_order() | ||
291 | |||
292 | filled_amount.assert_called_with(in_base_currency=True) | ||
293 | compute_value.assert_called_with(self.m.get_ticker.return_value, "buy", compute_value="default") | ||
294 | self.assertEqual(1, len(trade.orders)) | ||
295 | |||
296 | Order.assert_called_with("buy", portfolio.Amount("FOO", 48), | ||
297 | D("0.125"), "BTC", "long", self.m, | ||
298 | trade, close_if_possible=False) | ||
299 | |||
300 | with self.subTest(close_if_possible=True): | ||
301 | filled_amount.return_value = portfolio.Amount("FOO", "0") | ||
302 | compute_value.return_value = D("0.125") | ||
303 | |||
304 | value_from = portfolio.Amount("BTC", "10") | ||
305 | value_from.rate = D("0.1") | ||
306 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
307 | value_to = portfolio.Amount("BTC", "0") | ||
308 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
309 | |||
310 | trade.prepare_order() | ||
311 | |||
312 | filled_amount.assert_called_with(in_base_currency=False) | ||
313 | compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default") | ||
314 | self.assertEqual(1, len(trade.orders)) | ||
315 | Order.assert_called_with("sell", portfolio.Amount("FOO", 100), | ||
316 | D("0.125"), "BTC", "long", self.m, | ||
317 | trade, close_if_possible=True) | ||
318 | |||
319 | self.m.get_ticker.return_value = { "inverted": True, "original": {} } | ||
320 | with self.subTest(action="dispose", inverted=True): | ||
321 | filled_amount.return_value = portfolio.Amount("FOO", "300") | ||
322 | compute_value.return_value = D("125") | ||
323 | |||
324 | value_from = portfolio.Amount("BTC", "10") | ||
325 | value_from.rate = D("0.01") | ||
326 | value_from.linked_to = portfolio.Amount("FOO", "1000") | ||
327 | value_to = portfolio.Amount("BTC", "1") | ||
328 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
329 | |||
330 | trade.prepare_order(compute_value="foo") | ||
331 | |||
332 | filled_amount.assert_called_with(in_base_currency=True) | ||
333 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "buy", compute_value="foo") | ||
334 | self.assertEqual(1, len(trade.orders)) | ||
335 | Order.assert_called_with("buy", portfolio.Amount("BTC", D("4.8")), | ||
336 | D("125"), "FOO", "long", self.m, | ||
337 | trade, close_if_possible=False) | ||
338 | |||
339 | with self.subTest(action="acquire", inverted=True): | ||
340 | filled_amount.return_value = portfolio.Amount("BTC", "4") | ||
341 | compute_value.return_value = D("125") | ||
342 | |||
343 | value_from = portfolio.Amount("BTC", "1") | ||
344 | value_from.rate = D("0.01") | ||
345 | value_from.linked_to = portfolio.Amount("FOO", "100") | ||
346 | value_to = portfolio.Amount("BTC", "10") | ||
347 | trade = portfolio.Trade(value_from, value_to, "FOO", self.m) | ||
348 | |||
349 | trade.prepare_order(compute_value="foo") | ||
350 | |||
351 | filled_amount.assert_called_with(in_base_currency=False) | ||
352 | compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "sell", compute_value="foo") | ||
353 | self.assertEqual(1, len(trade.orders)) | ||
354 | Order.assert_called_with("sell", portfolio.Amount("BTC", D("5")), | ||
355 | D("125"), "FOO", "long", self.m, | ||
356 | trade, close_if_possible=False) | ||
357 | |||
358 | def test_tick_actions_recreate(self): | ||
359 | value_from = portfolio.Amount("BTC", "0.5") | ||
360 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
361 | value_to = portfolio.Amount("BTC", "1.0") | ||
362 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
363 | |||
364 | self.assertEqual("average", trade.tick_actions_recreate(0)) | ||
365 | self.assertEqual("foo", trade.tick_actions_recreate(0, default="foo")) | ||
366 | self.assertEqual("average", trade.tick_actions_recreate(1)) | ||
367 | self.assertEqual(trade.tick_actions[2][1], trade.tick_actions_recreate(2)) | ||
368 | self.assertEqual(trade.tick_actions[2][1], trade.tick_actions_recreate(3)) | ||
369 | self.assertEqual(trade.tick_actions[5][1], trade.tick_actions_recreate(5)) | ||
370 | self.assertEqual(trade.tick_actions[5][1], trade.tick_actions_recreate(6)) | ||
371 | self.assertEqual("default", trade.tick_actions_recreate(7)) | ||
372 | self.assertEqual("default", trade.tick_actions_recreate(8)) | ||
373 | |||
374 | @mock.patch.object(portfolio.Trade, "prepare_order") | ||
375 | def test_update_order(self, prepare_order): | ||
376 | order_mock = mock.Mock() | ||
377 | new_order_mock = mock.Mock() | ||
378 | |||
379 | value_from = portfolio.Amount("BTC", "0.5") | ||
380 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
381 | value_to = portfolio.Amount("BTC", "1.0") | ||
382 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
383 | prepare_order.return_value = new_order_mock | ||
384 | |||
385 | for i in [0, 1, 3, 4, 6]: | ||
386 | with self.subTest(tick=i): | ||
387 | trade.update_order(order_mock, i) | ||
388 | order_mock.cancel.assert_not_called() | ||
389 | new_order_mock.run.assert_not_called() | ||
390 | self.m.report.log_order.assert_called_once_with(order_mock, i, | ||
391 | update="waiting", compute_value=None, new_order=None) | ||
392 | |||
393 | order_mock.reset_mock() | ||
394 | new_order_mock.reset_mock() | ||
395 | trade.orders = [] | ||
396 | self.m.report.log_order.reset_mock() | ||
397 | |||
398 | trade.update_order(order_mock, 2) | ||
399 | order_mock.cancel.assert_called() | ||
400 | new_order_mock.run.assert_called() | ||
401 | prepare_order.assert_called() | ||
402 | self.m.report.log_order.assert_called() | ||
403 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
404 | calls = [ | ||
405 | mock.call(order_mock, 2, update="adjusting", | ||
406 | compute_value=mock.ANY, | ||
407 | new_order=new_order_mock), | ||
408 | mock.call(order_mock, 2, new_order=new_order_mock), | ||
409 | ] | ||
410 | self.m.report.log_order.assert_has_calls(calls) | ||
411 | |||
412 | order_mock.reset_mock() | ||
413 | new_order_mock.reset_mock() | ||
414 | trade.orders = [] | ||
415 | self.m.report.log_order.reset_mock() | ||
416 | |||
417 | trade.update_order(order_mock, 5) | ||
418 | order_mock.cancel.assert_called() | ||
419 | new_order_mock.run.assert_called() | ||
420 | prepare_order.assert_called() | ||
421 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
422 | self.m.report.log_order.assert_called() | ||
423 | calls = [ | ||
424 | mock.call(order_mock, 5, update="adjusting", | ||
425 | compute_value=mock.ANY, | ||
426 | new_order=new_order_mock), | ||
427 | mock.call(order_mock, 5, new_order=new_order_mock), | ||
428 | ] | ||
429 | self.m.report.log_order.assert_has_calls(calls) | ||
430 | |||
431 | order_mock.reset_mock() | ||
432 | new_order_mock.reset_mock() | ||
433 | trade.orders = [] | ||
434 | self.m.report.log_order.reset_mock() | ||
435 | |||
436 | trade.update_order(order_mock, 7) | ||
437 | order_mock.cancel.assert_called() | ||
438 | new_order_mock.run.assert_called() | ||
439 | prepare_order.assert_called_with(compute_value="default") | ||
440 | self.m.report.log_order.assert_called() | ||
441 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
442 | calls = [ | ||
443 | mock.call(order_mock, 7, update="market_fallback", | ||
444 | compute_value='default', | ||
445 | new_order=new_order_mock), | ||
446 | mock.call(order_mock, 7, new_order=new_order_mock), | ||
447 | ] | ||
448 | self.m.report.log_order.assert_has_calls(calls) | ||
449 | |||
450 | order_mock.reset_mock() | ||
451 | new_order_mock.reset_mock() | ||
452 | trade.orders = [] | ||
453 | self.m.report.log_order.reset_mock() | ||
454 | |||
455 | for i in [10, 13, 16]: | ||
456 | with self.subTest(tick=i): | ||
457 | trade.update_order(order_mock, i) | ||
458 | order_mock.cancel.assert_called() | ||
459 | new_order_mock.run.assert_called() | ||
460 | prepare_order.assert_called_with(compute_value="default") | ||
461 | self.m.report.log_order.assert_called() | ||
462 | self.assertEqual(2, self.m.report.log_order.call_count) | ||
463 | calls = [ | ||
464 | mock.call(order_mock, i, update="market_adjust", | ||
465 | compute_value='default', | ||
466 | new_order=new_order_mock), | ||
467 | mock.call(order_mock, i, new_order=new_order_mock), | ||
468 | ] | ||
469 | self.m.report.log_order.assert_has_calls(calls) | ||
470 | |||
471 | order_mock.reset_mock() | ||
472 | new_order_mock.reset_mock() | ||
473 | trade.orders = [] | ||
474 | self.m.report.log_order.reset_mock() | ||
475 | |||
476 | for i in [8, 9, 11, 12]: | ||
477 | with self.subTest(tick=i): | ||
478 | trade.update_order(order_mock, i) | ||
479 | order_mock.cancel.assert_not_called() | ||
480 | new_order_mock.run.assert_not_called() | ||
481 | self.m.report.log_order.assert_called_once_with(order_mock, i, update="waiting", | ||
482 | compute_value=None, new_order=None) | ||
483 | |||
484 | order_mock.reset_mock() | ||
485 | new_order_mock.reset_mock() | ||
486 | trade.orders = [] | ||
487 | self.m.report.log_order.reset_mock() | ||
488 | |||
489 | |||
490 | def test_print_with_order(self): | ||
491 | value_from = portfolio.Amount("BTC", "0.5") | ||
492 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
493 | value_to = portfolio.Amount("BTC", "1.0") | ||
494 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
495 | |||
496 | order_mock1 = mock.Mock() | ||
497 | order_mock1.__repr__ = mock.Mock() | ||
498 | order_mock1.__repr__.return_value = "Mock 1" | ||
499 | order_mock2 = mock.Mock() | ||
500 | order_mock2.__repr__ = mock.Mock() | ||
501 | order_mock2.__repr__.return_value = "Mock 2" | ||
502 | order_mock1.mouvements = [] | ||
503 | mouvement_mock1 = mock.Mock() | ||
504 | mouvement_mock1.__repr__ = mock.Mock() | ||
505 | mouvement_mock1.__repr__.return_value = "Mouvement 1" | ||
506 | mouvement_mock2 = mock.Mock() | ||
507 | mouvement_mock2.__repr__ = mock.Mock() | ||
508 | mouvement_mock2.__repr__.return_value = "Mouvement 2" | ||
509 | order_mock2.mouvements = [ | ||
510 | mouvement_mock1, mouvement_mock2 | ||
511 | ] | ||
512 | trade.orders.append(order_mock1) | ||
513 | trade.orders.append(order_mock2) | ||
514 | |||
515 | with mock.patch.object(trade, "filled_amount") as filled: | ||
516 | filled.return_value = portfolio.Amount("BTC", "0.1") | ||
517 | |||
518 | trade.print_with_order() | ||
519 | |||
520 | self.m.report.print_log.assert_called() | ||
521 | calls = self.m.report.print_log.mock_calls | ||
522 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls[0][1][0])) | ||
523 | self.assertEqual("\tMock 1", str(calls[1][1][0])) | ||
524 | self.assertEqual("\tMock 2", str(calls[2][1][0])) | ||
525 | self.assertEqual("\t\tMouvement 1", str(calls[3][1][0])) | ||
526 | self.assertEqual("\t\tMouvement 2", str(calls[4][1][0])) | ||
527 | |||
528 | self.m.report.print_log.reset_mock() | ||
529 | |||
530 | filled.return_value = portfolio.Amount("BTC", "0.5") | ||
531 | trade.print_with_order() | ||
532 | calls = self.m.report.print_log.mock_calls | ||
533 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls[0][1][0])) | ||
534 | |||
535 | self.m.report.print_log.reset_mock() | ||
536 | |||
537 | filled.return_value = portfolio.Amount("BTC", "0.1") | ||
538 | trade.closed = True | ||
539 | trade.print_with_order() | ||
540 | calls = self.m.report.print_log.mock_calls | ||
541 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls[0][1][0])) | ||
542 | |||
543 | def test_close(self): | ||
544 | value_from = portfolio.Amount("BTC", "0.5") | ||
545 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
546 | value_to = portfolio.Amount("BTC", "1.0") | ||
547 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
548 | order1 = mock.Mock() | ||
549 | trade.orders.append(order1) | ||
550 | |||
551 | trade.close() | ||
552 | |||
553 | self.assertEqual(True, trade.closed) | ||
554 | order1.cancel.assert_called_once_with() | ||
555 | |||
556 | def test_pending(self): | ||
557 | value_from = portfolio.Amount("BTC", "0.5") | ||
558 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
559 | value_to = portfolio.Amount("BTC", "1.0") | ||
560 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
561 | |||
562 | trade.closed = True | ||
563 | self.assertEqual(False, trade.pending) | ||
564 | |||
565 | trade.closed = False | ||
566 | self.assertEqual(True, trade.pending) | ||
567 | |||
568 | order1 = mock.Mock() | ||
569 | order1.filled_amount.return_value = portfolio.Amount("BTC", "0.5") | ||
570 | trade.orders.append(order1) | ||
571 | self.assertEqual(False, trade.pending) | ||
572 | |||
573 | def test__repr(self): | ||
574 | value_from = portfolio.Amount("BTC", "0.5") | ||
575 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
576 | value_to = portfolio.Amount("BTC", "1.0") | ||
577 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
578 | |||
579 | self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade)) | ||
580 | |||
581 | def test_as_json(self): | ||
582 | value_from = portfolio.Amount("BTC", "0.5") | ||
583 | value_from.linked_to = portfolio.Amount("ETH", "10.0") | ||
584 | value_to = portfolio.Amount("BTC", "1.0") | ||
585 | trade = portfolio.Trade(value_from, value_to, "ETH", self.m) | ||
586 | |||
587 | as_json = trade.as_json() | ||
588 | self.assertEqual("acquire", as_json["action"]) | ||
589 | self.assertEqual(D("0.5"), as_json["from"]) | ||
590 | self.assertEqual(D("1.0"), as_json["to"]) | ||
591 | self.assertEqual("ETH", as_json["currency"]) | ||
592 | self.assertEqual("BTC", as_json["base_currency"]) | ||
593 | |||
594 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
595 | class BalanceTest(WebMockTestCase): | ||
596 | def test_values(self): | ||
597 | balance = portfolio.Balance("BTC", { | ||
598 | "exchange_total": "0.65", | ||
599 | "exchange_free": "0.35", | ||
600 | "exchange_used": "0.30", | ||
601 | "margin_total": "-10", | ||
602 | "margin_borrowed": "10", | ||
603 | "margin_available": "0", | ||
604 | "margin_in_position": "0", | ||
605 | "margin_position_type": "short", | ||
606 | "margin_borrowed_base_currency": "USDT", | ||
607 | "margin_liquidation_price": "1.20", | ||
608 | "margin_pending_gain": "10", | ||
609 | "margin_lending_fees": "0.4", | ||
610 | "margin_borrowed_base_price": "0.15", | ||
611 | }) | ||
612 | self.assertEqual(portfolio.D("0.65"), balance.exchange_total.value) | ||
613 | self.assertEqual(portfolio.D("0.35"), balance.exchange_free.value) | ||
614 | self.assertEqual(portfolio.D("0.30"), balance.exchange_used.value) | ||
615 | self.assertEqual("BTC", balance.exchange_total.currency) | ||
616 | self.assertEqual("BTC", balance.exchange_free.currency) | ||
617 | self.assertEqual("BTC", balance.exchange_total.currency) | ||
618 | |||
619 | self.assertEqual(portfolio.D("-10"), balance.margin_total.value) | ||
620 | self.assertEqual(portfolio.D("10"), balance.margin_borrowed.value) | ||
621 | self.assertEqual(portfolio.D("0"), balance.margin_available.value) | ||
622 | self.assertEqual("BTC", balance.margin_total.currency) | ||
623 | self.assertEqual("BTC", balance.margin_borrowed.currency) | ||
624 | self.assertEqual("BTC", balance.margin_available.currency) | ||
625 | |||
626 | self.assertEqual("BTC", balance.currency) | ||
627 | |||
628 | self.assertEqual(portfolio.D("0.4"), balance.margin_lending_fees.value) | ||
629 | self.assertEqual("USDT", balance.margin_lending_fees.currency) | ||
630 | |||
631 | def test__repr(self): | ||
632 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])", | ||
633 | repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }))) | ||
634 | balance = portfolio.Balance("BTX", { "exchange_total": 3, | ||
635 | "exchange_used": 1, "exchange_free": 2 }) | ||
636 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | ||
637 | |||
638 | balance = portfolio.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}) | ||
639 | self.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance)) | ||
640 | |||
641 | balance = portfolio.Balance("BTX", { "margin_total": 3, | ||
642 | "margin_in_position": 1, "margin_available": 2 }) | ||
643 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance)) | ||
644 | |||
645 | balance = portfolio.Balance("BTX", { "margin_total": 2, "margin_available": 2 }) | ||
646 | self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance)) | ||
647 | |||
648 | balance = portfolio.Balance("BTX", { "margin_total": -3, | ||
649 | "margin_borrowed_base_price": D("0.1"), | ||
650 | "margin_borrowed_base_currency": "BTC", | ||
651 | "margin_lending_fees": D("0.002") }) | ||
652 | self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance)) | ||
653 | |||
654 | balance = portfolio.Balance("BTX", { "margin_total": 1, | ||
655 | "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2}) | ||
656 | self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance)) | ||
657 | |||
658 | def test_as_json(self): | ||
659 | balance = portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }) | ||
660 | as_json = balance.as_json() | ||
661 | self.assertEqual(set(portfolio.Balance.base_keys), set(as_json.keys())) | ||
662 | self.assertEqual(D(0), as_json["total"]) | ||
663 | self.assertEqual(D(2), as_json["exchange_total"]) | ||
664 | self.assertEqual(D(2), as_json["exchange_free"]) | ||
665 | self.assertEqual(D(0), as_json["exchange_used"]) | ||
666 | self.assertEqual(D(0), as_json["margin_total"]) | ||
667 | self.assertEqual(D(0), as_json["margin_available"]) | ||
668 | self.assertEqual(D(0), as_json["margin_borrowed"]) | ||
669 | |||
670 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
671 | class OrderTest(WebMockTestCase): | ||
672 | def test_values(self): | ||
673 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
674 | D("0.1"), "BTC", "long", "market", "trade") | ||
675 | self.assertEqual("buy", order.action) | ||
676 | self.assertEqual(10, order.amount.value) | ||
677 | self.assertEqual("ETH", order.amount.currency) | ||
678 | self.assertEqual(D("0.1"), order.rate) | ||
679 | self.assertEqual("BTC", order.base_currency) | ||
680 | self.assertEqual("market", order.market) | ||
681 | self.assertEqual("long", order.trade_type) | ||
682 | self.assertEqual("pending", order.status) | ||
683 | self.assertEqual("trade", order.trade) | ||
684 | self.assertIsNone(order.id) | ||
685 | self.assertFalse(order.close_if_possible) | ||
686 | |||
687 | def test__repr(self): | ||
688 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
689 | D("0.1"), "BTC", "long", "market", "trade") | ||
690 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order)) | ||
691 | |||
692 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
693 | D("0.1"), "BTC", "long", "market", "trade", | ||
694 | close_if_possible=True) | ||
695 | self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order)) | ||
696 | |||
697 | def test_as_json(self): | ||
698 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
699 | D("0.1"), "BTC", "long", "market", "trade") | ||
700 | mouvement_mock1 = mock.Mock() | ||
701 | mouvement_mock1.as_json.return_value = 1 | ||
702 | mouvement_mock2 = mock.Mock() | ||
703 | mouvement_mock2.as_json.return_value = 2 | ||
704 | |||
705 | order.mouvements = [mouvement_mock1, mouvement_mock2] | ||
706 | as_json = order.as_json() | ||
707 | self.assertEqual("buy", as_json["action"]) | ||
708 | self.assertEqual("long", as_json["trade_type"]) | ||
709 | self.assertEqual(10, as_json["amount"]) | ||
710 | self.assertEqual("ETH", as_json["currency"]) | ||
711 | self.assertEqual("BTC", as_json["base_currency"]) | ||
712 | self.assertEqual(D("0.1"), as_json["rate"]) | ||
713 | self.assertEqual("pending", as_json["status"]) | ||
714 | self.assertEqual(False, as_json["close_if_possible"]) | ||
715 | self.assertIsNone(as_json["id"]) | ||
716 | self.assertEqual([1, 2], as_json["mouvements"]) | ||
717 | |||
718 | def test_account(self): | ||
719 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
720 | D("0.1"), "BTC", "long", "market", "trade") | ||
721 | self.assertEqual("exchange", order.account) | ||
722 | |||
723 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | ||
724 | D("0.1"), "BTC", "short", "market", "trade") | ||
725 | self.assertEqual("margin", order.account) | ||
726 | |||
727 | def test_pending(self): | ||
728 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
729 | D("0.1"), "BTC", "long", "market", "trade") | ||
730 | self.assertTrue(order.pending) | ||
731 | order.status = "open" | ||
732 | self.assertFalse(order.pending) | ||
733 | |||
734 | def test_open(self): | ||
735 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
736 | D("0.1"), "BTC", "long", "market", "trade") | ||
737 | self.assertFalse(order.open) | ||
738 | order.status = "open" | ||
739 | self.assertTrue(order.open) | ||
740 | |||
741 | def test_finished(self): | ||
742 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
743 | D("0.1"), "BTC", "long", "market", "trade") | ||
744 | self.assertFalse(order.finished) | ||
745 | order.status = "closed" | ||
746 | self.assertTrue(order.finished) | ||
747 | order.status = "canceled" | ||
748 | self.assertTrue(order.finished) | ||
749 | order.status = "error" | ||
750 | self.assertTrue(order.finished) | ||
751 | |||
752 | @mock.patch.object(portfolio.Order, "fetch") | ||
753 | def test_cancel(self, fetch): | ||
754 | with self.subTest(debug=True): | ||
755 | self.m.debug = True | ||
756 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
757 | D("0.1"), "BTC", "long", self.m, "trade") | ||
758 | order.status = "open" | ||
759 | |||
760 | order.cancel() | ||
761 | self.m.ccxt.cancel_order.assert_not_called() | ||
762 | self.m.report.log_debug_action.assert_called_once() | ||
763 | self.m.report.log_debug_action.reset_mock() | ||
764 | self.assertEqual("canceled", order.status) | ||
765 | |||
766 | with self.subTest(desc="Nominal case"): | ||
767 | self.m.debug = False | ||
768 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
769 | D("0.1"), "BTC", "long", self.m, "trade") | ||
770 | order.status = "open" | ||
771 | order.id = 42 | ||
772 | |||
773 | order.cancel() | ||
774 | self.m.ccxt.cancel_order.assert_called_with(42) | ||
775 | fetch.assert_called_once_with() | ||
776 | self.m.report.log_debug_action.assert_not_called() | ||
777 | |||
778 | with self.subTest(exception=True): | ||
779 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
780 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
781 | D("0.1"), "BTC", "long", self.m, "trade") | ||
782 | order.status = "open" | ||
783 | order.id = 42 | ||
784 | order.cancel() | ||
785 | self.m.ccxt.cancel_order.assert_called_with(42) | ||
786 | self.m.report.log_error.assert_called_once() | ||
787 | |||
788 | self.m.reset_mock() | ||
789 | with self.subTest(id=None): | ||
790 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
791 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
792 | D("0.1"), "BTC", "long", self.m, "trade") | ||
793 | order.status = "open" | ||
794 | order.cancel() | ||
795 | self.m.ccxt.cancel_order.assert_not_called() | ||
796 | |||
797 | self.m.reset_mock() | ||
798 | with self.subTest(open=False): | ||
799 | self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound | ||
800 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
801 | D("0.1"), "BTC", "long", self.m, "trade") | ||
802 | order.status = "closed" | ||
803 | order.cancel() | ||
804 | self.m.ccxt.cancel_order.assert_not_called() | ||
805 | |||
806 | def test_dust_amount_remaining(self): | ||
807 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
808 | D("0.1"), "BTC", "long", self.m, "trade") | ||
809 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", 1)) | ||
810 | self.assertFalse(order.dust_amount_remaining()) | ||
811 | |||
812 | order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", D("0.0001"))) | ||
813 | self.assertTrue(order.dust_amount_remaining()) | ||
814 | |||
815 | @mock.patch.object(portfolio.Order, "fetch") | ||
816 | @mock.patch.object(portfolio.Order, "filled_amount", return_value=portfolio.Amount("ETH", 1)) | ||
817 | def test_remaining_amount(self, filled_amount, fetch): | ||
818 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
819 | D("0.1"), "BTC", "long", self.m, "trade") | ||
820 | |||
821 | self.assertEqual(9, order.remaining_amount().value) | ||
822 | |||
823 | order.status = "open" | ||
824 | self.assertEqual(9, order.remaining_amount().value) | ||
825 | |||
826 | @mock.patch.object(portfolio.Order, "fetch") | ||
827 | def test_filled_amount(self, fetch): | ||
828 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
829 | D("0.1"), "BTC", "long", self.m, "trade") | ||
830 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | ||
831 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
832 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
833 | "amount": "3", "total": "0.3" | ||
834 | })) | ||
835 | order.mouvements.append(portfolio.Mouvement("ETH", "BTC", { | ||
836 | "tradeID": 43, "type": "buy", "fee": "0.0015", | ||
837 | "date": "2017-12-30 13:00:12", "rate": "0.2", | ||
838 | "amount": "2", "total": "0.4" | ||
839 | })) | ||
840 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount()) | ||
841 | fetch.assert_not_called() | ||
842 | order.status = "open" | ||
843 | self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount(in_base_currency=False)) | ||
844 | fetch.assert_called_once() | ||
845 | self.assertEqual(portfolio.Amount("BTC", "0.7"), order.filled_amount(in_base_currency=True)) | ||
846 | |||
847 | def test_fetch_mouvements(self): | ||
848 | self.m.ccxt.privatePostReturnOrderTrades.return_value = [ | ||
849 | { | ||
850 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
851 | "date": "2017-12-30 13:00:12", "rate": "0.1", | ||
852 | "amount": "3", "total": "0.3" | ||
853 | }, | ||
854 | { | ||
855 | "tradeID": 43, "type": "buy", "fee": "0.0015", | ||
856 | "date": "2017-12-30 12:00:12", "rate": "0.2", | ||
857 | "amount": "2", "total": "0.4" | ||
858 | } | ||
859 | ] | ||
860 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
861 | D("0.1"), "BTC", "long", self.m, "trade") | ||
862 | order.id = 12 | ||
863 | order.mouvements = ["Foo", "Bar", "Baz"] | ||
864 | |||
865 | order.fetch_mouvements() | ||
866 | |||
867 | self.m.ccxt.privatePostReturnOrderTrades.assert_called_with({"orderNumber": 12}) | ||
868 | self.assertEqual(2, len(order.mouvements)) | ||
869 | self.assertEqual(43, order.mouvements[0].id) | ||
870 | self.assertEqual(42, order.mouvements[1].id) | ||
871 | |||
872 | self.m.ccxt.privatePostReturnOrderTrades.side_effect = portfolio.ExchangeError | ||
873 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
874 | D("0.1"), "BTC", "long", self.m, "trade") | ||
875 | order.fetch_mouvements() | ||
876 | self.assertEqual(0, len(order.mouvements)) | ||
877 | |||
878 | def test_mark_finished_order(self): | ||
879 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
880 | D("0.1"), "BTC", "short", self.m, "trade", | ||
881 | close_if_possible=True) | ||
882 | order.status = "closed" | ||
883 | self.m.debug = False | ||
884 | |||
885 | order.mark_finished_order() | ||
886 | self.m.ccxt.close_margin_position.assert_called_with("ETH", "BTC") | ||
887 | self.m.ccxt.close_margin_position.reset_mock() | ||
888 | |||
889 | order.status = "open" | ||
890 | order.mark_finished_order() | ||
891 | self.m.ccxt.close_margin_position.assert_not_called() | ||
892 | |||
893 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
894 | D("0.1"), "BTC", "short", self.m, "trade", | ||
895 | close_if_possible=False) | ||
896 | order.status = "closed" | ||
897 | order.mark_finished_order() | ||
898 | self.m.ccxt.close_margin_position.assert_not_called() | ||
899 | |||
900 | order = portfolio.Order("sell", portfolio.Amount("ETH", 10), | ||
901 | D("0.1"), "BTC", "short", self.m, "trade", | ||
902 | close_if_possible=True) | ||
903 | order.status = "closed" | ||
904 | order.mark_finished_order() | ||
905 | self.m.ccxt.close_margin_position.assert_not_called() | ||
906 | |||
907 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
908 | D("0.1"), "BTC", "long", self.m, "trade", | ||
909 | close_if_possible=True) | ||
910 | order.status = "closed" | ||
911 | order.mark_finished_order() | ||
912 | self.m.ccxt.close_margin_position.assert_not_called() | ||
913 | |||
914 | self.m.debug = True | ||
915 | |||
916 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
917 | D("0.1"), "BTC", "short", self.m, "trade", | ||
918 | close_if_possible=True) | ||
919 | order.status = "closed" | ||
920 | |||
921 | order.mark_finished_order() | ||
922 | self.m.ccxt.close_margin_position.assert_not_called() | ||
923 | self.m.report.log_debug_action.assert_called_once() | ||
924 | |||
925 | @mock.patch.object(portfolio.Order, "fetch_mouvements") | ||
926 | @mock.patch.object(portfolio.Order, "mark_disappeared_order") | ||
927 | @mock.patch.object(portfolio.Order, "mark_finished_order") | ||
928 | def test_fetch(self, mark_finished_order, mark_disappeared_order, fetch_mouvements): | ||
929 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
930 | D("0.1"), "BTC", "long", self.m, "trade") | ||
931 | order.id = 45 | ||
932 | with self.subTest(debug=True): | ||
933 | self.m.debug = True | ||
934 | order.fetch() | ||
935 | self.m.report.log_debug_action.assert_called_once() | ||
936 | self.m.report.log_debug_action.reset_mock() | ||
937 | self.m.ccxt.fetch_order.assert_not_called() | ||
938 | mark_finished_order.assert_not_called() | ||
939 | mark_disappeared_order.assert_not_called() | ||
940 | fetch_mouvements.assert_not_called() | ||
941 | |||
942 | with self.subTest(debug=False): | ||
943 | self.m.debug = False | ||
944 | self.m.ccxt.fetch_order.return_value = { | ||
945 | "status": "foo", | ||
946 | "datetime": "timestamp" | ||
947 | } | ||
948 | order.fetch() | ||
949 | |||
950 | self.m.ccxt.fetch_order.assert_called_once_with(45) | ||
951 | fetch_mouvements.assert_called_once() | ||
952 | self.assertEqual("foo", order.status) | ||
953 | self.assertEqual("timestamp", order.timestamp) | ||
954 | self.assertEqual(1, len(order.results)) | ||
955 | self.m.report.log_debug_action.assert_not_called() | ||
956 | mark_finished_order.assert_called_once() | ||
957 | mark_disappeared_order.assert_called_once() | ||
958 | |||
959 | mark_finished_order.reset_mock() | ||
960 | with self.subTest(missing_order=True): | ||
961 | self.m.ccxt.fetch_order.side_effect = [ | ||
962 | portfolio.OrderNotCached, | ||
963 | ] | ||
964 | order.fetch() | ||
965 | self.assertEqual("closed_unknown", order.status) | ||
966 | mark_finished_order.assert_called_once() | ||
967 | |||
968 | def test_mark_disappeared_order(self): | ||
969 | with self.subTest("Open order"): | ||
970 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
971 | D("0.1"), "BTC", "long", self.m, "trade") | ||
972 | order.id = 45 | ||
973 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
974 | "tradeID":21336541, | ||
975 | "currencyPair":"BTC_XRP", | ||
976 | "type":"sell", | ||
977 | "rate":"0.00007013", | ||
978 | "amount":"0.00000222", | ||
979 | "total":"0.00000000", | ||
980 | "fee":"0.00150000", | ||
981 | "date":"2018-04-02 00:09:13" | ||
982 | })) | ||
983 | order.mark_disappeared_order() | ||
984 | self.assertEqual("pending", order.status) | ||
985 | |||
986 | with self.subTest("Non-zero amount"): | ||
987 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
988 | D("0.1"), "BTC", "long", self.m, "trade") | ||
989 | order.id = 45 | ||
990 | order.status = "closed" | ||
991 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
992 | "tradeID":21336541, | ||
993 | "currencyPair":"BTC_XRP", | ||
994 | "type":"sell", | ||
995 | "rate":"0.00007013", | ||
996 | "amount":"0.00000222", | ||
997 | "total":"0.00000010", | ||
998 | "fee":"0.00150000", | ||
999 | "date":"2018-04-02 00:09:13" | ||
1000 | })) | ||
1001 | order.mark_disappeared_order() | ||
1002 | self.assertEqual("closed", order.status) | ||
1003 | |||
1004 | with self.subTest("Other mouvements"): | ||
1005 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1006 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1007 | order.id = 45 | ||
1008 | order.status = "closed" | ||
1009 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
1010 | "tradeID":21336541, | ||
1011 | "currencyPair":"BTC_XRP", | ||
1012 | "type":"sell", | ||
1013 | "rate":"0.00007013", | ||
1014 | "amount":"0.00000222", | ||
1015 | "total":"0.00000001", | ||
1016 | "fee":"0.00150000", | ||
1017 | "date":"2018-04-02 00:09:13" | ||
1018 | })) | ||
1019 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
1020 | "tradeID":21336541, | ||
1021 | "currencyPair":"BTC_XRP", | ||
1022 | "type":"sell", | ||
1023 | "rate":"0.00007013", | ||
1024 | "amount":"0.00000222", | ||
1025 | "total":"0.00000000", | ||
1026 | "fee":"0.00150000", | ||
1027 | "date":"2018-04-02 00:09:13" | ||
1028 | })) | ||
1029 | order.mark_disappeared_order() | ||
1030 | self.assertEqual("error_disappeared", order.status) | ||
1031 | |||
1032 | with self.subTest("Order disappeared"): | ||
1033 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1034 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1035 | order.id = 45 | ||
1036 | order.status = "closed" | ||
1037 | order.mouvements.append(portfolio.Mouvement("XRP", "BTC", { | ||
1038 | "tradeID":21336541, | ||
1039 | "currencyPair":"BTC_XRP", | ||
1040 | "type":"sell", | ||
1041 | "rate":"0.00007013", | ||
1042 | "amount":"0.00000222", | ||
1043 | "total":"0.00000000", | ||
1044 | "fee":"0.00150000", | ||
1045 | "date":"2018-04-02 00:09:13" | ||
1046 | })) | ||
1047 | order.mark_disappeared_order() | ||
1048 | self.assertEqual("error_disappeared", order.status) | ||
1049 | |||
1050 | @mock.patch.object(portfolio.Order, "fetch") | ||
1051 | def test_get_status(self, fetch): | ||
1052 | with self.subTest(debug=True): | ||
1053 | self.m.debug = True | ||
1054 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1055 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1056 | self.assertEqual("pending", order.get_status()) | ||
1057 | fetch.assert_not_called() | ||
1058 | self.m.report.log_debug_action.assert_called_once() | ||
1059 | |||
1060 | with self.subTest(debug=False, finished=False): | ||
1061 | self.m.debug = False | ||
1062 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1063 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1064 | def _fetch(order): | ||
1065 | def update_status(): | ||
1066 | order.status = "open" | ||
1067 | return update_status | ||
1068 | fetch.side_effect = _fetch(order) | ||
1069 | self.assertEqual("open", order.get_status()) | ||
1070 | fetch.assert_called_once() | ||
1071 | |||
1072 | fetch.reset_mock() | ||
1073 | with self.subTest(debug=False, finished=True): | ||
1074 | self.m.debug = False | ||
1075 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1076 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1077 | def _fetch(order): | ||
1078 | def update_status(): | ||
1079 | order.status = "closed" | ||
1080 | return update_status | ||
1081 | fetch.side_effect = _fetch(order) | ||
1082 | self.assertEqual("closed", order.get_status()) | ||
1083 | fetch.assert_called_once() | ||
1084 | |||
1085 | def test_run(self): | ||
1086 | self.m.ccxt.order_precision.return_value = 4 | ||
1087 | with self.subTest(debug=True): | ||
1088 | self.m.debug = True | ||
1089 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1090 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1091 | order.run() | ||
1092 | self.m.ccxt.create_order.assert_not_called() | ||
1093 | self.m.report.log_debug_action.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)") | ||
1094 | self.assertEqual("open", order.status) | ||
1095 | self.assertEqual(1, len(order.results)) | ||
1096 | self.assertEqual(-1, order.id) | ||
1097 | |||
1098 | self.m.ccxt.create_order.reset_mock() | ||
1099 | with self.subTest(debug=False): | ||
1100 | self.m.debug = False | ||
1101 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1102 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1103 | self.m.ccxt.create_order.return_value = { "id": 123 } | ||
1104 | order.run() | ||
1105 | self.m.ccxt.create_order.assert_called_once() | ||
1106 | self.assertEqual(1, len(order.results)) | ||
1107 | self.assertEqual("open", order.status) | ||
1108 | |||
1109 | self.m.ccxt.create_order.reset_mock() | ||
1110 | with self.subTest(exception=True): | ||
1111 | order = portfolio.Order("buy", portfolio.Amount("ETH", 10), | ||
1112 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1113 | self.m.ccxt.create_order.side_effect = Exception("bouh") | ||
1114 | order.run() | ||
1115 | self.m.ccxt.create_order.assert_called_once() | ||
1116 | self.assertEqual(0, len(order.results)) | ||
1117 | self.assertEqual("error", order.status) | ||
1118 | self.m.report.log_error.assert_called_once() | ||
1119 | |||
1120 | self.m.ccxt.create_order.reset_mock() | ||
1121 | with self.subTest(dust_amount_exception=True),\ | ||
1122 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
1123 | order = portfolio.Order("buy", portfolio.Amount("ETH", 0.001), | ||
1124 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1125 | self.m.ccxt.create_order.side_effect = portfolio.InvalidOrder | ||
1126 | order.run() | ||
1127 | self.m.ccxt.create_order.assert_called_once() | ||
1128 | self.assertEqual(0, len(order.results)) | ||
1129 | self.assertEqual("closed", order.status) | ||
1130 | mark_finished_order.assert_called_once() | ||
1131 | |||
1132 | self.m.ccxt.order_precision.return_value = 8 | ||
1133 | self.m.ccxt.create_order.reset_mock() | ||
1134 | with self.subTest(insufficient_funds=True),\ | ||
1135 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
1136 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1137 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1138 | self.m.ccxt.create_order.side_effect = [ | ||
1139 | portfolio.InsufficientFunds, | ||
1140 | portfolio.InsufficientFunds, | ||
1141 | portfolio.InsufficientFunds, | ||
1142 | { "id": 123 }, | ||
1143 | ] | ||
1144 | order.run() | ||
1145 | self.m.ccxt.create_order.assert_has_calls([ | ||
1146 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1147 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')), | ||
1148 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')), | ||
1149 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')), | ||
1150 | ]) | ||
1151 | self.assertEqual(4, self.m.ccxt.create_order.call_count) | ||
1152 | self.assertEqual(1, len(order.results)) | ||
1153 | self.assertEqual("open", order.status) | ||
1154 | self.assertEqual(4, order.tries) | ||
1155 | self.m.report.log_error.assert_called() | ||
1156 | self.assertEqual(4, self.m.report.log_error.call_count) | ||
1157 | |||
1158 | self.m.ccxt.order_precision.return_value = 8 | ||
1159 | self.m.ccxt.create_order.reset_mock() | ||
1160 | self.m.report.log_error.reset_mock() | ||
1161 | with self.subTest(insufficient_funds=True),\ | ||
1162 | mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order: | ||
1163 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1164 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1165 | self.m.ccxt.create_order.side_effect = [ | ||
1166 | portfolio.InsufficientFunds, | ||
1167 | portfolio.InsufficientFunds, | ||
1168 | portfolio.InsufficientFunds, | ||
1169 | portfolio.InsufficientFunds, | ||
1170 | portfolio.InsufficientFunds, | ||
1171 | ] | ||
1172 | order.run() | ||
1173 | self.m.ccxt.create_order.assert_has_calls([ | ||
1174 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1175 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')), | ||
1176 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')), | ||
1177 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')), | ||
1178 | mock.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account='exchange', price=D('0.1')), | ||
1179 | ]) | ||
1180 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
1181 | self.assertEqual(0, len(order.results)) | ||
1182 | self.assertEqual("error", order.status) | ||
1183 | self.assertEqual(5, order.tries) | ||
1184 | self.m.report.log_error.assert_called() | ||
1185 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
1186 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00096060 ETH at 0.1 BTC [pending])", exception=mock.ANY) | ||
1187 | |||
1188 | self.m.reset_mock() | ||
1189 | with self.subTest(invalid_nonce=True): | ||
1190 | with self.subTest(retry_success=True): | ||
1191 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1192 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1193 | self.m.ccxt.create_order.side_effect = [ | ||
1194 | portfolio.InvalidNonce, | ||
1195 | portfolio.InvalidNonce, | ||
1196 | { "id": 123 }, | ||
1197 | ] | ||
1198 | order.run() | ||
1199 | self.m.ccxt.create_order.assert_has_calls([ | ||
1200 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1201 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1202 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1203 | ]) | ||
1204 | self.assertEqual(3, self.m.ccxt.create_order.call_count) | ||
1205 | self.assertEqual(3, order.tries) | ||
1206 | self.m.report.log_error.assert_called() | ||
1207 | self.assertEqual(2, self.m.report.log_error.call_count) | ||
1208 | self.m.report.log_error.assert_called_with(mock.ANY, message="Retrying after invalid nonce", exception=mock.ANY) | ||
1209 | self.assertEqual(123, order.id) | ||
1210 | |||
1211 | self.m.reset_mock() | ||
1212 | with self.subTest(retry_success=False): | ||
1213 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1214 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1215 | self.m.ccxt.create_order.side_effect = [ | ||
1216 | portfolio.InvalidNonce, | ||
1217 | portfolio.InvalidNonce, | ||
1218 | portfolio.InvalidNonce, | ||
1219 | portfolio.InvalidNonce, | ||
1220 | portfolio.InvalidNonce, | ||
1221 | ] | ||
1222 | order.run() | ||
1223 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
1224 | self.assertEqual(5, order.tries) | ||
1225 | self.m.report.log_error.assert_called() | ||
1226 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
1227 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after invalid nonce", exception=mock.ANY) | ||
1228 | self.assertEqual("error", order.status) | ||
1229 | |||
1230 | self.m.reset_mock() | ||
1231 | with self.subTest(request_timeout=True): | ||
1232 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1233 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1234 | with self.subTest(retrieved=False), \ | ||
1235 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
1236 | self.m.ccxt.create_order.side_effect = [ | ||
1237 | portfolio.RequestTimeout, | ||
1238 | portfolio.RequestTimeout, | ||
1239 | { "id": 123 }, | ||
1240 | ] | ||
1241 | retrieve.return_value = False | ||
1242 | order.run() | ||
1243 | self.m.ccxt.create_order.assert_has_calls([ | ||
1244 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1245 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1246 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1247 | ]) | ||
1248 | self.assertEqual(3, self.m.ccxt.create_order.call_count) | ||
1249 | self.assertEqual(3, order.tries) | ||
1250 | self.m.report.log_error.assert_called() | ||
1251 | self.assertEqual(2, self.m.report.log_error.call_count) | ||
1252 | self.m.report.log_error.assert_called_with(mock.ANY, message="Retrying after timeout", exception=mock.ANY) | ||
1253 | self.assertEqual(123, order.id) | ||
1254 | |||
1255 | self.m.reset_mock() | ||
1256 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1257 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1258 | with self.subTest(retrieved=True), \ | ||
1259 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
1260 | self.m.ccxt.create_order.side_effect = [ | ||
1261 | portfolio.RequestTimeout, | ||
1262 | ] | ||
1263 | def _retrieve(): | ||
1264 | order.results.append({"id": 123}) | ||
1265 | return True | ||
1266 | retrieve.side_effect = _retrieve | ||
1267 | order.run() | ||
1268 | self.m.ccxt.create_order.assert_has_calls([ | ||
1269 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1270 | ]) | ||
1271 | self.assertEqual(1, self.m.ccxt.create_order.call_count) | ||
1272 | self.assertEqual(1, order.tries) | ||
1273 | self.m.report.log_error.assert_called() | ||
1274 | self.assertEqual(1, self.m.report.log_error.call_count) | ||
1275 | self.m.report.log_error.assert_called_with(mock.ANY, message="Timeout, found the order") | ||
1276 | self.assertEqual(123, order.id) | ||
1277 | |||
1278 | self.m.reset_mock() | ||
1279 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1280 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1281 | with self.subTest(retrieved=False), \ | ||
1282 | mock.patch.object(order, "retrieve_order") as retrieve: | ||
1283 | self.m.ccxt.create_order.side_effect = [ | ||
1284 | portfolio.RequestTimeout, | ||
1285 | portfolio.RequestTimeout, | ||
1286 | portfolio.RequestTimeout, | ||
1287 | portfolio.RequestTimeout, | ||
1288 | portfolio.RequestTimeout, | ||
1289 | ] | ||
1290 | retrieve.return_value = False | ||
1291 | order.run() | ||
1292 | self.m.ccxt.create_order.assert_has_calls([ | ||
1293 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1294 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1295 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1296 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1297 | mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')), | ||
1298 | ]) | ||
1299 | self.assertEqual(5, self.m.ccxt.create_order.call_count) | ||
1300 | self.assertEqual(5, order.tries) | ||
1301 | self.m.report.log_error.assert_called() | ||
1302 | self.assertEqual(5, self.m.report.log_error.call_count) | ||
1303 | self.m.report.log_error.assert_called_with(mock.ANY, message="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after timeouts", exception=mock.ANY) | ||
1304 | self.assertEqual("error", order.status) | ||
1305 | |||
1306 | def test_retrieve_order(self): | ||
1307 | with self.subTest(similar_open_order=True): | ||
1308 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1309 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1310 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
1311 | |||
1312 | self.m.ccxt.order_precision.return_value = 8 | ||
1313 | self.m.ccxt.fetch_orders.return_value = [ | ||
1314 | { # Wrong amount | ||
1315 | 'amount': 0.002, 'cost': 0.1, | ||
1316 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1317 | 'fee': None, 'filled': 0.0, | ||
1318 | 'id': '1', | ||
1319 | 'info': { | ||
1320 | 'amount': '0.002', | ||
1321 | 'date': '2018-03-25 15:15:51', | ||
1322 | 'margin': 0, 'orderNumber': '1', | ||
1323 | 'price': '0.1', 'rate': '0.1', | ||
1324 | 'side': 'buy', 'startingAmount': '0.002', | ||
1325 | 'status': 'open', 'total': '0.0002', | ||
1326 | 'type': 'limit' | ||
1327 | }, | ||
1328 | 'price': 0.1, 'remaining': 0.002, 'side': 'buy', | ||
1329 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1330 | 'timestamp': 1521990951000, 'trades': None, | ||
1331 | 'type': 'limit' | ||
1332 | }, | ||
1333 | { # Margin | ||
1334 | 'amount': 0.001, 'cost': 0.1, | ||
1335 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1336 | 'fee': None, 'filled': 0.0, | ||
1337 | 'id': '2', | ||
1338 | 'info': { | ||
1339 | 'amount': '0.001', | ||
1340 | 'date': '2018-03-25 15:15:51', | ||
1341 | 'margin': 1, 'orderNumber': '2', | ||
1342 | 'price': '0.1', 'rate': '0.1', | ||
1343 | 'side': 'buy', 'startingAmount': '0.001', | ||
1344 | 'status': 'open', 'total': '0.0001', | ||
1345 | 'type': 'limit' | ||
1346 | }, | ||
1347 | 'price': 0.1, 'remaining': 0.001, 'side': 'buy', | ||
1348 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1349 | 'timestamp': 1521990951000, 'trades': None, | ||
1350 | 'type': 'limit' | ||
1351 | }, | ||
1352 | { # selling | ||
1353 | 'amount': 0.001, 'cost': 0.1, | ||
1354 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1355 | 'fee': None, 'filled': 0.0, | ||
1356 | 'id': '3', | ||
1357 | 'info': { | ||
1358 | 'amount': '0.001', | ||
1359 | 'date': '2018-03-25 15:15:51', | ||
1360 | 'margin': 0, 'orderNumber': '3', | ||
1361 | 'price': '0.1', 'rate': '0.1', | ||
1362 | 'side': 'sell', 'startingAmount': '0.001', | ||
1363 | 'status': 'open', 'total': '0.0001', | ||
1364 | 'type': 'limit' | ||
1365 | }, | ||
1366 | 'price': 0.1, 'remaining': 0.001, 'side': 'sell', | ||
1367 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1368 | 'timestamp': 1521990951000, 'trades': None, | ||
1369 | 'type': 'limit' | ||
1370 | }, | ||
1371 | { # Wrong rate | ||
1372 | 'amount': 0.001, 'cost': 0.15, | ||
1373 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1374 | 'fee': None, 'filled': 0.0, | ||
1375 | 'id': '4', | ||
1376 | 'info': { | ||
1377 | 'amount': '0.001', | ||
1378 | 'date': '2018-03-25 15:15:51', | ||
1379 | 'margin': 0, 'orderNumber': '4', | ||
1380 | 'price': '0.15', 'rate': '0.15', | ||
1381 | 'side': 'buy', 'startingAmount': '0.001', | ||
1382 | 'status': 'open', 'total': '0.0001', | ||
1383 | 'type': 'limit' | ||
1384 | }, | ||
1385 | 'price': 0.15, 'remaining': 0.001, 'side': 'buy', | ||
1386 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1387 | 'timestamp': 1521990951000, 'trades': None, | ||
1388 | 'type': 'limit' | ||
1389 | }, | ||
1390 | { # All good | ||
1391 | 'amount': 0.001, 'cost': 0.1, | ||
1392 | 'datetime': '2018-03-25T15:15:51.000Z', | ||
1393 | 'fee': None, 'filled': 0.0, | ||
1394 | 'id': '5', | ||
1395 | 'info': { | ||
1396 | 'amount': '0.001', | ||
1397 | 'date': '2018-03-25 15:15:51', | ||
1398 | 'margin': 0, 'orderNumber': '1', | ||
1399 | 'price': '0.1', 'rate': '0.1', | ||
1400 | 'side': 'buy', 'startingAmount': '0.001', | ||
1401 | 'status': 'open', 'total': '0.0001', | ||
1402 | 'type': 'limit' | ||
1403 | }, | ||
1404 | 'price': 0.1, 'remaining': 0.001, 'side': 'buy', | ||
1405 | 'status': 'open', 'symbol': 'ETH/BTC', | ||
1406 | 'timestamp': 1521990951000, 'trades': None, | ||
1407 | 'type': 'limit' | ||
1408 | } | ||
1409 | ] | ||
1410 | result = order.retrieve_order() | ||
1411 | self.assertTrue(result) | ||
1412 | self.assertEqual('5', order.results[0]["id"]) | ||
1413 | self.m.ccxt.fetch_my_trades.assert_not_called() | ||
1414 | self.m.ccxt.fetch_orders.assert_called_once_with(symbol="ETH/BTC", since=1521983750) | ||
1415 | |||
1416 | self.m.reset_mock() | ||
1417 | with self.subTest(similar_open_order=False, past_trades=True): | ||
1418 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1419 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1420 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
1421 | |||
1422 | self.m.ccxt.order_precision.return_value = 8 | ||
1423 | self.m.ccxt.fetch_orders.return_value = [] | ||
1424 | self.m.ccxt.fetch_my_trades.return_value = [ | ||
1425 | { # Wrong timestamp 1 | ||
1426 | 'amount': 0.0006, | ||
1427 | 'cost': 0.00006, | ||
1428 | 'datetime': '2018-03-25T15:15:14.000Z', | ||
1429 | 'id': '1-1', | ||
1430 | 'info': { | ||
1431 | 'amount': '0.0006', | ||
1432 | 'category': 'exchange', | ||
1433 | 'date': '2018-03-25 15:15:14', | ||
1434 | 'fee': '0.00150000', | ||
1435 | 'globalTradeID': 1, | ||
1436 | 'orderNumber': '1', | ||
1437 | 'rate': '0.1', | ||
1438 | 'total': '0.00006', | ||
1439 | 'tradeID': '1-1', | ||
1440 | 'type': 'buy' | ||
1441 | }, | ||
1442 | 'order': '1', | ||
1443 | 'price': 0.1, | ||
1444 | 'side': 'buy', | ||
1445 | 'symbol': 'ETH/BTC', | ||
1446 | 'timestamp': 1521983714, | ||
1447 | 'type': 'limit' | ||
1448 | }, | ||
1449 | { # Wrong timestamp 2 | ||
1450 | 'amount': 0.0004, | ||
1451 | 'cost': 0.00004, | ||
1452 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1453 | 'id': '1-2', | ||
1454 | 'info': { | ||
1455 | 'amount': '0.0004', | ||
1456 | 'category': 'exchange', | ||
1457 | 'date': '2018-03-25 15:16:54', | ||
1458 | 'fee': '0.00150000', | ||
1459 | 'globalTradeID': 2, | ||
1460 | 'orderNumber': '1', | ||
1461 | 'rate': '0.1', | ||
1462 | 'total': '0.00004', | ||
1463 | 'tradeID': '1-2', | ||
1464 | 'type': 'buy' | ||
1465 | }, | ||
1466 | 'order': '1', | ||
1467 | 'price': 0.1, | ||
1468 | 'side': 'buy', | ||
1469 | 'symbol': 'ETH/BTC', | ||
1470 | 'timestamp': 1521983814, | ||
1471 | 'type': 'limit' | ||
1472 | }, | ||
1473 | { # Wrong side 1 | ||
1474 | 'amount': 0.0006, | ||
1475 | 'cost': 0.00006, | ||
1476 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1477 | 'id': '2-1', | ||
1478 | 'info': { | ||
1479 | 'amount': '0.0006', | ||
1480 | 'category': 'exchange', | ||
1481 | 'date': '2018-03-25 15:15:54', | ||
1482 | 'fee': '0.00150000', | ||
1483 | 'globalTradeID': 1, | ||
1484 | 'orderNumber': '2', | ||
1485 | 'rate': '0.1', | ||
1486 | 'total': '0.00006', | ||
1487 | 'tradeID': '2-1', | ||
1488 | 'type': 'sell' | ||
1489 | }, | ||
1490 | 'order': '2', | ||
1491 | 'price': 0.1, | ||
1492 | 'side': 'sell', | ||
1493 | 'symbol': 'ETH/BTC', | ||
1494 | 'timestamp': 1521983754, | ||
1495 | 'type': 'limit' | ||
1496 | }, | ||
1497 | { # Wrong side 2 | ||
1498 | 'amount': 0.0004, | ||
1499 | 'cost': 0.00004, | ||
1500 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1501 | 'id': '2-2', | ||
1502 | 'info': { | ||
1503 | 'amount': '0.0004', | ||
1504 | 'category': 'exchange', | ||
1505 | 'date': '2018-03-25 15:16:54', | ||
1506 | 'fee': '0.00150000', | ||
1507 | 'globalTradeID': 2, | ||
1508 | 'orderNumber': '2', | ||
1509 | 'rate': '0.1', | ||
1510 | 'total': '0.00004', | ||
1511 | 'tradeID': '2-2', | ||
1512 | 'type': 'buy' | ||
1513 | }, | ||
1514 | 'order': '2', | ||
1515 | 'price': 0.1, | ||
1516 | 'side': 'buy', | ||
1517 | 'symbol': 'ETH/BTC', | ||
1518 | 'timestamp': 1521983814, | ||
1519 | 'type': 'limit' | ||
1520 | }, | ||
1521 | { # Margin trade 1 | ||
1522 | 'amount': 0.0006, | ||
1523 | 'cost': 0.00006, | ||
1524 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1525 | 'id': '3-1', | ||
1526 | 'info': { | ||
1527 | 'amount': '0.0006', | ||
1528 | 'category': 'marginTrade', | ||
1529 | 'date': '2018-03-25 15:15:54', | ||
1530 | 'fee': '0.00150000', | ||
1531 | 'globalTradeID': 1, | ||
1532 | 'orderNumber': '3', | ||
1533 | 'rate': '0.1', | ||
1534 | 'total': '0.00006', | ||
1535 | 'tradeID': '3-1', | ||
1536 | 'type': 'buy' | ||
1537 | }, | ||
1538 | 'order': '3', | ||
1539 | 'price': 0.1, | ||
1540 | 'side': 'buy', | ||
1541 | 'symbol': 'ETH/BTC', | ||
1542 | 'timestamp': 1521983754, | ||
1543 | 'type': 'limit' | ||
1544 | }, | ||
1545 | { # Margin trade 2 | ||
1546 | 'amount': 0.0004, | ||
1547 | 'cost': 0.00004, | ||
1548 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1549 | 'id': '3-2', | ||
1550 | 'info': { | ||
1551 | 'amount': '0.0004', | ||
1552 | 'category': 'marginTrade', | ||
1553 | 'date': '2018-03-25 15:16:54', | ||
1554 | 'fee': '0.00150000', | ||
1555 | 'globalTradeID': 2, | ||
1556 | 'orderNumber': '3', | ||
1557 | 'rate': '0.1', | ||
1558 | 'total': '0.00004', | ||
1559 | 'tradeID': '3-2', | ||
1560 | 'type': 'buy' | ||
1561 | }, | ||
1562 | 'order': '3', | ||
1563 | 'price': 0.1, | ||
1564 | 'side': 'buy', | ||
1565 | 'symbol': 'ETH/BTC', | ||
1566 | 'timestamp': 1521983814, | ||
1567 | 'type': 'limit' | ||
1568 | }, | ||
1569 | { # Wrong amount 1 | ||
1570 | 'amount': 0.0005, | ||
1571 | 'cost': 0.00005, | ||
1572 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1573 | 'id': '4-1', | ||
1574 | 'info': { | ||
1575 | 'amount': '0.0005', | ||
1576 | 'category': 'exchange', | ||
1577 | 'date': '2018-03-25 15:15:54', | ||
1578 | 'fee': '0.00150000', | ||
1579 | 'globalTradeID': 1, | ||
1580 | 'orderNumber': '4', | ||
1581 | 'rate': '0.1', | ||
1582 | 'total': '0.00005', | ||
1583 | 'tradeID': '4-1', | ||
1584 | 'type': 'buy' | ||
1585 | }, | ||
1586 | 'order': '4', | ||
1587 | 'price': 0.1, | ||
1588 | 'side': 'buy', | ||
1589 | 'symbol': 'ETH/BTC', | ||
1590 | 'timestamp': 1521983754, | ||
1591 | 'type': 'limit' | ||
1592 | }, | ||
1593 | { # Wrong amount 2 | ||
1594 | 'amount': 0.0004, | ||
1595 | 'cost': 0.00004, | ||
1596 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1597 | 'id': '4-2', | ||
1598 | 'info': { | ||
1599 | 'amount': '0.0004', | ||
1600 | 'category': 'exchange', | ||
1601 | 'date': '2018-03-25 15:16:54', | ||
1602 | 'fee': '0.00150000', | ||
1603 | 'globalTradeID': 2, | ||
1604 | 'orderNumber': '4', | ||
1605 | 'rate': '0.1', | ||
1606 | 'total': '0.00004', | ||
1607 | 'tradeID': '4-2', | ||
1608 | 'type': 'buy' | ||
1609 | }, | ||
1610 | 'order': '4', | ||
1611 | 'price': 0.1, | ||
1612 | 'side': 'buy', | ||
1613 | 'symbol': 'ETH/BTC', | ||
1614 | 'timestamp': 1521983814, | ||
1615 | 'type': 'limit' | ||
1616 | }, | ||
1617 | { # Wrong price 1 | ||
1618 | 'amount': 0.0006, | ||
1619 | 'cost': 0.000066, | ||
1620 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1621 | 'id': '5-1', | ||
1622 | 'info': { | ||
1623 | 'amount': '0.0006', | ||
1624 | 'category': 'exchange', | ||
1625 | 'date': '2018-03-25 15:15:54', | ||
1626 | 'fee': '0.00150000', | ||
1627 | 'globalTradeID': 1, | ||
1628 | 'orderNumber': '5', | ||
1629 | 'rate': '0.11', | ||
1630 | 'total': '0.000066', | ||
1631 | 'tradeID': '5-1', | ||
1632 | 'type': 'buy' | ||
1633 | }, | ||
1634 | 'order': '5', | ||
1635 | 'price': 0.11, | ||
1636 | 'side': 'buy', | ||
1637 | 'symbol': 'ETH/BTC', | ||
1638 | 'timestamp': 1521983754, | ||
1639 | 'type': 'limit' | ||
1640 | }, | ||
1641 | { # Wrong price 2 | ||
1642 | 'amount': 0.0004, | ||
1643 | 'cost': 0.00004, | ||
1644 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1645 | 'id': '5-2', | ||
1646 | 'info': { | ||
1647 | 'amount': '0.0004', | ||
1648 | 'category': 'exchange', | ||
1649 | 'date': '2018-03-25 15:16:54', | ||
1650 | 'fee': '0.00150000', | ||
1651 | 'globalTradeID': 2, | ||
1652 | 'orderNumber': '5', | ||
1653 | 'rate': '0.1', | ||
1654 | 'total': '0.00004', | ||
1655 | 'tradeID': '5-2', | ||
1656 | 'type': 'buy' | ||
1657 | }, | ||
1658 | 'order': '5', | ||
1659 | 'price': 0.1, | ||
1660 | 'side': 'buy', | ||
1661 | 'symbol': 'ETH/BTC', | ||
1662 | 'timestamp': 1521983814, | ||
1663 | 'type': 'limit' | ||
1664 | }, | ||
1665 | { # All good 1 | ||
1666 | 'amount': 0.0006, | ||
1667 | 'cost': 0.00006, | ||
1668 | 'datetime': '2018-03-25T15:15:54.000Z', | ||
1669 | 'id': '7-1', | ||
1670 | 'info': { | ||
1671 | 'amount': '0.0006', | ||
1672 | 'category': 'exchange', | ||
1673 | 'date': '2018-03-25 15:15:54', | ||
1674 | 'fee': '0.00150000', | ||
1675 | 'globalTradeID': 1, | ||
1676 | 'orderNumber': '7', | ||
1677 | 'rate': '0.1', | ||
1678 | 'total': '0.00006', | ||
1679 | 'tradeID': '7-1', | ||
1680 | 'type': 'buy' | ||
1681 | }, | ||
1682 | 'order': '7', | ||
1683 | 'price': 0.1, | ||
1684 | 'side': 'buy', | ||
1685 | 'symbol': 'ETH/BTC', | ||
1686 | 'timestamp': 1521983754, | ||
1687 | 'type': 'limit' | ||
1688 | }, | ||
1689 | { # All good 2 | ||
1690 | 'amount': 0.0004, | ||
1691 | 'cost': 0.000036, | ||
1692 | 'datetime': '2018-03-25T15:16:54.000Z', | ||
1693 | 'id': '7-2', | ||
1694 | 'info': { | ||
1695 | 'amount': '0.0004', | ||
1696 | 'category': 'exchange', | ||
1697 | 'date': '2018-03-25 15:16:54', | ||
1698 | 'fee': '0.00150000', | ||
1699 | 'globalTradeID': 2, | ||
1700 | 'orderNumber': '7', | ||
1701 | 'rate': '0.09', | ||
1702 | 'total': '0.000036', | ||
1703 | 'tradeID': '7-2', | ||
1704 | 'type': 'buy' | ||
1705 | }, | ||
1706 | 'order': '7', | ||
1707 | 'price': 0.09, | ||
1708 | 'side': 'buy', | ||
1709 | 'symbol': 'ETH/BTC', | ||
1710 | 'timestamp': 1521983814, | ||
1711 | 'type': 'limit' | ||
1712 | }, | ||
1713 | ] | ||
1714 | |||
1715 | result = order.retrieve_order() | ||
1716 | self.assertTrue(result) | ||
1717 | self.assertEqual('7', order.results[0]["id"]) | ||
1718 | self.m.ccxt.fetch_orders.assert_called_once_with(symbol="ETH/BTC", since=1521983750) | ||
1719 | |||
1720 | self.m.reset_mock() | ||
1721 | with self.subTest(similar_open_order=False, past_trades=False): | ||
1722 | order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"), | ||
1723 | D("0.1"), "BTC", "long", self.m, "trade") | ||
1724 | order.start_date = datetime.datetime(2018, 3, 25, 15, 15, 55) | ||
1725 | |||
1726 | self.m.ccxt.order_precision.return_value = 8 | ||
1727 | self.m.ccxt.fetch_orders.return_value = [] | ||
1728 | self.m.ccxt.fetch_my_trades.return_value = [] | ||
1729 | result = order.retrieve_order() | ||
1730 | self.assertFalse(result) | ||
1731 | |||
1732 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1733 | class MouvementTest(WebMockTestCase): | ||
1734 | def test_values(self): | ||
1735 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1736 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
1737 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
1738 | "amount": "10", "total": "1" | ||
1739 | }) | ||
1740 | self.assertEqual("ETH", mouvement.currency) | ||
1741 | self.assertEqual("BTC", mouvement.base_currency) | ||
1742 | self.assertEqual(42, mouvement.id) | ||
1743 | self.assertEqual("buy", mouvement.action) | ||
1744 | self.assertEqual(D("0.0015"), mouvement.fee_rate) | ||
1745 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), mouvement.date) | ||
1746 | self.assertEqual(D("0.1"), mouvement.rate) | ||
1747 | self.assertEqual(portfolio.Amount("ETH", "10"), mouvement.total) | ||
1748 | self.assertEqual(portfolio.Amount("BTC", "1"), mouvement.total_in_base) | ||
1749 | |||
1750 | mouvement = portfolio.Mouvement("ETH", "BTC", { "foo": "bar" }) | ||
1751 | self.assertIsNone(mouvement.date) | ||
1752 | self.assertIsNone(mouvement.id) | ||
1753 | self.assertIsNone(mouvement.action) | ||
1754 | self.assertEqual(-1, mouvement.fee_rate) | ||
1755 | self.assertEqual(0, mouvement.rate) | ||
1756 | self.assertEqual(portfolio.Amount("ETH", 0), mouvement.total) | ||
1757 | self.assertEqual(portfolio.Amount("BTC", 0), mouvement.total_in_base) | ||
1758 | |||
1759 | def test__repr(self): | ||
1760 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1761 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
1762 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
1763 | "amount": "10", "total": "1" | ||
1764 | }) | ||
1765 | self.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement)) | ||
1766 | |||
1767 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1768 | "tradeID": 42, "type": "buy", | ||
1769 | "date": "garbage", "rate": "0.1", | ||
1770 | "amount": "10", "total": "1" | ||
1771 | }) | ||
1772 | self.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement)) | ||
1773 | |||
1774 | def test_as_json(self): | ||
1775 | mouvement = portfolio.Mouvement("ETH", "BTC", { | ||
1776 | "tradeID": 42, "type": "buy", "fee": "0.0015", | ||
1777 | "date": "2017-12-30 12:00:12", "rate": "0.1", | ||
1778 | "amount": "10", "total": "1" | ||
1779 | }) | ||
1780 | as_json = mouvement.as_json() | ||
1781 | |||
1782 | self.assertEqual(D("0.0015"), as_json["fee_rate"]) | ||
1783 | self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), as_json["date"]) | ||
1784 | self.assertEqual("buy", as_json["action"]) | ||
1785 | self.assertEqual(D("10"), as_json["total"]) | ||
1786 | self.assertEqual(D("1"), as_json["total_in_base"]) | ||
1787 | self.assertEqual("BTC", as_json["base_currency"]) | ||
1788 | self.assertEqual("ETH", as_json["currency"]) | ||
1789 | |||
1790 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
1791 | class AmountTest(WebMockTestCase): | ||
1792 | def test_values(self): | ||
1793 | amount = portfolio.Amount("BTC", "0.65") | ||
1794 | self.assertEqual(D("0.65"), amount.value) | ||
1795 | self.assertEqual("BTC", amount.currency) | ||
1796 | |||
1797 | def test_in_currency(self): | ||
1798 | amount = portfolio.Amount("ETC", 10) | ||
1799 | |||
1800 | self.assertEqual(amount, amount.in_currency("ETC", self.m)) | ||
1801 | |||
1802 | with self.subTest(desc="no ticker for currency"): | ||
1803 | self.m.get_ticker.return_value = None | ||
1804 | |||
1805 | self.assertRaises(Exception, amount.in_currency, "ETH", self.m) | ||
1806 | |||
1807 | with self.subTest(desc="nominal case"): | ||
1808 | self.m.get_ticker.return_value = { | ||
1809 | "bid": D("0.2"), | ||
1810 | "ask": D("0.4"), | ||
1811 | "average": D("0.3"), | ||
1812 | "foo": "bar", | ||
1813 | } | ||
1814 | converted_amount = amount.in_currency("ETH", self.m) | ||
1815 | |||
1816 | self.assertEqual(D("3.0"), converted_amount.value) | ||
1817 | self.assertEqual("ETH", converted_amount.currency) | ||
1818 | self.assertEqual(amount, converted_amount.linked_to) | ||
1819 | self.assertEqual("bar", converted_amount.ticker["foo"]) | ||
1820 | |||
1821 | converted_amount = amount.in_currency("ETH", self.m, action="bid", compute_value="default") | ||
1822 | self.assertEqual(D("2"), converted_amount.value) | ||
1823 | |||
1824 | converted_amount = amount.in_currency("ETH", self.m, compute_value="ask") | ||
1825 | self.assertEqual(D("4"), converted_amount.value) | ||
1826 | |||
1827 | converted_amount = amount.in_currency("ETH", self.m, rate=D("0.02")) | ||
1828 | self.assertEqual(D("0.2"), converted_amount.value) | ||
1829 | |||
1830 | def test__round(self): | ||
1831 | amount = portfolio.Amount("BAR", portfolio.D("1.23456789876")) | ||
1832 | self.assertEqual(D("1.23456789"), round(amount).value) | ||
1833 | self.assertEqual(D("1.23"), round(amount, 2).value) | ||
1834 | |||
1835 | def test__abs(self): | ||
1836 | amount = portfolio.Amount("SC", -120) | ||
1837 | self.assertEqual(120, abs(amount).value) | ||
1838 | self.assertEqual("SC", abs(amount).currency) | ||
1839 | |||
1840 | amount = portfolio.Amount("SC", 10) | ||
1841 | self.assertEqual(10, abs(amount).value) | ||
1842 | self.assertEqual("SC", abs(amount).currency) | ||
1843 | |||
1844 | def test__add(self): | ||
1845 | amount1 = portfolio.Amount("XVG", "12.9") | ||
1846 | amount2 = portfolio.Amount("XVG", "13.1") | ||
1847 | |||
1848 | self.assertEqual(26, (amount1 + amount2).value) | ||
1849 | self.assertEqual("XVG", (amount1 + amount2).currency) | ||
1850 | |||
1851 | amount3 = portfolio.Amount("ETH", "1.6") | ||
1852 | with self.assertRaises(Exception): | ||
1853 | amount1 + amount3 | ||
1854 | |||
1855 | amount4 = portfolio.Amount("ETH", 0.0) | ||
1856 | self.assertEqual(amount1, amount1 + amount4) | ||
1857 | |||
1858 | self.assertEqual(amount1, amount1 + 0) | ||
1859 | |||
1860 | def test__radd(self): | ||
1861 | amount = portfolio.Amount("XVG", "12.9") | ||
1862 | |||
1863 | self.assertEqual(amount, 0 + amount) | ||
1864 | with self.assertRaises(Exception): | ||
1865 | 4 + amount | ||
1866 | |||
1867 | def test__sub(self): | ||
1868 | amount1 = portfolio.Amount("XVG", "13.3") | ||
1869 | amount2 = portfolio.Amount("XVG", "13.1") | ||
1870 | |||
1871 | self.assertEqual(D("0.2"), (amount1 - amount2).value) | ||
1872 | self.assertEqual("XVG", (amount1 - amount2).currency) | ||
1873 | |||
1874 | amount3 = portfolio.Amount("ETH", "1.6") | ||
1875 | with self.assertRaises(Exception): | ||
1876 | amount1 - amount3 | ||
1877 | |||
1878 | amount4 = portfolio.Amount("ETH", 0.0) | ||
1879 | self.assertEqual(amount1, amount1 - amount4) | ||
1880 | |||
1881 | def test__rsub(self): | ||
1882 | amount = portfolio.Amount("ETH", "1.6") | ||
1883 | with self.assertRaises(Exception): | ||
1884 | 3 - amount | ||
1885 | |||
1886 | self.assertEqual(portfolio.Amount("ETH", "-1.6"), 0-amount) | ||
1887 | |||
1888 | def test__mul(self): | ||
1889 | amount = portfolio.Amount("XEM", 11) | ||
1890 | |||
1891 | self.assertEqual(D("38.5"), (amount * D("3.5")).value) | ||
1892 | self.assertEqual(D("33"), (amount * 3).value) | ||
1893 | |||
1894 | with self.assertRaises(Exception): | ||
1895 | amount * amount | ||
1896 | |||
1897 | def test__rmul(self): | ||
1898 | amount = portfolio.Amount("XEM", 11) | ||
1899 | |||
1900 | self.assertEqual(D("38.5"), (D("3.5") * amount).value) | ||
1901 | self.assertEqual(D("33"), (3 * amount).value) | ||
1902 | |||
1903 | def test__floordiv(self): | ||
1904 | amount = portfolio.Amount("XEM", 11) | ||
1905 | |||
1906 | self.assertEqual(D("5.5"), (amount / 2).value) | ||
1907 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | ||
1908 | |||
1909 | with self.assertRaises(Exception): | ||
1910 | amount / amount | ||
1911 | |||
1912 | def test__truediv(self): | ||
1913 | amount = portfolio.Amount("XEM", 11) | ||
1914 | |||
1915 | self.assertEqual(D("5.5"), (amount / 2).value) | ||
1916 | self.assertEqual(D("4.4"), (amount / D("2.5")).value) | ||
1917 | |||
1918 | def test__lt(self): | ||
1919 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1920 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1921 | |||
1922 | self.assertTrue(amount1 < amount2) | ||
1923 | self.assertFalse(amount2 < amount1) | ||
1924 | self.assertFalse(amount1 < amount1) | ||
1925 | |||
1926 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1927 | with self.assertRaises(Exception): | ||
1928 | amount1 < amount3 | ||
1929 | |||
1930 | def test__le(self): | ||
1931 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1932 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1933 | |||
1934 | self.assertTrue(amount1 <= amount2) | ||
1935 | self.assertFalse(amount2 <= amount1) | ||
1936 | self.assertTrue(amount1 <= amount1) | ||
1937 | |||
1938 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1939 | with self.assertRaises(Exception): | ||
1940 | amount1 <= amount3 | ||
1941 | |||
1942 | def test__gt(self): | ||
1943 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1944 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1945 | |||
1946 | self.assertTrue(amount2 > amount1) | ||
1947 | self.assertFalse(amount1 > amount2) | ||
1948 | self.assertFalse(amount1 > amount1) | ||
1949 | |||
1950 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1951 | with self.assertRaises(Exception): | ||
1952 | amount3 > amount1 | ||
1953 | |||
1954 | def test__ge(self): | ||
1955 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1956 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1957 | |||
1958 | self.assertTrue(amount2 >= amount1) | ||
1959 | self.assertFalse(amount1 >= amount2) | ||
1960 | self.assertTrue(amount1 >= amount1) | ||
1961 | |||
1962 | amount3 = portfolio.Amount("BTC", 1.6) | ||
1963 | with self.assertRaises(Exception): | ||
1964 | amount3 >= amount1 | ||
1965 | |||
1966 | def test__eq(self): | ||
1967 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1968 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1969 | amount3 = portfolio.Amount("BTD", 11.3) | ||
1970 | |||
1971 | self.assertFalse(amount1 == amount2) | ||
1972 | self.assertFalse(amount2 == amount1) | ||
1973 | self.assertTrue(amount1 == amount3) | ||
1974 | self.assertFalse(amount2 == 0) | ||
1975 | |||
1976 | amount4 = portfolio.Amount("BTC", 1.6) | ||
1977 | with self.assertRaises(Exception): | ||
1978 | amount1 == amount4 | ||
1979 | |||
1980 | amount5 = portfolio.Amount("BTD", 0) | ||
1981 | self.assertTrue(amount5 == 0) | ||
1982 | |||
1983 | def test__ne(self): | ||
1984 | amount1 = portfolio.Amount("BTD", 11.3) | ||
1985 | amount2 = portfolio.Amount("BTD", 13.1) | ||
1986 | amount3 = portfolio.Amount("BTD", 11.3) | ||
1987 | |||
1988 | self.assertTrue(amount1 != amount2) | ||
1989 | self.assertTrue(amount2 != amount1) | ||
1990 | self.assertFalse(amount1 != amount3) | ||
1991 | self.assertTrue(amount2 != 0) | ||
1992 | |||
1993 | amount4 = portfolio.Amount("BTC", 1.6) | ||
1994 | with self.assertRaises(Exception): | ||
1995 | amount1 != amount4 | ||
1996 | |||
1997 | amount5 = portfolio.Amount("BTD", 0) | ||
1998 | self.assertFalse(amount5 != 0) | ||
1999 | |||
2000 | def test__neg(self): | ||
2001 | amount1 = portfolio.Amount("BTD", "11.3") | ||
2002 | |||
2003 | self.assertEqual(portfolio.D("-11.3"), (-amount1).value) | ||
2004 | |||
2005 | def test__str(self): | ||
2006 | amount1 = portfolio.Amount("BTX", 32) | ||
2007 | self.assertEqual("32.00000000 BTX", str(amount1)) | ||
2008 | |||
2009 | amount2 = portfolio.Amount("USDT", 12000) | ||
2010 | amount1.linked_to = amount2 | ||
2011 | self.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1)) | ||
2012 | |||
2013 | def test__repr(self): | ||
2014 | amount1 = portfolio.Amount("BTX", 32) | ||
2015 | self.assertEqual("Amount(32.00000000 BTX)", repr(amount1)) | ||
2016 | |||
2017 | amount2 = portfolio.Amount("USDT", 12000) | ||
2018 | amount1.linked_to = amount2 | ||
2019 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1)) | ||
2020 | |||
2021 | amount3 = portfolio.Amount("BTC", 0.1) | ||
2022 | amount2.linked_to = amount3 | ||
2023 | self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1)) | ||
2024 | |||
2025 | def test_as_json(self): | ||
2026 | amount = portfolio.Amount("BTX", 32) | ||
2027 | self.assertEqual({"currency": "BTX", "value": D("32")}, amount.as_json()) | ||
2028 | |||
2029 | amount = portfolio.Amount("BTX", "1E-10") | ||
2030 | self.assertEqual({"currency": "BTX", "value": D("0")}, amount.as_json()) | ||
2031 | |||
2032 | amount = portfolio.Amount("BTX", "1E-5") | ||
2033 | self.assertEqual({"currency": "BTX", "value": D("0.00001")}, amount.as_json()) | ||
2034 | self.assertEqual("0.00001", str(amount.as_json()["value"])) | ||
2035 | |||
2036 | |||
diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..c0b1fb9 --- /dev/null +++ b/tests/test_store.py | |||
@@ -0,0 +1,1203 @@ | |||
1 | from .helper import * | ||
2 | import requests | ||
3 | import datetime | ||
4 | import threading | ||
5 | import market, portfolio, store | ||
6 | |||
7 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
8 | class NoopLockTest(unittest.TestCase): | ||
9 | def test_with(self): | ||
10 | noop_lock = store.NoopLock() | ||
11 | with noop_lock: | ||
12 | self.assertTrue(True) | ||
13 | |||
14 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
15 | class LockedVarTest(unittest.TestCase): | ||
16 | |||
17 | def test_values(self): | ||
18 | locked_var = store.LockedVar("Foo") | ||
19 | self.assertIsInstance(locked_var.lock, store.NoopLock) | ||
20 | self.assertEqual("Foo", locked_var.val) | ||
21 | |||
22 | def test_get(self): | ||
23 | with self.subTest(desc="Normal case"): | ||
24 | locked_var = store.LockedVar("Foo") | ||
25 | self.assertEqual("Foo", locked_var.get()) | ||
26 | with self.subTest(desc="Dict"): | ||
27 | locked_var = store.LockedVar({"foo": "bar"}) | ||
28 | self.assertEqual({"foo": "bar"}, locked_var.get()) | ||
29 | self.assertEqual("bar", locked_var.get("foo")) | ||
30 | self.assertIsNone(locked_var.get("other")) | ||
31 | |||
32 | def test_set(self): | ||
33 | locked_var = store.LockedVar("Foo") | ||
34 | locked_var.set("Bar") | ||
35 | self.assertEqual("Bar", locked_var.get()) | ||
36 | |||
37 | def test__getattr(self): | ||
38 | dummy = type('Dummy', (object,), {})() | ||
39 | dummy.attribute = "Hey" | ||
40 | |||
41 | locked_var = store.LockedVar(dummy) | ||
42 | self.assertEqual("Hey", locked_var.attribute) | ||
43 | with self.assertRaises(AttributeError): | ||
44 | locked_var.other | ||
45 | |||
46 | def test_start_lock(self): | ||
47 | locked_var = store.LockedVar("Foo") | ||
48 | locked_var.start_lock() | ||
49 | self.assertEqual("lock", locked_var.lock.__class__.__name__) | ||
50 | |||
51 | thread1 = threading.Thread(target=locked_var.set, args=["Bar1"]) | ||
52 | thread2 = threading.Thread(target=locked_var.set, args=["Bar2"]) | ||
53 | thread3 = threading.Thread(target=locked_var.set, args=["Bar3"]) | ||
54 | |||
55 | with locked_var.lock: | ||
56 | thread1.start() | ||
57 | thread2.start() | ||
58 | thread3.start() | ||
59 | |||
60 | self.assertEqual("Foo", locked_var.val) | ||
61 | thread1.join() | ||
62 | thread2.join() | ||
63 | thread3.join() | ||
64 | self.assertEqual("Bar", locked_var.get()[0:3]) | ||
65 | |||
66 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
67 | class TradeStoreTest(WebMockTestCase): | ||
68 | def test_compute_trades(self): | ||
69 | self.m.balances.currencies.return_value = ["XMR", "DASH", "XVG", "BTC", "ETH"] | ||
70 | |||
71 | values_in_base = { | ||
72 | "XMR": portfolio.Amount("BTC", D("0.9")), | ||
73 | "DASH": portfolio.Amount("BTC", D("0.4")), | ||
74 | "XVG": portfolio.Amount("BTC", D("-0.5")), | ||
75 | "BTC": portfolio.Amount("BTC", D("0.5")), | ||
76 | } | ||
77 | new_repartition = { | ||
78 | "DASH": portfolio.Amount("BTC", D("0.5")), | ||
79 | "XVG": portfolio.Amount("BTC", D("0.1")), | ||
80 | "BTC": portfolio.Amount("BTC", D("0.4")), | ||
81 | "ETH": portfolio.Amount("BTC", D("0.3")), | ||
82 | } | ||
83 | side_effect = [ | ||
84 | (True, 1), | ||
85 | (False, 2), | ||
86 | (False, 3), | ||
87 | (True, 4), | ||
88 | (True, 5) | ||
89 | ] | ||
90 | |||
91 | with mock.patch.object(market.TradeStore, "trade_if_matching") as trade_if_matching: | ||
92 | trade_store = market.TradeStore(self.m) | ||
93 | trade_if_matching.side_effect = side_effect | ||
94 | |||
95 | trade_store.compute_trades(values_in_base, | ||
96 | new_repartition, only="only") | ||
97 | |||
98 | self.assertEqual(5, trade_if_matching.call_count) | ||
99 | self.assertEqual(3, len(trade_store.all)) | ||
100 | self.assertEqual([1, 4, 5], trade_store.all) | ||
101 | self.m.report.log_trades.assert_called_with(side_effect, "only") | ||
102 | |||
103 | def test_trade_if_matching(self): | ||
104 | |||
105 | with self.subTest(only="nope"): | ||
106 | trade_store = market.TradeStore(self.m) | ||
107 | result = trade_store.trade_if_matching( | ||
108 | portfolio.Amount("BTC", D("0")), | ||
109 | portfolio.Amount("BTC", D("0.3")), | ||
110 | "ETH", only="nope") | ||
111 | self.assertEqual(False, result[0]) | ||
112 | self.assertIsInstance(result[1], portfolio.Trade) | ||
113 | |||
114 | with self.subTest(only=None): | ||
115 | trade_store = market.TradeStore(self.m) | ||
116 | result = trade_store.trade_if_matching( | ||
117 | portfolio.Amount("BTC", D("0")), | ||
118 | portfolio.Amount("BTC", D("0.3")), | ||
119 | "ETH", only=None) | ||
120 | self.assertEqual(True, result[0]) | ||
121 | |||
122 | with self.subTest(only="acquire"): | ||
123 | trade_store = market.TradeStore(self.m) | ||
124 | result = trade_store.trade_if_matching( | ||
125 | portfolio.Amount("BTC", D("0")), | ||
126 | portfolio.Amount("BTC", D("0.3")), | ||
127 | "ETH", only="acquire") | ||
128 | self.assertEqual(True, result[0]) | ||
129 | |||
130 | with self.subTest(only="dispose"): | ||
131 | trade_store = market.TradeStore(self.m) | ||
132 | result = trade_store.trade_if_matching( | ||
133 | portfolio.Amount("BTC", D("0")), | ||
134 | portfolio.Amount("BTC", D("0.3")), | ||
135 | "ETH", only="dispose") | ||
136 | self.assertEqual(False, result[0]) | ||
137 | |||
138 | def test_prepare_orders(self): | ||
139 | trade_store = market.TradeStore(self.m) | ||
140 | |||
141 | trade_mock1 = mock.Mock() | ||
142 | trade_mock2 = mock.Mock() | ||
143 | trade_mock3 = mock.Mock() | ||
144 | |||
145 | trade_mock1.prepare_order.return_value = 1 | ||
146 | trade_mock2.prepare_order.return_value = 2 | ||
147 | trade_mock3.prepare_order.return_value = 3 | ||
148 | |||
149 | trade_mock1.pending = True | ||
150 | trade_mock2.pending = True | ||
151 | trade_mock3.pending = False | ||
152 | |||
153 | trade_store.all.append(trade_mock1) | ||
154 | trade_store.all.append(trade_mock2) | ||
155 | trade_store.all.append(trade_mock3) | ||
156 | |||
157 | trade_store.prepare_orders() | ||
158 | trade_mock1.prepare_order.assert_called_with(compute_value="default") | ||
159 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | ||
160 | trade_mock3.prepare_order.assert_not_called() | ||
161 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "default") | ||
162 | |||
163 | self.m.report.log_orders.reset_mock() | ||
164 | |||
165 | trade_store.prepare_orders(compute_value="bla") | ||
166 | trade_mock1.prepare_order.assert_called_with(compute_value="bla") | ||
167 | trade_mock2.prepare_order.assert_called_with(compute_value="bla") | ||
168 | self.m.report.log_orders.assert_called_once_with([1, 2], None, "bla") | ||
169 | |||
170 | trade_mock1.prepare_order.reset_mock() | ||
171 | trade_mock2.prepare_order.reset_mock() | ||
172 | self.m.report.log_orders.reset_mock() | ||
173 | |||
174 | trade_mock1.action = "foo" | ||
175 | trade_mock2.action = "bar" | ||
176 | trade_store.prepare_orders(only="bar") | ||
177 | trade_mock1.prepare_order.assert_not_called() | ||
178 | trade_mock2.prepare_order.assert_called_with(compute_value="default") | ||
179 | self.m.report.log_orders.assert_called_once_with([2], "bar", "default") | ||
180 | |||
181 | def test_print_all_with_order(self): | ||
182 | trade_mock1 = mock.Mock() | ||
183 | trade_mock2 = mock.Mock() | ||
184 | trade_mock3 = mock.Mock() | ||
185 | trade_store = market.TradeStore(self.m) | ||
186 | trade_store.all = [trade_mock1, trade_mock2, trade_mock3] | ||
187 | |||
188 | trade_store.print_all_with_order() | ||
189 | |||
190 | trade_mock1.print_with_order.assert_called() | ||
191 | trade_mock2.print_with_order.assert_called() | ||
192 | trade_mock3.print_with_order.assert_called() | ||
193 | |||
194 | def test_run_orders(self): | ||
195 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | ||
196 | order_mock1 = mock.Mock() | ||
197 | order_mock2 = mock.Mock() | ||
198 | order_mock3 = mock.Mock() | ||
199 | trade_store = market.TradeStore(self.m) | ||
200 | |||
201 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | ||
202 | |||
203 | trade_store.run_orders() | ||
204 | |||
205 | all_orders.assert_called_with(state="pending") | ||
206 | |||
207 | order_mock1.run.assert_called() | ||
208 | order_mock2.run.assert_called() | ||
209 | order_mock3.run.assert_called() | ||
210 | |||
211 | self.m.report.log_stage.assert_called_with("run_orders") | ||
212 | self.m.report.log_orders.assert_called_with([order_mock1, order_mock2, | ||
213 | order_mock3]) | ||
214 | |||
215 | def test_all_orders(self): | ||
216 | trade_mock1 = mock.Mock() | ||
217 | trade_mock2 = mock.Mock() | ||
218 | |||
219 | order_mock1 = mock.Mock() | ||
220 | order_mock2 = mock.Mock() | ||
221 | order_mock3 = mock.Mock() | ||
222 | |||
223 | trade_mock1.orders = [order_mock1, order_mock2] | ||
224 | trade_mock2.orders = [order_mock3] | ||
225 | |||
226 | order_mock1.status = "pending" | ||
227 | order_mock2.status = "open" | ||
228 | order_mock3.status = "open" | ||
229 | |||
230 | trade_store = market.TradeStore(self.m) | ||
231 | trade_store.all.append(trade_mock1) | ||
232 | trade_store.all.append(trade_mock2) | ||
233 | |||
234 | orders = trade_store.all_orders() | ||
235 | self.assertEqual(3, len(orders)) | ||
236 | |||
237 | open_orders = trade_store.all_orders(state="open") | ||
238 | self.assertEqual(2, len(open_orders)) | ||
239 | self.assertEqual([order_mock2, order_mock3], open_orders) | ||
240 | |||
241 | def test_update_all_orders_status(self): | ||
242 | with mock.patch.object(market.TradeStore, "all_orders") as all_orders: | ||
243 | order_mock1 = mock.Mock() | ||
244 | order_mock2 = mock.Mock() | ||
245 | order_mock3 = mock.Mock() | ||
246 | |||
247 | all_orders.return_value = [order_mock1, order_mock2, order_mock3] | ||
248 | |||
249 | trade_store = market.TradeStore(self.m) | ||
250 | |||
251 | trade_store.update_all_orders_status() | ||
252 | all_orders.assert_called_with(state="open") | ||
253 | |||
254 | order_mock1.get_status.assert_called() | ||
255 | order_mock2.get_status.assert_called() | ||
256 | order_mock3.get_status.assert_called() | ||
257 | |||
258 | def test_close_trades(self): | ||
259 | trade_mock1 = mock.Mock() | ||
260 | trade_mock2 = mock.Mock() | ||
261 | trade_mock3 = mock.Mock() | ||
262 | |||
263 | trade_store = market.TradeStore(self.m) | ||
264 | |||
265 | trade_store.all.append(trade_mock1) | ||
266 | trade_store.all.append(trade_mock2) | ||
267 | trade_store.all.append(trade_mock3) | ||
268 | |||
269 | trade_store.close_trades() | ||
270 | |||
271 | trade_mock1.close.assert_called_once_with() | ||
272 | trade_mock2.close.assert_called_once_with() | ||
273 | trade_mock3.close.assert_called_once_with() | ||
274 | |||
275 | def test_pending(self): | ||
276 | trade_mock1 = mock.Mock() | ||
277 | trade_mock1.pending = True | ||
278 | trade_mock2 = mock.Mock() | ||
279 | trade_mock2.pending = True | ||
280 | trade_mock3 = mock.Mock() | ||
281 | trade_mock3.pending = False | ||
282 | |||
283 | trade_store = market.TradeStore(self.m) | ||
284 | |||
285 | trade_store.all.append(trade_mock1) | ||
286 | trade_store.all.append(trade_mock2) | ||
287 | trade_store.all.append(trade_mock3) | ||
288 | |||
289 | self.assertEqual([trade_mock1, trade_mock2], trade_store.pending) | ||
290 | |||
291 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
292 | class BalanceStoreTest(WebMockTestCase): | ||
293 | def setUp(self): | ||
294 | super().setUp() | ||
295 | |||
296 | self.fetch_balance = { | ||
297 | "ETC": { | ||
298 | "exchange_free": 0, | ||
299 | "exchange_used": 0, | ||
300 | "exchange_total": 0, | ||
301 | "margin_total": 0, | ||
302 | }, | ||
303 | "USDT": { | ||
304 | "exchange_free": D("6.0"), | ||
305 | "exchange_used": D("1.2"), | ||
306 | "exchange_total": D("7.2"), | ||
307 | "margin_total": 0, | ||
308 | }, | ||
309 | "XVG": { | ||
310 | "exchange_free": 16, | ||
311 | "exchange_used": 0, | ||
312 | "exchange_total": 16, | ||
313 | "margin_total": 0, | ||
314 | }, | ||
315 | "XMR": { | ||
316 | "exchange_free": 0, | ||
317 | "exchange_used": 0, | ||
318 | "exchange_total": 0, | ||
319 | "margin_total": D("-1.0"), | ||
320 | "margin_free": 0, | ||
321 | }, | ||
322 | } | ||
323 | |||
324 | def test_in_currency(self): | ||
325 | self.m.get_ticker.return_value = { | ||
326 | "bid": D("0.09"), | ||
327 | "ask": D("0.11"), | ||
328 | "average": D("0.1"), | ||
329 | } | ||
330 | |||
331 | balance_store = market.BalanceStore(self.m) | ||
332 | balance_store.all = { | ||
333 | "BTC": portfolio.Balance("BTC", { | ||
334 | "total": "0.65", | ||
335 | "exchange_total":"0.65", | ||
336 | "exchange_free": "0.35", | ||
337 | "exchange_used": "0.30"}), | ||
338 | "ETH": portfolio.Balance("ETH", { | ||
339 | "total": 3, | ||
340 | "exchange_total": 3, | ||
341 | "exchange_free": 3, | ||
342 | "exchange_used": 0}), | ||
343 | } | ||
344 | |||
345 | amounts = balance_store.in_currency("BTC") | ||
346 | self.assertEqual("BTC", amounts["ETH"].currency) | ||
347 | self.assertEqual(D("0.65"), amounts["BTC"].value) | ||
348 | self.assertEqual(D("0.30"), amounts["ETH"].value) | ||
349 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
350 | "average", "total") | ||
351 | self.m.report.log_tickers.reset_mock() | ||
352 | |||
353 | amounts = balance_store.in_currency("BTC", compute_value="bid") | ||
354 | self.assertEqual(D("0.65"), amounts["BTC"].value) | ||
355 | self.assertEqual(D("0.27"), amounts["ETH"].value) | ||
356 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
357 | "bid", "total") | ||
358 | self.m.report.log_tickers.reset_mock() | ||
359 | |||
360 | amounts = balance_store.in_currency("BTC", compute_value="bid", type="exchange_used") | ||
361 | self.assertEqual(D("0.30"), amounts["BTC"].value) | ||
362 | self.assertEqual(0, amounts["ETH"].value) | ||
363 | self.m.report.log_tickers.assert_called_once_with(amounts, "BTC", | ||
364 | "bid", "exchange_used") | ||
365 | self.m.report.log_tickers.reset_mock() | ||
366 | |||
367 | def test_fetch_balances(self): | ||
368 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | ||
369 | |||
370 | balance_store = market.BalanceStore(self.m) | ||
371 | |||
372 | balance_store.fetch_balances() | ||
373 | self.assertNotIn("ETC", balance_store.currencies()) | ||
374 | self.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store.currencies())) | ||
375 | |||
376 | balance_store.all["ETC"] = portfolio.Balance("ETC", { | ||
377 | "exchange_total": "1", "exchange_free": "0", | ||
378 | "exchange_used": "1" }) | ||
379 | balance_store.fetch_balances(tag="foo") | ||
380 | self.assertEqual(0, balance_store.all["ETC"].total) | ||
381 | self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies())) | ||
382 | self.m.report.log_balances.assert_called_with(tag="foo") | ||
383 | |||
384 | @mock.patch.object(market.Portfolio, "repartition") | ||
385 | def test_dispatch_assets(self, repartition): | ||
386 | self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance | ||
387 | |||
388 | balance_store = market.BalanceStore(self.m) | ||
389 | balance_store.fetch_balances() | ||
390 | |||
391 | self.assertNotIn("XEM", balance_store.currencies()) | ||
392 | |||
393 | repartition_hash = { | ||
394 | "XEM": (D("0.75"), "long"), | ||
395 | "BTC": (D("0.26"), "long"), | ||
396 | "DASH": (D("0.10"), "short"), | ||
397 | } | ||
398 | repartition.return_value = repartition_hash | ||
399 | |||
400 | amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1")) | ||
401 | repartition.assert_called_with(liquidity="medium") | ||
402 | self.assertIn("XEM", balance_store.currencies()) | ||
403 | self.assertEqual(D("2.6"), amounts["BTC"].value) | ||
404 | self.assertEqual(D("7.5"), amounts["XEM"].value) | ||
405 | self.assertEqual(D("-1.0"), amounts["DASH"].value) | ||
406 | self.m.report.log_balances.assert_called_with(tag=None) | ||
407 | self.m.report.log_dispatch.assert_called_once_with(portfolio.Amount("BTC", | ||
408 | "11.1"), amounts, "medium", repartition_hash) | ||
409 | |||
410 | def test_currencies(self): | ||
411 | balance_store = market.BalanceStore(self.m) | ||
412 | |||
413 | balance_store.all = { | ||
414 | "BTC": portfolio.Balance("BTC", { | ||
415 | "total": "0.65", | ||
416 | "exchange_total":"0.65", | ||
417 | "exchange_free": "0.35", | ||
418 | "exchange_used": "0.30"}), | ||
419 | "ETH": portfolio.Balance("ETH", { | ||
420 | "total": 3, | ||
421 | "exchange_total": 3, | ||
422 | "exchange_free": 3, | ||
423 | "exchange_used": 0}), | ||
424 | } | ||
425 | self.assertListEqual(["BTC", "ETH"], list(balance_store.currencies())) | ||
426 | |||
427 | def test_as_json(self): | ||
428 | balance_mock1 = mock.Mock() | ||
429 | balance_mock1.as_json.return_value = 1 | ||
430 | |||
431 | balance_mock2 = mock.Mock() | ||
432 | balance_mock2.as_json.return_value = 2 | ||
433 | |||
434 | balance_store = market.BalanceStore(self.m) | ||
435 | balance_store.all = { | ||
436 | "BTC": balance_mock1, | ||
437 | "ETH": balance_mock2, | ||
438 | } | ||
439 | |||
440 | as_json = balance_store.as_json() | ||
441 | self.assertEqual(1, as_json["BTC"]) | ||
442 | self.assertEqual(2, as_json["ETH"]) | ||
443 | |||
444 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
445 | class ReportStoreTest(WebMockTestCase): | ||
446 | def test_add_log(self): | ||
447 | report_store = market.ReportStore(self.m) | ||
448 | report_store.add_log({"foo": "bar"}) | ||
449 | |||
450 | self.assertEqual({"foo": "bar", "date": mock.ANY}, report_store.logs[0]) | ||
451 | |||
452 | def test_set_verbose(self): | ||
453 | report_store = market.ReportStore(self.m) | ||
454 | with self.subTest(verbose=True): | ||
455 | report_store.set_verbose(True) | ||
456 | self.assertTrue(report_store.verbose_print) | ||
457 | |||
458 | with self.subTest(verbose=False): | ||
459 | report_store.set_verbose(False) | ||
460 | self.assertFalse(report_store.verbose_print) | ||
461 | |||
462 | def test_merge(self): | ||
463 | report_store1 = market.ReportStore(self.m, verbose_print=False) | ||
464 | report_store2 = market.ReportStore(None, verbose_print=False) | ||
465 | |||
466 | report_store2.log_stage("1") | ||
467 | report_store1.log_stage("2") | ||
468 | report_store2.log_stage("3") | ||
469 | |||
470 | report_store1.merge(report_store2) | ||
471 | |||
472 | self.assertEqual(3, len(report_store1.logs)) | ||
473 | self.assertEqual(["1", "2", "3"], list(map(lambda x: x["stage"], report_store1.logs))) | ||
474 | self.assertEqual(6, len(report_store1.print_logs)) | ||
475 | |||
476 | def test_print_log(self): | ||
477 | report_store = market.ReportStore(self.m) | ||
478 | with self.subTest(verbose=True),\ | ||
479 | mock.patch.object(store, "datetime") as time_mock,\ | ||
480 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
481 | time_mock.now.return_value = datetime.datetime(2018, 2, 25, 2, 20, 10) | ||
482 | report_store.set_verbose(True) | ||
483 | report_store.print_log("Coucou") | ||
484 | report_store.print_log(portfolio.Amount("BTC", 1)) | ||
485 | self.assertEqual(stdout_mock.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n") | ||
486 | |||
487 | with self.subTest(verbose=False),\ | ||
488 | mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock: | ||
489 | report_store.set_verbose(False) | ||
490 | report_store.print_log("Coucou") | ||
491 | report_store.print_log(portfolio.Amount("BTC", 1)) | ||
492 | self.assertEqual(stdout_mock.getvalue(), "") | ||
493 | |||
494 | def test_default_json_serial(self): | ||
495 | report_store = market.ReportStore(self.m) | ||
496 | |||
497 | self.assertEqual("2018-02-24T00:00:00", | ||
498 | report_store.default_json_serial(portfolio.datetime(2018, 2, 24))) | ||
499 | self.assertEqual("1.00000000 BTC", | ||
500 | report_store.default_json_serial(portfolio.Amount("BTC", 1))) | ||
501 | |||
502 | def test_to_json(self): | ||
503 | report_store = market.ReportStore(self.m) | ||
504 | report_store.logs.append({"foo": "bar"}) | ||
505 | self.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store.to_json()) | ||
506 | report_store.logs.append({"date": portfolio.datetime(2018, 2, 24)}) | ||
507 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store.to_json()) | ||
508 | report_store.logs.append({"amount": portfolio.Amount("BTC", 1)}) | ||
509 | self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store.to_json()) | ||
510 | |||
511 | def test_to_json_array(self): | ||
512 | report_store = market.ReportStore(self.m) | ||
513 | report_store.logs.append({ | ||
514 | "date": "date1", "type": "type1", "foo": "bar", "bla": "bla" | ||
515 | }) | ||
516 | report_store.logs.append({ | ||
517 | "date": "date2", "type": "type2", "foo": "bar", "bla": "bla" | ||
518 | }) | ||
519 | logs = list(report_store.to_json_array()) | ||
520 | |||
521 | self.assertEqual(2, len(logs)) | ||
522 | self.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[0]) | ||
523 | self.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[1]) | ||
524 | |||
525 | @mock.patch.object(market.ReportStore, "print_log") | ||
526 | @mock.patch.object(market.ReportStore, "add_log") | ||
527 | def test_log_stage(self, add_log, print_log): | ||
528 | report_store = market.ReportStore(self.m) | ||
529 | c = lambda x: x | ||
530 | report_store.log_stage("foo", bar="baz", c=c, d=portfolio.Amount("BTC", 1)) | ||
531 | print_log.assert_has_calls([ | ||
532 | mock.call("-----------"), | ||
533 | mock.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"), | ||
534 | ]) | ||
535 | add_log.assert_called_once_with({ | ||
536 | 'type': 'stage', | ||
537 | 'stage': 'foo', | ||
538 | 'args': { | ||
539 | 'bar': 'baz', | ||
540 | 'c': 'c = lambda x: x', | ||
541 | 'd': { | ||
542 | 'currency': 'BTC', | ||
543 | 'value': D('1') | ||
544 | } | ||
545 | } | ||
546 | }) | ||
547 | |||
548 | @mock.patch.object(market.ReportStore, "print_log") | ||
549 | @mock.patch.object(market.ReportStore, "add_log") | ||
550 | def test_log_balances(self, add_log, print_log): | ||
551 | report_store = market.ReportStore(self.m) | ||
552 | self.m.balances.as_json.return_value = "json" | ||
553 | self.m.balances.all = { "FOO": "bar", "BAR": "baz" } | ||
554 | |||
555 | report_store.log_balances(tag="tag") | ||
556 | print_log.assert_has_calls([ | ||
557 | mock.call("[Balance]"), | ||
558 | mock.call("\tbar"), | ||
559 | mock.call("\tbaz"), | ||
560 | ]) | ||
561 | add_log.assert_called_once_with({ | ||
562 | 'type': 'balance', | ||
563 | 'balances': 'json', | ||
564 | 'tag': 'tag' | ||
565 | }) | ||
566 | |||
567 | @mock.patch.object(market.ReportStore, "print_log") | ||
568 | @mock.patch.object(market.ReportStore, "add_log") | ||
569 | def test_log_tickers(self, add_log, print_log): | ||
570 | report_store = market.ReportStore(self.m) | ||
571 | amounts = { | ||
572 | "BTC": portfolio.Amount("BTC", 10), | ||
573 | "ETH": portfolio.Amount("BTC", D("0.3")) | ||
574 | } | ||
575 | amounts["ETH"].rate = D("0.1") | ||
576 | |||
577 | report_store.log_tickers(amounts, "BTC", "default", "total") | ||
578 | print_log.assert_not_called() | ||
579 | add_log.assert_called_once_with({ | ||
580 | 'type': 'tickers', | ||
581 | 'compute_value': 'default', | ||
582 | 'balance_type': 'total', | ||
583 | 'currency': 'BTC', | ||
584 | 'balances': { | ||
585 | 'BTC': D('10'), | ||
586 | 'ETH': D('0.3') | ||
587 | }, | ||
588 | 'rates': { | ||
589 | 'BTC': None, | ||
590 | 'ETH': D('0.1') | ||
591 | }, | ||
592 | 'total': D('10.3') | ||
593 | }) | ||
594 | |||
595 | add_log.reset_mock() | ||
596 | compute_value = lambda x: x["bid"] | ||
597 | report_store.log_tickers(amounts, "BTC", compute_value, "total") | ||
598 | add_log.assert_called_once_with({ | ||
599 | 'type': 'tickers', | ||
600 | 'compute_value': 'compute_value = lambda x: x["bid"]', | ||
601 | 'balance_type': 'total', | ||
602 | 'currency': 'BTC', | ||
603 | 'balances': { | ||
604 | 'BTC': D('10'), | ||
605 | 'ETH': D('0.3') | ||
606 | }, | ||
607 | 'rates': { | ||
608 | 'BTC': None, | ||
609 | 'ETH': D('0.1') | ||
610 | }, | ||
611 | 'total': D('10.3') | ||
612 | }) | ||
613 | |||
614 | @mock.patch.object(market.ReportStore, "print_log") | ||
615 | @mock.patch.object(market.ReportStore, "add_log") | ||
616 | def test_log_dispatch(self, add_log, print_log): | ||
617 | report_store = market.ReportStore(self.m) | ||
618 | amount = portfolio.Amount("BTC", "10.3") | ||
619 | amounts = { | ||
620 | "BTC": portfolio.Amount("BTC", 10), | ||
621 | "ETH": portfolio.Amount("BTC", D("0.3")) | ||
622 | } | ||
623 | report_store.log_dispatch(amount, amounts, "medium", "repartition") | ||
624 | print_log.assert_not_called() | ||
625 | add_log.assert_called_once_with({ | ||
626 | 'type': 'dispatch', | ||
627 | 'liquidity': 'medium', | ||
628 | 'repartition_ratio': 'repartition', | ||
629 | 'total_amount': { | ||
630 | 'currency': 'BTC', | ||
631 | 'value': D('10.3') | ||
632 | }, | ||
633 | 'repartition': { | ||
634 | 'BTC': D('10'), | ||
635 | 'ETH': D('0.3') | ||
636 | } | ||
637 | }) | ||
638 | |||
639 | @mock.patch.object(market.ReportStore, "print_log") | ||
640 | @mock.patch.object(market.ReportStore, "add_log") | ||
641 | def test_log_trades(self, add_log, print_log): | ||
642 | report_store = market.ReportStore(self.m) | ||
643 | trade_mock1 = mock.Mock() | ||
644 | trade_mock2 = mock.Mock() | ||
645 | trade_mock1.as_json.return_value = { "trade": "1" } | ||
646 | trade_mock2.as_json.return_value = { "trade": "2" } | ||
647 | |||
648 | matching_and_trades = [ | ||
649 | (True, trade_mock1), | ||
650 | (False, trade_mock2), | ||
651 | ] | ||
652 | report_store.log_trades(matching_and_trades, "only") | ||
653 | |||
654 | print_log.assert_not_called() | ||
655 | add_log.assert_called_with({ | ||
656 | 'type': 'trades', | ||
657 | 'only': 'only', | ||
658 | 'debug': False, | ||
659 | 'trades': [ | ||
660 | {'trade': '1', 'skipped': False}, | ||
661 | {'trade': '2', 'skipped': True} | ||
662 | ] | ||
663 | }) | ||
664 | |||
665 | @mock.patch.object(market.ReportStore, "print_log") | ||
666 | @mock.patch.object(market.ReportStore, "add_log") | ||
667 | def test_log_orders(self, add_log, print_log): | ||
668 | report_store = market.ReportStore(self.m) | ||
669 | |||
670 | order_mock1 = mock.Mock() | ||
671 | order_mock2 = mock.Mock() | ||
672 | |||
673 | order_mock1.as_json.return_value = "order1" | ||
674 | order_mock2.as_json.return_value = "order2" | ||
675 | |||
676 | orders = [order_mock1, order_mock2] | ||
677 | |||
678 | report_store.log_orders(orders, tick="tick", | ||
679 | only="only", compute_value="compute_value") | ||
680 | |||
681 | print_log.assert_called_once_with("[Orders]") | ||
682 | self.m.trades.print_all_with_order.assert_called_once_with(ind="\t") | ||
683 | |||
684 | add_log.assert_called_with({ | ||
685 | 'type': 'orders', | ||
686 | 'only': 'only', | ||
687 | 'compute_value': 'compute_value', | ||
688 | 'tick': 'tick', | ||
689 | 'orders': ['order1', 'order2'] | ||
690 | }) | ||
691 | |||
692 | add_log.reset_mock() | ||
693 | def compute_value(x, y): | ||
694 | return x[y] | ||
695 | report_store.log_orders(orders, tick="tick", | ||
696 | only="only", compute_value=compute_value) | ||
697 | add_log.assert_called_with({ | ||
698 | 'type': 'orders', | ||
699 | 'only': 'only', | ||
700 | 'compute_value': 'def compute_value(x, y):\n return x[y]', | ||
701 | 'tick': 'tick', | ||
702 | 'orders': ['order1', 'order2'] | ||
703 | }) | ||
704 | |||
705 | |||
706 | @mock.patch.object(market.ReportStore, "print_log") | ||
707 | @mock.patch.object(market.ReportStore, "add_log") | ||
708 | def test_log_order(self, add_log, print_log): | ||
709 | report_store = market.ReportStore(self.m) | ||
710 | order_mock = mock.Mock() | ||
711 | order_mock.as_json.return_value = "order" | ||
712 | new_order_mock = mock.Mock() | ||
713 | new_order_mock.as_json.return_value = "new_order" | ||
714 | order_mock.__repr__ = mock.Mock() | ||
715 | order_mock.__repr__.return_value = "Order Mock" | ||
716 | new_order_mock.__repr__ = mock.Mock() | ||
717 | new_order_mock.__repr__.return_value = "New order Mock" | ||
718 | |||
719 | with self.subTest(finished=True): | ||
720 | report_store.log_order(order_mock, 1, finished=True) | ||
721 | print_log.assert_called_once_with("[Order] Finished Order Mock") | ||
722 | add_log.assert_called_once_with({ | ||
723 | 'type': 'order', | ||
724 | 'tick': 1, | ||
725 | 'update': None, | ||
726 | 'order': 'order', | ||
727 | 'compute_value': None, | ||
728 | 'new_order': None | ||
729 | }) | ||
730 | |||
731 | add_log.reset_mock() | ||
732 | print_log.reset_mock() | ||
733 | |||
734 | with self.subTest(update="waiting"): | ||
735 | report_store.log_order(order_mock, 1, update="waiting") | ||
736 | print_log.assert_called_once_with("[Order] Order Mock, tick 1, waiting") | ||
737 | add_log.assert_called_once_with({ | ||
738 | 'type': 'order', | ||
739 | 'tick': 1, | ||
740 | 'update': 'waiting', | ||
741 | 'order': 'order', | ||
742 | 'compute_value': None, | ||
743 | 'new_order': None | ||
744 | }) | ||
745 | |||
746 | add_log.reset_mock() | ||
747 | print_log.reset_mock() | ||
748 | with self.subTest(update="adjusting"): | ||
749 | compute_value = lambda x: (x["bid"] + x["ask"]*2)/3 | ||
750 | report_store.log_order(order_mock, 3, | ||
751 | update="adjusting", new_order=new_order_mock, | ||
752 | compute_value=compute_value) | ||
753 | print_log.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock") | ||
754 | add_log.assert_called_once_with({ | ||
755 | 'type': 'order', | ||
756 | 'tick': 3, | ||
757 | 'update': 'adjusting', | ||
758 | 'order': 'order', | ||
759 | 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3', | ||
760 | 'new_order': 'new_order' | ||
761 | }) | ||
762 | |||
763 | add_log.reset_mock() | ||
764 | print_log.reset_mock() | ||
765 | with self.subTest(update="market_fallback"): | ||
766 | report_store.log_order(order_mock, 7, | ||
767 | update="market_fallback", new_order=new_order_mock) | ||
768 | print_log.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value") | ||
769 | add_log.assert_called_once_with({ | ||
770 | 'type': 'order', | ||
771 | 'tick': 7, | ||
772 | 'update': 'market_fallback', | ||
773 | 'order': 'order', | ||
774 | 'compute_value': None, | ||
775 | 'new_order': 'new_order' | ||
776 | }) | ||
777 | |||
778 | add_log.reset_mock() | ||
779 | print_log.reset_mock() | ||
780 | with self.subTest(update="market_adjusting"): | ||
781 | report_store.log_order(order_mock, 17, | ||
782 | update="market_adjust", new_order=new_order_mock) | ||
783 | print_log.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock") | ||
784 | add_log.assert_called_once_with({ | ||
785 | 'type': 'order', | ||
786 | 'tick': 17, | ||
787 | 'update': 'market_adjust', | ||
788 | 'order': 'order', | ||
789 | 'compute_value': None, | ||
790 | 'new_order': 'new_order' | ||
791 | }) | ||
792 | |||
793 | @mock.patch.object(market.ReportStore, "print_log") | ||
794 | @mock.patch.object(market.ReportStore, "add_log") | ||
795 | def test_log_move_balances(self, add_log, print_log): | ||
796 | report_store = market.ReportStore(self.m) | ||
797 | needed = { | ||
798 | "BTC": portfolio.Amount("BTC", 10), | ||
799 | "USDT": 1 | ||
800 | } | ||
801 | moving = { | ||
802 | "BTC": portfolio.Amount("BTC", 3), | ||
803 | "USDT": -2 | ||
804 | } | ||
805 | report_store.log_move_balances(needed, moving) | ||
806 | print_log.assert_not_called() | ||
807 | add_log.assert_called_once_with({ | ||
808 | 'type': 'move_balances', | ||
809 | 'debug': False, | ||
810 | 'needed': { | ||
811 | 'BTC': D('10'), | ||
812 | 'USDT': 1 | ||
813 | }, | ||
814 | 'moving': { | ||
815 | 'BTC': D('3'), | ||
816 | 'USDT': -2 | ||
817 | } | ||
818 | }) | ||
819 | |||
820 | @mock.patch.object(market.ReportStore, "print_log") | ||
821 | @mock.patch.object(market.ReportStore, "add_log") | ||
822 | def test_log_http_request(self, add_log, print_log): | ||
823 | report_store = market.ReportStore(self.m) | ||
824 | response = mock.Mock() | ||
825 | response.status_code = 200 | ||
826 | response.text = "Hey" | ||
827 | |||
828 | report_store.log_http_request("method", "url", "body", | ||
829 | "headers", response) | ||
830 | print_log.assert_not_called() | ||
831 | add_log.assert_called_once_with({ | ||
832 | 'type': 'http_request', | ||
833 | 'method': 'method', | ||
834 | 'url': 'url', | ||
835 | 'body': 'body', | ||
836 | 'headers': 'headers', | ||
837 | 'status': 200, | ||
838 | 'response': 'Hey' | ||
839 | }) | ||
840 | |||
841 | add_log.reset_mock() | ||
842 | report_store.log_http_request("method", "url", "body", | ||
843 | "headers", ValueError("Foo")) | ||
844 | add_log.assert_called_once_with({ | ||
845 | 'type': 'http_request', | ||
846 | 'method': 'method', | ||
847 | 'url': 'url', | ||
848 | 'body': 'body', | ||
849 | 'headers': 'headers', | ||
850 | 'status': -1, | ||
851 | 'response': None, | ||
852 | 'error': 'ValueError', | ||
853 | 'error_message': 'Foo', | ||
854 | }) | ||
855 | |||
856 | @mock.patch.object(market.ReportStore, "add_log") | ||
857 | def test_log_market(self, add_log): | ||
858 | report_store = market.ReportStore(self.m) | ||
859 | |||
860 | report_store.log_market(self.market_args(debug=True, quiet=False), 4, 1) | ||
861 | add_log.assert_called_once_with({ | ||
862 | "type": "market", | ||
863 | "commit": "$Format:%H$", | ||
864 | "args": { "report_path": None, "debug": True, "quiet": False }, | ||
865 | "user_id": 4, | ||
866 | "market_id": 1, | ||
867 | }) | ||
868 | |||
869 | @mock.patch.object(market.ReportStore, "print_log") | ||
870 | @mock.patch.object(market.ReportStore, "add_log") | ||
871 | def test_log_error(self, add_log, print_log): | ||
872 | report_store = market.ReportStore(self.m) | ||
873 | with self.subTest(message=None, exception=None): | ||
874 | report_store.log_error("action") | ||
875 | print_log.assert_called_once_with("[Error] action") | ||
876 | add_log.assert_called_once_with({ | ||
877 | 'type': 'error', | ||
878 | 'action': 'action', | ||
879 | 'exception_class': None, | ||
880 | 'exception_message': None, | ||
881 | 'message': None | ||
882 | }) | ||
883 | |||
884 | print_log.reset_mock() | ||
885 | add_log.reset_mock() | ||
886 | with self.subTest(message="Hey", exception=None): | ||
887 | report_store.log_error("action", message="Hey") | ||
888 | print_log.assert_has_calls([ | ||
889 | mock.call("[Error] action"), | ||
890 | mock.call("\tHey") | ||
891 | ]) | ||
892 | add_log.assert_called_once_with({ | ||
893 | 'type': 'error', | ||
894 | 'action': 'action', | ||
895 | 'exception_class': None, | ||
896 | 'exception_message': None, | ||
897 | 'message': "Hey" | ||
898 | }) | ||
899 | |||
900 | print_log.reset_mock() | ||
901 | add_log.reset_mock() | ||
902 | with self.subTest(message=None, exception=Exception("bouh")): | ||
903 | report_store.log_error("action", exception=Exception("bouh")) | ||
904 | print_log.assert_has_calls([ | ||
905 | mock.call("[Error] action"), | ||
906 | mock.call("\tException: bouh") | ||
907 | ]) | ||
908 | add_log.assert_called_once_with({ | ||
909 | 'type': 'error', | ||
910 | 'action': 'action', | ||
911 | 'exception_class': "Exception", | ||
912 | 'exception_message': "bouh", | ||
913 | 'message': None | ||
914 | }) | ||
915 | |||
916 | print_log.reset_mock() | ||
917 | add_log.reset_mock() | ||
918 | with self.subTest(message="Hey", exception=Exception("bouh")): | ||
919 | report_store.log_error("action", message="Hey", exception=Exception("bouh")) | ||
920 | print_log.assert_has_calls([ | ||
921 | mock.call("[Error] action"), | ||
922 | mock.call("\tException: bouh"), | ||
923 | mock.call("\tHey") | ||
924 | ]) | ||
925 | add_log.assert_called_once_with({ | ||
926 | 'type': 'error', | ||
927 | 'action': 'action', | ||
928 | 'exception_class': "Exception", | ||
929 | 'exception_message': "bouh", | ||
930 | 'message': "Hey" | ||
931 | }) | ||
932 | |||
933 | @mock.patch.object(market.ReportStore, "print_log") | ||
934 | @mock.patch.object(market.ReportStore, "add_log") | ||
935 | def test_log_debug_action(self, add_log, print_log): | ||
936 | report_store = market.ReportStore(self.m) | ||
937 | report_store.log_debug_action("Hey") | ||
938 | |||
939 | print_log.assert_called_once_with("[Debug] Hey") | ||
940 | add_log.assert_called_once_with({ | ||
941 | 'type': 'debug_action', | ||
942 | 'action': 'Hey' | ||
943 | }) | ||
944 | |||
945 | @unittest.skipUnless("unit" in limits, "Unit skipped") | ||
946 | class PortfolioTest(WebMockTestCase): | ||
947 | def setUp(self): | ||
948 | super().setUp() | ||
949 | |||
950 | with open("test_samples/test_portfolio.json") as example: | ||
951 | self.json_response = example.read() | ||
952 | |||
953 | self.wm.get(market.Portfolio.URL, text=self.json_response) | ||
954 | |||
955 | @mock.patch.object(market.Portfolio, "parse_cryptoportfolio") | ||
956 | def test_get_cryptoportfolio(self, parse_cryptoportfolio): | ||
957 | with self.subTest(parallel=False): | ||
958 | self.wm.get(market.Portfolio.URL, [ | ||
959 | {"text":'{ "foo": "bar" }', "status_code": 200}, | ||
960 | {"text": "System Error", "status_code": 500}, | ||
961 | {"exc": requests.exceptions.ConnectTimeout}, | ||
962 | ]) | ||
963 | market.Portfolio.get_cryptoportfolio() | ||
964 | self.assertIn("foo", market.Portfolio.data.get()) | ||
965 | self.assertEqual("bar", market.Portfolio.data.get()["foo"]) | ||
966 | self.assertTrue(self.wm.called) | ||
967 | self.assertEqual(1, self.wm.call_count) | ||
968 | market.Portfolio.report.log_error.assert_not_called() | ||
969 | market.Portfolio.report.log_http_request.assert_called_once() | ||
970 | parse_cryptoportfolio.assert_called_once_with() | ||
971 | market.Portfolio.report.log_http_request.reset_mock() | ||
972 | parse_cryptoportfolio.reset_mock() | ||
973 | market.Portfolio.data = store.LockedVar(None) | ||
974 | |||
975 | market.Portfolio.get_cryptoportfolio() | ||
976 | self.assertIsNone(market.Portfolio.data.get()) | ||
977 | self.assertEqual(2, self.wm.call_count) | ||
978 | parse_cryptoportfolio.assert_not_called() | ||
979 | market.Portfolio.report.log_error.assert_not_called() | ||
980 | market.Portfolio.report.log_http_request.assert_called_once() | ||
981 | market.Portfolio.report.log_http_request.reset_mock() | ||
982 | parse_cryptoportfolio.reset_mock() | ||
983 | |||
984 | market.Portfolio.data = store.LockedVar("Foo") | ||
985 | market.Portfolio.get_cryptoportfolio() | ||
986 | self.assertEqual(2, self.wm.call_count) | ||
987 | parse_cryptoportfolio.assert_not_called() | ||
988 | |||
989 | market.Portfolio.get_cryptoportfolio(refetch=True) | ||
990 | self.assertEqual("Foo", market.Portfolio.data.get()) | ||
991 | self.assertEqual(3, self.wm.call_count) | ||
992 | market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio", | ||
993 | exception=mock.ANY) | ||
994 | market.Portfolio.report.log_http_request.assert_not_called() | ||
995 | with self.subTest(parallel=True): | ||
996 | with mock.patch.object(market.Portfolio, "is_worker_thread") as is_worker,\ | ||
997 | mock.patch.object(market.Portfolio, "notify_and_wait") as notify: | ||
998 | with self.subTest(worker=True): | ||
999 | market.Portfolio.data = store.LockedVar(None) | ||
1000 | market.Portfolio.worker = mock.Mock() | ||
1001 | is_worker.return_value = True | ||
1002 | self.wm.get(market.Portfolio.URL, [ | ||
1003 | {"text":'{ "foo": "bar" }', "status_code": 200}, | ||
1004 | ]) | ||
1005 | market.Portfolio.get_cryptoportfolio() | ||
1006 | self.assertIn("foo", market.Portfolio.data.get()) | ||
1007 | parse_cryptoportfolio.reset_mock() | ||
1008 | with self.subTest(worker=False): | ||
1009 | market.Portfolio.data = store.LockedVar(None) | ||
1010 | market.Portfolio.worker = mock.Mock() | ||
1011 | is_worker.return_value = False | ||
1012 | market.Portfolio.get_cryptoportfolio() | ||
1013 | notify.assert_called_once_with() | ||
1014 | parse_cryptoportfolio.assert_not_called() | ||
1015 | |||
1016 | def test_parse_cryptoportfolio(self): | ||
1017 | with self.subTest(description="Normal case"): | ||
1018 | market.Portfolio.data = store.LockedVar(store.json.loads( | ||
1019 | self.json_response, parse_int=D, parse_float=D)) | ||
1020 | market.Portfolio.parse_cryptoportfolio() | ||
1021 | |||
1022 | self.assertListEqual( | ||
1023 | ["medium", "high"], | ||
1024 | list(market.Portfolio.liquidities.get().keys())) | ||
1025 | |||
1026 | liquidities = market.Portfolio.liquidities.get() | ||
1027 | self.assertEqual(10, len(liquidities["medium"].keys())) | ||
1028 | self.assertEqual(10, len(liquidities["high"].keys())) | ||
1029 | |||
1030 | expected = { | ||
1031 | 'BTC': (D("0.2857"), "long"), | ||
1032 | 'DGB': (D("0.1015"), "long"), | ||
1033 | 'DOGE': (D("0.1805"), "long"), | ||
1034 | 'SC': (D("0.0623"), "long"), | ||
1035 | 'ZEC': (D("0.3701"), "long"), | ||
1036 | } | ||
1037 | date = portfolio.datetime(2018, 1, 8) | ||
1038 | self.assertDictEqual(expected, liquidities["high"][date]) | ||
1039 | |||
1040 | expected = { | ||
1041 | 'BTC': (D("1.1102e-16"), "long"), | ||
1042 | 'ETC': (D("0.1"), "long"), | ||
1043 | 'FCT': (D("0.1"), "long"), | ||
1044 | 'GAS': (D("0.1"), "long"), | ||
1045 | 'NAV': (D("0.1"), "long"), | ||
1046 | 'OMG': (D("0.1"), "long"), | ||
1047 | 'OMNI': (D("0.1"), "long"), | ||
1048 | 'PPC': (D("0.1"), "long"), | ||
1049 | 'RIC': (D("0.1"), "long"), | ||
1050 | 'VIA': (D("0.1"), "long"), | ||
1051 | 'XCP': (D("0.1"), "long"), | ||
1052 | } | ||
1053 | self.assertDictEqual(expected, liquidities["medium"][date]) | ||
1054 | self.assertEqual(portfolio.datetime(2018, 1, 15), market.Portfolio.last_date.get()) | ||
1055 | |||
1056 | with self.subTest(description="Missing weight"): | ||
1057 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | ||
1058 | del(data["portfolio_2"]["weights"]) | ||
1059 | market.Portfolio.data = store.LockedVar(data) | ||
1060 | |||
1061 | market.Portfolio.parse_cryptoportfolio() | ||
1062 | self.assertListEqual( | ||
1063 | ["medium", "high"], | ||
1064 | list(market.Portfolio.liquidities.get().keys())) | ||
1065 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | ||
1066 | |||
1067 | with self.subTest(description="All missing weights"): | ||
1068 | data = store.json.loads(self.json_response, parse_int=D, parse_float=D) | ||
1069 | del(data["portfolio_1"]["weights"]) | ||
1070 | del(data["portfolio_2"]["weights"]) | ||
1071 | market.Portfolio.data = store.LockedVar(data) | ||
1072 | |||
1073 | market.Portfolio.parse_cryptoportfolio() | ||
1074 | self.assertEqual({}, market.Portfolio.liquidities.get("medium")) | ||
1075 | self.assertEqual({}, market.Portfolio.liquidities.get("high")) | ||
1076 | self.assertEqual(datetime.datetime(1,1,1), market.Portfolio.last_date.get()) | ||
1077 | |||
1078 | |||
1079 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | ||
1080 | def test_repartition(self, get_cryptoportfolio): | ||
1081 | market.Portfolio.liquidities = store.LockedVar({ | ||
1082 | "medium": { | ||
1083 | "2018-03-01": "medium_2018-03-01", | ||
1084 | "2018-03-08": "medium_2018-03-08", | ||
1085 | }, | ||
1086 | "high": { | ||
1087 | "2018-03-01": "high_2018-03-01", | ||
1088 | "2018-03-08": "high_2018-03-08", | ||
1089 | } | ||
1090 | }) | ||
1091 | market.Portfolio.last_date = store.LockedVar("2018-03-08") | ||
1092 | |||
1093 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition()) | ||
1094 | get_cryptoportfolio.assert_called_once_with() | ||
1095 | self.assertEqual("medium_2018-03-08", market.Portfolio.repartition(liquidity="medium")) | ||
1096 | self.assertEqual("high_2018-03-08", market.Portfolio.repartition(liquidity="high")) | ||
1097 | |||
1098 | @mock.patch.object(market.time, "sleep") | ||
1099 | @mock.patch.object(market.Portfolio, "get_cryptoportfolio") | ||
1100 | def test_wait_for_recent(self, get_cryptoportfolio, sleep): | ||
1101 | self.call_count = 0 | ||
1102 | def _get(refetch=False): | ||
1103 | if self.call_count != 0: | ||
1104 | self.assertTrue(refetch) | ||
1105 | else: | ||
1106 | self.assertFalse(refetch) | ||
1107 | self.call_count += 1 | ||
1108 | market.Portfolio.last_date = store.LockedVar(store.datetime.now()\ | ||
1109 | - store.timedelta(10)\ | ||
1110 | + store.timedelta(self.call_count)) | ||
1111 | get_cryptoportfolio.side_effect = _get | ||
1112 | |||
1113 | market.Portfolio.wait_for_recent() | ||
1114 | sleep.assert_called_with(30) | ||
1115 | self.assertEqual(6, sleep.call_count) | ||
1116 | self.assertEqual(7, get_cryptoportfolio.call_count) | ||
1117 | market.Portfolio.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio") | ||
1118 | |||
1119 | sleep.reset_mock() | ||
1120 | get_cryptoportfolio.reset_mock() | ||
1121 | market.Portfolio.last_date = store.LockedVar(None) | ||
1122 | self.call_count = 0 | ||
1123 | market.Portfolio.wait_for_recent(delta=15) | ||
1124 | sleep.assert_not_called() | ||
1125 | self.assertEqual(1, get_cryptoportfolio.call_count) | ||
1126 | |||
1127 | sleep.reset_mock() | ||
1128 | get_cryptoportfolio.reset_mock() | ||
1129 | market.Portfolio.last_date = store.LockedVar(None) | ||
1130 | self.call_count = 0 | ||
1131 | market.Portfolio.wait_for_recent(delta=1) | ||
1132 | sleep.assert_called_with(30) | ||
1133 | self.assertEqual(9, sleep.call_count) | ||
1134 | self.assertEqual(10, get_cryptoportfolio.call_count) | ||
1135 | |||
1136 | def test_is_worker_thread(self): | ||
1137 | with self.subTest(worker=None): | ||
1138 | self.assertFalse(store.Portfolio.is_worker_thread()) | ||
1139 | |||
1140 | with self.subTest(worker="not self"),\ | ||
1141 | mock.patch("threading.current_thread") as current_thread: | ||
1142 | current = mock.Mock() | ||
1143 | current_thread.return_value = current | ||
1144 | store.Portfolio.worker = mock.Mock() | ||
1145 | self.assertFalse(store.Portfolio.is_worker_thread()) | ||
1146 | |||
1147 | with self.subTest(worker="self"),\ | ||
1148 | mock.patch("threading.current_thread") as current_thread: | ||
1149 | current = mock.Mock() | ||
1150 | current_thread.return_value = current | ||
1151 | store.Portfolio.worker = current | ||
1152 | self.assertTrue(store.Portfolio.is_worker_thread()) | ||
1153 | |||
1154 | def test_start_worker(self): | ||
1155 | with mock.patch.object(store.Portfolio, "wait_for_notification") as notification: | ||
1156 | store.Portfolio.start_worker() | ||
1157 | notification.assert_called_once_with(poll=30) | ||
1158 | |||
1159 | self.assertEqual("lock", store.Portfolio.last_date.lock.__class__.__name__) | ||
1160 | self.assertEqual("lock", store.Portfolio.liquidities.lock.__class__.__name__) | ||
1161 | store.Portfolio.report.start_lock.assert_called_once_with() | ||
1162 | |||
1163 | self.assertIsNotNone(store.Portfolio.worker) | ||
1164 | self.assertIsNotNone(store.Portfolio.worker_notify) | ||
1165 | self.assertIsNotNone(store.Portfolio.callback) | ||
1166 | self.assertTrue(store.Portfolio.worker_started) | ||
1167 | |||
1168 | self.assertFalse(store.Portfolio.worker.is_alive()) | ||
1169 | |||
1170 | def test_wait_for_notification(self): | ||
1171 | with self.assertRaises(RuntimeError): | ||
1172 | store.Portfolio.wait_for_notification() | ||
1173 | |||
1174 | with mock.patch.object(store.Portfolio, "get_cryptoportfolio") as get,\ | ||
1175 | mock.patch.object(store.Portfolio, "report") as report,\ | ||
1176 | mock.patch.object(store.time, "sleep") as sleep: | ||
1177 | store.Portfolio.start_worker(poll=3) | ||
1178 | |||
1179 | store.Portfolio.worker_notify.set() | ||
1180 | |||
1181 | store.Portfolio.callback.wait() | ||
1182 | |||
1183 | report.print_log.assert_called_once_with("Fetching cryptoportfolio") | ||
1184 | get.assert_called_once_with(refetch=True) | ||
1185 | sleep.assert_called_once_with(3) | ||
1186 | self.assertFalse(store.Portfolio.worker_notify.is_set()) | ||
1187 | self.assertTrue(store.Portfolio.worker.is_alive()) | ||
1188 | |||
1189 | store.Portfolio.callback.clear() | ||
1190 | store.Portfolio.worker_started = False | ||
1191 | store.Portfolio.worker_notify.set() | ||
1192 | store.Portfolio.callback.wait() | ||
1193 | self.assertFalse(store.Portfolio.worker.is_alive()) | ||
1194 | |||
1195 | def test_notify_and_wait(self): | ||
1196 | with mock.patch.object(store.Portfolio, "callback") as callback,\ | ||
1197 | mock.patch.object(store.Portfolio, "worker_notify") as worker_notify: | ||
1198 | store.Portfolio.notify_and_wait() | ||
1199 | callback.clear.assert_called_once_with() | ||
1200 | worker_notify.set.assert_called_once_with() | ||
1201 | callback.wait.assert_called_once_with() | ||
1202 | |||
1203 | |||