diff options
author | Ismaël Bouya <ismael.bouya@normalesup.org> | 2018-04-08 00:53:34 +0200 |
---|---|---|
committer | Ismaël Bouya <ismael.bouya@normalesup.org> | 2018-04-08 00:53:34 +0200 |
commit | c8df27385e02b22d36b240fe29532e97dbba1f43 (patch) | |
tree | 44d7f9089468f35277bb8d0257da0f3a3bb88448 /test.py | |
parent | e6015816224f8f405e9b1c9557f22e73b21246e8 (diff) | |
parent | 1d72880c097ea8259ce9cc63cfe55e6cc7516bd2 (diff) | |
download | Trader-c8df27385e02b22d36b240fe29532e97dbba1f43.tar.gz Trader-c8df27385e02b22d36b240fe29532e97dbba1f43.tar.zst Trader-c8df27385e02b22d36b240fe29532e97dbba1f43.zip |
Merge branch 'test_cleanup' into dev
Diffstat (limited to 'test.py')
-rw-r--r-- | test.py | 5223 |
1 files changed, 5 insertions, 5218 deletions
@@ -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() |