4 from decimal
import Decimal
as D
5 from unittest
import mock
8 from io
import StringIO
11 limits
= ["acceptance", "unit"]
12 for test_type
in limits
:
13 if "--no{}".format(test_type
) in sys
.argv
:
14 sys
.argv
.remove("--no{}".format(test_type
))
15 limits
.remove(test_type
)
16 if "--only{}".format(test_type
) in sys
.argv
:
17 sys
.argv
.remove("--only{}".format(test_type
))
21 class WebMockTestCase(unittest
.TestCase
):
25 super(WebMockTestCase
, self
).setUp()
26 self
.wm
= requests_mock
.Mocker()
30 mock
.patch
.multiple(portfolio
.BalanceStore
,
32 mock
.patch
.multiple(portfolio
.TradeStore
,
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(helper
,
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()
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)
78 portfolio.Portfolio.get_cryptoportfolio()
79 self.assertIsNone(portfolio.Portfolio.data)
80 self.assertEqual(2, self.wm.call_count)
82 portfolio.Portfolio.data = "Foo"
83 portfolio.Portfolio.get_cryptoportfolio()
84 self.assertEqual("Foo", portfolio.Portfolio.data)
85 self.assertEqual(3, self.wm.call_count)
87 def test_parse_cryptoportfolio(self):
88 portfolio.Portfolio.parse_cryptoportfolio()
92 list(portfolio.Portfolio.liquidities.keys()))
94 liquidities = portfolio.Portfolio.liquidities
95 self.assertEqual(10, len(liquidities["medium"].keys()))
96 self.assertEqual(10, len(liquidities["high"].keys()))
99 'BTC
': (D("0.2857"), "long"),
100 'DGB
': (D("0.1015"), "long"),
101 'DOGE
': (D("0.1805"), "long"),
102 'SC
': (D("0.0623"), "long"),
103 'ZEC
': (D("0.3701"), "long"),
105 date = portfolio.datetime(2018, 1, 8)
106 self.assertDictEqual(expected, liquidities["high"][date])
109 'BTC
': (D("1.1102e-16"), "long"),
110 'ETC
': (D("0.1"), "long"),
111 'FCT
': (D("0.1"), "long"),
112 'GAS
': (D("0.1"), "long"),
113 'NAV
': (D("0.1"), "long"),
114 'OMG
': (D("0.1"), "long"),
115 'OMNI
': (D("0.1"), "long"),
116 'PPC
': (D("0.1"), "long"),
117 'RIC
': (D("0.1"), "long"),
118 'VIA
': (D("0.1"), "long"),
119 'XCP
': (D("0.1"), "long"),
121 self.assertDictEqual(expected, liquidities["medium"][date])
122 self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date)
124 # It doesn't refetch the data when available
125 portfolio
.Portfolio
.parse_cryptoportfolio()
127 self
.assertEqual(1, self
.wm
.call_count
)
129 portfolio
.Portfolio
.parse_cryptoportfolio(refetch
=True)
130 self
.assertEqual(2, self
.wm
.call_count
)
132 def test_repartition(self
):
134 'BTC': (D("1.1102e-16"), "long"),
135 'USDT': (D("0.1"), "long"),
136 'ETC': (D("0.1"), "long"),
137 'FCT': (D("0.1"), "long"),
138 'OMG': (D("0.1"), "long"),
139 'STEEM': (D("0.1"), "long"),
140 'STRAT': (D("0.1"), "long"),
141 'XEM': (D("0.1"), "long"),
142 'XMR': (D("0.1"), "long"),
143 'XVC': (D("0.1"), "long"),
144 'ZRX': (D("0.1"), "long"),
147 'USDT': (D("0.1226"), "long"),
148 'BTC': (D("0.1429"), "long"),
149 'ETC': (D("0.1127"), "long"),
150 'ETH': (D("0.1569"), "long"),
151 'FCT': (D("0.3341"), "long"),
152 'GAS': (D("0.1308"), "long"),
155 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition())
156 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(liquidity
="medium"))
157 self
.assertEqual(expected_high
, portfolio
.Portfolio
.repartition(liquidity
="high"))
159 self
.assertEqual(1, self
.wm
.call_count
)
161 portfolio
.Portfolio
.repartition()
162 self
.assertEqual(1, self
.wm
.call_count
)
164 portfolio
.Portfolio
.repartition(refetch
=True)
165 self
.assertEqual(2, self
.wm
.call_count
)
167 @mock.patch.object(portfolio
.time
, "sleep")
168 @mock.patch.object(portfolio
.Portfolio
, "repartition")
169 def test_wait_for_recent(self
, repartition
, sleep
):
171 def _repartition(refetch
):
172 self
.assertTrue(refetch
)
174 portfolio
.Portfolio
.last_date
= portfolio
.datetime
.now()\
175 - portfolio
.timedelta(10)\
176 + portfolio
.timedelta(self
.call_count
)
177 repartition
.side_effect
= _repartition
179 portfolio
.Portfolio
.wait_for_recent()
180 sleep
.assert_called_with(30)
181 self
.assertEqual(6, sleep
.call_count
)
182 self
.assertEqual(7, repartition
.call_count
)
185 repartition
.reset_mock()
186 portfolio
.Portfolio
.last_date
= None
188 portfolio
.Portfolio
.wait_for_recent(delta
=15)
189 sleep
.assert_not_called()
190 self
.assertEqual(1, repartition
.call_count
)
193 repartition
.reset_mock()
194 portfolio
.Portfolio
.last_date
= None
196 portfolio
.Portfolio
.wait_for_recent(delta
=1)
197 sleep
.assert_called_with(30)
198 self
.assertEqual(9, sleep
.call_count
)
199 self
.assertEqual(10, repartition
.call_count
)
201 @unittest.skipUnless("unit" in limits
, "Unit skipped")
202 class AmountTest(WebMockTestCase
):
203 def test_values(self
):
204 amount
= portfolio
.Amount("BTC", "0.65")
205 self
.assertEqual(D("0.65"), amount
.value
)
206 self
.assertEqual("BTC", amount
.currency
)
208 def test_in_currency(self
):
209 amount
= portfolio
.Amount("ETC", 10)
211 self
.assertEqual(amount
, amount
.in_currency("ETC", None))
213 ticker_mock
= unittest
.mock
.Mock()
214 with mock
.patch
.object(helper
, 'get_ticker', new
=ticker_mock
):
215 ticker_mock
.return_value
= None
217 self
.assertRaises(Exception, amount
.in_currency
, "ETH", None)
219 with mock
.patch
.object(helper
, 'get_ticker', new
=ticker_mock
):
220 ticker_mock
.return_value
= {
226 converted_amount
= amount
.in_currency("ETH", None)
228 self
.assertEqual(D("3.0"), converted_amount
.value
)
229 self
.assertEqual("ETH", converted_amount
.currency
)
230 self
.assertEqual(amount
, converted_amount
.linked_to
)
231 self
.assertEqual("bar", converted_amount
.ticker
["foo"])
233 converted_amount
= amount
.in_currency("ETH", None, action
="bid", compute_value
="default")
234 self
.assertEqual(D("2"), converted_amount
.value
)
236 converted_amount
= amount
.in_currency("ETH", None, compute_value
="ask")
237 self
.assertEqual(D("4"), converted_amount
.value
)
239 converted_amount
= amount
.in_currency("ETH", None, rate
=D("0.02"))
240 self
.assertEqual(D("0.2"), converted_amount
.value
)
242 def test__round(self
):
243 amount
= portfolio
.Amount("BAR", portfolio
.D("1.23456789876"))
244 self
.assertEqual(D("1.23456789"), round(amount
).value
)
245 self
.assertEqual(D("1.23"), round(amount
, 2).value
)
248 amount
= portfolio
.Amount("SC", -120)
249 self
.assertEqual(120, abs(amount
).value
)
250 self
.assertEqual("SC", abs(amount
).currency
)
252 amount
= portfolio
.Amount("SC", 10)
253 self
.assertEqual(10, abs(amount
).value
)
254 self
.assertEqual("SC", abs(amount
).currency
)
257 amount1
= portfolio
.Amount("XVG", "12.9")
258 amount2
= portfolio
.Amount("XVG", "13.1")
260 self
.assertEqual(26, (amount1
+ amount2
).value
)
261 self
.assertEqual("XVG", (amount1
+ amount2
).currency
)
263 amount3
= portfolio
.Amount("ETH", "1.6")
264 with self
.assertRaises(Exception):
267 amount4
= portfolio
.Amount("ETH", 0.0)
268 self
.assertEqual(amount1
, amount1
+ amount4
)
270 self
.assertEqual(amount1
, amount1
+ 0)
272 def test__radd(self
):
273 amount
= portfolio
.Amount("XVG", "12.9")
275 self
.assertEqual(amount
, 0 + amount
)
276 with self
.assertRaises(Exception):
280 amount1
= portfolio
.Amount("XVG", "13.3")
281 amount2
= portfolio
.Amount("XVG", "13.1")
283 self
.assertEqual(D("0.2"), (amount1
- amount2
).value
)
284 self
.assertEqual("XVG", (amount1
- amount2
).currency
)
286 amount3
= portfolio
.Amount("ETH", "1.6")
287 with self
.assertRaises(Exception):
290 amount4
= portfolio
.Amount("ETH", 0.0)
291 self
.assertEqual(amount1
, amount1
- amount4
)
293 def test__rsub(self
):
294 amount
= portfolio
.Amount("ETH", "1.6")
295 with self
.assertRaises(Exception):
298 self
.assertEqual(portfolio
.Amount("ETH", "-1.6"), -amount
)
301 amount
= portfolio
.Amount("XEM", 11)
303 self
.assertEqual(D("38.5"), (amount
* D("3.5")).value
)
304 self
.assertEqual(D("33"), (amount
* 3).value
)
306 with self
.assertRaises(Exception):
309 def test__rmul(self
):
310 amount
= portfolio
.Amount("XEM", 11)
312 self
.assertEqual(D("38.5"), (D("3.5") * amount
).value
)
313 self
.assertEqual(D("33"), (3 * amount
).value
)
315 def test__floordiv(self
):
316 amount
= portfolio
.Amount("XEM", 11)
318 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
319 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
321 with self
.assertRaises(Exception):
324 def test__truediv(self
):
325 amount
= portfolio
.Amount("XEM", 11)
327 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
328 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
331 amount1
= portfolio
.Amount("BTD", 11.3)
332 amount2
= portfolio
.Amount("BTD", 13.1)
334 self
.assertTrue(amount1
< amount2
)
335 self
.assertFalse(amount2
< amount1
)
336 self
.assertFalse(amount1
< amount1
)
338 amount3
= portfolio
.Amount("BTC", 1.6)
339 with self
.assertRaises(Exception):
343 amount1
= portfolio
.Amount("BTD", 11.3)
344 amount2
= portfolio
.Amount("BTD", 13.1)
346 self
.assertTrue(amount1
<= amount2
)
347 self
.assertFalse(amount2
<= amount1
)
348 self
.assertTrue(amount1
<= amount1
)
350 amount3
= portfolio
.Amount("BTC", 1.6)
351 with self
.assertRaises(Exception):
355 amount1
= portfolio
.Amount("BTD", 11.3)
356 amount2
= portfolio
.Amount("BTD", 13.1)
358 self
.assertTrue(amount2
> amount1
)
359 self
.assertFalse(amount1
> amount2
)
360 self
.assertFalse(amount1
> amount1
)
362 amount3
= portfolio
.Amount("BTC", 1.6)
363 with self
.assertRaises(Exception):
367 amount1
= portfolio
.Amount("BTD", 11.3)
368 amount2
= portfolio
.Amount("BTD", 13.1)
370 self
.assertTrue(amount2
>= amount1
)
371 self
.assertFalse(amount1
>= amount2
)
372 self
.assertTrue(amount1
>= amount1
)
374 amount3
= portfolio
.Amount("BTC", 1.6)
375 with self
.assertRaises(Exception):
379 amount1
= portfolio
.Amount("BTD", 11.3)
380 amount2
= portfolio
.Amount("BTD", 13.1)
381 amount3
= portfolio
.Amount("BTD", 11.3)
383 self
.assertFalse(amount1
== amount2
)
384 self
.assertFalse(amount2
== amount1
)
385 self
.assertTrue(amount1
== amount3
)
386 self
.assertFalse(amount2
== 0)
388 amount4
= portfolio
.Amount("BTC", 1.6)
389 with self
.assertRaises(Exception):
392 amount5
= portfolio
.Amount("BTD", 0)
393 self
.assertTrue(amount5
== 0)
396 amount1
= portfolio
.Amount("BTD", 11.3)
397 amount2
= portfolio
.Amount("BTD", 13.1)
398 amount3
= portfolio
.Amount("BTD", 11.3)
400 self
.assertTrue(amount1
!= amount2
)
401 self
.assertTrue(amount2
!= amount1
)
402 self
.assertFalse(amount1
!= amount3
)
403 self
.assertTrue(amount2
!= 0)
405 amount4
= portfolio
.Amount("BTC", 1.6)
406 with self
.assertRaises(Exception):
409 amount5
= portfolio
.Amount("BTD", 0)
410 self
.assertFalse(amount5
!= 0)
413 amount1
= portfolio
.Amount("BTD", "11.3")
415 self
.assertEqual(portfolio
.D("-11.3"), (-amount1
).value
)
418 amount1
= portfolio
.Amount("BTX", 32)
419 self
.assertEqual("32.00000000 BTX", str(amount1
))
421 amount2
= portfolio
.Amount("USDT", 12000)
422 amount1
.linked_to
= amount2
423 self
.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1
))
425 def test__repr(self
):
426 amount1
= portfolio
.Amount("BTX", 32)
427 self
.assertEqual("Amount(32.00000000 BTX)", repr(amount1
))
429 amount2
= portfolio
.Amount("USDT", 12000)
430 amount1
.linked_to
= amount2
431 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1
))
433 amount3
= portfolio
.Amount("BTC", 0.1)
434 amount2
.linked_to
= amount3
435 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1
))
437 @unittest.skipUnless("unit" in limits
, "Unit skipped")
438 class BalanceTest(WebMockTestCase
):
439 def test_values(self
):
440 balance
= portfolio
.Balance("BTC", {
441 "exchange_total": "0.65",
442 "exchange_free": "0.35",
443 "exchange_used": "0.30",
444 "margin_total": "-10",
445 "margin_borrowed": "-10",
447 "margin_position_type": "short",
448 "margin_borrowed_base_currency": "USDT",
449 "margin_liquidation_price": "1.20",
450 "margin_pending_gain": "10",
451 "margin_lending_fees": "0.4",
452 "margin_borrowed_base_price": "0.15",
454 self
.assertEqual(portfolio
.D("0.65"), balance
.exchange_total
.value
)
455 self
.assertEqual(portfolio
.D("0.35"), balance
.exchange_free
.value
)
456 self
.assertEqual(portfolio
.D("0.30"), balance
.exchange_used
.value
)
457 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
458 self
.assertEqual("BTC", balance
.exchange_free
.currency
)
459 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
461 self
.assertEqual(portfolio
.D("-10"), balance
.margin_total
.value
)
462 self
.assertEqual(portfolio
.D("-10"), balance
.margin_borrowed
.value
)
463 self
.assertEqual(portfolio
.D("0"), balance
.margin_free
.value
)
464 self
.assertEqual("BTC", balance
.margin_total
.currency
)
465 self
.assertEqual("BTC", balance
.margin_borrowed
.currency
)
466 self
.assertEqual("BTC", balance
.margin_free
.currency
)
468 self
.assertEqual("BTC", balance
.currency
)
470 self
.assertEqual(portfolio
.D("0.4"), balance
.margin_lending_fees
.value
)
471 self
.assertEqual("USDT", balance
.margin_lending_fees
.currency
)
473 def test__repr(self
):
474 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
475 repr(portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)))
476 balance
= portfolio
.Balance("BTX", { "exchange_total": 3,
477 "exchange_used": 1, "exchange_free": 2 })
478 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
480 balance
= portfolio
.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}
)
481 self
.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance
))
483 balance
= portfolio
.Balance("BTX", { "margin_total": 3,
484 "margin_borrowed": 1, "margin_free": 2 })
485 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + borrowed 1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
487 balance
= portfolio
.Balance("BTX", { "margin_total": 2, "margin_free": 2 }
)
488 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance
))
490 balance
= portfolio
.Balance("BTX", { "margin_total": -3,
491 "margin_borrowed_base_price": D("0.1"),
492 "margin_borrowed_base_currency": "BTC",
493 "margin_lending_fees": D("0.002") })
494 self
.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance
))
496 balance
= portfolio
.Balance("BTX", { "margin_total": 1,
497 "margin_borrowed": 1, "exchange_free": 2, "exchange_total": 2})
498 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [borrowed 1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance
))
500 @unittest.skipUnless("unit" in limits
, "Unit skipped")
501 class HelperTest(WebMockTestCase
):
502 def test_get_ticker(self
):
504 market
.fetch_ticker
.side_effect
= [
505 { "bid": 1, "ask": 3 }
,
506 helper
.ExchangeError("foo"),
507 { "bid": 10, "ask": 40 }
,
508 helper
.ExchangeError("foo"),
509 helper
.ExchangeError("foo"),
512 ticker
= helper
.get_ticker("ETH", "ETC", market
)
513 market
.fetch_ticker
.assert_called_with("ETH/ETC")
514 self
.assertEqual(1, ticker
["bid"])
515 self
.assertEqual(3, ticker
["ask"])
516 self
.assertEqual(2, ticker
["average"])
517 self
.assertFalse(ticker
["inverted"])
519 ticker
= helper
.get_ticker("ETH", "XVG", market
)
520 self
.assertEqual(0.0625, ticker
["average"])
521 self
.assertTrue(ticker
["inverted"])
522 self
.assertIn("original", ticker
)
523 self
.assertEqual(10, ticker
["original"]["bid"])
525 ticker
= helper
.get_ticker("XVG", "XMR", market
)
526 self
.assertIsNone(ticker
)
528 market
.fetch_ticker
.assert_has_calls([
529 mock
.call("ETH/ETC"),
530 mock
.call("ETH/XVG"),
531 mock
.call("XVG/ETH"),
532 mock
.call("XVG/XMR"),
533 mock
.call("XMR/XVG"),
536 market2
= mock
.Mock()
537 market2
.fetch_ticker
.side_effect
= [
538 { "bid": 1, "ask": 3 }
,
539 { "bid": 1.2, "ask": 3.5 }
,
541 ticker1
= helper
.get_ticker("ETH", "ETC", market2
)
542 ticker2
= helper
.get_ticker("ETH", "ETC", market2
)
543 ticker3
= helper
.get_ticker("ETC", "ETH", market2
)
544 market2
.fetch_ticker
.assert_called_once_with("ETH/ETC")
545 self
.assertEqual(1, ticker1
["bid"])
546 self
.assertDictEqual(ticker1
, ticker2
)
547 self
.assertDictEqual(ticker1
, ticker3
["original"])
549 ticker4
= helper
.get_ticker("ETH", "ETC", market2
, refresh
=True)
550 ticker5
= helper
.get_ticker("ETH", "ETC", market2
)
551 self
.assertEqual(1.2, ticker4
["bid"])
552 self
.assertDictEqual(ticker4
, ticker5
)
554 market3
= mock
.Mock()
555 market3
.fetch_ticker
.side_effect
= [
556 { "bid": 1, "ask": 3 }
,
557 { "bid": 1.2, "ask": 3.5 }
,
559 ticker6
= helper
.get_ticker("ETH", "ETC", market3
)
560 helper
.ticker_cache_timestamp
-= 4
561 ticker7
= helper
.get_ticker("ETH", "ETC", market3
)
562 helper
.ticker_cache_timestamp
-= 2
563 ticker8
= helper
.get_ticker("ETH", "ETC", market3
)
564 self
.assertDictEqual(ticker6
, ticker7
)
565 self
.assertEqual(1.2, ticker8
["bid"])
567 def test_fetch_fees(self
):
569 market
.fetch_fees
.return_value
= "Foo"
570 self
.assertEqual("Foo", helper
.fetch_fees(market
))
571 market
.fetch_fees
.assert_called_once()
572 self
.assertEqual("Foo", helper
.fetch_fees(market
))
573 market
.fetch_fees
.assert_called_once()
575 @mock.patch.object(portfolio
.Portfolio
, "repartition")
576 @mock.patch.object(helper
, "get_ticker")
577 @mock.patch.object(portfolio
.TradeStore
, "compute_trades")
578 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
579 repartition
.return_value
= {
580 "XEM": (D("0.75"), "long"),
581 "BTC": (D("0.25"), "long"),
583 def _get_ticker(c1
, c2
, market
):
584 if c1
== "USDT" and c2
== "BTC":
585 return { "average": D("0.0001") }
586 if c1
== "XVG" and c2
== "BTC":
587 return { "average": D("0.000001") }
588 if c1
== "XEM" and c2
== "BTC":
589 return { "average": D("0.001") }
590 self
.fail("Should be called with {}, {}".format(c1
, c2
))
591 get_ticker
.side_effect
= _get_ticker
594 market
.fetch_all_balances
.return_value
= {
596 "exchange_free": D("10000.0"),
597 "exchange_used": D("0.0"),
598 "exchange_total": D("10000.0"),
599 "total": D("10000.0")
602 "exchange_free": D("10000.0"),
603 "exchange_used": D("0.0"),
604 "exchange_total": D("10000.0"),
605 "total": D("10000.0")
608 helper
.prepare_trades(market
)
609 compute_trades
.assert_called()
611 call
= compute_trades
.call_args
612 self
.assertEqual(market
, call
[1]["market"])
613 self
.assertEqual(1, call
[0][0]["USDT"].value
)
614 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
615 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
616 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
618 @mock.patch.object(portfolio
.Portfolio
, "repartition")
619 @mock.patch.object(helper
, "get_ticker")
620 @mock.patch.object(portfolio
.TradeStore
, "compute_trades")
621 def test_update_trades(self
, compute_trades
, get_ticker
, repartition
):
622 repartition
.return_value
= {
623 "XEM": (D("0.75"), "long"),
624 "BTC": (D("0.25"), "long"),
626 def _get_ticker(c1
, c2
, market
):
627 if c1
== "USDT" and c2
== "BTC":
628 return { "average": D("0.0001") }
629 if c1
== "XVG" and c2
== "BTC":
630 return { "average": D("0.000001") }
631 if c1
== "XEM" and c2
== "BTC":
632 return { "average": D("0.001") }
633 self
.fail("Should be called with {}, {}".format(c1
, c2
))
634 get_ticker
.side_effect
= _get_ticker
637 market
.fetch_all_balances
.return_value
= {
639 "exchange_free": D("10000.0"),
640 "exchange_used": D("0.0"),
641 "exchange_total": D("10000.0"),
642 "total": D("10000.0")
645 "exchange_free": D("10000.0"),
646 "exchange_used": D("0.0"),
647 "exchange_total": D("10000.0"),
648 "total": D("10000.0")
651 helper
.update_trades(market
)
652 compute_trades
.assert_called()
654 call
= compute_trades
.call_args
655 self
.assertEqual(market
, call
[1]["market"])
656 self
.assertEqual(1, call
[0][0]["USDT"].value
)
657 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
658 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
659 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
661 @mock.patch.object(portfolio
.Portfolio
, "repartition")
662 @mock.patch.object(helper
, "get_ticker")
663 @mock.patch.object(portfolio
.TradeStore
, "compute_trades")
664 def test_prepare_trades_to_sell_all(self
, compute_trades
, get_ticker
, repartition
):
665 def _get_ticker(c1
, c2
, market
):
666 if c1
== "USDT" and c2
== "BTC":
667 return { "average": D("0.0001") }
668 if c1
== "XVG" and c2
== "BTC":
669 return { "average": D("0.000001") }
670 self
.fail("Should be called with {}, {}".format(c1
, c2
))
671 get_ticker
.side_effect
= _get_ticker
674 market
.fetch_all_balances
.return_value
= {
676 "exchange_free": D("10000.0"),
677 "exchange_used": D("0.0"),
678 "exchange_total": D("10000.0"),
679 "total": D("10000.0")
682 "exchange_free": D("10000.0"),
683 "exchange_used": D("0.0"),
684 "exchange_total": D("10000.0"),
685 "total": D("10000.0")
688 helper
.prepare_trades_to_sell_all(market
)
689 repartition
.assert_not_called()
690 compute_trades
.assert_called()
692 call
= compute_trades
.call_args
693 self
.assertEqual(market
, call
[1]["market"])
694 self
.assertEqual(1, call
[0][0]["USDT"].value
)
695 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
696 self
.assertEqual(D("1.01"), call
[0][1]["BTC"].value
)
698 @mock.patch.object(portfolio
.time
, "sleep")
699 @mock.patch.object(portfolio
.TradeStore
, "all_orders")
700 def test_follow_orders(self
, all_orders
, time_mock
):
701 for verbose
, debug
, sleep
in [
702 (True, False, None), (False, False, None),
703 (True, True, None), (True, False, 12),
705 with self
.subTest(sleep
=sleep
, debug
=debug
, verbose
=verbose
), \
706 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
707 portfolio
.TradeStore
.debug
= debug
708 order_mock1
= mock
.Mock()
709 order_mock2
= mock
.Mock()
710 order_mock3
= mock
.Mock()
711 all_orders
.side_effect
= [
712 [order_mock1
, order_mock2
],
713 [order_mock1
, order_mock2
],
715 [order_mock1
, order_mock3
],
716 [order_mock1
, order_mock3
],
718 [order_mock1
, order_mock3
],
719 [order_mock1
, order_mock3
],
724 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
725 order_mock2
.get_status
.side_effect
= ["open"]
726 order_mock3
.get_status
.side_effect
= ["open", "closed"]
728 order_mock1
.trade
= mock
.Mock()
729 order_mock2
.trade
= mock
.Mock()
730 order_mock3
.trade
= mock
.Mock()
732 helper
.follow_orders(verbose
=verbose
, sleep
=sleep
)
734 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
735 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
736 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
737 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
739 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
740 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
741 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
743 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
744 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
745 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
749 time_mock
.assert_called_with(7)
751 time_mock
.assert_called_with(30)
753 time_mock
.assert_called_with(sleep
)
756 self
.assertNotEqual("", stdout_mock
.getvalue())
758 self
.assertEqual("", stdout_mock
.getvalue())
760 @mock.patch.object(portfolio
.BalanceStore
, "fetch_balances")
761 def test_move_balance(self
, fetch_balances
):
762 for debug
in [True, False]:
763 with self
.subTest(debug
=debug
),\
764 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
765 value_from
= portfolio
.Amount("BTC", "1.0")
766 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
767 value_to
= portfolio
.Amount("BTC", "10.0")
768 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH")
770 value_from
= portfolio
.Amount("BTC", "0.0")
771 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
772 value_to
= portfolio
.Amount("BTC", "-3.0")
773 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH")
775 value_from
= portfolio
.Amount("USDT", "0.0")
776 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
777 value_to
= portfolio
.Amount("USDT", "-50.0")
778 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG")
780 portfolio
.TradeStore
.all
= [trade1
, trade2
, trade3
]
781 balance1
= portfolio
.Balance("BTC", { "margin_free": "0" }
)
782 balance2
= portfolio
.Balance("USDT", { "margin_free": "100" }
)
783 balance3
= portfolio
.Balance("ETC", { "margin_free": "10" }
)
784 portfolio
.BalanceStore
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
788 helper
.move_balances(market
, debug
=debug
)
790 fetch_balances
.assert_called_with(market
)
792 self
.assertRegex(stdout_mock
.getvalue(), "market.transfer_balance")
794 market
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
795 market
.transfer_balance
.assert_any_call("USDT", 50, "margin", "exchange")
796 market
.transfer_balance
.assert_any_call("ETC", 10, "margin", "exchange")
798 @mock.patch.object(helper
, "prepare_trades")
799 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
800 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
801 @mock.patch('sys.stdout', new_callable
=StringIO
)
802 def test_print_orders(self
, stdout_mock
, print_all_with_order
, prepare_orders
, prepare_trades
):
804 portfolio
.BalanceStore
.all
= {
805 "BTC": portfolio
.Balance("BTC", {
807 "exchange_total":"0.65",
808 "exchange_free": "0.35",
809 "exchange_used": "0.30"}),
810 "ETH": portfolio
.Balance("ETH", {
814 "exchange_used": 0}),
816 helper
.print_orders(market
)
817 prepare_trades
.assert_called_with(market
, base_currency
="BTC",
818 compute_value
="average", debug
=True)
819 prepare_orders
.assert_called_with(compute_value
="average")
820 print_all_with_order
.assert_called()
821 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
823 @mock.patch.object(portfolio
.BalanceStore
, "fetch_balances")
824 @mock.patch.object(portfolio
.BalanceStore
, "in_currency")
825 @mock.patch('sys.stdout', new_callable
=StringIO
)
826 def test_print_balances(self
, stdout_mock
, in_currency
, fetch_balances
):
828 portfolio
.BalanceStore
.all
= {
829 "BTC": portfolio
.Balance("BTC", {
831 "exchange_total":"0.65",
832 "exchange_free": "0.35",
833 "exchange_used": "0.30"}),
834 "ETH": portfolio
.Balance("ETH", {
838 "exchange_used": 0}),
840 in_currency
.return_value
= {
841 "BTC": portfolio
.Amount("BTC", "0.65"),
842 "ETH": portfolio
.Amount("BTC", "0.3"),
844 helper
.print_balances(market
)
845 fetch_balances
.assert_called_with(market
)
846 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
847 self
.assertRegex(stdout_mock
.getvalue(), "0.95000000 BTC")
849 @mock.patch.object(helper
, "prepare_trades")
850 @mock.patch.object(helper
, "follow_orders")
851 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
852 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
853 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
854 @mock.patch('sys.stdout', new_callable
=StringIO
)
855 def test_process_sell_needed__1_sell(self
, stdout_mock
, run_orders
,
856 print_all_with_order
, prepare_orders
, follow_orders
,
859 portfolio
.BalanceStore
.all
= {
860 "BTC": portfolio
.Balance("BTC", {
862 "exchange_total":"0.65",
863 "exchange_free": "0.35",
864 "exchange_used": "0.30"}),
865 "ETH": portfolio
.Balance("ETH", {
869 "exchange_used": 0}),
871 helper
.process_sell_needed__1_sell(market
)
872 prepare_trades
.assert_called_with(market
, base_currency
="BTC",
874 prepare_orders
.assert_called_with(compute_value
="average",
876 print_all_with_order
.assert_called()
877 run_orders
.assert_called()
878 follow_orders
.assert_called()
879 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
881 @mock.patch.object(helper
, "update_trades")
882 @mock.patch.object(helper
, "follow_orders")
883 @mock.patch.object(helper
, "move_balances")
884 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
885 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
886 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
887 @mock.patch('sys.stdout', new_callable
=StringIO
)
888 def test_process_sell_needed__2_buy(self
, stdout_mock
, run_orders
,
889 print_all_with_order
, prepare_orders
, move_balances
,
890 follow_orders
, update_trades
):
892 portfolio
.BalanceStore
.all
= {
893 "BTC": portfolio
.Balance("BTC", {
895 "exchange_total":"0.65",
896 "exchange_free": "0.35",
897 "exchange_used": "0.30"}),
898 "ETH": portfolio
.Balance("ETH", {
902 "exchange_used": 0}),
904 helper
.process_sell_needed__2_buy(market
)
905 update_trades
.assert_called_with(market
, base_currency
="BTC",
906 debug
=False, only
="acquire")
907 prepare_orders
.assert_called_with(compute_value
="average",
909 print_all_with_order
.assert_called()
910 move_balances
.assert_called_with(market
, debug
=False)
911 run_orders
.assert_called()
912 follow_orders
.assert_called()
913 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
915 @mock.patch.object(helper
, "prepare_trades_to_sell_all")
916 @mock.patch.object(helper
, "follow_orders")
917 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
918 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
919 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
920 @mock.patch('sys.stdout', new_callable
=StringIO
)
921 def test_process_sell_all__1_sell(self
, stdout_mock
, run_orders
,
922 print_all_with_order
, prepare_orders
, follow_orders
,
923 prepare_trades_to_sell_all
):
925 portfolio
.BalanceStore
.all
= {
926 "BTC": portfolio
.Balance("BTC", {
928 "exchange_total":"0.65",
929 "exchange_free": "0.35",
930 "exchange_used": "0.30"}),
931 "ETH": portfolio
.Balance("ETH", {
935 "exchange_used": 0}),
937 helper
.process_sell_all__1_all_sell(market
)
938 prepare_trades_to_sell_all
.assert_called_with(market
, base_currency
="BTC",
940 prepare_orders
.assert_called_with(compute_value
="average")
941 print_all_with_order
.assert_called()
942 run_orders
.assert_called()
943 follow_orders
.assert_called()
944 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
946 @mock.patch.object(helper
, "prepare_trades")
947 @mock.patch.object(helper
, "follow_orders")
948 @mock.patch.object(helper
, "move_balances")
949 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
950 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
951 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
952 @mock.patch('sys.stdout', new_callable
=StringIO
)
953 def test_process_sell_all__2_all_buy(self
, stdout_mock
, run_orders
,
954 print_all_with_order
, prepare_orders
, move_balances
,
955 follow_orders
, prepare_trades
):
957 portfolio
.BalanceStore
.all
= {
958 "BTC": portfolio
.Balance("BTC", {
960 "exchange_total":"0.65",
961 "exchange_free": "0.35",
962 "exchange_used": "0.30"}),
963 "ETH": portfolio
.Balance("ETH", {
967 "exchange_used": 0}),
969 helper
.process_sell_all__2_all_buy(market
)
970 prepare_trades
.assert_called_with(market
, base_currency
="BTC",
972 prepare_orders
.assert_called_with()
973 print_all_with_order
.assert_called()
974 move_balances
.assert_called_with(market
, debug
=False)
975 run_orders
.assert_called()
976 follow_orders
.assert_called()
977 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
980 @unittest.skipUnless("unit" in limits
, "Unit skipped")
981 class TradeStoreTest(WebMockTestCase
):
982 @mock.patch.object(portfolio
.BalanceStore
, "currencies")
983 @mock.patch.object(portfolio
.TradeStore
, "add_trade_if_matching")
984 def test_compute_trades(self
, add_trade_if_matching
, currencies
):
985 currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
988 "XMR": portfolio
.Amount("BTC", D("0.9")),
989 "DASH": portfolio
.Amount("BTC", D("0.4")),
990 "XVG": portfolio
.Amount("BTC", D("-0.5")),
991 "BTC": portfolio
.Amount("BTC", D("0.5")),
994 "DASH": portfolio
.Amount("BTC", D("0.5")),
995 "XVG": portfolio
.Amount("BTC", D("0.1")),
996 "BTC": portfolio
.Amount("BTC", D("0.4")),
997 "ETH": portfolio
.Amount("BTC", D("0.3")),
1000 portfolio
.TradeStore
.compute_trades(values_in_base
,
1001 new_repartition
, only
="only", market
="market")
1003 self
.assertEqual(5, add_trade_if_matching
.call_count
)
1004 add_trade_if_matching
.assert_any_call(
1005 portfolio
.Amount("BTC", D("0.9")),
1006 portfolio
.Amount("BTC", 0),
1007 "XMR", only
="only", market
="market"
1009 add_trade_if_matching
.assert_any_call(
1010 portfolio
.Amount("BTC", D("0.4")),
1011 portfolio
.Amount("BTC", D("0.5")),
1012 "DASH", only
="only", market
="market"
1014 add_trade_if_matching
.assert_any_call(
1015 portfolio
.Amount("BTC", D("-0.5")),
1016 portfolio
.Amount("BTC", D("0")),
1017 "XVG", only
="only", market
="market"
1019 add_trade_if_matching
.assert_any_call(
1020 portfolio
.Amount("BTC", D("0")),
1021 portfolio
.Amount("BTC", D("0.1")),
1022 "XVG", only
="only", market
="market"
1024 add_trade_if_matching
.assert_any_call(
1025 portfolio
.Amount("BTC", D("0")),
1026 portfolio
.Amount("BTC", D("0.3")),
1027 "ETH", only
="only", market
="market"
1030 def test_add_trade_if_matching(self
):
1031 result
= portfolio
.TradeStore
.add_trade_if_matching(
1032 portfolio
.Amount("BTC", D("0")),
1033 portfolio
.Amount("BTC", D("0.3")),
1034 "ETH", only
="nope", market
="market"
1036 self
.assertEqual(0, len(portfolio
.TradeStore
.all
))
1037 self
.assertEqual(False, result
)
1039 portfolio
.TradeStore
.all
= []
1040 result
= portfolio
.TradeStore
.add_trade_if_matching(
1041 portfolio
.Amount("BTC", D("0")),
1042 portfolio
.Amount("BTC", D("0.3")),
1043 "ETH", only
=None, market
="market"
1045 self
.assertEqual(1, len(portfolio
.TradeStore
.all
))
1046 self
.assertEqual(True, result
)
1048 portfolio
.TradeStore
.all
= []
1049 result
= portfolio
.TradeStore
.add_trade_if_matching(
1050 portfolio
.Amount("BTC", D("0")),
1051 portfolio
.Amount("BTC", D("0.3")),
1052 "ETH", only
="acquire", market
="market"
1054 self
.assertEqual(1, len(portfolio
.TradeStore
.all
))
1055 self
.assertEqual(True, result
)
1057 portfolio
.TradeStore
.all
= []
1058 result
= portfolio
.TradeStore
.add_trade_if_matching(
1059 portfolio
.Amount("BTC", D("0")),
1060 portfolio
.Amount("BTC", D("0.3")),
1061 "ETH", only
="dispose", market
="market"
1063 self
.assertEqual(0, len(portfolio
.TradeStore
.all
))
1064 self
.assertEqual(False, result
)
1066 def test_prepare_orders(self
):
1067 trade_mock1
= mock
.Mock()
1068 trade_mock2
= mock
.Mock()
1070 portfolio
.TradeStore
.all
.append(trade_mock1
)
1071 portfolio
.TradeStore
.all
.append(trade_mock2
)
1073 portfolio
.TradeStore
.prepare_orders()
1074 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1075 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1077 portfolio
.TradeStore
.prepare_orders(compute_value
="bla")
1078 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1079 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1081 trade_mock1
.prepare_order
.reset_mock()
1082 trade_mock2
.prepare_order
.reset_mock()
1084 trade_mock1
.action
= "foo"
1085 trade_mock2
.action
= "bar"
1086 portfolio
.TradeStore
.prepare_orders(only
="bar")
1087 trade_mock1
.prepare_order
.assert_not_called()
1088 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1090 def test_print_all_with_order(self
):
1091 trade_mock1
= mock
.Mock()
1092 trade_mock2
= mock
.Mock()
1093 trade_mock3
= mock
.Mock()
1094 portfolio
.TradeStore
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1096 portfolio
.TradeStore
.print_all_with_order()
1098 trade_mock1
.print_with_order
.assert_called()
1099 trade_mock2
.print_with_order
.assert_called()
1100 trade_mock3
.print_with_order
.assert_called()
1102 @mock.patch.object(portfolio
.TradeStore
, "all_orders")
1103 def test_run_orders(self
, all_orders
):
1104 order_mock1
= mock
.Mock()
1105 order_mock2
= mock
.Mock()
1106 order_mock3
= mock
.Mock()
1107 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1108 portfolio
.TradeStore
.run_orders()
1109 all_orders
.assert_called_with(state
="pending")
1111 order_mock1
.run
.assert_called()
1112 order_mock2
.run
.assert_called()
1113 order_mock3
.run
.assert_called()
1115 def test_all_orders(self
):
1116 trade_mock1
= mock
.Mock()
1117 trade_mock2
= mock
.Mock()
1119 order_mock1
= mock
.Mock()
1120 order_mock2
= mock
.Mock()
1121 order_mock3
= mock
.Mock()
1123 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1124 trade_mock2
.orders
= [order_mock3
]
1126 order_mock1
.status
= "pending"
1127 order_mock2
.status
= "open"
1128 order_mock3
.status
= "open"
1130 portfolio
.TradeStore
.all
.append(trade_mock1
)
1131 portfolio
.TradeStore
.all
.append(trade_mock2
)
1133 orders
= portfolio
.TradeStore
.all_orders()
1134 self
.assertEqual(3, len(orders
))
1136 open_orders
= portfolio
.TradeStore
.all_orders(state
="open")
1137 self
.assertEqual(2, len(open_orders
))
1138 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1140 @mock.patch.object(portfolio
.TradeStore
, "all_orders")
1141 def test_update_all_orders_status(self
, all_orders
):
1142 order_mock1
= mock
.Mock()
1143 order_mock2
= mock
.Mock()
1144 order_mock3
= mock
.Mock()
1145 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1146 portfolio
.TradeStore
.update_all_orders_status()
1147 all_orders
.assert_called_with(state
="open")
1149 order_mock1
.get_status
.assert_called()
1150 order_mock2
.get_status
.assert_called()
1151 order_mock3
.get_status
.assert_called()
1153 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1154 class BalanceStoreTest(WebMockTestCase
):
1156 super(BalanceStoreTest
, self
).setUp()
1158 self
.fetch_balance
= {
1162 "exchange_total": 0,
1166 "exchange_free": D("6.0"),
1167 "exchange_used": D("1.2"),
1168 "exchange_total": D("7.2"),
1172 "exchange_free": 16,
1174 "exchange_total": 16,
1180 "exchange_total": 0,
1181 "margin_total": D("-1.0"),
1186 @mock.patch.object(helper
, "get_ticker")
1187 def test_in_currency(self
, get_ticker
):
1188 portfolio
.BalanceStore
.all
= {
1189 "BTC": portfolio
.Balance("BTC", {
1191 "exchange_total":"0.65",
1192 "exchange_free": "0.35",
1193 "exchange_used": "0.30"}),
1194 "ETH": portfolio
.Balance("ETH", {
1196 "exchange_total": 3,
1198 "exchange_used": 0}),
1200 market
= mock
.Mock()
1201 get_ticker
.return_value
= {
1204 "average": D("0.1"),
1207 amounts
= portfolio
.BalanceStore
.in_currency("BTC", market
)
1208 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1209 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1210 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1212 amounts
= portfolio
.BalanceStore
.in_currency("BTC", market
, compute_value
="bid")
1213 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1214 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1216 amounts
= portfolio
.BalanceStore
.in_currency("BTC", market
, compute_value
="bid", type="exchange_used")
1217 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1218 self
.assertEqual(0, amounts
["ETH"].value
)
1220 def test_fetch_balances(self
):
1221 market
= mock
.Mock()
1222 market
.fetch_all_balances
.return_value
= self
.fetch_balance
1224 portfolio
.BalanceStore
.fetch_balances(market
)
1225 self
.assertNotIn("ETC", portfolio
.BalanceStore
.currencies())
1226 self
.assertListEqual(["USDT", "XVG", "XMR"], list(portfolio
.BalanceStore
.currencies()))
1228 portfolio
.BalanceStore
.all
["ETC"] = portfolio
.Balance("ETC", {
1229 "exchange_total": "1", "exchange_free": "0",
1230 "exchange_used": "1" })
1231 portfolio
.BalanceStore
.fetch_balances(market
)
1232 self
.assertEqual(0, portfolio
.BalanceStore
.all
["ETC"].total
)
1233 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(portfolio
.BalanceStore
.currencies()))
1235 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1236 def test_dispatch_assets(self
, repartition
):
1237 market
= mock
.Mock()
1238 market
.fetch_all_balances
.return_value
= self
.fetch_balance
1239 portfolio
.BalanceStore
.fetch_balances(market
)
1241 self
.assertNotIn("XEM", portfolio
.BalanceStore
.currencies())
1243 repartition
.return_value
= {
1244 "XEM": (D("0.75"), "long"),
1245 "BTC": (D("0.26"), "long"),
1246 "DASH": (D("0.10"), "short"),
1249 amounts
= portfolio
.BalanceStore
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1250 self
.assertIn("XEM", portfolio
.BalanceStore
.currencies())
1251 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1252 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1253 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1255 def test_currencies(self
):
1256 portfolio
.BalanceStore
.all
= {
1257 "BTC": portfolio
.Balance("BTC", {
1259 "exchange_total":"0.65",
1260 "exchange_free": "0.35",
1261 "exchange_used": "0.30"}),
1262 "ETH": portfolio
.Balance("ETH", {
1264 "exchange_total": 3,
1266 "exchange_used": 0}),
1268 self
.assertListEqual(["BTC", "ETH"], list(portfolio
.BalanceStore
.currencies()))
1270 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1271 class ComputationTest(WebMockTestCase
):
1272 def test_compute_value(self
):
1273 compute
= mock
.Mock()
1274 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1275 compute
.assert_called_with("foo", "ask")
1277 compute
.reset_mock()
1278 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1279 compute
.assert_called_with("foo", "bid")
1281 compute
.reset_mock()
1282 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1283 compute
.assert_called_with("foo", "ask")
1285 compute
.reset_mock()
1286 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1287 compute
.assert_called_with("foo", "bid")
1289 compute
.reset_mock()
1290 portfolio
.Computation
.computations
["test"] = compute
1291 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1292 compute
.assert_called_with("foo", "bid")
1295 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1296 class TradeTest(WebMockTestCase
):
1298 def test_values_assertion(self
):
1299 value_from
= portfolio
.Amount("BTC", "1.0")
1300 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1301 value_to
= portfolio
.Amount("BTC", "1.0")
1302 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1303 self
.assertEqual("BTC", trade
.base_currency
)
1304 self
.assertEqual("ETH", trade
.currency
)
1306 with self
.assertRaises(AssertionError):
1307 portfolio
.Trade(value_from
, value_to
, "ETC")
1308 with self
.assertRaises(AssertionError):
1309 value_from
.linked_to
= None
1310 portfolio
.Trade(value_from
, value_to
, "ETH")
1311 with self
.assertRaises(AssertionError):
1312 value_from
.currency
= "ETH"
1313 portfolio
.Trade(value_from
, value_to
, "ETH")
1315 value_from
= portfolio
.Amount("BTC", 0)
1316 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1317 self
.assertEqual(0, trade
.value_from
.linked_to
)
1319 def test_action(self
):
1320 value_from
= portfolio
.Amount("BTC", "1.0")
1321 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1322 value_to
= portfolio
.Amount("BTC", "1.0")
1323 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1325 self
.assertIsNone(trade
.action
)
1327 value_from
= portfolio
.Amount("BTC", "1.0")
1328 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1329 value_to
= portfolio
.Amount("BTC", "2.0")
1330 trade
= portfolio
.Trade(value_from
, value_to
, "BTC")
1332 self
.assertIsNone(trade
.action
)
1334 value_from
= portfolio
.Amount("BTC", "0.5")
1335 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1336 value_to
= portfolio
.Amount("BTC", "1.0")
1337 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1339 self
.assertEqual("acquire", trade
.action
)
1341 value_from
= portfolio
.Amount("BTC", "0")
1342 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1343 value_to
= portfolio
.Amount("BTC", "-1.0")
1344 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1346 self
.assertEqual("acquire", trade
.action
)
1348 def test_order_action(self
):
1349 value_from
= portfolio
.Amount("BTC", "0.5")
1350 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1351 value_to
= portfolio
.Amount("BTC", "1.0")
1352 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1354 self
.assertEqual("buy", trade
.order_action(False))
1355 self
.assertEqual("sell", trade
.order_action(True))
1357 value_from
= portfolio
.Amount("BTC", "0")
1358 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1359 value_to
= portfolio
.Amount("BTC", "-1.0")
1360 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1362 self
.assertEqual("sell", trade
.order_action(False))
1363 self
.assertEqual("buy", trade
.order_action(True))
1365 def test_trade_type(self
):
1366 value_from
= portfolio
.Amount("BTC", "0.5")
1367 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1368 value_to
= portfolio
.Amount("BTC", "1.0")
1369 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1371 self
.assertEqual("long", trade
.trade_type
)
1373 value_from
= portfolio
.Amount("BTC", "0")
1374 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1375 value_to
= portfolio
.Amount("BTC", "-1.0")
1376 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1378 self
.assertEqual("short", trade
.trade_type
)
1380 def test_filled_amount(self
):
1381 value_from
= portfolio
.Amount("BTC", "0.5")
1382 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1383 value_to
= portfolio
.Amount("BTC", "1.0")
1384 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1386 order1
= mock
.Mock()
1387 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1389 order2
= mock
.Mock()
1390 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1391 trade
.orders
.append(order1
)
1392 trade
.orders
.append(order2
)
1394 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1395 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1396 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1398 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1399 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1400 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1402 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1403 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1404 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1406 @mock.patch.object(helper
, "get_ticker")
1407 @mock.patch.object(portfolio
.Computation
, "compute_value")
1408 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1409 @mock.patch.object(portfolio
, "Order")
1410 def test_prepare_order(self
, Order
, filled_amount
, compute_value
, get_ticker
):
1411 Order
.return_value
= "Order"
1413 with self
.subTest(desc
="Nothing to do"):
1414 value_from
= portfolio
.Amount("BTC", "10")
1415 value_from
.rate
= D("0.1")
1416 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1417 value_to
= portfolio
.Amount("BTC", "10")
1418 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1420 trade
.prepare_order()
1422 filled_amount
.assert_not_called()
1423 compute_value
.assert_not_called()
1424 self
.assertEqual(0, len(trade
.orders
))
1425 Order
.assert_not_called()
1427 get_ticker
.return_value
= { "inverted": False }
1428 with self
.subTest(desc
="Already filled"), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1429 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1430 compute_value
.return_value
= D("0.125")
1432 value_from
= portfolio
.Amount("BTC", "10")
1433 value_from
.rate
= D("0.1")
1434 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1435 value_to
= portfolio
.Amount("BTC", "0")
1436 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1438 trade
.prepare_order()
1440 filled_amount
.assert_called_with(in_base_currency
=False)
1441 compute_value
.assert_called_with(get_ticker
.return_value
, "sell", compute_value
="default")
1442 self
.assertEqual(0, len(trade
.orders
))
1443 self
.assertRegex(stdout_mock
.getvalue(), "Less to do than already filled: ")
1444 Order
.assert_not_called()
1446 with self
.subTest(action
="dispose", inverted
=False):
1447 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1448 compute_value
.return_value
= D("0.125")
1450 value_from
= portfolio
.Amount("BTC", "10")
1451 value_from
.rate
= D("0.1")
1452 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1453 value_to
= portfolio
.Amount("BTC", "1")
1454 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1456 trade
.prepare_order()
1458 filled_amount
.assert_called_with(in_base_currency
=False)
1459 compute_value
.assert_called_with(get_ticker
.return_value
, "sell", compute_value
="default")
1460 self
.assertEqual(1, len(trade
.orders
))
1461 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1462 D("0.125"), "BTC", "long", "market",
1463 trade
, close_if_possible
=False)
1465 with self
.subTest(action
="acquire", inverted
=False):
1466 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1467 compute_value
.return_value
= D("0.125")
1469 value_from
= portfolio
.Amount("BTC", "1")
1470 value_from
.rate
= D("0.1")
1471 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1472 value_to
= portfolio
.Amount("BTC", "10")
1473 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1475 trade
.prepare_order()
1477 filled_amount
.assert_called_with(in_base_currency
=True)
1478 compute_value
.assert_called_with(get_ticker
.return_value
, "buy", compute_value
="default")
1479 self
.assertEqual(1, len(trade
.orders
))
1481 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1482 D("0.125"), "BTC", "long", "market",
1483 trade
, close_if_possible
=False)
1485 with self
.subTest(close_if_possible
=True):
1486 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1487 compute_value
.return_value
= D("0.125")
1489 value_from
= portfolio
.Amount("BTC", "10")
1490 value_from
.rate
= D("0.1")
1491 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1492 value_to
= portfolio
.Amount("BTC", "0")
1493 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1495 trade
.prepare_order()
1497 filled_amount
.assert_called_with(in_base_currency
=False)
1498 compute_value
.assert_called_with(get_ticker
.return_value
, "sell", compute_value
="default")
1499 self
.assertEqual(1, len(trade
.orders
))
1500 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1501 D("0.125"), "BTC", "long", "market",
1502 trade
, close_if_possible
=True)
1504 get_ticker
.return_value
= { "inverted": True, "original": {}
}
1505 with self
.subTest(action
="dispose", inverted
=True):
1506 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1507 compute_value
.return_value
= D("125")
1509 value_from
= portfolio
.Amount("BTC", "10")
1510 value_from
.rate
= D("0.01")
1511 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1512 value_to
= portfolio
.Amount("BTC", "1")
1513 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1515 trade
.prepare_order(compute_value
="foo")
1517 filled_amount
.assert_called_with(in_base_currency
=True)
1518 compute_value
.assert_called_with(get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1519 self
.assertEqual(1, len(trade
.orders
))
1520 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1521 D("125"), "FOO", "long", "market",
1522 trade
, close_if_possible
=False)
1524 with self
.subTest(action
="acquire", inverted
=True):
1525 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1526 compute_value
.return_value
= D("125")
1528 value_from
= portfolio
.Amount("BTC", "1")
1529 value_from
.rate
= D("0.01")
1530 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1531 value_to
= portfolio
.Amount("BTC", "10")
1532 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1534 trade
.prepare_order(compute_value
="foo")
1536 filled_amount
.assert_called_with(in_base_currency
=False)
1537 compute_value
.assert_called_with(get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1538 self
.assertEqual(1, len(trade
.orders
))
1539 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1540 D("125"), "FOO", "long", "market",
1541 trade
, close_if_possible
=False)
1544 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1545 def test_update_order(self
, prepare_order
):
1546 order_mock
= mock
.Mock()
1547 new_order_mock
= mock
.Mock()
1549 value_from
= portfolio
.Amount("BTC", "0.5")
1550 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1551 value_to
= portfolio
.Amount("BTC", "1.0")
1552 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1553 prepare_order
.return_value
= new_order_mock
1555 for i
in [0, 1, 3, 4, 6]:
1556 with self
.subTest(tick
=i
), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1557 trade
.update_order(order_mock
, i
)
1558 order_mock
.cancel
.assert_not_called()
1559 new_order_mock
.run
.assert_not_called()
1560 self
.assertRegex(stdout_mock
.getvalue(), "tick {}, waiting".format(i
))
1562 order_mock
.reset_mock()
1563 new_order_mock
.reset_mock()
1566 with mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1567 trade
.update_order(order_mock
, 2)
1568 order_mock
.cancel
.assert_called()
1569 new_order_mock
.run
.assert_called()
1570 prepare_order
.assert_called()
1571 self
.assertRegex(stdout_mock
.getvalue(), "tick 2, cancelling and adjusting")
1573 order_mock
.reset_mock()
1574 new_order_mock
.reset_mock()
1577 with mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1578 trade
.update_order(order_mock
, 5)
1579 order_mock
.cancel
.assert_called()
1580 new_order_mock
.run
.assert_called()
1581 prepare_order
.assert_called()
1582 self
.assertRegex(stdout_mock
.getvalue(), "tick 5, cancelling and adjusting")
1584 order_mock
.reset_mock()
1585 new_order_mock
.reset_mock()
1588 with mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1589 trade
.update_order(order_mock
, 7)
1590 order_mock
.cancel
.assert_called()
1591 new_order_mock
.run
.assert_called()
1592 prepare_order
.assert_called_with(compute_value
="default")
1593 self
.assertRegex(stdout_mock
.getvalue(), "tick 7, fallbacking to market value")
1594 self
.assertRegex(stdout_mock
.getvalue(), "tick 7, market value, cancelling and adjusting to")
1596 order_mock
.reset_mock()
1597 new_order_mock
.reset_mock()
1600 for i
in [10, 13, 16]:
1601 with self
.subTest(tick
=i
), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1602 trade
.update_order(order_mock
, i
)
1603 order_mock
.cancel
.assert_called()
1604 new_order_mock
.run
.assert_called()
1605 prepare_order
.assert_called_with(compute_value
="default")
1606 self
.assertNotRegex(stdout_mock
.getvalue(), "tick {}, fallbacking to market value".format(i
))
1607 self
.assertRegex(stdout_mock
.getvalue(), "tick {}, market value, cancelling and adjusting to".format(i
))
1609 order_mock
.reset_mock()
1610 new_order_mock
.reset_mock()
1613 for i
in [8, 9, 11, 12]:
1614 with self
.subTest(tick
=i
), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1615 trade
.update_order(order_mock
, i
)
1616 order_mock
.cancel
.assert_not_called()
1617 new_order_mock
.run
.assert_not_called()
1618 self
.assertEqual("", stdout_mock
.getvalue())
1620 order_mock
.reset_mock()
1621 new_order_mock
.reset_mock()
1625 @mock.patch('sys.stdout', new_callable
=StringIO
)
1626 def test_print_with_order(self
, mock_stdout
):
1627 value_from
= portfolio
.Amount("BTC", "0.5")
1628 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1629 value_to
= portfolio
.Amount("BTC", "1.0")
1630 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1632 order_mock1
= mock
.Mock()
1633 order_mock1
.__repr__
= mock
.Mock()
1634 order_mock1
.__repr__
.return_value
= "Mock 1"
1635 order_mock2
= mock
.Mock()
1636 order_mock2
.__repr__
= mock
.Mock()
1637 order_mock2
.__repr__
.return_value
= "Mock 2"
1638 trade
.orders
.append(order_mock1
)
1639 trade
.orders
.append(order_mock2
)
1641 trade
.print_with_order()
1643 out
= mock_stdout
.getvalue().split("\n")
1644 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", out
[0])
1645 self
.assertEqual("\tMock 1", out
[1])
1646 self
.assertEqual("\tMock 2", out
[2])
1648 def test__repr(self
):
1649 value_from
= portfolio
.Amount("BTC", "0.5")
1650 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1651 value_to
= portfolio
.Amount("BTC", "1.0")
1652 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1654 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1656 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1657 class OrderTest(WebMockTestCase
):
1658 def test_values(self
):
1659 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1660 D("0.1"), "BTC", "long", "market", "trade")
1661 self
.assertEqual("buy", order
.action
)
1662 self
.assertEqual(10, order
.amount
.value
)
1663 self
.assertEqual("ETH", order
.amount
.currency
)
1664 self
.assertEqual(D("0.1"), order
.rate
)
1665 self
.assertEqual("BTC", order
.base_currency
)
1666 self
.assertEqual("market", order
.market
)
1667 self
.assertEqual("long", order
.trade_type
)
1668 self
.assertEqual("pending", order
.status
)
1669 self
.assertEqual("trade", order
.trade
)
1670 self
.assertIsNone(order
.id)
1671 self
.assertFalse(order
.close_if_possible
)
1673 def test__repr(self
):
1674 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1675 D("0.1"), "BTC", "long", "market", "trade")
1676 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1678 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1679 D("0.1"), "BTC", "long", "market", "trade",
1680 close_if_possible
=True)
1681 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1683 def test_account(self
):
1684 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1685 D("0.1"), "BTC", "long", "market", "trade")
1686 self
.assertEqual("exchange", order
.account
)
1688 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1689 D("0.1"), "BTC", "short", "market", "trade")
1690 self
.assertEqual("margin", order
.account
)
1692 def test_pending(self
):
1693 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1694 D("0.1"), "BTC", "long", "market", "trade")
1695 self
.assertTrue(order
.pending
)
1696 order
.status
= "open"
1697 self
.assertFalse(order
.pending
)
1699 def test_open(self
):
1700 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1701 D("0.1"), "BTC", "long", "market", "trade")
1702 self
.assertFalse(order
.open)
1703 order
.status
= "open"
1704 self
.assertTrue(order
.open)
1706 def test_finished(self
):
1707 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1708 D("0.1"), "BTC", "long", "market", "trade")
1709 self
.assertFalse(order
.finished
)
1710 order
.status
= "closed"
1711 self
.assertTrue(order
.finished
)
1712 order
.status
= "canceled"
1713 self
.assertTrue(order
.finished
)
1714 order
.status
= "error"
1715 self
.assertTrue(order
.finished
)
1717 @mock.patch.object(portfolio
.Order
, "fetch")
1718 def test_cancel(self
, fetch
):
1719 market
= mock
.Mock()
1720 portfolio
.TradeStore
.debug
= True
1721 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1722 D("0.1"), "BTC", "long", market
, "trade")
1723 order
.status
= "open"
1726 market
.cancel_order
.assert_not_called()
1727 self
.assertEqual("canceled", order
.status
)
1729 portfolio
.TradeStore
.debug
= False
1730 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1731 D("0.1"), "BTC", "long", market
, "trade")
1732 order
.status
= "open"
1736 market
.cancel_order
.assert_called_with(42)
1737 fetch
.assert_called_once()
1739 def test_dust_amount_remaining(self
):
1740 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1741 D("0.1"), "BTC", "long", "market", "trade")
1742 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1743 self
.assertFalse(order
.dust_amount_remaining())
1745 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1746 self
.assertTrue(order
.dust_amount_remaining())
1748 @mock.patch.object(portfolio
.Order
, "fetch")
1749 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1750 def test_remaining_amount(self
, filled_amount
, fetch
):
1751 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1752 D("0.1"), "BTC", "long", "market", "trade")
1754 self
.assertEqual(9, order
.remaining_amount().value
)
1755 order
.fetch
.assert_not_called()
1757 order
.status
= "open"
1758 self
.assertEqual(9, order
.remaining_amount().value
)
1759 fetch
.assert_called_once()
1761 @mock.patch.object(portfolio
.Order
, "fetch")
1762 def test_filled_amount(self
, fetch
):
1763 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1764 D("0.1"), "BTC", "long", "market", "trade")
1765 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1766 "tradeID": 42, "type": "buy", "fee": "0.0015",
1767 "date": "2017-12-30 12:00:12", "rate": "0.1",
1768 "amount": "3", "total": "0.3"
1770 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1771 "tradeID": 43, "type": "buy", "fee": "0.0015",
1772 "date": "2017-12-30 13:00:12", "rate": "0.2",
1773 "amount": "2", "total": "0.4"
1775 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1776 fetch
.assert_not_called()
1777 order
.status
= "open"
1778 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1779 fetch
.assert_called_once()
1780 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1782 def test_fetch_mouvements(self
):
1783 market
= mock
.Mock()
1784 market
.privatePostReturnOrderTrades
.return_value
= [
1786 "tradeID": 42, "type": "buy", "fee": "0.0015",
1787 "date": "2017-12-30 12:00:12", "rate": "0.1",
1788 "amount": "3", "total": "0.3"
1791 "tradeID": 43, "type": "buy", "fee": "0.0015",
1792 "date": "2017-12-30 13:00:12", "rate": "0.2",
1793 "amount": "2", "total": "0.4"
1796 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1797 D("0.1"), "BTC", "long", market
, "trade")
1799 order
.mouvements
= ["Foo", "Bar", "Baz"]
1801 order
.fetch_mouvements()
1803 market
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
1804 self
.assertEqual(2, len(order
.mouvements
))
1805 self
.assertEqual(42, order
.mouvements
[0].id)
1806 self
.assertEqual(43, order
.mouvements
[1].id)
1808 market
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
1809 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1810 D("0.1"), "BTC", "long", market
, "trade")
1811 order
.fetch_mouvements()
1812 self
.assertEqual(0, len(order
.mouvements
))
1814 def test_mark_finished_order(self
):
1815 market
= mock
.Mock()
1816 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1817 D("0.1"), "BTC", "short", market
, "trade",
1818 close_if_possible
=True)
1819 order
.status
= "closed"
1820 portfolio
.TradeStore
.debug
= False
1822 order
.mark_finished_order()
1823 market
.close_margin_position
.assert_called_with("ETH", "BTC")
1824 market
.close_margin_position
.reset_mock()
1826 order
.status
= "open"
1827 order
.mark_finished_order()
1828 market
.close_margin_position
.assert_not_called()
1830 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1831 D("0.1"), "BTC", "short", market
, "trade",
1832 close_if_possible
=False)
1833 order
.status
= "closed"
1834 order
.mark_finished_order()
1835 market
.close_margin_position
.assert_not_called()
1837 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1838 D("0.1"), "BTC", "short", market
, "trade",
1839 close_if_possible
=True)
1840 order
.status
= "closed"
1841 order
.mark_finished_order()
1842 market
.close_margin_position
.assert_not_called()
1844 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1845 D("0.1"), "BTC", "long", market
, "trade",
1846 close_if_possible
=True)
1847 order
.status
= "closed"
1848 order
.mark_finished_order()
1849 market
.close_margin_position
.assert_not_called()
1851 portfolio
.TradeStore
.debug
= True
1853 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1854 D("0.1"), "BTC", "short", market
, "trade",
1855 close_if_possible
=True)
1856 order
.status
= "closed"
1858 order
.mark_finished_order()
1859 market
.close_margin_position
.assert_not_called()
1861 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
1862 def test_fetch(self
, fetch_mouvements
):
1863 time
= self
.time
.time()
1864 with mock
.patch
.object(portfolio
.time
, "time") as time_mock
:
1865 market
= mock
.Mock()
1866 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1867 D("0.1"), "BTC", "long", market
, "trade")
1869 with self
.subTest(debug
=True):
1870 portfolio
.TradeStore
.debug
= True
1872 time_mock
.assert_not_called()
1873 order
.fetch(force
=True)
1874 time_mock
.assert_not_called()
1875 market
.fetch_order
.assert_not_called()
1876 fetch_mouvements
.assert_not_called()
1877 self
.assertIsNone(order
.fetch_cache_timestamp
)
1879 with self
.subTest(debug
=False):
1880 portfolio
.TradeStore
.debug
= False
1881 time_mock
.return_value
= time
1882 market
.fetch_order
.return_value
= {
1884 "datetime": "timestamp"
1888 market
.fetch_order
.assert_called_once()
1889 fetch_mouvements
.assert_called_once()
1890 self
.assertEqual("foo", order
.status
)
1891 self
.assertEqual("timestamp", order
.timestamp
)
1892 self
.assertEqual(time
, order
.fetch_cache_timestamp
)
1893 self
.assertEqual(1, len(order
.results
))
1895 market
.fetch_order
.reset_mock()
1896 fetch_mouvements
.reset_mock()
1898 time_mock
.return_value
= time
+ 8
1900 market
.fetch_order
.assert_not_called()
1901 fetch_mouvements
.assert_not_called()
1903 order
.fetch(force
=True)
1904 market
.fetch_order
.assert_called_once()
1905 fetch_mouvements
.assert_called_once()
1907 market
.fetch_order
.reset_mock()
1908 fetch_mouvements
.reset_mock()
1910 time_mock
.return_value
= time
+ 19
1912 market
.fetch_order
.assert_called_once()
1913 fetch_mouvements
.assert_called_once()
1915 @mock.patch.object(portfolio
.Order
, "fetch")
1916 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
1917 def test_get_status(self
, mark_finished_order
, fetch
):
1918 with self
.subTest(debug
=True):
1919 portfolio
.TradeStore
.debug
= True
1920 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1921 D("0.1"), "BTC", "long", "market", "trade")
1922 self
.assertEqual("pending", order
.get_status())
1923 fetch
.assert_not_called()
1925 with self
.subTest(debug
=False, finished
=False):
1926 portfolio
.TradeStore
.debug
= False
1927 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1928 D("0.1"), "BTC", "long", "market", "trade")
1930 def update_status():
1931 order
.status
= "open"
1932 return update_status
1933 fetch
.side_effect
= _fetch(order
)
1934 self
.assertEqual("open", order
.get_status())
1935 mark_finished_order
.assert_not_called()
1936 fetch
.assert_called_once()
1938 mark_finished_order
.reset_mock()
1940 with self
.subTest(debug
=False, finished
=True):
1941 portfolio
.TradeStore
.debug
= False
1942 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1943 D("0.1"), "BTC", "long", "market", "trade")
1945 def update_status():
1946 order
.status
= "closed"
1947 return update_status
1948 fetch
.side_effect
= _fetch(order
)
1949 self
.assertEqual("closed", order
.get_status())
1950 mark_finished_order
.assert_called_once()
1951 fetch
.assert_called_once()
1954 market
= mock
.Mock()
1956 market
.order_precision
.return_value
= 4
1957 with self
.subTest(debug
=True),\
1958 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1959 portfolio
.TradeStore
.debug
= True
1960 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1961 D("0.1"), "BTC", "long", market
, "trade")
1963 market
.create_order
.assert_not_called()
1964 self
.assertEqual("market.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)\n", stdout_mock
.getvalue())
1965 self
.assertEqual("open", order
.status
)
1966 self
.assertEqual(1, len(order
.results
))
1967 self
.assertEqual(-1, order
.id)
1969 market
.create_order
.reset_mock()
1970 with self
.subTest(debug
=False):
1971 portfolio
.TradeStore
.debug
= False
1972 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1973 D("0.1"), "BTC", "long", market
, "trade")
1974 market
.create_order
.return_value
= { "id": 123 }
1976 market
.create_order
.assert_called_once()
1977 self
.assertEqual(1, len(order
.results
))
1978 self
.assertEqual("open", order
.status
)
1980 market
.create_order
.reset_mock()
1981 with self
.subTest(exception
=True),\
1982 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1983 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1984 D("0.1"), "BTC", "long", market
, "trade")
1985 market
.create_order
.side_effect
= Exception("bouh")
1987 market
.create_order
.assert_called_once()
1988 self
.assertEqual(0, len(order
.results
))
1989 self
.assertEqual("error", order
.status
)
1990 self
.assertRegex(stdout_mock
.getvalue(), "error when running market.create_order")
1991 self
.assertRegex(stdout_mock
.getvalue(), "Exception: bouh")
1993 market
.create_order
.reset_mock()
1994 with self
.subTest(dust_amount_exception
=True),\
1995 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
1996 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
1997 D("0.1"), "BTC", "long", market
, "trade")
1998 market
.create_order
.side_effect
= portfolio
.ExchangeNotAvailable
2000 market
.create_order
.assert_called_once()
2001 self
.assertEqual(0, len(order
.results
))
2002 self
.assertEqual("closed", order
.status
)
2003 mark_finished_order
.assert_called_once()
2006 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2007 class MouvementTest(WebMockTestCase
):
2008 def test_values(self
):
2009 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2010 "tradeID": 42, "type": "buy", "fee": "0.0015",
2011 "date": "2017-12-30 12:00:12", "rate": "0.1",
2012 "amount": "10", "total": "1"
2014 self
.assertEqual("ETH", mouvement
.currency
)
2015 self
.assertEqual("BTC", mouvement
.base_currency
)
2016 self
.assertEqual(42, mouvement
.id)
2017 self
.assertEqual("buy", mouvement
.action
)
2018 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2019 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2020 self
.assertEqual(D("0.1"), mouvement
.rate
)
2021 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2022 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2024 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2025 self
.assertIsNone(mouvement
.date
)
2026 self
.assertIsNone(mouvement
.id)
2027 self
.assertIsNone(mouvement
.action
)
2028 self
.assertEqual(-1, mouvement
.fee_rate
)
2029 self
.assertEqual(0, mouvement
.rate
)
2030 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2031 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2033 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
2034 class AcceptanceTest(WebMockTestCase
):
2035 @unittest.expectedFailure
2036 def test_success_sell_only_necessary(self
):
2039 "exchange_free": D("1.0"),
2040 "exchange_used": D("0.0"),
2041 "exchange_total": D("1.0"),
2045 "exchange_free": D("4.0"),
2046 "exchange_used": D("0.0"),
2047 "exchange_total": D("4.0"),
2051 "exchange_free": D("1000.0"),
2052 "exchange_used": D("0.0"),
2053 "exchange_total": D("1000.0"),
2054 "total": D("1000.0"),
2058 "ETH": (D("0.25"), "long"),
2059 "ETC": (D("0.25"), "long"),
2060 "BTC": (D("0.4"), "long"),
2061 "BTD": (D("0.01"), "short"),
2062 "B2X": (D("0.04"), "long"),
2063 "USDT": (D("0.05"), "long"),
2066 def fetch_ticker(symbol
):
2067 if symbol
== "ETH/BTC":
2069 "symbol": "ETH/BTC",
2073 if symbol
== "ETC/BTC":
2075 "symbol": "ETC/BTC",
2079 if symbol
== "XVG/BTC":
2081 "symbol": "XVG/BTC",
2082 "bid": D("0.00003"),
2085 if symbol
== "BTD/BTC":
2087 "symbol": "BTD/BTC",
2091 if symbol
== "B2X/BTC":
2093 "symbol": "B2X/BTC",
2097 if symbol
== "USDT/BTC":
2098 raise helper
.ExchangeError
2099 if symbol
== "BTC/USDT":
2101 "symbol": "BTC/USDT",
2105 self
.fail("Shouldn't have been called with {}".format(symbol
))
2107 market
= mock
.Mock()
2108 market
.fetch_all_balances
.return_value
= fetch_balance
2109 market
.fetch_ticker
.side_effect
= fetch_ticker
2110 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
2112 helper
.prepare_trades(market
)
2114 balances
= portfolio
.BalanceStore
.all
2115 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
2116 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
2117 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
2120 trades
= portfolio
.TradeStore
.all
2121 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
2122 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
2123 self
.assertEqual("dispose", trades
[0].action
)
2125 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
2126 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
2127 self
.assertEqual("acquire", trades
[1].action
)
2129 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
2130 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
2131 self
.assertEqual("dispose", trades
[2].action
)
2133 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
2134 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
2135 self
.assertEqual("acquire", trades
[3].action
)
2137 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
2138 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
2139 self
.assertEqual("acquire", trades
[4].action
)
2141 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
2142 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
2143 self
.assertEqual("acquire", trades
[5].action
)
2146 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
2148 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
2149 self
.assertEqual(2, len(all_orders
))
2150 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
2151 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
2152 self
.assertEqual(1000, all_orders
[1].amount
.value
)
2153 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
2156 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
2157 self
.assertEqual("limit", type)
2158 if symbol
== "ETH/BTC":
2159 self
.assertEqual("sell", action
)
2160 self
.assertEqual(D('0.66666666'), amount
)
2161 self
.assertEqual(D("0.14014"), price
)
2162 elif symbol
== "XVG/BTC":
2163 self
.assertEqual("sell", action
)
2164 self
.assertEqual(1000, amount
)
2165 self
.assertEqual(D("0.00003003"), price
)
2167 self
.fail("I shouldn't have been called")
2172 market
.create_order
.side_effect
= create_order
2173 market
.order_precision
.return_value
= 8
2176 portfolio
.TradeStore
.run_orders()
2178 self
.assertEqual("open", all_orders
[0].status
)
2179 self
.assertEqual("open", all_orders
[1].status
)
2181 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
2182 market
.privatePostReturnOrderTrades
.return_value
= [
2184 "tradeID": 42, "type": "buy", "fee": "0.0015",
2185 "date": "2017-12-30 12:00:12", "rate": "0.1",
2186 "amount": "10", "total": "1"
2189 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
2191 helper
.follow_orders(verbose
=False)
2193 sleep
.assert_called_with(30)
2195 for order
in all_orders
:
2196 self
.assertEqual("closed", order
.status
)
2200 "exchange_free": D("1.0") / 3,
2201 "exchange_used": D("0.0"),
2202 "exchange_total": D("1.0") / 3,
2204 "total": D("1.0") / 3,
2207 "exchange_free": D("0.134"),
2208 "exchange_used": D("0.0"),
2209 "exchange_total": D("0.134"),
2211 "total": D("0.134"),
2214 "exchange_free": D("4.0"),
2215 "exchange_used": D("0.0"),
2216 "exchange_total": D("4.0"),
2221 "exchange_free": D("0.0"),
2222 "exchange_used": D("0.0"),
2223 "exchange_total": D("0.0"),
2228 market
.fetch_all_balances
.return_value
= fetch_balance
2230 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
2232 helper
.update_trades(market
, only
="acquire", compute_value
="average")
2234 balances
= portfolio
.BalanceStore
.all
2235 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
2236 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
2237 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
2238 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
2241 trades
= portfolio
.TradeStore
.all
2242 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
2243 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
2244 self
.assertEqual("dispose", trades
[0].action
)
2246 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
2247 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
2248 self
.assertEqual("acquire", trades
[1].action
)
2250 self
.assertNotIn("BTC", trades
)
2252 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
2253 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
2254 self
.assertEqual("dispose", trades
[2].action
)
2256 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
2257 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
2258 self
.assertEqual("acquire", trades
[3].action
)
2260 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
2261 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
2262 self
.assertEqual("acquire", trades
[4].action
)
2264 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
2265 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
2266 self
.assertEqual("acquire", trades
[5].action
)
2269 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
2271 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
2272 self
.assertEqual(4, len(all_orders
))
2273 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
2274 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
2275 self
.assertEqual("buy", all_orders
[0].action
)
2276 self
.assertEqual("long", all_orders
[0].trade_type
)
2278 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
2279 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
2280 self
.assertEqual("sell", all_orders
[1].action
)
2281 self
.assertEqual("short", all_orders
[1].trade_type
)
2283 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
2284 self
.assertAlmostEqual(0, diff
.value
)
2285 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
2286 self
.assertEqual("buy", all_orders
[2].action
)
2287 self
.assertEqual("long", all_orders
[2].trade_type
)
2289 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
2290 self
.assertEqual(D("16000"), all_orders
[3].rate
)
2291 self
.assertEqual("sell", all_orders
[3].action
)
2292 self
.assertEqual("long", all_orders
[3].trade_type
)
2296 # Move balances to margin
2300 # portfolio.TradeStore.run_orders()
2302 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
2304 helper
.follow_orders(verbose
=False)
2306 sleep
.assert_called_with(30)
2308 if __name__
== '__main__':