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