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(helper
, "prepare_trades")
824 @mock.patch.object(helper
, "follow_orders")
825 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
826 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
827 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
828 @mock.patch('sys.stdout', new_callable
=StringIO
)
829 def test_process_sell_needed__1_sell(self
, stdout_mock
, run_orders
,
830 print_all_with_order
, prepare_orders
, follow_orders
,
833 portfolio
.BalanceStore
.all
= {
834 "BTC": portfolio
.Balance("BTC", {
836 "exchange_total":"0.65",
837 "exchange_free": "0.35",
838 "exchange_used": "0.30"}),
839 "ETH": portfolio
.Balance("ETH", {
843 "exchange_used": 0}),
845 helper
.process_sell_needed__1_sell(market
)
846 prepare_trades
.assert_called_with(market
, base_currency
="BTC",
848 prepare_orders
.assert_called_with(compute_value
="average",
850 print_all_with_order
.assert_called()
851 run_orders
.assert_called()
852 follow_orders
.assert_called()
853 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
855 @mock.patch.object(helper
, "update_trades")
856 @mock.patch.object(helper
, "follow_orders")
857 @mock.patch.object(helper
, "move_balances")
858 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
859 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
860 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
861 @mock.patch('sys.stdout', new_callable
=StringIO
)
862 def test_process_sell_needed__2_buy(self
, stdout_mock
, run_orders
,
863 print_all_with_order
, prepare_orders
, move_balances
,
864 follow_orders
, update_trades
):
866 portfolio
.BalanceStore
.all
= {
867 "BTC": portfolio
.Balance("BTC", {
869 "exchange_total":"0.65",
870 "exchange_free": "0.35",
871 "exchange_used": "0.30"}),
872 "ETH": portfolio
.Balance("ETH", {
876 "exchange_used": 0}),
878 helper
.process_sell_needed__2_buy(market
)
879 update_trades
.assert_called_with(market
, base_currency
="BTC",
880 debug
=False, only
="acquire")
881 prepare_orders
.assert_called_with(compute_value
="average",
883 print_all_with_order
.assert_called()
884 move_balances
.assert_called_with(market
, debug
=False)
885 run_orders
.assert_called()
886 follow_orders
.assert_called()
887 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
889 @mock.patch.object(helper
, "prepare_trades_to_sell_all")
890 @mock.patch.object(helper
, "follow_orders")
891 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
892 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
893 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
894 @mock.patch('sys.stdout', new_callable
=StringIO
)
895 def test_process_sell_all__1_sell(self
, stdout_mock
, run_orders
,
896 print_all_with_order
, prepare_orders
, follow_orders
,
897 prepare_trades_to_sell_all
):
899 portfolio
.BalanceStore
.all
= {
900 "BTC": portfolio
.Balance("BTC", {
902 "exchange_total":"0.65",
903 "exchange_free": "0.35",
904 "exchange_used": "0.30"}),
905 "ETH": portfolio
.Balance("ETH", {
909 "exchange_used": 0}),
911 helper
.process_sell_all__1_all_sell(market
)
912 prepare_trades_to_sell_all
.assert_called_with(market
, base_currency
="BTC",
914 prepare_orders
.assert_called_with(compute_value
="average")
915 print_all_with_order
.assert_called()
916 run_orders
.assert_called()
917 follow_orders
.assert_called()
918 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
920 @mock.patch.object(helper
, "prepare_trades")
921 @mock.patch.object(helper
, "follow_orders")
922 @mock.patch.object(helper
, "move_balances")
923 @mock.patch.object(portfolio
.TradeStore
, "prepare_orders")
924 @mock.patch.object(portfolio
.TradeStore
, "print_all_with_order")
925 @mock.patch.object(portfolio
.TradeStore
, "run_orders")
926 @mock.patch('sys.stdout', new_callable
=StringIO
)
927 def test_process_sell_all__2_all_buy(self
, stdout_mock
, run_orders
,
928 print_all_with_order
, prepare_orders
, move_balances
,
929 follow_orders
, prepare_trades
):
931 portfolio
.BalanceStore
.all
= {
932 "BTC": portfolio
.Balance("BTC", {
934 "exchange_total":"0.65",
935 "exchange_free": "0.35",
936 "exchange_used": "0.30"}),
937 "ETH": portfolio
.Balance("ETH", {
941 "exchange_used": 0}),
943 helper
.process_sell_all__2_all_buy(market
)
944 prepare_trades
.assert_called_with(market
, base_currency
="BTC",
946 prepare_orders
.assert_called_with()
947 print_all_with_order
.assert_called()
948 move_balances
.assert_called_with(market
, debug
=False)
949 run_orders
.assert_called()
950 follow_orders
.assert_called()
951 self
.assertRegex(stdout_mock
.getvalue(), "Balance")
954 @unittest.skipUnless("unit" in limits
, "Unit skipped")
955 class TradeStoreTest(WebMockTestCase
):
956 @mock.patch.object(portfolio
.BalanceStore
, "currencies")
957 @mock.patch.object(portfolio
.TradeStore
, "add_trade_if_matching")
958 def test_compute_trades(self
, add_trade_if_matching
, currencies
):
959 currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
962 "XMR": portfolio
.Amount("BTC", D("0.9")),
963 "DASH": portfolio
.Amount("BTC", D("0.4")),
964 "XVG": portfolio
.Amount("BTC", D("-0.5")),
965 "BTC": portfolio
.Amount("BTC", D("0.5")),
968 "DASH": portfolio
.Amount("BTC", D("0.5")),
969 "XVG": portfolio
.Amount("BTC", D("0.1")),
970 "BTC": portfolio
.Amount("BTC", D("0.4")),
971 "ETH": portfolio
.Amount("BTC", D("0.3")),
974 portfolio
.TradeStore
.compute_trades(values_in_base
,
975 new_repartition
, only
="only", market
="market")
977 self
.assertEqual(5, add_trade_if_matching
.call_count
)
978 add_trade_if_matching
.assert_any_call(
979 portfolio
.Amount("BTC", D("0.9")),
980 portfolio
.Amount("BTC", 0),
981 "XMR", only
="only", market
="market"
983 add_trade_if_matching
.assert_any_call(
984 portfolio
.Amount("BTC", D("0.4")),
985 portfolio
.Amount("BTC", D("0.5")),
986 "DASH", only
="only", market
="market"
988 add_trade_if_matching
.assert_any_call(
989 portfolio
.Amount("BTC", D("-0.5")),
990 portfolio
.Amount("BTC", D("0")),
991 "XVG", only
="only", market
="market"
993 add_trade_if_matching
.assert_any_call(
994 portfolio
.Amount("BTC", D("0")),
995 portfolio
.Amount("BTC", D("0.1")),
996 "XVG", only
="only", market
="market"
998 add_trade_if_matching
.assert_any_call(
999 portfolio
.Amount("BTC", D("0")),
1000 portfolio
.Amount("BTC", D("0.3")),
1001 "ETH", only
="only", market
="market"
1004 def test_add_trade_if_matching(self
):
1005 result
= portfolio
.TradeStore
.add_trade_if_matching(
1006 portfolio
.Amount("BTC", D("0")),
1007 portfolio
.Amount("BTC", D("0.3")),
1008 "ETH", only
="nope", market
="market"
1010 self
.assertEqual(0, len(portfolio
.TradeStore
.all
))
1011 self
.assertEqual(False, result
)
1013 portfolio
.TradeStore
.all
= []
1014 result
= portfolio
.TradeStore
.add_trade_if_matching(
1015 portfolio
.Amount("BTC", D("0")),
1016 portfolio
.Amount("BTC", D("0.3")),
1017 "ETH", only
=None, market
="market"
1019 self
.assertEqual(1, len(portfolio
.TradeStore
.all
))
1020 self
.assertEqual(True, result
)
1022 portfolio
.TradeStore
.all
= []
1023 result
= portfolio
.TradeStore
.add_trade_if_matching(
1024 portfolio
.Amount("BTC", D("0")),
1025 portfolio
.Amount("BTC", D("0.3")),
1026 "ETH", only
="acquire", market
="market"
1028 self
.assertEqual(1, len(portfolio
.TradeStore
.all
))
1029 self
.assertEqual(True, result
)
1031 portfolio
.TradeStore
.all
= []
1032 result
= portfolio
.TradeStore
.add_trade_if_matching(
1033 portfolio
.Amount("BTC", D("0")),
1034 portfolio
.Amount("BTC", D("0.3")),
1035 "ETH", only
="dispose", market
="market"
1037 self
.assertEqual(0, len(portfolio
.TradeStore
.all
))
1038 self
.assertEqual(False, result
)
1040 def test_prepare_orders(self
):
1041 trade_mock1
= mock
.Mock()
1042 trade_mock2
= mock
.Mock()
1044 portfolio
.TradeStore
.all
.append(trade_mock1
)
1045 portfolio
.TradeStore
.all
.append(trade_mock2
)
1047 portfolio
.TradeStore
.prepare_orders()
1048 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1049 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1051 portfolio
.TradeStore
.prepare_orders(compute_value
="bla")
1052 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1053 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1055 trade_mock1
.prepare_order
.reset_mock()
1056 trade_mock2
.prepare_order
.reset_mock()
1058 trade_mock1
.action
= "foo"
1059 trade_mock2
.action
= "bar"
1060 portfolio
.TradeStore
.prepare_orders(only
="bar")
1061 trade_mock1
.prepare_order
.assert_not_called()
1062 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1064 def test_print_all_with_order(self
):
1065 trade_mock1
= mock
.Mock()
1066 trade_mock2
= mock
.Mock()
1067 trade_mock3
= mock
.Mock()
1068 portfolio
.TradeStore
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1070 portfolio
.TradeStore
.print_all_with_order()
1072 trade_mock1
.print_with_order
.assert_called()
1073 trade_mock2
.print_with_order
.assert_called()
1074 trade_mock3
.print_with_order
.assert_called()
1076 @mock.patch.object(portfolio
.TradeStore
, "all_orders")
1077 def test_run_orders(self
, all_orders
):
1078 order_mock1
= mock
.Mock()
1079 order_mock2
= mock
.Mock()
1080 order_mock3
= mock
.Mock()
1081 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1082 portfolio
.TradeStore
.run_orders()
1083 all_orders
.assert_called_with(state
="pending")
1085 order_mock1
.run
.assert_called()
1086 order_mock2
.run
.assert_called()
1087 order_mock3
.run
.assert_called()
1089 def test_all_orders(self
):
1090 trade_mock1
= mock
.Mock()
1091 trade_mock2
= mock
.Mock()
1093 order_mock1
= mock
.Mock()
1094 order_mock2
= mock
.Mock()
1095 order_mock3
= mock
.Mock()
1097 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1098 trade_mock2
.orders
= [order_mock3
]
1100 order_mock1
.status
= "pending"
1101 order_mock2
.status
= "open"
1102 order_mock3
.status
= "open"
1104 portfolio
.TradeStore
.all
.append(trade_mock1
)
1105 portfolio
.TradeStore
.all
.append(trade_mock2
)
1107 orders
= portfolio
.TradeStore
.all_orders()
1108 self
.assertEqual(3, len(orders
))
1110 open_orders
= portfolio
.TradeStore
.all_orders(state
="open")
1111 self
.assertEqual(2, len(open_orders
))
1112 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1114 @mock.patch.object(portfolio
.TradeStore
, "all_orders")
1115 def test_update_all_orders_status(self
, all_orders
):
1116 order_mock1
= mock
.Mock()
1117 order_mock2
= mock
.Mock()
1118 order_mock3
= mock
.Mock()
1119 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1120 portfolio
.TradeStore
.update_all_orders_status()
1121 all_orders
.assert_called_with(state
="open")
1123 order_mock1
.get_status
.assert_called()
1124 order_mock2
.get_status
.assert_called()
1125 order_mock3
.get_status
.assert_called()
1127 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1128 class BalanceStoreTest(WebMockTestCase
):
1130 super(BalanceStoreTest
, self
).setUp()
1132 self
.fetch_balance
= {
1136 "exchange_total": 0,
1140 "exchange_free": D("6.0"),
1141 "exchange_used": D("1.2"),
1142 "exchange_total": D("7.2"),
1146 "exchange_free": 16,
1148 "exchange_total": 16,
1154 "exchange_total": 0,
1155 "margin_total": D("-1.0"),
1160 @mock.patch.object(helper
, "get_ticker")
1161 def test_in_currency(self
, get_ticker
):
1162 portfolio
.BalanceStore
.all
= {
1163 "BTC": portfolio
.Balance("BTC", {
1165 "exchange_total":"0.65",
1166 "exchange_free": "0.35",
1167 "exchange_used": "0.30"}),
1168 "ETH": portfolio
.Balance("ETH", {
1170 "exchange_total": 3,
1172 "exchange_used": 0}),
1174 market
= mock
.Mock()
1175 get_ticker
.return_value
= {
1178 "average": D("0.1"),
1181 amounts
= portfolio
.BalanceStore
.in_currency("BTC", market
)
1182 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1183 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1184 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1186 amounts
= portfolio
.BalanceStore
.in_currency("BTC", market
, compute_value
="bid")
1187 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1188 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1190 amounts
= portfolio
.BalanceStore
.in_currency("BTC", market
, compute_value
="bid", type="exchange_used")
1191 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1192 self
.assertEqual(0, amounts
["ETH"].value
)
1194 def test_fetch_balances(self
):
1195 market
= mock
.Mock()
1196 market
.fetch_all_balances
.return_value
= self
.fetch_balance
1198 portfolio
.BalanceStore
.fetch_balances(market
)
1199 self
.assertNotIn("ETC", portfolio
.BalanceStore
.currencies())
1200 self
.assertListEqual(["USDT", "XVG", "XMR"], list(portfolio
.BalanceStore
.currencies()))
1202 portfolio
.BalanceStore
.all
["ETC"] = portfolio
.Balance("ETC", {
1203 "exchange_total": "1", "exchange_free": "0",
1204 "exchange_used": "1" })
1205 portfolio
.BalanceStore
.fetch_balances(market
)
1206 self
.assertEqual(0, portfolio
.BalanceStore
.all
["ETC"].total
)
1207 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(portfolio
.BalanceStore
.currencies()))
1209 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1210 def test_dispatch_assets(self
, repartition
):
1211 market
= mock
.Mock()
1212 market
.fetch_all_balances
.return_value
= self
.fetch_balance
1213 portfolio
.BalanceStore
.fetch_balances(market
)
1215 self
.assertNotIn("XEM", portfolio
.BalanceStore
.currencies())
1217 repartition
.return_value
= {
1218 "XEM": (D("0.75"), "long"),
1219 "BTC": (D("0.26"), "long"),
1220 "DASH": (D("0.10"), "short"),
1223 amounts
= portfolio
.BalanceStore
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1224 self
.assertIn("XEM", portfolio
.BalanceStore
.currencies())
1225 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1226 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1227 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1229 def test_currencies(self
):
1230 portfolio
.BalanceStore
.all
= {
1231 "BTC": portfolio
.Balance("BTC", {
1233 "exchange_total":"0.65",
1234 "exchange_free": "0.35",
1235 "exchange_used": "0.30"}),
1236 "ETH": portfolio
.Balance("ETH", {
1238 "exchange_total": 3,
1240 "exchange_used": 0}),
1242 self
.assertListEqual(["BTC", "ETH"], list(portfolio
.BalanceStore
.currencies()))
1244 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1245 class ComputationTest(WebMockTestCase
):
1246 def test_compute_value(self
):
1247 compute
= mock
.Mock()
1248 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1249 compute
.assert_called_with("foo", "ask")
1251 compute
.reset_mock()
1252 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1253 compute
.assert_called_with("foo", "bid")
1255 compute
.reset_mock()
1256 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1257 compute
.assert_called_with("foo", "ask")
1259 compute
.reset_mock()
1260 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1261 compute
.assert_called_with("foo", "bid")
1263 compute
.reset_mock()
1264 portfolio
.Computation
.computations
["test"] = compute
1265 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1266 compute
.assert_called_with("foo", "bid")
1269 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1270 class TradeTest(WebMockTestCase
):
1272 def test_values_assertion(self
):
1273 value_from
= portfolio
.Amount("BTC", "1.0")
1274 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1275 value_to
= portfolio
.Amount("BTC", "1.0")
1276 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1277 self
.assertEqual("BTC", trade
.base_currency
)
1278 self
.assertEqual("ETH", trade
.currency
)
1280 with self
.assertRaises(AssertionError):
1281 portfolio
.Trade(value_from
, value_to
, "ETC")
1282 with self
.assertRaises(AssertionError):
1283 value_from
.linked_to
= None
1284 portfolio
.Trade(value_from
, value_to
, "ETH")
1285 with self
.assertRaises(AssertionError):
1286 value_from
.currency
= "ETH"
1287 portfolio
.Trade(value_from
, value_to
, "ETH")
1289 value_from
= portfolio
.Amount("BTC", 0)
1290 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1291 self
.assertEqual(0, trade
.value_from
.linked_to
)
1293 def test_action(self
):
1294 value_from
= portfolio
.Amount("BTC", "1.0")
1295 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1296 value_to
= portfolio
.Amount("BTC", "1.0")
1297 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1299 self
.assertIsNone(trade
.action
)
1301 value_from
= portfolio
.Amount("BTC", "1.0")
1302 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1303 value_to
= portfolio
.Amount("BTC", "2.0")
1304 trade
= portfolio
.Trade(value_from
, value_to
, "BTC")
1306 self
.assertIsNone(trade
.action
)
1308 value_from
= portfolio
.Amount("BTC", "0.5")
1309 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1310 value_to
= portfolio
.Amount("BTC", "1.0")
1311 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1313 self
.assertEqual("acquire", trade
.action
)
1315 value_from
= portfolio
.Amount("BTC", "0")
1316 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1317 value_to
= portfolio
.Amount("BTC", "-1.0")
1318 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1320 self
.assertEqual("acquire", trade
.action
)
1322 def test_order_action(self
):
1323 value_from
= portfolio
.Amount("BTC", "0.5")
1324 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1325 value_to
= portfolio
.Amount("BTC", "1.0")
1326 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1328 self
.assertEqual("buy", trade
.order_action(False))
1329 self
.assertEqual("sell", trade
.order_action(True))
1331 value_from
= portfolio
.Amount("BTC", "0")
1332 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1333 value_to
= portfolio
.Amount("BTC", "-1.0")
1334 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1336 self
.assertEqual("sell", trade
.order_action(False))
1337 self
.assertEqual("buy", trade
.order_action(True))
1339 def test_trade_type(self
):
1340 value_from
= portfolio
.Amount("BTC", "0.5")
1341 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1342 value_to
= portfolio
.Amount("BTC", "1.0")
1343 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1345 self
.assertEqual("long", trade
.trade_type
)
1347 value_from
= portfolio
.Amount("BTC", "0")
1348 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1349 value_to
= portfolio
.Amount("BTC", "-1.0")
1350 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1352 self
.assertEqual("short", trade
.trade_type
)
1354 def test_filled_amount(self
):
1355 value_from
= portfolio
.Amount("BTC", "0.5")
1356 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1357 value_to
= portfolio
.Amount("BTC", "1.0")
1358 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1360 order1
= mock
.Mock()
1361 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1363 order2
= mock
.Mock()
1364 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1365 trade
.orders
.append(order1
)
1366 trade
.orders
.append(order2
)
1368 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1369 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1370 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1372 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1373 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1374 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1376 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1377 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1378 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1380 @mock.patch.object(helper
, "get_ticker")
1381 @mock.patch.object(portfolio
.Computation
, "compute_value")
1382 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1383 @mock.patch.object(portfolio
, "Order")
1384 def test_prepare_order(self
, Order
, filled_amount
, compute_value
, get_ticker
):
1385 Order
.return_value
= "Order"
1387 with self
.subTest(desc
="Nothing to do"):
1388 value_from
= portfolio
.Amount("BTC", "10")
1389 value_from
.rate
= D("0.1")
1390 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1391 value_to
= portfolio
.Amount("BTC", "10")
1392 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1394 trade
.prepare_order()
1396 filled_amount
.assert_not_called()
1397 compute_value
.assert_not_called()
1398 self
.assertEqual(0, len(trade
.orders
))
1399 Order
.assert_not_called()
1401 get_ticker
.return_value
= { "inverted": False }
1402 with self
.subTest(desc
="Already filled"), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1403 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1404 compute_value
.return_value
= D("0.125")
1406 value_from
= portfolio
.Amount("BTC", "10")
1407 value_from
.rate
= D("0.1")
1408 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1409 value_to
= portfolio
.Amount("BTC", "0")
1410 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1412 trade
.prepare_order()
1414 filled_amount
.assert_called_with(in_base_currency
=False)
1415 compute_value
.assert_called_with(get_ticker
.return_value
, "sell", compute_value
="default")
1416 self
.assertEqual(0, len(trade
.orders
))
1417 self
.assertRegex(stdout_mock
.getvalue(), "Less to do than already filled: ")
1418 Order
.assert_not_called()
1420 with self
.subTest(action
="dispose", inverted
=False):
1421 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1422 compute_value
.return_value
= D("0.125")
1424 value_from
= portfolio
.Amount("BTC", "10")
1425 value_from
.rate
= D("0.1")
1426 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1427 value_to
= portfolio
.Amount("BTC", "1")
1428 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1430 trade
.prepare_order()
1432 filled_amount
.assert_called_with(in_base_currency
=False)
1433 compute_value
.assert_called_with(get_ticker
.return_value
, "sell", compute_value
="default")
1434 self
.assertEqual(1, len(trade
.orders
))
1435 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1436 D("0.125"), "BTC", "long", "market",
1437 trade
, close_if_possible
=False)
1439 with self
.subTest(action
="acquire", inverted
=False):
1440 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1441 compute_value
.return_value
= D("0.125")
1443 value_from
= portfolio
.Amount("BTC", "1")
1444 value_from
.rate
= D("0.1")
1445 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1446 value_to
= portfolio
.Amount("BTC", "10")
1447 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1449 trade
.prepare_order()
1451 filled_amount
.assert_called_with(in_base_currency
=True)
1452 compute_value
.assert_called_with(get_ticker
.return_value
, "buy", compute_value
="default")
1453 self
.assertEqual(1, len(trade
.orders
))
1455 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1456 D("0.125"), "BTC", "long", "market",
1457 trade
, close_if_possible
=False)
1459 with self
.subTest(close_if_possible
=True):
1460 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1461 compute_value
.return_value
= D("0.125")
1463 value_from
= portfolio
.Amount("BTC", "10")
1464 value_from
.rate
= D("0.1")
1465 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1466 value_to
= portfolio
.Amount("BTC", "0")
1467 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1469 trade
.prepare_order()
1471 filled_amount
.assert_called_with(in_base_currency
=False)
1472 compute_value
.assert_called_with(get_ticker
.return_value
, "sell", compute_value
="default")
1473 self
.assertEqual(1, len(trade
.orders
))
1474 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1475 D("0.125"), "BTC", "long", "market",
1476 trade
, close_if_possible
=True)
1478 get_ticker
.return_value
= { "inverted": True, "original": {}
}
1479 with self
.subTest(action
="dispose", inverted
=True):
1480 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1481 compute_value
.return_value
= D("125")
1483 value_from
= portfolio
.Amount("BTC", "10")
1484 value_from
.rate
= D("0.01")
1485 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1486 value_to
= portfolio
.Amount("BTC", "1")
1487 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1489 trade
.prepare_order(compute_value
="foo")
1491 filled_amount
.assert_called_with(in_base_currency
=True)
1492 compute_value
.assert_called_with(get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1493 self
.assertEqual(1, len(trade
.orders
))
1494 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1495 D("125"), "FOO", "long", "market",
1496 trade
, close_if_possible
=False)
1498 with self
.subTest(action
="acquire", inverted
=True):
1499 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1500 compute_value
.return_value
= D("125")
1502 value_from
= portfolio
.Amount("BTC", "1")
1503 value_from
.rate
= D("0.01")
1504 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1505 value_to
= portfolio
.Amount("BTC", "10")
1506 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", market
="market")
1508 trade
.prepare_order(compute_value
="foo")
1510 filled_amount
.assert_called_with(in_base_currency
=False)
1511 compute_value
.assert_called_with(get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1512 self
.assertEqual(1, len(trade
.orders
))
1513 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1514 D("125"), "FOO", "long", "market",
1515 trade
, close_if_possible
=False)
1518 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1519 def test_update_order(self
, prepare_order
):
1520 order_mock
= mock
.Mock()
1521 new_order_mock
= mock
.Mock()
1523 value_from
= portfolio
.Amount("BTC", "0.5")
1524 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1525 value_to
= portfolio
.Amount("BTC", "1.0")
1526 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1527 prepare_order
.return_value
= new_order_mock
1529 for i
in [0, 1, 3, 4, 6]:
1530 with self
.subTest(tick
=i
), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1531 trade
.update_order(order_mock
, i
)
1532 order_mock
.cancel
.assert_not_called()
1533 new_order_mock
.run
.assert_not_called()
1534 self
.assertRegex(stdout_mock
.getvalue(), "tick {}, waiting".format(i
))
1536 order_mock
.reset_mock()
1537 new_order_mock
.reset_mock()
1540 with mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1541 trade
.update_order(order_mock
, 2)
1542 order_mock
.cancel
.assert_called()
1543 new_order_mock
.run
.assert_called()
1544 prepare_order
.assert_called()
1545 self
.assertRegex(stdout_mock
.getvalue(), "tick 2, cancelling and adjusting")
1547 order_mock
.reset_mock()
1548 new_order_mock
.reset_mock()
1551 with mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1552 trade
.update_order(order_mock
, 5)
1553 order_mock
.cancel
.assert_called()
1554 new_order_mock
.run
.assert_called()
1555 prepare_order
.assert_called()
1556 self
.assertRegex(stdout_mock
.getvalue(), "tick 5, cancelling and adjusting")
1558 order_mock
.reset_mock()
1559 new_order_mock
.reset_mock()
1562 with mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1563 trade
.update_order(order_mock
, 7)
1564 order_mock
.cancel
.assert_called()
1565 new_order_mock
.run
.assert_called()
1566 prepare_order
.assert_called_with(compute_value
="default")
1567 self
.assertRegex(stdout_mock
.getvalue(), "tick 7, fallbacking to market value")
1568 self
.assertRegex(stdout_mock
.getvalue(), "tick 7, market value, cancelling and adjusting to")
1570 order_mock
.reset_mock()
1571 new_order_mock
.reset_mock()
1574 for i
in [10, 13, 16]:
1575 with self
.subTest(tick
=i
), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1576 trade
.update_order(order_mock
, i
)
1577 order_mock
.cancel
.assert_called()
1578 new_order_mock
.run
.assert_called()
1579 prepare_order
.assert_called_with(compute_value
="default")
1580 self
.assertNotRegex(stdout_mock
.getvalue(), "tick {}, fallbacking to market value".format(i
))
1581 self
.assertRegex(stdout_mock
.getvalue(), "tick {}, market value, cancelling and adjusting to".format(i
))
1583 order_mock
.reset_mock()
1584 new_order_mock
.reset_mock()
1587 for i
in [8, 9, 11, 12]:
1588 with self
.subTest(tick
=i
), mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1589 trade
.update_order(order_mock
, i
)
1590 order_mock
.cancel
.assert_not_called()
1591 new_order_mock
.run
.assert_not_called()
1592 self
.assertEqual("", stdout_mock
.getvalue())
1594 order_mock
.reset_mock()
1595 new_order_mock
.reset_mock()
1599 @mock.patch('sys.stdout', new_callable
=StringIO
)
1600 def test_print_with_order(self
, mock_stdout
):
1601 value_from
= portfolio
.Amount("BTC", "0.5")
1602 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1603 value_to
= portfolio
.Amount("BTC", "1.0")
1604 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1606 order_mock1
= mock
.Mock()
1607 order_mock1
.__repr__
= mock
.Mock()
1608 order_mock1
.__repr__
.return_value
= "Mock 1"
1609 order_mock2
= mock
.Mock()
1610 order_mock2
.__repr__
= mock
.Mock()
1611 order_mock2
.__repr__
.return_value
= "Mock 2"
1612 trade
.orders
.append(order_mock1
)
1613 trade
.orders
.append(order_mock2
)
1615 trade
.print_with_order()
1617 out
= mock_stdout
.getvalue().split("\n")
1618 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", out
[0])
1619 self
.assertEqual("\tMock 1", out
[1])
1620 self
.assertEqual("\tMock 2", out
[2])
1622 def test__repr(self
):
1623 value_from
= portfolio
.Amount("BTC", "0.5")
1624 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1625 value_to
= portfolio
.Amount("BTC", "1.0")
1626 trade
= portfolio
.Trade(value_from
, value_to
, "ETH")
1628 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1630 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1631 class OrderTest(WebMockTestCase
):
1632 def test_values(self
):
1633 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1634 D("0.1"), "BTC", "long", "market", "trade")
1635 self
.assertEqual("buy", order
.action
)
1636 self
.assertEqual(10, order
.amount
.value
)
1637 self
.assertEqual("ETH", order
.amount
.currency
)
1638 self
.assertEqual(D("0.1"), order
.rate
)
1639 self
.assertEqual("BTC", order
.base_currency
)
1640 self
.assertEqual("market", order
.market
)
1641 self
.assertEqual("long", order
.trade_type
)
1642 self
.assertEqual("pending", order
.status
)
1643 self
.assertEqual("trade", order
.trade
)
1644 self
.assertIsNone(order
.id)
1645 self
.assertFalse(order
.close_if_possible
)
1647 def test__repr(self
):
1648 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1649 D("0.1"), "BTC", "long", "market", "trade")
1650 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1652 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1653 D("0.1"), "BTC", "long", "market", "trade",
1654 close_if_possible
=True)
1655 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1657 def test_account(self
):
1658 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1659 D("0.1"), "BTC", "long", "market", "trade")
1660 self
.assertEqual("exchange", order
.account
)
1662 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1663 D("0.1"), "BTC", "short", "market", "trade")
1664 self
.assertEqual("margin", order
.account
)
1666 def test_pending(self
):
1667 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1668 D("0.1"), "BTC", "long", "market", "trade")
1669 self
.assertTrue(order
.pending
)
1670 order
.status
= "open"
1671 self
.assertFalse(order
.pending
)
1673 def test_open(self
):
1674 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1675 D("0.1"), "BTC", "long", "market", "trade")
1676 self
.assertFalse(order
.open)
1677 order
.status
= "open"
1678 self
.assertTrue(order
.open)
1680 def test_finished(self
):
1681 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1682 D("0.1"), "BTC", "long", "market", "trade")
1683 self
.assertFalse(order
.finished
)
1684 order
.status
= "closed"
1685 self
.assertTrue(order
.finished
)
1686 order
.status
= "canceled"
1687 self
.assertTrue(order
.finished
)
1688 order
.status
= "error"
1689 self
.assertTrue(order
.finished
)
1691 @mock.patch.object(portfolio
.Order
, "fetch")
1692 def test_cancel(self
, fetch
):
1693 market
= mock
.Mock()
1694 portfolio
.TradeStore
.debug
= True
1695 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1696 D("0.1"), "BTC", "long", market
, "trade")
1697 order
.status
= "open"
1700 market
.cancel_order
.assert_not_called()
1701 self
.assertEqual("canceled", order
.status
)
1703 portfolio
.TradeStore
.debug
= False
1704 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1705 D("0.1"), "BTC", "long", market
, "trade")
1706 order
.status
= "open"
1710 market
.cancel_order
.assert_called_with(42)
1711 fetch
.assert_called_once()
1713 def test_dust_amount_remaining(self
):
1714 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1715 D("0.1"), "BTC", "long", "market", "trade")
1716 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1717 self
.assertFalse(order
.dust_amount_remaining())
1719 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1720 self
.assertTrue(order
.dust_amount_remaining())
1722 @mock.patch.object(portfolio
.Order
, "fetch")
1723 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1724 def test_remaining_amount(self
, filled_amount
, fetch
):
1725 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1726 D("0.1"), "BTC", "long", "market", "trade")
1728 self
.assertEqual(9, order
.remaining_amount().value
)
1729 order
.fetch
.assert_not_called()
1731 order
.status
= "open"
1732 self
.assertEqual(9, order
.remaining_amount().value
)
1733 fetch
.assert_called_once()
1735 @mock.patch.object(portfolio
.Order
, "fetch")
1736 def test_filled_amount(self
, fetch
):
1737 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1738 D("0.1"), "BTC", "long", "market", "trade")
1739 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1740 "tradeID": 42, "type": "buy", "fee": "0.0015",
1741 "date": "2017-12-30 12:00:12", "rate": "0.1",
1742 "amount": "3", "total": "0.3"
1744 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1745 "tradeID": 43, "type": "buy", "fee": "0.0015",
1746 "date": "2017-12-30 13:00:12", "rate": "0.2",
1747 "amount": "2", "total": "0.4"
1749 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1750 fetch
.assert_not_called()
1751 order
.status
= "open"
1752 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1753 fetch
.assert_called_once()
1754 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1756 def test_fetch_mouvements(self
):
1757 market
= mock
.Mock()
1758 market
.privatePostReturnOrderTrades
.return_value
= [
1760 "tradeID": 42, "type": "buy", "fee": "0.0015",
1761 "date": "2017-12-30 12:00:12", "rate": "0.1",
1762 "amount": "3", "total": "0.3"
1765 "tradeID": 43, "type": "buy", "fee": "0.0015",
1766 "date": "2017-12-30 13:00:12", "rate": "0.2",
1767 "amount": "2", "total": "0.4"
1770 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1771 D("0.1"), "BTC", "long", market
, "trade")
1773 order
.mouvements
= ["Foo", "Bar", "Baz"]
1775 order
.fetch_mouvements()
1777 market
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
1778 self
.assertEqual(2, len(order
.mouvements
))
1779 self
.assertEqual(42, order
.mouvements
[0].id)
1780 self
.assertEqual(43, order
.mouvements
[1].id)
1782 market
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
1783 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1784 D("0.1"), "BTC", "long", market
, "trade")
1785 order
.fetch_mouvements()
1786 self
.assertEqual(0, len(order
.mouvements
))
1788 def test_mark_finished_order(self
):
1789 market
= mock
.Mock()
1790 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1791 D("0.1"), "BTC", "short", market
, "trade",
1792 close_if_possible
=True)
1793 order
.status
= "closed"
1794 portfolio
.TradeStore
.debug
= False
1796 order
.mark_finished_order()
1797 market
.close_margin_position
.assert_called_with("ETH", "BTC")
1798 market
.close_margin_position
.reset_mock()
1800 order
.status
= "open"
1801 order
.mark_finished_order()
1802 market
.close_margin_position
.assert_not_called()
1804 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1805 D("0.1"), "BTC", "short", market
, "trade",
1806 close_if_possible
=False)
1807 order
.status
= "closed"
1808 order
.mark_finished_order()
1809 market
.close_margin_position
.assert_not_called()
1811 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1812 D("0.1"), "BTC", "short", market
, "trade",
1813 close_if_possible
=True)
1814 order
.status
= "closed"
1815 order
.mark_finished_order()
1816 market
.close_margin_position
.assert_not_called()
1818 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1819 D("0.1"), "BTC", "long", market
, "trade",
1820 close_if_possible
=True)
1821 order
.status
= "closed"
1822 order
.mark_finished_order()
1823 market
.close_margin_position
.assert_not_called()
1825 portfolio
.TradeStore
.debug
= True
1827 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1828 D("0.1"), "BTC", "short", market
, "trade",
1829 close_if_possible
=True)
1830 order
.status
= "closed"
1832 order
.mark_finished_order()
1833 market
.close_margin_position
.assert_not_called()
1835 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
1836 def test_fetch(self
, fetch_mouvements
):
1837 time
= self
.time
.time()
1838 with mock
.patch
.object(portfolio
.time
, "time") as time_mock
:
1839 market
= mock
.Mock()
1840 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1841 D("0.1"), "BTC", "long", market
, "trade")
1843 with self
.subTest(debug
=True):
1844 portfolio
.TradeStore
.debug
= True
1846 time_mock
.assert_not_called()
1847 order
.fetch(force
=True)
1848 time_mock
.assert_not_called()
1849 market
.fetch_order
.assert_not_called()
1850 fetch_mouvements
.assert_not_called()
1851 self
.assertIsNone(order
.fetch_cache_timestamp
)
1853 with self
.subTest(debug
=False):
1854 portfolio
.TradeStore
.debug
= False
1855 time_mock
.return_value
= time
1856 market
.fetch_order
.return_value
= {
1858 "datetime": "timestamp"
1862 market
.fetch_order
.assert_called_once()
1863 fetch_mouvements
.assert_called_once()
1864 self
.assertEqual("foo", order
.status
)
1865 self
.assertEqual("timestamp", order
.timestamp
)
1866 self
.assertEqual(time
, order
.fetch_cache_timestamp
)
1867 self
.assertEqual(1, len(order
.results
))
1869 market
.fetch_order
.reset_mock()
1870 fetch_mouvements
.reset_mock()
1872 time_mock
.return_value
= time
+ 8
1874 market
.fetch_order
.assert_not_called()
1875 fetch_mouvements
.assert_not_called()
1877 order
.fetch(force
=True)
1878 market
.fetch_order
.assert_called_once()
1879 fetch_mouvements
.assert_called_once()
1881 market
.fetch_order
.reset_mock()
1882 fetch_mouvements
.reset_mock()
1884 time_mock
.return_value
= time
+ 19
1886 market
.fetch_order
.assert_called_once()
1887 fetch_mouvements
.assert_called_once()
1889 @mock.patch.object(portfolio
.Order
, "fetch")
1890 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
1891 def test_get_status(self
, mark_finished_order
, fetch
):
1892 with self
.subTest(debug
=True):
1893 portfolio
.TradeStore
.debug
= True
1894 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1895 D("0.1"), "BTC", "long", "market", "trade")
1896 self
.assertEqual("pending", order
.get_status())
1897 fetch
.assert_not_called()
1899 with self
.subTest(debug
=False, finished
=False):
1900 portfolio
.TradeStore
.debug
= False
1901 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1902 D("0.1"), "BTC", "long", "market", "trade")
1904 def update_status():
1905 order
.status
= "open"
1906 return update_status
1907 fetch
.side_effect
= _fetch(order
)
1908 self
.assertEqual("open", order
.get_status())
1909 mark_finished_order
.assert_not_called()
1910 fetch
.assert_called_once()
1912 mark_finished_order
.reset_mock()
1914 with self
.subTest(debug
=False, finished
=True):
1915 portfolio
.TradeStore
.debug
= False
1916 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1917 D("0.1"), "BTC", "long", "market", "trade")
1919 def update_status():
1920 order
.status
= "closed"
1921 return update_status
1922 fetch
.side_effect
= _fetch(order
)
1923 self
.assertEqual("closed", order
.get_status())
1924 mark_finished_order
.assert_called_once()
1925 fetch
.assert_called_once()
1928 market
= mock
.Mock()
1930 market
.order_precision
.return_value
= 4
1931 with self
.subTest(debug
=True),\
1932 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1933 portfolio
.TradeStore
.debug
= True
1934 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1935 D("0.1"), "BTC", "long", market
, "trade")
1937 market
.create_order
.assert_not_called()
1938 self
.assertEqual("market.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)\n", stdout_mock
.getvalue())
1939 self
.assertEqual("open", order
.status
)
1940 self
.assertEqual(1, len(order
.results
))
1941 self
.assertEqual(-1, order
.id)
1943 market
.create_order
.reset_mock()
1944 with self
.subTest(debug
=False):
1945 portfolio
.TradeStore
.debug
= False
1946 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1947 D("0.1"), "BTC", "long", market
, "trade")
1948 market
.create_order
.return_value
= { "id": 123 }
1950 market
.create_order
.assert_called_once()
1951 self
.assertEqual(1, len(order
.results
))
1952 self
.assertEqual("open", order
.status
)
1954 market
.create_order
.reset_mock()
1955 with self
.subTest(exception
=True),\
1956 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1957 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1958 D("0.1"), "BTC", "long", market
, "trade")
1959 market
.create_order
.side_effect
= Exception("bouh")
1961 market
.create_order
.assert_called_once()
1962 self
.assertEqual(0, len(order
.results
))
1963 self
.assertEqual("error", order
.status
)
1964 self
.assertRegex(stdout_mock
.getvalue(), "error when running market.create_order")
1965 self
.assertRegex(stdout_mock
.getvalue(), "Exception: bouh")
1967 market
.create_order
.reset_mock()
1968 with self
.subTest(dust_amount_exception
=True),\
1969 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
1970 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
1971 D("0.1"), "BTC", "long", market
, "trade")
1972 market
.create_order
.side_effect
= portfolio
.ExchangeNotAvailable
1974 market
.create_order
.assert_called_once()
1975 self
.assertEqual(0, len(order
.results
))
1976 self
.assertEqual("closed", order
.status
)
1977 mark_finished_order
.assert_called_once()
1980 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1981 class MouvementTest(WebMockTestCase
):
1982 def test_values(self
):
1983 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
1984 "tradeID": 42, "type": "buy", "fee": "0.0015",
1985 "date": "2017-12-30 12:00:12", "rate": "0.1",
1986 "amount": "10", "total": "1"
1988 self
.assertEqual("ETH", mouvement
.currency
)
1989 self
.assertEqual("BTC", mouvement
.base_currency
)
1990 self
.assertEqual(42, mouvement
.id)
1991 self
.assertEqual("buy", mouvement
.action
)
1992 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
1993 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
1994 self
.assertEqual(D("0.1"), mouvement
.rate
)
1995 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
1996 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
1998 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
1999 self
.assertIsNone(mouvement
.date
)
2000 self
.assertIsNone(mouvement
.id)
2001 self
.assertIsNone(mouvement
.action
)
2002 self
.assertEqual(-1, mouvement
.fee_rate
)
2003 self
.assertEqual(0, mouvement
.rate
)
2004 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2005 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2007 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
2008 class AcceptanceTest(WebMockTestCase
):
2009 @unittest.expectedFailure
2010 def test_success_sell_only_necessary(self
):
2013 "exchange_free": D("1.0"),
2014 "exchange_used": D("0.0"),
2015 "exchange_total": D("1.0"),
2019 "exchange_free": D("4.0"),
2020 "exchange_used": D("0.0"),
2021 "exchange_total": D("4.0"),
2025 "exchange_free": D("1000.0"),
2026 "exchange_used": D("0.0"),
2027 "exchange_total": D("1000.0"),
2028 "total": D("1000.0"),
2032 "ETH": (D("0.25"), "long"),
2033 "ETC": (D("0.25"), "long"),
2034 "BTC": (D("0.4"), "long"),
2035 "BTD": (D("0.01"), "short"),
2036 "B2X": (D("0.04"), "long"),
2037 "USDT": (D("0.05"), "long"),
2040 def fetch_ticker(symbol
):
2041 if symbol
== "ETH/BTC":
2043 "symbol": "ETH/BTC",
2047 if symbol
== "ETC/BTC":
2049 "symbol": "ETC/BTC",
2053 if symbol
== "XVG/BTC":
2055 "symbol": "XVG/BTC",
2056 "bid": D("0.00003"),
2059 if symbol
== "BTD/BTC":
2061 "symbol": "BTD/BTC",
2065 if symbol
== "B2X/BTC":
2067 "symbol": "B2X/BTC",
2071 if symbol
== "USDT/BTC":
2072 raise helper
.ExchangeError
2073 if symbol
== "BTC/USDT":
2075 "symbol": "BTC/USDT",
2079 self
.fail("Shouldn't have been called with {}".format(symbol
))
2081 market
= mock
.Mock()
2082 market
.fetch_all_balances
.return_value
= fetch_balance
2083 market
.fetch_ticker
.side_effect
= fetch_ticker
2084 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
2086 helper
.prepare_trades(market
)
2088 balances
= portfolio
.BalanceStore
.all
2089 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
2090 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
2091 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
2094 trades
= portfolio
.TradeStore
.all
2095 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
2096 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
2097 self
.assertEqual("dispose", trades
[0].action
)
2099 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
2100 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
2101 self
.assertEqual("acquire", trades
[1].action
)
2103 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
2104 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
2105 self
.assertEqual("dispose", trades
[2].action
)
2107 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
2108 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
2109 self
.assertEqual("acquire", trades
[3].action
)
2111 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
2112 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
2113 self
.assertEqual("acquire", trades
[4].action
)
2115 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
2116 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
2117 self
.assertEqual("acquire", trades
[5].action
)
2120 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
2122 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
2123 self
.assertEqual(2, len(all_orders
))
2124 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
2125 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
2126 self
.assertEqual(1000, all_orders
[1].amount
.value
)
2127 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
2130 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
2131 self
.assertEqual("limit", type)
2132 if symbol
== "ETH/BTC":
2133 self
.assertEqual("sell", action
)
2134 self
.assertEqual(D('0.66666666'), amount
)
2135 self
.assertEqual(D("0.14014"), price
)
2136 elif symbol
== "XVG/BTC":
2137 self
.assertEqual("sell", action
)
2138 self
.assertEqual(1000, amount
)
2139 self
.assertEqual(D("0.00003003"), price
)
2141 self
.fail("I shouldn't have been called")
2146 market
.create_order
.side_effect
= create_order
2147 market
.order_precision
.return_value
= 8
2150 portfolio
.TradeStore
.run_orders()
2152 self
.assertEqual("open", all_orders
[0].status
)
2153 self
.assertEqual("open", all_orders
[1].status
)
2155 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
2156 market
.privatePostReturnOrderTrades
.return_value
= [
2158 "tradeID": 42, "type": "buy", "fee": "0.0015",
2159 "date": "2017-12-30 12:00:12", "rate": "0.1",
2160 "amount": "10", "total": "1"
2163 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
2165 helper
.follow_orders(verbose
=False)
2167 sleep
.assert_called_with(30)
2169 for order
in all_orders
:
2170 self
.assertEqual("closed", order
.status
)
2174 "exchange_free": D("1.0") / 3,
2175 "exchange_used": D("0.0"),
2176 "exchange_total": D("1.0") / 3,
2178 "total": D("1.0") / 3,
2181 "exchange_free": D("0.134"),
2182 "exchange_used": D("0.0"),
2183 "exchange_total": D("0.134"),
2185 "total": D("0.134"),
2188 "exchange_free": D("4.0"),
2189 "exchange_used": D("0.0"),
2190 "exchange_total": D("4.0"),
2195 "exchange_free": D("0.0"),
2196 "exchange_used": D("0.0"),
2197 "exchange_total": D("0.0"),
2202 market
.fetch_all_balances
.return_value
= fetch_balance
2204 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
2206 helper
.update_trades(market
, only
="acquire", compute_value
="average")
2208 balances
= portfolio
.BalanceStore
.all
2209 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
2210 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
2211 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
2212 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
2215 trades
= portfolio
.TradeStore
.all
2216 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
2217 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
2218 self
.assertEqual("dispose", trades
[0].action
)
2220 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
2221 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
2222 self
.assertEqual("acquire", trades
[1].action
)
2224 self
.assertNotIn("BTC", trades
)
2226 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
2227 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
2228 self
.assertEqual("dispose", trades
[2].action
)
2230 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
2231 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
2232 self
.assertEqual("acquire", trades
[3].action
)
2234 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
2235 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
2236 self
.assertEqual("acquire", trades
[4].action
)
2238 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
2239 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
2240 self
.assertEqual("acquire", trades
[5].action
)
2243 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
2245 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
2246 self
.assertEqual(4, len(all_orders
))
2247 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
2248 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
2249 self
.assertEqual("buy", all_orders
[0].action
)
2250 self
.assertEqual("long", all_orders
[0].trade_type
)
2252 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
2253 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
2254 self
.assertEqual("sell", all_orders
[1].action
)
2255 self
.assertEqual("short", all_orders
[1].trade_type
)
2257 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
2258 self
.assertAlmostEqual(0, diff
.value
)
2259 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
2260 self
.assertEqual("buy", all_orders
[2].action
)
2261 self
.assertEqual("long", all_orders
[2].trade_type
)
2263 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
2264 self
.assertEqual(D("16000"), all_orders
[3].rate
)
2265 self
.assertEqual("sell", all_orders
[3].action
)
2266 self
.assertEqual("long", all_orders
[3].trade_type
)
2270 # Move balances to margin
2274 # portfolio.TradeStore.run_orders()
2276 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
2278 helper
.follow_orders(verbose
=False)
2280 sleep
.assert_called_with(30)
2282 if __name__
== '__main__':