5 from decimal
import Decimal
as D
6 from unittest
import mock
9 from io
import StringIO
10 import portfolio
, helper
, market
12 limits
= ["acceptance", "unit"]
13 for 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
))
22 class WebMockTestCase(unittest
.TestCase
):
26 super(WebMockTestCase
, self
).setUp()
27 self
.wm
= requests_mock
.Mocker()
31 self
.m
= mock
.Mock(name
="Market", spec
=market
.Market
)
35 mock
.patch
.multiple(portfolio
.Portfolio
, last_date
=None, data
=None, liquidities
={}),
36 mock
.patch
.multiple(portfolio
.Computation
,
37 computations
=portfolio
.Computation
.computations
),
38 mock
.patch
.multiple(market
.Market
,
41 ticker_cache_timestamp
=self
.time
.time()),
43 for patcher
in self
.patchers
:
47 for patcher
in self
.patchers
:
50 super(WebMockTestCase
, self
).tearDown()
52 @unittest.skipUnless("unit" in limits
, "Unit skipped")
53 class PortfolioTest(WebMockTestCase
):
55 if self
.json_response
is not None:
56 portfolio
.Portfolio
.data
= self
.json_response
59 super(PortfolioTest
, self
).setUp()
61 with open("test_portfolio.json") as example
:
62 self
.json_response
= example
.read()
64 self
.wm
.get(portfolio
.Portfolio
.URL
, text
=self
.json_response
)
66 def test_get_cryptoportfolio(self
):
67 self
.wm
.get(portfolio
.Portfolio
.URL
, [
68 {"text":'{ "foo": "bar" }
', "status_code": 200},
69 {"text": "System Error", "status_code": 500},
70 {"exc": requests.exceptions.ConnectTimeout},
72 portfolio.Portfolio.get_cryptoportfolio(self.m)
73 self.assertIn("foo", portfolio.Portfolio.data)
74 self.assertEqual("bar", portfolio.Portfolio.data["foo"])
75 self.assertTrue(self.wm.called)
76 self.assertEqual(1, self.wm.call_count)
77 self.m.report.log_error.assert_not_called()
78 self.m.report.log_http_request.assert_called_once()
79 self.m.report.log_http_request.reset_mock()
81 portfolio.Portfolio.get_cryptoportfolio(self.m)
82 self.assertIsNone(portfolio.Portfolio.data)
83 self.assertEqual(2, self.wm.call_count)
84 self.m.report.log_error.assert_not_called()
85 self.m.report.log_http_request.assert_called_once()
86 self.m.report.log_http_request.reset_mock()
89 portfolio.Portfolio.data = "Foo"
90 portfolio.Portfolio.get_cryptoportfolio(self.m)
91 self.assertEqual("Foo", portfolio.Portfolio.data)
92 self.assertEqual(3, self.wm.call_count)
93 self.m.report.log_error.assert_called_once_with("get_cryptoportfolio",
95 self.m.report.log_http_request.assert_not_called()
97 def test_parse_cryptoportfolio(self):
98 portfolio.Portfolio.parse_cryptoportfolio(self.m)
100 self.assertListEqual(
102 list(portfolio.Portfolio.liquidities.keys()))
104 liquidities = portfolio.Portfolio.liquidities
105 self.assertEqual(10, len(liquidities["medium"].keys()))
106 self.assertEqual(10, len(liquidities["high"].keys()))
109 'BTC
': (D("0.2857"), "long"),
110 'DGB
': (D("0.1015"), "long"),
111 'DOGE
': (D("0.1805"), "long"),
112 'SC
': (D("0.0623"), "long"),
113 'ZEC
': (D("0.3701"), "long"),
115 date = portfolio.datetime(2018, 1, 8)
116 self.assertDictEqual(expected, liquidities["high"][date])
119 'BTC
': (D("1.1102e-16"), "long"),
120 'ETC
': (D("0.1"), "long"),
121 'FCT
': (D("0.1"), "long"),
122 'GAS
': (D("0.1"), "long"),
123 'NAV
': (D("0.1"), "long"),
124 'OMG
': (D("0.1"), "long"),
125 'OMNI
': (D("0.1"), "long"),
126 'PPC
': (D("0.1"), "long"),
127 'RIC
': (D("0.1"), "long"),
128 'VIA
': (D("0.1"), "long"),
129 'XCP
': (D("0.1"), "long"),
131 self.assertDictEqual(expected, liquidities["medium"][date])
132 self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date)
134 self.m.report.log_http_request.assert_called_once_with("GET",
135 portfolio.Portfolio.URL, None, mock.ANY, mock.ANY)
136 self.m.report.log_http_request.reset_mock()
138 # It doesn't refetch the data when available
139 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
)
140 self
.m
.report
.log_http_request
.assert_not_called()
142 self
.assertEqual(1, self
.wm
.call_count
)
144 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
, refetch
=True)
145 self
.assertEqual(2, self
.wm
.call_count
)
146 self
.m
.report
.log_http_request
.assert_called_once()
148 def test_repartition(self
):
150 'BTC': (D("1.1102e-16"), "long"),
151 'USDT': (D("0.1"), "long"),
152 'ETC': (D("0.1"), "long"),
153 'FCT': (D("0.1"), "long"),
154 'OMG': (D("0.1"), "long"),
155 'STEEM': (D("0.1"), "long"),
156 'STRAT': (D("0.1"), "long"),
157 'XEM': (D("0.1"), "long"),
158 'XMR': (D("0.1"), "long"),
159 'XVC': (D("0.1"), "long"),
160 'ZRX': (D("0.1"), "long"),
163 'USDT': (D("0.1226"), "long"),
164 'BTC': (D("0.1429"), "long"),
165 'ETC': (D("0.1127"), "long"),
166 'ETH': (D("0.1569"), "long"),
167 'FCT': (D("0.3341"), "long"),
168 'GAS': (D("0.1308"), "long"),
171 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
))
172 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="medium"))
173 self
.assertEqual(expected_high
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="high"))
175 self
.assertEqual(1, self
.wm
.call_count
)
177 portfolio
.Portfolio
.repartition(self
.m
)
178 self
.assertEqual(1, self
.wm
.call_count
)
180 portfolio
.Portfolio
.repartition(self
.m
, refetch
=True)
181 self
.assertEqual(2, self
.wm
.call_count
)
182 self
.m
.report
.log_http_request
.assert_called()
183 self
.assertEqual(2, self
.m
.report
.log_http_request
.call_count
)
185 @mock.patch.object(portfolio
.time
, "sleep")
186 @mock.patch.object(portfolio
.Portfolio
, "repartition")
187 def test_wait_for_recent(self
, repartition
, sleep
):
189 def _repartition(market
, refetch
):
190 self
.assertEqual(self
.m
, market
)
191 self
.assertTrue(refetch
)
193 portfolio
.Portfolio
.last_date
= portfolio
.datetime
.now()\
194 - portfolio
.timedelta(10)\
195 + portfolio
.timedelta(self
.call_count
)
196 repartition
.side_effect
= _repartition
198 portfolio
.Portfolio
.wait_for_recent(self
.m
)
199 sleep
.assert_called_with(30)
200 self
.assertEqual(6, sleep
.call_count
)
201 self
.assertEqual(7, repartition
.call_count
)
202 self
.m
.report
.print_log
.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
205 repartition
.reset_mock()
206 portfolio
.Portfolio
.last_date
= None
208 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=15)
209 sleep
.assert_not_called()
210 self
.assertEqual(1, repartition
.call_count
)
213 repartition
.reset_mock()
214 portfolio
.Portfolio
.last_date
= None
216 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=1)
217 sleep
.assert_called_with(30)
218 self
.assertEqual(9, sleep
.call_count
)
219 self
.assertEqual(10, repartition
.call_count
)
221 @unittest.skipUnless("unit" in limits
, "Unit skipped")
222 class AmountTest(WebMockTestCase
):
223 def test_values(self
):
224 amount
= portfolio
.Amount("BTC", "0.65")
225 self
.assertEqual(D("0.65"), amount
.value
)
226 self
.assertEqual("BTC", amount
.currency
)
228 def test_in_currency(self
):
229 amount
= portfolio
.Amount("ETC", 10)
231 self
.assertEqual(amount
, amount
.in_currency("ETC", self
.m
))
233 with self
.subTest(desc
="no ticker for currency"):
234 self
.m
.get_ticker
.return_value
= None
236 self
.assertRaises(Exception, amount
.in_currency
, "ETH", self
.m
)
238 with self
.subTest(desc
="nominal case"):
239 self
.m
.get_ticker
.return_value
= {
245 converted_amount
= amount
.in_currency("ETH", self
.m
)
247 self
.assertEqual(D("3.0"), converted_amount
.value
)
248 self
.assertEqual("ETH", converted_amount
.currency
)
249 self
.assertEqual(amount
, converted_amount
.linked_to
)
250 self
.assertEqual("bar", converted_amount
.ticker
["foo"])
252 converted_amount
= amount
.in_currency("ETH", self
.m
, action
="bid", compute_value
="default")
253 self
.assertEqual(D("2"), converted_amount
.value
)
255 converted_amount
= amount
.in_currency("ETH", self
.m
, compute_value
="ask")
256 self
.assertEqual(D("4"), converted_amount
.value
)
258 converted_amount
= amount
.in_currency("ETH", self
.m
, rate
=D("0.02"))
259 self
.assertEqual(D("0.2"), converted_amount
.value
)
261 def test__round(self
):
262 amount
= portfolio
.Amount("BAR", portfolio
.D("1.23456789876"))
263 self
.assertEqual(D("1.23456789"), round(amount
).value
)
264 self
.assertEqual(D("1.23"), round(amount
, 2).value
)
267 amount
= portfolio
.Amount("SC", -120)
268 self
.assertEqual(120, abs(amount
).value
)
269 self
.assertEqual("SC", abs(amount
).currency
)
271 amount
= portfolio
.Amount("SC", 10)
272 self
.assertEqual(10, abs(amount
).value
)
273 self
.assertEqual("SC", abs(amount
).currency
)
276 amount1
= portfolio
.Amount("XVG", "12.9")
277 amount2
= portfolio
.Amount("XVG", "13.1")
279 self
.assertEqual(26, (amount1
+ amount2
).value
)
280 self
.assertEqual("XVG", (amount1
+ amount2
).currency
)
282 amount3
= portfolio
.Amount("ETH", "1.6")
283 with self
.assertRaises(Exception):
286 amount4
= portfolio
.Amount("ETH", 0.0)
287 self
.assertEqual(amount1
, amount1
+ amount4
)
289 self
.assertEqual(amount1
, amount1
+ 0)
291 def test__radd(self
):
292 amount
= portfolio
.Amount("XVG", "12.9")
294 self
.assertEqual(amount
, 0 + amount
)
295 with self
.assertRaises(Exception):
299 amount1
= portfolio
.Amount("XVG", "13.3")
300 amount2
= portfolio
.Amount("XVG", "13.1")
302 self
.assertEqual(D("0.2"), (amount1
- amount2
).value
)
303 self
.assertEqual("XVG", (amount1
- amount2
).currency
)
305 amount3
= portfolio
.Amount("ETH", "1.6")
306 with self
.assertRaises(Exception):
309 amount4
= portfolio
.Amount("ETH", 0.0)
310 self
.assertEqual(amount1
, amount1
- amount4
)
312 def test__rsub(self
):
313 amount
= portfolio
.Amount("ETH", "1.6")
314 with self
.assertRaises(Exception):
317 self
.assertEqual(portfolio
.Amount("ETH", "-1.6"), 0-amount
)
320 amount
= portfolio
.Amount("XEM", 11)
322 self
.assertEqual(D("38.5"), (amount
* D("3.5")).value
)
323 self
.assertEqual(D("33"), (amount
* 3).value
)
325 with self
.assertRaises(Exception):
328 def test__rmul(self
):
329 amount
= portfolio
.Amount("XEM", 11)
331 self
.assertEqual(D("38.5"), (D("3.5") * amount
).value
)
332 self
.assertEqual(D("33"), (3 * amount
).value
)
334 def test__floordiv(self
):
335 amount
= portfolio
.Amount("XEM", 11)
337 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
338 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
340 with self
.assertRaises(Exception):
343 def test__truediv(self
):
344 amount
= portfolio
.Amount("XEM", 11)
346 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
347 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
350 amount1
= portfolio
.Amount("BTD", 11.3)
351 amount2
= portfolio
.Amount("BTD", 13.1)
353 self
.assertTrue(amount1
< amount2
)
354 self
.assertFalse(amount2
< amount1
)
355 self
.assertFalse(amount1
< amount1
)
357 amount3
= portfolio
.Amount("BTC", 1.6)
358 with self
.assertRaises(Exception):
362 amount1
= portfolio
.Amount("BTD", 11.3)
363 amount2
= portfolio
.Amount("BTD", 13.1)
365 self
.assertTrue(amount1
<= amount2
)
366 self
.assertFalse(amount2
<= amount1
)
367 self
.assertTrue(amount1
<= amount1
)
369 amount3
= portfolio
.Amount("BTC", 1.6)
370 with self
.assertRaises(Exception):
374 amount1
= portfolio
.Amount("BTD", 11.3)
375 amount2
= portfolio
.Amount("BTD", 13.1)
377 self
.assertTrue(amount2
> amount1
)
378 self
.assertFalse(amount1
> amount2
)
379 self
.assertFalse(amount1
> amount1
)
381 amount3
= portfolio
.Amount("BTC", 1.6)
382 with self
.assertRaises(Exception):
386 amount1
= portfolio
.Amount("BTD", 11.3)
387 amount2
= portfolio
.Amount("BTD", 13.1)
389 self
.assertTrue(amount2
>= amount1
)
390 self
.assertFalse(amount1
>= amount2
)
391 self
.assertTrue(amount1
>= amount1
)
393 amount3
= portfolio
.Amount("BTC", 1.6)
394 with self
.assertRaises(Exception):
398 amount1
= portfolio
.Amount("BTD", 11.3)
399 amount2
= portfolio
.Amount("BTD", 13.1)
400 amount3
= portfolio
.Amount("BTD", 11.3)
402 self
.assertFalse(amount1
== amount2
)
403 self
.assertFalse(amount2
== amount1
)
404 self
.assertTrue(amount1
== amount3
)
405 self
.assertFalse(amount2
== 0)
407 amount4
= portfolio
.Amount("BTC", 1.6)
408 with self
.assertRaises(Exception):
411 amount5
= portfolio
.Amount("BTD", 0)
412 self
.assertTrue(amount5
== 0)
415 amount1
= portfolio
.Amount("BTD", 11.3)
416 amount2
= portfolio
.Amount("BTD", 13.1)
417 amount3
= portfolio
.Amount("BTD", 11.3)
419 self
.assertTrue(amount1
!= amount2
)
420 self
.assertTrue(amount2
!= amount1
)
421 self
.assertFalse(amount1
!= amount3
)
422 self
.assertTrue(amount2
!= 0)
424 amount4
= portfolio
.Amount("BTC", 1.6)
425 with self
.assertRaises(Exception):
428 amount5
= portfolio
.Amount("BTD", 0)
429 self
.assertFalse(amount5
!= 0)
432 amount1
= portfolio
.Amount("BTD", "11.3")
434 self
.assertEqual(portfolio
.D("-11.3"), (-amount1
).value
)
437 amount1
= portfolio
.Amount("BTX", 32)
438 self
.assertEqual("32.00000000 BTX", str(amount1
))
440 amount2
= portfolio
.Amount("USDT", 12000)
441 amount1
.linked_to
= amount2
442 self
.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1
))
444 def test__repr(self
):
445 amount1
= portfolio
.Amount("BTX", 32)
446 self
.assertEqual("Amount(32.00000000 BTX)", repr(amount1
))
448 amount2
= portfolio
.Amount("USDT", 12000)
449 amount1
.linked_to
= amount2
450 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1
))
452 amount3
= portfolio
.Amount("BTC", 0.1)
453 amount2
.linked_to
= amount3
454 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1
))
456 def test_as_json(self
):
457 amount
= portfolio
.Amount("BTX", 32)
458 self
.assertEqual({"currency": "BTX", "value": D("32")}
, amount
.as_json())
460 amount
= portfolio
.Amount("BTX", "1E-10")
461 self
.assertEqual({"currency": "BTX", "value": D("0")}
, amount
.as_json())
463 amount
= portfolio
.Amount("BTX", "1E-5")
464 self
.assertEqual({"currency": "BTX", "value": D("0.00001")}
, amount
.as_json())
465 self
.assertEqual("0.00001", str(amount
.as_json()["value"]))
467 @unittest.skipUnless("unit" in limits
, "Unit skipped")
468 class BalanceTest(WebMockTestCase
):
469 def test_values(self
):
470 balance
= portfolio
.Balance("BTC", {
471 "exchange_total": "0.65",
472 "exchange_free": "0.35",
473 "exchange_used": "0.30",
474 "margin_total": "-10",
475 "margin_borrowed": "-10",
477 "margin_position_type": "short",
478 "margin_borrowed_base_currency": "USDT",
479 "margin_liquidation_price": "1.20",
480 "margin_pending_gain": "10",
481 "margin_lending_fees": "0.4",
482 "margin_borrowed_base_price": "0.15",
484 self
.assertEqual(portfolio
.D("0.65"), balance
.exchange_total
.value
)
485 self
.assertEqual(portfolio
.D("0.35"), balance
.exchange_free
.value
)
486 self
.assertEqual(portfolio
.D("0.30"), balance
.exchange_used
.value
)
487 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
488 self
.assertEqual("BTC", balance
.exchange_free
.currency
)
489 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
491 self
.assertEqual(portfolio
.D("-10"), balance
.margin_total
.value
)
492 self
.assertEqual(portfolio
.D("-10"), balance
.margin_borrowed
.value
)
493 self
.assertEqual(portfolio
.D("0"), balance
.margin_free
.value
)
494 self
.assertEqual("BTC", balance
.margin_total
.currency
)
495 self
.assertEqual("BTC", balance
.margin_borrowed
.currency
)
496 self
.assertEqual("BTC", balance
.margin_free
.currency
)
498 self
.assertEqual("BTC", balance
.currency
)
500 self
.assertEqual(portfolio
.D("0.4"), balance
.margin_lending_fees
.value
)
501 self
.assertEqual("USDT", balance
.margin_lending_fees
.currency
)
503 def test__repr(self
):
504 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
505 repr(portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)))
506 balance
= portfolio
.Balance("BTX", { "exchange_total": 3,
507 "exchange_used": 1, "exchange_free": 2 })
508 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
510 balance
= portfolio
.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}
)
511 self
.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance
))
513 balance
= portfolio
.Balance("BTX", { "margin_total": 3,
514 "margin_borrowed": 1, "margin_free": 2 })
515 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + borrowed 1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
517 balance
= portfolio
.Balance("BTX", { "margin_total": 2, "margin_free": 2 }
)
518 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance
))
520 balance
= portfolio
.Balance("BTX", { "margin_total": -3,
521 "margin_borrowed_base_price": D("0.1"),
522 "margin_borrowed_base_currency": "BTC",
523 "margin_lending_fees": D("0.002") })
524 self
.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance
))
526 balance
= portfolio
.Balance("BTX", { "margin_total": 1,
527 "margin_borrowed": 1, "exchange_free": 2, "exchange_total": 2})
528 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [borrowed 1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance
))
530 def test_as_json(self
):
531 balance
= portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)
532 as_json
= balance
.as_json()
533 self
.assertEqual(set(portfolio
.Balance
.base_keys
), set(as_json
.keys()))
534 self
.assertEqual(D(0), as_json
["total"])
535 self
.assertEqual(D(2), as_json
["exchange_total"])
536 self
.assertEqual(D(2), as_json
["exchange_free"])
537 self
.assertEqual(D(0), as_json
["exchange_used"])
538 self
.assertEqual(D(0), as_json
["margin_total"])
539 self
.assertEqual(D(0), as_json
["margin_free"])
540 self
.assertEqual(D(0), as_json
["margin_borrowed"])
542 @unittest.skipUnless("unit" in limits
, "Unit skipped")
543 class MarketTest(WebMockTestCase
):
545 super(MarketTest
, self
).setUp()
547 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
549 def test_values(self
):
550 m
= market
.Market(self
.ccxt
)
552 self
.assertEqual(self
.ccxt
, m
.ccxt
)
553 self
.assertFalse(m
.debug
)
554 self
.assertIsInstance(m
.report
, market
.ReportStore
)
555 self
.assertIsInstance(m
.trades
, market
.TradeStore
)
556 self
.assertIsInstance(m
.balances
, market
.BalanceStore
)
557 self
.assertEqual(m
, m
.report
.market
)
558 self
.assertEqual(m
, m
.trades
.market
)
559 self
.assertEqual(m
, m
.balances
.market
)
560 self
.assertEqual(m
, m
.ccxt
._market
)
562 m
= market
.Market(self
.ccxt
, debug
=True)
563 self
.assertTrue(m
.debug
)
565 m
= market
.Market(self
.ccxt
, debug
=False)
566 self
.assertFalse(m
.debug
)
568 @mock.patch("market.ccxt")
569 def test_from_config(self
, ccxt
):
570 with mock
.patch("market.ReportStore"):
571 ccxt
.poloniexE
.return_value
= self
.ccxt
572 self
.ccxt
.session
.request
.return_value
= "response"
574 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
)
576 self
.assertEqual(self
.ccxt
, m
.ccxt
)
578 self
.ccxt
.session
.request("GET", "URL", data
="data",
580 m
.report
.log_http_request
.assert_called_with('GET', 'URL', 'data',
581 'headers', 'response')
583 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, debug
=True)
584 self
.assertEqual(True, m
.debug
)
586 def test_get_ticker(self
):
587 m
= market
.Market(self
.ccxt
)
588 self
.ccxt
.fetch_ticker
.side_effect
= [
589 { "bid": 1, "ask": 3 }
,
590 market
.ExchangeError("foo"),
591 { "bid": 10, "ask": 40 }
,
592 market
.ExchangeError("foo"),
593 market
.ExchangeError("foo"),
596 ticker
= m
.get_ticker("ETH", "ETC")
597 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
598 self
.assertEqual(1, ticker
["bid"])
599 self
.assertEqual(3, ticker
["ask"])
600 self
.assertEqual(2, ticker
["average"])
601 self
.assertFalse(ticker
["inverted"])
603 ticker
= m
.get_ticker("ETH", "XVG")
604 self
.assertEqual(0.0625, ticker
["average"])
605 self
.assertTrue(ticker
["inverted"])
606 self
.assertIn("original", ticker
)
607 self
.assertEqual(10, ticker
["original"]["bid"])
609 ticker
= m
.get_ticker("XVG", "XMR")
610 self
.assertIsNone(ticker
)
612 self
.ccxt
.fetch_ticker
.assert_has_calls([
613 mock
.call("ETH/ETC"),
614 mock
.call("ETH/XVG"),
615 mock
.call("XVG/ETH"),
616 mock
.call("XVG/XMR"),
617 mock
.call("XMR/XVG"),
620 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
621 m1b
= market
.Market(self
.ccxt
)
622 m1b
.get_ticker("ETH", "ETC")
623 self
.ccxt
.fetch_ticker
.assert_not_called()
625 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniex
)
626 m2
= market
.Market(self
.ccxt
)
627 self
.ccxt
.fetch_ticker
.side_effect
= [
628 { "bid": 1, "ask": 3 }
,
629 { "bid": 1.2, "ask": 3.5 }
,
631 ticker1
= m2
.get_ticker("ETH", "ETC")
632 ticker2
= m2
.get_ticker("ETH", "ETC")
633 ticker3
= m2
.get_ticker("ETC", "ETH")
634 self
.ccxt
.fetch_ticker
.assert_called_once_with("ETH/ETC")
635 self
.assertEqual(1, ticker1
["bid"])
636 self
.assertDictEqual(ticker1
, ticker2
)
637 self
.assertDictEqual(ticker1
, ticker3
["original"])
639 ticker4
= m2
.get_ticker("ETH", "ETC", refresh
=True)
640 ticker5
= m2
.get_ticker("ETH", "ETC")
641 self
.assertEqual(1.2, ticker4
["bid"])
642 self
.assertDictEqual(ticker4
, ticker5
)
644 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.binance
)
645 m3
= market
.Market(self
.ccxt
)
646 self
.ccxt
.fetch_ticker
.side_effect
= [
647 { "bid": 1, "ask": 3 }
,
648 { "bid": 1.2, "ask": 3.5 }
,
650 ticker6
= m3
.get_ticker("ETH", "ETC")
651 m3
.ticker_cache_timestamp
-= 4
652 ticker7
= m3
.get_ticker("ETH", "ETC")
653 m3
.ticker_cache_timestamp
-= 2
654 ticker8
= m3
.get_ticker("ETH", "ETC")
655 self
.assertDictEqual(ticker6
, ticker7
)
656 self
.assertEqual(1.2, ticker8
["bid"])
658 def test_fetch_fees(self
):
659 m
= market
.Market(self
.ccxt
)
660 self
.ccxt
.fetch_fees
.return_value
= "Foo"
661 self
.assertEqual("Foo", m
.fetch_fees())
662 self
.ccxt
.fetch_fees
.assert_called_once()
663 self
.ccxt
.reset_mock()
664 self
.assertEqual("Foo", m
.fetch_fees())
665 self
.ccxt
.fetch_fees
.assert_not_called()
667 @mock.patch.object(portfolio
.Portfolio
, "repartition")
668 @mock.patch.object(market
.Market
, "get_ticker")
669 @mock.patch.object(market
.TradeStore
, "compute_trades")
670 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
671 repartition
.return_value
= {
672 "XEM": (D("0.75"), "long"),
673 "BTC": (D("0.25"), "long"),
675 def _get_ticker(c1
, c2
):
676 if c1
== "USDT" and c2
== "BTC":
677 return { "average": D("0.0001") }
678 if c1
== "XVG" and c2
== "BTC":
679 return { "average": D("0.000001") }
680 if c1
== "XEM" and c2
== "BTC":
681 return { "average": D("0.001") }
682 self
.fail("Should be called with {}, {}".format(c1
, c2
))
683 get_ticker
.side_effect
= _get_ticker
685 with mock
.patch("market.ReportStore"):
686 m
= market
.Market(self
.ccxt
)
687 self
.ccxt
.fetch_all_balances
.return_value
= {
689 "exchange_free": D("10000.0"),
690 "exchange_used": D("0.0"),
691 "exchange_total": D("10000.0"),
692 "total": D("10000.0")
695 "exchange_free": D("10000.0"),
696 "exchange_used": D("0.0"),
697 "exchange_total": D("10000.0"),
698 "total": D("10000.0")
702 m
.balances
.fetch_balances(tag
="tag")
705 compute_trades
.assert_called()
707 call
= compute_trades
.call_args
708 self
.assertEqual(1, call
[0][0]["USDT"].value
)
709 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
710 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
711 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
712 m
.report
.log_stage
.assert_called_once_with("prepare_trades")
713 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
715 @mock.patch.object(portfolio
.Portfolio
, "repartition")
716 @mock.patch.object(market
.Market
, "get_ticker")
717 @mock.patch.object(market
.TradeStore
, "compute_trades")
718 def test_update_trades(self
, compute_trades
, get_ticker
, repartition
):
719 repartition
.return_value
= {
720 "XEM": (D("0.75"), "long"),
721 "BTC": (D("0.25"), "long"),
723 def _get_ticker(c1
, c2
):
724 if c1
== "USDT" and c2
== "BTC":
725 return { "average": D("0.0001") }
726 if c1
== "XVG" and c2
== "BTC":
727 return { "average": D("0.000001") }
728 if c1
== "XEM" and c2
== "BTC":
729 return { "average": D("0.001") }
730 self
.fail("Should be called with {}, {}".format(c1
, c2
))
731 get_ticker
.side_effect
= _get_ticker
733 with mock
.patch("market.ReportStore"):
734 m
= market
.Market(self
.ccxt
)
735 self
.ccxt
.fetch_all_balances
.return_value
= {
737 "exchange_free": D("10000.0"),
738 "exchange_used": D("0.0"),
739 "exchange_total": D("10000.0"),
740 "total": D("10000.0")
743 "exchange_free": D("10000.0"),
744 "exchange_used": D("0.0"),
745 "exchange_total": D("10000.0"),
746 "total": D("10000.0")
750 m
.balances
.fetch_balances(tag
="tag")
753 compute_trades
.assert_called()
755 call
= compute_trades
.call_args
756 self
.assertEqual(1, call
[0][0]["USDT"].value
)
757 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
758 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
759 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
760 m
.report
.log_stage
.assert_called_once_with("update_trades")
761 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
763 @mock.patch.object(portfolio
.Portfolio
, "repartition")
764 @mock.patch.object(market
.Market
, "get_ticker")
765 @mock.patch.object(market
.TradeStore
, "compute_trades")
766 def test_prepare_trades_to_sell_all(self
, compute_trades
, get_ticker
, repartition
):
767 def _get_ticker(c1
, c2
):
768 if c1
== "USDT" and c2
== "BTC":
769 return { "average": D("0.0001") }
770 if c1
== "XVG" and c2
== "BTC":
771 return { "average": D("0.000001") }
772 self
.fail("Should be called with {}, {}".format(c1
, c2
))
773 get_ticker
.side_effect
= _get_ticker
775 with mock
.patch("market.ReportStore"):
776 m
= market
.Market(self
.ccxt
)
777 self
.ccxt
.fetch_all_balances
.return_value
= {
779 "exchange_free": D("10000.0"),
780 "exchange_used": D("0.0"),
781 "exchange_total": D("10000.0"),
782 "total": D("10000.0")
785 "exchange_free": D("10000.0"),
786 "exchange_used": D("0.0"),
787 "exchange_total": D("10000.0"),
788 "total": D("10000.0")
792 m
.balances
.fetch_balances(tag
="tag")
794 m
.prepare_trades_to_sell_all()
796 repartition
.assert_not_called()
797 compute_trades
.assert_called()
799 call
= compute_trades
.call_args
800 self
.assertEqual(1, call
[0][0]["USDT"].value
)
801 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
802 self
.assertEqual(D("1.01"), call
[0][1]["BTC"].value
)
803 m
.report
.log_stage
.assert_called_once_with("prepare_trades_to_sell_all")
804 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
806 @mock.patch.object(portfolio
.time
, "sleep")
807 @mock.patch.object(market
.TradeStore
, "all_orders")
808 def test_follow_orders(self
, all_orders
, time_mock
):
809 for debug
, sleep
in [
810 (False, None), (True, None),
811 (False, 12), (True, 12)]:
812 with self
.subTest(sleep
=sleep
, debug
=debug
), \
813 mock
.patch("market.ReportStore"):
814 m
= market
.Market(self
.ccxt
, debug
=debug
)
816 order_mock1
= mock
.Mock()
817 order_mock2
= mock
.Mock()
818 order_mock3
= mock
.Mock()
819 all_orders
.side_effect
= [
820 [order_mock1
, order_mock2
],
821 [order_mock1
, order_mock2
],
823 [order_mock1
, order_mock3
],
824 [order_mock1
, order_mock3
],
826 [order_mock1
, order_mock3
],
827 [order_mock1
, order_mock3
],
832 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
833 order_mock2
.get_status
.side_effect
= ["open"]
834 order_mock3
.get_status
.side_effect
= ["open", "closed"]
836 order_mock1
.trade
= mock
.Mock()
837 order_mock2
.trade
= mock
.Mock()
838 order_mock3
.trade
= mock
.Mock()
840 m
.follow_orders(sleep
=sleep
)
842 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
843 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
844 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
845 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
847 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
848 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
849 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
851 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
852 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
853 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
854 m
.report
.log_stage
.assert_called()
856 mock
.call("follow_orders_begin"),
857 mock
.call("follow_orders_tick_1"),
858 mock
.call("follow_orders_tick_2"),
859 mock
.call("follow_orders_tick_3"),
860 mock
.call("follow_orders_end"),
862 m
.report
.log_stage
.assert_has_calls(calls
)
863 m
.report
.log_orders
.assert_called()
864 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
866 mock
.call([order_mock1
, order_mock2
], tick
=1),
867 mock
.call([order_mock1
, order_mock3
], tick
=2),
868 mock
.call([order_mock1
, order_mock3
], tick
=3),
870 m
.report
.log_orders
.assert_has_calls(calls
)
872 mock
.call(order_mock1
, 3, finished
=True),
873 mock
.call(order_mock3
, 3, finished
=True),
875 m
.report
.log_order
.assert_has_calls(calls
)
879 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
880 time_mock
.assert_called_with(7)
882 time_mock
.assert_called_with(30)
884 time_mock
.assert_called_with(sleep
)
886 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
887 def test_move_balance(self
, fetch_balances
):
888 for debug
in [True, False]:
889 with self
.subTest(debug
=debug
),\
890 mock
.patch("market.ReportStore"):
891 m
= market
.Market(self
.ccxt
, debug
=debug
)
893 value_from
= portfolio
.Amount("BTC", "1.0")
894 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
895 value_to
= portfolio
.Amount("BTC", "10.0")
896 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
898 value_from
= portfolio
.Amount("BTC", "0.0")
899 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
900 value_to
= portfolio
.Amount("BTC", "-3.0")
901 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
903 value_from
= portfolio
.Amount("USDT", "0.0")
904 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
905 value_to
= portfolio
.Amount("USDT", "-50.0")
906 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
908 m
.trades
.all
= [trade1
, trade2
, trade3
]
909 balance1
= portfolio
.Balance("BTC", { "margin_free": "0" }
)
910 balance2
= portfolio
.Balance("USDT", { "margin_free": "100" }
)
911 balance3
= portfolio
.Balance("ETC", { "margin_free": "10" }
)
912 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
916 fetch_balances
.assert_called_with()
917 m
.report
.log_move_balances
.assert_called_once()
920 m
.report
.log_debug_action
.assert_called()
921 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
923 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
924 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 50, "margin", "exchange")
925 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 10, "margin", "exchange")
927 @unittest.skipUnless("unit" in limits
, "Unit skipped")
928 class TradeStoreTest(WebMockTestCase
):
929 def test_compute_trades(self
):
930 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
933 "XMR": portfolio
.Amount("BTC", D("0.9")),
934 "DASH": portfolio
.Amount("BTC", D("0.4")),
935 "XVG": portfolio
.Amount("BTC", D("-0.5")),
936 "BTC": portfolio
.Amount("BTC", D("0.5")),
939 "DASH": portfolio
.Amount("BTC", D("0.5")),
940 "XVG": portfolio
.Amount("BTC", D("0.1")),
941 "BTC": portfolio
.Amount("BTC", D("0.4")),
942 "ETH": portfolio
.Amount("BTC", D("0.3")),
952 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
953 trade_store
= market
.TradeStore(self
.m
)
954 trade_if_matching
.side_effect
= side_effect
956 trade_store
.compute_trades(values_in_base
,
957 new_repartition
, only
="only")
959 self
.assertEqual(5, trade_if_matching
.call_count
)
960 self
.assertEqual(3, len(trade_store
.all
))
961 self
.assertEqual([1, 4, 5], trade_store
.all
)
962 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
964 def test_trade_if_matching(self
):
966 with self
.subTest(only
="nope"):
967 trade_store
= market
.TradeStore(self
.m
)
968 result
= trade_store
.trade_if_matching(
969 portfolio
.Amount("BTC", D("0")),
970 portfolio
.Amount("BTC", D("0.3")),
972 self
.assertEqual(False, result
[0])
973 self
.assertIsInstance(result
[1], portfolio
.Trade
)
975 with self
.subTest(only
=None):
976 trade_store
= market
.TradeStore(self
.m
)
977 result
= trade_store
.trade_if_matching(
978 portfolio
.Amount("BTC", D("0")),
979 portfolio
.Amount("BTC", D("0.3")),
981 self
.assertEqual(True, result
[0])
983 with self
.subTest(only
="acquire"):
984 trade_store
= market
.TradeStore(self
.m
)
985 result
= trade_store
.trade_if_matching(
986 portfolio
.Amount("BTC", D("0")),
987 portfolio
.Amount("BTC", D("0.3")),
988 "ETH", only
="acquire")
989 self
.assertEqual(True, result
[0])
991 with self
.subTest(only
="dispose"):
992 trade_store
= market
.TradeStore(self
.m
)
993 result
= trade_store
.trade_if_matching(
994 portfolio
.Amount("BTC", D("0")),
995 portfolio
.Amount("BTC", D("0.3")),
996 "ETH", only
="dispose")
997 self
.assertEqual(False, result
[0])
999 def test_prepare_orders(self
):
1000 trade_store
= market
.TradeStore(self
.m
)
1002 trade_mock1
= mock
.Mock()
1003 trade_mock2
= mock
.Mock()
1005 trade_mock1
.prepare_order
.return_value
= 1
1006 trade_mock2
.prepare_order
.return_value
= 2
1008 trade_store
.all
.append(trade_mock1
)
1009 trade_store
.all
.append(trade_mock2
)
1011 trade_store
.prepare_orders()
1012 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1013 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1014 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1016 self
.m
.report
.log_orders
.reset_mock()
1018 trade_store
.prepare_orders(compute_value
="bla")
1019 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1020 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1021 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1023 trade_mock1
.prepare_order
.reset_mock()
1024 trade_mock2
.prepare_order
.reset_mock()
1025 self
.m
.report
.log_orders
.reset_mock()
1027 trade_mock1
.action
= "foo"
1028 trade_mock2
.action
= "bar"
1029 trade_store
.prepare_orders(only
="bar")
1030 trade_mock1
.prepare_order
.assert_not_called()
1031 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1032 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1034 def test_print_all_with_order(self
):
1035 trade_mock1
= mock
.Mock()
1036 trade_mock2
= mock
.Mock()
1037 trade_mock3
= mock
.Mock()
1038 trade_store
= market
.TradeStore(self
.m
)
1039 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1041 trade_store
.print_all_with_order()
1043 trade_mock1
.print_with_order
.assert_called()
1044 trade_mock2
.print_with_order
.assert_called()
1045 trade_mock3
.print_with_order
.assert_called()
1047 def test_run_orders(self
):
1048 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1049 order_mock1
= mock
.Mock()
1050 order_mock2
= mock
.Mock()
1051 order_mock3
= mock
.Mock()
1052 trade_store
= market
.TradeStore(self
.m
)
1054 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1056 trade_store
.run_orders()
1058 all_orders
.assert_called_with(state
="pending")
1060 order_mock1
.run
.assert_called()
1061 order_mock2
.run
.assert_called()
1062 order_mock3
.run
.assert_called()
1064 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1065 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1068 def test_all_orders(self
):
1069 trade_mock1
= mock
.Mock()
1070 trade_mock2
= mock
.Mock()
1072 order_mock1
= mock
.Mock()
1073 order_mock2
= mock
.Mock()
1074 order_mock3
= mock
.Mock()
1076 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1077 trade_mock2
.orders
= [order_mock3
]
1079 order_mock1
.status
= "pending"
1080 order_mock2
.status
= "open"
1081 order_mock3
.status
= "open"
1083 trade_store
= market
.TradeStore(self
.m
)
1084 trade_store
.all
.append(trade_mock1
)
1085 trade_store
.all
.append(trade_mock2
)
1087 orders
= trade_store
.all_orders()
1088 self
.assertEqual(3, len(orders
))
1090 open_orders
= trade_store
.all_orders(state
="open")
1091 self
.assertEqual(2, len(open_orders
))
1092 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1094 def test_update_all_orders_status(self
):
1095 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1096 order_mock1
= mock
.Mock()
1097 order_mock2
= mock
.Mock()
1098 order_mock3
= mock
.Mock()
1100 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1102 trade_store
= market
.TradeStore(self
.m
)
1104 trade_store
.update_all_orders_status()
1105 all_orders
.assert_called_with(state
="open")
1107 order_mock1
.get_status
.assert_called()
1108 order_mock2
.get_status
.assert_called()
1109 order_mock3
.get_status
.assert_called()
1112 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1113 class BalanceStoreTest(WebMockTestCase
):
1115 super(BalanceStoreTest
, self
).setUp()
1117 self
.fetch_balance
= {
1121 "exchange_total": 0,
1125 "exchange_free": D("6.0"),
1126 "exchange_used": D("1.2"),
1127 "exchange_total": D("7.2"),
1131 "exchange_free": 16,
1133 "exchange_total": 16,
1139 "exchange_total": 0,
1140 "margin_total": D("-1.0"),
1145 def test_in_currency(self
):
1146 self
.m
.get_ticker
.return_value
= {
1149 "average": D("0.1"),
1152 balance_store
= market
.BalanceStore(self
.m
)
1153 balance_store
.all
= {
1154 "BTC": portfolio
.Balance("BTC", {
1156 "exchange_total":"0.65",
1157 "exchange_free": "0.35",
1158 "exchange_used": "0.30"}),
1159 "ETH": portfolio
.Balance("ETH", {
1161 "exchange_total": 3,
1163 "exchange_used": 0}),
1166 amounts
= balance_store
.in_currency("BTC")
1167 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1168 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1169 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1170 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1172 self
.m
.report
.log_tickers
.reset_mock()
1174 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1175 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1176 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1177 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1179 self
.m
.report
.log_tickers
.reset_mock()
1181 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1182 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1183 self
.assertEqual(0, amounts
["ETH"].value
)
1184 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1185 "bid", "exchange_used")
1186 self
.m
.report
.log_tickers
.reset_mock()
1188 def test_fetch_balances(self
):
1189 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1191 balance_store
= market
.BalanceStore(self
.m
)
1193 balance_store
.fetch_balances()
1194 self
.assertNotIn("ETC", balance_store
.currencies())
1195 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1197 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1198 "exchange_total": "1", "exchange_free": "0",
1199 "exchange_used": "1" })
1200 balance_store
.fetch_balances(tag
="foo")
1201 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1202 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1203 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1205 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1206 def test_dispatch_assets(self
, repartition
):
1207 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1209 balance_store
= market
.BalanceStore(self
.m
)
1210 balance_store
.fetch_balances()
1212 self
.assertNotIn("XEM", balance_store
.currencies())
1214 repartition_hash
= {
1215 "XEM": (D("0.75"), "long"),
1216 "BTC": (D("0.26"), "long"),
1217 "DASH": (D("0.10"), "short"),
1219 repartition
.return_value
= repartition_hash
1221 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1222 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1223 self
.assertIn("XEM", balance_store
.currencies())
1224 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1225 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1226 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1227 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1228 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1229 "11.1"), amounts
, "medium", repartition_hash
)
1231 def test_currencies(self
):
1232 balance_store
= market
.BalanceStore(self
.m
)
1234 balance_store
.all
= {
1235 "BTC": portfolio
.Balance("BTC", {
1237 "exchange_total":"0.65",
1238 "exchange_free": "0.35",
1239 "exchange_used": "0.30"}),
1240 "ETH": portfolio
.Balance("ETH", {
1242 "exchange_total": 3,
1244 "exchange_used": 0}),
1246 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1248 def test_as_json(self
):
1249 balance_mock1
= mock
.Mock()
1250 balance_mock1
.as_json
.return_value
= 1
1252 balance_mock2
= mock
.Mock()
1253 balance_mock2
.as_json
.return_value
= 2
1255 balance_store
= market
.BalanceStore(self
.m
)
1256 balance_store
.all
= {
1257 "BTC": balance_mock1
,
1258 "ETH": balance_mock2
,
1261 as_json
= balance_store
.as_json()
1262 self
.assertEqual(1, as_json
["BTC"])
1263 self
.assertEqual(2, as_json
["ETH"])
1266 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1267 class ComputationTest(WebMockTestCase
):
1268 def test_compute_value(self
):
1269 compute
= mock
.Mock()
1270 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1271 compute
.assert_called_with("foo", "ask")
1273 compute
.reset_mock()
1274 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1275 compute
.assert_called_with("foo", "bid")
1277 compute
.reset_mock()
1278 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1279 compute
.assert_called_with("foo", "ask")
1281 compute
.reset_mock()
1282 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1283 compute
.assert_called_with("foo", "bid")
1285 compute
.reset_mock()
1286 portfolio
.Computation
.computations
["test"] = compute
1287 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1288 compute
.assert_called_with("foo", "bid")
1291 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1292 class TradeTest(WebMockTestCase
):
1294 def test_values_assertion(self
):
1295 value_from
= portfolio
.Amount("BTC", "1.0")
1296 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1297 value_to
= portfolio
.Amount("BTC", "1.0")
1298 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1299 self
.assertEqual("BTC", trade
.base_currency
)
1300 self
.assertEqual("ETH", trade
.currency
)
1301 self
.assertEqual(self
.m
, trade
.market
)
1303 with self
.assertRaises(AssertionError):
1304 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1305 with self
.assertRaises(AssertionError):
1306 value_from
.linked_to
= None
1307 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1308 with self
.assertRaises(AssertionError):
1309 value_from
.currency
= "ETH"
1310 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1312 value_from
= portfolio
.Amount("BTC", 0)
1313 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1314 self
.assertEqual(0, trade
.value_from
.linked_to
)
1316 def test_action(self
):
1317 value_from
= portfolio
.Amount("BTC", "1.0")
1318 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1319 value_to
= portfolio
.Amount("BTC", "1.0")
1320 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1322 self
.assertIsNone(trade
.action
)
1324 value_from
= portfolio
.Amount("BTC", "1.0")
1325 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1326 value_to
= portfolio
.Amount("BTC", "2.0")
1327 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1329 self
.assertIsNone(trade
.action
)
1331 value_from
= portfolio
.Amount("BTC", "0.5")
1332 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1333 value_to
= portfolio
.Amount("BTC", "1.0")
1334 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1336 self
.assertEqual("acquire", trade
.action
)
1338 value_from
= portfolio
.Amount("BTC", "0")
1339 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1340 value_to
= portfolio
.Amount("BTC", "-1.0")
1341 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1343 self
.assertEqual("acquire", trade
.action
)
1345 def test_order_action(self
):
1346 value_from
= portfolio
.Amount("BTC", "0.5")
1347 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1348 value_to
= portfolio
.Amount("BTC", "1.0")
1349 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1351 self
.assertEqual("buy", trade
.order_action(False))
1352 self
.assertEqual("sell", trade
.order_action(True))
1354 value_from
= portfolio
.Amount("BTC", "0")
1355 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1356 value_to
= portfolio
.Amount("BTC", "-1.0")
1357 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1359 self
.assertEqual("sell", trade
.order_action(False))
1360 self
.assertEqual("buy", trade
.order_action(True))
1362 def test_trade_type(self
):
1363 value_from
= portfolio
.Amount("BTC", "0.5")
1364 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1365 value_to
= portfolio
.Amount("BTC", "1.0")
1366 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1368 self
.assertEqual("long", trade
.trade_type
)
1370 value_from
= portfolio
.Amount("BTC", "0")
1371 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1372 value_to
= portfolio
.Amount("BTC", "-1.0")
1373 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1375 self
.assertEqual("short", trade
.trade_type
)
1377 def test_filled_amount(self
):
1378 value_from
= portfolio
.Amount("BTC", "0.5")
1379 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1380 value_to
= portfolio
.Amount("BTC", "1.0")
1381 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1383 order1
= mock
.Mock()
1384 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1386 order2
= mock
.Mock()
1387 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1388 trade
.orders
.append(order1
)
1389 trade
.orders
.append(order2
)
1391 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1392 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1393 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1395 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1396 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1397 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1399 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1400 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1401 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1403 @mock.patch.object(portfolio
.Computation
, "compute_value")
1404 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1405 @mock.patch.object(portfolio
, "Order")
1406 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1407 Order
.return_value
= "Order"
1409 with self
.subTest(desc
="Nothing to do"):
1410 value_from
= portfolio
.Amount("BTC", "10")
1411 value_from
.rate
= D("0.1")
1412 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1413 value_to
= portfolio
.Amount("BTC", "10")
1414 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1416 trade
.prepare_order()
1418 filled_amount
.assert_not_called()
1419 compute_value
.assert_not_called()
1420 self
.assertEqual(0, len(trade
.orders
))
1421 Order
.assert_not_called()
1423 self
.m
.get_ticker
.return_value
= { "inverted": False }
1424 with self
.subTest(desc
="Already filled"):
1425 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1426 compute_value
.return_value
= D("0.125")
1428 value_from
= portfolio
.Amount("BTC", "10")
1429 value_from
.rate
= D("0.1")
1430 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1431 value_to
= portfolio
.Amount("BTC", "0")
1432 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1434 trade
.prepare_order()
1436 filled_amount
.assert_called_with(in_base_currency
=False)
1437 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1438 self
.assertEqual(0, len(trade
.orders
))
1439 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1440 Order
.assert_not_called()
1442 with self
.subTest(action
="dispose", inverted
=False):
1443 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1444 compute_value
.return_value
= D("0.125")
1446 value_from
= portfolio
.Amount("BTC", "10")
1447 value_from
.rate
= D("0.1")
1448 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1449 value_to
= portfolio
.Amount("BTC", "1")
1450 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1452 trade
.prepare_order()
1454 filled_amount
.assert_called_with(in_base_currency
=False)
1455 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1456 self
.assertEqual(1, len(trade
.orders
))
1457 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1458 D("0.125"), "BTC", "long", self
.m
,
1459 trade
, close_if_possible
=False)
1461 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1462 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1463 compute_value
.return_value
= D("0.125")
1465 value_from
= portfolio
.Amount("BTC", "10")
1466 value_from
.rate
= D("0.1")
1467 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1468 value_to
= portfolio
.Amount("BTC", "1")
1469 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1471 trade
.prepare_order(close_if_possible
=True)
1473 filled_amount
.assert_called_with(in_base_currency
=False)
1474 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1475 self
.assertEqual(1, len(trade
.orders
))
1476 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1477 D("0.125"), "BTC", "long", self
.m
,
1478 trade
, close_if_possible
=True)
1480 with self
.subTest(action
="acquire", inverted
=False):
1481 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1482 compute_value
.return_value
= D("0.125")
1484 value_from
= portfolio
.Amount("BTC", "1")
1485 value_from
.rate
= D("0.1")
1486 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1487 value_to
= portfolio
.Amount("BTC", "10")
1488 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1490 trade
.prepare_order()
1492 filled_amount
.assert_called_with(in_base_currency
=True)
1493 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1494 self
.assertEqual(1, len(trade
.orders
))
1496 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1497 D("0.125"), "BTC", "long", self
.m
,
1498 trade
, close_if_possible
=False)
1500 with self
.subTest(close_if_possible
=True):
1501 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1502 compute_value
.return_value
= D("0.125")
1504 value_from
= portfolio
.Amount("BTC", "10")
1505 value_from
.rate
= D("0.1")
1506 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1507 value_to
= portfolio
.Amount("BTC", "0")
1508 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1510 trade
.prepare_order()
1512 filled_amount
.assert_called_with(in_base_currency
=False)
1513 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1514 self
.assertEqual(1, len(trade
.orders
))
1515 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1516 D("0.125"), "BTC", "long", self
.m
,
1517 trade
, close_if_possible
=True)
1519 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1520 with self
.subTest(action
="dispose", inverted
=True):
1521 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1522 compute_value
.return_value
= D("125")
1524 value_from
= portfolio
.Amount("BTC", "10")
1525 value_from
.rate
= D("0.01")
1526 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1527 value_to
= portfolio
.Amount("BTC", "1")
1528 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1530 trade
.prepare_order(compute_value
="foo")
1532 filled_amount
.assert_called_with(in_base_currency
=True)
1533 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1534 self
.assertEqual(1, len(trade
.orders
))
1535 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1536 D("125"), "FOO", "long", self
.m
,
1537 trade
, close_if_possible
=False)
1539 with self
.subTest(action
="acquire", inverted
=True):
1540 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1541 compute_value
.return_value
= D("125")
1543 value_from
= portfolio
.Amount("BTC", "1")
1544 value_from
.rate
= D("0.01")
1545 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1546 value_to
= portfolio
.Amount("BTC", "10")
1547 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1549 trade
.prepare_order(compute_value
="foo")
1551 filled_amount
.assert_called_with(in_base_currency
=False)
1552 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1553 self
.assertEqual(1, len(trade
.orders
))
1554 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1555 D("125"), "FOO", "long", self
.m
,
1556 trade
, close_if_possible
=False)
1559 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1560 def test_update_order(self
, prepare_order
):
1561 order_mock
= mock
.Mock()
1562 new_order_mock
= mock
.Mock()
1564 value_from
= portfolio
.Amount("BTC", "0.5")
1565 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1566 value_to
= portfolio
.Amount("BTC", "1.0")
1567 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1568 prepare_order
.return_value
= new_order_mock
1570 for i
in [0, 1, 3, 4, 6]:
1571 with self
.subTest(tick
=i
):
1572 trade
.update_order(order_mock
, i
)
1573 order_mock
.cancel
.assert_not_called()
1574 new_order_mock
.run
.assert_not_called()
1575 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1576 update
="waiting", compute_value
=None, new_order
=None)
1578 order_mock
.reset_mock()
1579 new_order_mock
.reset_mock()
1581 self
.m
.report
.log_order
.reset_mock()
1583 trade
.update_order(order_mock
, 2)
1584 order_mock
.cancel
.assert_called()
1585 new_order_mock
.run
.assert_called()
1586 prepare_order
.assert_called()
1587 self
.m
.report
.log_order
.assert_called()
1588 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1590 mock
.call(order_mock
, 2, update
="adjusting",
1591 compute_value
='lambda x, y: (x[y] + x["average"]) / 2',
1592 new_order
=new_order_mock
),
1593 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1595 self
.m
.report
.log_order
.assert_has_calls(calls
)
1597 order_mock
.reset_mock()
1598 new_order_mock
.reset_mock()
1600 self
.m
.report
.log_order
.reset_mock()
1602 trade
.update_order(order_mock
, 5)
1603 order_mock
.cancel
.assert_called()
1604 new_order_mock
.run
.assert_called()
1605 prepare_order
.assert_called()
1606 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1607 self
.m
.report
.log_order
.assert_called()
1609 mock
.call(order_mock
, 5, update
="adjusting",
1610 compute_value
='lambda x, y: (x[y]*2 + x["average"]) / 3',
1611 new_order
=new_order_mock
),
1612 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1614 self
.m
.report
.log_order
.assert_has_calls(calls
)
1616 order_mock
.reset_mock()
1617 new_order_mock
.reset_mock()
1619 self
.m
.report
.log_order
.reset_mock()
1621 trade
.update_order(order_mock
, 7)
1622 order_mock
.cancel
.assert_called()
1623 new_order_mock
.run
.assert_called()
1624 prepare_order
.assert_called_with(compute_value
="default")
1625 self
.m
.report
.log_order
.assert_called()
1626 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1628 mock
.call(order_mock
, 7, update
="market_fallback",
1629 compute_value
='default',
1630 new_order
=new_order_mock
),
1631 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1633 self
.m
.report
.log_order
.assert_has_calls(calls
)
1635 order_mock
.reset_mock()
1636 new_order_mock
.reset_mock()
1638 self
.m
.report
.log_order
.reset_mock()
1640 for i
in [10, 13, 16]:
1641 with self
.subTest(tick
=i
):
1642 trade
.update_order(order_mock
, i
)
1643 order_mock
.cancel
.assert_called()
1644 new_order_mock
.run
.assert_called()
1645 prepare_order
.assert_called_with(compute_value
="default")
1646 self
.m
.report
.log_order
.assert_called()
1647 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1649 mock
.call(order_mock
, i
, update
="market_adjust",
1650 compute_value
='default',
1651 new_order
=new_order_mock
),
1652 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1654 self
.m
.report
.log_order
.assert_has_calls(calls
)
1656 order_mock
.reset_mock()
1657 new_order_mock
.reset_mock()
1659 self
.m
.report
.log_order
.reset_mock()
1661 for i
in [8, 9, 11, 12]:
1662 with self
.subTest(tick
=i
):
1663 trade
.update_order(order_mock
, i
)
1664 order_mock
.cancel
.assert_not_called()
1665 new_order_mock
.run
.assert_not_called()
1666 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1667 compute_value
=None, new_order
=None)
1669 order_mock
.reset_mock()
1670 new_order_mock
.reset_mock()
1672 self
.m
.report
.log_order
.reset_mock()
1675 def test_print_with_order(self
):
1676 value_from
= portfolio
.Amount("BTC", "0.5")
1677 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1678 value_to
= portfolio
.Amount("BTC", "1.0")
1679 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1681 order_mock1
= mock
.Mock()
1682 order_mock1
.__repr__
= mock
.Mock()
1683 order_mock1
.__repr__
.return_value
= "Mock 1"
1684 order_mock2
= mock
.Mock()
1685 order_mock2
.__repr__
= mock
.Mock()
1686 order_mock2
.__repr__
.return_value
= "Mock 2"
1687 order_mock1
.mouvements
= []
1688 mouvement_mock1
= mock
.Mock()
1689 mouvement_mock1
.__repr__
= mock
.Mock()
1690 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1691 mouvement_mock2
= mock
.Mock()
1692 mouvement_mock2
.__repr__
= mock
.Mock()
1693 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1694 order_mock2
.mouvements
= [
1695 mouvement_mock1
, mouvement_mock2
1697 trade
.orders
.append(order_mock1
)
1698 trade
.orders
.append(order_mock2
)
1700 trade
.print_with_order()
1702 self
.m
.report
.print_log
.assert_called()
1703 calls
= self
.m
.report
.print_log
.mock_calls
1704 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1705 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1706 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1707 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1708 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1710 def test__repr(self
):
1711 value_from
= portfolio
.Amount("BTC", "0.5")
1712 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1713 value_to
= portfolio
.Amount("BTC", "1.0")
1714 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1716 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1718 def test_as_json(self
):
1719 value_from
= portfolio
.Amount("BTC", "0.5")
1720 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1721 value_to
= portfolio
.Amount("BTC", "1.0")
1722 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1724 as_json
= trade
.as_json()
1725 self
.assertEqual("acquire", as_json
["action"])
1726 self
.assertEqual(D("0.5"), as_json
["from"])
1727 self
.assertEqual(D("1.0"), as_json
["to"])
1728 self
.assertEqual("ETH", as_json
["currency"])
1729 self
.assertEqual("BTC", as_json
["base_currency"])
1731 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1732 class OrderTest(WebMockTestCase
):
1733 def test_values(self
):
1734 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1735 D("0.1"), "BTC", "long", "market", "trade")
1736 self
.assertEqual("buy", order
.action
)
1737 self
.assertEqual(10, order
.amount
.value
)
1738 self
.assertEqual("ETH", order
.amount
.currency
)
1739 self
.assertEqual(D("0.1"), order
.rate
)
1740 self
.assertEqual("BTC", order
.base_currency
)
1741 self
.assertEqual("market", order
.market
)
1742 self
.assertEqual("long", order
.trade_type
)
1743 self
.assertEqual("pending", order
.status
)
1744 self
.assertEqual("trade", order
.trade
)
1745 self
.assertIsNone(order
.id)
1746 self
.assertFalse(order
.close_if_possible
)
1748 def test__repr(self
):
1749 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1750 D("0.1"), "BTC", "long", "market", "trade")
1751 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1753 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1754 D("0.1"), "BTC", "long", "market", "trade",
1755 close_if_possible
=True)
1756 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1758 def test_as_json(self
):
1759 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1760 D("0.1"), "BTC", "long", "market", "trade")
1761 mouvement_mock1
= mock
.Mock()
1762 mouvement_mock1
.as_json
.return_value
= 1
1763 mouvement_mock2
= mock
.Mock()
1764 mouvement_mock2
.as_json
.return_value
= 2
1766 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1767 as_json
= order
.as_json()
1768 self
.assertEqual("buy", as_json
["action"])
1769 self
.assertEqual("long", as_json
["trade_type"])
1770 self
.assertEqual(10, as_json
["amount"])
1771 self
.assertEqual("ETH", as_json
["currency"])
1772 self
.assertEqual("BTC", as_json
["base_currency"])
1773 self
.assertEqual(D("0.1"), as_json
["rate"])
1774 self
.assertEqual("pending", as_json
["status"])
1775 self
.assertEqual(False, as_json
["close_if_possible"])
1776 self
.assertIsNone(as_json
["id"])
1777 self
.assertEqual([1, 2], as_json
["mouvements"])
1779 def test_account(self
):
1780 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1781 D("0.1"), "BTC", "long", "market", "trade")
1782 self
.assertEqual("exchange", order
.account
)
1784 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1785 D("0.1"), "BTC", "short", "market", "trade")
1786 self
.assertEqual("margin", order
.account
)
1788 def test_pending(self
):
1789 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1790 D("0.1"), "BTC", "long", "market", "trade")
1791 self
.assertTrue(order
.pending
)
1792 order
.status
= "open"
1793 self
.assertFalse(order
.pending
)
1795 def test_open(self
):
1796 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1797 D("0.1"), "BTC", "long", "market", "trade")
1798 self
.assertFalse(order
.open)
1799 order
.status
= "open"
1800 self
.assertTrue(order
.open)
1802 def test_finished(self
):
1803 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1804 D("0.1"), "BTC", "long", "market", "trade")
1805 self
.assertFalse(order
.finished
)
1806 order
.status
= "closed"
1807 self
.assertTrue(order
.finished
)
1808 order
.status
= "canceled"
1809 self
.assertTrue(order
.finished
)
1810 order
.status
= "error"
1811 self
.assertTrue(order
.finished
)
1813 @mock.patch.object(portfolio
.Order
, "fetch")
1814 def test_cancel(self
, fetch
):
1816 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1817 D("0.1"), "BTC", "long", self
.m
, "trade")
1818 order
.status
= "open"
1821 self
.m
.ccxt
.cancel_order
.assert_not_called()
1822 self
.m
.report
.log_debug_action
.assert_called_once()
1823 self
.m
.report
.log_debug_action
.reset_mock()
1824 self
.assertEqual("canceled", order
.status
)
1826 self
.m
.debug
= False
1827 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1828 D("0.1"), "BTC", "long", self
.m
, "trade")
1829 order
.status
= "open"
1833 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1834 fetch
.assert_called_once_with(force
=True)
1835 self
.m
.report
.log_debug_action
.assert_not_called()
1837 def test_dust_amount_remaining(self
):
1838 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1839 D("0.1"), "BTC", "long", self
.m
, "trade")
1840 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1841 self
.assertFalse(order
.dust_amount_remaining())
1843 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1844 self
.assertTrue(order
.dust_amount_remaining())
1846 @mock.patch.object(portfolio
.Order
, "fetch")
1847 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1848 def test_remaining_amount(self
, filled_amount
, fetch
):
1849 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1850 D("0.1"), "BTC", "long", self
.m
, "trade")
1852 self
.assertEqual(9, order
.remaining_amount().value
)
1853 order
.fetch
.assert_not_called()
1855 order
.status
= "open"
1856 self
.assertEqual(9, order
.remaining_amount().value
)
1857 fetch
.assert_called_once()
1859 @mock.patch.object(portfolio
.Order
, "fetch")
1860 def test_filled_amount(self
, fetch
):
1861 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1862 D("0.1"), "BTC", "long", self
.m
, "trade")
1863 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1864 "tradeID": 42, "type": "buy", "fee": "0.0015",
1865 "date": "2017-12-30 12:00:12", "rate": "0.1",
1866 "amount": "3", "total": "0.3"
1868 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1869 "tradeID": 43, "type": "buy", "fee": "0.0015",
1870 "date": "2017-12-30 13:00:12", "rate": "0.2",
1871 "amount": "2", "total": "0.4"
1873 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1874 fetch
.assert_not_called()
1875 order
.status
= "open"
1876 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1877 fetch
.assert_called_once()
1878 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1880 def test_fetch_mouvements(self
):
1881 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
1883 "tradeID": 42, "type": "buy", "fee": "0.0015",
1884 "date": "2017-12-30 12:00:12", "rate": "0.1",
1885 "amount": "3", "total": "0.3"
1888 "tradeID": 43, "type": "buy", "fee": "0.0015",
1889 "date": "2017-12-30 13:00:12", "rate": "0.2",
1890 "amount": "2", "total": "0.4"
1893 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1894 D("0.1"), "BTC", "long", self
.m
, "trade")
1896 order
.mouvements
= ["Foo", "Bar", "Baz"]
1898 order
.fetch_mouvements()
1900 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
1901 self
.assertEqual(2, len(order
.mouvements
))
1902 self
.assertEqual(42, order
.mouvements
[0].id)
1903 self
.assertEqual(43, order
.mouvements
[1].id)
1905 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
1906 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1907 D("0.1"), "BTC", "long", self
.m
, "trade")
1908 order
.fetch_mouvements()
1909 self
.assertEqual(0, len(order
.mouvements
))
1911 def test_mark_finished_order(self
):
1912 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1913 D("0.1"), "BTC", "short", self
.m
, "trade",
1914 close_if_possible
=True)
1915 order
.status
= "closed"
1916 self
.m
.debug
= False
1918 order
.mark_finished_order()
1919 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
1920 self
.m
.ccxt
.close_margin_position
.reset_mock()
1922 order
.status
= "open"
1923 order
.mark_finished_order()
1924 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1926 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1927 D("0.1"), "BTC", "short", self
.m
, "trade",
1928 close_if_possible
=False)
1929 order
.status
= "closed"
1930 order
.mark_finished_order()
1931 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1933 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1934 D("0.1"), "BTC", "short", self
.m
, "trade",
1935 close_if_possible
=True)
1936 order
.status
= "closed"
1937 order
.mark_finished_order()
1938 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1940 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1941 D("0.1"), "BTC", "long", self
.m
, "trade",
1942 close_if_possible
=True)
1943 order
.status
= "closed"
1944 order
.mark_finished_order()
1945 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1949 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1950 D("0.1"), "BTC", "short", self
.m
, "trade",
1951 close_if_possible
=True)
1952 order
.status
= "closed"
1954 order
.mark_finished_order()
1955 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1956 self
.m
.report
.log_debug_action
.assert_called_once()
1958 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
1959 def test_fetch(self
, fetch_mouvements
):
1960 time
= self
.time
.time()
1961 with mock
.patch
.object(portfolio
.time
, "time") as time_mock
:
1962 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1963 D("0.1"), "BTC", "long", self
.m
, "trade")
1965 with self
.subTest(debug
=True):
1968 time_mock
.assert_not_called()
1969 self
.m
.report
.log_debug_action
.assert_called_once()
1970 self
.m
.report
.log_debug_action
.reset_mock()
1971 order
.fetch(force
=True)
1972 time_mock
.assert_not_called()
1973 self
.m
.ccxt
.fetch_order
.assert_not_called()
1974 fetch_mouvements
.assert_not_called()
1975 self
.m
.report
.log_debug_action
.assert_called_once()
1976 self
.m
.report
.log_debug_action
.reset_mock()
1977 self
.assertIsNone(order
.fetch_cache_timestamp
)
1979 with self
.subTest(debug
=False):
1980 self
.m
.debug
= False
1981 time_mock
.return_value
= time
1982 self
.m
.ccxt
.fetch_order
.return_value
= {
1984 "datetime": "timestamp"
1988 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
1989 fetch_mouvements
.assert_called_once()
1990 self
.assertEqual("foo", order
.status
)
1991 self
.assertEqual("timestamp", order
.timestamp
)
1992 self
.assertEqual(time
, order
.fetch_cache_timestamp
)
1993 self
.assertEqual(1, len(order
.results
))
1995 self
.m
.ccxt
.fetch_order
.reset_mock()
1996 fetch_mouvements
.reset_mock()
1998 time_mock
.return_value
= time
+ 8
2000 self
.m
.ccxt
.fetch_order
.assert_not_called()
2001 fetch_mouvements
.assert_not_called()
2003 order
.fetch(force
=True)
2004 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
2005 fetch_mouvements
.assert_called_once()
2007 self
.m
.ccxt
.fetch_order
.reset_mock()
2008 fetch_mouvements
.reset_mock()
2010 time_mock
.return_value
= time
+ 19
2012 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
2013 fetch_mouvements
.assert_called_once()
2014 self
.m
.report
.log_debug_action
.assert_not_called()
2016 @mock.patch.object(portfolio
.Order
, "fetch")
2017 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2018 def test_get_status(self
, mark_finished_order
, fetch
):
2019 with self
.subTest(debug
=True):
2021 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2022 D("0.1"), "BTC", "long", self
.m
, "trade")
2023 self
.assertEqual("pending", order
.get_status())
2024 fetch
.assert_not_called()
2025 self
.m
.report
.log_debug_action
.assert_called_once()
2027 with self
.subTest(debug
=False, finished
=False):
2028 self
.m
.debug
= False
2029 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2030 D("0.1"), "BTC", "long", self
.m
, "trade")
2032 def update_status():
2033 order
.status
= "open"
2034 return update_status
2035 fetch
.side_effect
= _fetch(order
)
2036 self
.assertEqual("open", order
.get_status())
2037 mark_finished_order
.assert_not_called()
2038 fetch
.assert_called_once()
2040 mark_finished_order
.reset_mock()
2042 with self
.subTest(debug
=False, finished
=True):
2043 self
.m
.debug
= False
2044 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2045 D("0.1"), "BTC", "long", self
.m
, "trade")
2047 def update_status():
2048 order
.status
= "closed"
2049 return update_status
2050 fetch
.side_effect
= _fetch(order
)
2051 self
.assertEqual("closed", order
.get_status())
2052 mark_finished_order
.assert_called_once()
2053 fetch
.assert_called_once()
2056 self
.m
.ccxt
.order_precision
.return_value
= 4
2057 with self
.subTest(debug
=True):
2059 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2060 D("0.1"), "BTC", "long", self
.m
, "trade")
2062 self
.m
.ccxt
.create_order
.assert_not_called()
2063 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2064 self
.assertEqual("open", order
.status
)
2065 self
.assertEqual(1, len(order
.results
))
2066 self
.assertEqual(-1, order
.id)
2068 self
.m
.ccxt
.create_order
.reset_mock()
2069 with self
.subTest(debug
=False):
2070 self
.m
.debug
= False
2071 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2072 D("0.1"), "BTC", "long", self
.m
, "trade")
2073 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2075 self
.m
.ccxt
.create_order
.assert_called_once()
2076 self
.assertEqual(1, len(order
.results
))
2077 self
.assertEqual("open", order
.status
)
2079 self
.m
.ccxt
.create_order
.reset_mock()
2080 with self
.subTest(exception
=True):
2081 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2082 D("0.1"), "BTC", "long", self
.m
, "trade")
2083 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2085 self
.m
.ccxt
.create_order
.assert_called_once()
2086 self
.assertEqual(0, len(order
.results
))
2087 self
.assertEqual("error", order
.status
)
2088 self
.m
.report
.log_error
.assert_called_once()
2090 self
.m
.ccxt
.create_order
.reset_mock()
2091 with self
.subTest(dust_amount_exception
=True),\
2092 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2093 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2094 D("0.1"), "BTC", "long", self
.m
, "trade")
2095 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2097 self
.m
.ccxt
.create_order
.assert_called_once()
2098 self
.assertEqual(0, len(order
.results
))
2099 self
.assertEqual("closed", order
.status
)
2100 mark_finished_order
.assert_called_once()
2102 self
.m
.ccxt
.order_precision
.return_value
= 8
2103 self
.m
.ccxt
.create_order
.reset_mock()
2104 with self
.subTest(insufficient_funds
=True),\
2105 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2106 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2107 D("0.1"), "BTC", "long", self
.m
, "trade")
2108 self
.m
.ccxt
.create_order
.side_effect
= [
2109 portfolio
.InsufficientFunds
,
2110 portfolio
.InsufficientFunds
,
2111 portfolio
.InsufficientFunds
,
2115 self
.m
.ccxt
.create_order
.assert_has_calls([
2116 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2117 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2118 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2119 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2121 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2122 self
.assertEqual(1, len(order
.results
))
2123 self
.assertEqual("open", order
.status
)
2124 self
.assertEqual(4, order
.tries
)
2125 self
.m
.report
.log_error
.assert_called()
2126 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2128 self
.m
.ccxt
.order_precision
.return_value
= 8
2129 self
.m
.ccxt
.create_order
.reset_mock()
2130 self
.m
.report
.log_error
.reset_mock()
2131 with self
.subTest(insufficient_funds
=True),\
2132 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2133 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2134 D("0.1"), "BTC", "long", self
.m
, "trade")
2135 self
.m
.ccxt
.create_order
.side_effect
= [
2136 portfolio
.InsufficientFunds
,
2137 portfolio
.InsufficientFunds
,
2138 portfolio
.InsufficientFunds
,
2139 portfolio
.InsufficientFunds
,
2140 portfolio
.InsufficientFunds
,
2143 self
.m
.ccxt
.create_order
.assert_has_calls([
2144 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2145 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2146 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2147 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2148 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2150 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2151 self
.assertEqual(0, len(order
.results
))
2152 self
.assertEqual("error", order
.status
)
2153 self
.assertEqual(5, order
.tries
)
2154 self
.m
.report
.log_error
.assert_called()
2155 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2156 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
)
2159 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2160 class MouvementTest(WebMockTestCase
):
2161 def test_values(self
):
2162 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2163 "tradeID": 42, "type": "buy", "fee": "0.0015",
2164 "date": "2017-12-30 12:00:12", "rate": "0.1",
2165 "amount": "10", "total": "1"
2167 self
.assertEqual("ETH", mouvement
.currency
)
2168 self
.assertEqual("BTC", mouvement
.base_currency
)
2169 self
.assertEqual(42, mouvement
.id)
2170 self
.assertEqual("buy", mouvement
.action
)
2171 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2172 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2173 self
.assertEqual(D("0.1"), mouvement
.rate
)
2174 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2175 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2177 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2178 self
.assertIsNone(mouvement
.date
)
2179 self
.assertIsNone(mouvement
.id)
2180 self
.assertIsNone(mouvement
.action
)
2181 self
.assertEqual(-1, mouvement
.fee_rate
)
2182 self
.assertEqual(0, mouvement
.rate
)
2183 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2184 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2186 def test__repr(self
):
2187 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2188 "tradeID": 42, "type": "buy", "fee": "0.0015",
2189 "date": "2017-12-30 12:00:12", "rate": "0.1",
2190 "amount": "10", "total": "1"
2192 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2194 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2195 "tradeID": 42, "type": "buy",
2196 "date": "garbage", "rate": "0.1",
2197 "amount": "10", "total": "1"
2199 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2201 def test_as_json(self
):
2202 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2203 "tradeID": 42, "type": "buy", "fee": "0.0015",
2204 "date": "2017-12-30 12:00:12", "rate": "0.1",
2205 "amount": "10", "total": "1"
2207 as_json
= mouvement
.as_json()
2209 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2210 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2211 self
.assertEqual("buy", as_json
["action"])
2212 self
.assertEqual(D("10"), as_json
["total"])
2213 self
.assertEqual(D("1"), as_json
["total_in_base"])
2214 self
.assertEqual("BTC", as_json
["base_currency"])
2215 self
.assertEqual("ETH", as_json
["currency"])
2217 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2218 class ReportStoreTest(WebMockTestCase
):
2219 def test_add_log(self
):
2220 report_store
= market
.ReportStore(self
.m
)
2221 report_store
.add_log({"foo": "bar"}
)
2223 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2225 def test_set_verbose(self
):
2226 report_store
= market
.ReportStore(self
.m
)
2227 with self
.subTest(verbose
=True):
2228 report_store
.set_verbose(True)
2229 self
.assertTrue(report_store
.verbose_print
)
2231 with self
.subTest(verbose
=False):
2232 report_store
.set_verbose(False)
2233 self
.assertFalse(report_store
.verbose_print
)
2235 def test_print_log(self
):
2236 report_store
= market
.ReportStore(self
.m
)
2237 with self
.subTest(verbose
=True),\
2238 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2239 report_store
.set_verbose(True)
2240 report_store
.print_log("Coucou")
2241 report_store
.print_log(portfolio
.Amount("BTC", 1))
2242 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2244 with self
.subTest(verbose
=False),\
2245 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2246 report_store
.set_verbose(False)
2247 report_store
.print_log("Coucou")
2248 report_store
.print_log(portfolio
.Amount("BTC", 1))
2249 self
.assertEqual(stdout_mock
.getvalue(), "")
2251 def test_to_json(self
):
2252 report_store
= market
.ReportStore(self
.m
)
2253 report_store
.logs
.append({"foo": "bar"}
)
2254 self
.assertEqual('[{"foo": "bar"}]', report_store
.to_json())
2255 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2256 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}]', report_store
.to_json())
2257 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2258 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}, {"amount": "1.00000000 BTC"}]', report_store
.to_json())
2260 @mock.patch.object(market
.ReportStore
, "print_log")
2261 @mock.patch.object(market
.ReportStore
, "add_log")
2262 def test_log_stage(self
, add_log
, print_log
):
2263 report_store
= market
.ReportStore(self
.m
)
2264 report_store
.log_stage("foo")
2265 print_log
.assert_has_calls([
2266 mock
.call("-----------"),
2267 mock
.call("[Stage] foo"),
2269 add_log
.assert_called_once_with({'type': 'stage', 'stage': 'foo'}
)
2271 @mock.patch.object(market
.ReportStore
, "print_log")
2272 @mock.patch.object(market
.ReportStore
, "add_log")
2273 def test_log_balances(self
, add_log
, print_log
):
2274 report_store
= market
.ReportStore(self
.m
)
2275 self
.m
.balances
.as_json
.return_value
= "json"
2276 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2278 report_store
.log_balances(tag
="tag")
2279 print_log
.assert_has_calls([
2280 mock
.call("[Balance]"),
2284 add_log
.assert_called_once_with({
2290 @mock.patch.object(market
.ReportStore
, "print_log")
2291 @mock.patch.object(market
.ReportStore
, "add_log")
2292 def test_log_tickers(self
, add_log
, print_log
):
2293 report_store
= market
.ReportStore(self
.m
)
2295 "BTC": portfolio
.Amount("BTC", 10),
2296 "ETH": portfolio
.Amount("BTC", D("0.3"))
2298 amounts
["ETH"].rate
= D("0.1")
2300 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2301 print_log
.assert_not_called()
2302 add_log
.assert_called_once_with({
2304 'compute_value': 'default',
2305 'balance_type': 'total',
2318 @mock.patch.object(market
.ReportStore
, "print_log")
2319 @mock.patch.object(market
.ReportStore
, "add_log")
2320 def test_log_dispatch(self
, add_log
, print_log
):
2321 report_store
= market
.ReportStore(self
.m
)
2322 amount
= portfolio
.Amount("BTC", "10.3")
2324 "BTC": portfolio
.Amount("BTC", 10),
2325 "ETH": portfolio
.Amount("BTC", D("0.3"))
2327 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2328 print_log
.assert_not_called()
2329 add_log
.assert_called_once_with({
2331 'liquidity': 'medium',
2332 'repartition_ratio': 'repartition',
2343 @mock.patch.object(market
.ReportStore
, "print_log")
2344 @mock.patch.object(market
.ReportStore
, "add_log")
2345 def test_log_trades(self
, add_log
, print_log
):
2346 report_store
= market
.ReportStore(self
.m
)
2347 trade_mock1
= mock
.Mock()
2348 trade_mock2
= mock
.Mock()
2349 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2350 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2352 matching_and_trades
= [
2353 (True, trade_mock1
),
2354 (False, trade_mock2
),
2356 report_store
.log_trades(matching_and_trades
, "only")
2358 print_log
.assert_not_called()
2359 add_log
.assert_called_with({
2364 {'trade': '1', 'skipped': False}
,
2365 {'trade': '2', 'skipped': True}
2369 @mock.patch.object(market
.ReportStore
, "print_log")
2370 @mock.patch.object(market
.ReportStore
, "add_log")
2371 def test_log_orders(self
, add_log
, print_log
):
2372 report_store
= market
.ReportStore(self
.m
)
2374 order_mock1
= mock
.Mock()
2375 order_mock2
= mock
.Mock()
2377 order_mock1
.as_json
.return_value
= "order1"
2378 order_mock2
.as_json
.return_value
= "order2"
2380 orders
= [order_mock1
, order_mock2
]
2382 report_store
.log_orders(orders
, tick
="tick",
2383 only
="only", compute_value
="compute_value")
2385 print_log
.assert_called_once_with("[Orders]")
2386 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2388 add_log
.assert_called_with({
2391 'compute_value': 'compute_value',
2393 'orders': ['order1', 'order2']
2396 @mock.patch.object(market
.ReportStore
, "print_log")
2397 @mock.patch.object(market
.ReportStore
, "add_log")
2398 def test_log_order(self
, add_log
, print_log
):
2399 report_store
= market
.ReportStore(self
.m
)
2400 order_mock
= mock
.Mock()
2401 order_mock
.as_json
.return_value
= "order"
2402 new_order_mock
= mock
.Mock()
2403 new_order_mock
.as_json
.return_value
= "new_order"
2404 order_mock
.__repr
__ = mock
.Mock()
2405 order_mock
.__repr
__.return_value
= "Order Mock"
2406 new_order_mock
.__repr
__ = mock
.Mock()
2407 new_order_mock
.__repr
__.return_value
= "New order Mock"
2409 with self
.subTest(finished
=True):
2410 report_store
.log_order(order_mock
, 1, finished
=True)
2411 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2412 add_log
.assert_called_once_with({
2417 'compute_value': None,
2421 add_log
.reset_mock()
2422 print_log
.reset_mock()
2424 with self
.subTest(update
="waiting"):
2425 report_store
.log_order(order_mock
, 1, update
="waiting")
2426 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2427 add_log
.assert_called_once_with({
2430 'update': 'waiting',
2432 'compute_value': None,
2436 add_log
.reset_mock()
2437 print_log
.reset_mock()
2438 with self
.subTest(update
="adjusting"):
2439 report_store
.log_order(order_mock
, 3,
2440 update
="adjusting", new_order
=new_order_mock
,
2441 compute_value
="default")
2442 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2443 add_log
.assert_called_once_with({
2446 'update': 'adjusting',
2448 'compute_value': "default",
2449 'new_order': 'new_order'
2452 add_log
.reset_mock()
2453 print_log
.reset_mock()
2454 with self
.subTest(update
="market_fallback"):
2455 report_store
.log_order(order_mock
, 7,
2456 update
="market_fallback", new_order
=new_order_mock
)
2457 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2458 add_log
.assert_called_once_with({
2461 'update': 'market_fallback',
2463 'compute_value': None,
2464 'new_order': 'new_order'
2467 add_log
.reset_mock()
2468 print_log
.reset_mock()
2469 with self
.subTest(update
="market_adjusting"):
2470 report_store
.log_order(order_mock
, 17,
2471 update
="market_adjust", new_order
=new_order_mock
)
2472 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2473 add_log
.assert_called_once_with({
2476 'update': 'market_adjust',
2478 'compute_value': None,
2479 'new_order': 'new_order'
2482 @mock.patch.object(market
.ReportStore
, "print_log")
2483 @mock.patch.object(market
.ReportStore
, "add_log")
2484 def test_log_move_balances(self
, add_log
, print_log
):
2485 report_store
= market
.ReportStore(self
.m
)
2487 "BTC": portfolio
.Amount("BTC", 10),
2491 "BTC": portfolio
.Amount("BTC", 3),
2494 report_store
.log_move_balances(needed
, moving
)
2495 print_log
.assert_not_called()
2496 add_log
.assert_called_once_with({
2497 'type': 'move_balances',
2509 @mock.patch.object(market
.ReportStore
, "print_log")
2510 @mock.patch.object(market
.ReportStore
, "add_log")
2511 def test_log_http_request(self
, add_log
, print_log
):
2512 report_store
= market
.ReportStore(self
.m
)
2513 response
= mock
.Mock()
2514 response
.status_code
= 200
2515 response
.text
= "Hey"
2517 report_store
.log_http_request("method", "url", "body",
2518 "headers", response
)
2519 print_log
.assert_not_called()
2520 add_log
.assert_called_once_with({
2521 'type': 'http_request',
2525 'headers': 'headers',
2530 @mock.patch.object(market
.ReportStore
, "print_log")
2531 @mock.patch.object(market
.ReportStore
, "add_log")
2532 def test_log_error(self
, add_log
, print_log
):
2533 report_store
= market
.ReportStore(self
.m
)
2534 with self
.subTest(message
=None, exception
=None):
2535 report_store
.log_error("action")
2536 print_log
.assert_called_once_with("[Error] action")
2537 add_log
.assert_called_once_with({
2540 'exception_class': None,
2541 'exception_message': None,
2545 print_log
.reset_mock()
2546 add_log
.reset_mock()
2547 with self
.subTest(message
="Hey", exception
=None):
2548 report_store
.log_error("action", message
="Hey")
2549 print_log
.assert_has_calls([
2550 mock
.call("[Error] action"),
2553 add_log
.assert_called_once_with({
2556 'exception_class': None,
2557 'exception_message': None,
2561 print_log
.reset_mock()
2562 add_log
.reset_mock()
2563 with self
.subTest(message
=None, exception
=Exception("bouh")):
2564 report_store
.log_error("action", exception
=Exception("bouh"))
2565 print_log
.assert_has_calls([
2566 mock
.call("[Error] action"),
2567 mock
.call("\tException: bouh")
2569 add_log
.assert_called_once_with({
2572 'exception_class': "Exception",
2573 'exception_message': "bouh",
2577 print_log
.reset_mock()
2578 add_log
.reset_mock()
2579 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2580 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2581 print_log
.assert_has_calls([
2582 mock
.call("[Error] action"),
2583 mock
.call("\tException: bouh"),
2586 add_log
.assert_called_once_with({
2589 'exception_class': "Exception",
2590 'exception_message': "bouh",
2594 @mock.patch.object(market
.ReportStore
, "print_log")
2595 @mock.patch.object(market
.ReportStore
, "add_log")
2596 def test_log_debug_action(self
, add_log
, print_log
):
2597 report_store
= market
.ReportStore(self
.m
)
2598 report_store
.log_debug_action("Hey")
2600 print_log
.assert_called_once_with("[Debug] Hey")
2601 add_log
.assert_called_once_with({
2602 'type': 'debug_action',
2606 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2607 class HelperTest(WebMockTestCase
):
2608 def test_make_order(self
):
2609 self
.m
.get_ticker
.return_value
= {
2611 "average": D("0.1"),
2616 with self
.subTest(description
="nominal case"):
2617 helper
.make_order(self
.m
, 10, "ETH")
2619 self
.m
.report
.log_stage
.assert_has_calls([
2620 mock
.call("make_order_begin"),
2621 mock
.call("make_order_end"),
2623 self
.m
.balances
.fetch_balances
.assert_has_calls([
2624 mock
.call(tag
="make_order_begin"),
2625 mock
.call(tag
="make_order_end"),
2627 self
.m
.trades
.all
.append
.assert_called_once()
2628 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2629 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2630 self
.assertEqual(0, trade
.value_from
)
2631 self
.assertEqual("ETH", trade
.currency
)
2632 self
.assertEqual("BTC", trade
.base_currency
)
2633 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2634 self
.m
.trades
.run_orders
.assert_called_once_with()
2635 self
.m
.follow_orders
.assert_called_once_with()
2637 order
= trade
.orders
[0]
2638 self
.assertEqual(D("0.10"), order
.rate
)
2641 with self
.subTest(compute_value
="default"):
2642 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2643 compute_value
="ask")
2645 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2646 order
= trade
.orders
[0]
2647 self
.assertEqual(D("0.11"), order
.rate
)
2650 with self
.subTest(follow
=False):
2651 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2653 self
.m
.report
.log_stage
.assert_has_calls([
2654 mock
.call("make_order_begin"),
2655 mock
.call("make_order_end_not_followed"),
2657 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2659 self
.m
.trades
.all
.append
.assert_called_once()
2660 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2661 self
.assertEqual(0, trade
.value_from
)
2662 self
.assertEqual("ETH", trade
.currency
)
2663 self
.assertEqual("BTC", trade
.base_currency
)
2664 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2665 self
.m
.trades
.run_orders
.assert_called_once_with()
2666 self
.m
.follow_orders
.assert_not_called()
2667 self
.assertEqual(trade
.orders
[0], result
)
2670 with self
.subTest(base_currency
="USDT"):
2671 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2673 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2674 self
.assertEqual("BTC", trade
.currency
)
2675 self
.assertEqual("USDT", trade
.base_currency
)
2678 with self
.subTest(close_if_possible
=True):
2679 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2681 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2682 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2685 with self
.subTest(action
="dispose"):
2686 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2688 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2689 self
.assertEqual(0, trade
.value_to
)
2690 self
.assertEqual(1, trade
.value_from
.value
)
2691 self
.assertEqual("ETH", trade
.currency
)
2692 self
.assertEqual("BTC", trade
.base_currency
)
2695 with self
.subTest(compute_value
="default"):
2696 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2697 compute_value
="bid")
2699 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2700 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2702 def test_user_market(self
):
2703 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2704 mock
.patch("helper.main_parse_config") as main_parse_config
:
2705 with self
.subTest(debug
=False):
2706 main_parse_config
.return_value
= ["pg_config", "report_path"]
2707 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2708 m
= helper
.get_user_market("config_path.ini", 1)
2710 self
.assertIsInstance(m
, market
.Market
)
2711 self
.assertFalse(m
.debug
)
2713 with self
.subTest(debug
=True):
2714 main_parse_config
.return_value
= ["pg_config", "report_path"]
2715 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2716 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2718 self
.assertIsInstance(m
, market
.Market
)
2719 self
.assertTrue(m
.debug
)
2721 def test_main_store_report(self
):
2722 file_open
= mock
.mock_open()
2723 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2724 helper
.main_store_report(None, 1, self
.m
)
2725 file_open
.assert_not_called()
2727 file_open
= mock
.mock_open()
2728 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2729 mock
.patch
.object(helper
, "datetime") as time_mock
:
2730 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2731 self
.m
.report
.to_json
.return_value
= "json_content"
2733 helper
.main_store_report("present", 1, self
.m
)
2735 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2736 file_open().write
.assert_called_once_with("json_content")
2737 self
.m
.report
.to_json
.assert_called_once_with()
2739 with self
.subTest(file="error"),\
2740 mock
.patch("helper.open") as file_open
,\
2741 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2742 file_open
.side_effect
= FileNotFoundError
2744 helper
.main_store_report("error", 1, self
.m
)
2746 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2748 @mock.patch("helper.process_sell_all__1_all_sell")
2749 @mock.patch("helper.process_sell_all__2_all_buy")
2750 @mock.patch("portfolio.Portfolio.wait_for_recent")
2751 def test_main_process_market(self
, wait
, buy
, sell
):
2752 with self
.subTest(before
=False, after
=False):
2753 helper
.main_process_market("user", None)
2755 wait
.assert_not_called()
2756 buy
.assert_not_called()
2757 sell
.assert_not_called()
2762 with self
.subTest(before
=True, after
=False):
2763 helper
.main_process_market("user", None, before
=True)
2765 wait
.assert_not_called()
2766 buy
.assert_not_called()
2767 sell
.assert_called_once_with("user")
2772 with self
.subTest(before
=False, after
=True):
2773 helper
.main_process_market("user", None, after
=True)
2775 wait
.assert_called_once_with("user")
2776 buy
.assert_called_once_with("user")
2777 sell
.assert_not_called()
2782 with self
.subTest(before
=True, after
=True):
2783 helper
.main_process_market("user", None, before
=True, after
=True)
2785 wait
.assert_called_once_with("user")
2786 buy
.assert_called_once_with("user")
2787 sell
.assert_called_once_with("user")
2792 with self
.subTest(action
="print_balances"),\
2793 mock
.patch("helper.print_balances") as print_balances
:
2794 helper
.main_process_market("user", "print_balances")
2796 buy
.assert_not_called()
2797 wait
.assert_not_called()
2798 sell
.assert_not_called()
2799 print_balances
.assert_called_once_with("user")
2801 with self
.subTest(action
="print_orders"),\
2802 mock
.patch("helper.print_orders") as print_orders
:
2803 helper
.main_process_market("user", "print_orders")
2805 buy
.assert_not_called()
2806 wait
.assert_not_called()
2807 sell
.assert_not_called()
2808 print_orders
.assert_called_once_with("user")
2810 with self
.subTest(action
="unknown"),\
2811 self
.assertRaises(NotImplementedError):
2812 helper
.main_process_market("user", "unknown")
2814 @mock.patch.object(helper
, "psycopg2")
2815 def test_fetch_markets(self
, psycopg2
):
2816 connect_mock
= mock
.Mock()
2817 cursor_mock
= mock
.MagicMock()
2818 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2820 connect_mock
.cursor
.return_value
= cursor_mock
2821 psycopg2
.connect
.return_value
= connect_mock
2823 with self
.subTest(user
=None):
2824 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2826 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2827 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2829 self
.assertEqual(["row_1", "row_2"], rows
)
2831 psycopg2
.connect
.reset_mock()
2832 cursor_mock
.execute
.reset_mock()
2833 with self
.subTest(user
=1):
2834 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
2836 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2837 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
2839 self
.assertEqual(["row_1", "row_2"], rows
)
2841 @mock.patch.object(helper
.sys
, "exit")
2842 def test_main_parse_args(self
, exit
):
2843 with self
.subTest(config
="config.ini"):
2844 args
= helper
.main_parse_args([])
2845 self
.assertEqual("config.ini", args
.config
)
2846 self
.assertFalse(args
.before
)
2847 self
.assertFalse(args
.after
)
2848 self
.assertFalse(args
.debug
)
2850 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
2851 self
.assertTrue(args
.before
)
2852 self
.assertTrue(args
.after
)
2853 self
.assertTrue(args
.debug
)
2855 exit
.assert_not_called()
2857 with self
.subTest(config
="inexistant"),\
2858 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2859 args
= helper
.main_parse_args(["--config", "foo.bar"])
2860 exit
.assert_called_once_with(1)
2861 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
2863 @mock.patch.object(helper
.sys
, "exit")
2864 @mock.patch("helper.configparser")
2865 @mock.patch("helper.os")
2866 def test_main_parse_config(self
, os
, configparser
, exit
):
2867 with self
.subTest(pg_config
=True, report_path
=None):
2868 config_mock
= mock
.MagicMock()
2869 configparser
.ConfigParser
.return_value
= config_mock
2870 def config(element
):
2871 return element
== "postgresql"
2873 config_mock
.__contains
__.side_effect
= config
2874 config_mock
.__getitem
__.return_value
= "pg_config"
2876 result
= helper
.main_parse_config("configfile")
2878 config_mock
.read
.assert_called_with("configfile")
2880 self
.assertEqual(["pg_config", None], result
)
2882 with self
.subTest(pg_config
=True, report_path
="present"):
2883 config_mock
= mock
.MagicMock()
2884 configparser
.ConfigParser
.return_value
= config_mock
2886 config_mock
.__contains
__.return_value
= True
2887 config_mock
.__getitem
__.side_effect
= [
2888 {"report_path": "report_path"}
,
2889 {"report_path": "report_path"}
,
2893 os
.path
.exists
.return_value
= False
2894 result
= helper
.main_parse_config("configfile")
2896 config_mock
.read
.assert_called_with("configfile")
2897 self
.assertEqual(["pg_config", "report_path"], result
)
2898 os
.path
.exists
.assert_called_once_with("report_path")
2899 os
.makedirs
.assert_called_once_with("report_path")
2901 with self
.subTest(pg_config
=False),\
2902 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2903 config_mock
= mock
.MagicMock()
2904 configparser
.ConfigParser
.return_value
= config_mock
2905 result
= helper
.main_parse_config("configfile")
2907 config_mock
.read
.assert_called_with("configfile")
2908 exit
.assert_called_once_with(1)
2909 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
2912 def test_print_orders(self
):
2913 helper
.print_orders(self
.m
)
2915 self
.m
.report
.log_stage
.assert_called_with("print_orders")
2916 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
2917 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
2918 compute_value
="average")
2919 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
2921 def test_print_balances(self
):
2922 self
.m
.balances
.in_currency
.return_value
= {
2923 "BTC": portfolio
.Amount("BTC", "0.65"),
2924 "ETH": portfolio
.Amount("BTC", "0.3"),
2927 helper
.print_balances(self
.m
)
2929 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
2930 self
.m
.balances
.fetch_balances
.assert_called_with()
2931 self
.m
.report
.print_log
.assert_has_calls([
2932 mock
.call("total:"),
2933 mock
.call(portfolio
.Amount("BTC", "0.95")),
2936 def test_process_sell_needed__1_sell(self
):
2937 helper
.process_sell_needed__1_sell(self
.m
)
2939 self
.m
.balances
.fetch_balances
.assert_has_calls([
2940 mock
.call(tag
="process_sell_needed__1_sell_begin"),
2941 mock
.call(tag
="process_sell_needed__1_sell_end"),
2943 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
2945 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
2947 self
.m
.trades
.run_orders
.assert_called()
2948 self
.m
.follow_orders
.assert_called()
2949 self
.m
.report
.log_stage
.assert_has_calls([
2950 mock
.call("process_sell_needed__1_sell_begin"),
2951 mock
.call("process_sell_needed__1_sell_end")
2954 def test_process_sell_needed__2_buy(self
):
2955 helper
.process_sell_needed__2_buy(self
.m
)
2957 self
.m
.balances
.fetch_balances
.assert_has_calls([
2958 mock
.call(tag
="process_sell_needed__2_buy_begin"),
2959 mock
.call(tag
="process_sell_needed__2_buy_end"),
2961 self
.m
.update_trades
.assert_called_with(base_currency
="BTC",
2962 liquidity
="medium", only
="acquire")
2963 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
2965 self
.m
.move_balances
.assert_called_with()
2966 self
.m
.trades
.run_orders
.assert_called()
2967 self
.m
.follow_orders
.assert_called()
2968 self
.m
.report
.log_stage
.assert_has_calls([
2969 mock
.call("process_sell_needed__2_buy_begin"),
2970 mock
.call("process_sell_needed__2_buy_end")
2973 def test_process_sell_all__1_sell(self
):
2974 helper
.process_sell_all__1_all_sell(self
.m
)
2976 self
.m
.balances
.fetch_balances
.assert_has_calls([
2977 mock
.call(tag
="process_sell_all__1_all_sell_begin"),
2978 mock
.call(tag
="process_sell_all__1_all_sell_end"),
2980 self
.m
.prepare_trades_to_sell_all
.assert_called_with(base_currency
="BTC")
2981 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
2982 self
.m
.trades
.run_orders
.assert_called()
2983 self
.m
.follow_orders
.assert_called()
2984 self
.m
.report
.log_stage
.assert_has_calls([
2985 mock
.call("process_sell_all__1_all_sell_begin"),
2986 mock
.call("process_sell_all__1_all_sell_end")
2989 def test_process_sell_all__2_all_buy(self
):
2990 helper
.process_sell_all__2_all_buy(self
.m
)
2992 self
.m
.balances
.fetch_balances
.assert_has_calls([
2993 mock
.call(tag
="process_sell_all__2_all_buy_begin"),
2994 mock
.call(tag
="process_sell_all__2_all_buy_end"),
2996 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
2998 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
2999 self
.m
.move_balances
.assert_called_with()
3000 self
.m
.trades
.run_orders
.assert_called()
3001 self
.m
.follow_orders
.assert_called()
3002 self
.m
.report
.log_stage
.assert_has_calls([
3003 mock
.call("process_sell_all__2_all_buy_begin"),
3004 mock
.call("process_sell_all__2_all_buy_end")
3007 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3008 class AcceptanceTest(WebMockTestCase
):
3009 @unittest.expectedFailure
3010 def test_success_sell_only_necessary(self
):
3011 # FIXME: catch stdout
3012 self
.m
.report
.verbose_print
= False
3015 "exchange_free": D("1.0"),
3016 "exchange_used": D("0.0"),
3017 "exchange_total": D("1.0"),
3021 "exchange_free": D("4.0"),
3022 "exchange_used": D("0.0"),
3023 "exchange_total": D("4.0"),
3027 "exchange_free": D("1000.0"),
3028 "exchange_used": D("0.0"),
3029 "exchange_total": D("1000.0"),
3030 "total": D("1000.0"),
3034 "ETH": (D("0.25"), "long"),
3035 "ETC": (D("0.25"), "long"),
3036 "BTC": (D("0.4"), "long"),
3037 "BTD": (D("0.01"), "short"),
3038 "B2X": (D("0.04"), "long"),
3039 "USDT": (D("0.05"), "long"),
3042 def fetch_ticker(symbol
):
3043 if symbol
== "ETH/BTC":
3045 "symbol": "ETH/BTC",
3049 if symbol
== "ETC/BTC":
3051 "symbol": "ETC/BTC",
3055 if symbol
== "XVG/BTC":
3057 "symbol": "XVG/BTC",
3058 "bid": D("0.00003"),
3061 if symbol
== "BTD/BTC":
3063 "symbol": "BTD/BTC",
3067 if symbol
== "B2X/BTC":
3069 "symbol": "B2X/BTC",
3073 if symbol
== "USDT/BTC":
3074 raise helper
.ExchangeError
3075 if symbol
== "BTC/USDT":
3077 "symbol": "BTC/USDT",
3081 self
.fail("Shouldn't have been called with {}".format(symbol
))
3083 market
= mock
.Mock()
3084 market
.fetch_all_balances
.return_value
= fetch_balance
3085 market
.fetch_ticker
.side_effect
= fetch_ticker
3086 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3088 helper
.prepare_trades(market
)
3090 balances
= portfolio
.BalanceStore
.all
3091 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3092 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3093 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3096 trades
= portfolio
.TradeStore
.all
3097 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3098 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3099 self
.assertEqual("dispose", trades
[0].action
)
3101 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3102 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3103 self
.assertEqual("acquire", trades
[1].action
)
3105 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3106 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3107 self
.assertEqual("dispose", trades
[2].action
)
3109 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3110 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3111 self
.assertEqual("acquire", trades
[3].action
)
3113 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3114 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3115 self
.assertEqual("acquire", trades
[4].action
)
3117 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3118 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3119 self
.assertEqual("acquire", trades
[5].action
)
3122 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3124 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3125 self
.assertEqual(2, len(all_orders
))
3126 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3127 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3128 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3129 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3132 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3133 self
.assertEqual("limit", type)
3134 if symbol
== "ETH/BTC":
3135 self
.assertEqual("sell", action
)
3136 self
.assertEqual(D('0.66666666'), amount
)
3137 self
.assertEqual(D("0.14014"), price
)
3138 elif symbol
== "XVG/BTC":
3139 self
.assertEqual("sell", action
)
3140 self
.assertEqual(1000, amount
)
3141 self
.assertEqual(D("0.00003003"), price
)
3143 self
.fail("I shouldn't have been called")
3148 market
.create_order
.side_effect
= create_order
3149 market
.order_precision
.return_value
= 8
3152 portfolio
.TradeStore
.run_orders()
3154 self
.assertEqual("open", all_orders
[0].status
)
3155 self
.assertEqual("open", all_orders
[1].status
)
3157 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3158 market
.privatePostReturnOrderTrades
.return_value
= [
3160 "tradeID": 42, "type": "buy", "fee": "0.0015",
3161 "date": "2017-12-30 12:00:12", "rate": "0.1",
3162 "amount": "10", "total": "1"
3165 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3167 helper
.follow_orders(verbose
=False)
3169 sleep
.assert_called_with(30)
3171 for order
in all_orders
:
3172 self
.assertEqual("closed", order
.status
)
3176 "exchange_free": D("1.0") / 3,
3177 "exchange_used": D("0.0"),
3178 "exchange_total": D("1.0") / 3,
3180 "total": D("1.0") / 3,
3183 "exchange_free": D("0.134"),
3184 "exchange_used": D("0.0"),
3185 "exchange_total": D("0.134"),
3187 "total": D("0.134"),
3190 "exchange_free": D("4.0"),
3191 "exchange_used": D("0.0"),
3192 "exchange_total": D("4.0"),
3197 "exchange_free": D("0.0"),
3198 "exchange_used": D("0.0"),
3199 "exchange_total": D("0.0"),
3204 market
.fetch_all_balances
.return_value
= fetch_balance
3206 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3208 helper
.update_trades(market
, only
="acquire", compute_value
="average")
3210 balances
= portfolio
.BalanceStore
.all
3211 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3212 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3213 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3214 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3217 trades
= portfolio
.TradeStore
.all
3218 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3219 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3220 self
.assertEqual("dispose", trades
[0].action
)
3222 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3223 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3224 self
.assertEqual("acquire", trades
[1].action
)
3226 self
.assertNotIn("BTC", trades
)
3228 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3229 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3230 self
.assertEqual("dispose", trades
[2].action
)
3232 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3233 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3234 self
.assertEqual("acquire", trades
[3].action
)
3236 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3237 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3238 self
.assertEqual("acquire", trades
[4].action
)
3240 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3241 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3242 self
.assertEqual("acquire", trades
[5].action
)
3245 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3247 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3248 self
.assertEqual(4, len(all_orders
))
3249 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3250 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3251 self
.assertEqual("buy", all_orders
[0].action
)
3252 self
.assertEqual("long", all_orders
[0].trade_type
)
3254 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3255 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3256 self
.assertEqual("sell", all_orders
[1].action
)
3257 self
.assertEqual("short", all_orders
[1].trade_type
)
3259 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3260 self
.assertAlmostEqual(0, diff
.value
)
3261 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3262 self
.assertEqual("buy", all_orders
[2].action
)
3263 self
.assertEqual("long", all_orders
[2].trade_type
)
3265 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3266 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3267 self
.assertEqual("sell", all_orders
[3].action
)
3268 self
.assertEqual("long", all_orders
[3].trade_type
)
3272 # Move balances to margin
3276 # portfolio.TradeStore.run_orders()
3278 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3280 helper
.follow_orders(verbose
=False)
3282 sleep
.assert_called_with(30)
3284 if __name__
== '__main__':