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