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