]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - test.py
Move request wrapper to ccxt
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / test.py
CommitLineData
1aa7d4fa 1import sys
dd359bc0
IB
2import portfolio
3import unittest
f86ee140 4import datetime
5ab23e1c 5from decimal import Decimal as D
dd359bc0 6from unittest import mock
80cdd672
IB
7import requests
8import requests_mock
c51687d2 9from io import StringIO
dc1ca9a3 10import threading
ada1b5f1 11import portfolio, market, main, store
dd359bc0 12
1aa7d4fa
IB
13limits = ["acceptance", "unit"]
14for test_type in limits:
15 if "--no{}".format(test_type) in sys.argv:
16 sys.argv.remove("--no{}".format(test_type))
17 limits.remove(test_type)
18 if "--only{}".format(test_type) in sys.argv:
19 sys.argv.remove("--only{}".format(test_type))
20 limits = [test_type]
21 break
22
80cdd672
IB
23class WebMockTestCase(unittest.TestCase):
24 import time
25
07fa7a4b
IB
26 def market_args(self, debug=False, quiet=False):
27 return type('Args', (object,), { "debug": debug, "quiet": quiet })()
28
80cdd672
IB
29 def setUp(self):
30 super(WebMockTestCase, self).setUp()
31 self.wm = requests_mock.Mocker()
32 self.wm.start()
33
f86ee140
IB
34 # market
35 self.m = mock.Mock(name="Market", spec=market.Market)
36 self.m.debug = False
37
80cdd672 38 self.patchers = [
ada1b5f1 39 mock.patch.multiple(market.Portfolio,
dc1ca9a3
IB
40 data=store.LockedVar(None),
41 liquidities=store.LockedVar({}),
42 last_date=store.LockedVar(None),
43 report=mock.Mock(),
44 worker=None,
45 worker_notify=None,
46 worker_started=False,
47 callback=None),
80cdd672 48 mock.patch.multiple(portfolio.Computation,
6ca5a1ec 49 computations=portfolio.Computation.computations),
80cdd672
IB
50 ]
51 for patcher in self.patchers:
52 patcher.start()
53
80cdd672
IB
54 def tearDown(self):
55 for patcher in self.patchers:
56 patcher.stop()
57 self.wm.stop()
58 super(WebMockTestCase, self).tearDown()
59
3f415207
IB
60@unittest.skipUnless("unit" in limits, "Unit skipped")
61class poloniexETest(unittest.TestCase):
62 def setUp(self):
63 super(poloniexETest, self).setUp()
64 self.wm = requests_mock.Mocker()
65 self.wm.start()
66
67 self.s = market.ccxt.poloniexE()
68
69 def tearDown(self):
70 self.wm.stop()
71 super(poloniexETest, self).tearDown()
72
445b4a77
IB
73 def test__init(self):
74 with mock.patch("market.ccxt.poloniexE.session") as session:
75 session.request.return_value = "response"
76 ccxt = market.ccxt.poloniexE()
77 ccxt._market = mock.Mock
78 ccxt._market.report = mock.Mock()
79
80 ccxt.session.request("GET", "URL", data="data",
81 headers="headers")
82 ccxt._market.report.log_http_request.assert_called_with('GET', 'URL', 'data',
83 'headers', 'response')
84
3f415207
IB
85 def test_nanoseconds(self):
86 with mock.patch.object(market.ccxt.time, "time") as time:
87 time.return_value = 123456.7890123456
88 self.assertEqual(123456789012345, self.s.nanoseconds())
89
90 def test_nonce(self):
91 with mock.patch.object(market.ccxt.time, "time") as time:
92 time.return_value = 123456.7890123456
93 self.assertEqual(123456789012345, self.s.nonce())
94
c7c1e0b2
IB
95 def test_request(self):
96 with mock.patch.object(market.ccxt.poloniex, "request") as request,\
97 mock.patch("market.ccxt.retry_call") as retry_call:
98 with self.subTest(wrapped=True):
99 with self.subTest(desc="public"):
100 self.s.request("foo")
101 retry_call.assert_called_with(request,
102 delay=1, tries=10, fargs=["foo"],
103 fkwargs={'api': 'public', 'method': 'GET', 'params': {}, 'headers': None, 'body': None},
104 exceptions=(market.ccxt.RequestTimeout,))
105 request.assert_not_called()
106
107 with self.subTest(desc="private GET"):
108 self.s.request("foo", api="private")
109 retry_call.assert_called_with(request,
110 delay=1, tries=10, fargs=["foo"],
111 fkwargs={'api': 'private', 'method': 'GET', 'params': {}, 'headers': None, 'body': None},
112 exceptions=(market.ccxt.RequestTimeout,))
113 request.assert_not_called()
114
115 with self.subTest(desc="private POST regexp"):
116 self.s.request("returnFoo", api="private", method="POST")
117 retry_call.assert_called_with(request,
118 delay=1, tries=10, fargs=["returnFoo"],
119 fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None},
120 exceptions=(market.ccxt.RequestTimeout,))
121 request.assert_not_called()
122
123 with self.subTest(desc="private POST non-regexp"):
124 self.s.request("getMarginPosition", api="private", method="POST")
125 retry_call.assert_called_with(request,
126 delay=1, tries=10, fargs=["getMarginPosition"],
127 fkwargs={'api': 'private', 'method': 'POST', 'params': {}, 'headers': None, 'body': None},
128 exceptions=(market.ccxt.RequestTimeout,))
129 request.assert_not_called()
130 retry_call.reset_mock()
131 request.reset_mock()
132 with self.subTest(wrapped=False):
133 with self.subTest(desc="private POST non-matching regexp"):
134 self.s.request("marginBuy", api="private", method="POST")
135 request.assert_called_with("marginBuy",
136 api="private", method="POST", params={},
137 headers=None, body=None)
138 retry_call.assert_not_called()
139
140 with self.subTest(desc="private POST non-matching non-regexp"):
141 self.s.request("closeMarginPositionOther", api="private", method="POST")
142 request.assert_called_with("closeMarginPositionOther",
143 api="private", method="POST", params={},
144 headers=None, body=None)
145 retry_call.assert_not_called()
146
3f415207
IB
147 def test_order_precision(self):
148 self.assertEqual(8, self.s.order_precision("FOO"))
149
150 def test_transfer_balance(self):
151 with self.subTest(success=True),\
152 mock.patch.object(self.s, "privatePostTransferBalance") as t:
153 t.return_value = { "success": 1 }
154 result = self.s.transfer_balance("FOO", 12, "exchange", "margin")
155 t.assert_called_once_with({
156 "currency": "FOO",
157 "amount": 12,
158 "fromAccount": "exchange",
159 "toAccount": "margin",
160 "confirmed": 1
161 })
162 self.assertTrue(result)
163
164 with self.subTest(success=False),\
165 mock.patch.object(self.s, "privatePostTransferBalance") as t:
166 t.return_value = { "success": 0 }
167 self.assertFalse(self.s.transfer_balance("FOO", 12, "exchange", "margin"))
168
169 def test_close_margin_position(self):
170 with mock.patch.object(self.s, "privatePostCloseMarginPosition") as c:
171 self.s.close_margin_position("FOO", "BAR")
172 c.assert_called_with({"currencyPair": "BAR_FOO"})
173
174 def test_tradable_balances(self):
175 with mock.patch.object(self.s, "privatePostReturnTradableBalances") as r:
176 r.return_value = {
177 "FOO": { "exchange": "12.1234", "margin": "0.0123" },
178 "BAR": { "exchange": "1", "margin": "0" },
179 }
180 balances = self.s.tradable_balances()
181 self.assertEqual(["FOO", "BAR"], list(balances.keys()))
182 self.assertEqual(["exchange", "margin"], list(balances["FOO"].keys()))
183 self.assertEqual(D("12.1234"), balances["FOO"]["exchange"])
184 self.assertEqual(["exchange", "margin"], list(balances["BAR"].keys()))
185
186 def test_margin_summary(self):
187 with mock.patch.object(self.s, "privatePostReturnMarginAccountSummary") as r:
188 r.return_value = {
189 "currentMargin": "1.49680968",
190 "lendingFees": "0.0000001",
191 "pl": "0.00008254",
192 "totalBorrowedValue": "0.00673602",
193 "totalValue": "0.01000000",
194 "netValue": "0.01008254",
195 }
196 expected = {
197 'current_margin': D('1.49680968'),
198 'gains': D('0.00008254'),
199 'lending_fees': D('0.0000001'),
200 'total': D('0.01000000'),
201 'total_borrowed': D('0.00673602')
202 }
203 self.assertEqual(expected, self.s.margin_summary())
204
d00dc02b
IB
205 def test_create_order(self):
206 with mock.patch.object(self.s, "create_exchange_order") as exchange,\
207 mock.patch.object(self.s, "create_margin_order") as margin:
208 with self.subTest(account="unspecified"):
209 self.s.create_order("symbol", "type", "side", "amount", price="price", lending_rate="lending_rate", params="params")
210 exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
211 margin.assert_not_called()
212 exchange.reset_mock()
213 margin.reset_mock()
214
215 with self.subTest(account="exchange"):
216 self.s.create_order("symbol", "type", "side", "amount", account="exchange", price="price", lending_rate="lending_rate", params="params")
217 exchange.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
218 margin.assert_not_called()
219 exchange.reset_mock()
220 margin.reset_mock()
221
222 with self.subTest(account="margin"):
223 self.s.create_order("symbol", "type", "side", "amount", account="margin", price="price", lending_rate="lending_rate", params="params")
224 margin.assert_called_once_with("symbol", "type", "side", "amount", lending_rate="lending_rate", price="price", params="params")
225 exchange.assert_not_called()
226 exchange.reset_mock()
227 margin.reset_mock()
228
229 with self.subTest(account="unknown"), self.assertRaises(NotImplementedError):
230 self.s.create_order("symbol", "type", "side", "amount", account="unknown")
231
232 def test_parse_ticker(self):
233 ticker = {
234 "high24hr": "12",
235 "low24hr": "10",
236 "highestBid": "10.5",
237 "lowestAsk": "11.5",
238 "last": "11",
239 "percentChange": "0.1",
240 "quoteVolume": "10",
241 "baseVolume": "20"
242 }
243 market = {
244 "symbol": "BTC/ETC"
245 }
246 with mock.patch.object(self.s, "milliseconds") as ms:
247 ms.return_value = 1520292715123
248 result = self.s.parse_ticker(ticker, market)
249
250 expected = {
251 "symbol": "BTC/ETC",
252 "timestamp": 1520292715123,
253 "datetime": "2018-03-05T23:31:55.123Z",
254 "high": D("12"),
255 "low": D("10"),
256 "bid": D("10.5"),
257 "ask": D("11.5"),
258 "vwap": None,
259 "open": None,
260 "close": None,
261 "first": None,
262 "last": D("11"),
263 "change": D("0.1"),
264 "percentage": None,
265 "average": None,
266 "baseVolume": D("10"),
267 "quoteVolume": D("20"),
268 "info": ticker
269 }
270 self.assertEqual(expected, result)
271
272 def test_fetch_margin_balance(self):
273 with mock.patch.object(self.s, "privatePostGetMarginPosition") as get_margin_position:
274 get_margin_position.return_value = {
275 "BTC_DASH": {
276 "amount": "-0.1",
277 "basePrice": "0.06818560",
278 "lendingFees": "0.00000001",
279 "liquidationPrice": "0.15107132",
280 "pl": "-0.00000371",
281 "total": "0.00681856",
282 "type": "short"
283 },
284 "BTC_ETC": {
285 "amount": "-0.6",
286 "basePrice": "0.1",
287 "lendingFees": "0.00000001",
288 "liquidationPrice": "0.6",
289 "pl": "0.00000371",
290 "total": "0.06",
291 "type": "short"
292 },
293 "BTC_ETH": {
294 "amount": "0",
295 "basePrice": "0",
296 "lendingFees": "0",
297 "liquidationPrice": "-1",
298 "pl": "0",
299 "total": "0",
300 "type": "none"
301 }
302 }
303 balances = self.s.fetch_margin_balance()
304 self.assertEqual(2, len(balances))
305 expected = {
306 "DASH": {
307 "amount": D("-0.1"),
308 "borrowedPrice": D("0.06818560"),
309 "lendingFees": D("1E-8"),
310 "pl": D("-0.00000371"),
311 "liquidationPrice": D("0.15107132"),
312 "type": "short",
313 "total": D("0.00681856"),
314 "baseCurrency": "BTC"
315 },
316 "ETC": {
317 "amount": D("-0.6"),
318 "borrowedPrice": D("0.1"),
319 "lendingFees": D("1E-8"),
320 "pl": D("0.00000371"),
321 "liquidationPrice": D("0.6"),
322 "type": "short",
323 "total": D("0.06"),
324 "baseCurrency": "BTC"
325 }
326 }
327 self.assertEqual(expected, balances)
328
329 def test_sum(self):
330 self.assertEqual(D("1.1"), self.s.sum(D("1"), D("0.1")))
331
332 def test_fetch_balance(self):
333 with mock.patch.object(self.s, "load_markets") as load_markets,\
334 mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balances,\
335 mock.patch.object(self.s, "common_currency_code") as ccc:
336 ccc.side_effect = ["ETH", "BTC", "DASH"]
337 balances.return_value = {
338 "ETH": {
339 "available": "10",
340 "onOrders": "1",
341 },
342 "BTC": {
343 "available": "1",
344 "onOrders": "0",
345 },
346 "DASH": {
347 "available": "0",
348 "onOrders": "3"
349 }
350 }
351
352 expected = {
353 "info": {
354 "ETH": {"available": "10", "onOrders": "1"},
355 "BTC": {"available": "1", "onOrders": "0"},
356 "DASH": {"available": "0", "onOrders": "3"}
357 },
358 "ETH": {"free": D("10"), "used": D("1"), "total": D("11")},
359 "BTC": {"free": D("1"), "used": D("0"), "total": D("1")},
360 "DASH": {"free": D("0"), "used": D("3"), "total": D("3")},
361 "free": {"ETH": D("10"), "BTC": D("1"), "DASH": D("0")},
362 "used": {"ETH": D("1"), "BTC": D("0"), "DASH": D("3")},
363 "total": {"ETH": D("11"), "BTC": D("1"), "DASH": D("3")}
364 }
365 result = self.s.fetch_balance()
366 load_markets.assert_called_once()
367 self.assertEqual(expected, result)
368
369 def test_fetch_balance_per_type(self):
370 with mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balances:
371 balances.return_value = {
372 "exchange": {
373 "BLK": "159.83673869",
374 "BTC": "0.00005959",
375 "USDT": "0.00002625",
376 "XMR": "0.18719303"
377 },
378 "margin": {
379 "BTC": "0.03019227"
380 }
381 }
382 expected = {
383 "info": {
384 "exchange": {
385 "BLK": "159.83673869",
386 "BTC": "0.00005959",
387 "USDT": "0.00002625",
388 "XMR": "0.18719303"
389 },
390 "margin": {
391 "BTC": "0.03019227"
392 }
393 },
394 "exchange": {
395 "BLK": D("159.83673869"),
396 "BTC": D("0.00005959"),
397 "USDT": D("0.00002625"),
398 "XMR": D("0.18719303")
399 },
400 "margin": {"BTC": D("0.03019227")},
401 "BLK": {"exchange": D("159.83673869")},
402 "BTC": {"exchange": D("0.00005959"), "margin": D("0.03019227")},
403 "USDT": {"exchange": D("0.00002625")},
404 "XMR": {"exchange": D("0.18719303")}
405 }
406 result = self.s.fetch_balance_per_type()
407 self.assertEqual(expected, result)
408
409 def test_fetch_all_balances(self):
410 import json
411 with mock.patch.object(self.s, "load_markets") as load_markets,\
412 mock.patch.object(self.s, "privatePostGetMarginPosition") as margin_balance,\
413 mock.patch.object(self.s, "privatePostReturnCompleteBalances") as balance,\
414 mock.patch.object(self.s, "privatePostReturnAvailableAccountBalances") as balance_per_type:
415
416 with open("test_samples/poloniexETest.test_fetch_all_balances.1.json") as f:
417 balance.return_value = json.load(f)
418 with open("test_samples/poloniexETest.test_fetch_all_balances.2.json") as f:
419 margin_balance.return_value = json.load(f)
420 with open("test_samples/poloniexETest.test_fetch_all_balances.3.json") as f:
421 balance_per_type.return_value = json.load(f)
422
423 result = self.s.fetch_all_balances()
424 expected_doge = {
425 "total": D("-12779.79821852"),
426 "exchange_used": D("0E-8"),
427 "exchange_total": D("0E-8"),
428 "exchange_free": D("0E-8"),
429 "margin_available": 0,
430 "margin_in_position": 0,
431 "margin_borrowed": D("12779.79821852"),
432 "margin_total": D("-12779.79821852"),
433 "margin_pending_gain": 0,
434 "margin_lending_fees": D("-9E-8"),
435 "margin_pending_base_gain": D("0.00024059"),
436 "margin_position_type": "short",
437 "margin_liquidation_price": D("0.00000246"),
438 "margin_borrowed_base_price": D("0.00599149"),
439 "margin_borrowed_base_currency": "BTC"
440 }
441 expected_btc = {"total": D("0.05432165"),
442 "exchange_used": D("0E-8"),
443 "exchange_total": D("0.00005959"),
444 "exchange_free": D("0.00005959"),
445 "margin_available": D("0.03019227"),
446 "margin_in_position": D("0.02406979"),
447 "margin_borrowed": 0,
448 "margin_total": D("0.05426206"),
449 "margin_pending_gain": D("0.00093955"),
450 "margin_lending_fees": 0,
451 "margin_pending_base_gain": 0,
452 "margin_position_type": None,
453 "margin_liquidation_price": 0,
454 "margin_borrowed_base_price": 0,
455 "margin_borrowed_base_currency": None
456 }
457 expected_xmr = {"total": D("0.18719303"),
458 "exchange_used": D("0E-8"),
459 "exchange_total": D("0.18719303"),
460 "exchange_free": D("0.18719303"),
461 "margin_available": 0,
462 "margin_in_position": 0,
463 "margin_borrowed": 0,
464 "margin_total": 0,
465 "margin_pending_gain": 0,
466 "margin_lending_fees": 0,
467 "margin_pending_base_gain": 0,
468 "margin_position_type": None,
469 "margin_liquidation_price": 0,
470 "margin_borrowed_base_price": 0,
471 "margin_borrowed_base_currency": None
472 }
473 self.assertEqual(expected_xmr, result["XMR"])
474 self.assertEqual(expected_doge, result["DOGE"])
475 self.assertEqual(expected_btc, result["BTC"])
476
477 def test_create_margin_order(self):
478 with self.assertRaises(market.ExchangeError):
479 self.s.create_margin_order("FOO", "market", "buy", "10")
480
481 with mock.patch.object(self.s, "load_markets") as load_markets,\
482 mock.patch.object(self.s, "privatePostMarginBuy") as margin_buy,\
483 mock.patch.object(self.s, "privatePostMarginSell") as margin_sell,\
484 mock.patch.object(self.s, "market") as market_mock,\
485 mock.patch.object(self.s, "price_to_precision") as ptp,\
486 mock.patch.object(self.s, "amount_to_precision") as atp:
487
488 margin_buy.return_value = {
489 "orderNumber": 123
490 }
491 margin_sell.return_value = {
492 "orderNumber": 456
493 }
494 market_mock.return_value = { "id": "BTC_ETC", "symbol": "BTC_ETC" }
495 ptp.return_value = D("0.1")
496 atp.return_value = D("12")
497
498 order = self.s.create_margin_order("BTC_ETC", "margin", "buy", "12", price="0.1")
499 self.assertEqual(123, order["id"])
500 margin_buy.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")})
501 margin_sell.assert_not_called()
502 margin_buy.reset_mock()
503 margin_sell.reset_mock()
504
505 order = self.s.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate="0.01", price="0.1")
506 self.assertEqual(456, order["id"])
507 margin_sell.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"})
508 margin_buy.assert_not_called()
509
510 def test_create_exchange_order(self):
511 with mock.patch.object(market.ccxt.poloniex, "create_order") as create_order:
512 self.s.create_order("symbol", "type", "side", "amount", price="price", params="params")
513
514 create_order.assert_called_once_with("symbol", "type", "side", "amount", price="price", params="params")
515
dc1ca9a3
IB
516@unittest.skipUnless("unit" in limits, "Unit skipped")
517class NoopLockTest(unittest.TestCase):
518 def test_with(self):
519 noop_lock = store.NoopLock()
520 with noop_lock:
521 self.assertTrue(True)
522
523@unittest.skipUnless("unit" in limits, "Unit skipped")
524class LockedVar(unittest.TestCase):
525
526 def test_values(self):
527 locked_var = store.LockedVar("Foo")
528 self.assertIsInstance(locked_var.lock, store.NoopLock)
529 self.assertEqual("Foo", locked_var.val)
530
531 def test_get(self):
532 with self.subTest(desc="Normal case"):
533 locked_var = store.LockedVar("Foo")
534 self.assertEqual("Foo", locked_var.get())
535 with self.subTest(desc="Dict"):
536 locked_var = store.LockedVar({"foo": "bar"})
537 self.assertEqual({"foo": "bar"}, locked_var.get())
538 self.assertEqual("bar", locked_var.get("foo"))
539 self.assertIsNone(locked_var.get("other"))
540
541 def test_set(self):
542 locked_var = store.LockedVar("Foo")
543 locked_var.set("Bar")
544 self.assertEqual("Bar", locked_var.get())
545
546 def test__getattr(self):
547 dummy = type('Dummy', (object,), {})()
548 dummy.attribute = "Hey"
549
550 locked_var = store.LockedVar(dummy)
551 self.assertEqual("Hey", locked_var.attribute)
552 with self.assertRaises(AttributeError):
553 locked_var.other
554
555 def test_start_lock(self):
556 locked_var = store.LockedVar("Foo")
557 locked_var.start_lock()
558 self.assertEqual("lock", locked_var.lock.__class__.__name__)
559
560 thread1 = threading.Thread(target=locked_var.set, args=["Bar1"])
561 thread2 = threading.Thread(target=locked_var.set, args=["Bar2"])
562 thread3 = threading.Thread(target=locked_var.set, args=["Bar3"])
563
564 with locked_var.lock:
565 thread1.start()
566 thread2.start()
567 thread3.start()
568
569 self.assertEqual("Foo", locked_var.val)
570 thread1.join()
571 thread2.join()
572 thread3.join()
573 self.assertEqual("Bar", locked_var.get()[0:3])
574
575 def test_wait_for_notification(self):
576 with self.assertRaises(RuntimeError):
577 store.Portfolio.wait_for_notification()
578
579 with mock.patch.object(store.Portfolio, "get_cryptoportfolio") as get,\
580 mock.patch.object(store.Portfolio, "report") as report,\
581 mock.patch.object(store.time, "sleep") as sleep:
582 store.Portfolio.start_worker(poll=3)
583
584 store.Portfolio.worker_notify.set()
585
586 store.Portfolio.callback.wait()
587
588 report.print_log.assert_called_once_with("Fetching cryptoportfolio")
589 get.assert_called_once_with(refetch=True)
590 sleep.assert_called_once_with(3)
591 self.assertFalse(store.Portfolio.worker_notify.is_set())
592 self.assertTrue(store.Portfolio.worker.is_alive())
593
594 store.Portfolio.callback.clear()
595 store.Portfolio.worker_started = False
596 store.Portfolio.worker_notify.set()
597 store.Portfolio.callback.wait()
598
599 self.assertFalse(store.Portfolio.worker.is_alive())
600
601 def test_notify_and_wait(self):
602 with mock.patch.object(store.Portfolio, "callback") as callback,\
603 mock.patch.object(store.Portfolio, "worker_notify") as worker_notify:
604 store.Portfolio.notify_and_wait()
605 callback.clear.assert_called_once_with()
606 worker_notify.set.assert_called_once_with()
607 callback.wait.assert_called_once_with()
608
1aa7d4fa 609@unittest.skipUnless("unit" in limits, "Unit skipped")
80cdd672 610class PortfolioTest(WebMockTestCase):
80cdd672
IB
611 def setUp(self):
612 super(PortfolioTest, self).setUp()
613
d00dc02b 614 with open("test_samples/test_portfolio.json") as example:
80cdd672
IB
615 self.json_response = example.read()
616
ada1b5f1 617 self.wm.get(market.Portfolio.URL, text=self.json_response)
80cdd672 618
ada1b5f1
IB
619 @mock.patch.object(market.Portfolio, "parse_cryptoportfolio")
620 def test_get_cryptoportfolio(self, parse_cryptoportfolio):
dc1ca9a3
IB
621 with self.subTest(parallel=False):
622 self.wm.get(market.Portfolio.URL, [
623 {"text":'{ "foo": "bar" }', "status_code": 200},
624 {"text": "System Error", "status_code": 500},
625 {"exc": requests.exceptions.ConnectTimeout},
626 ])
627 market.Portfolio.get_cryptoportfolio()
628 self.assertIn("foo", market.Portfolio.data.get())
629 self.assertEqual("bar", market.Portfolio.data.get()["foo"])
630 self.assertTrue(self.wm.called)
631 self.assertEqual(1, self.wm.call_count)
632 market.Portfolio.report.log_error.assert_not_called()
633 market.Portfolio.report.log_http_request.assert_called_once()
634 parse_cryptoportfolio.assert_called_once_with()
635 market.Portfolio.report.log_http_request.reset_mock()
636 parse_cryptoportfolio.reset_mock()
637 market.Portfolio.data = store.LockedVar(None)
638
639 market.Portfolio.get_cryptoportfolio()
640 self.assertIsNone(market.Portfolio.data.get())
641 self.assertEqual(2, self.wm.call_count)
642 parse_cryptoportfolio.assert_not_called()
643 market.Portfolio.report.log_error.assert_not_called()
644 market.Portfolio.report.log_http_request.assert_called_once()
645 market.Portfolio.report.log_http_request.reset_mock()
646 parse_cryptoportfolio.reset_mock()
647
648 market.Portfolio.data = store.LockedVar("Foo")
649 market.Portfolio.get_cryptoportfolio()
650 self.assertEqual(2, self.wm.call_count)
651 parse_cryptoportfolio.assert_not_called()
652
653 market.Portfolio.get_cryptoportfolio(refetch=True)
654 self.assertEqual("Foo", market.Portfolio.data.get())
655 self.assertEqual(3, self.wm.call_count)
656 market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio",
657 exception=mock.ANY)
658 market.Portfolio.report.log_http_request.assert_not_called()
659 with self.subTest(parallel=True):
660 with mock.patch.object(market.Portfolio, "is_worker_thread") as is_worker,\
661 mock.patch.object(market.Portfolio, "notify_and_wait") as notify:
662 with self.subTest(worker=True):
663 market.Portfolio.data = store.LockedVar(None)
664 market.Portfolio.worker = mock.Mock()
665 is_worker.return_value = True
666 self.wm.get(market.Portfolio.URL, [
667 {"text":'{ "foo": "bar" }', "status_code": 200},
668 ])
669 market.Portfolio.get_cryptoportfolio()
670 self.assertIn("foo", market.Portfolio.data.get())
671 parse_cryptoportfolio.reset_mock()
672 with self.subTest(worker=False):
673 market.Portfolio.data = store.LockedVar(None)
674 market.Portfolio.worker = mock.Mock()
675 is_worker.return_value = False
676 market.Portfolio.get_cryptoportfolio()
677 notify.assert_called_once_with()
678 parse_cryptoportfolio.assert_not_called()
80cdd672 679
f86ee140 680 def test_parse_cryptoportfolio(self):
dc1ca9a3
IB
681 with self.subTest(description="Normal case"):
682 market.Portfolio.data = store.LockedVar(store.json.loads(
683 self.json_response, parse_int=D, parse_float=D))
684 market.Portfolio.parse_cryptoportfolio()
685
686 self.assertListEqual(
687 ["medium", "high"],
688 list(market.Portfolio.liquidities.get().keys()))
689
690 liquidities = market.Portfolio.liquidities.get()
691 self.assertEqual(10, len(liquidities["medium"].keys()))
692 self.assertEqual(10, len(liquidities["high"].keys()))
693
694 expected = {
695 'BTC': (D("0.2857"), "long"),
696 'DGB': (D("0.1015"), "long"),
697 'DOGE': (D("0.1805"), "long"),
698 'SC': (D("0.0623"), "long"),
699 'ZEC': (D("0.3701"), "long"),
700 }
701 date = portfolio.datetime(2018, 1, 8)
702 self.assertDictEqual(expected, liquidities["high"][date])
703
704 expected = {
705 'BTC': (D("1.1102e-16"), "long"),
706 'ETC': (D("0.1"), "long"),
707 'FCT': (D("0.1"), "long"),
708 'GAS': (D("0.1"), "long"),
709 'NAV': (D("0.1"), "long"),
710 'OMG': (D("0.1"), "long"),
711 'OMNI': (D("0.1"), "long"),
712 'PPC': (D("0.1"), "long"),
713 'RIC': (D("0.1"), "long"),
714 'VIA': (D("0.1"), "long"),
715 'XCP': (D("0.1"), "long"),
716 }
717 self.assertDictEqual(expected, liquidities["medium"][date])
718 self.assertEqual(portfolio.datetime(2018, 1, 15), market.Portfolio.last_date.get())
719
720 with self.subTest(description="Missing weight"):
721 data = store.json.loads(self.json_response, parse_int=D, parse_float=D)
722 del(data["portfolio_2"]["weights"])
723 market.Portfolio.data = store.LockedVar(data)
724
725 market.Portfolio.parse_cryptoportfolio()
726 self.assertListEqual(
727 ["medium", "high"],
728 list(market.Portfolio.liquidities.get().keys()))
729 self.assertEqual({}, market.Portfolio.liquidities.get("medium"))
730
731 with self.subTest(description="All missing weights"):
732 data = store.json.loads(self.json_response, parse_int=D, parse_float=D)
733 del(data["portfolio_1"]["weights"])
734 del(data["portfolio_2"]["weights"])
735 market.Portfolio.data = store.LockedVar(data)
736
737 market.Portfolio.parse_cryptoportfolio()
738 self.assertEqual({}, market.Portfolio.liquidities.get("medium"))
739 self.assertEqual({}, market.Portfolio.liquidities.get("high"))
740 self.assertEqual(datetime.datetime(1,1,1), market.Portfolio.last_date.get())
741
ada1b5f1
IB
742
743 @mock.patch.object(market.Portfolio, "get_cryptoportfolio")
744 def test_repartition(self, get_cryptoportfolio):
dc1ca9a3 745 market.Portfolio.liquidities = store.LockedVar({
ada1b5f1
IB
746 "medium": {
747 "2018-03-01": "medium_2018-03-01",
748 "2018-03-08": "medium_2018-03-08",
749 },
750 "high": {
751 "2018-03-01": "high_2018-03-01",
752 "2018-03-08": "high_2018-03-08",
753 }
dc1ca9a3
IB
754 })
755 market.Portfolio.last_date = store.LockedVar("2018-03-08")
80cdd672 756
ada1b5f1
IB
757 self.assertEqual("medium_2018-03-08", market.Portfolio.repartition())
758 get_cryptoportfolio.assert_called_once_with()
759 self.assertEqual("medium_2018-03-08", market.Portfolio.repartition(liquidity="medium"))
760 self.assertEqual("high_2018-03-08", market.Portfolio.repartition(liquidity="high"))
9f54fd9a 761
ada1b5f1
IB
762 @mock.patch.object(market.time, "sleep")
763 @mock.patch.object(market.Portfolio, "get_cryptoportfolio")
764 def test_wait_for_recent(self, get_cryptoportfolio, sleep):
9f54fd9a 765 self.call_count = 0
ada1b5f1
IB
766 def _get(refetch=False):
767 if self.call_count != 0:
768 self.assertTrue(refetch)
769 else:
770 self.assertFalse(refetch)
9f54fd9a 771 self.call_count += 1
dc1ca9a3 772 market.Portfolio.last_date = store.LockedVar(store.datetime.now()\
ada1b5f1 773 - store.timedelta(10)\
dc1ca9a3 774 + store.timedelta(self.call_count))
ada1b5f1 775 get_cryptoportfolio.side_effect = _get
9f54fd9a 776
ada1b5f1 777 market.Portfolio.wait_for_recent()
9f54fd9a
IB
778 sleep.assert_called_with(30)
779 self.assertEqual(6, sleep.call_count)
ada1b5f1
IB
780 self.assertEqual(7, get_cryptoportfolio.call_count)
781 market.Portfolio.report.print_log.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
9f54fd9a
IB
782
783 sleep.reset_mock()
ada1b5f1 784 get_cryptoportfolio.reset_mock()
dc1ca9a3 785 market.Portfolio.last_date = store.LockedVar(None)
9f54fd9a 786 self.call_count = 0
ada1b5f1 787 market.Portfolio.wait_for_recent(delta=15)
9f54fd9a 788 sleep.assert_not_called()
ada1b5f1 789 self.assertEqual(1, get_cryptoportfolio.call_count)
9f54fd9a
IB
790
791 sleep.reset_mock()
ada1b5f1 792 get_cryptoportfolio.reset_mock()
dc1ca9a3 793 market.Portfolio.last_date = store.LockedVar(None)
9f54fd9a 794 self.call_count = 0
ada1b5f1 795 market.Portfolio.wait_for_recent(delta=1)
9f54fd9a
IB
796 sleep.assert_called_with(30)
797 self.assertEqual(9, sleep.call_count)
ada1b5f1 798 self.assertEqual(10, get_cryptoportfolio.call_count)
9f54fd9a 799
dc1ca9a3
IB
800 def test_is_worker_thread(self):
801 with self.subTest(worker=None):
802 self.assertFalse(store.Portfolio.is_worker_thread())
803
804 with self.subTest(worker="not self"),\
805 mock.patch("threading.current_thread") as current_thread:
806 current = mock.Mock()
807 current_thread.return_value = current
808 store.Portfolio.worker = mock.Mock()
809 self.assertFalse(store.Portfolio.is_worker_thread())
810
811 with self.subTest(worker="self"),\
812 mock.patch("threading.current_thread") as current_thread:
813 current = mock.Mock()
814 current_thread.return_value = current
815 store.Portfolio.worker = current
816 self.assertTrue(store.Portfolio.is_worker_thread())
817
818 def test_start_worker(self):
819 with mock.patch.object(store.Portfolio, "wait_for_notification") as notification:
820 store.Portfolio.start_worker()
821 notification.assert_called_once_with(poll=30)
822
823 self.assertEqual("lock", store.Portfolio.last_date.lock.__class__.__name__)
824 self.assertEqual("lock", store.Portfolio.liquidities.lock.__class__.__name__)
825 store.Portfolio.report.start_lock.assert_called_once_with()
826
827 self.assertIsNotNone(store.Portfolio.worker)
828 self.assertIsNotNone(store.Portfolio.worker_notify)
829 self.assertIsNotNone(store.Portfolio.callback)
830 self.assertTrue(store.Portfolio.worker_started)
831
1aa7d4fa 832@unittest.skipUnless("unit" in limits, "Unit skipped")
80cdd672 833class AmountTest(WebMockTestCase):
dd359bc0 834 def test_values(self):
5ab23e1c
IB
835 amount = portfolio.Amount("BTC", "0.65")
836 self.assertEqual(D("0.65"), amount.value)
dd359bc0
IB
837 self.assertEqual("BTC", amount.currency)
838
dd359bc0
IB
839 def test_in_currency(self):
840 amount = portfolio.Amount("ETC", 10)
841
f86ee140 842 self.assertEqual(amount, amount.in_currency("ETC", self.m))
dd359bc0 843
f86ee140
IB
844 with self.subTest(desc="no ticker for currency"):
845 self.m.get_ticker.return_value = None
dd359bc0 846
f86ee140 847 self.assertRaises(Exception, amount.in_currency, "ETH", self.m)
dd359bc0 848
f86ee140
IB
849 with self.subTest(desc="nominal case"):
850 self.m.get_ticker.return_value = {
deb8924c
IB
851 "bid": D("0.2"),
852 "ask": D("0.4"),
5ab23e1c 853 "average": D("0.3"),
dd359bc0
IB
854 "foo": "bar",
855 }
f86ee140 856 converted_amount = amount.in_currency("ETH", self.m)
dd359bc0 857
5ab23e1c 858 self.assertEqual(D("3.0"), converted_amount.value)
dd359bc0
IB
859 self.assertEqual("ETH", converted_amount.currency)
860 self.assertEqual(amount, converted_amount.linked_to)
861 self.assertEqual("bar", converted_amount.ticker["foo"])
862
f86ee140 863 converted_amount = amount.in_currency("ETH", self.m, action="bid", compute_value="default")
deb8924c
IB
864 self.assertEqual(D("2"), converted_amount.value)
865
f86ee140 866 converted_amount = amount.in_currency("ETH", self.m, compute_value="ask")
deb8924c
IB
867 self.assertEqual(D("4"), converted_amount.value)
868
f86ee140 869 converted_amount = amount.in_currency("ETH", self.m, rate=D("0.02"))
c2644ba8
IB
870 self.assertEqual(D("0.2"), converted_amount.value)
871
80cdd672
IB
872 def test__round(self):
873 amount = portfolio.Amount("BAR", portfolio.D("1.23456789876"))
874 self.assertEqual(D("1.23456789"), round(amount).value)
875 self.assertEqual(D("1.23"), round(amount, 2).value)
876
dd359bc0
IB
877 def test__abs(self):
878 amount = portfolio.Amount("SC", -120)
879 self.assertEqual(120, abs(amount).value)
880 self.assertEqual("SC", abs(amount).currency)
881
882 amount = portfolio.Amount("SC", 10)
883 self.assertEqual(10, abs(amount).value)
884 self.assertEqual("SC", abs(amount).currency)
885
886 def test__add(self):
5ab23e1c
IB
887 amount1 = portfolio.Amount("XVG", "12.9")
888 amount2 = portfolio.Amount("XVG", "13.1")
dd359bc0
IB
889
890 self.assertEqual(26, (amount1 + amount2).value)
891 self.assertEqual("XVG", (amount1 + amount2).currency)
892
5ab23e1c 893 amount3 = portfolio.Amount("ETH", "1.6")
dd359bc0
IB
894 with self.assertRaises(Exception):
895 amount1 + amount3
896
897 amount4 = portfolio.Amount("ETH", 0.0)
898 self.assertEqual(amount1, amount1 + amount4)
899
f320eb8a
IB
900 self.assertEqual(amount1, amount1 + 0)
901
dd359bc0 902 def test__radd(self):
5ab23e1c 903 amount = portfolio.Amount("XVG", "12.9")
dd359bc0
IB
904
905 self.assertEqual(amount, 0 + amount)
906 with self.assertRaises(Exception):
907 4 + amount
908
909 def test__sub(self):
5ab23e1c
IB
910 amount1 = portfolio.Amount("XVG", "13.3")
911 amount2 = portfolio.Amount("XVG", "13.1")
dd359bc0 912
5ab23e1c 913 self.assertEqual(D("0.2"), (amount1 - amount2).value)
dd359bc0
IB
914 self.assertEqual("XVG", (amount1 - amount2).currency)
915
5ab23e1c 916 amount3 = portfolio.Amount("ETH", "1.6")
dd359bc0
IB
917 with self.assertRaises(Exception):
918 amount1 - amount3
919
920 amount4 = portfolio.Amount("ETH", 0.0)
921 self.assertEqual(amount1, amount1 - amount4)
922
f320eb8a
IB
923 def test__rsub(self):
924 amount = portfolio.Amount("ETH", "1.6")
925 with self.assertRaises(Exception):
926 3 - amount
927
f86ee140 928 self.assertEqual(portfolio.Amount("ETH", "-1.6"), 0-amount)
f320eb8a 929
dd359bc0
IB
930 def test__mul(self):
931 amount = portfolio.Amount("XEM", 11)
932
5ab23e1c
IB
933 self.assertEqual(D("38.5"), (amount * D("3.5")).value)
934 self.assertEqual(D("33"), (amount * 3).value)
dd359bc0
IB
935
936 with self.assertRaises(Exception):
937 amount * amount
938
939 def test__rmul(self):
940 amount = portfolio.Amount("XEM", 11)
941
5ab23e1c
IB
942 self.assertEqual(D("38.5"), (D("3.5") * amount).value)
943 self.assertEqual(D("33"), (3 * amount).value)
dd359bc0
IB
944
945 def test__floordiv(self):
946 amount = portfolio.Amount("XEM", 11)
947
5ab23e1c
IB
948 self.assertEqual(D("5.5"), (amount / 2).value)
949 self.assertEqual(D("4.4"), (amount / D("2.5")).value)
dd359bc0 950
1aa7d4fa
IB
951 with self.assertRaises(Exception):
952 amount / amount
953
80cdd672 954 def test__truediv(self):
dd359bc0
IB
955 amount = portfolio.Amount("XEM", 11)
956
5ab23e1c
IB
957 self.assertEqual(D("5.5"), (amount / 2).value)
958 self.assertEqual(D("4.4"), (amount / D("2.5")).value)
dd359bc0
IB
959
960 def test__lt(self):
961 amount1 = portfolio.Amount("BTD", 11.3)
962 amount2 = portfolio.Amount("BTD", 13.1)
963
964 self.assertTrue(amount1 < amount2)
965 self.assertFalse(amount2 < amount1)
966 self.assertFalse(amount1 < amount1)
967
968 amount3 = portfolio.Amount("BTC", 1.6)
969 with self.assertRaises(Exception):
970 amount1 < amount3
971
80cdd672
IB
972 def test__le(self):
973 amount1 = portfolio.Amount("BTD", 11.3)
974 amount2 = portfolio.Amount("BTD", 13.1)
975
976 self.assertTrue(amount1 <= amount2)
977 self.assertFalse(amount2 <= amount1)
978 self.assertTrue(amount1 <= amount1)
979
980 amount3 = portfolio.Amount("BTC", 1.6)
981 with self.assertRaises(Exception):
982 amount1 <= amount3
983
984 def test__gt(self):
985 amount1 = portfolio.Amount("BTD", 11.3)
986 amount2 = portfolio.Amount("BTD", 13.1)
987
988 self.assertTrue(amount2 > amount1)
989 self.assertFalse(amount1 > amount2)
990 self.assertFalse(amount1 > amount1)
991
992 amount3 = portfolio.Amount("BTC", 1.6)
993 with self.assertRaises(Exception):
994 amount3 > amount1
995
996 def test__ge(self):
997 amount1 = portfolio.Amount("BTD", 11.3)
998 amount2 = portfolio.Amount("BTD", 13.1)
999
1000 self.assertTrue(amount2 >= amount1)
1001 self.assertFalse(amount1 >= amount2)
1002 self.assertTrue(amount1 >= amount1)
1003
1004 amount3 = portfolio.Amount("BTC", 1.6)
1005 with self.assertRaises(Exception):
1006 amount3 >= amount1
1007
dd359bc0
IB
1008 def test__eq(self):
1009 amount1 = portfolio.Amount("BTD", 11.3)
1010 amount2 = portfolio.Amount("BTD", 13.1)
1011 amount3 = portfolio.Amount("BTD", 11.3)
1012
1013 self.assertFalse(amount1 == amount2)
1014 self.assertFalse(amount2 == amount1)
1015 self.assertTrue(amount1 == amount3)
1016 self.assertFalse(amount2 == 0)
1017
1018 amount4 = portfolio.Amount("BTC", 1.6)
1019 with self.assertRaises(Exception):
1020 amount1 == amount4
1021
1022 amount5 = portfolio.Amount("BTD", 0)
1023 self.assertTrue(amount5 == 0)
1024
80cdd672
IB
1025 def test__ne(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.assertTrue(amount1 != amount2)
1031 self.assertTrue(amount2 != amount1)
1032 self.assertFalse(amount1 != amount3)
1033 self.assertTrue(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.assertFalse(amount5 != 0)
1041
1042 def test__neg(self):
1043 amount1 = portfolio.Amount("BTD", "11.3")
1044
1045 self.assertEqual(portfolio.D("-11.3"), (-amount1).value)
1046
dd359bc0
IB
1047 def test__str(self):
1048 amount1 = portfolio.Amount("BTX", 32)
1049 self.assertEqual("32.00000000 BTX", str(amount1))
1050
1051 amount2 = portfolio.Amount("USDT", 12000)
1052 amount1.linked_to = amount2
1053 self.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1))
1054
1055 def test__repr(self):
1056 amount1 = portfolio.Amount("BTX", 32)
1057 self.assertEqual("Amount(32.00000000 BTX)", repr(amount1))
1058
1059 amount2 = portfolio.Amount("USDT", 12000)
1060 amount1.linked_to = amount2
1061 self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1))
1062
1063 amount3 = portfolio.Amount("BTC", 0.1)
1064 amount2.linked_to = amount3
1065 self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1))
1066
3d0247f9
IB
1067 def test_as_json(self):
1068 amount = portfolio.Amount("BTX", 32)
1069 self.assertEqual({"currency": "BTX", "value": D("32")}, amount.as_json())
1070
1071 amount = portfolio.Amount("BTX", "1E-10")
1072 self.assertEqual({"currency": "BTX", "value": D("0")}, amount.as_json())
1073
1074 amount = portfolio.Amount("BTX", "1E-5")
1075 self.assertEqual({"currency": "BTX", "value": D("0.00001")}, amount.as_json())
1076 self.assertEqual("0.00001", str(amount.as_json()["value"]))
1077
1aa7d4fa 1078@unittest.skipUnless("unit" in limits, "Unit skipped")
80cdd672 1079class BalanceTest(WebMockTestCase):
f2da6589 1080 def test_values(self):
80cdd672
IB
1081 balance = portfolio.Balance("BTC", {
1082 "exchange_total": "0.65",
1083 "exchange_free": "0.35",
1084 "exchange_used": "0.30",
1085 "margin_total": "-10",
aca4d437
IB
1086 "margin_borrowed": "10",
1087 "margin_available": "0",
1088 "margin_in_position": "0",
80cdd672
IB
1089 "margin_position_type": "short",
1090 "margin_borrowed_base_currency": "USDT",
1091 "margin_liquidation_price": "1.20",
1092 "margin_pending_gain": "10",
1093 "margin_lending_fees": "0.4",
1094 "margin_borrowed_base_price": "0.15",
1095 })
1096 self.assertEqual(portfolio.D("0.65"), balance.exchange_total.value)
1097 self.assertEqual(portfolio.D("0.35"), balance.exchange_free.value)
1098 self.assertEqual(portfolio.D("0.30"), balance.exchange_used.value)
1099 self.assertEqual("BTC", balance.exchange_total.currency)
1100 self.assertEqual("BTC", balance.exchange_free.currency)
1101 self.assertEqual("BTC", balance.exchange_total.currency)
1102
1103 self.assertEqual(portfolio.D("-10"), balance.margin_total.value)
aca4d437
IB
1104 self.assertEqual(portfolio.D("10"), balance.margin_borrowed.value)
1105 self.assertEqual(portfolio.D("0"), balance.margin_available.value)
80cdd672
IB
1106 self.assertEqual("BTC", balance.margin_total.currency)
1107 self.assertEqual("BTC", balance.margin_borrowed.currency)
aca4d437 1108 self.assertEqual("BTC", balance.margin_available.currency)
f2da6589 1109
f2da6589
IB
1110 self.assertEqual("BTC", balance.currency)
1111
80cdd672
IB
1112 self.assertEqual(portfolio.D("0.4"), balance.margin_lending_fees.value)
1113 self.assertEqual("USDT", balance.margin_lending_fees.currency)
1114
6ca5a1ec
IB
1115 def test__repr(self):
1116 self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
1117 repr(portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 })))
1118 balance = portfolio.Balance("BTX", { "exchange_total": 3,
1119 "exchange_used": 1, "exchange_free": 2 })
1120 self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance))
f2da6589 1121
1aa7d4fa
IB
1122 balance = portfolio.Balance("BTX", { "exchange_total": 1, "exchange_used": 1})
1123 self.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance))
1124
6ca5a1ec 1125 balance = portfolio.Balance("BTX", { "margin_total": 3,
aca4d437
IB
1126 "margin_in_position": 1, "margin_available": 2 })
1127 self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance))
f2da6589 1128
aca4d437 1129 balance = portfolio.Balance("BTX", { "margin_total": 2, "margin_available": 2 })
1aa7d4fa
IB
1130 self.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance))
1131
6ca5a1ec
IB
1132 balance = portfolio.Balance("BTX", { "margin_total": -3,
1133 "margin_borrowed_base_price": D("0.1"),
1134 "margin_borrowed_base_currency": "BTC",
1135 "margin_lending_fees": D("0.002") })
1136 self.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance))
f2da6589 1137
1aa7d4fa 1138 balance = portfolio.Balance("BTX", { "margin_total": 1,
aca4d437
IB
1139 "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2})
1140 self.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance))
1aa7d4fa 1141
3d0247f9
IB
1142 def test_as_json(self):
1143 balance = portfolio.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 })
1144 as_json = balance.as_json()
1145 self.assertEqual(set(portfolio.Balance.base_keys), set(as_json.keys()))
1146 self.assertEqual(D(0), as_json["total"])
1147 self.assertEqual(D(2), as_json["exchange_total"])
1148 self.assertEqual(D(2), as_json["exchange_free"])
1149 self.assertEqual(D(0), as_json["exchange_used"])
1150 self.assertEqual(D(0), as_json["margin_total"])
aca4d437 1151 self.assertEqual(D(0), as_json["margin_available"])
3d0247f9
IB
1152 self.assertEqual(D(0), as_json["margin_borrowed"])
1153
1aa7d4fa 1154@unittest.skipUnless("unit" in limits, "Unit skipped")
f86ee140
IB
1155class MarketTest(WebMockTestCase):
1156 def setUp(self):
1157 super(MarketTest, self).setUp()
1158
1159 self.ccxt = mock.Mock(spec=market.ccxt.poloniexE)
1160
1161 def test_values(self):
07fa7a4b 1162 m = market.Market(self.ccxt, self.market_args())
f86ee140
IB
1163
1164 self.assertEqual(self.ccxt, m.ccxt)
1165 self.assertFalse(m.debug)
1166 self.assertIsInstance(m.report, market.ReportStore)
1167 self.assertIsInstance(m.trades, market.TradeStore)
1168 self.assertIsInstance(m.balances, market.BalanceStore)
1169 self.assertEqual(m, m.report.market)
1170 self.assertEqual(m, m.trades.market)
1171 self.assertEqual(m, m.balances.market)
1172 self.assertEqual(m, m.ccxt._market)
1173
07fa7a4b 1174 m = market.Market(self.ccxt, self.market_args(debug=True))
f86ee140
IB
1175 self.assertTrue(m.debug)
1176
07fa7a4b 1177 m = market.Market(self.ccxt, self.market_args(debug=False))
f86ee140
IB
1178 self.assertFalse(m.debug)
1179
07fa7a4b
IB
1180 with mock.patch("market.ReportStore") as report_store:
1181 with self.subTest(quiet=False):
1182 m = market.Market(self.ccxt, self.market_args(quiet=False))
1183 report_store.assert_called_with(m, verbose_print=True)
1184 with self.subTest(quiet=True):
1185 m = market.Market(self.ccxt, self.market_args(quiet=True))
1186 report_store.assert_called_with(m, verbose_print=False)
1187
f86ee140
IB
1188 @mock.patch("market.ccxt")
1189 def test_from_config(self, ccxt):
1190 with mock.patch("market.ReportStore"):
1191 ccxt.poloniexE.return_value = self.ccxt
f86ee140 1192
07fa7a4b 1193 m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args())
f86ee140
IB
1194
1195 self.assertEqual(self.ccxt, m.ccxt)
1196
07fa7a4b 1197 m = market.Market.from_config({"key": "key", "secred": "secret"}, self.market_args(debug=True))
f86ee140
IB
1198 self.assertEqual(True, m.debug)
1199
aca4d437
IB
1200 def test_get_tickers(self):
1201 self.ccxt.fetch_tickers.side_effect = [
1202 "tickers",
1203 market.NotSupported
6ca5a1ec 1204 ]
f2da6589 1205
07fa7a4b 1206 m = market.Market(self.ccxt, self.market_args())
aca4d437
IB
1207 self.assertEqual("tickers", m.get_tickers())
1208 self.assertEqual("tickers", m.get_tickers())
1209 self.ccxt.fetch_tickers.assert_called_once()
f2da6589 1210
aca4d437
IB
1211 self.assertIsNone(m.get_tickers(refresh=self.time.time()))
1212
1213 def test_get_ticker(self):
1214 with self.subTest(get_tickers=True):
1215 self.ccxt.fetch_tickers.return_value = {
1216 "ETH/ETC": { "bid": 1, "ask": 3 },
1217 "XVG/ETH": { "bid": 10, "ask": 40 },
1218 }
07fa7a4b 1219 m = market.Market(self.ccxt, self.market_args())
aca4d437
IB
1220
1221 ticker = m.get_ticker("ETH", "ETC")
1222 self.assertEqual(1, ticker["bid"])
1223 self.assertEqual(3, ticker["ask"])
1224 self.assertEqual(2, ticker["average"])
1225 self.assertFalse(ticker["inverted"])
1226
1227 ticker = m.get_ticker("ETH", "XVG")
1228 self.assertEqual(0.0625, ticker["average"])
1229 self.assertTrue(ticker["inverted"])
1230 self.assertIn("original", ticker)
1231 self.assertEqual(10, ticker["original"]["bid"])
7192b2e1 1232 self.assertEqual(25, ticker["original"]["average"])
aca4d437
IB
1233
1234 ticker = m.get_ticker("XVG", "XMR")
1235 self.assertIsNone(ticker)
1236
1237 with self.subTest(get_tickers=False):
1238 self.ccxt.fetch_tickers.return_value = None
1239 self.ccxt.fetch_ticker.side_effect = [
1240 { "bid": 1, "ask": 3 },
1241 market.ExchangeError("foo"),
1242 { "bid": 10, "ask": 40 },
1243 market.ExchangeError("foo"),
1244 market.ExchangeError("foo"),
1245 ]
1246
07fa7a4b 1247 m = market.Market(self.ccxt, self.market_args())
aca4d437
IB
1248
1249 ticker = m.get_ticker("ETH", "ETC")
1250 self.ccxt.fetch_ticker.assert_called_with("ETH/ETC")
1251 self.assertEqual(1, ticker["bid"])
1252 self.assertEqual(3, ticker["ask"])
1253 self.assertEqual(2, ticker["average"])
1254 self.assertFalse(ticker["inverted"])
1255
1256 ticker = m.get_ticker("ETH", "XVG")
1257 self.assertEqual(0.0625, ticker["average"])
1258 self.assertTrue(ticker["inverted"])
1259 self.assertIn("original", ticker)
1260 self.assertEqual(10, ticker["original"]["bid"])
7192b2e1 1261 self.assertEqual(25, ticker["original"]["average"])
aca4d437
IB
1262
1263 ticker = m.get_ticker("XVG", "XMR")
1264 self.assertIsNone(ticker)
f2da6589 1265
6ca5a1ec 1266 def test_fetch_fees(self):
07fa7a4b 1267 m = market.Market(self.ccxt, self.market_args())
f86ee140
IB
1268 self.ccxt.fetch_fees.return_value = "Foo"
1269 self.assertEqual("Foo", m.fetch_fees())
1270 self.ccxt.fetch_fees.assert_called_once()
1271 self.ccxt.reset_mock()
1272 self.assertEqual("Foo", m.fetch_fees())
1273 self.ccxt.fetch_fees.assert_not_called()
f2da6589 1274
ada1b5f1 1275 @mock.patch.object(market.Portfolio, "repartition")
f86ee140
IB
1276 @mock.patch.object(market.Market, "get_ticker")
1277 @mock.patch.object(market.TradeStore, "compute_trades")
1278 def test_prepare_trades(self, compute_trades, get_ticker, repartition):
f2da6589 1279 repartition.return_value = {
350ed24d
IB
1280 "XEM": (D("0.75"), "long"),
1281 "BTC": (D("0.25"), "long"),
f2da6589 1282 }
f86ee140 1283 def _get_ticker(c1, c2):
deb8924c
IB
1284 if c1 == "USDT" and c2 == "BTC":
1285 return { "average": D("0.0001") }
1286 if c1 == "XVG" and c2 == "BTC":
1287 return { "average": D("0.000001") }
1288 if c1 == "XEM" and c2 == "BTC":
1289 return { "average": D("0.001") }
a9950fd0 1290 self.fail("Should be called with {}, {}".format(c1, c2))
deb8924c
IB
1291 get_ticker.side_effect = _get_ticker
1292
f86ee140 1293 with mock.patch("market.ReportStore"):
07fa7a4b 1294 m = market.Market(self.ccxt, self.market_args())
f86ee140
IB
1295 self.ccxt.fetch_all_balances.return_value = {
1296 "USDT": {
1297 "exchange_free": D("10000.0"),
1298 "exchange_used": D("0.0"),
1299 "exchange_total": D("10000.0"),
1300 "total": D("10000.0")
1301 },
1302 "XVG": {
1303 "exchange_free": D("10000.0"),
1304 "exchange_used": D("0.0"),
1305 "exchange_total": D("10000.0"),
1306 "total": D("10000.0")
1307 },
1308 }
18167a3c 1309
f86ee140 1310 m.balances.fetch_balances(tag="tag")
f2da6589 1311
f86ee140
IB
1312 m.prepare_trades()
1313 compute_trades.assert_called()
1314
1315 call = compute_trades.call_args
1316 self.assertEqual(1, call[0][0]["USDT"].value)
1317 self.assertEqual(D("0.01"), call[0][0]["XVG"].value)
1318 self.assertEqual(D("0.2525"), call[0][1]["BTC"].value)
1319 self.assertEqual(D("0.7575"), call[0][1]["XEM"].value)
7bd830a8
IB
1320 m.report.log_stage.assert_called_once_with("prepare_trades",
1321 base_currency='BTC', compute_value='average',
9db7d156 1322 liquidity='medium', only=None, repartition=None)
f86ee140 1323 m.report.log_balances.assert_called_once_with(tag="tag")
c51687d2 1324
a9950fd0 1325
ada1b5f1 1326 @mock.patch.object(market.time, "sleep")
f86ee140 1327 @mock.patch.object(market.TradeStore, "all_orders")
1aa7d4fa 1328 def test_follow_orders(self, all_orders, time_mock):
3d0247f9
IB
1329 for debug, sleep in [
1330 (False, None), (True, None),
1331 (False, 12), (True, 12)]:
1332 with self.subTest(sleep=sleep, debug=debug), \
f86ee140 1333 mock.patch("market.ReportStore"):
07fa7a4b 1334 m = market.Market(self.ccxt, self.market_args(debug=debug))
f86ee140 1335
1aa7d4fa
IB
1336 order_mock1 = mock.Mock()
1337 order_mock2 = mock.Mock()
1338 order_mock3 = mock.Mock()
1339 all_orders.side_effect = [
1340 [order_mock1, order_mock2],
1341 [order_mock1, order_mock2],
1342
1343 [order_mock1, order_mock3],
1344 [order_mock1, order_mock3],
1345
1346 [order_mock1, order_mock3],
1347 [order_mock1, order_mock3],
1348
1349 []
1350 ]
1351
1352 order_mock1.get_status.side_effect = ["open", "open", "closed"]
1353 order_mock2.get_status.side_effect = ["open"]
1354 order_mock3.get_status.side_effect = ["open", "closed"]
1355
1356 order_mock1.trade = mock.Mock()
1357 order_mock2.trade = mock.Mock()
1358 order_mock3.trade = mock.Mock()
1359
f86ee140 1360 m.follow_orders(sleep=sleep)
1aa7d4fa
IB
1361
1362 order_mock1.trade.update_order.assert_any_call(order_mock1, 1)
1363 order_mock1.trade.update_order.assert_any_call(order_mock1, 2)
1364 self.assertEqual(2, order_mock1.trade.update_order.call_count)
1365 self.assertEqual(3, order_mock1.get_status.call_count)
1366
1367 order_mock2.trade.update_order.assert_any_call(order_mock2, 1)
1368 self.assertEqual(1, order_mock2.trade.update_order.call_count)
1369 self.assertEqual(1, order_mock2.get_status.call_count)
1370
1371 order_mock3.trade.update_order.assert_any_call(order_mock3, 2)
1372 self.assertEqual(1, order_mock3.trade.update_order.call_count)
1373 self.assertEqual(2, order_mock3.get_status.call_count)
f86ee140 1374 m.report.log_stage.assert_called()
3d0247f9
IB
1375 calls = [
1376 mock.call("follow_orders_begin"),
1377 mock.call("follow_orders_tick_1"),
1378 mock.call("follow_orders_tick_2"),
1379 mock.call("follow_orders_tick_3"),
1380 mock.call("follow_orders_end"),
1381 ]
f86ee140
IB
1382 m.report.log_stage.assert_has_calls(calls)
1383 m.report.log_orders.assert_called()
1384 self.assertEqual(3, m.report.log_orders.call_count)
3d0247f9
IB
1385 calls = [
1386 mock.call([order_mock1, order_mock2], tick=1),
1387 mock.call([order_mock1, order_mock3], tick=2),
1388 mock.call([order_mock1, order_mock3], tick=3),
1389 ]
f86ee140 1390 m.report.log_orders.assert_has_calls(calls)
3d0247f9
IB
1391 calls = [
1392 mock.call(order_mock1, 3, finished=True),
1393 mock.call(order_mock3, 3, finished=True),
1394 ]
f86ee140 1395 m.report.log_order.assert_has_calls(calls)
1aa7d4fa
IB
1396
1397 if sleep is None:
1398 if debug:
f86ee140 1399 m.report.log_debug_action.assert_called_with("Set follow_orders tick to 7s")
1aa7d4fa
IB
1400 time_mock.assert_called_with(7)
1401 else:
1402 time_mock.assert_called_with(30)
1403 else:
1404 time_mock.assert_called_with(sleep)
1405
f86ee140 1406 @mock.patch.object(market.BalanceStore, "fetch_balances")
5a72ded7
IB
1407 def test_move_balance(self, fetch_balances):
1408 for debug in [True, False]:
1409 with self.subTest(debug=debug),\
f86ee140 1410 mock.patch("market.ReportStore"):
07fa7a4b 1411 m = market.Market(self.ccxt, self.market_args(debug=debug))
f86ee140 1412
5a72ded7
IB
1413 value_from = portfolio.Amount("BTC", "1.0")
1414 value_from.linked_to = portfolio.Amount("ETH", "10.0")
1415 value_to = portfolio.Amount("BTC", "10.0")
f86ee140 1416 trade1 = portfolio.Trade(value_from, value_to, "ETH", m)
5a72ded7
IB
1417
1418 value_from = portfolio.Amount("BTC", "0.0")
1419 value_from.linked_to = portfolio.Amount("ETH", "0.0")
1420 value_to = portfolio.Amount("BTC", "-3.0")
f86ee140 1421 trade2 = portfolio.Trade(value_from, value_to, "ETH", m)
5a72ded7
IB
1422
1423 value_from = portfolio.Amount("USDT", "0.0")
1424 value_from.linked_to = portfolio.Amount("XVG", "0.0")
1425 value_to = portfolio.Amount("USDT", "-50.0")
f86ee140 1426 trade3 = portfolio.Trade(value_from, value_to, "XVG", m)
5a72ded7 1427
f86ee140 1428 m.trades.all = [trade1, trade2, trade3]
aca4d437
IB
1429 balance1 = portfolio.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" })
1430 balance2 = portfolio.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" })
1431 balance3 = portfolio.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" })
f86ee140 1432 m.balances.all = {"BTC": balance1, "USDT": balance2, "ETC": balance3}
5a72ded7 1433
f86ee140 1434 m.move_balances()
5a72ded7 1435
f86ee140
IB
1436 fetch_balances.assert_called_with()
1437 m.report.log_move_balances.assert_called_once()
3d0247f9 1438
5a72ded7 1439 if debug:
f86ee140
IB
1440 m.report.log_debug_action.assert_called()
1441 self.assertEqual(3, m.report.log_debug_action.call_count)
5a72ded7 1442 else:
f86ee140 1443 self.ccxt.transfer_balance.assert_any_call("BTC", 3, "exchange", "margin")
aca4d437
IB
1444 self.ccxt.transfer_balance.assert_any_call("USDT", 100, "exchange", "margin")
1445 self.ccxt.transfer_balance.assert_any_call("ETC", 5, "margin", "exchange")
1f117ac7 1446
b4e0ba0b 1447 def test_store_file_report(self):
1f117ac7 1448 file_open = mock.mock_open()
07fa7a4b 1449 m = market.Market(self.ccxt, self.market_args(), report_path="present", user_id=1)
1f117ac7
IB
1450 with self.subTest(file="present"),\
1451 mock.patch("market.open", file_open),\
1452 mock.patch.object(m, "report") as report,\
1453 mock.patch.object(market, "datetime") as time_mock:
1454
718e3e91 1455 report.print_logs = [[time_mock.now(), "Foo"], [time_mock.now(), "Bar"]]
1f117ac7
IB
1456 report.to_json.return_value = "json_content"
1457
b4e0ba0b 1458 m.store_file_report(datetime.datetime(2018, 2, 25))
1f117ac7
IB
1459
1460 file_open.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
718e3e91
IB
1461 file_open.assert_any_call("present/2018-02-25T00:00:00_1.log", "w")
1462 file_open().write.assert_any_call("json_content")
1463 file_open().write.assert_any_call("Foo\nBar")
1f117ac7
IB
1464 m.report.to_json.assert_called_once_with()
1465
07fa7a4b 1466 m = market.Market(self.ccxt, self.market_args(), report_path="error", user_id=1)
1f117ac7
IB
1467 with self.subTest(file="error"),\
1468 mock.patch("market.open") as file_open,\
9bde69bf 1469 mock.patch.object(m, "report") as report,\
1f117ac7
IB
1470 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
1471 file_open.side_effect = FileNotFoundError
1472
b4e0ba0b
IB
1473 m.store_file_report(datetime.datetime(2018, 2, 25))
1474
1475 self.assertRegex(stdout_mock.getvalue(), "impossible to store report file: FileNotFoundError;")
1476
1477 @mock.patch.object(market, "psycopg2")
1478 def test_store_database_report(self, psycopg2):
1479 connect_mock = mock.Mock()
1480 cursor_mock = mock.MagicMock()
1481
1482 connect_mock.cursor.return_value = cursor_mock
1483 psycopg2.connect.return_value = connect_mock
1484 m = market.Market(self.ccxt, self.market_args(),
1485 pg_config={"config": "pg_config"}, user_id=1)
1486 cursor_mock.fetchone.return_value = [42]
1487
1488 with self.subTest(error=False),\
1489 mock.patch.object(m, "report") as report:
1490 report.to_json_array.return_value = [
1491 ("date1", "type1", "payload1"),
1492 ("date2", "type2", "payload2"),
1493 ]
1494 m.store_database_report(datetime.datetime(2018, 3, 24))
1495 connect_mock.assert_has_calls([
1496 mock.call.cursor(),
1497 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)),
1498 mock.call.cursor().fetchone(),
1499 mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date1', 42, 'type1', 'payload1')),
1500 mock.call.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date2', 42, 'type2', 'payload2')),
1501 mock.call.commit(),
1502 mock.call.cursor().close(),
1503 mock.call.close()
1504 ])
1505
1506 connect_mock.reset_mock()
1507 with self.subTest(error=True),\
1508 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
1509 psycopg2.connect.side_effect = Exception("Bouh")
1510 m.store_database_report(datetime.datetime(2018, 3, 24))
1511 self.assertEqual(stdout_mock.getvalue(), "impossible to store report to database: Exception; Bouh\n")
1512
1513 def test_store_report(self):
1514 m = market.Market(self.ccxt, self.market_args(), user_id=1)
1515 with self.subTest(file=None, pg_config=None),\
1516 mock.patch.object(m, "report") as report,\
1517 mock.patch.object(m, "store_database_report") as db_report,\
1518 mock.patch.object(m, "store_file_report") as file_report:
1519 m.store_report()
1520 report.merge.assert_called_with(store.Portfolio.report)
1521
1522 file_report.assert_not_called()
1523 db_report.assert_not_called()
1524
1525 report.reset_mock()
1526 m = market.Market(self.ccxt, self.market_args(), report_path="present", user_id=1)
1527 with self.subTest(file="present", pg_config=None),\
1528 mock.patch.object(m, "report") as report,\
1529 mock.patch.object(m, "store_file_report") as file_report,\
1530 mock.patch.object(m, "store_database_report") as db_report,\
1531 mock.patch.object(market, "datetime") as time_mock:
1532
1533 time_mock.now.return_value = datetime.datetime(2018, 2, 25)
1534
1f117ac7
IB
1535 m.store_report()
1536
9bde69bf 1537 report.merge.assert_called_with(store.Portfolio.report)
b4e0ba0b
IB
1538 file_report.assert_called_once_with(datetime.datetime(2018, 2, 25))
1539 db_report.assert_not_called()
1540
1541 report.reset_mock()
1542 m = market.Market(self.ccxt, self.market_args(), pg_config="present", user_id=1)
1543 with self.subTest(file=None, pg_config="present"),\
1544 mock.patch.object(m, "report") as report,\
1545 mock.patch.object(m, "store_file_report") as file_report,\
1546 mock.patch.object(m, "store_database_report") as db_report,\
1547 mock.patch.object(market, "datetime") as time_mock:
1548
1549 time_mock.now.return_value = datetime.datetime(2018, 2, 25)
1550
1551 m.store_report()
1552
1553 report.merge.assert_called_with(store.Portfolio.report)
1554 file_report.assert_not_called()
1555 db_report.assert_called_once_with(datetime.datetime(2018, 2, 25))
1556
1557 report.reset_mock()
1558 m = market.Market(self.ccxt, self.market_args(),
1559 pg_config="pg_config", report_path="present", user_id=1)
1560 with self.subTest(file="present", pg_config="present"),\
1561 mock.patch.object(m, "report") as report,\
1562 mock.patch.object(m, "store_file_report") as file_report,\
1563 mock.patch.object(m, "store_database_report") as db_report,\
1564 mock.patch.object(market, "datetime") as time_mock:
1565
1566 time_mock.now.return_value = datetime.datetime(2018, 2, 25)
1567
1568 m.store_report()
1569
1570 report.merge.assert_called_with(store.Portfolio.report)
1571 file_report.assert_called_once_with(datetime.datetime(2018, 2, 25))
1572 db_report.assert_called_once_with(datetime.datetime(2018, 2, 25))
1f117ac7
IB
1573
1574 def test_print_orders(self):
07fa7a4b 1575 m = market.Market(self.ccxt, self.market_args())
1f117ac7
IB
1576 with mock.patch.object(m.report, "log_stage") as log_stage,\
1577 mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\
1578 mock.patch.object(m, "prepare_trades") as prepare_trades,\
1579 mock.patch.object(m.trades, "prepare_orders") as prepare_orders:
1580 m.print_orders()
1581
1582 log_stage.assert_called_with("print_orders")
1583 fetch_balances.assert_called_with(tag="print_orders")
1584 prepare_trades.assert_called_with(base_currency="BTC",
1585 compute_value="average")
1586 prepare_orders.assert_called_with(compute_value="average")
1587
1588 def test_print_balances(self):
07fa7a4b 1589 m = market.Market(self.ccxt, self.market_args())
1f117ac7
IB
1590
1591 with mock.patch.object(m.balances, "in_currency") as in_currency,\
1592 mock.patch.object(m.report, "log_stage") as log_stage,\
1593 mock.patch.object(m.balances, "fetch_balances") as fetch_balances,\
1594 mock.patch.object(m.report, "print_log") as print_log:
1595
1596 in_currency.return_value = {
1597 "BTC": portfolio.Amount("BTC", "0.65"),
1598 "ETH": portfolio.Amount("BTC", "0.3"),
1599 }
1600
1601 m.print_balances()
1602
1603 log_stage.assert_called_once_with("print_balances")
1604 fetch_balances.assert_called_with()
1605 print_log.assert_has_calls([
1606 mock.call("total:"),
1607 mock.call(portfolio.Amount("BTC", "0.95")),
1608 ])
1609
1610 @mock.patch("market.Processor.process")
1611 @mock.patch("market.ReportStore.log_error")
1612 @mock.patch("market.Market.store_report")
1613 def test_process(self, store_report, log_error, process):
07fa7a4b 1614 m = market.Market(self.ccxt, self.market_args())
1f117ac7
IB
1615 with self.subTest(before=False, after=False):
1616 m.process(None)
1617
1618 process.assert_not_called()
1619 store_report.assert_called_once()
1620 log_error.assert_not_called()
1621
1622 process.reset_mock()
1623 log_error.reset_mock()
1624 store_report.reset_mock()
1625 with self.subTest(before=True, after=False):
1626 m.process(None, before=True)
1627
1628 process.assert_called_once_with("sell_all", steps="before")
1629 store_report.assert_called_once()
1630 log_error.assert_not_called()
1631
1632 process.reset_mock()
1633 log_error.reset_mock()
1634 store_report.reset_mock()
1635 with self.subTest(before=False, after=True):
1636 m.process(None, after=True)
1637
1638 process.assert_called_once_with("sell_all", steps="after")
1639 store_report.assert_called_once()
1640 log_error.assert_not_called()
1641
1642 process.reset_mock()
1643 log_error.reset_mock()
1644 store_report.reset_mock()
1645 with self.subTest(before=True, after=True):
1646 m.process(None, before=True, after=True)
1647
1648 process.assert_has_calls([
1649 mock.call("sell_all", steps="before"),
1650 mock.call("sell_all", steps="after"),
1651 ])
1652 store_report.assert_called_once()
1653 log_error.assert_not_called()
1654
1655 process.reset_mock()
1656 log_error.reset_mock()
1657 store_report.reset_mock()
1658 with self.subTest(action="print_balances"),\
1659 mock.patch.object(m, "print_balances") as print_balances:
1660 m.process(["print_balances"])
1661
1662 process.assert_not_called()
1663 log_error.assert_not_called()
1664 store_report.assert_called_once()
1665 print_balances.assert_called_once_with()
1666
1667 log_error.reset_mock()
1668 store_report.reset_mock()
1669 with self.subTest(action="print_orders"),\
1670 mock.patch.object(m, "print_orders") as print_orders,\
1671 mock.patch.object(m, "print_balances") as print_balances:
1672 m.process(["print_orders", "print_balances"])
1673
1674 process.assert_not_called()
1675 log_error.assert_not_called()
1676 store_report.assert_called_once()
1677 print_orders.assert_called_once_with()
1678 print_balances.assert_called_once_with()
1679
1680 log_error.reset_mock()
1681 store_report.reset_mock()
1682 with self.subTest(action="unknown"):
1683 m.process(["unknown"])
1684 log_error.assert_called_once_with("market_process", message="Unknown action unknown")
1685 store_report.assert_called_once()
1686
1687 log_error.reset_mock()
1688 store_report.reset_mock()
1689 with self.subTest(unhandled_exception=True):
1690 process.side_effect = Exception("bouh")
1691
1692 m.process(None, before=True)
1693 log_error.assert_called_with("market_process", exception=mock.ANY)
1694 store_report.assert_called_once()
1695
1aa7d4fa 1696@unittest.skipUnless("unit" in limits, "Unit skipped")
6ca5a1ec 1697class TradeStoreTest(WebMockTestCase):
f86ee140
IB
1698 def test_compute_trades(self):
1699 self.m.balances.currencies.return_value = ["XMR", "DASH", "XVG", "BTC", "ETH"]
1aa7d4fa
IB
1700
1701 values_in_base = {
1702 "XMR": portfolio.Amount("BTC", D("0.9")),
1703 "DASH": portfolio.Amount("BTC", D("0.4")),
1704 "XVG": portfolio.Amount("BTC", D("-0.5")),
1705 "BTC": portfolio.Amount("BTC", D("0.5")),
1706 }
1707 new_repartition = {
1708 "DASH": portfolio.Amount("BTC", D("0.5")),
1709 "XVG": portfolio.Amount("BTC", D("0.1")),
1710 "BTC": portfolio.Amount("BTC", D("0.4")),
1711 "ETH": portfolio.Amount("BTC", D("0.3")),
1712 }
3d0247f9
IB
1713 side_effect = [
1714 (True, 1),
1715 (False, 2),
1716 (False, 3),
1717 (True, 4),
1718 (True, 5)
1719 ]
1aa7d4fa 1720
f86ee140
IB
1721 with mock.patch.object(market.TradeStore, "trade_if_matching") as trade_if_matching:
1722 trade_store = market.TradeStore(self.m)
1723 trade_if_matching.side_effect = side_effect
1aa7d4fa 1724
f86ee140
IB
1725 trade_store.compute_trades(values_in_base,
1726 new_repartition, only="only")
1727
1728 self.assertEqual(5, trade_if_matching.call_count)
1729 self.assertEqual(3, len(trade_store.all))
1730 self.assertEqual([1, 4, 5], trade_store.all)
1731 self.m.report.log_trades.assert_called_with(side_effect, "only")
1aa7d4fa 1732
3d0247f9 1733 def test_trade_if_matching(self):
f86ee140
IB
1734
1735 with self.subTest(only="nope"):
1736 trade_store = market.TradeStore(self.m)
1737 result = trade_store.trade_if_matching(
1738 portfolio.Amount("BTC", D("0")),
1739 portfolio.Amount("BTC", D("0.3")),
1740 "ETH", only="nope")
1741 self.assertEqual(False, result[0])
1742 self.assertIsInstance(result[1], portfolio.Trade)
1743
1744 with self.subTest(only=None):
1745 trade_store = market.TradeStore(self.m)
1746 result = trade_store.trade_if_matching(
1747 portfolio.Amount("BTC", D("0")),
1748 portfolio.Amount("BTC", D("0.3")),
1749 "ETH", only=None)
1750 self.assertEqual(True, result[0])
1751
1752 with self.subTest(only="acquire"):
1753 trade_store = market.TradeStore(self.m)
1754 result = trade_store.trade_if_matching(
1755 portfolio.Amount("BTC", D("0")),
1756 portfolio.Amount("BTC", D("0.3")),
1757 "ETH", only="acquire")
1758 self.assertEqual(True, result[0])
1759
1760 with self.subTest(only="dispose"):
1761 trade_store = market.TradeStore(self.m)
1762 result = trade_store.trade_if_matching(
1763 portfolio.Amount("BTC", D("0")),
1764 portfolio.Amount("BTC", D("0.3")),
1765 "ETH", only="dispose")
1766 self.assertEqual(False, result[0])
1767
1768 def test_prepare_orders(self):
1769 trade_store = market.TradeStore(self.m)
1770
6ca5a1ec
IB
1771 trade_mock1 = mock.Mock()
1772 trade_mock2 = mock.Mock()
aca4d437 1773 trade_mock3 = mock.Mock()
cfab619d 1774
3d0247f9
IB
1775 trade_mock1.prepare_order.return_value = 1
1776 trade_mock2.prepare_order.return_value = 2
aca4d437
IB
1777 trade_mock3.prepare_order.return_value = 3
1778
17598517
IB
1779 trade_mock1.pending = True
1780 trade_mock2.pending = True
1781 trade_mock3.pending = False
3d0247f9 1782
f86ee140
IB
1783 trade_store.all.append(trade_mock1)
1784 trade_store.all.append(trade_mock2)
aca4d437 1785 trade_store.all.append(trade_mock3)
6ca5a1ec 1786
f86ee140 1787 trade_store.prepare_orders()
6ca5a1ec
IB
1788 trade_mock1.prepare_order.assert_called_with(compute_value="default")
1789 trade_mock2.prepare_order.assert_called_with(compute_value="default")
aca4d437 1790 trade_mock3.prepare_order.assert_not_called()
f86ee140 1791 self.m.report.log_orders.assert_called_once_with([1, 2], None, "default")
3d0247f9 1792
f86ee140 1793 self.m.report.log_orders.reset_mock()
6ca5a1ec 1794
f86ee140 1795 trade_store.prepare_orders(compute_value="bla")
6ca5a1ec
IB
1796 trade_mock1.prepare_order.assert_called_with(compute_value="bla")
1797 trade_mock2.prepare_order.assert_called_with(compute_value="bla")
f86ee140 1798 self.m.report.log_orders.assert_called_once_with([1, 2], None, "bla")
6ca5a1ec
IB
1799
1800 trade_mock1.prepare_order.reset_mock()
1801 trade_mock2.prepare_order.reset_mock()
f86ee140 1802 self.m.report.log_orders.reset_mock()
6ca5a1ec
IB
1803
1804 trade_mock1.action = "foo"
1805 trade_mock2.action = "bar"
f86ee140 1806 trade_store.prepare_orders(only="bar")
6ca5a1ec
IB
1807 trade_mock1.prepare_order.assert_not_called()
1808 trade_mock2.prepare_order.assert_called_with(compute_value="default")
f86ee140 1809 self.m.report.log_orders.assert_called_once_with([2], "bar", "default")
6ca5a1ec
IB
1810
1811 def test_print_all_with_order(self):
1812 trade_mock1 = mock.Mock()
1813 trade_mock2 = mock.Mock()
1814 trade_mock3 = mock.Mock()
f86ee140
IB
1815 trade_store = market.TradeStore(self.m)
1816 trade_store.all = [trade_mock1, trade_mock2, trade_mock3]
6ca5a1ec 1817
f86ee140 1818 trade_store.print_all_with_order()
6ca5a1ec
IB
1819
1820 trade_mock1.print_with_order.assert_called()
1821 trade_mock2.print_with_order.assert_called()
1822 trade_mock3.print_with_order.assert_called()
1823
f86ee140
IB
1824 def test_run_orders(self):
1825 with mock.patch.object(market.TradeStore, "all_orders") as all_orders:
1826 order_mock1 = mock.Mock()
1827 order_mock2 = mock.Mock()
1828 order_mock3 = mock.Mock()
1829 trade_store = market.TradeStore(self.m)
1830
1831 all_orders.return_value = [order_mock1, order_mock2, order_mock3]
1832
1833 trade_store.run_orders()
1834
1835 all_orders.assert_called_with(state="pending")
6ca5a1ec
IB
1836
1837 order_mock1.run.assert_called()
1838 order_mock2.run.assert_called()
1839 order_mock3.run.assert_called()
1840
f86ee140
IB
1841 self.m.report.log_stage.assert_called_with("run_orders")
1842 self.m.report.log_orders.assert_called_with([order_mock1, order_mock2,
3d0247f9
IB
1843 order_mock3])
1844
6ca5a1ec
IB
1845 def test_all_orders(self):
1846 trade_mock1 = mock.Mock()
1847 trade_mock2 = mock.Mock()
1848
1849 order_mock1 = mock.Mock()
1850 order_mock2 = mock.Mock()
1851 order_mock3 = mock.Mock()
1852
1853 trade_mock1.orders = [order_mock1, order_mock2]
1854 trade_mock2.orders = [order_mock3]
1855
1856 order_mock1.status = "pending"
1857 order_mock2.status = "open"
1858 order_mock3.status = "open"
1859
f86ee140
IB
1860 trade_store = market.TradeStore(self.m)
1861 trade_store.all.append(trade_mock1)
1862 trade_store.all.append(trade_mock2)
6ca5a1ec 1863
f86ee140 1864 orders = trade_store.all_orders()
6ca5a1ec
IB
1865 self.assertEqual(3, len(orders))
1866
f86ee140 1867 open_orders = trade_store.all_orders(state="open")
6ca5a1ec
IB
1868 self.assertEqual(2, len(open_orders))
1869 self.assertEqual([order_mock2, order_mock3], open_orders)
1870
f86ee140
IB
1871 def test_update_all_orders_status(self):
1872 with mock.patch.object(market.TradeStore, "all_orders") as all_orders:
1873 order_mock1 = mock.Mock()
1874 order_mock2 = mock.Mock()
1875 order_mock3 = mock.Mock()
1876
1877 all_orders.return_value = [order_mock1, order_mock2, order_mock3]
1878
1879 trade_store = market.TradeStore(self.m)
1880
1881 trade_store.update_all_orders_status()
1882 all_orders.assert_called_with(state="open")
6ca5a1ec 1883
f86ee140
IB
1884 order_mock1.get_status.assert_called()
1885 order_mock2.get_status.assert_called()
1886 order_mock3.get_status.assert_called()
6ca5a1ec 1887
17598517
IB
1888 def test_close_trades(self):
1889 trade_mock1 = mock.Mock()
1890 trade_mock2 = mock.Mock()
1891 trade_mock3 = mock.Mock()
1892
1893 trade_store = market.TradeStore(self.m)
1894
1895 trade_store.all.append(trade_mock1)
1896 trade_store.all.append(trade_mock2)
1897 trade_store.all.append(trade_mock3)
1898
1899 trade_store.close_trades()
1900
1901 trade_mock1.close.assert_called_once_with()
1902 trade_mock2.close.assert_called_once_with()
1903 trade_mock3.close.assert_called_once_with()
1904
aca4d437
IB
1905 def test_pending(self):
1906 trade_mock1 = mock.Mock()
17598517 1907 trade_mock1.pending = True
aca4d437 1908 trade_mock2 = mock.Mock()
17598517 1909 trade_mock2.pending = True
aca4d437 1910 trade_mock3 = mock.Mock()
17598517 1911 trade_mock3.pending = False
aca4d437
IB
1912
1913 trade_store = market.TradeStore(self.m)
1914
1915 trade_store.all.append(trade_mock1)
1916 trade_store.all.append(trade_mock2)
1917 trade_store.all.append(trade_mock3)
1918
1919 self.assertEqual([trade_mock1, trade_mock2], trade_store.pending)
3d0247f9 1920
1aa7d4fa 1921@unittest.skipUnless("unit" in limits, "Unit skipped")
6ca5a1ec
IB
1922class BalanceStoreTest(WebMockTestCase):
1923 def setUp(self):
1924 super(BalanceStoreTest, self).setUp()
1925
1926 self.fetch_balance = {
1927 "ETC": {
1928 "exchange_free": 0,
1929 "exchange_used": 0,
1930 "exchange_total": 0,
1931 "margin_total": 0,
1932 },
1933 "USDT": {
1934 "exchange_free": D("6.0"),
1935 "exchange_used": D("1.2"),
1936 "exchange_total": D("7.2"),
1937 "margin_total": 0,
1938 },
1939 "XVG": {
1940 "exchange_free": 16,
1941 "exchange_used": 0,
1942 "exchange_total": 16,
1943 "margin_total": 0,
1944 },
1945 "XMR": {
1946 "exchange_free": 0,
1947 "exchange_used": 0,
1948 "exchange_total": 0,
1949 "margin_total": D("-1.0"),
1950 "margin_free": 0,
1951 },
1952 }
1953
f86ee140
IB
1954 def test_in_currency(self):
1955 self.m.get_ticker.return_value = {
1956 "bid": D("0.09"),
1957 "ask": D("0.11"),
1958 "average": D("0.1"),
1959 }
1960
1961 balance_store = market.BalanceStore(self.m)
1962 balance_store.all = {
6ca5a1ec
IB
1963 "BTC": portfolio.Balance("BTC", {
1964 "total": "0.65",
1965 "exchange_total":"0.65",
1966 "exchange_free": "0.35",
1967 "exchange_used": "0.30"}),
1968 "ETH": portfolio.Balance("ETH", {
1969 "total": 3,
1970 "exchange_total": 3,
1971 "exchange_free": 3,
1972 "exchange_used": 0}),
1973 }
cfab619d 1974
f86ee140 1975 amounts = balance_store.in_currency("BTC")
6ca5a1ec
IB
1976 self.assertEqual("BTC", amounts["ETH"].currency)
1977 self.assertEqual(D("0.65"), amounts["BTC"].value)
1978 self.assertEqual(D("0.30"), amounts["ETH"].value)
f86ee140 1979 self.m.report.log_tickers.assert_called_once_with(amounts, "BTC",
3d0247f9 1980 "average", "total")
f86ee140 1981 self.m.report.log_tickers.reset_mock()
cfab619d 1982
f86ee140 1983 amounts = balance_store.in_currency("BTC", compute_value="bid")
6ca5a1ec
IB
1984 self.assertEqual(D("0.65"), amounts["BTC"].value)
1985 self.assertEqual(D("0.27"), amounts["ETH"].value)
f86ee140 1986 self.m.report.log_tickers.assert_called_once_with(amounts, "BTC",
3d0247f9 1987 "bid", "total")
f86ee140 1988 self.m.report.log_tickers.reset_mock()
cfab619d 1989
f86ee140 1990 amounts = balance_store.in_currency("BTC", compute_value="bid", type="exchange_used")
6ca5a1ec
IB
1991 self.assertEqual(D("0.30"), amounts["BTC"].value)
1992 self.assertEqual(0, amounts["ETH"].value)
f86ee140 1993 self.m.report.log_tickers.assert_called_once_with(amounts, "BTC",
3d0247f9 1994 "bid", "exchange_used")
f86ee140 1995 self.m.report.log_tickers.reset_mock()
cfab619d 1996
f86ee140
IB
1997 def test_fetch_balances(self):
1998 self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance
cfab619d 1999
f86ee140 2000 balance_store = market.BalanceStore(self.m)
cfab619d 2001
f86ee140
IB
2002 balance_store.fetch_balances()
2003 self.assertNotIn("ETC", balance_store.currencies())
2004 self.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store.currencies()))
2005
2006 balance_store.all["ETC"] = portfolio.Balance("ETC", {
6ca5a1ec
IB
2007 "exchange_total": "1", "exchange_free": "0",
2008 "exchange_used": "1" })
f86ee140
IB
2009 balance_store.fetch_balances(tag="foo")
2010 self.assertEqual(0, balance_store.all["ETC"].total)
2011 self.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store.currencies()))
2012 self.m.report.log_balances.assert_called_with(tag="foo")
cfab619d 2013
ada1b5f1 2014 @mock.patch.object(market.Portfolio, "repartition")
f86ee140
IB
2015 def test_dispatch_assets(self, repartition):
2016 self.m.ccxt.fetch_all_balances.return_value = self.fetch_balance
2017
2018 balance_store = market.BalanceStore(self.m)
2019 balance_store.fetch_balances()
6ca5a1ec 2020
f86ee140 2021 self.assertNotIn("XEM", balance_store.currencies())
6ca5a1ec 2022
3d0247f9 2023 repartition_hash = {
6ca5a1ec
IB
2024 "XEM": (D("0.75"), "long"),
2025 "BTC": (D("0.26"), "long"),
1aa7d4fa 2026 "DASH": (D("0.10"), "short"),
6ca5a1ec 2027 }
3d0247f9 2028 repartition.return_value = repartition_hash
6ca5a1ec 2029
f86ee140 2030 amounts = balance_store.dispatch_assets(portfolio.Amount("BTC", "11.1"))
ada1b5f1 2031 repartition.assert_called_with(liquidity="medium")
f86ee140 2032 self.assertIn("XEM", balance_store.currencies())
6ca5a1ec
IB
2033 self.assertEqual(D("2.6"), amounts["BTC"].value)
2034 self.assertEqual(D("7.5"), amounts["XEM"].value)
1aa7d4fa 2035 self.assertEqual(D("-1.0"), amounts["DASH"].value)
f86ee140
IB
2036 self.m.report.log_balances.assert_called_with(tag=None)
2037 self.m.report.log_dispatch.assert_called_once_with(portfolio.Amount("BTC",
3d0247f9 2038 "11.1"), amounts, "medium", repartition_hash)
6ca5a1ec
IB
2039
2040 def test_currencies(self):
f86ee140
IB
2041 balance_store = market.BalanceStore(self.m)
2042
2043 balance_store.all = {
6ca5a1ec
IB
2044 "BTC": portfolio.Balance("BTC", {
2045 "total": "0.65",
2046 "exchange_total":"0.65",
2047 "exchange_free": "0.35",
2048 "exchange_used": "0.30"}),
2049 "ETH": portfolio.Balance("ETH", {
2050 "total": 3,
2051 "exchange_total": 3,
2052 "exchange_free": 3,
2053 "exchange_used": 0}),
2054 }
f86ee140 2055 self.assertListEqual(["BTC", "ETH"], list(balance_store.currencies()))
6ca5a1ec 2056
3d0247f9
IB
2057 def test_as_json(self):
2058 balance_mock1 = mock.Mock()
2059 balance_mock1.as_json.return_value = 1
2060
2061 balance_mock2 = mock.Mock()
2062 balance_mock2.as_json.return_value = 2
2063
f86ee140
IB
2064 balance_store = market.BalanceStore(self.m)
2065 balance_store.all = {
3d0247f9
IB
2066 "BTC": balance_mock1,
2067 "ETH": balance_mock2,
2068 }
2069
f86ee140 2070 as_json = balance_store.as_json()
3d0247f9
IB
2071 self.assertEqual(1, as_json["BTC"])
2072 self.assertEqual(2, as_json["ETH"])
2073
2074
1aa7d4fa 2075@unittest.skipUnless("unit" in limits, "Unit skipped")
6ca5a1ec
IB
2076class ComputationTest(WebMockTestCase):
2077 def test_compute_value(self):
2078 compute = mock.Mock()
2079 portfolio.Computation.compute_value("foo", "buy", compute_value=compute)
2080 compute.assert_called_with("foo", "ask")
2081
2082 compute.reset_mock()
2083 portfolio.Computation.compute_value("foo", "sell", compute_value=compute)
2084 compute.assert_called_with("foo", "bid")
2085
2086 compute.reset_mock()
2087 portfolio.Computation.compute_value("foo", "ask", compute_value=compute)
2088 compute.assert_called_with("foo", "ask")
2089
2090 compute.reset_mock()
2091 portfolio.Computation.compute_value("foo", "bid", compute_value=compute)
2092 compute.assert_called_with("foo", "bid")
2093
2094 compute.reset_mock()
2095 portfolio.Computation.computations["test"] = compute
2096 portfolio.Computation.compute_value("foo", "bid", compute_value="test")
2097 compute.assert_called_with("foo", "bid")
2098
2099
1aa7d4fa 2100@unittest.skipUnless("unit" in limits, "Unit skipped")
6ca5a1ec 2101class TradeTest(WebMockTestCase):
cfab619d 2102
cfab619d 2103 def test_values_assertion(self):
c51687d2
IB
2104 value_from = portfolio.Amount("BTC", "1.0")
2105 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2106 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2107 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
66c8b3dd
IB
2108 self.assertEqual("BTC", trade.base_currency)
2109 self.assertEqual("ETH", trade.currency)
f86ee140 2110 self.assertEqual(self.m, trade.market)
66c8b3dd
IB
2111
2112 with self.assertRaises(AssertionError):
aca4d437 2113 portfolio.Trade(value_from, -value_to, "ETH", self.m)
66c8b3dd 2114 with self.assertRaises(AssertionError):
aca4d437 2115 portfolio.Trade(value_from, value_to, "ETC", self.m)
66c8b3dd
IB
2116 with self.assertRaises(AssertionError):
2117 value_from.currency = "ETH"
f86ee140 2118 portfolio.Trade(value_from, value_to, "ETH", self.m)
aca4d437
IB
2119 value_from.currency = "BTC"
2120 with self.assertRaises(AssertionError):
2121 value_from2 = portfolio.Amount("BTC", "1.0")
2122 portfolio.Trade(value_from2, value_to, "ETH", self.m)
cfab619d 2123
c51687d2 2124 value_from = portfolio.Amount("BTC", 0)
f86ee140 2125 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2 2126 self.assertEqual(0, trade.value_from.linked_to)
cfab619d 2127
cfab619d 2128 def test_action(self):
c51687d2
IB
2129 value_from = portfolio.Amount("BTC", "1.0")
2130 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2131 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2132 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
cfab619d 2133
c51687d2
IB
2134 self.assertIsNone(trade.action)
2135
2136 value_from = portfolio.Amount("BTC", "1.0")
2137 value_from.linked_to = portfolio.Amount("BTC", "1.0")
1aa7d4fa 2138 value_to = portfolio.Amount("BTC", "2.0")
f86ee140 2139 trade = portfolio.Trade(value_from, value_to, "BTC", self.m)
c51687d2
IB
2140
2141 self.assertIsNone(trade.action)
2142
2143 value_from = portfolio.Amount("BTC", "0.5")
2144 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2145 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2146 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2
IB
2147
2148 self.assertEqual("acquire", trade.action)
2149
2150 value_from = portfolio.Amount("BTC", "0")
2151 value_from.linked_to = portfolio.Amount("ETH", "0")
2152 value_to = portfolio.Amount("BTC", "-1.0")
f86ee140 2153 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2 2154
5a72ded7 2155 self.assertEqual("acquire", trade.action)
cfab619d 2156
cfab619d 2157 def test_order_action(self):
c51687d2
IB
2158 value_from = portfolio.Amount("BTC", "0.5")
2159 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2160 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2161 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2 2162
186f7d81
IB
2163 trade.inverted = False
2164 self.assertEqual("buy", trade.order_action())
2165 trade.inverted = True
2166 self.assertEqual("sell", trade.order_action())
c51687d2
IB
2167
2168 value_from = portfolio.Amount("BTC", "0")
2169 value_from.linked_to = portfolio.Amount("ETH", "0")
2170 value_to = portfolio.Amount("BTC", "-1.0")
f86ee140 2171 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2 2172
186f7d81
IB
2173 trade.inverted = False
2174 self.assertEqual("sell", trade.order_action())
2175 trade.inverted = True
2176 self.assertEqual("buy", trade.order_action())
c51687d2
IB
2177
2178 def test_trade_type(self):
2179 value_from = portfolio.Amount("BTC", "0.5")
2180 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2181 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2182 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2
IB
2183
2184 self.assertEqual("long", trade.trade_type)
2185
2186 value_from = portfolio.Amount("BTC", "0")
2187 value_from.linked_to = portfolio.Amount("ETH", "0")
2188 value_to = portfolio.Amount("BTC", "-1.0")
f86ee140 2189 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2
IB
2190
2191 self.assertEqual("short", trade.trade_type)
2192
aca4d437 2193 def test_is_fullfiled(self):
186f7d81
IB
2194 with self.subTest(inverted=False):
2195 value_from = portfolio.Amount("BTC", "0.5")
2196 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2197 value_to = portfolio.Amount("BTC", "1.0")
2198 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
aca4d437 2199
186f7d81
IB
2200 order1 = mock.Mock()
2201 order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3")
aca4d437 2202
186f7d81
IB
2203 order2 = mock.Mock()
2204 order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01")
2205 trade.orders.append(order1)
2206 trade.orders.append(order2)
2207
2208 self.assertFalse(trade.is_fullfiled)
2209
2210 order3 = mock.Mock()
2211 order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19")
2212 trade.orders.append(order3)
2213
2214 self.assertTrue(trade.is_fullfiled)
2215
2216 order1.filled_amount.assert_called_with(in_base_currency=True)
2217 order2.filled_amount.assert_called_with(in_base_currency=True)
2218 order3.filled_amount.assert_called_with(in_base_currency=True)
aca4d437 2219
186f7d81
IB
2220 with self.subTest(inverted=True):
2221 value_from = portfolio.Amount("BTC", "0.5")
2222 value_from.linked_to = portfolio.Amount("USDT", "1000.0")
2223 value_to = portfolio.Amount("BTC", "1.0")
2224 trade = portfolio.Trade(value_from, value_to, "USDT", self.m)
2225 trade.inverted = True
aca4d437 2226
186f7d81
IB
2227 order1 = mock.Mock()
2228 order1.filled_amount.return_value = portfolio.Amount("BTC", "0.3")
2229
2230 order2 = mock.Mock()
2231 order2.filled_amount.return_value = portfolio.Amount("BTC", "0.01")
2232 trade.orders.append(order1)
2233 trade.orders.append(order2)
aca4d437 2234
186f7d81 2235 self.assertFalse(trade.is_fullfiled)
aca4d437 2236
186f7d81
IB
2237 order3 = mock.Mock()
2238 order3.filled_amount.return_value = portfolio.Amount("BTC", "0.19")
2239 trade.orders.append(order3)
aca4d437 2240
186f7d81 2241 self.assertTrue(trade.is_fullfiled)
aca4d437 2242
186f7d81
IB
2243 order1.filled_amount.assert_called_with(in_base_currency=False)
2244 order2.filled_amount.assert_called_with(in_base_currency=False)
2245 order3.filled_amount.assert_called_with(in_base_currency=False)
aca4d437 2246
aca4d437 2247
c51687d2
IB
2248 def test_filled_amount(self):
2249 value_from = portfolio.Amount("BTC", "0.5")
2250 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2251 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2252 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2
IB
2253
2254 order1 = mock.Mock()
1aa7d4fa 2255 order1.filled_amount.return_value = portfolio.Amount("ETH", "0.3")
c51687d2
IB
2256
2257 order2 = mock.Mock()
1aa7d4fa 2258 order2.filled_amount.return_value = portfolio.Amount("ETH", "0.01")
c51687d2
IB
2259 trade.orders.append(order1)
2260 trade.orders.append(order2)
2261
1aa7d4fa
IB
2262 self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount())
2263 order1.filled_amount.assert_called_with(in_base_currency=False)
2264 order2.filled_amount.assert_called_with(in_base_currency=False)
c51687d2 2265
1aa7d4fa
IB
2266 self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=False))
2267 order1.filled_amount.assert_called_with(in_base_currency=False)
2268 order2.filled_amount.assert_called_with(in_base_currency=False)
2269
2270 self.assertEqual(portfolio.Amount("ETH", "0.31"), trade.filled_amount(in_base_currency=True))
2271 order1.filled_amount.assert_called_with(in_base_currency=True)
2272 order2.filled_amount.assert_called_with(in_base_currency=True)
2273
1aa7d4fa
IB
2274 @mock.patch.object(portfolio.Computation, "compute_value")
2275 @mock.patch.object(portfolio.Trade, "filled_amount")
2276 @mock.patch.object(portfolio, "Order")
f86ee140 2277 def test_prepare_order(self, Order, filled_amount, compute_value):
1aa7d4fa
IB
2278 Order.return_value = "Order"
2279
2280 with self.subTest(desc="Nothing to do"):
2281 value_from = portfolio.Amount("BTC", "10")
2282 value_from.rate = D("0.1")
2283 value_from.linked_to = portfolio.Amount("FOO", "100")
2284 value_to = portfolio.Amount("BTC", "10")
f86ee140 2285 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2286
2287 trade.prepare_order()
2288
2289 filled_amount.assert_not_called()
2290 compute_value.assert_not_called()
2291 self.assertEqual(0, len(trade.orders))
2292 Order.assert_not_called()
2293
f86ee140
IB
2294 self.m.get_ticker.return_value = { "inverted": False }
2295 with self.subTest(desc="Already filled"):
1aa7d4fa
IB
2296 filled_amount.return_value = portfolio.Amount("FOO", "100")
2297 compute_value.return_value = D("0.125")
2298
2299 value_from = portfolio.Amount("BTC", "10")
2300 value_from.rate = D("0.1")
2301 value_from.linked_to = portfolio.Amount("FOO", "100")
2302 value_to = portfolio.Amount("BTC", "0")
f86ee140 2303 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2304
2305 trade.prepare_order()
2306
2307 filled_amount.assert_called_with(in_base_currency=False)
f86ee140 2308 compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default")
1aa7d4fa 2309 self.assertEqual(0, len(trade.orders))
f86ee140 2310 self.m.report.log_error.assert_called_with("prepare_order", message=mock.ANY)
1aa7d4fa
IB
2311 Order.assert_not_called()
2312
2313 with self.subTest(action="dispose", inverted=False):
2314 filled_amount.return_value = portfolio.Amount("FOO", "60")
2315 compute_value.return_value = D("0.125")
2316
2317 value_from = portfolio.Amount("BTC", "10")
2318 value_from.rate = D("0.1")
2319 value_from.linked_to = portfolio.Amount("FOO", "100")
2320 value_to = portfolio.Amount("BTC", "1")
f86ee140 2321 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2322
2323 trade.prepare_order()
2324
2325 filled_amount.assert_called_with(in_base_currency=False)
f86ee140 2326 compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default")
1aa7d4fa
IB
2327 self.assertEqual(1, len(trade.orders))
2328 Order.assert_called_with("sell", portfolio.Amount("FOO", 30),
f86ee140 2329 D("0.125"), "BTC", "long", self.m,
1aa7d4fa
IB
2330 trade, close_if_possible=False)
2331
2033e7fe
IB
2332 with self.subTest(action="dispose", inverted=False, close_if_possible=True):
2333 filled_amount.return_value = portfolio.Amount("FOO", "60")
2334 compute_value.return_value = D("0.125")
2335
2336 value_from = portfolio.Amount("BTC", "10")
2337 value_from.rate = D("0.1")
2338 value_from.linked_to = portfolio.Amount("FOO", "100")
2339 value_to = portfolio.Amount("BTC", "1")
2340 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
2341
2342 trade.prepare_order(close_if_possible=True)
2343
2344 filled_amount.assert_called_with(in_base_currency=False)
2345 compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default")
2346 self.assertEqual(1, len(trade.orders))
2347 Order.assert_called_with("sell", portfolio.Amount("FOO", 30),
2348 D("0.125"), "BTC", "long", self.m,
2349 trade, close_if_possible=True)
2350
1aa7d4fa
IB
2351 with self.subTest(action="acquire", inverted=False):
2352 filled_amount.return_value = portfolio.Amount("BTC", "3")
2353 compute_value.return_value = D("0.125")
2354
2355 value_from = portfolio.Amount("BTC", "1")
2356 value_from.rate = D("0.1")
2357 value_from.linked_to = portfolio.Amount("FOO", "10")
2358 value_to = portfolio.Amount("BTC", "10")
f86ee140 2359 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2360
2361 trade.prepare_order()
2362
2363 filled_amount.assert_called_with(in_base_currency=True)
f86ee140 2364 compute_value.assert_called_with(self.m.get_ticker.return_value, "buy", compute_value="default")
1aa7d4fa
IB
2365 self.assertEqual(1, len(trade.orders))
2366
2367 Order.assert_called_with("buy", portfolio.Amount("FOO", 48),
f86ee140 2368 D("0.125"), "BTC", "long", self.m,
1aa7d4fa
IB
2369 trade, close_if_possible=False)
2370
2371 with self.subTest(close_if_possible=True):
2372 filled_amount.return_value = portfolio.Amount("FOO", "0")
2373 compute_value.return_value = D("0.125")
2374
2375 value_from = portfolio.Amount("BTC", "10")
2376 value_from.rate = D("0.1")
2377 value_from.linked_to = portfolio.Amount("FOO", "100")
2378 value_to = portfolio.Amount("BTC", "0")
f86ee140 2379 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2380
2381 trade.prepare_order()
2382
2383 filled_amount.assert_called_with(in_base_currency=False)
f86ee140 2384 compute_value.assert_called_with(self.m.get_ticker.return_value, "sell", compute_value="default")
1aa7d4fa
IB
2385 self.assertEqual(1, len(trade.orders))
2386 Order.assert_called_with("sell", portfolio.Amount("FOO", 100),
f86ee140 2387 D("0.125"), "BTC", "long", self.m,
1aa7d4fa
IB
2388 trade, close_if_possible=True)
2389
f86ee140 2390 self.m.get_ticker.return_value = { "inverted": True, "original": {} }
1aa7d4fa
IB
2391 with self.subTest(action="dispose", inverted=True):
2392 filled_amount.return_value = portfolio.Amount("FOO", "300")
2393 compute_value.return_value = D("125")
2394
2395 value_from = portfolio.Amount("BTC", "10")
2396 value_from.rate = D("0.01")
2397 value_from.linked_to = portfolio.Amount("FOO", "1000")
2398 value_to = portfolio.Amount("BTC", "1")
f86ee140 2399 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2400
2401 trade.prepare_order(compute_value="foo")
2402
2403 filled_amount.assert_called_with(in_base_currency=True)
f86ee140 2404 compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "buy", compute_value="foo")
1aa7d4fa
IB
2405 self.assertEqual(1, len(trade.orders))
2406 Order.assert_called_with("buy", portfolio.Amount("BTC", D("4.8")),
f86ee140 2407 D("125"), "FOO", "long", self.m,
1aa7d4fa
IB
2408 trade, close_if_possible=False)
2409
2410 with self.subTest(action="acquire", inverted=True):
2411 filled_amount.return_value = portfolio.Amount("BTC", "4")
2412 compute_value.return_value = D("125")
2413
2414 value_from = portfolio.Amount("BTC", "1")
2415 value_from.rate = D("0.01")
2416 value_from.linked_to = portfolio.Amount("FOO", "100")
2417 value_to = portfolio.Amount("BTC", "10")
f86ee140 2418 trade = portfolio.Trade(value_from, value_to, "FOO", self.m)
1aa7d4fa
IB
2419
2420 trade.prepare_order(compute_value="foo")
2421
2422 filled_amount.assert_called_with(in_base_currency=False)
f86ee140 2423 compute_value.assert_called_with(self.m.get_ticker.return_value["original"], "sell", compute_value="foo")
1aa7d4fa
IB
2424 self.assertEqual(1, len(trade.orders))
2425 Order.assert_called_with("sell", portfolio.Amount("BTC", D("5")),
f86ee140 2426 D("125"), "FOO", "long", self.m,
1aa7d4fa
IB
2427 trade, close_if_possible=False)
2428
2429
2430 @mock.patch.object(portfolio.Trade, "prepare_order")
2431 def test_update_order(self, prepare_order):
2432 order_mock = mock.Mock()
2433 new_order_mock = mock.Mock()
2434
2435 value_from = portfolio.Amount("BTC", "0.5")
2436 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2437 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2438 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
5a72ded7 2439 prepare_order.return_value = new_order_mock
1aa7d4fa
IB
2440
2441 for i in [0, 1, 3, 4, 6]:
f86ee140 2442 with self.subTest(tick=i):
1aa7d4fa
IB
2443 trade.update_order(order_mock, i)
2444 order_mock.cancel.assert_not_called()
2445 new_order_mock.run.assert_not_called()
f86ee140 2446 self.m.report.log_order.assert_called_once_with(order_mock, i,
3d0247f9 2447 update="waiting", compute_value=None, new_order=None)
1aa7d4fa
IB
2448
2449 order_mock.reset_mock()
2450 new_order_mock.reset_mock()
2451 trade.orders = []
f86ee140
IB
2452 self.m.report.log_order.reset_mock()
2453
2454 trade.update_order(order_mock, 2)
2455 order_mock.cancel.assert_called()
2456 new_order_mock.run.assert_called()
2457 prepare_order.assert_called()
2458 self.m.report.log_order.assert_called()
2459 self.assertEqual(2, self.m.report.log_order.call_count)
2460 calls = [
2461 mock.call(order_mock, 2, update="adjusting",
aca4d437 2462 compute_value=mock.ANY,
f86ee140
IB
2463 new_order=new_order_mock),
2464 mock.call(order_mock, 2, new_order=new_order_mock),
2465 ]
2466 self.m.report.log_order.assert_has_calls(calls)
1aa7d4fa
IB
2467
2468 order_mock.reset_mock()
2469 new_order_mock.reset_mock()
2470 trade.orders = []
f86ee140
IB
2471 self.m.report.log_order.reset_mock()
2472
2473 trade.update_order(order_mock, 5)
2474 order_mock.cancel.assert_called()
2475 new_order_mock.run.assert_called()
2476 prepare_order.assert_called()
2477 self.assertEqual(2, self.m.report.log_order.call_count)
2478 self.m.report.log_order.assert_called()
2479 calls = [
2480 mock.call(order_mock, 5, update="adjusting",
aca4d437 2481 compute_value=mock.ANY,
f86ee140
IB
2482 new_order=new_order_mock),
2483 mock.call(order_mock, 5, new_order=new_order_mock),
2484 ]
2485 self.m.report.log_order.assert_has_calls(calls)
1aa7d4fa
IB
2486
2487 order_mock.reset_mock()
2488 new_order_mock.reset_mock()
2489 trade.orders = []
f86ee140
IB
2490 self.m.report.log_order.reset_mock()
2491
2492 trade.update_order(order_mock, 7)
2493 order_mock.cancel.assert_called()
2494 new_order_mock.run.assert_called()
2495 prepare_order.assert_called_with(compute_value="default")
2496 self.m.report.log_order.assert_called()
2497 self.assertEqual(2, self.m.report.log_order.call_count)
2498 calls = [
2499 mock.call(order_mock, 7, update="market_fallback",
2500 compute_value='default',
2501 new_order=new_order_mock),
2502 mock.call(order_mock, 7, new_order=new_order_mock),
2503 ]
2504 self.m.report.log_order.assert_has_calls(calls)
1aa7d4fa
IB
2505
2506 order_mock.reset_mock()
2507 new_order_mock.reset_mock()
2508 trade.orders = []
f86ee140 2509 self.m.report.log_order.reset_mock()
1aa7d4fa
IB
2510
2511 for i in [10, 13, 16]:
f86ee140 2512 with self.subTest(tick=i):
1aa7d4fa
IB
2513 trade.update_order(order_mock, i)
2514 order_mock.cancel.assert_called()
2515 new_order_mock.run.assert_called()
2516 prepare_order.assert_called_with(compute_value="default")
f86ee140
IB
2517 self.m.report.log_order.assert_called()
2518 self.assertEqual(2, self.m.report.log_order.call_count)
3d0247f9
IB
2519 calls = [
2520 mock.call(order_mock, i, update="market_adjust",
2521 compute_value='default',
2522 new_order=new_order_mock),
2523 mock.call(order_mock, i, new_order=new_order_mock),
2524 ]
f86ee140 2525 self.m.report.log_order.assert_has_calls(calls)
1aa7d4fa
IB
2526
2527 order_mock.reset_mock()
2528 new_order_mock.reset_mock()
2529 trade.orders = []
f86ee140 2530 self.m.report.log_order.reset_mock()
1aa7d4fa
IB
2531
2532 for i in [8, 9, 11, 12]:
f86ee140 2533 with self.subTest(tick=i):
1aa7d4fa
IB
2534 trade.update_order(order_mock, i)
2535 order_mock.cancel.assert_not_called()
2536 new_order_mock.run.assert_not_called()
f86ee140 2537 self.m.report.log_order.assert_called_once_with(order_mock, i, update="waiting",
3d0247f9 2538 compute_value=None, new_order=None)
1aa7d4fa
IB
2539
2540 order_mock.reset_mock()
2541 new_order_mock.reset_mock()
2542 trade.orders = []
f86ee140 2543 self.m.report.log_order.reset_mock()
cfab619d 2544
cfab619d 2545
f86ee140 2546 def test_print_with_order(self):
c51687d2
IB
2547 value_from = portfolio.Amount("BTC", "0.5")
2548 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2549 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2550 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2
IB
2551
2552 order_mock1 = mock.Mock()
2553 order_mock1.__repr__ = mock.Mock()
2554 order_mock1.__repr__.return_value = "Mock 1"
2555 order_mock2 = mock.Mock()
2556 order_mock2.__repr__ = mock.Mock()
2557 order_mock2.__repr__.return_value = "Mock 2"
c31df868
IB
2558 order_mock1.mouvements = []
2559 mouvement_mock1 = mock.Mock()
2560 mouvement_mock1.__repr__ = mock.Mock()
2561 mouvement_mock1.__repr__.return_value = "Mouvement 1"
2562 mouvement_mock2 = mock.Mock()
2563 mouvement_mock2.__repr__ = mock.Mock()
2564 mouvement_mock2.__repr__.return_value = "Mouvement 2"
2565 order_mock2.mouvements = [
2566 mouvement_mock1, mouvement_mock2
2567 ]
c51687d2
IB
2568 trade.orders.append(order_mock1)
2569 trade.orders.append(order_mock2)
2570
f9226903
IB
2571 with mock.patch.object(trade, "filled_amount") as filled:
2572 filled.return_value = portfolio.Amount("BTC", "0.1")
c51687d2 2573
f9226903
IB
2574 trade.print_with_order()
2575
2576 self.m.report.print_log.assert_called()
2577 calls = self.m.report.print_log.mock_calls
2578 self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls[0][1][0]))
2579 self.assertEqual("\tMock 1", str(calls[1][1][0]))
2580 self.assertEqual("\tMock 2", str(calls[2][1][0]))
2581 self.assertEqual("\t\tMouvement 1", str(calls[3][1][0]))
2582 self.assertEqual("\t\tMouvement 2", str(calls[4][1][0]))
2583
2584 self.m.report.print_log.reset_mock()
2585
2586 filled.return_value = portfolio.Amount("BTC", "0.5")
2587 trade.print_with_order()
2588 calls = self.m.report.print_log.mock_calls
2589 self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls[0][1][0]))
2590
2591 self.m.report.print_log.reset_mock()
2592
2593 filled.return_value = portfolio.Amount("BTC", "0.1")
2594 trade.closed = True
2595 trade.print_with_order()
2596 calls = self.m.report.print_log.mock_calls
2597 self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls[0][1][0]))
c51687d2 2598
17598517
IB
2599 def test_close(self):
2600 value_from = portfolio.Amount("BTC", "0.5")
2601 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2602 value_to = portfolio.Amount("BTC", "1.0")
2603 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
f9226903
IB
2604 order1 = mock.Mock()
2605 trade.orders.append(order1)
17598517
IB
2606
2607 trade.close()
2608
2609 self.assertEqual(True, trade.closed)
f9226903 2610 order1.cancel.assert_called_once_with()
17598517
IB
2611
2612 def test_pending(self):
2613 value_from = portfolio.Amount("BTC", "0.5")
2614 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2615 value_to = portfolio.Amount("BTC", "1.0")
2616 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
2617
2618 trade.closed = True
2619 self.assertEqual(False, trade.pending)
2620
2621 trade.closed = False
2622 self.assertEqual(True, trade.pending)
2623
2624 order1 = mock.Mock()
2625 order1.filled_amount.return_value = portfolio.Amount("BTC", "0.5")
2626 trade.orders.append(order1)
2627 self.assertEqual(False, trade.pending)
2628
cfab619d 2629 def test__repr(self):
c51687d2
IB
2630 value_from = portfolio.Amount("BTC", "0.5")
2631 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2632 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2633 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
c51687d2
IB
2634
2635 self.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade))
cfab619d 2636
3d0247f9
IB
2637 def test_as_json(self):
2638 value_from = portfolio.Amount("BTC", "0.5")
2639 value_from.linked_to = portfolio.Amount("ETH", "10.0")
2640 value_to = portfolio.Amount("BTC", "1.0")
f86ee140 2641 trade = portfolio.Trade(value_from, value_to, "ETH", self.m)
3d0247f9
IB
2642
2643 as_json = trade.as_json()
2644 self.assertEqual("acquire", as_json["action"])
2645 self.assertEqual(D("0.5"), as_json["from"])
2646 self.assertEqual(D("1.0"), as_json["to"])
2647 self.assertEqual("ETH", as_json["currency"])
2648 self.assertEqual("BTC", as_json["base_currency"])
2649
5a72ded7
IB
2650@unittest.skipUnless("unit" in limits, "Unit skipped")
2651class OrderTest(WebMockTestCase):
2652 def test_values(self):
2653 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2654 D("0.1"), "BTC", "long", "market", "trade")
2655 self.assertEqual("buy", order.action)
2656 self.assertEqual(10, order.amount.value)
2657 self.assertEqual("ETH", order.amount.currency)
2658 self.assertEqual(D("0.1"), order.rate)
2659 self.assertEqual("BTC", order.base_currency)
2660 self.assertEqual("market", order.market)
2661 self.assertEqual("long", order.trade_type)
2662 self.assertEqual("pending", order.status)
2663 self.assertEqual("trade", order.trade)
2664 self.assertIsNone(order.id)
2665 self.assertFalse(order.close_if_possible)
2666
2667 def test__repr(self):
2668 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2669 D("0.1"), "BTC", "long", "market", "trade")
2670 self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order))
2671
2672 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2673 D("0.1"), "BTC", "long", "market", "trade",
2674 close_if_possible=True)
2675 self.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order))
2676
3d0247f9
IB
2677 def test_as_json(self):
2678 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2679 D("0.1"), "BTC", "long", "market", "trade")
2680 mouvement_mock1 = mock.Mock()
2681 mouvement_mock1.as_json.return_value = 1
2682 mouvement_mock2 = mock.Mock()
2683 mouvement_mock2.as_json.return_value = 2
2684
2685 order.mouvements = [mouvement_mock1, mouvement_mock2]
2686 as_json = order.as_json()
2687 self.assertEqual("buy", as_json["action"])
2688 self.assertEqual("long", as_json["trade_type"])
2689 self.assertEqual(10, as_json["amount"])
2690 self.assertEqual("ETH", as_json["currency"])
2691 self.assertEqual("BTC", as_json["base_currency"])
2692 self.assertEqual(D("0.1"), as_json["rate"])
2693 self.assertEqual("pending", as_json["status"])
2694 self.assertEqual(False, as_json["close_if_possible"])
2695 self.assertIsNone(as_json["id"])
2696 self.assertEqual([1, 2], as_json["mouvements"])
2697
5a72ded7
IB
2698 def test_account(self):
2699 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2700 D("0.1"), "BTC", "long", "market", "trade")
2701 self.assertEqual("exchange", order.account)
2702
2703 order = portfolio.Order("sell", portfolio.Amount("ETH", 10),
2704 D("0.1"), "BTC", "short", "market", "trade")
2705 self.assertEqual("margin", order.account)
2706
2707 def test_pending(self):
2708 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2709 D("0.1"), "BTC", "long", "market", "trade")
2710 self.assertTrue(order.pending)
2711 order.status = "open"
2712 self.assertFalse(order.pending)
2713
2714 def test_open(self):
2715 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2716 D("0.1"), "BTC", "long", "market", "trade")
2717 self.assertFalse(order.open)
2718 order.status = "open"
2719 self.assertTrue(order.open)
2720
2721 def test_finished(self):
2722 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2723 D("0.1"), "BTC", "long", "market", "trade")
2724 self.assertFalse(order.finished)
2725 order.status = "closed"
2726 self.assertTrue(order.finished)
2727 order.status = "canceled"
2728 self.assertTrue(order.finished)
2729 order.status = "error"
2730 self.assertTrue(order.finished)
2731
2732 @mock.patch.object(portfolio.Order, "fetch")
f86ee140 2733 def test_cancel(self, fetch):
f9226903
IB
2734 with self.subTest(debug=True):
2735 self.m.debug = True
2736 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2737 D("0.1"), "BTC", "long", self.m, "trade")
2738 order.status = "open"
5a72ded7 2739
f9226903
IB
2740 order.cancel()
2741 self.m.ccxt.cancel_order.assert_not_called()
2742 self.m.report.log_debug_action.assert_called_once()
2743 self.m.report.log_debug_action.reset_mock()
2744 self.assertEqual("canceled", order.status)
5a72ded7 2745
f9226903
IB
2746 with self.subTest(desc="Nominal case"):
2747 self.m.debug = False
2748 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2749 D("0.1"), "BTC", "long", self.m, "trade")
2750 order.status = "open"
2751 order.id = 42
2752
2753 order.cancel()
2754 self.m.ccxt.cancel_order.assert_called_with(42)
2755 fetch.assert_called_once_with()
2756 self.m.report.log_debug_action.assert_not_called()
2757
2758 with self.subTest(exception=True):
2759 self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound
2760 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2761 D("0.1"), "BTC", "long", self.m, "trade")
2762 order.status = "open"
2763 order.id = 42
2764 order.cancel()
2765 self.m.ccxt.cancel_order.assert_called_with(42)
2766 self.m.report.log_error.assert_called_once()
2767
2768 self.m.reset_mock()
2769 with self.subTest(id=None):
2770 self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound
2771 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2772 D("0.1"), "BTC", "long", self.m, "trade")
2773 order.status = "open"
2774 order.cancel()
2775 self.m.ccxt.cancel_order.assert_not_called()
2776
2777 self.m.reset_mock()
2778 with self.subTest(open=False):
2779 self.m.ccxt.cancel_order.side_effect = portfolio.OrderNotFound
2780 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2781 D("0.1"), "BTC", "long", self.m, "trade")
2782 order.status = "closed"
2783 order.cancel()
2784 self.m.ccxt.cancel_order.assert_not_called()
5a72ded7
IB
2785
2786 def test_dust_amount_remaining(self):
2787 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2788 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7
IB
2789 order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", 1))
2790 self.assertFalse(order.dust_amount_remaining())
2791
2792 order.remaining_amount = mock.Mock(return_value=portfolio.Amount("ETH", D("0.0001")))
2793 self.assertTrue(order.dust_amount_remaining())
2794
2795 @mock.patch.object(portfolio.Order, "fetch")
2796 @mock.patch.object(portfolio.Order, "filled_amount", return_value=portfolio.Amount("ETH", 1))
2797 def test_remaining_amount(self, filled_amount, fetch):
2798 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2799 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7
IB
2800
2801 self.assertEqual(9, order.remaining_amount().value)
5a72ded7
IB
2802
2803 order.status = "open"
2804 self.assertEqual(9, order.remaining_amount().value)
5a72ded7
IB
2805
2806 @mock.patch.object(portfolio.Order, "fetch")
2807 def test_filled_amount(self, fetch):
2808 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2809 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7 2810 order.mouvements.append(portfolio.Mouvement("ETH", "BTC", {
df9e4e7f 2811 "tradeID": 42, "type": "buy", "fee": "0.0015",
5a72ded7
IB
2812 "date": "2017-12-30 12:00:12", "rate": "0.1",
2813 "amount": "3", "total": "0.3"
2814 }))
2815 order.mouvements.append(portfolio.Mouvement("ETH", "BTC", {
df9e4e7f 2816 "tradeID": 43, "type": "buy", "fee": "0.0015",
5a72ded7
IB
2817 "date": "2017-12-30 13:00:12", "rate": "0.2",
2818 "amount": "2", "total": "0.4"
2819 }))
2820 self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount())
2821 fetch.assert_not_called()
2822 order.status = "open"
2823 self.assertEqual(portfolio.Amount("ETH", 5), order.filled_amount(in_base_currency=False))
2824 fetch.assert_called_once()
2825 self.assertEqual(portfolio.Amount("BTC", "0.7"), order.filled_amount(in_base_currency=True))
2826
2827 def test_fetch_mouvements(self):
f86ee140 2828 self.m.ccxt.privatePostReturnOrderTrades.return_value = [
5a72ded7 2829 {
df9e4e7f 2830 "tradeID": 42, "type": "buy", "fee": "0.0015",
5a72ded7
IB
2831 "date": "2017-12-30 12:00:12", "rate": "0.1",
2832 "amount": "3", "total": "0.3"
2833 },
2834 {
df9e4e7f 2835 "tradeID": 43, "type": "buy", "fee": "0.0015",
5a72ded7
IB
2836 "date": "2017-12-30 13:00:12", "rate": "0.2",
2837 "amount": "2", "total": "0.4"
2838 }
2839 ]
2840 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2841 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7
IB
2842 order.id = 12
2843 order.mouvements = ["Foo", "Bar", "Baz"]
2844
2845 order.fetch_mouvements()
2846
f86ee140 2847 self.m.ccxt.privatePostReturnOrderTrades.assert_called_with({"orderNumber": 12})
5a72ded7
IB
2848 self.assertEqual(2, len(order.mouvements))
2849 self.assertEqual(42, order.mouvements[0].id)
2850 self.assertEqual(43, order.mouvements[1].id)
2851
f86ee140 2852 self.m.ccxt.privatePostReturnOrderTrades.side_effect = portfolio.ExchangeError
df9e4e7f 2853 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2854 D("0.1"), "BTC", "long", self.m, "trade")
df9e4e7f
IB
2855 order.fetch_mouvements()
2856 self.assertEqual(0, len(order.mouvements))
2857
f86ee140 2858 def test_mark_finished_order(self):
5a72ded7 2859 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2860 D("0.1"), "BTC", "short", self.m, "trade",
5a72ded7
IB
2861 close_if_possible=True)
2862 order.status = "closed"
f86ee140 2863 self.m.debug = False
5a72ded7
IB
2864
2865 order.mark_finished_order()
f86ee140
IB
2866 self.m.ccxt.close_margin_position.assert_called_with("ETH", "BTC")
2867 self.m.ccxt.close_margin_position.reset_mock()
5a72ded7
IB
2868
2869 order.status = "open"
2870 order.mark_finished_order()
f86ee140 2871 self.m.ccxt.close_margin_position.assert_not_called()
5a72ded7
IB
2872
2873 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2874 D("0.1"), "BTC", "short", self.m, "trade",
5a72ded7
IB
2875 close_if_possible=False)
2876 order.status = "closed"
2877 order.mark_finished_order()
f86ee140 2878 self.m.ccxt.close_margin_position.assert_not_called()
5a72ded7
IB
2879
2880 order = portfolio.Order("sell", portfolio.Amount("ETH", 10),
f86ee140 2881 D("0.1"), "BTC", "short", self.m, "trade",
5a72ded7
IB
2882 close_if_possible=True)
2883 order.status = "closed"
2884 order.mark_finished_order()
f86ee140 2885 self.m.ccxt.close_margin_position.assert_not_called()
5a72ded7
IB
2886
2887 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2888 D("0.1"), "BTC", "long", self.m, "trade",
5a72ded7
IB
2889 close_if_possible=True)
2890 order.status = "closed"
2891 order.mark_finished_order()
f86ee140 2892 self.m.ccxt.close_margin_position.assert_not_called()
5a72ded7 2893
f86ee140 2894 self.m.debug = True
5a72ded7
IB
2895
2896 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2897 D("0.1"), "BTC", "short", self.m, "trade",
5a72ded7
IB
2898 close_if_possible=True)
2899 order.status = "closed"
2900
2901 order.mark_finished_order()
f86ee140
IB
2902 self.m.ccxt.close_margin_position.assert_not_called()
2903 self.m.report.log_debug_action.assert_called_once()
5a72ded7
IB
2904
2905 @mock.patch.object(portfolio.Order, "fetch_mouvements")
d8deb0e9
IB
2906 @mock.patch.object(portfolio.Order, "mark_finished_order")
2907 def test_fetch(self, mark_finished_order, fetch_mouvements):
aca4d437
IB
2908 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
2909 D("0.1"), "BTC", "long", self.m, "trade")
2910 order.id = 45
2911 with self.subTest(debug=True):
2912 self.m.debug = True
2913 order.fetch()
2914 self.m.report.log_debug_action.assert_called_once()
2915 self.m.report.log_debug_action.reset_mock()
2916 self.m.ccxt.fetch_order.assert_not_called()
d8deb0e9 2917 mark_finished_order.assert_not_called()
aca4d437 2918 fetch_mouvements.assert_not_called()
5a72ded7 2919
aca4d437
IB
2920 with self.subTest(debug=False):
2921 self.m.debug = False
2922 self.m.ccxt.fetch_order.return_value = {
2923 "status": "foo",
2924 "datetime": "timestamp"
2925 }
2926 order.fetch()
5a72ded7 2927
f9226903 2928 self.m.ccxt.fetch_order.assert_called_once_with(45)
aca4d437
IB
2929 fetch_mouvements.assert_called_once()
2930 self.assertEqual("foo", order.status)
2931 self.assertEqual("timestamp", order.timestamp)
2932 self.assertEqual(1, len(order.results))
2933 self.m.report.log_debug_action.assert_not_called()
d8deb0e9 2934 mark_finished_order.assert_called_once()
5a72ded7 2935
d8deb0e9 2936 mark_finished_order.reset_mock()
aca4d437
IB
2937 with self.subTest(missing_order=True):
2938 self.m.ccxt.fetch_order.side_effect = [
2939 portfolio.OrderNotCached,
2940 ]
5a72ded7 2941 order.fetch()
aca4d437 2942 self.assertEqual("closed_unknown", order.status)
d8deb0e9 2943 mark_finished_order.assert_called_once()
5a72ded7
IB
2944
2945 @mock.patch.object(portfolio.Order, "fetch")
d8deb0e9 2946 def test_get_status(self, fetch):
5a72ded7 2947 with self.subTest(debug=True):
f86ee140 2948 self.m.debug = True
5a72ded7 2949 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2950 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7
IB
2951 self.assertEqual("pending", order.get_status())
2952 fetch.assert_not_called()
f86ee140 2953 self.m.report.log_debug_action.assert_called_once()
5a72ded7
IB
2954
2955 with self.subTest(debug=False, finished=False):
f86ee140 2956 self.m.debug = False
5a72ded7 2957 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2958 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7
IB
2959 def _fetch(order):
2960 def update_status():
2961 order.status = "open"
2962 return update_status
2963 fetch.side_effect = _fetch(order)
2964 self.assertEqual("open", order.get_status())
5a72ded7
IB
2965 fetch.assert_called_once()
2966
5a72ded7
IB
2967 fetch.reset_mock()
2968 with self.subTest(debug=False, finished=True):
f86ee140 2969 self.m.debug = False
5a72ded7 2970 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2971 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7
IB
2972 def _fetch(order):
2973 def update_status():
2974 order.status = "closed"
2975 return update_status
2976 fetch.side_effect = _fetch(order)
2977 self.assertEqual("closed", order.get_status())
5a72ded7
IB
2978 fetch.assert_called_once()
2979
2980 def test_run(self):
f86ee140
IB
2981 self.m.ccxt.order_precision.return_value = 4
2982 with self.subTest(debug=True):
2983 self.m.debug = True
5a72ded7 2984 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140 2985 D("0.1"), "BTC", "long", self.m, "trade")
5a72ded7 2986 order.run()
f86ee140
IB
2987 self.m.ccxt.create_order.assert_not_called()
2988 self.m.report.log_debug_action.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
5a72ded7
IB
2989 self.assertEqual("open", order.status)
2990 self.assertEqual(1, len(order.results))
2991 self.assertEqual(-1, order.id)
2992
f86ee140 2993 self.m.ccxt.create_order.reset_mock()
5a72ded7 2994 with self.subTest(debug=False):
f86ee140 2995 self.m.debug = False
5a72ded7 2996 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140
IB
2997 D("0.1"), "BTC", "long", self.m, "trade")
2998 self.m.ccxt.create_order.return_value = { "id": 123 }
5a72ded7 2999 order.run()
f86ee140 3000 self.m.ccxt.create_order.assert_called_once()
5a72ded7
IB
3001 self.assertEqual(1, len(order.results))
3002 self.assertEqual("open", order.status)
3003
f86ee140
IB
3004 self.m.ccxt.create_order.reset_mock()
3005 with self.subTest(exception=True):
5a72ded7 3006 order = portfolio.Order("buy", portfolio.Amount("ETH", 10),
f86ee140
IB
3007 D("0.1"), "BTC", "long", self.m, "trade")
3008 self.m.ccxt.create_order.side_effect = Exception("bouh")
5a72ded7 3009 order.run()
f86ee140 3010 self.m.ccxt.create_order.assert_called_once()
5a72ded7
IB
3011 self.assertEqual(0, len(order.results))
3012 self.assertEqual("error", order.status)
f86ee140 3013 self.m.report.log_error.assert_called_once()
5a72ded7 3014
f86ee140 3015 self.m.ccxt.create_order.reset_mock()
df9e4e7f
IB
3016 with self.subTest(dust_amount_exception=True),\
3017 mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order:
3018 order = portfolio.Order("buy", portfolio.Amount("ETH", 0.001),
f86ee140 3019 D("0.1"), "BTC", "long", self.m, "trade")
f70bb858 3020 self.m.ccxt.create_order.side_effect = portfolio.InvalidOrder
df9e4e7f 3021 order.run()
f86ee140 3022 self.m.ccxt.create_order.assert_called_once()
df9e4e7f
IB
3023 self.assertEqual(0, len(order.results))
3024 self.assertEqual("closed", order.status)
3025 mark_finished_order.assert_called_once()
3026
f70bb858 3027 self.m.ccxt.order_precision.return_value = 8
d24bb10c 3028 self.m.ccxt.create_order.reset_mock()
f70bb858 3029 with self.subTest(insufficient_funds=True),\
d24bb10c 3030 mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order:
f70bb858 3031 order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"),
d24bb10c 3032 D("0.1"), "BTC", "long", self.m, "trade")
f70bb858
IB
3033 self.m.ccxt.create_order.side_effect = [
3034 portfolio.InsufficientFunds,
3035 portfolio.InsufficientFunds,
3036 portfolio.InsufficientFunds,
3037 { "id": 123 },
3038 ]
d24bb10c 3039 order.run()
f70bb858
IB
3040 self.m.ccxt.create_order.assert_has_calls([
3041 mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')),
3042 mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')),
3043 mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')),
3044 mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')),
3045 ])
3046 self.assertEqual(4, self.m.ccxt.create_order.call_count)
3047 self.assertEqual(1, len(order.results))
3048 self.assertEqual("open", order.status)
3049 self.assertEqual(4, order.tries)
3050 self.m.report.log_error.assert_called()
3051 self.assertEqual(4, self.m.report.log_error.call_count)
3052
3053 self.m.ccxt.order_precision.return_value = 8
3054 self.m.ccxt.create_order.reset_mock()
3055 self.m.report.log_error.reset_mock()
3056 with self.subTest(insufficient_funds=True),\
3057 mock.patch.object(portfolio.Order, "mark_finished_order") as mark_finished_order:
3058 order = portfolio.Order("buy", portfolio.Amount("ETH", "0.001"),
3059 D("0.1"), "BTC", "long", self.m, "trade")
3060 self.m.ccxt.create_order.side_effect = [
3061 portfolio.InsufficientFunds,
3062 portfolio.InsufficientFunds,
3063 portfolio.InsufficientFunds,
3064 portfolio.InsufficientFunds,
3065 portfolio.InsufficientFunds,
3066 ]
3067 order.run()
3068 self.m.ccxt.create_order.assert_has_calls([
3069 mock.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account='exchange', price=D('0.1')),
3070 mock.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account='exchange', price=D('0.1')),
3071 mock.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account='exchange', price=D('0.1')),
3072 mock.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account='exchange', price=D('0.1')),
3073 mock.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account='exchange', price=D('0.1')),
3074 ])
3075 self.assertEqual(5, self.m.ccxt.create_order.call_count)
d24bb10c 3076 self.assertEqual(0, len(order.results))
f70bb858
IB
3077 self.assertEqual("error", order.status)
3078 self.assertEqual(5, order.tries)
3079 self.m.report.log_error.assert_called()
3080 self.assertEqual(5, self.m.report.log_error.call_count)
3081 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)
d24bb10c 3082
df9e4e7f 3083
5a72ded7
IB
3084@unittest.skipUnless("unit" in limits, "Unit skipped")
3085class MouvementTest(WebMockTestCase):
3086 def test_values(self):
3087 mouvement = portfolio.Mouvement("ETH", "BTC", {
df9e4e7f 3088 "tradeID": 42, "type": "buy", "fee": "0.0015",
5a72ded7
IB
3089 "date": "2017-12-30 12:00:12", "rate": "0.1",
3090 "amount": "10", "total": "1"
3091 })
3092 self.assertEqual("ETH", mouvement.currency)
3093 self.assertEqual("BTC", mouvement.base_currency)
3094 self.assertEqual(42, mouvement.id)
3095 self.assertEqual("buy", mouvement.action)
3096 self.assertEqual(D("0.0015"), mouvement.fee_rate)
3097 self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), mouvement.date)
3098 self.assertEqual(D("0.1"), mouvement.rate)
3099 self.assertEqual(portfolio.Amount("ETH", "10"), mouvement.total)
3100 self.assertEqual(portfolio.Amount("BTC", "1"), mouvement.total_in_base)
3101
df9e4e7f
IB
3102 mouvement = portfolio.Mouvement("ETH", "BTC", { "foo": "bar" })
3103 self.assertIsNone(mouvement.date)
3104 self.assertIsNone(mouvement.id)
3105 self.assertIsNone(mouvement.action)
3106 self.assertEqual(-1, mouvement.fee_rate)
3107 self.assertEqual(0, mouvement.rate)
3108 self.assertEqual(portfolio.Amount("ETH", 0), mouvement.total)
3109 self.assertEqual(portfolio.Amount("BTC", 0), mouvement.total_in_base)
3110
c31df868
IB
3111 def test__repr(self):
3112 mouvement = portfolio.Mouvement("ETH", "BTC", {
3113 "tradeID": 42, "type": "buy", "fee": "0.0015",
3114 "date": "2017-12-30 12:00:12", "rate": "0.1",
3115 "amount": "10", "total": "1"
3116 })
3117 self.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement))
3d0247f9 3118
c31df868
IB
3119 mouvement = portfolio.Mouvement("ETH", "BTC", {
3120 "tradeID": 42, "type": "buy",
3121 "date": "garbage", "rate": "0.1",
3122 "amount": "10", "total": "1"
3123 })
3124 self.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement))
3125
3d0247f9
IB
3126 def test_as_json(self):
3127 mouvement = portfolio.Mouvement("ETH", "BTC", {
3128 "tradeID": 42, "type": "buy", "fee": "0.0015",
3129 "date": "2017-12-30 12:00:12", "rate": "0.1",
3130 "amount": "10", "total": "1"
3131 })
3132 as_json = mouvement.as_json()
3133
3134 self.assertEqual(D("0.0015"), as_json["fee_rate"])
3135 self.assertEqual(portfolio.datetime(2017, 12, 30, 12, 0, 12), as_json["date"])
3136 self.assertEqual("buy", as_json["action"])
3137 self.assertEqual(D("10"), as_json["total"])
3138 self.assertEqual(D("1"), as_json["total_in_base"])
3139 self.assertEqual("BTC", as_json["base_currency"])
3140 self.assertEqual("ETH", as_json["currency"])
3141
3142@unittest.skipUnless("unit" in limits, "Unit skipped")
3143class ReportStoreTest(WebMockTestCase):
3144 def test_add_log(self):
f86ee140
IB
3145 report_store = market.ReportStore(self.m)
3146 report_store.add_log({"foo": "bar"})
3d0247f9 3147
f86ee140 3148 self.assertEqual({"foo": "bar", "date": mock.ANY}, report_store.logs[0])
3d0247f9
IB
3149
3150 def test_set_verbose(self):
f86ee140 3151 report_store = market.ReportStore(self.m)
3d0247f9 3152 with self.subTest(verbose=True):
f86ee140
IB
3153 report_store.set_verbose(True)
3154 self.assertTrue(report_store.verbose_print)
3d0247f9
IB
3155
3156 with self.subTest(verbose=False):
f86ee140
IB
3157 report_store.set_verbose(False)
3158 self.assertFalse(report_store.verbose_print)
3d0247f9 3159
9bde69bf
IB
3160 def test_merge(self):
3161 report_store1 = market.ReportStore(self.m, verbose_print=False)
3162 report_store2 = market.ReportStore(None, verbose_print=False)
3163
3164 report_store2.log_stage("1")
3165 report_store1.log_stage("2")
3166 report_store2.log_stage("3")
3167
3168 report_store1.merge(report_store2)
3169
3170 self.assertEqual(3, len(report_store1.logs))
3171 self.assertEqual(["1", "2", "3"], list(map(lambda x: x["stage"], report_store1.logs)))
718e3e91 3172 self.assertEqual(6, len(report_store1.print_logs))
9bde69bf 3173
3d0247f9 3174 def test_print_log(self):
f86ee140 3175 report_store = market.ReportStore(self.m)
3d0247f9 3176 with self.subTest(verbose=True),\
718e3e91 3177 mock.patch.object(store, "datetime") as time_mock,\
3d0247f9 3178 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
718e3e91 3179 time_mock.now.return_value = datetime.datetime(2018, 2, 25, 2, 20, 10)
f86ee140
IB
3180 report_store.set_verbose(True)
3181 report_store.print_log("Coucou")
3182 report_store.print_log(portfolio.Amount("BTC", 1))
718e3e91 3183 self.assertEqual(stdout_mock.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n")
3d0247f9
IB
3184
3185 with self.subTest(verbose=False),\
3186 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
f86ee140
IB
3187 report_store.set_verbose(False)
3188 report_store.print_log("Coucou")
3189 report_store.print_log(portfolio.Amount("BTC", 1))
3d0247f9
IB
3190 self.assertEqual(stdout_mock.getvalue(), "")
3191
b4e0ba0b
IB
3192 def test_default_json_serial(self):
3193 report_store = market.ReportStore(self.m)
3194
3195 self.assertEqual("2018-02-24T00:00:00",
3196 report_store.default_json_serial(portfolio.datetime(2018, 2, 24)))
3197 self.assertEqual("1.00000000 BTC",
3198 report_store.default_json_serial(portfolio.Amount("BTC", 1)))
3199
3d0247f9 3200 def test_to_json(self):
f86ee140
IB
3201 report_store = market.ReportStore(self.m)
3202 report_store.logs.append({"foo": "bar"})
c5a7f286 3203 self.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store.to_json())
f86ee140 3204 report_store.logs.append({"date": portfolio.datetime(2018, 2, 24)})
c5a7f286 3205 self.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store.to_json())
f86ee140 3206 report_store.logs.append({"amount": portfolio.Amount("BTC", 1)})
c5a7f286 3207 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())
3d0247f9 3208
b4e0ba0b
IB
3209 def test_to_json_array(self):
3210 report_store = market.ReportStore(self.m)
3211 report_store.logs.append({
3212 "date": "date1", "type": "type1", "foo": "bar", "bla": "bla"
3213 })
3214 report_store.logs.append({
3215 "date": "date2", "type": "type2", "foo": "bar", "bla": "bla"
3216 })
3217 logs = list(report_store.to_json_array())
3218
3219 self.assertEqual(2, len(logs))
3220 self.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[0])
3221 self.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs[1])
3222
f86ee140
IB
3223 @mock.patch.object(market.ReportStore, "print_log")
3224 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3225 def test_log_stage(self, add_log, print_log):
f86ee140 3226 report_store = market.ReportStore(self.m)
7bd830a8
IB
3227 c = lambda x: x
3228 report_store.log_stage("foo", bar="baz", c=c, d=portfolio.Amount("BTC", 1))
3d0247f9
IB
3229 print_log.assert_has_calls([
3230 mock.call("-----------"),
7bd830a8 3231 mock.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
3d0247f9 3232 ])
7bd830a8
IB
3233 add_log.assert_called_once_with({
3234 'type': 'stage',
3235 'stage': 'foo',
3236 'args': {
3237 'bar': 'baz',
3238 'c': 'c = lambda x: x',
3239 'd': {
3240 'currency': 'BTC',
3241 'value': D('1')
3242 }
3243 }
3244 })
3d0247f9 3245
f86ee140
IB
3246 @mock.patch.object(market.ReportStore, "print_log")
3247 @mock.patch.object(market.ReportStore, "add_log")
3248 def test_log_balances(self, add_log, print_log):
3249 report_store = market.ReportStore(self.m)
3250 self.m.balances.as_json.return_value = "json"
3251 self.m.balances.all = { "FOO": "bar", "BAR": "baz" }
3d0247f9 3252
f86ee140 3253 report_store.log_balances(tag="tag")
3d0247f9
IB
3254 print_log.assert_has_calls([
3255 mock.call("[Balance]"),
3256 mock.call("\tbar"),
3257 mock.call("\tbaz"),
3258 ])
18167a3c
IB
3259 add_log.assert_called_once_with({
3260 'type': 'balance',
3261 'balances': 'json',
3262 'tag': 'tag'
3263 })
3d0247f9 3264
f86ee140
IB
3265 @mock.patch.object(market.ReportStore, "print_log")
3266 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3267 def test_log_tickers(self, add_log, print_log):
f86ee140 3268 report_store = market.ReportStore(self.m)
3d0247f9
IB
3269 amounts = {
3270 "BTC": portfolio.Amount("BTC", 10),
3271 "ETH": portfolio.Amount("BTC", D("0.3"))
3272 }
3273 amounts["ETH"].rate = D("0.1")
3274
f86ee140 3275 report_store.log_tickers(amounts, "BTC", "default", "total")
3d0247f9
IB
3276 print_log.assert_not_called()
3277 add_log.assert_called_once_with({
3278 'type': 'tickers',
3279 'compute_value': 'default',
3280 'balance_type': 'total',
3281 'currency': 'BTC',
3282 'balances': {
3283 'BTC': D('10'),
3284 'ETH': D('0.3')
3285 },
3286 'rates': {
3287 'BTC': None,
3288 'ETH': D('0.1')
3289 },
3290 'total': D('10.3')
3291 })
3292
aca4d437
IB
3293 add_log.reset_mock()
3294 compute_value = lambda x: x["bid"]
3295 report_store.log_tickers(amounts, "BTC", compute_value, "total")
3296 add_log.assert_called_once_with({
3297 'type': 'tickers',
3298 'compute_value': 'compute_value = lambda x: x["bid"]',
3299 'balance_type': 'total',
3300 'currency': 'BTC',
3301 'balances': {
3302 'BTC': D('10'),
3303 'ETH': D('0.3')
3304 },
3305 'rates': {
3306 'BTC': None,
3307 'ETH': D('0.1')
3308 },
3309 'total': D('10.3')
3310 })
3311
f86ee140
IB
3312 @mock.patch.object(market.ReportStore, "print_log")
3313 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3314 def test_log_dispatch(self, add_log, print_log):
f86ee140 3315 report_store = market.ReportStore(self.m)
3d0247f9
IB
3316 amount = portfolio.Amount("BTC", "10.3")
3317 amounts = {
3318 "BTC": portfolio.Amount("BTC", 10),
3319 "ETH": portfolio.Amount("BTC", D("0.3"))
3320 }
f86ee140 3321 report_store.log_dispatch(amount, amounts, "medium", "repartition")
3d0247f9
IB
3322 print_log.assert_not_called()
3323 add_log.assert_called_once_with({
3324 'type': 'dispatch',
3325 'liquidity': 'medium',
3326 'repartition_ratio': 'repartition',
3327 'total_amount': {
3328 'currency': 'BTC',
3329 'value': D('10.3')
3330 },
3331 'repartition': {
3332 'BTC': D('10'),
3333 'ETH': D('0.3')
3334 }
3335 })
3336
f86ee140
IB
3337 @mock.patch.object(market.ReportStore, "print_log")
3338 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3339 def test_log_trades(self, add_log, print_log):
f86ee140 3340 report_store = market.ReportStore(self.m)
3d0247f9
IB
3341 trade_mock1 = mock.Mock()
3342 trade_mock2 = mock.Mock()
3343 trade_mock1.as_json.return_value = { "trade": "1" }
3344 trade_mock2.as_json.return_value = { "trade": "2" }
3345
3346 matching_and_trades = [
3347 (True, trade_mock1),
3348 (False, trade_mock2),
3349 ]
f86ee140 3350 report_store.log_trades(matching_and_trades, "only")
3d0247f9
IB
3351
3352 print_log.assert_not_called()
3353 add_log.assert_called_with({
3354 'type': 'trades',
3355 'only': 'only',
f86ee140 3356 'debug': False,
3d0247f9
IB
3357 'trades': [
3358 {'trade': '1', 'skipped': False},
3359 {'trade': '2', 'skipped': True}
3360 ]
3361 })
3362
f86ee140
IB
3363 @mock.patch.object(market.ReportStore, "print_log")
3364 @mock.patch.object(market.ReportStore, "add_log")
3365 def test_log_orders(self, add_log, print_log):
3366 report_store = market.ReportStore(self.m)
3367
3d0247f9
IB
3368 order_mock1 = mock.Mock()
3369 order_mock2 = mock.Mock()
3370
3371 order_mock1.as_json.return_value = "order1"
3372 order_mock2.as_json.return_value = "order2"
3373
3374 orders = [order_mock1, order_mock2]
3375
f86ee140 3376 report_store.log_orders(orders, tick="tick",
3d0247f9
IB
3377 only="only", compute_value="compute_value")
3378
3379 print_log.assert_called_once_with("[Orders]")
f86ee140 3380 self.m.trades.print_all_with_order.assert_called_once_with(ind="\t")
3d0247f9
IB
3381
3382 add_log.assert_called_with({
3383 'type': 'orders',
3384 'only': 'only',
3385 'compute_value': 'compute_value',
3386 'tick': 'tick',
3387 'orders': ['order1', 'order2']
3388 })
3389
aca4d437
IB
3390 add_log.reset_mock()
3391 def compute_value(x, y):
3392 return x[y]
3393 report_store.log_orders(orders, tick="tick",
3394 only="only", compute_value=compute_value)
3395 add_log.assert_called_with({
3396 'type': 'orders',
3397 'only': 'only',
3398 'compute_value': 'def compute_value(x, y):\n return x[y]',
3399 'tick': 'tick',
3400 'orders': ['order1', 'order2']
3401 })
3402
3403
f86ee140
IB
3404 @mock.patch.object(market.ReportStore, "print_log")
3405 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3406 def test_log_order(self, add_log, print_log):
f86ee140 3407 report_store = market.ReportStore(self.m)
3d0247f9
IB
3408 order_mock = mock.Mock()
3409 order_mock.as_json.return_value = "order"
3410 new_order_mock = mock.Mock()
3411 new_order_mock.as_json.return_value = "new_order"
3412 order_mock.__repr__ = mock.Mock()
3413 order_mock.__repr__.return_value = "Order Mock"
3414 new_order_mock.__repr__ = mock.Mock()
3415 new_order_mock.__repr__.return_value = "New order Mock"
3416
3417 with self.subTest(finished=True):
f86ee140 3418 report_store.log_order(order_mock, 1, finished=True)
3d0247f9
IB
3419 print_log.assert_called_once_with("[Order] Finished Order Mock")
3420 add_log.assert_called_once_with({
3421 'type': 'order',
3422 'tick': 1,
3423 'update': None,
3424 'order': 'order',
3425 'compute_value': None,
3426 'new_order': None
3427 })
3428
3429 add_log.reset_mock()
3430 print_log.reset_mock()
3431
3432 with self.subTest(update="waiting"):
f86ee140 3433 report_store.log_order(order_mock, 1, update="waiting")
3d0247f9
IB
3434 print_log.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
3435 add_log.assert_called_once_with({
3436 'type': 'order',
3437 'tick': 1,
3438 'update': 'waiting',
3439 'order': 'order',
3440 'compute_value': None,
3441 'new_order': None
3442 })
3443
3444 add_log.reset_mock()
3445 print_log.reset_mock()
3446 with self.subTest(update="adjusting"):
aca4d437 3447 compute_value = lambda x: (x["bid"] + x["ask"]*2)/3
f86ee140 3448 report_store.log_order(order_mock, 3,
3d0247f9 3449 update="adjusting", new_order=new_order_mock,
aca4d437 3450 compute_value=compute_value)
3d0247f9
IB
3451 print_log.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
3452 add_log.assert_called_once_with({
3453 'type': 'order',
3454 'tick': 3,
3455 'update': 'adjusting',
3456 'order': 'order',
aca4d437 3457 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
3d0247f9
IB
3458 'new_order': 'new_order'
3459 })
3460
3461 add_log.reset_mock()
3462 print_log.reset_mock()
3463 with self.subTest(update="market_fallback"):
f86ee140 3464 report_store.log_order(order_mock, 7,
3d0247f9
IB
3465 update="market_fallback", new_order=new_order_mock)
3466 print_log.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
3467 add_log.assert_called_once_with({
3468 'type': 'order',
3469 'tick': 7,
3470 'update': 'market_fallback',
3471 'order': 'order',
3472 'compute_value': None,
3473 'new_order': 'new_order'
3474 })
3475
3476 add_log.reset_mock()
3477 print_log.reset_mock()
3478 with self.subTest(update="market_adjusting"):
f86ee140 3479 report_store.log_order(order_mock, 17,
3d0247f9
IB
3480 update="market_adjust", new_order=new_order_mock)
3481 print_log.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
3482 add_log.assert_called_once_with({
3483 'type': 'order',
3484 'tick': 17,
3485 'update': 'market_adjust',
3486 'order': 'order',
3487 'compute_value': None,
3488 'new_order': 'new_order'
3489 })
3490
f86ee140
IB
3491 @mock.patch.object(market.ReportStore, "print_log")
3492 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3493 def test_log_move_balances(self, add_log, print_log):
f86ee140 3494 report_store = market.ReportStore(self.m)
3d0247f9
IB
3495 needed = {
3496 "BTC": portfolio.Amount("BTC", 10),
3497 "USDT": 1
3498 }
3499 moving = {
3500 "BTC": portfolio.Amount("BTC", 3),
3501 "USDT": -2
3502 }
f86ee140 3503 report_store.log_move_balances(needed, moving)
3d0247f9
IB
3504 print_log.assert_not_called()
3505 add_log.assert_called_once_with({
3506 'type': 'move_balances',
f86ee140 3507 'debug': False,
3d0247f9
IB
3508 'needed': {
3509 'BTC': D('10'),
3510 'USDT': 1
3511 },
3512 'moving': {
3513 'BTC': D('3'),
3514 'USDT': -2
3515 }
3516 })
3517
f86ee140
IB
3518 @mock.patch.object(market.ReportStore, "print_log")
3519 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3520 def test_log_http_request(self, add_log, print_log):
f86ee140 3521 report_store = market.ReportStore(self.m)
3d0247f9
IB
3522 response = mock.Mock()
3523 response.status_code = 200
3524 response.text = "Hey"
3525
f86ee140 3526 report_store.log_http_request("method", "url", "body",
3d0247f9
IB
3527 "headers", response)
3528 print_log.assert_not_called()
3529 add_log.assert_called_once_with({
3530 'type': 'http_request',
3531 'method': 'method',
3532 'url': 'url',
3533 'body': 'body',
3534 'headers': 'headers',
3535 'status': 200,
3536 'response': 'Hey'
3537 })
3538
f86ee140
IB
3539 @mock.patch.object(market.ReportStore, "print_log")
3540 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3541 def test_log_error(self, add_log, print_log):
f86ee140 3542 report_store = market.ReportStore(self.m)
3d0247f9 3543 with self.subTest(message=None, exception=None):
f86ee140 3544 report_store.log_error("action")
3d0247f9
IB
3545 print_log.assert_called_once_with("[Error] action")
3546 add_log.assert_called_once_with({
3547 'type': 'error',
3548 'action': 'action',
3549 'exception_class': None,
3550 'exception_message': None,
3551 'message': None
3552 })
3553
3554 print_log.reset_mock()
3555 add_log.reset_mock()
3556 with self.subTest(message="Hey", exception=None):
f86ee140 3557 report_store.log_error("action", message="Hey")
3d0247f9
IB
3558 print_log.assert_has_calls([
3559 mock.call("[Error] action"),
3560 mock.call("\tHey")
3561 ])
3562 add_log.assert_called_once_with({
3563 'type': 'error',
3564 'action': 'action',
3565 'exception_class': None,
3566 'exception_message': None,
3567 'message': "Hey"
3568 })
3569
3570 print_log.reset_mock()
3571 add_log.reset_mock()
3572 with self.subTest(message=None, exception=Exception("bouh")):
f86ee140 3573 report_store.log_error("action", exception=Exception("bouh"))
3d0247f9
IB
3574 print_log.assert_has_calls([
3575 mock.call("[Error] action"),
3576 mock.call("\tException: bouh")
3577 ])
3578 add_log.assert_called_once_with({
3579 'type': 'error',
3580 'action': 'action',
3581 'exception_class': "Exception",
3582 'exception_message': "bouh",
3583 'message': None
3584 })
3585
3586 print_log.reset_mock()
3587 add_log.reset_mock()
3588 with self.subTest(message="Hey", exception=Exception("bouh")):
f86ee140 3589 report_store.log_error("action", message="Hey", exception=Exception("bouh"))
3d0247f9
IB
3590 print_log.assert_has_calls([
3591 mock.call("[Error] action"),
3592 mock.call("\tException: bouh"),
3593 mock.call("\tHey")
3594 ])
3595 add_log.assert_called_once_with({
3596 'type': 'error',
3597 'action': 'action',
3598 'exception_class': "Exception",
3599 'exception_message': "bouh",
3600 'message': "Hey"
3601 })
3602
f86ee140
IB
3603 @mock.patch.object(market.ReportStore, "print_log")
3604 @mock.patch.object(market.ReportStore, "add_log")
3d0247f9 3605 def test_log_debug_action(self, add_log, print_log):
f86ee140
IB
3606 report_store = market.ReportStore(self.m)
3607 report_store.log_debug_action("Hey")
3d0247f9
IB
3608
3609 print_log.assert_called_once_with("[Debug] Hey")
3610 add_log.assert_called_once_with({
3611 'type': 'debug_action',
3612 'action': 'Hey'
3613 })
3614
f86ee140 3615@unittest.skipUnless("unit" in limits, "Unit skipped")
1f117ac7 3616class MainTest(WebMockTestCase):
2033e7fe
IB
3617 def test_make_order(self):
3618 self.m.get_ticker.return_value = {
3619 "inverted": False,
3620 "average": D("0.1"),
3621 "bid": D("0.09"),
3622 "ask": D("0.11"),
3623 }
3624
3625 with self.subTest(description="nominal case"):
1f117ac7 3626 main.make_order(self.m, 10, "ETH")
2033e7fe
IB
3627
3628 self.m.report.log_stage.assert_has_calls([
3629 mock.call("make_order_begin"),
3630 mock.call("make_order_end"),
3631 ])
3632 self.m.balances.fetch_balances.assert_has_calls([
3633 mock.call(tag="make_order_begin"),
3634 mock.call(tag="make_order_end"),
3635 ])
3636 self.m.trades.all.append.assert_called_once()
3637 trade = self.m.trades.all.append.mock_calls[0][1][0]
3638 self.assertEqual(False, trade.orders[0].close_if_possible)
3639 self.assertEqual(0, trade.value_from)
3640 self.assertEqual("ETH", trade.currency)
3641 self.assertEqual("BTC", trade.base_currency)
3642 self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average")
3643 self.m.trades.run_orders.assert_called_once_with()
3644 self.m.follow_orders.assert_called_once_with()
3645
3646 order = trade.orders[0]
3647 self.assertEqual(D("0.10"), order.rate)
3648
3649 self.m.reset_mock()
3650 with self.subTest(compute_value="default"):
1f117ac7 3651 main.make_order(self.m, 10, "ETH", action="dispose",
2033e7fe
IB
3652 compute_value="ask")
3653
3654 trade = self.m.trades.all.append.mock_calls[0][1][0]
3655 order = trade.orders[0]
3656 self.assertEqual(D("0.11"), order.rate)
3657
3658 self.m.reset_mock()
3659 with self.subTest(follow=False):
1f117ac7 3660 result = main.make_order(self.m, 10, "ETH", follow=False)
2033e7fe
IB
3661
3662 self.m.report.log_stage.assert_has_calls([
3663 mock.call("make_order_begin"),
3664 mock.call("make_order_end_not_followed"),
3665 ])
3666 self.m.balances.fetch_balances.assert_called_once_with(tag="make_order_begin")
3667
3668 self.m.trades.all.append.assert_called_once()
3669 trade = self.m.trades.all.append.mock_calls[0][1][0]
3670 self.assertEqual(0, trade.value_from)
3671 self.assertEqual("ETH", trade.currency)
3672 self.assertEqual("BTC", trade.base_currency)
3673 self.m.report.log_orders.assert_called_once_with([trade.orders[0]], None, "average")
3674 self.m.trades.run_orders.assert_called_once_with()
3675 self.m.follow_orders.assert_not_called()
3676 self.assertEqual(trade.orders[0], result)
3677
3678 self.m.reset_mock()
3679 with self.subTest(base_currency="USDT"):
1f117ac7 3680 main.make_order(self.m, 1, "BTC", base_currency="USDT")
2033e7fe
IB
3681
3682 trade = self.m.trades.all.append.mock_calls[0][1][0]
3683 self.assertEqual("BTC", trade.currency)
3684 self.assertEqual("USDT", trade.base_currency)
3685
3686 self.m.reset_mock()
3687 with self.subTest(close_if_possible=True):
1f117ac7 3688 main.make_order(self.m, 10, "ETH", close_if_possible=True)
2033e7fe
IB
3689
3690 trade = self.m.trades.all.append.mock_calls[0][1][0]
3691 self.assertEqual(True, trade.orders[0].close_if_possible)
3692
3693 self.m.reset_mock()
3694 with self.subTest(action="dispose"):
1f117ac7 3695 main.make_order(self.m, 10, "ETH", action="dispose")
2033e7fe
IB
3696
3697 trade = self.m.trades.all.append.mock_calls[0][1][0]
3698 self.assertEqual(0, trade.value_to)
3699 self.assertEqual(1, trade.value_from.value)
3700 self.assertEqual("ETH", trade.currency)
3701 self.assertEqual("BTC", trade.base_currency)
3702
3703 self.m.reset_mock()
3704 with self.subTest(compute_value="default"):
1f117ac7 3705 main.make_order(self.m, 10, "ETH", action="dispose",
2033e7fe
IB
3706 compute_value="bid")
3707
3708 trade = self.m.trades.all.append.mock_calls[0][1][0]
3709 self.assertEqual(D("0.9"), trade.value_from.value)
3710
1f117ac7
IB
3711 def test_get_user_market(self):
3712 with mock.patch("main.fetch_markets") as main_fetch_markets,\
3713 mock.patch("main.parse_config") as main_parse_config:
2033e7fe
IB
3714 with self.subTest(debug=False):
3715 main_parse_config.return_value = ["pg_config", "report_path"]
b4e0ba0b 3716 main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)]
1f117ac7 3717 m = main.get_user_market("config_path.ini", 1)
2033e7fe
IB
3718
3719 self.assertIsInstance(m, market.Market)
3720 self.assertFalse(m.debug)
3721
3722 with self.subTest(debug=True):
3723 main_parse_config.return_value = ["pg_config", "report_path"]
b4e0ba0b 3724 main_fetch_markets.return_value = [(1, {"key": "market_config"}, 3)]
1f117ac7 3725 m = main.get_user_market("config_path.ini", 1, debug=True)
2033e7fe
IB
3726
3727 self.assertIsInstance(m, market.Market)
3728 self.assertTrue(m.debug)
3729
a18ce2f1
IB
3730 def test_process(self):
3731 with mock.patch("market.Market") as market_mock,\
f86ee140 3732 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
f86ee140 3733
1f117ac7
IB
3734 args_mock = mock.Mock()
3735 args_mock.action = "action"
3736 args_mock.config = "config"
3737 args_mock.user = "user"
3738 args_mock.debug = "debug"
3739 args_mock.before = "before"
3740 args_mock.after = "after"
a18ce2f1
IB
3741 self.assertEqual("", stdout_mock.getvalue())
3742
35667b31 3743 main.process("config", 3, 1, args_mock, "report_path", "pg_config")
a18ce2f1
IB
3744
3745 market_mock.from_config.assert_has_calls([
b4e0ba0b 3746 mock.call("config", args_mock, pg_config="pg_config", market_id=3, user_id=1, report_path="report_path"),
a18ce2f1
IB
3747 mock.call().process("action", before="before", after="after"),
3748 ])
3749
3750 with self.subTest(exception=True):
3751 market_mock.from_config.side_effect = Exception("boo")
b4e0ba0b 3752 main.process(3, "config", 1, "report_path", args_mock, "pg_config")
a18ce2f1
IB
3753 self.assertEqual("Exception: boo\n", stdout_mock.getvalue())
3754
3755 def test_main(self):
dc1ca9a3
IB
3756 with self.subTest(parallel=False):
3757 with mock.patch("main.parse_args") as parse_args,\
3758 mock.patch("main.parse_config") as parse_config,\
3759 mock.patch("main.fetch_markets") as fetch_markets,\
3760 mock.patch("main.process") as process:
a18ce2f1 3761
dc1ca9a3
IB
3762 args_mock = mock.Mock()
3763 args_mock.parallel = False
3764 args_mock.config = "config"
3765 args_mock.user = "user"
3766 parse_args.return_value = args_mock
f86ee140 3767
dc1ca9a3 3768 parse_config.return_value = ["pg_config", "report_path"]
f86ee140 3769
b4e0ba0b 3770 fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]]
9db7d156 3771
dc1ca9a3 3772 main.main(["Foo", "Bar"])
f86ee140 3773
dc1ca9a3
IB
3774 parse_args.assert_called_with(["Foo", "Bar"])
3775 parse_config.assert_called_with("config")
3776 fetch_markets.assert_called_with("pg_config", "user")
f86ee140 3777
dc1ca9a3
IB
3778 self.assertEqual(2, process.call_count)
3779 process.assert_has_calls([
35667b31
IB
3780 mock.call("config1", 3, 1, args_mock, "report_path", "pg_config"),
3781 mock.call("config2", 1, 2, args_mock, "report_path", "pg_config"),
dc1ca9a3
IB
3782 ])
3783 with self.subTest(parallel=True):
3784 with mock.patch("main.parse_args") as parse_args,\
3785 mock.patch("main.parse_config") as parse_config,\
3786 mock.patch("main.fetch_markets") as fetch_markets,\
3787 mock.patch("main.process") as process,\
3788 mock.patch("store.Portfolio.start_worker") as start:
3789
3790 args_mock = mock.Mock()
3791 args_mock.parallel = True
3792 args_mock.config = "config"
3793 args_mock.user = "user"
3794 parse_args.return_value = args_mock
3795
3796 parse_config.return_value = ["pg_config", "report_path"]
3797
b4e0ba0b 3798 fetch_markets.return_value = [[3, "config1", 1], [1, "config2", 2]]
dc1ca9a3
IB
3799
3800 main.main(["Foo", "Bar"])
3801
3802 parse_args.assert_called_with(["Foo", "Bar"])
3803 parse_config.assert_called_with("config")
3804 fetch_markets.assert_called_with("pg_config", "user")
3805
3806 start.assert_called_once_with()
3807 self.assertEqual(2, process.call_count)
3808 process.assert_has_calls([
3809 mock.call.__bool__(),
35667b31 3810 mock.call("config1", 3, 1, args_mock, "report_path", "pg_config"),
dc1ca9a3 3811 mock.call.__bool__(),
35667b31 3812 mock.call("config2", 1, 2, args_mock, "report_path", "pg_config"),
dc1ca9a3 3813 ])
9db7d156 3814
1f117ac7
IB
3815 @mock.patch.object(main.sys, "exit")
3816 @mock.patch("main.configparser")
3817 @mock.patch("main.os")
3818 def test_parse_config(self, os, configparser, exit):
f86ee140
IB
3819 with self.subTest(pg_config=True, report_path=None):
3820 config_mock = mock.MagicMock()
3821 configparser.ConfigParser.return_value = config_mock
3822 def config(element):
3823 return element == "postgresql"
3824
3825 config_mock.__contains__.side_effect = config
3826 config_mock.__getitem__.return_value = "pg_config"
3827
1f117ac7 3828 result = main.parse_config("configfile")
f86ee140
IB
3829
3830 config_mock.read.assert_called_with("configfile")
3831
3832 self.assertEqual(["pg_config", None], result)
3833
3834 with self.subTest(pg_config=True, report_path="present"):
3835 config_mock = mock.MagicMock()
3836 configparser.ConfigParser.return_value = config_mock
3837
3838 config_mock.__contains__.return_value = True
3839 config_mock.__getitem__.side_effect = [
3840 {"report_path": "report_path"},
3841 {"report_path": "report_path"},
3842 "pg_config",
3843 ]
3844
3845 os.path.exists.return_value = False
1f117ac7 3846 result = main.parse_config("configfile")
f86ee140
IB
3847
3848 config_mock.read.assert_called_with("configfile")
3849 self.assertEqual(["pg_config", "report_path"], result)
3850 os.path.exists.assert_called_once_with("report_path")
3851 os.makedirs.assert_called_once_with("report_path")
3852
3853 with self.subTest(pg_config=False),\
3854 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
3855 config_mock = mock.MagicMock()
3856 configparser.ConfigParser.return_value = config_mock
1f117ac7 3857 result = main.parse_config("configfile")
f86ee140
IB
3858
3859 config_mock.read.assert_called_with("configfile")
3860 exit.assert_called_once_with(1)
3861 self.assertEqual("no configuration for postgresql in config file\n", stdout_mock.getvalue())
3862
1f117ac7
IB
3863 @mock.patch.object(main.sys, "exit")
3864 def test_parse_args(self, exit):
3865 with self.subTest(config="config.ini"):
3866 args = main.parse_args([])
3867 self.assertEqual("config.ini", args.config)
3868 self.assertFalse(args.before)
3869 self.assertFalse(args.after)
3870 self.assertFalse(args.debug)
f86ee140 3871
1f117ac7
IB
3872 args = main.parse_args(["--before", "--after", "--debug"])
3873 self.assertTrue(args.before)
3874 self.assertTrue(args.after)
3875 self.assertTrue(args.debug)
f86ee140 3876
1f117ac7
IB
3877 exit.assert_not_called()
3878
3879 with self.subTest(config="inexistant"),\
3880 mock.patch('sys.stdout', new_callable=StringIO) as stdout_mock:
3881 args = main.parse_args(["--config", "foo.bar"])
3882 exit.assert_called_once_with(1)
3883 self.assertEqual("no config file found, exiting\n", stdout_mock.getvalue())
3884
3885 @mock.patch.object(main, "psycopg2")
3886 def test_fetch_markets(self, psycopg2):
3887 connect_mock = mock.Mock()
3888 cursor_mock = mock.MagicMock()
3889 cursor_mock.__iter__.return_value = ["row_1", "row_2"]
3890
3891 connect_mock.cursor.return_value = cursor_mock
3892 psycopg2.connect.return_value = connect_mock
3893
3894 with self.subTest(user=None):
3895 rows = list(main.fetch_markets({"foo": "bar"}, None))
3896
3897 psycopg2.connect.assert_called_once_with(foo="bar")
b4e0ba0b 3898 cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs")
1f117ac7
IB
3899
3900 self.assertEqual(["row_1", "row_2"], rows)
3901
3902 psycopg2.connect.reset_mock()
3903 cursor_mock.execute.reset_mock()
3904 with self.subTest(user=1):
3905 rows = list(main.fetch_markets({"foo": "bar"}, 1))
3906
3907 psycopg2.connect.assert_called_once_with(foo="bar")
b4e0ba0b 3908 cursor_mock.execute.assert_called_once_with("SELECT id,config,user_id FROM market_configs WHERE user_id = %s", 1)
1f117ac7
IB
3909
3910 self.assertEqual(["row_1", "row_2"], rows)
f86ee140 3911
f86ee140 3912
66f1aed5
IB
3913@unittest.skipUnless("unit" in limits, "Unit skipped")
3914class ProcessorTest(WebMockTestCase):
3915 def test_values(self):
1f117ac7 3916 processor = market.Processor(self.m)
f86ee140 3917
66f1aed5 3918 self.assertEqual(self.m, processor.market)
f86ee140 3919
66f1aed5 3920 def test_run_action(self):
1f117ac7 3921 processor = market.Processor(self.m)
f86ee140 3922
66f1aed5
IB
3923 with mock.patch.object(processor, "parse_args") as parse_args:
3924 method_mock = mock.Mock()
3925 parse_args.return_value = [method_mock, { "foo": "bar" }]
f86ee140 3926
66f1aed5 3927 processor.run_action("foo", "bar", "baz")
f86ee140 3928
66f1aed5 3929 parse_args.assert_called_with("foo", "bar", "baz")
f86ee140 3930
66f1aed5 3931 method_mock.assert_called_with(foo="bar")
065ee342 3932
66f1aed5 3933 processor.run_action("wait_for_recent", "bar", "baz")
065ee342 3934
ada1b5f1 3935 method_mock.assert_called_with(foo="bar")
66f1aed5
IB
3936
3937 def test_select_step(self):
1f117ac7 3938 processor = market.Processor(self.m)
66f1aed5
IB
3939
3940 scenario = processor.scenarios["sell_all"]
3941
3942 self.assertEqual(scenario, processor.select_steps(scenario, "all"))
3943 self.assertEqual(["all_sell"], list(map(lambda x: x["name"], processor.select_steps(scenario, "before"))))
3944 self.assertEqual(["wait", "all_buy"], list(map(lambda x: x["name"], processor.select_steps(scenario, "after"))))
3945 self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, 2))))
3946 self.assertEqual(["wait"], list(map(lambda x: x["name"], processor.select_steps(scenario, "wait"))))
3947
3948 with self.assertRaises(TypeError):
3949 processor.select_steps(scenario, ["wait"])
3950
1f117ac7 3951 @mock.patch("market.Processor.process_step")
66f1aed5 3952 def test_process(self, process_step):
1f117ac7 3953 processor = market.Processor(self.m)
66f1aed5
IB
3954
3955 processor.process("sell_all", foo="bar")
3956 self.assertEqual(3, process_step.call_count)
3957
3958 steps = list(map(lambda x: x[1][1]["name"], process_step.mock_calls))
3959 scenario_names = list(map(lambda x: x[1][0], process_step.mock_calls))
3960 kwargs = list(map(lambda x: x[1][2], process_step.mock_calls))
3961 self.assertEqual(["all_sell", "wait", "all_buy"], steps)
3962 self.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names)
3963 self.assertEqual([{"foo":"bar"}, {"foo":"bar"}, {"foo":"bar"}], kwargs)
3964
3965 process_step.reset_mock()
3966
3967 processor.process("sell_needed", steps=["before", "after"])
3968 self.assertEqual(3, process_step.call_count)
3969
3970 def test_method_arguments(self):
3971 ccxt = mock.Mock(spec=market.ccxt.poloniexE)
07fa7a4b 3972 m = market.Market(ccxt, self.market_args())
66f1aed5 3973
1f117ac7 3974 processor = market.Processor(m)
66f1aed5
IB
3975
3976 method, arguments = processor.method_arguments("wait_for_recent")
ada1b5f1 3977 self.assertEqual(market.Portfolio.wait_for_recent, method)
dc1ca9a3 3978 self.assertEqual(["delta", "poll"], arguments)
66f1aed5
IB
3979
3980 method, arguments = processor.method_arguments("prepare_trades")
3981 self.assertEqual(m.prepare_trades, method)
3982 self.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments)
3983
3984 method, arguments = processor.method_arguments("prepare_orders")
3985 self.assertEqual(m.trades.prepare_orders, method)
3986
3987 method, arguments = processor.method_arguments("move_balances")
3988 self.assertEqual(m.move_balances, method)
3989
3990 method, arguments = processor.method_arguments("run_orders")
3991 self.assertEqual(m.trades.run_orders, method)
3992
3993 method, arguments = processor.method_arguments("follow_orders")
3994 self.assertEqual(m.follow_orders, method)
3995
3996 method, arguments = processor.method_arguments("close_trades")
3997 self.assertEqual(m.trades.close_trades, method)
3998
3999 def test_process_step(self):
1f117ac7 4000 processor = market.Processor(self.m)
66f1aed5
IB
4001
4002 with mock.patch.object(processor, "run_action") as run_action:
4003 step = processor.scenarios["sell_needed"][1]
4004
4005 processor.process_step("foo", step, {"foo":"bar"})
4006
4007 self.m.report.log_stage.assert_has_calls([
4008 mock.call("process_foo__1_sell_begin"),
4009 mock.call("process_foo__1_sell_end"),
4010 ])
4011 self.m.balances.fetch_balances.assert_has_calls([
4012 mock.call(tag="process_foo__1_sell_begin"),
4013 mock.call(tag="process_foo__1_sell_end"),
4014 ])
4015
4016 self.assertEqual(5, run_action.call_count)
4017
4018 run_action.assert_has_calls([
4019 mock.call('prepare_trades', {}, {'foo': 'bar'}),
4020 mock.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}, {'foo': 'bar'}),
4021 mock.call('run_orders', {}, {'foo': 'bar'}),
4022 mock.call('follow_orders', {}, {'foo': 'bar'}),
4023 mock.call('close_trades', {}, {'foo': 'bar'}),
4024 ])
4025
4026 self.m.reset_mock()
4027 with mock.patch.object(processor, "run_action") as run_action:
4028 step = processor.scenarios["sell_needed"][0]
4029
4030 processor.process_step("foo", step, {"foo":"bar"})
4031 self.m.balances.fetch_balances.assert_not_called()
4032
4033 def test_parse_args(self):
1f117ac7 4034 processor = market.Processor(self.m)
66f1aed5
IB
4035
4036 with mock.patch.object(processor, "method_arguments") as method_arguments:
4037 method_mock = mock.Mock()
4038 method_arguments.return_value = [
4039 method_mock,
4040 ["foo2", "foo"]
4041 ]
4042 method, args = processor.parse_args("action", {"foo": "bar", "foo2": "bar"}, {"foo": "bar2", "bla": "bla"})
4043
4044 self.assertEqual(method_mock, method)
4045 self.assertEqual({"foo": "bar2", "foo2": "bar"}, args)
4046
4047 with mock.patch.object(processor, "method_arguments") as method_arguments:
4048 method_mock = mock.Mock()
4049 method_arguments.return_value = [
4050 method_mock,
4051 ["repartition"]
4052 ]
4053 method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {})
4054
4055 self.assertEqual(1, len(args["repartition"]))
4056 self.assertIn("BTC", args["repartition"])
4057
4058 with mock.patch.object(processor, "method_arguments") as method_arguments:
4059 method_mock = mock.Mock()
4060 method_arguments.return_value = [
4061 method_mock,
4062 ["repartition", "base_currency"]
4063 ]
4064 method, args = processor.parse_args("action", {"repartition": { "base_currency": 1 }}, {"base_currency": "USDT"})
4065
4066 self.assertEqual(1, len(args["repartition"]))
4067 self.assertIn("USDT", args["repartition"])
4068
4069 with mock.patch.object(processor, "method_arguments") as method_arguments:
4070 method_mock = mock.Mock()
4071 method_arguments.return_value = [
4072 method_mock,
4073 ["repartition", "base_currency"]
4074 ]
4075 method, args = processor.parse_args("action", {"repartition": { "ETH": 1 }}, {"base_currency": "USDT"})
4076
4077 self.assertEqual(1, len(args["repartition"]))
4078 self.assertIn("ETH", args["repartition"])
f86ee140 4079
f86ee140 4080
1aa7d4fa 4081@unittest.skipUnless("acceptance" in limits, "Acceptance skipped")
80cdd672
IB
4082class AcceptanceTest(WebMockTestCase):
4083 @unittest.expectedFailure
a9950fd0 4084 def test_success_sell_only_necessary(self):
3d0247f9 4085 # FIXME: catch stdout
f86ee140 4086 self.m.report.verbose_print = False
a9950fd0
IB
4087 fetch_balance = {
4088 "ETH": {
c51687d2
IB
4089 "exchange_free": D("1.0"),
4090 "exchange_used": D("0.0"),
4091 "exchange_total": D("1.0"),
a9950fd0
IB
4092 "total": D("1.0"),
4093 },
4094 "ETC": {
c51687d2
IB
4095 "exchange_free": D("4.0"),
4096 "exchange_used": D("0.0"),
4097 "exchange_total": D("4.0"),
a9950fd0
IB
4098 "total": D("4.0"),
4099 },
4100 "XVG": {
c51687d2
IB
4101 "exchange_free": D("1000.0"),
4102 "exchange_used": D("0.0"),
4103 "exchange_total": D("1000.0"),
a9950fd0
IB
4104 "total": D("1000.0"),
4105 },
4106 }
4107 repartition = {
350ed24d
IB
4108 "ETH": (D("0.25"), "long"),
4109 "ETC": (D("0.25"), "long"),
4110 "BTC": (D("0.4"), "long"),
4111 "BTD": (D("0.01"), "short"),
4112 "B2X": (D("0.04"), "long"),
4113 "USDT": (D("0.05"), "long"),
a9950fd0
IB
4114 }
4115
4116 def fetch_ticker(symbol):
4117 if symbol == "ETH/BTC":
4118 return {
4119 "symbol": "ETH/BTC",
4120 "bid": D("0.14"),
4121 "ask": D("0.16")
4122 }
4123 if symbol == "ETC/BTC":
4124 return {
4125 "symbol": "ETC/BTC",
4126 "bid": D("0.002"),
4127 "ask": D("0.003")
4128 }
4129 if symbol == "XVG/BTC":
4130 return {
4131 "symbol": "XVG/BTC",
4132 "bid": D("0.00003"),
4133 "ask": D("0.00005")
4134 }
4135 if symbol == "BTD/BTC":
4136 return {
4137 "symbol": "BTD/BTC",
4138 "bid": D("0.0008"),
4139 "ask": D("0.0012")
4140 }
350ed24d
IB
4141 if symbol == "B2X/BTC":
4142 return {
4143 "symbol": "B2X/BTC",
4144 "bid": D("0.0008"),
4145 "ask": D("0.0012")
4146 }
a9950fd0 4147 if symbol == "USDT/BTC":
6ca5a1ec 4148 raise helper.ExchangeError
a9950fd0
IB
4149 if symbol == "BTC/USDT":
4150 return {
4151 "symbol": "BTC/USDT",
4152 "bid": D("14000"),
4153 "ask": D("16000")
4154 }
4155 self.fail("Shouldn't have been called with {}".format(symbol))
4156
4157 market = mock.Mock()
c51687d2 4158 market.fetch_all_balances.return_value = fetch_balance
a9950fd0 4159 market.fetch_ticker.side_effect = fetch_ticker
ada1b5f1 4160 with mock.patch.object(market.Portfolio, "repartition", return_value=repartition):
a9950fd0 4161 # Action 1
6ca5a1ec 4162 helper.prepare_trades(market)
a9950fd0 4163
6ca5a1ec 4164 balances = portfolio.BalanceStore.all
a9950fd0
IB
4165 self.assertEqual(portfolio.Amount("ETH", 1), balances["ETH"].total)
4166 self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total)
4167 self.assertEqual(portfolio.Amount("XVG", 1000), balances["XVG"].total)
4168
4169
5a72ded7 4170 trades = portfolio.TradeStore.all
c51687d2
IB
4171 self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from)
4172 self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to)
4173 self.assertEqual("dispose", trades[0].action)
a9950fd0 4174
c51687d2
IB
4175 self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from)
4176 self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to)
4177 self.assertEqual("acquire", trades[1].action)
a9950fd0 4178
c51687d2
IB
4179 self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from)
4180 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to)
4181 self.assertEqual("dispose", trades[2].action)
a9950fd0 4182
c51687d2
IB
4183 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from)
4184 self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to)
5a72ded7 4185 self.assertEqual("acquire", trades[3].action)
350ed24d 4186
c51687d2
IB
4187 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from)
4188 self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to)
4189 self.assertEqual("acquire", trades[4].action)
a9950fd0 4190
c51687d2
IB
4191 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from)
4192 self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to)
4193 self.assertEqual("acquire", trades[5].action)
a9950fd0
IB
4194
4195 # Action 2
5a72ded7 4196 portfolio.TradeStore.prepare_orders(only="dispose", compute_value=lambda x, y: x["bid"] * D("1.001"))
a9950fd0 4197
5a72ded7 4198 all_orders = portfolio.TradeStore.all_orders(state="pending")
a9950fd0
IB
4199 self.assertEqual(2, len(all_orders))
4200 self.assertEqual(2, 3*all_orders[0].amount.value)
4201 self.assertEqual(D("0.14014"), all_orders[0].rate)
4202 self.assertEqual(1000, all_orders[1].amount.value)
4203 self.assertEqual(D("0.00003003"), all_orders[1].rate)
4204
4205
ecba1113 4206 def create_order(symbol, type, action, amount, price=None, account="exchange"):
a9950fd0
IB
4207 self.assertEqual("limit", type)
4208 if symbol == "ETH/BTC":
b83d4897 4209 self.assertEqual("sell", action)
350ed24d 4210 self.assertEqual(D('0.66666666'), amount)
a9950fd0
IB
4211 self.assertEqual(D("0.14014"), price)
4212 elif symbol == "XVG/BTC":
b83d4897 4213 self.assertEqual("sell", action)
a9950fd0
IB
4214 self.assertEqual(1000, amount)
4215 self.assertEqual(D("0.00003003"), price)
4216 else:
4217 self.fail("I shouldn't have been called")
4218
4219 return {
4220 "id": symbol,
4221 }
4222 market.create_order.side_effect = create_order
350ed24d 4223 market.order_precision.return_value = 8
a9950fd0
IB
4224
4225 # Action 3
6ca5a1ec 4226 portfolio.TradeStore.run_orders()
a9950fd0
IB
4227
4228 self.assertEqual("open", all_orders[0].status)
4229 self.assertEqual("open", all_orders[1].status)
4230
5a72ded7
IB
4231 market.fetch_order.return_value = { "status": "closed", "datetime": "2018-01-20 13:40:00" }
4232 market.privatePostReturnOrderTrades.return_value = [
4233 {
df9e4e7f 4234 "tradeID": 42, "type": "buy", "fee": "0.0015",
5a72ded7
IB
4235 "date": "2017-12-30 12:00:12", "rate": "0.1",
4236 "amount": "10", "total": "1"
4237 }
4238 ]
ada1b5f1 4239 with mock.patch.object(market.time, "sleep") as sleep:
a9950fd0 4240 # Action 4
6ca5a1ec 4241 helper.follow_orders(verbose=False)
a9950fd0
IB
4242
4243 sleep.assert_called_with(30)
4244
4245 for order in all_orders:
4246 self.assertEqual("closed", order.status)
4247
4248 fetch_balance = {
4249 "ETH": {
5a72ded7
IB
4250 "exchange_free": D("1.0") / 3,
4251 "exchange_used": D("0.0"),
4252 "exchange_total": D("1.0") / 3,
4253 "margin_total": 0,
a9950fd0
IB
4254 "total": D("1.0") / 3,
4255 },
4256 "BTC": {
5a72ded7
IB
4257 "exchange_free": D("0.134"),
4258 "exchange_used": D("0.0"),
4259 "exchange_total": D("0.134"),
4260 "margin_total": 0,
a9950fd0
IB
4261 "total": D("0.134"),
4262 },
4263 "ETC": {
5a72ded7
IB
4264 "exchange_free": D("4.0"),
4265 "exchange_used": D("0.0"),
4266 "exchange_total": D("4.0"),
4267 "margin_total": 0,
a9950fd0
IB
4268 "total": D("4.0"),
4269 },
4270 "XVG": {
5a72ded7
IB
4271 "exchange_free": D("0.0"),
4272 "exchange_used": D("0.0"),
4273 "exchange_total": D("0.0"),
4274 "margin_total": 0,
a9950fd0
IB
4275 "total": D("0.0"),
4276 },
4277 }
5a72ded7 4278 market.fetch_all_balances.return_value = fetch_balance
a9950fd0 4279
ada1b5f1 4280 with mock.patch.object(market.Portfolio, "repartition", return_value=repartition):
a9950fd0 4281 # Action 5
7bd830a8 4282 helper.prepare_trades(market, only="acquire", compute_value="average")
a9950fd0 4283
6ca5a1ec 4284 balances = portfolio.BalanceStore.all
a9950fd0
IB
4285 self.assertEqual(portfolio.Amount("ETH", 1 / D("3")), balances["ETH"].total)
4286 self.assertEqual(portfolio.Amount("ETC", 4), balances["ETC"].total)
4287 self.assertEqual(portfolio.Amount("BTC", D("0.134")), balances["BTC"].total)
4288 self.assertEqual(portfolio.Amount("XVG", 0), balances["XVG"].total)
4289
4290
5a72ded7
IB
4291 trades = portfolio.TradeStore.all
4292 self.assertEqual(portfolio.Amount("BTC", D("0.15")), trades[0].value_from)
4293 self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[0].value_to)
4294 self.assertEqual("dispose", trades[0].action)
a9950fd0 4295
5a72ded7
IB
4296 self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[1].value_from)
4297 self.assertEqual(portfolio.Amount("BTC", D("0.05")), trades[1].value_to)
4298 self.assertEqual("acquire", trades[1].action)
a9950fd0
IB
4299
4300 self.assertNotIn("BTC", trades)
4301
5a72ded7
IB
4302 self.assertEqual(portfolio.Amount("BTC", D("0.04")), trades[2].value_from)
4303 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[2].value_to)
4304 self.assertEqual("dispose", trades[2].action)
a9950fd0 4305
5a72ded7
IB
4306 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[3].value_from)
4307 self.assertEqual(portfolio.Amount("BTC", D("-0.002")), trades[3].value_to)
4308 self.assertEqual("acquire", trades[3].action)
350ed24d 4309
5a72ded7
IB
4310 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[4].value_from)
4311 self.assertEqual(portfolio.Amount("BTC", D("0.008")), trades[4].value_to)
4312 self.assertEqual("acquire", trades[4].action)
a9950fd0 4313
5a72ded7
IB
4314 self.assertEqual(portfolio.Amount("BTC", D("0.00")), trades[5].value_from)
4315 self.assertEqual(portfolio.Amount("BTC", D("0.01")), trades[5].value_to)
4316 self.assertEqual("acquire", trades[5].action)
a9950fd0
IB
4317
4318 # Action 6
5a72ded7 4319 portfolio.TradeStore.prepare_orders(only="acquire", compute_value=lambda x, y: x["ask"])
b83d4897 4320
5a72ded7 4321 all_orders = portfolio.TradeStore.all_orders(state="pending")
350ed24d
IB
4322 self.assertEqual(4, len(all_orders))
4323 self.assertEqual(portfolio.Amount("ETC", D("12.83333333")), round(all_orders[0].amount))
b83d4897
IB
4324 self.assertEqual(D("0.003"), all_orders[0].rate)
4325 self.assertEqual("buy", all_orders[0].action)
350ed24d 4326 self.assertEqual("long", all_orders[0].trade_type)
b83d4897 4327
350ed24d 4328 self.assertEqual(portfolio.Amount("BTD", D("1.61666666")), round(all_orders[1].amount))
b83d4897 4329 self.assertEqual(D("0.0012"), all_orders[1].rate)
350ed24d
IB
4330 self.assertEqual("sell", all_orders[1].action)
4331 self.assertEqual("short", all_orders[1].trade_type)
4332
4333 diff = portfolio.Amount("B2X", D("19.4")/3) - all_orders[2].amount
4334 self.assertAlmostEqual(0, diff.value)
4335 self.assertEqual(D("0.0012"), all_orders[2].rate)
4336 self.assertEqual("buy", all_orders[2].action)
4337 self.assertEqual("long", all_orders[2].trade_type)
4338
4339 self.assertEqual(portfolio.Amount("BTC", D("0.0097")), all_orders[3].amount)
4340 self.assertEqual(D("16000"), all_orders[3].rate)
4341 self.assertEqual("sell", all_orders[3].action)
4342 self.assertEqual("long", all_orders[3].trade_type)
b83d4897 4343
006a2084
IB
4344 # Action 6b
4345 # TODO:
4346 # Move balances to margin
4347
350ed24d
IB
4348 # Action 7
4349 # TODO
6ca5a1ec 4350 # portfolio.TradeStore.run_orders()
a9950fd0 4351
ada1b5f1 4352 with mock.patch.object(market.time, "sleep") as sleep:
350ed24d 4353 # Action 8
6ca5a1ec 4354 helper.follow_orders(verbose=False)
a9950fd0
IB
4355
4356 sleep.assert_called_with(30)
4357
dd359bc0
IB
4358if __name__ == '__main__':
4359 unittest.main()