5 from decimal
import Decimal
as D
6 from unittest
import mock
9 from io
import StringIO
10 import portfolio
, helper
, market
12 limits
= ["acceptance", "unit"]
13 for test_type
in limits
:
14 if "--no{}".format(test_type
) in sys
.argv
:
15 sys
.argv
.remove("--no{}".format(test_type
))
16 limits
.remove(test_type
)
17 if "--only{}".format(test_type
) in sys
.argv
:
18 sys
.argv
.remove("--only{}".format(test_type
))
22 class WebMockTestCase(unittest
.TestCase
):
26 super(WebMockTestCase
, self
).setUp()
27 self
.wm
= requests_mock
.Mocker()
31 self
.m
= mock
.Mock(name
="Market", spec
=market
.Market
)
35 mock
.patch
.multiple(portfolio
.Portfolio
, last_date
=None, data
=None, liquidities
={}),
36 mock
.patch
.multiple(portfolio
.Computation
,
37 computations
=portfolio
.Computation
.computations
),
39 for patcher
in self
.patchers
:
43 for patcher
in self
.patchers
:
46 super(WebMockTestCase
, self
).tearDown()
48 @unittest.skipUnless("unit" in limits
, "Unit skipped")
49 class poloniexETest(unittest
.TestCase
):
51 super(poloniexETest
, self
).setUp()
52 self
.wm
= requests_mock
.Mocker()
55 self
.s
= market
.ccxt
.poloniexE()
59 super(poloniexETest
, self
).tearDown()
61 def test_nanoseconds(self
):
62 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
63 time
.return_value
= 123456.7890123456
64 self
.assertEqual(123456789012345, self
.s
.nanoseconds())
67 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
68 time
.return_value
= 123456.7890123456
69 self
.assertEqual(123456789012345, self
.s
.nonce())
71 def test_order_precision(self
):
72 self
.assertEqual(8, self
.s
.order_precision("FOO"))
74 def test_transfer_balance(self
):
75 with self
.subTest(success
=True),\
76 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
77 t
.return_value
= { "success": 1 }
78 result
= self
.s
.transfer_balance("FOO", 12, "exchange", "margin")
79 t
.assert_called_once_with({
82 "fromAccount": "exchange",
83 "toAccount": "margin",
86 self
.assertTrue(result
)
88 with self
.subTest(success
=False),\
89 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
90 t
.return_value
= { "success": 0 }
91 self
.assertFalse(self
.s
.transfer_balance("FOO", 12, "exchange", "margin"))
93 def test_close_margin_position(self
):
94 with mock
.patch
.object(self
.s
, "privatePostCloseMarginPosition") as c
:
95 self
.s
.close_margin_position("FOO", "BAR")
96 c
.assert_called_with({"currencyPair": "BAR_FOO"}
)
98 def test_tradable_balances(self
):
99 with mock
.patch
.object(self
.s
, "privatePostReturnTradableBalances") as r
:
101 "FOO": { "exchange": "12.1234", "margin": "0.0123" }
,
102 "BAR": { "exchange": "1", "margin": "0" }
,
104 balances
= self
.s
.tradable_balances()
105 self
.assertEqual(["FOO", "BAR"], list(balances
.keys()))
106 self
.assertEqual(["exchange", "margin"], list(balances
["FOO"].keys()))
107 self
.assertEqual(D("12.1234"), balances
["FOO"]["exchange"])
108 self
.assertEqual(["exchange", "margin"], list(balances
["BAR"].keys()))
110 def test_margin_summary(self
):
111 with mock
.patch
.object(self
.s
, "privatePostReturnMarginAccountSummary") as r
:
113 "currentMargin": "1.49680968",
114 "lendingFees": "0.0000001",
116 "totalBorrowedValue": "0.00673602",
117 "totalValue": "0.01000000",
118 "netValue": "0.01008254",
121 'current_margin': D('1.49680968'),
122 'gains': D('0.00008254'),
123 'lending_fees': D('0.0000001'),
124 'total': D('0.01000000'),
125 'total_borrowed': D('0.00673602')
127 self
.assertEqual(expected
, self
.s
.margin_summary())
129 @unittest.skipUnless("unit" in limits
, "Unit skipped")
130 class PortfolioTest(WebMockTestCase
):
132 if self
.json_response
is not None:
133 portfolio
.Portfolio
.data
= self
.json_response
136 super(PortfolioTest
, self
).setUp()
138 with open("test_portfolio.json") as example
:
139 self
.json_response
= example
.read()
141 self
.wm
.get(portfolio
.Portfolio
.URL
, text
=self
.json_response
)
143 def test_get_cryptoportfolio(self
):
144 self
.wm
.get(portfolio
.Portfolio
.URL
, [
145 {"text":'{ "foo": "bar" }
', "status_code": 200},
146 {"text": "System Error", "status_code": 500},
147 {"exc": requests.exceptions.ConnectTimeout},
149 portfolio.Portfolio.get_cryptoportfolio(self.m)
150 self.assertIn("foo", portfolio.Portfolio.data)
151 self.assertEqual("bar", portfolio.Portfolio.data["foo"])
152 self.assertTrue(self.wm.called)
153 self.assertEqual(1, self.wm.call_count)
154 self.m.report.log_error.assert_not_called()
155 self.m.report.log_http_request.assert_called_once()
156 self.m.report.log_http_request.reset_mock()
158 portfolio.Portfolio.get_cryptoportfolio(self.m)
159 self.assertIsNone(portfolio.Portfolio.data)
160 self.assertEqual(2, self.wm.call_count)
161 self.m.report.log_error.assert_not_called()
162 self.m.report.log_http_request.assert_called_once()
163 self.m.report.log_http_request.reset_mock()
166 portfolio.Portfolio.data = "Foo"
167 portfolio.Portfolio.get_cryptoportfolio(self.m)
168 self.assertEqual("Foo", portfolio.Portfolio.data)
169 self.assertEqual(3, self.wm.call_count)
170 self.m.report.log_error.assert_called_once_with("get_cryptoportfolio",
172 self.m.report.log_http_request.assert_not_called()
174 def test_parse_cryptoportfolio(self):
175 portfolio.Portfolio.parse_cryptoportfolio(self.m)
177 self.assertListEqual(
179 list(portfolio.Portfolio.liquidities.keys()))
181 liquidities = portfolio.Portfolio.liquidities
182 self.assertEqual(10, len(liquidities["medium"].keys()))
183 self.assertEqual(10, len(liquidities["high"].keys()))
186 'BTC
': (D("0.2857"), "long"),
187 'DGB
': (D("0.1015"), "long"),
188 'DOGE
': (D("0.1805"), "long"),
189 'SC
': (D("0.0623"), "long"),
190 'ZEC
': (D("0.3701"), "long"),
192 date = portfolio.datetime(2018, 1, 8)
193 self.assertDictEqual(expected, liquidities["high"][date])
196 'BTC
': (D("1.1102e-16"), "long"),
197 'ETC
': (D("0.1"), "long"),
198 'FCT
': (D("0.1"), "long"),
199 'GAS
': (D("0.1"), "long"),
200 'NAV
': (D("0.1"), "long"),
201 'OMG
': (D("0.1"), "long"),
202 'OMNI
': (D("0.1"), "long"),
203 'PPC
': (D("0.1"), "long"),
204 'RIC
': (D("0.1"), "long"),
205 'VIA
': (D("0.1"), "long"),
206 'XCP
': (D("0.1"), "long"),
208 self.assertDictEqual(expected, liquidities["medium"][date])
209 self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date)
211 self.m.report.log_http_request.assert_called_once_with("GET",
212 portfolio.Portfolio.URL, None, mock.ANY, mock.ANY)
213 self.m.report.log_http_request.reset_mock()
215 # It doesn't refetch the data when available
216 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
)
217 self
.m
.report
.log_http_request
.assert_not_called()
219 self
.assertEqual(1, self
.wm
.call_count
)
221 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
, refetch
=True)
222 self
.assertEqual(2, self
.wm
.call_count
)
223 self
.m
.report
.log_http_request
.assert_called_once()
225 def test_repartition(self
):
227 'BTC': (D("1.1102e-16"), "long"),
228 'USDT': (D("0.1"), "long"),
229 'ETC': (D("0.1"), "long"),
230 'FCT': (D("0.1"), "long"),
231 'OMG': (D("0.1"), "long"),
232 'STEEM': (D("0.1"), "long"),
233 'STRAT': (D("0.1"), "long"),
234 'XEM': (D("0.1"), "long"),
235 'XMR': (D("0.1"), "long"),
236 'XVC': (D("0.1"), "long"),
237 'ZRX': (D("0.1"), "long"),
240 'USDT': (D("0.1226"), "long"),
241 'BTC': (D("0.1429"), "long"),
242 'ETC': (D("0.1127"), "long"),
243 'ETH': (D("0.1569"), "long"),
244 'FCT': (D("0.3341"), "long"),
245 'GAS': (D("0.1308"), "long"),
248 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
))
249 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="medium"))
250 self
.assertEqual(expected_high
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="high"))
252 self
.assertEqual(1, self
.wm
.call_count
)
254 portfolio
.Portfolio
.repartition(self
.m
)
255 self
.assertEqual(1, self
.wm
.call_count
)
257 portfolio
.Portfolio
.repartition(self
.m
, refetch
=True)
258 self
.assertEqual(2, self
.wm
.call_count
)
259 self
.m
.report
.log_http_request
.assert_called()
260 self
.assertEqual(2, self
.m
.report
.log_http_request
.call_count
)
262 @mock.patch.object(portfolio
.time
, "sleep")
263 @mock.patch.object(portfolio
.Portfolio
, "repartition")
264 def test_wait_for_recent(self
, repartition
, sleep
):
266 def _repartition(market
, refetch
):
267 self
.assertEqual(self
.m
, market
)
268 self
.assertTrue(refetch
)
270 portfolio
.Portfolio
.last_date
= portfolio
.datetime
.now()\
271 - portfolio
.timedelta(10)\
272 + portfolio
.timedelta(self
.call_count
)
273 repartition
.side_effect
= _repartition
275 portfolio
.Portfolio
.wait_for_recent(self
.m
)
276 sleep
.assert_called_with(30)
277 self
.assertEqual(6, sleep
.call_count
)
278 self
.assertEqual(7, repartition
.call_count
)
279 self
.m
.report
.print_log
.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
282 repartition
.reset_mock()
283 portfolio
.Portfolio
.last_date
= None
285 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=15)
286 sleep
.assert_not_called()
287 self
.assertEqual(1, repartition
.call_count
)
290 repartition
.reset_mock()
291 portfolio
.Portfolio
.last_date
= None
293 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=1)
294 sleep
.assert_called_with(30)
295 self
.assertEqual(9, sleep
.call_count
)
296 self
.assertEqual(10, repartition
.call_count
)
298 @unittest.skipUnless("unit" in limits
, "Unit skipped")
299 class AmountTest(WebMockTestCase
):
300 def test_values(self
):
301 amount
= portfolio
.Amount("BTC", "0.65")
302 self
.assertEqual(D("0.65"), amount
.value
)
303 self
.assertEqual("BTC", amount
.currency
)
305 def test_in_currency(self
):
306 amount
= portfolio
.Amount("ETC", 10)
308 self
.assertEqual(amount
, amount
.in_currency("ETC", self
.m
))
310 with self
.subTest(desc
="no ticker for currency"):
311 self
.m
.get_ticker
.return_value
= None
313 self
.assertRaises(Exception, amount
.in_currency
, "ETH", self
.m
)
315 with self
.subTest(desc
="nominal case"):
316 self
.m
.get_ticker
.return_value
= {
322 converted_amount
= amount
.in_currency("ETH", self
.m
)
324 self
.assertEqual(D("3.0"), converted_amount
.value
)
325 self
.assertEqual("ETH", converted_amount
.currency
)
326 self
.assertEqual(amount
, converted_amount
.linked_to
)
327 self
.assertEqual("bar", converted_amount
.ticker
["foo"])
329 converted_amount
= amount
.in_currency("ETH", self
.m
, action
="bid", compute_value
="default")
330 self
.assertEqual(D("2"), converted_amount
.value
)
332 converted_amount
= amount
.in_currency("ETH", self
.m
, compute_value
="ask")
333 self
.assertEqual(D("4"), converted_amount
.value
)
335 converted_amount
= amount
.in_currency("ETH", self
.m
, rate
=D("0.02"))
336 self
.assertEqual(D("0.2"), converted_amount
.value
)
338 def test__round(self
):
339 amount
= portfolio
.Amount("BAR", portfolio
.D("1.23456789876"))
340 self
.assertEqual(D("1.23456789"), round(amount
).value
)
341 self
.assertEqual(D("1.23"), round(amount
, 2).value
)
344 amount
= portfolio
.Amount("SC", -120)
345 self
.assertEqual(120, abs(amount
).value
)
346 self
.assertEqual("SC", abs(amount
).currency
)
348 amount
= portfolio
.Amount("SC", 10)
349 self
.assertEqual(10, abs(amount
).value
)
350 self
.assertEqual("SC", abs(amount
).currency
)
353 amount1
= portfolio
.Amount("XVG", "12.9")
354 amount2
= portfolio
.Amount("XVG", "13.1")
356 self
.assertEqual(26, (amount1
+ amount2
).value
)
357 self
.assertEqual("XVG", (amount1
+ amount2
).currency
)
359 amount3
= portfolio
.Amount("ETH", "1.6")
360 with self
.assertRaises(Exception):
363 amount4
= portfolio
.Amount("ETH", 0.0)
364 self
.assertEqual(amount1
, amount1
+ amount4
)
366 self
.assertEqual(amount1
, amount1
+ 0)
368 def test__radd(self
):
369 amount
= portfolio
.Amount("XVG", "12.9")
371 self
.assertEqual(amount
, 0 + amount
)
372 with self
.assertRaises(Exception):
376 amount1
= portfolio
.Amount("XVG", "13.3")
377 amount2
= portfolio
.Amount("XVG", "13.1")
379 self
.assertEqual(D("0.2"), (amount1
- amount2
).value
)
380 self
.assertEqual("XVG", (amount1
- amount2
).currency
)
382 amount3
= portfolio
.Amount("ETH", "1.6")
383 with self
.assertRaises(Exception):
386 amount4
= portfolio
.Amount("ETH", 0.0)
387 self
.assertEqual(amount1
, amount1
- amount4
)
389 def test__rsub(self
):
390 amount
= portfolio
.Amount("ETH", "1.6")
391 with self
.assertRaises(Exception):
394 self
.assertEqual(portfolio
.Amount("ETH", "-1.6"), 0-amount
)
397 amount
= portfolio
.Amount("XEM", 11)
399 self
.assertEqual(D("38.5"), (amount
* D("3.5")).value
)
400 self
.assertEqual(D("33"), (amount
* 3).value
)
402 with self
.assertRaises(Exception):
405 def test__rmul(self
):
406 amount
= portfolio
.Amount("XEM", 11)
408 self
.assertEqual(D("38.5"), (D("3.5") * amount
).value
)
409 self
.assertEqual(D("33"), (3 * amount
).value
)
411 def test__floordiv(self
):
412 amount
= portfolio
.Amount("XEM", 11)
414 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
415 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
417 with self
.assertRaises(Exception):
420 def test__truediv(self
):
421 amount
= portfolio
.Amount("XEM", 11)
423 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
424 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
427 amount1
= portfolio
.Amount("BTD", 11.3)
428 amount2
= portfolio
.Amount("BTD", 13.1)
430 self
.assertTrue(amount1
< amount2
)
431 self
.assertFalse(amount2
< amount1
)
432 self
.assertFalse(amount1
< amount1
)
434 amount3
= portfolio
.Amount("BTC", 1.6)
435 with self
.assertRaises(Exception):
439 amount1
= portfolio
.Amount("BTD", 11.3)
440 amount2
= portfolio
.Amount("BTD", 13.1)
442 self
.assertTrue(amount1
<= amount2
)
443 self
.assertFalse(amount2
<= amount1
)
444 self
.assertTrue(amount1
<= amount1
)
446 amount3
= portfolio
.Amount("BTC", 1.6)
447 with self
.assertRaises(Exception):
451 amount1
= portfolio
.Amount("BTD", 11.3)
452 amount2
= portfolio
.Amount("BTD", 13.1)
454 self
.assertTrue(amount2
> amount1
)
455 self
.assertFalse(amount1
> amount2
)
456 self
.assertFalse(amount1
> amount1
)
458 amount3
= portfolio
.Amount("BTC", 1.6)
459 with self
.assertRaises(Exception):
463 amount1
= portfolio
.Amount("BTD", 11.3)
464 amount2
= portfolio
.Amount("BTD", 13.1)
466 self
.assertTrue(amount2
>= amount1
)
467 self
.assertFalse(amount1
>= amount2
)
468 self
.assertTrue(amount1
>= amount1
)
470 amount3
= portfolio
.Amount("BTC", 1.6)
471 with self
.assertRaises(Exception):
475 amount1
= portfolio
.Amount("BTD", 11.3)
476 amount2
= portfolio
.Amount("BTD", 13.1)
477 amount3
= portfolio
.Amount("BTD", 11.3)
479 self
.assertFalse(amount1
== amount2
)
480 self
.assertFalse(amount2
== amount1
)
481 self
.assertTrue(amount1
== amount3
)
482 self
.assertFalse(amount2
== 0)
484 amount4
= portfolio
.Amount("BTC", 1.6)
485 with self
.assertRaises(Exception):
488 amount5
= portfolio
.Amount("BTD", 0)
489 self
.assertTrue(amount5
== 0)
492 amount1
= portfolio
.Amount("BTD", 11.3)
493 amount2
= portfolio
.Amount("BTD", 13.1)
494 amount3
= portfolio
.Amount("BTD", 11.3)
496 self
.assertTrue(amount1
!= amount2
)
497 self
.assertTrue(amount2
!= amount1
)
498 self
.assertFalse(amount1
!= amount3
)
499 self
.assertTrue(amount2
!= 0)
501 amount4
= portfolio
.Amount("BTC", 1.6)
502 with self
.assertRaises(Exception):
505 amount5
= portfolio
.Amount("BTD", 0)
506 self
.assertFalse(amount5
!= 0)
509 amount1
= portfolio
.Amount("BTD", "11.3")
511 self
.assertEqual(portfolio
.D("-11.3"), (-amount1
).value
)
514 amount1
= portfolio
.Amount("BTX", 32)
515 self
.assertEqual("32.00000000 BTX", str(amount1
))
517 amount2
= portfolio
.Amount("USDT", 12000)
518 amount1
.linked_to
= amount2
519 self
.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1
))
521 def test__repr(self
):
522 amount1
= portfolio
.Amount("BTX", 32)
523 self
.assertEqual("Amount(32.00000000 BTX)", repr(amount1
))
525 amount2
= portfolio
.Amount("USDT", 12000)
526 amount1
.linked_to
= amount2
527 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1
))
529 amount3
= portfolio
.Amount("BTC", 0.1)
530 amount2
.linked_to
= amount3
531 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1
))
533 def test_as_json(self
):
534 amount
= portfolio
.Amount("BTX", 32)
535 self
.assertEqual({"currency": "BTX", "value": D("32")}
, amount
.as_json())
537 amount
= portfolio
.Amount("BTX", "1E-10")
538 self
.assertEqual({"currency": "BTX", "value": D("0")}
, amount
.as_json())
540 amount
= portfolio
.Amount("BTX", "1E-5")
541 self
.assertEqual({"currency": "BTX", "value": D("0.00001")}
, amount
.as_json())
542 self
.assertEqual("0.00001", str(amount
.as_json()["value"]))
544 @unittest.skipUnless("unit" in limits
, "Unit skipped")
545 class BalanceTest(WebMockTestCase
):
546 def test_values(self
):
547 balance
= portfolio
.Balance("BTC", {
548 "exchange_total": "0.65",
549 "exchange_free": "0.35",
550 "exchange_used": "0.30",
551 "margin_total": "-10",
552 "margin_borrowed": "10",
553 "margin_available": "0",
554 "margin_in_position": "0",
555 "margin_position_type": "short",
556 "margin_borrowed_base_currency": "USDT",
557 "margin_liquidation_price": "1.20",
558 "margin_pending_gain": "10",
559 "margin_lending_fees": "0.4",
560 "margin_borrowed_base_price": "0.15",
562 self
.assertEqual(portfolio
.D("0.65"), balance
.exchange_total
.value
)
563 self
.assertEqual(portfolio
.D("0.35"), balance
.exchange_free
.value
)
564 self
.assertEqual(portfolio
.D("0.30"), balance
.exchange_used
.value
)
565 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
566 self
.assertEqual("BTC", balance
.exchange_free
.currency
)
567 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
569 self
.assertEqual(portfolio
.D("-10"), balance
.margin_total
.value
)
570 self
.assertEqual(portfolio
.D("10"), balance
.margin_borrowed
.value
)
571 self
.assertEqual(portfolio
.D("0"), balance
.margin_available
.value
)
572 self
.assertEqual("BTC", balance
.margin_total
.currency
)
573 self
.assertEqual("BTC", balance
.margin_borrowed
.currency
)
574 self
.assertEqual("BTC", balance
.margin_available
.currency
)
576 self
.assertEqual("BTC", balance
.currency
)
578 self
.assertEqual(portfolio
.D("0.4"), balance
.margin_lending_fees
.value
)
579 self
.assertEqual("USDT", balance
.margin_lending_fees
.currency
)
581 def test__repr(self
):
582 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
583 repr(portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)))
584 balance
= portfolio
.Balance("BTX", { "exchange_total": 3,
585 "exchange_used": 1, "exchange_free": 2 })
586 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
588 balance
= portfolio
.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}
)
589 self
.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance
))
591 balance
= portfolio
.Balance("BTX", { "margin_total": 3,
592 "margin_in_position": 1, "margin_available": 2 })
593 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
595 balance
= portfolio
.Balance("BTX", { "margin_total": 2, "margin_available": 2 }
)
596 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance
))
598 balance
= portfolio
.Balance("BTX", { "margin_total": -3,
599 "margin_borrowed_base_price": D("0.1"),
600 "margin_borrowed_base_currency": "BTC",
601 "margin_lending_fees": D("0.002") })
602 self
.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance
))
604 balance
= portfolio
.Balance("BTX", { "margin_total": 1,
605 "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2})
606 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance
))
608 def test_as_json(self
):
609 balance
= portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)
610 as_json
= balance
.as_json()
611 self
.assertEqual(set(portfolio
.Balance
.base_keys
), set(as_json
.keys()))
612 self
.assertEqual(D(0), as_json
["total"])
613 self
.assertEqual(D(2), as_json
["exchange_total"])
614 self
.assertEqual(D(2), as_json
["exchange_free"])
615 self
.assertEqual(D(0), as_json
["exchange_used"])
616 self
.assertEqual(D(0), as_json
["margin_total"])
617 self
.assertEqual(D(0), as_json
["margin_available"])
618 self
.assertEqual(D(0), as_json
["margin_borrowed"])
620 @unittest.skipUnless("unit" in limits
, "Unit skipped")
621 class MarketTest(WebMockTestCase
):
623 super(MarketTest
, self
).setUp()
625 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
627 def test_values(self
):
628 m
= market
.Market(self
.ccxt
)
630 self
.assertEqual(self
.ccxt
, m
.ccxt
)
631 self
.assertFalse(m
.debug
)
632 self
.assertIsInstance(m
.report
, market
.ReportStore
)
633 self
.assertIsInstance(m
.trades
, market
.TradeStore
)
634 self
.assertIsInstance(m
.balances
, market
.BalanceStore
)
635 self
.assertEqual(m
, m
.report
.market
)
636 self
.assertEqual(m
, m
.trades
.market
)
637 self
.assertEqual(m
, m
.balances
.market
)
638 self
.assertEqual(m
, m
.ccxt
._market
)
640 m
= market
.Market(self
.ccxt
, debug
=True)
641 self
.assertTrue(m
.debug
)
643 m
= market
.Market(self
.ccxt
, debug
=False)
644 self
.assertFalse(m
.debug
)
646 @mock.patch("market.ccxt")
647 def test_from_config(self
, ccxt
):
648 with mock
.patch("market.ReportStore"):
649 ccxt
.poloniexE
.return_value
= self
.ccxt
650 self
.ccxt
.session
.request
.return_value
= "response"
652 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
)
654 self
.assertEqual(self
.ccxt
, m
.ccxt
)
656 self
.ccxt
.session
.request("GET", "URL", data
="data",
658 m
.report
.log_http_request
.assert_called_with('GET', 'URL', 'data',
659 'headers', 'response')
661 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, debug
=True)
662 self
.assertEqual(True, m
.debug
)
664 def test_get_tickers(self
):
665 self
.ccxt
.fetch_tickers
.side_effect
= [
670 m
= market
.Market(self
.ccxt
)
671 self
.assertEqual("tickers", m
.get_tickers())
672 self
.assertEqual("tickers", m
.get_tickers())
673 self
.ccxt
.fetch_tickers
.assert_called_once()
675 self
.assertIsNone(m
.get_tickers(refresh
=self
.time
.time()))
677 def test_get_ticker(self
):
678 with self
.subTest(get_tickers
=True):
679 self
.ccxt
.fetch_tickers
.return_value
= {
680 "ETH/ETC": { "bid": 1, "ask": 3 }
,
681 "XVG/ETH": { "bid": 10, "ask": 40 }
,
683 m
= market
.Market(self
.ccxt
)
685 ticker
= m
.get_ticker("ETH", "ETC")
686 self
.assertEqual(1, ticker
["bid"])
687 self
.assertEqual(3, ticker
["ask"])
688 self
.assertEqual(2, ticker
["average"])
689 self
.assertFalse(ticker
["inverted"])
691 ticker
= m
.get_ticker("ETH", "XVG")
692 self
.assertEqual(0.0625, ticker
["average"])
693 self
.assertTrue(ticker
["inverted"])
694 self
.assertIn("original", ticker
)
695 self
.assertEqual(10, ticker
["original"]["bid"])
696 self
.assertEqual(25, ticker
["original"]["average"])
698 ticker
= m
.get_ticker("XVG", "XMR")
699 self
.assertIsNone(ticker
)
701 with self
.subTest(get_tickers
=False):
702 self
.ccxt
.fetch_tickers
.return_value
= None
703 self
.ccxt
.fetch_ticker
.side_effect
= [
704 { "bid": 1, "ask": 3 }
,
705 market
.ExchangeError("foo"),
706 { "bid": 10, "ask": 40 }
,
707 market
.ExchangeError("foo"),
708 market
.ExchangeError("foo"),
711 m
= market
.Market(self
.ccxt
)
713 ticker
= m
.get_ticker("ETH", "ETC")
714 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
715 self
.assertEqual(1, ticker
["bid"])
716 self
.assertEqual(3, ticker
["ask"])
717 self
.assertEqual(2, ticker
["average"])
718 self
.assertFalse(ticker
["inverted"])
720 ticker
= m
.get_ticker("ETH", "XVG")
721 self
.assertEqual(0.0625, ticker
["average"])
722 self
.assertTrue(ticker
["inverted"])
723 self
.assertIn("original", ticker
)
724 self
.assertEqual(10, ticker
["original"]["bid"])
725 self
.assertEqual(25, ticker
["original"]["average"])
727 ticker
= m
.get_ticker("XVG", "XMR")
728 self
.assertIsNone(ticker
)
730 def test_fetch_fees(self
):
731 m
= market
.Market(self
.ccxt
)
732 self
.ccxt
.fetch_fees
.return_value
= "Foo"
733 self
.assertEqual("Foo", m
.fetch_fees())
734 self
.ccxt
.fetch_fees
.assert_called_once()
735 self
.ccxt
.reset_mock()
736 self
.assertEqual("Foo", m
.fetch_fees())
737 self
.ccxt
.fetch_fees
.assert_not_called()
739 @mock.patch.object(portfolio
.Portfolio
, "repartition")
740 @mock.patch.object(market
.Market
, "get_ticker")
741 @mock.patch.object(market
.TradeStore
, "compute_trades")
742 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
743 repartition
.return_value
= {
744 "XEM": (D("0.75"), "long"),
745 "BTC": (D("0.25"), "long"),
747 def _get_ticker(c1
, c2
):
748 if c1
== "USDT" and c2
== "BTC":
749 return { "average": D("0.0001") }
750 if c1
== "XVG" and c2
== "BTC":
751 return { "average": D("0.000001") }
752 if c1
== "XEM" and c2
== "BTC":
753 return { "average": D("0.001") }
754 self
.fail("Should be called with {}, {}".format(c1
, c2
))
755 get_ticker
.side_effect
= _get_ticker
757 with mock
.patch("market.ReportStore"):
758 m
= market
.Market(self
.ccxt
)
759 self
.ccxt
.fetch_all_balances
.return_value
= {
761 "exchange_free": D("10000.0"),
762 "exchange_used": D("0.0"),
763 "exchange_total": D("10000.0"),
764 "total": D("10000.0")
767 "exchange_free": D("10000.0"),
768 "exchange_used": D("0.0"),
769 "exchange_total": D("10000.0"),
770 "total": D("10000.0")
774 m
.balances
.fetch_balances(tag
="tag")
777 compute_trades
.assert_called()
779 call
= compute_trades
.call_args
780 self
.assertEqual(1, call
[0][0]["USDT"].value
)
781 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
782 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
783 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
784 m
.report
.log_stage
.assert_called_once_with("prepare_trades",
785 base_currency
='BTC', compute_value
='average',
786 liquidity
='medium', only
=None, repartition
=None)
787 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
790 @mock.patch.object(portfolio
.time
, "sleep")
791 @mock.patch.object(market
.TradeStore
, "all_orders")
792 def test_follow_orders(self
, all_orders
, time_mock
):
793 for debug
, sleep
in [
794 (False, None), (True, None),
795 (False, 12), (True, 12)]:
796 with self
.subTest(sleep
=sleep
, debug
=debug
), \
797 mock
.patch("market.ReportStore"):
798 m
= market
.Market(self
.ccxt
, debug
=debug
)
800 order_mock1
= mock
.Mock()
801 order_mock2
= mock
.Mock()
802 order_mock3
= mock
.Mock()
803 all_orders
.side_effect
= [
804 [order_mock1
, order_mock2
],
805 [order_mock1
, order_mock2
],
807 [order_mock1
, order_mock3
],
808 [order_mock1
, order_mock3
],
810 [order_mock1
, order_mock3
],
811 [order_mock1
, order_mock3
],
816 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
817 order_mock2
.get_status
.side_effect
= ["open"]
818 order_mock3
.get_status
.side_effect
= ["open", "closed"]
820 order_mock1
.trade
= mock
.Mock()
821 order_mock2
.trade
= mock
.Mock()
822 order_mock3
.trade
= mock
.Mock()
824 m
.follow_orders(sleep
=sleep
)
826 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
827 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
828 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
829 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
831 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
832 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
833 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
835 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
836 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
837 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
838 m
.report
.log_stage
.assert_called()
840 mock
.call("follow_orders_begin"),
841 mock
.call("follow_orders_tick_1"),
842 mock
.call("follow_orders_tick_2"),
843 mock
.call("follow_orders_tick_3"),
844 mock
.call("follow_orders_end"),
846 m
.report
.log_stage
.assert_has_calls(calls
)
847 m
.report
.log_orders
.assert_called()
848 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
850 mock
.call([order_mock1
, order_mock2
], tick
=1),
851 mock
.call([order_mock1
, order_mock3
], tick
=2),
852 mock
.call([order_mock1
, order_mock3
], tick
=3),
854 m
.report
.log_orders
.assert_has_calls(calls
)
856 mock
.call(order_mock1
, 3, finished
=True),
857 mock
.call(order_mock3
, 3, finished
=True),
859 m
.report
.log_order
.assert_has_calls(calls
)
863 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
864 time_mock
.assert_called_with(7)
866 time_mock
.assert_called_with(30)
868 time_mock
.assert_called_with(sleep
)
870 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
871 def test_move_balance(self
, fetch_balances
):
872 for debug
in [True, False]:
873 with self
.subTest(debug
=debug
),\
874 mock
.patch("market.ReportStore"):
875 m
= market
.Market(self
.ccxt
, debug
=debug
)
877 value_from
= portfolio
.Amount("BTC", "1.0")
878 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
879 value_to
= portfolio
.Amount("BTC", "10.0")
880 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
882 value_from
= portfolio
.Amount("BTC", "0.0")
883 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
884 value_to
= portfolio
.Amount("BTC", "-3.0")
885 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
887 value_from
= portfolio
.Amount("USDT", "0.0")
888 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
889 value_to
= portfolio
.Amount("USDT", "-50.0")
890 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
892 m
.trades
.all
= [trade1
, trade2
, trade3
]
893 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
894 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
895 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
896 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
900 fetch_balances
.assert_called_with()
901 m
.report
.log_move_balances
.assert_called_once()
904 m
.report
.log_debug_action
.assert_called()
905 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
907 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
908 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
909 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
911 @unittest.skipUnless("unit" in limits
, "Unit skipped")
912 class TradeStoreTest(WebMockTestCase
):
913 def test_compute_trades(self
):
914 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
917 "XMR": portfolio
.Amount("BTC", D("0.9")),
918 "DASH": portfolio
.Amount("BTC", D("0.4")),
919 "XVG": portfolio
.Amount("BTC", D("-0.5")),
920 "BTC": portfolio
.Amount("BTC", D("0.5")),
923 "DASH": portfolio
.Amount("BTC", D("0.5")),
924 "XVG": portfolio
.Amount("BTC", D("0.1")),
925 "BTC": portfolio
.Amount("BTC", D("0.4")),
926 "ETH": portfolio
.Amount("BTC", D("0.3")),
936 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
937 trade_store
= market
.TradeStore(self
.m
)
938 trade_if_matching
.side_effect
= side_effect
940 trade_store
.compute_trades(values_in_base
,
941 new_repartition
, only
="only")
943 self
.assertEqual(5, trade_if_matching
.call_count
)
944 self
.assertEqual(3, len(trade_store
.all
))
945 self
.assertEqual([1, 4, 5], trade_store
.all
)
946 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
948 def test_trade_if_matching(self
):
950 with self
.subTest(only
="nope"):
951 trade_store
= market
.TradeStore(self
.m
)
952 result
= trade_store
.trade_if_matching(
953 portfolio
.Amount("BTC", D("0")),
954 portfolio
.Amount("BTC", D("0.3")),
956 self
.assertEqual(False, result
[0])
957 self
.assertIsInstance(result
[1], portfolio
.Trade
)
959 with self
.subTest(only
=None):
960 trade_store
= market
.TradeStore(self
.m
)
961 result
= trade_store
.trade_if_matching(
962 portfolio
.Amount("BTC", D("0")),
963 portfolio
.Amount("BTC", D("0.3")),
965 self
.assertEqual(True, result
[0])
967 with self
.subTest(only
="acquire"):
968 trade_store
= market
.TradeStore(self
.m
)
969 result
= trade_store
.trade_if_matching(
970 portfolio
.Amount("BTC", D("0")),
971 portfolio
.Amount("BTC", D("0.3")),
972 "ETH", only
="acquire")
973 self
.assertEqual(True, result
[0])
975 with self
.subTest(only
="dispose"):
976 trade_store
= market
.TradeStore(self
.m
)
977 result
= trade_store
.trade_if_matching(
978 portfolio
.Amount("BTC", D("0")),
979 portfolio
.Amount("BTC", D("0.3")),
980 "ETH", only
="dispose")
981 self
.assertEqual(False, result
[0])
983 def test_prepare_orders(self
):
984 trade_store
= market
.TradeStore(self
.m
)
986 trade_mock1
= mock
.Mock()
987 trade_mock2
= mock
.Mock()
988 trade_mock3
= mock
.Mock()
990 trade_mock1
.prepare_order
.return_value
= 1
991 trade_mock2
.prepare_order
.return_value
= 2
992 trade_mock3
.prepare_order
.return_value
= 3
994 trade_mock1
.pending
= True
995 trade_mock2
.pending
= True
996 trade_mock3
.pending
= False
998 trade_store
.all
.append(trade_mock1
)
999 trade_store
.all
.append(trade_mock2
)
1000 trade_store
.all
.append(trade_mock3
)
1002 trade_store
.prepare_orders()
1003 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1004 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1005 trade_mock3
.prepare_order
.assert_not_called()
1006 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1008 self
.m
.report
.log_orders
.reset_mock()
1010 trade_store
.prepare_orders(compute_value
="bla")
1011 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1012 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1013 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1015 trade_mock1
.prepare_order
.reset_mock()
1016 trade_mock2
.prepare_order
.reset_mock()
1017 self
.m
.report
.log_orders
.reset_mock()
1019 trade_mock1
.action
= "foo"
1020 trade_mock2
.action
= "bar"
1021 trade_store
.prepare_orders(only
="bar")
1022 trade_mock1
.prepare_order
.assert_not_called()
1023 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1024 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1026 def test_print_all_with_order(self
):
1027 trade_mock1
= mock
.Mock()
1028 trade_mock2
= mock
.Mock()
1029 trade_mock3
= mock
.Mock()
1030 trade_store
= market
.TradeStore(self
.m
)
1031 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1033 trade_store
.print_all_with_order()
1035 trade_mock1
.print_with_order
.assert_called()
1036 trade_mock2
.print_with_order
.assert_called()
1037 trade_mock3
.print_with_order
.assert_called()
1039 def test_run_orders(self
):
1040 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1041 order_mock1
= mock
.Mock()
1042 order_mock2
= mock
.Mock()
1043 order_mock3
= mock
.Mock()
1044 trade_store
= market
.TradeStore(self
.m
)
1046 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1048 trade_store
.run_orders()
1050 all_orders
.assert_called_with(state
="pending")
1052 order_mock1
.run
.assert_called()
1053 order_mock2
.run
.assert_called()
1054 order_mock3
.run
.assert_called()
1056 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1057 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1060 def test_all_orders(self
):
1061 trade_mock1
= mock
.Mock()
1062 trade_mock2
= mock
.Mock()
1064 order_mock1
= mock
.Mock()
1065 order_mock2
= mock
.Mock()
1066 order_mock3
= mock
.Mock()
1068 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1069 trade_mock2
.orders
= [order_mock3
]
1071 order_mock1
.status
= "pending"
1072 order_mock2
.status
= "open"
1073 order_mock3
.status
= "open"
1075 trade_store
= market
.TradeStore(self
.m
)
1076 trade_store
.all
.append(trade_mock1
)
1077 trade_store
.all
.append(trade_mock2
)
1079 orders
= trade_store
.all_orders()
1080 self
.assertEqual(3, len(orders
))
1082 open_orders
= trade_store
.all_orders(state
="open")
1083 self
.assertEqual(2, len(open_orders
))
1084 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1086 def test_update_all_orders_status(self
):
1087 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1088 order_mock1
= mock
.Mock()
1089 order_mock2
= mock
.Mock()
1090 order_mock3
= mock
.Mock()
1092 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1094 trade_store
= market
.TradeStore(self
.m
)
1096 trade_store
.update_all_orders_status()
1097 all_orders
.assert_called_with(state
="open")
1099 order_mock1
.get_status
.assert_called()
1100 order_mock2
.get_status
.assert_called()
1101 order_mock3
.get_status
.assert_called()
1103 def test_close_trades(self
):
1104 trade_mock1
= mock
.Mock()
1105 trade_mock2
= mock
.Mock()
1106 trade_mock3
= mock
.Mock()
1108 trade_store
= market
.TradeStore(self
.m
)
1110 trade_store
.all
.append(trade_mock1
)
1111 trade_store
.all
.append(trade_mock2
)
1112 trade_store
.all
.append(trade_mock3
)
1114 trade_store
.close_trades()
1116 trade_mock1
.close
.assert_called_once_with()
1117 trade_mock2
.close
.assert_called_once_with()
1118 trade_mock3
.close
.assert_called_once_with()
1120 def test_pending(self
):
1121 trade_mock1
= mock
.Mock()
1122 trade_mock1
.pending
= True
1123 trade_mock2
= mock
.Mock()
1124 trade_mock2
.pending
= True
1125 trade_mock3
= mock
.Mock()
1126 trade_mock3
.pending
= False
1128 trade_store
= market
.TradeStore(self
.m
)
1130 trade_store
.all
.append(trade_mock1
)
1131 trade_store
.all
.append(trade_mock2
)
1132 trade_store
.all
.append(trade_mock3
)
1134 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
1136 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1137 class BalanceStoreTest(WebMockTestCase
):
1139 super(BalanceStoreTest
, self
).setUp()
1141 self
.fetch_balance
= {
1145 "exchange_total": 0,
1149 "exchange_free": D("6.0"),
1150 "exchange_used": D("1.2"),
1151 "exchange_total": D("7.2"),
1155 "exchange_free": 16,
1157 "exchange_total": 16,
1163 "exchange_total": 0,
1164 "margin_total": D("-1.0"),
1169 def test_in_currency(self
):
1170 self
.m
.get_ticker
.return_value
= {
1173 "average": D("0.1"),
1176 balance_store
= market
.BalanceStore(self
.m
)
1177 balance_store
.all
= {
1178 "BTC": portfolio
.Balance("BTC", {
1180 "exchange_total":"0.65",
1181 "exchange_free": "0.35",
1182 "exchange_used": "0.30"}),
1183 "ETH": portfolio
.Balance("ETH", {
1185 "exchange_total": 3,
1187 "exchange_used": 0}),
1190 amounts
= balance_store
.in_currency("BTC")
1191 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1192 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1193 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1194 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1196 self
.m
.report
.log_tickers
.reset_mock()
1198 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1199 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1200 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1201 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1203 self
.m
.report
.log_tickers
.reset_mock()
1205 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1206 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1207 self
.assertEqual(0, amounts
["ETH"].value
)
1208 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1209 "bid", "exchange_used")
1210 self
.m
.report
.log_tickers
.reset_mock()
1212 def test_fetch_balances(self
):
1213 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1215 balance_store
= market
.BalanceStore(self
.m
)
1217 balance_store
.fetch_balances()
1218 self
.assertNotIn("ETC", balance_store
.currencies())
1219 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1221 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1222 "exchange_total": "1", "exchange_free": "0",
1223 "exchange_used": "1" })
1224 balance_store
.fetch_balances(tag
="foo")
1225 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1226 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1227 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1229 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1230 def test_dispatch_assets(self
, repartition
):
1231 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1233 balance_store
= market
.BalanceStore(self
.m
)
1234 balance_store
.fetch_balances()
1236 self
.assertNotIn("XEM", balance_store
.currencies())
1238 repartition_hash
= {
1239 "XEM": (D("0.75"), "long"),
1240 "BTC": (D("0.26"), "long"),
1241 "DASH": (D("0.10"), "short"),
1243 repartition
.return_value
= repartition_hash
1245 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1246 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1247 self
.assertIn("XEM", balance_store
.currencies())
1248 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1249 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1250 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1251 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1252 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1253 "11.1"), amounts
, "medium", repartition_hash
)
1255 def test_currencies(self
):
1256 balance_store
= market
.BalanceStore(self
.m
)
1258 balance_store
.all
= {
1259 "BTC": portfolio
.Balance("BTC", {
1261 "exchange_total":"0.65",
1262 "exchange_free": "0.35",
1263 "exchange_used": "0.30"}),
1264 "ETH": portfolio
.Balance("ETH", {
1266 "exchange_total": 3,
1268 "exchange_used": 0}),
1270 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1272 def test_as_json(self
):
1273 balance_mock1
= mock
.Mock()
1274 balance_mock1
.as_json
.return_value
= 1
1276 balance_mock2
= mock
.Mock()
1277 balance_mock2
.as_json
.return_value
= 2
1279 balance_store
= market
.BalanceStore(self
.m
)
1280 balance_store
.all
= {
1281 "BTC": balance_mock1
,
1282 "ETH": balance_mock2
,
1285 as_json
= balance_store
.as_json()
1286 self
.assertEqual(1, as_json
["BTC"])
1287 self
.assertEqual(2, as_json
["ETH"])
1290 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1291 class ComputationTest(WebMockTestCase
):
1292 def test_compute_value(self
):
1293 compute
= mock
.Mock()
1294 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1295 compute
.assert_called_with("foo", "ask")
1297 compute
.reset_mock()
1298 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1299 compute
.assert_called_with("foo", "bid")
1301 compute
.reset_mock()
1302 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1303 compute
.assert_called_with("foo", "ask")
1305 compute
.reset_mock()
1306 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1307 compute
.assert_called_with("foo", "bid")
1309 compute
.reset_mock()
1310 portfolio
.Computation
.computations
["test"] = compute
1311 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1312 compute
.assert_called_with("foo", "bid")
1315 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1316 class TradeTest(WebMockTestCase
):
1318 def test_values_assertion(self
):
1319 value_from
= portfolio
.Amount("BTC", "1.0")
1320 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1321 value_to
= portfolio
.Amount("BTC", "1.0")
1322 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1323 self
.assertEqual("BTC", trade
.base_currency
)
1324 self
.assertEqual("ETH", trade
.currency
)
1325 self
.assertEqual(self
.m
, trade
.market
)
1327 with self
.assertRaises(AssertionError):
1328 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
1329 with self
.assertRaises(AssertionError):
1330 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1331 with self
.assertRaises(AssertionError):
1332 value_from
.currency
= "ETH"
1333 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1334 value_from
.currency
= "BTC"
1335 with self
.assertRaises(AssertionError):
1336 value_from2
= portfolio
.Amount("BTC", "1.0")
1337 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
1339 value_from
= portfolio
.Amount("BTC", 0)
1340 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1341 self
.assertEqual(0, trade
.value_from
.linked_to
)
1343 def test_action(self
):
1344 value_from
= portfolio
.Amount("BTC", "1.0")
1345 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1346 value_to
= portfolio
.Amount("BTC", "1.0")
1347 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1349 self
.assertIsNone(trade
.action
)
1351 value_from
= portfolio
.Amount("BTC", "1.0")
1352 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1353 value_to
= portfolio
.Amount("BTC", "2.0")
1354 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1356 self
.assertIsNone(trade
.action
)
1358 value_from
= portfolio
.Amount("BTC", "0.5")
1359 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1360 value_to
= portfolio
.Amount("BTC", "1.0")
1361 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1363 self
.assertEqual("acquire", trade
.action
)
1365 value_from
= portfolio
.Amount("BTC", "0")
1366 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1367 value_to
= portfolio
.Amount("BTC", "-1.0")
1368 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1370 self
.assertEqual("acquire", trade
.action
)
1372 def test_order_action(self
):
1373 value_from
= portfolio
.Amount("BTC", "0.5")
1374 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1375 value_to
= portfolio
.Amount("BTC", "1.0")
1376 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1378 self
.assertEqual("buy", trade
.order_action(False))
1379 self
.assertEqual("sell", trade
.order_action(True))
1381 value_from
= portfolio
.Amount("BTC", "0")
1382 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1383 value_to
= portfolio
.Amount("BTC", "-1.0")
1384 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1386 self
.assertEqual("sell", trade
.order_action(False))
1387 self
.assertEqual("buy", trade
.order_action(True))
1389 def test_trade_type(self
):
1390 value_from
= portfolio
.Amount("BTC", "0.5")
1391 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1392 value_to
= portfolio
.Amount("BTC", "1.0")
1393 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1395 self
.assertEqual("long", trade
.trade_type
)
1397 value_from
= portfolio
.Amount("BTC", "0")
1398 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1399 value_to
= portfolio
.Amount("BTC", "-1.0")
1400 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1402 self
.assertEqual("short", trade
.trade_type
)
1404 def test_is_fullfiled(self
):
1405 value_from
= portfolio
.Amount("BTC", "0.5")
1406 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1407 value_to
= portfolio
.Amount("BTC", "1.0")
1408 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1410 order1
= mock
.Mock()
1411 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1413 order2
= mock
.Mock()
1414 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1415 trade
.orders
.append(order1
)
1416 trade
.orders
.append(order2
)
1418 self
.assertFalse(trade
.is_fullfiled
)
1420 order3
= mock
.Mock()
1421 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1422 trade
.orders
.append(order3
)
1424 self
.assertTrue(trade
.is_fullfiled
)
1426 def test_filled_amount(self
):
1427 value_from
= portfolio
.Amount("BTC", "0.5")
1428 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1429 value_to
= portfolio
.Amount("BTC", "1.0")
1430 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1432 order1
= mock
.Mock()
1433 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1435 order2
= mock
.Mock()
1436 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1437 trade
.orders
.append(order1
)
1438 trade
.orders
.append(order2
)
1440 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1441 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1442 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1444 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1445 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1446 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1448 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1449 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1450 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1452 @mock.patch.object(portfolio
.Computation
, "compute_value")
1453 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1454 @mock.patch.object(portfolio
, "Order")
1455 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1456 Order
.return_value
= "Order"
1458 with self
.subTest(desc
="Nothing to do"):
1459 value_from
= portfolio
.Amount("BTC", "10")
1460 value_from
.rate
= D("0.1")
1461 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1462 value_to
= portfolio
.Amount("BTC", "10")
1463 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1465 trade
.prepare_order()
1467 filled_amount
.assert_not_called()
1468 compute_value
.assert_not_called()
1469 self
.assertEqual(0, len(trade
.orders
))
1470 Order
.assert_not_called()
1472 self
.m
.get_ticker
.return_value
= { "inverted": False }
1473 with self
.subTest(desc
="Already filled"):
1474 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1475 compute_value
.return_value
= D("0.125")
1477 value_from
= portfolio
.Amount("BTC", "10")
1478 value_from
.rate
= D("0.1")
1479 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1480 value_to
= portfolio
.Amount("BTC", "0")
1481 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1483 trade
.prepare_order()
1485 filled_amount
.assert_called_with(in_base_currency
=False)
1486 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1487 self
.assertEqual(0, len(trade
.orders
))
1488 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1489 Order
.assert_not_called()
1491 with self
.subTest(action
="dispose", inverted
=False):
1492 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1493 compute_value
.return_value
= D("0.125")
1495 value_from
= portfolio
.Amount("BTC", "10")
1496 value_from
.rate
= D("0.1")
1497 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1498 value_to
= portfolio
.Amount("BTC", "1")
1499 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1501 trade
.prepare_order()
1503 filled_amount
.assert_called_with(in_base_currency
=False)
1504 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1505 self
.assertEqual(1, len(trade
.orders
))
1506 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1507 D("0.125"), "BTC", "long", self
.m
,
1508 trade
, close_if_possible
=False)
1510 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1511 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1512 compute_value
.return_value
= D("0.125")
1514 value_from
= portfolio
.Amount("BTC", "10")
1515 value_from
.rate
= D("0.1")
1516 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1517 value_to
= portfolio
.Amount("BTC", "1")
1518 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1520 trade
.prepare_order(close_if_possible
=True)
1522 filled_amount
.assert_called_with(in_base_currency
=False)
1523 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1524 self
.assertEqual(1, len(trade
.orders
))
1525 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1526 D("0.125"), "BTC", "long", self
.m
,
1527 trade
, close_if_possible
=True)
1529 with self
.subTest(action
="acquire", inverted
=False):
1530 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1531 compute_value
.return_value
= D("0.125")
1533 value_from
= portfolio
.Amount("BTC", "1")
1534 value_from
.rate
= D("0.1")
1535 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1536 value_to
= portfolio
.Amount("BTC", "10")
1537 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1539 trade
.prepare_order()
1541 filled_amount
.assert_called_with(in_base_currency
=True)
1542 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1543 self
.assertEqual(1, len(trade
.orders
))
1545 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1546 D("0.125"), "BTC", "long", self
.m
,
1547 trade
, close_if_possible
=False)
1549 with self
.subTest(close_if_possible
=True):
1550 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1551 compute_value
.return_value
= D("0.125")
1553 value_from
= portfolio
.Amount("BTC", "10")
1554 value_from
.rate
= D("0.1")
1555 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1556 value_to
= portfolio
.Amount("BTC", "0")
1557 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1559 trade
.prepare_order()
1561 filled_amount
.assert_called_with(in_base_currency
=False)
1562 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1563 self
.assertEqual(1, len(trade
.orders
))
1564 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1565 D("0.125"), "BTC", "long", self
.m
,
1566 trade
, close_if_possible
=True)
1568 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1569 with self
.subTest(action
="dispose", inverted
=True):
1570 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1571 compute_value
.return_value
= D("125")
1573 value_from
= portfolio
.Amount("BTC", "10")
1574 value_from
.rate
= D("0.01")
1575 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1576 value_to
= portfolio
.Amount("BTC", "1")
1577 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1579 trade
.prepare_order(compute_value
="foo")
1581 filled_amount
.assert_called_with(in_base_currency
=True)
1582 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1583 self
.assertEqual(1, len(trade
.orders
))
1584 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1585 D("125"), "FOO", "long", self
.m
,
1586 trade
, close_if_possible
=False)
1588 with self
.subTest(action
="acquire", inverted
=True):
1589 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1590 compute_value
.return_value
= D("125")
1592 value_from
= portfolio
.Amount("BTC", "1")
1593 value_from
.rate
= D("0.01")
1594 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1595 value_to
= portfolio
.Amount("BTC", "10")
1596 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1598 trade
.prepare_order(compute_value
="foo")
1600 filled_amount
.assert_called_with(in_base_currency
=False)
1601 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1602 self
.assertEqual(1, len(trade
.orders
))
1603 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1604 D("125"), "FOO", "long", self
.m
,
1605 trade
, close_if_possible
=False)
1608 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1609 def test_update_order(self
, prepare_order
):
1610 order_mock
= mock
.Mock()
1611 new_order_mock
= mock
.Mock()
1613 value_from
= portfolio
.Amount("BTC", "0.5")
1614 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1615 value_to
= portfolio
.Amount("BTC", "1.0")
1616 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1617 prepare_order
.return_value
= new_order_mock
1619 for i
in [0, 1, 3, 4, 6]:
1620 with self
.subTest(tick
=i
):
1621 trade
.update_order(order_mock
, i
)
1622 order_mock
.cancel
.assert_not_called()
1623 new_order_mock
.run
.assert_not_called()
1624 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1625 update
="waiting", compute_value
=None, new_order
=None)
1627 order_mock
.reset_mock()
1628 new_order_mock
.reset_mock()
1630 self
.m
.report
.log_order
.reset_mock()
1632 trade
.update_order(order_mock
, 2)
1633 order_mock
.cancel
.assert_called()
1634 new_order_mock
.run
.assert_called()
1635 prepare_order
.assert_called()
1636 self
.m
.report
.log_order
.assert_called()
1637 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1639 mock
.call(order_mock
, 2, update
="adjusting",
1640 compute_value
=mock
.ANY
,
1641 new_order
=new_order_mock
),
1642 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1644 self
.m
.report
.log_order
.assert_has_calls(calls
)
1646 order_mock
.reset_mock()
1647 new_order_mock
.reset_mock()
1649 self
.m
.report
.log_order
.reset_mock()
1651 trade
.update_order(order_mock
, 5)
1652 order_mock
.cancel
.assert_called()
1653 new_order_mock
.run
.assert_called()
1654 prepare_order
.assert_called()
1655 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1656 self
.m
.report
.log_order
.assert_called()
1658 mock
.call(order_mock
, 5, update
="adjusting",
1659 compute_value
=mock
.ANY
,
1660 new_order
=new_order_mock
),
1661 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1663 self
.m
.report
.log_order
.assert_has_calls(calls
)
1665 order_mock
.reset_mock()
1666 new_order_mock
.reset_mock()
1668 self
.m
.report
.log_order
.reset_mock()
1670 trade
.update_order(order_mock
, 7)
1671 order_mock
.cancel
.assert_called()
1672 new_order_mock
.run
.assert_called()
1673 prepare_order
.assert_called_with(compute_value
="default")
1674 self
.m
.report
.log_order
.assert_called()
1675 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1677 mock
.call(order_mock
, 7, update
="market_fallback",
1678 compute_value
='default',
1679 new_order
=new_order_mock
),
1680 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1682 self
.m
.report
.log_order
.assert_has_calls(calls
)
1684 order_mock
.reset_mock()
1685 new_order_mock
.reset_mock()
1687 self
.m
.report
.log_order
.reset_mock()
1689 for i
in [10, 13, 16]:
1690 with self
.subTest(tick
=i
):
1691 trade
.update_order(order_mock
, i
)
1692 order_mock
.cancel
.assert_called()
1693 new_order_mock
.run
.assert_called()
1694 prepare_order
.assert_called_with(compute_value
="default")
1695 self
.m
.report
.log_order
.assert_called()
1696 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1698 mock
.call(order_mock
, i
, update
="market_adjust",
1699 compute_value
='default',
1700 new_order
=new_order_mock
),
1701 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1703 self
.m
.report
.log_order
.assert_has_calls(calls
)
1705 order_mock
.reset_mock()
1706 new_order_mock
.reset_mock()
1708 self
.m
.report
.log_order
.reset_mock()
1710 for i
in [8, 9, 11, 12]:
1711 with self
.subTest(tick
=i
):
1712 trade
.update_order(order_mock
, i
)
1713 order_mock
.cancel
.assert_not_called()
1714 new_order_mock
.run
.assert_not_called()
1715 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1716 compute_value
=None, new_order
=None)
1718 order_mock
.reset_mock()
1719 new_order_mock
.reset_mock()
1721 self
.m
.report
.log_order
.reset_mock()
1724 def test_print_with_order(self
):
1725 value_from
= portfolio
.Amount("BTC", "0.5")
1726 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1727 value_to
= portfolio
.Amount("BTC", "1.0")
1728 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1730 order_mock1
= mock
.Mock()
1731 order_mock1
.__repr__
= mock
.Mock()
1732 order_mock1
.__repr__
.return_value
= "Mock 1"
1733 order_mock2
= mock
.Mock()
1734 order_mock2
.__repr__
= mock
.Mock()
1735 order_mock2
.__repr__
.return_value
= "Mock 2"
1736 order_mock1
.mouvements
= []
1737 mouvement_mock1
= mock
.Mock()
1738 mouvement_mock1
.__repr__
= mock
.Mock()
1739 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1740 mouvement_mock2
= mock
.Mock()
1741 mouvement_mock2
.__repr__
= mock
.Mock()
1742 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1743 order_mock2
.mouvements
= [
1744 mouvement_mock1
, mouvement_mock2
1746 trade
.orders
.append(order_mock1
)
1747 trade
.orders
.append(order_mock2
)
1749 with mock
.patch
.object(trade
, "filled_amount") as filled
:
1750 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
1752 trade
.print_with_order()
1754 self
.m
.report
.print_log
.assert_called()
1755 calls
= self
.m
.report
.print_log
.mock_calls
1756 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1757 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1758 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1759 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1760 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1762 self
.m
.report
.print_log
.reset_mock()
1764 filled
.return_value
= portfolio
.Amount("BTC", "0.5")
1765 trade
.print_with_order()
1766 calls
= self
.m
.report
.print_log
.mock_calls
1767 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls
[0][1][0]))
1769 self
.m
.report
.print_log
.reset_mock()
1771 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
1773 trade
.print_with_order()
1774 calls
= self
.m
.report
.print_log
.mock_calls
1775 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls
[0][1][0]))
1777 def test_close(self
):
1778 value_from
= portfolio
.Amount("BTC", "0.5")
1779 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1780 value_to
= portfolio
.Amount("BTC", "1.0")
1781 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1782 order1
= mock
.Mock()
1783 trade
.orders
.append(order1
)
1787 self
.assertEqual(True, trade
.closed
)
1788 order1
.cancel
.assert_called_once_with()
1790 def test_pending(self
):
1791 value_from
= portfolio
.Amount("BTC", "0.5")
1792 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1793 value_to
= portfolio
.Amount("BTC", "1.0")
1794 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1797 self
.assertEqual(False, trade
.pending
)
1799 trade
.closed
= False
1800 self
.assertEqual(True, trade
.pending
)
1802 order1
= mock
.Mock()
1803 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.5")
1804 trade
.orders
.append(order1
)
1805 self
.assertEqual(False, trade
.pending
)
1807 def test__repr(self
):
1808 value_from
= portfolio
.Amount("BTC", "0.5")
1809 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1810 value_to
= portfolio
.Amount("BTC", "1.0")
1811 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1813 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1815 def test_as_json(self
):
1816 value_from
= portfolio
.Amount("BTC", "0.5")
1817 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1818 value_to
= portfolio
.Amount("BTC", "1.0")
1819 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1821 as_json
= trade
.as_json()
1822 self
.assertEqual("acquire", as_json
["action"])
1823 self
.assertEqual(D("0.5"), as_json
["from"])
1824 self
.assertEqual(D("1.0"), as_json
["to"])
1825 self
.assertEqual("ETH", as_json
["currency"])
1826 self
.assertEqual("BTC", as_json
["base_currency"])
1828 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1829 class OrderTest(WebMockTestCase
):
1830 def test_values(self
):
1831 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1832 D("0.1"), "BTC", "long", "market", "trade")
1833 self
.assertEqual("buy", order
.action
)
1834 self
.assertEqual(10, order
.amount
.value
)
1835 self
.assertEqual("ETH", order
.amount
.currency
)
1836 self
.assertEqual(D("0.1"), order
.rate
)
1837 self
.assertEqual("BTC", order
.base_currency
)
1838 self
.assertEqual("market", order
.market
)
1839 self
.assertEqual("long", order
.trade_type
)
1840 self
.assertEqual("pending", order
.status
)
1841 self
.assertEqual("trade", order
.trade
)
1842 self
.assertIsNone(order
.id)
1843 self
.assertFalse(order
.close_if_possible
)
1845 def test__repr(self
):
1846 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1847 D("0.1"), "BTC", "long", "market", "trade")
1848 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1850 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1851 D("0.1"), "BTC", "long", "market", "trade",
1852 close_if_possible
=True)
1853 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1855 def test_as_json(self
):
1856 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1857 D("0.1"), "BTC", "long", "market", "trade")
1858 mouvement_mock1
= mock
.Mock()
1859 mouvement_mock1
.as_json
.return_value
= 1
1860 mouvement_mock2
= mock
.Mock()
1861 mouvement_mock2
.as_json
.return_value
= 2
1863 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1864 as_json
= order
.as_json()
1865 self
.assertEqual("buy", as_json
["action"])
1866 self
.assertEqual("long", as_json
["trade_type"])
1867 self
.assertEqual(10, as_json
["amount"])
1868 self
.assertEqual("ETH", as_json
["currency"])
1869 self
.assertEqual("BTC", as_json
["base_currency"])
1870 self
.assertEqual(D("0.1"), as_json
["rate"])
1871 self
.assertEqual("pending", as_json
["status"])
1872 self
.assertEqual(False, as_json
["close_if_possible"])
1873 self
.assertIsNone(as_json
["id"])
1874 self
.assertEqual([1, 2], as_json
["mouvements"])
1876 def test_account(self
):
1877 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1878 D("0.1"), "BTC", "long", "market", "trade")
1879 self
.assertEqual("exchange", order
.account
)
1881 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1882 D("0.1"), "BTC", "short", "market", "trade")
1883 self
.assertEqual("margin", order
.account
)
1885 def test_pending(self
):
1886 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1887 D("0.1"), "BTC", "long", "market", "trade")
1888 self
.assertTrue(order
.pending
)
1889 order
.status
= "open"
1890 self
.assertFalse(order
.pending
)
1892 def test_open(self
):
1893 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1894 D("0.1"), "BTC", "long", "market", "trade")
1895 self
.assertFalse(order
.open)
1896 order
.status
= "open"
1897 self
.assertTrue(order
.open)
1899 def test_finished(self
):
1900 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1901 D("0.1"), "BTC", "long", "market", "trade")
1902 self
.assertFalse(order
.finished
)
1903 order
.status
= "closed"
1904 self
.assertTrue(order
.finished
)
1905 order
.status
= "canceled"
1906 self
.assertTrue(order
.finished
)
1907 order
.status
= "error"
1908 self
.assertTrue(order
.finished
)
1910 @mock.patch.object(portfolio
.Order
, "fetch")
1911 def test_cancel(self
, fetch
):
1912 with self
.subTest(debug
=True):
1914 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1915 D("0.1"), "BTC", "long", self
.m
, "trade")
1916 order
.status
= "open"
1919 self
.m
.ccxt
.cancel_order
.assert_not_called()
1920 self
.m
.report
.log_debug_action
.assert_called_once()
1921 self
.m
.report
.log_debug_action
.reset_mock()
1922 self
.assertEqual("canceled", order
.status
)
1924 with self
.subTest(desc
="Nominal case"):
1925 self
.m
.debug
= False
1926 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1927 D("0.1"), "BTC", "long", self
.m
, "trade")
1928 order
.status
= "open"
1932 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1933 fetch
.assert_called_once_with()
1934 self
.m
.report
.log_debug_action
.assert_not_called()
1936 with self
.subTest(exception
=True):
1937 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
1938 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1939 D("0.1"), "BTC", "long", self
.m
, "trade")
1940 order
.status
= "open"
1943 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1944 self
.m
.report
.log_error
.assert_called_once()
1947 with self
.subTest(id=None):
1948 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
1949 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1950 D("0.1"), "BTC", "long", self
.m
, "trade")
1951 order
.status
= "open"
1953 self
.m
.ccxt
.cancel_order
.assert_not_called()
1956 with self
.subTest(open=False):
1957 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
1958 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1959 D("0.1"), "BTC", "long", self
.m
, "trade")
1960 order
.status
= "closed"
1962 self
.m
.ccxt
.cancel_order
.assert_not_called()
1964 def test_dust_amount_remaining(self
):
1965 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1966 D("0.1"), "BTC", "long", self
.m
, "trade")
1967 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1968 self
.assertFalse(order
.dust_amount_remaining())
1970 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1971 self
.assertTrue(order
.dust_amount_remaining())
1973 @mock.patch.object(portfolio
.Order
, "fetch")
1974 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1975 def test_remaining_amount(self
, filled_amount
, fetch
):
1976 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1977 D("0.1"), "BTC", "long", self
.m
, "trade")
1979 self
.assertEqual(9, order
.remaining_amount().value
)
1981 order
.status
= "open"
1982 self
.assertEqual(9, order
.remaining_amount().value
)
1984 @mock.patch.object(portfolio
.Order
, "fetch")
1985 def test_filled_amount(self
, fetch
):
1986 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1987 D("0.1"), "BTC", "long", self
.m
, "trade")
1988 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1989 "tradeID": 42, "type": "buy", "fee": "0.0015",
1990 "date": "2017-12-30 12:00:12", "rate": "0.1",
1991 "amount": "3", "total": "0.3"
1993 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1994 "tradeID": 43, "type": "buy", "fee": "0.0015",
1995 "date": "2017-12-30 13:00:12", "rate": "0.2",
1996 "amount": "2", "total": "0.4"
1998 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1999 fetch
.assert_not_called()
2000 order
.status
= "open"
2001 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
2002 fetch
.assert_called_once()
2003 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
2005 def test_fetch_mouvements(self
):
2006 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
2008 "tradeID": 42, "type": "buy", "fee": "0.0015",
2009 "date": "2017-12-30 12:00:12", "rate": "0.1",
2010 "amount": "3", "total": "0.3"
2013 "tradeID": 43, "type": "buy", "fee": "0.0015",
2014 "date": "2017-12-30 13:00:12", "rate": "0.2",
2015 "amount": "2", "total": "0.4"
2018 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2019 D("0.1"), "BTC", "long", self
.m
, "trade")
2021 order
.mouvements
= ["Foo", "Bar", "Baz"]
2023 order
.fetch_mouvements()
2025 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
2026 self
.assertEqual(2, len(order
.mouvements
))
2027 self
.assertEqual(42, order
.mouvements
[0].id)
2028 self
.assertEqual(43, order
.mouvements
[1].id)
2030 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
2031 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2032 D("0.1"), "BTC", "long", self
.m
, "trade")
2033 order
.fetch_mouvements()
2034 self
.assertEqual(0, len(order
.mouvements
))
2036 def test_mark_finished_order(self
):
2037 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2038 D("0.1"), "BTC", "short", self
.m
, "trade",
2039 close_if_possible
=True)
2040 order
.status
= "closed"
2041 self
.m
.debug
= False
2043 order
.mark_finished_order()
2044 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
2045 self
.m
.ccxt
.close_margin_position
.reset_mock()
2047 order
.status
= "open"
2048 order
.mark_finished_order()
2049 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2051 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2052 D("0.1"), "BTC", "short", self
.m
, "trade",
2053 close_if_possible
=False)
2054 order
.status
= "closed"
2055 order
.mark_finished_order()
2056 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2058 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2059 D("0.1"), "BTC", "short", self
.m
, "trade",
2060 close_if_possible
=True)
2061 order
.status
= "closed"
2062 order
.mark_finished_order()
2063 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2065 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2066 D("0.1"), "BTC", "long", self
.m
, "trade",
2067 close_if_possible
=True)
2068 order
.status
= "closed"
2069 order
.mark_finished_order()
2070 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2074 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2075 D("0.1"), "BTC", "short", self
.m
, "trade",
2076 close_if_possible
=True)
2077 order
.status
= "closed"
2079 order
.mark_finished_order()
2080 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2081 self
.m
.report
.log_debug_action
.assert_called_once()
2083 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
2084 def test_fetch(self
, fetch_mouvements
):
2085 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2086 D("0.1"), "BTC", "long", self
.m
, "trade")
2088 with self
.subTest(debug
=True):
2091 self
.m
.report
.log_debug_action
.assert_called_once()
2092 self
.m
.report
.log_debug_action
.reset_mock()
2093 self
.m
.ccxt
.fetch_order
.assert_not_called()
2094 fetch_mouvements
.assert_not_called()
2096 with self
.subTest(debug
=False):
2097 self
.m
.debug
= False
2098 self
.m
.ccxt
.fetch_order
.return_value
= {
2100 "datetime": "timestamp"
2104 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45)
2105 fetch_mouvements
.assert_called_once()
2106 self
.assertEqual("foo", order
.status
)
2107 self
.assertEqual("timestamp", order
.timestamp
)
2108 self
.assertEqual(1, len(order
.results
))
2109 self
.m
.report
.log_debug_action
.assert_not_called()
2111 with self
.subTest(missing_order
=True):
2112 self
.m
.ccxt
.fetch_order
.side_effect
= [
2113 portfolio
.OrderNotCached
,
2116 self
.assertEqual("closed_unknown", order
.status
)
2118 @mock.patch.object(portfolio
.Order
, "fetch")
2119 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2120 def test_get_status(self
, mark_finished_order
, fetch
):
2121 with self
.subTest(debug
=True):
2123 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2124 D("0.1"), "BTC", "long", self
.m
, "trade")
2125 self
.assertEqual("pending", order
.get_status())
2126 fetch
.assert_not_called()
2127 self
.m
.report
.log_debug_action
.assert_called_once()
2129 with self
.subTest(debug
=False, finished
=False):
2130 self
.m
.debug
= False
2131 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2132 D("0.1"), "BTC", "long", self
.m
, "trade")
2134 def update_status():
2135 order
.status
= "open"
2136 return update_status
2137 fetch
.side_effect
= _fetch(order
)
2138 self
.assertEqual("open", order
.get_status())
2139 mark_finished_order
.assert_not_called()
2140 fetch
.assert_called_once()
2142 mark_finished_order
.reset_mock()
2144 with self
.subTest(debug
=False, finished
=True):
2145 self
.m
.debug
= False
2146 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2147 D("0.1"), "BTC", "long", self
.m
, "trade")
2149 def update_status():
2150 order
.status
= "closed"
2151 return update_status
2152 fetch
.side_effect
= _fetch(order
)
2153 self
.assertEqual("closed", order
.get_status())
2154 mark_finished_order
.assert_called_once()
2155 fetch
.assert_called_once()
2158 self
.m
.ccxt
.order_precision
.return_value
= 4
2159 with self
.subTest(debug
=True):
2161 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2162 D("0.1"), "BTC", "long", self
.m
, "trade")
2164 self
.m
.ccxt
.create_order
.assert_not_called()
2165 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2166 self
.assertEqual("open", order
.status
)
2167 self
.assertEqual(1, len(order
.results
))
2168 self
.assertEqual(-1, order
.id)
2170 self
.m
.ccxt
.create_order
.reset_mock()
2171 with self
.subTest(debug
=False):
2172 self
.m
.debug
= False
2173 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2174 D("0.1"), "BTC", "long", self
.m
, "trade")
2175 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2177 self
.m
.ccxt
.create_order
.assert_called_once()
2178 self
.assertEqual(1, len(order
.results
))
2179 self
.assertEqual("open", order
.status
)
2181 self
.m
.ccxt
.create_order
.reset_mock()
2182 with self
.subTest(exception
=True):
2183 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2184 D("0.1"), "BTC", "long", self
.m
, "trade")
2185 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2187 self
.m
.ccxt
.create_order
.assert_called_once()
2188 self
.assertEqual(0, len(order
.results
))
2189 self
.assertEqual("error", order
.status
)
2190 self
.m
.report
.log_error
.assert_called_once()
2192 self
.m
.ccxt
.create_order
.reset_mock()
2193 with self
.subTest(dust_amount_exception
=True),\
2194 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2195 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2196 D("0.1"), "BTC", "long", self
.m
, "trade")
2197 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2199 self
.m
.ccxt
.create_order
.assert_called_once()
2200 self
.assertEqual(0, len(order
.results
))
2201 self
.assertEqual("closed", order
.status
)
2202 mark_finished_order
.assert_called_once()
2204 self
.m
.ccxt
.order_precision
.return_value
= 8
2205 self
.m
.ccxt
.create_order
.reset_mock()
2206 with self
.subTest(insufficient_funds
=True),\
2207 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2208 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2209 D("0.1"), "BTC", "long", self
.m
, "trade")
2210 self
.m
.ccxt
.create_order
.side_effect
= [
2211 portfolio
.InsufficientFunds
,
2212 portfolio
.InsufficientFunds
,
2213 portfolio
.InsufficientFunds
,
2217 self
.m
.ccxt
.create_order
.assert_has_calls([
2218 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2219 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2220 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2221 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2223 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2224 self
.assertEqual(1, len(order
.results
))
2225 self
.assertEqual("open", order
.status
)
2226 self
.assertEqual(4, order
.tries
)
2227 self
.m
.report
.log_error
.assert_called()
2228 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2230 self
.m
.ccxt
.order_precision
.return_value
= 8
2231 self
.m
.ccxt
.create_order
.reset_mock()
2232 self
.m
.report
.log_error
.reset_mock()
2233 with self
.subTest(insufficient_funds
=True),\
2234 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2235 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2236 D("0.1"), "BTC", "long", self
.m
, "trade")
2237 self
.m
.ccxt
.create_order
.side_effect
= [
2238 portfolio
.InsufficientFunds
,
2239 portfolio
.InsufficientFunds
,
2240 portfolio
.InsufficientFunds
,
2241 portfolio
.InsufficientFunds
,
2242 portfolio
.InsufficientFunds
,
2245 self
.m
.ccxt
.create_order
.assert_has_calls([
2246 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2247 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2248 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2249 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2250 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2252 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2253 self
.assertEqual(0, len(order
.results
))
2254 self
.assertEqual("error", order
.status
)
2255 self
.assertEqual(5, order
.tries
)
2256 self
.m
.report
.log_error
.assert_called()
2257 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2258 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Giving up Order(buy long 0.00096060 ETH at 0.1 BTC [pending])", exception
=mock
.ANY
)
2261 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2262 class MouvementTest(WebMockTestCase
):
2263 def test_values(self
):
2264 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2265 "tradeID": 42, "type": "buy", "fee": "0.0015",
2266 "date": "2017-12-30 12:00:12", "rate": "0.1",
2267 "amount": "10", "total": "1"
2269 self
.assertEqual("ETH", mouvement
.currency
)
2270 self
.assertEqual("BTC", mouvement
.base_currency
)
2271 self
.assertEqual(42, mouvement
.id)
2272 self
.assertEqual("buy", mouvement
.action
)
2273 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2274 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2275 self
.assertEqual(D("0.1"), mouvement
.rate
)
2276 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2277 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2279 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2280 self
.assertIsNone(mouvement
.date
)
2281 self
.assertIsNone(mouvement
.id)
2282 self
.assertIsNone(mouvement
.action
)
2283 self
.assertEqual(-1, mouvement
.fee_rate
)
2284 self
.assertEqual(0, mouvement
.rate
)
2285 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2286 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2288 def test__repr(self
):
2289 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2290 "tradeID": 42, "type": "buy", "fee": "0.0015",
2291 "date": "2017-12-30 12:00:12", "rate": "0.1",
2292 "amount": "10", "total": "1"
2294 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2296 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2297 "tradeID": 42, "type": "buy",
2298 "date": "garbage", "rate": "0.1",
2299 "amount": "10", "total": "1"
2301 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2303 def test_as_json(self
):
2304 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2305 "tradeID": 42, "type": "buy", "fee": "0.0015",
2306 "date": "2017-12-30 12:00:12", "rate": "0.1",
2307 "amount": "10", "total": "1"
2309 as_json
= mouvement
.as_json()
2311 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2312 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2313 self
.assertEqual("buy", as_json
["action"])
2314 self
.assertEqual(D("10"), as_json
["total"])
2315 self
.assertEqual(D("1"), as_json
["total_in_base"])
2316 self
.assertEqual("BTC", as_json
["base_currency"])
2317 self
.assertEqual("ETH", as_json
["currency"])
2319 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2320 class ReportStoreTest(WebMockTestCase
):
2321 def test_add_log(self
):
2322 report_store
= market
.ReportStore(self
.m
)
2323 report_store
.add_log({"foo": "bar"}
)
2325 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2327 def test_set_verbose(self
):
2328 report_store
= market
.ReportStore(self
.m
)
2329 with self
.subTest(verbose
=True):
2330 report_store
.set_verbose(True)
2331 self
.assertTrue(report_store
.verbose_print
)
2333 with self
.subTest(verbose
=False):
2334 report_store
.set_verbose(False)
2335 self
.assertFalse(report_store
.verbose_print
)
2337 def test_print_log(self
):
2338 report_store
= market
.ReportStore(self
.m
)
2339 with self
.subTest(verbose
=True),\
2340 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2341 report_store
.set_verbose(True)
2342 report_store
.print_log("Coucou")
2343 report_store
.print_log(portfolio
.Amount("BTC", 1))
2344 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2346 with self
.subTest(verbose
=False),\
2347 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2348 report_store
.set_verbose(False)
2349 report_store
.print_log("Coucou")
2350 report_store
.print_log(portfolio
.Amount("BTC", 1))
2351 self
.assertEqual(stdout_mock
.getvalue(), "")
2353 def test_to_json(self
):
2354 report_store
= market
.ReportStore(self
.m
)
2355 report_store
.logs
.append({"foo": "bar"}
)
2356 self
.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store
.to_json())
2357 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2358 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store
.to_json())
2359 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2360 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store
.to_json())
2362 @mock.patch.object(market
.ReportStore
, "print_log")
2363 @mock.patch.object(market
.ReportStore
, "add_log")
2364 def test_log_stage(self
, add_log
, print_log
):
2365 report_store
= market
.ReportStore(self
.m
)
2367 report_store
.log_stage("foo", bar
="baz", c
=c
, d
=portfolio
.Amount("BTC", 1))
2368 print_log
.assert_has_calls([
2369 mock
.call("-----------"),
2370 mock
.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
2372 add_log
.assert_called_once_with({
2377 'c': 'c = lambda x: x',
2385 @mock.patch.object(market
.ReportStore
, "print_log")
2386 @mock.patch.object(market
.ReportStore
, "add_log")
2387 def test_log_balances(self
, add_log
, print_log
):
2388 report_store
= market
.ReportStore(self
.m
)
2389 self
.m
.balances
.as_json
.return_value
= "json"
2390 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2392 report_store
.log_balances(tag
="tag")
2393 print_log
.assert_has_calls([
2394 mock
.call("[Balance]"),
2398 add_log
.assert_called_once_with({
2404 @mock.patch.object(market
.ReportStore
, "print_log")
2405 @mock.patch.object(market
.ReportStore
, "add_log")
2406 def test_log_tickers(self
, add_log
, print_log
):
2407 report_store
= market
.ReportStore(self
.m
)
2409 "BTC": portfolio
.Amount("BTC", 10),
2410 "ETH": portfolio
.Amount("BTC", D("0.3"))
2412 amounts
["ETH"].rate
= D("0.1")
2414 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2415 print_log
.assert_not_called()
2416 add_log
.assert_called_once_with({
2418 'compute_value': 'default',
2419 'balance_type': 'total',
2432 add_log
.reset_mock()
2433 compute_value
= lambda x
: x
["bid"]
2434 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
2435 add_log
.assert_called_once_with({
2437 'compute_value': 'compute_value = lambda x: x["bid"]',
2438 'balance_type': 'total',
2451 @mock.patch.object(market
.ReportStore
, "print_log")
2452 @mock.patch.object(market
.ReportStore
, "add_log")
2453 def test_log_dispatch(self
, add_log
, print_log
):
2454 report_store
= market
.ReportStore(self
.m
)
2455 amount
= portfolio
.Amount("BTC", "10.3")
2457 "BTC": portfolio
.Amount("BTC", 10),
2458 "ETH": portfolio
.Amount("BTC", D("0.3"))
2460 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2461 print_log
.assert_not_called()
2462 add_log
.assert_called_once_with({
2464 'liquidity': 'medium',
2465 'repartition_ratio': 'repartition',
2476 @mock.patch.object(market
.ReportStore
, "print_log")
2477 @mock.patch.object(market
.ReportStore
, "add_log")
2478 def test_log_trades(self
, add_log
, print_log
):
2479 report_store
= market
.ReportStore(self
.m
)
2480 trade_mock1
= mock
.Mock()
2481 trade_mock2
= mock
.Mock()
2482 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2483 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2485 matching_and_trades
= [
2486 (True, trade_mock1
),
2487 (False, trade_mock2
),
2489 report_store
.log_trades(matching_and_trades
, "only")
2491 print_log
.assert_not_called()
2492 add_log
.assert_called_with({
2497 {'trade': '1', 'skipped': False}
,
2498 {'trade': '2', 'skipped': True}
2502 @mock.patch.object(market
.ReportStore
, "print_log")
2503 @mock.patch.object(market
.ReportStore
, "add_log")
2504 def test_log_orders(self
, add_log
, print_log
):
2505 report_store
= market
.ReportStore(self
.m
)
2507 order_mock1
= mock
.Mock()
2508 order_mock2
= mock
.Mock()
2510 order_mock1
.as_json
.return_value
= "order1"
2511 order_mock2
.as_json
.return_value
= "order2"
2513 orders
= [order_mock1
, order_mock2
]
2515 report_store
.log_orders(orders
, tick
="tick",
2516 only
="only", compute_value
="compute_value")
2518 print_log
.assert_called_once_with("[Orders]")
2519 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2521 add_log
.assert_called_with({
2524 'compute_value': 'compute_value',
2526 'orders': ['order1', 'order2']
2529 add_log
.reset_mock()
2530 def compute_value(x
, y
):
2532 report_store
.log_orders(orders
, tick
="tick",
2533 only
="only", compute_value
=compute_value
)
2534 add_log
.assert_called_with({
2537 'compute_value': 'def compute_value(x, y):\n return x[y]',
2539 'orders': ['order1', 'order2']
2543 @mock.patch.object(market
.ReportStore
, "print_log")
2544 @mock.patch.object(market
.ReportStore
, "add_log")
2545 def test_log_order(self
, add_log
, print_log
):
2546 report_store
= market
.ReportStore(self
.m
)
2547 order_mock
= mock
.Mock()
2548 order_mock
.as_json
.return_value
= "order"
2549 new_order_mock
= mock
.Mock()
2550 new_order_mock
.as_json
.return_value
= "new_order"
2551 order_mock
.__repr
__ = mock
.Mock()
2552 order_mock
.__repr
__.return_value
= "Order Mock"
2553 new_order_mock
.__repr
__ = mock
.Mock()
2554 new_order_mock
.__repr
__.return_value
= "New order Mock"
2556 with self
.subTest(finished
=True):
2557 report_store
.log_order(order_mock
, 1, finished
=True)
2558 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2559 add_log
.assert_called_once_with({
2564 'compute_value': None,
2568 add_log
.reset_mock()
2569 print_log
.reset_mock()
2571 with self
.subTest(update
="waiting"):
2572 report_store
.log_order(order_mock
, 1, update
="waiting")
2573 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2574 add_log
.assert_called_once_with({
2577 'update': 'waiting',
2579 'compute_value': None,
2583 add_log
.reset_mock()
2584 print_log
.reset_mock()
2585 with self
.subTest(update
="adjusting"):
2586 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
2587 report_store
.log_order(order_mock
, 3,
2588 update
="adjusting", new_order
=new_order_mock
,
2589 compute_value
=compute_value
)
2590 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2591 add_log
.assert_called_once_with({
2594 'update': 'adjusting',
2596 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
2597 'new_order': 'new_order'
2600 add_log
.reset_mock()
2601 print_log
.reset_mock()
2602 with self
.subTest(update
="market_fallback"):
2603 report_store
.log_order(order_mock
, 7,
2604 update
="market_fallback", new_order
=new_order_mock
)
2605 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2606 add_log
.assert_called_once_with({
2609 'update': 'market_fallback',
2611 'compute_value': None,
2612 'new_order': 'new_order'
2615 add_log
.reset_mock()
2616 print_log
.reset_mock()
2617 with self
.subTest(update
="market_adjusting"):
2618 report_store
.log_order(order_mock
, 17,
2619 update
="market_adjust", new_order
=new_order_mock
)
2620 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2621 add_log
.assert_called_once_with({
2624 'update': 'market_adjust',
2626 'compute_value': None,
2627 'new_order': 'new_order'
2630 @mock.patch.object(market
.ReportStore
, "print_log")
2631 @mock.patch.object(market
.ReportStore
, "add_log")
2632 def test_log_move_balances(self
, add_log
, print_log
):
2633 report_store
= market
.ReportStore(self
.m
)
2635 "BTC": portfolio
.Amount("BTC", 10),
2639 "BTC": portfolio
.Amount("BTC", 3),
2642 report_store
.log_move_balances(needed
, moving
)
2643 print_log
.assert_not_called()
2644 add_log
.assert_called_once_with({
2645 'type': 'move_balances',
2657 @mock.patch.object(market
.ReportStore
, "print_log")
2658 @mock.patch.object(market
.ReportStore
, "add_log")
2659 def test_log_http_request(self
, add_log
, print_log
):
2660 report_store
= market
.ReportStore(self
.m
)
2661 response
= mock
.Mock()
2662 response
.status_code
= 200
2663 response
.text
= "Hey"
2665 report_store
.log_http_request("method", "url", "body",
2666 "headers", response
)
2667 print_log
.assert_not_called()
2668 add_log
.assert_called_once_with({
2669 'type': 'http_request',
2673 'headers': 'headers',
2678 @mock.patch.object(market
.ReportStore
, "print_log")
2679 @mock.patch.object(market
.ReportStore
, "add_log")
2680 def test_log_error(self
, add_log
, print_log
):
2681 report_store
= market
.ReportStore(self
.m
)
2682 with self
.subTest(message
=None, exception
=None):
2683 report_store
.log_error("action")
2684 print_log
.assert_called_once_with("[Error] action")
2685 add_log
.assert_called_once_with({
2688 'exception_class': None,
2689 'exception_message': None,
2693 print_log
.reset_mock()
2694 add_log
.reset_mock()
2695 with self
.subTest(message
="Hey", exception
=None):
2696 report_store
.log_error("action", message
="Hey")
2697 print_log
.assert_has_calls([
2698 mock
.call("[Error] action"),
2701 add_log
.assert_called_once_with({
2704 'exception_class': None,
2705 'exception_message': None,
2709 print_log
.reset_mock()
2710 add_log
.reset_mock()
2711 with self
.subTest(message
=None, exception
=Exception("bouh")):
2712 report_store
.log_error("action", exception
=Exception("bouh"))
2713 print_log
.assert_has_calls([
2714 mock
.call("[Error] action"),
2715 mock
.call("\tException: bouh")
2717 add_log
.assert_called_once_with({
2720 'exception_class': "Exception",
2721 'exception_message': "bouh",
2725 print_log
.reset_mock()
2726 add_log
.reset_mock()
2727 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2728 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2729 print_log
.assert_has_calls([
2730 mock
.call("[Error] action"),
2731 mock
.call("\tException: bouh"),
2734 add_log
.assert_called_once_with({
2737 'exception_class': "Exception",
2738 'exception_message': "bouh",
2742 @mock.patch.object(market
.ReportStore
, "print_log")
2743 @mock.patch.object(market
.ReportStore
, "add_log")
2744 def test_log_debug_action(self
, add_log
, print_log
):
2745 report_store
= market
.ReportStore(self
.m
)
2746 report_store
.log_debug_action("Hey")
2748 print_log
.assert_called_once_with("[Debug] Hey")
2749 add_log
.assert_called_once_with({
2750 'type': 'debug_action',
2754 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2755 class HelperTest(WebMockTestCase
):
2756 def test_make_order(self
):
2757 self
.m
.get_ticker
.return_value
= {
2759 "average": D("0.1"),
2764 with self
.subTest(description
="nominal case"):
2765 helper
.make_order(self
.m
, 10, "ETH")
2767 self
.m
.report
.log_stage
.assert_has_calls([
2768 mock
.call("make_order_begin"),
2769 mock
.call("make_order_end"),
2771 self
.m
.balances
.fetch_balances
.assert_has_calls([
2772 mock
.call(tag
="make_order_begin"),
2773 mock
.call(tag
="make_order_end"),
2775 self
.m
.trades
.all
.append
.assert_called_once()
2776 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2777 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2778 self
.assertEqual(0, trade
.value_from
)
2779 self
.assertEqual("ETH", trade
.currency
)
2780 self
.assertEqual("BTC", trade
.base_currency
)
2781 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2782 self
.m
.trades
.run_orders
.assert_called_once_with()
2783 self
.m
.follow_orders
.assert_called_once_with()
2785 order
= trade
.orders
[0]
2786 self
.assertEqual(D("0.10"), order
.rate
)
2789 with self
.subTest(compute_value
="default"):
2790 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2791 compute_value
="ask")
2793 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2794 order
= trade
.orders
[0]
2795 self
.assertEqual(D("0.11"), order
.rate
)
2798 with self
.subTest(follow
=False):
2799 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2801 self
.m
.report
.log_stage
.assert_has_calls([
2802 mock
.call("make_order_begin"),
2803 mock
.call("make_order_end_not_followed"),
2805 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2807 self
.m
.trades
.all
.append
.assert_called_once()
2808 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2809 self
.assertEqual(0, trade
.value_from
)
2810 self
.assertEqual("ETH", trade
.currency
)
2811 self
.assertEqual("BTC", trade
.base_currency
)
2812 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2813 self
.m
.trades
.run_orders
.assert_called_once_with()
2814 self
.m
.follow_orders
.assert_not_called()
2815 self
.assertEqual(trade
.orders
[0], result
)
2818 with self
.subTest(base_currency
="USDT"):
2819 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2821 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2822 self
.assertEqual("BTC", trade
.currency
)
2823 self
.assertEqual("USDT", trade
.base_currency
)
2826 with self
.subTest(close_if_possible
=True):
2827 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2829 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2830 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2833 with self
.subTest(action
="dispose"):
2834 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2836 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2837 self
.assertEqual(0, trade
.value_to
)
2838 self
.assertEqual(1, trade
.value_from
.value
)
2839 self
.assertEqual("ETH", trade
.currency
)
2840 self
.assertEqual("BTC", trade
.base_currency
)
2843 with self
.subTest(compute_value
="default"):
2844 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2845 compute_value
="bid")
2847 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2848 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2850 def test_user_market(self
):
2851 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2852 mock
.patch("helper.main_parse_config") as main_parse_config
:
2853 with self
.subTest(debug
=False):
2854 main_parse_config
.return_value
= ["pg_config", "report_path"]
2855 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2856 m
= helper
.get_user_market("config_path.ini", 1)
2858 self
.assertIsInstance(m
, market
.Market
)
2859 self
.assertFalse(m
.debug
)
2861 with self
.subTest(debug
=True):
2862 main_parse_config
.return_value
= ["pg_config", "report_path"]
2863 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2864 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2866 self
.assertIsInstance(m
, market
.Market
)
2867 self
.assertTrue(m
.debug
)
2869 def test_main_store_report(self
):
2870 file_open
= mock
.mock_open()
2871 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2872 helper
.main_store_report(None, 1, self
.m
)
2873 file_open
.assert_not_called()
2875 file_open
= mock
.mock_open()
2876 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2877 mock
.patch
.object(helper
, "datetime") as time_mock
:
2878 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2879 self
.m
.report
.to_json
.return_value
= "json_content"
2881 helper
.main_store_report("present", 1, self
.m
)
2883 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2884 file_open().write
.assert_called_once_with("json_content")
2885 self
.m
.report
.to_json
.assert_called_once_with()
2887 with self
.subTest(file="error"),\
2888 mock
.patch("helper.open") as file_open
,\
2889 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2890 file_open
.side_effect
= FileNotFoundError
2892 helper
.main_store_report("error", 1, self
.m
)
2894 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2896 @mock.patch("helper.Processor.process")
2897 def test_main_process_market(self
, process
):
2898 with self
.subTest(before
=False, after
=False):
2900 helper
.main_process_market(m
, None)
2902 process
.assert_not_called()
2904 process
.reset_mock()
2905 with self
.subTest(before
=True, after
=False):
2906 helper
.main_process_market(m
, None, before
=True)
2908 process
.assert_called_once_with("sell_all", steps
="before")
2910 process
.reset_mock()
2911 with self
.subTest(before
=False, after
=True):
2912 helper
.main_process_market(m
, None, after
=True)
2914 process
.assert_called_once_with("sell_all", steps
="after")
2916 process
.reset_mock()
2917 with self
.subTest(before
=True, after
=True):
2918 helper
.main_process_market(m
, None, before
=True, after
=True)
2920 process
.assert_has_calls([
2921 mock
.call("sell_all", steps
="before"),
2922 mock
.call("sell_all", steps
="after"),
2925 process
.reset_mock()
2926 with self
.subTest(action
="print_balances"),\
2927 mock
.patch("helper.print_balances") as print_balances
:
2928 helper
.main_process_market("user", ["print_balances"])
2930 process
.assert_not_called()
2931 print_balances
.assert_called_once_with("user")
2933 with self
.subTest(action
="print_orders"),\
2934 mock
.patch("helper.print_orders") as print_orders
,\
2935 mock
.patch("helper.print_balances") as print_balances
:
2936 helper
.main_process_market("user", ["print_orders", "print_balances"])
2938 process
.assert_not_called()
2939 print_orders
.assert_called_once_with("user")
2940 print_balances
.assert_called_once_with("user")
2942 with self
.subTest(action
="unknown"),\
2943 self
.assertRaises(NotImplementedError):
2944 helper
.main_process_market("user", ["unknown"])
2946 @mock.patch.object(helper
, "psycopg2")
2947 def test_fetch_markets(self
, psycopg2
):
2948 connect_mock
= mock
.Mock()
2949 cursor_mock
= mock
.MagicMock()
2950 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2952 connect_mock
.cursor
.return_value
= cursor_mock
2953 psycopg2
.connect
.return_value
= connect_mock
2955 with self
.subTest(user
=None):
2956 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2958 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2959 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2961 self
.assertEqual(["row_1", "row_2"], rows
)
2963 psycopg2
.connect
.reset_mock()
2964 cursor_mock
.execute
.reset_mock()
2965 with self
.subTest(user
=1):
2966 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
2968 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2969 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
2971 self
.assertEqual(["row_1", "row_2"], rows
)
2973 @mock.patch.object(helper
.sys
, "exit")
2974 def test_main_parse_args(self
, exit
):
2975 with self
.subTest(config
="config.ini"):
2976 args
= helper
.main_parse_args([])
2977 self
.assertEqual("config.ini", args
.config
)
2978 self
.assertFalse(args
.before
)
2979 self
.assertFalse(args
.after
)
2980 self
.assertFalse(args
.debug
)
2982 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
2983 self
.assertTrue(args
.before
)
2984 self
.assertTrue(args
.after
)
2985 self
.assertTrue(args
.debug
)
2987 exit
.assert_not_called()
2989 with self
.subTest(config
="inexistant"),\
2990 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2991 args
= helper
.main_parse_args(["--config", "foo.bar"])
2992 exit
.assert_called_once_with(1)
2993 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
2995 @mock.patch.object(helper
.sys
, "exit")
2996 @mock.patch("helper.configparser")
2997 @mock.patch("helper.os")
2998 def test_main_parse_config(self
, os
, configparser
, exit
):
2999 with self
.subTest(pg_config
=True, report_path
=None):
3000 config_mock
= mock
.MagicMock()
3001 configparser
.ConfigParser
.return_value
= config_mock
3002 def config(element
):
3003 return element
== "postgresql"
3005 config_mock
.__contains
__.side_effect
= config
3006 config_mock
.__getitem
__.return_value
= "pg_config"
3008 result
= helper
.main_parse_config("configfile")
3010 config_mock
.read
.assert_called_with("configfile")
3012 self
.assertEqual(["pg_config", None], result
)
3014 with self
.subTest(pg_config
=True, report_path
="present"):
3015 config_mock
= mock
.MagicMock()
3016 configparser
.ConfigParser
.return_value
= config_mock
3018 config_mock
.__contains
__.return_value
= True
3019 config_mock
.__getitem
__.side_effect
= [
3020 {"report_path": "report_path"}
,
3021 {"report_path": "report_path"}
,
3025 os
.path
.exists
.return_value
= False
3026 result
= helper
.main_parse_config("configfile")
3028 config_mock
.read
.assert_called_with("configfile")
3029 self
.assertEqual(["pg_config", "report_path"], result
)
3030 os
.path
.exists
.assert_called_once_with("report_path")
3031 os
.makedirs
.assert_called_once_with("report_path")
3033 with self
.subTest(pg_config
=False),\
3034 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3035 config_mock
= mock
.MagicMock()
3036 configparser
.ConfigParser
.return_value
= config_mock
3037 result
= helper
.main_parse_config("configfile")
3039 config_mock
.read
.assert_called_with("configfile")
3040 exit
.assert_called_once_with(1)
3041 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
3044 def test_print_orders(self
):
3045 helper
.print_orders(self
.m
)
3047 self
.m
.report
.log_stage
.assert_called_with("print_orders")
3048 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
3049 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3050 compute_value
="average")
3051 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3053 def test_print_balances(self
):
3054 self
.m
.balances
.in_currency
.return_value
= {
3055 "BTC": portfolio
.Amount("BTC", "0.65"),
3056 "ETH": portfolio
.Amount("BTC", "0.3"),
3059 helper
.print_balances(self
.m
)
3061 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
3062 self
.m
.balances
.fetch_balances
.assert_called_with()
3063 self
.m
.report
.print_log
.assert_has_calls([
3064 mock
.call("total:"),
3065 mock
.call(portfolio
.Amount("BTC", "0.95")),
3068 @unittest.skipUnless("unit" in limits
, "Unit skipped")
3069 class ProcessorTest(WebMockTestCase
):
3070 def test_values(self
):
3071 processor
= helper
.Processor(self
.m
)
3073 self
.assertEqual(self
.m
, processor
.market
)
3075 def test_run_action(self
):
3076 processor
= helper
.Processor(self
.m
)
3078 with mock
.patch
.object(processor
, "parse_args") as parse_args
:
3079 method_mock
= mock
.Mock()
3080 parse_args
.return_value
= [method_mock
, { "foo": "bar" }
]
3082 processor
.run_action("foo", "bar", "baz")
3084 parse_args
.assert_called_with("foo", "bar", "baz")
3086 method_mock
.assert_called_with(foo
="bar")
3088 processor
.run_action("wait_for_recent", "bar", "baz")
3090 method_mock
.assert_called_with(self
.m
, foo
="bar")
3092 def test_select_step(self
):
3093 processor
= helper
.Processor(self
.m
)
3095 scenario
= processor
.scenarios
["sell_all"]
3097 self
.assertEqual(scenario
, processor
.select_steps(scenario
, "all"))
3098 self
.assertEqual(["all_sell"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "before"))))
3099 self
.assertEqual(["wait", "all_buy"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "after"))))
3100 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, 2))))
3101 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "wait"))))
3103 with self
.assertRaises(TypeError):
3104 processor
.select_steps(scenario
, ["wait"])
3106 @mock.patch("helper.Processor.process_step")
3107 def test_process(self
, process_step
):
3108 processor
= helper
.Processor(self
.m
)
3110 processor
.process("sell_all", foo
="bar")
3111 self
.assertEqual(3, process_step
.call_count
)
3113 steps
= list(map(lambda x
: x
[1][1]["name"], process_step
.mock_calls
))
3114 scenario_names
= list(map(lambda x
: x
[1][0], process_step
.mock_calls
))
3115 kwargs
= list(map(lambda x
: x
[1][2], process_step
.mock_calls
))
3116 self
.assertEqual(["all_sell", "wait", "all_buy"], steps
)
3117 self
.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names
)
3118 self
.assertEqual([{"foo":"bar"}
, {"foo":"bar"}
, {"foo":"bar"}
], kwargs
)
3120 process_step
.reset_mock()
3122 processor
.process("sell_needed", steps
=["before", "after"])
3123 self
.assertEqual(3, process_step
.call_count
)
3125 def test_method_arguments(self
):
3126 ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
3127 m
= market
.Market(ccxt
)
3129 processor
= helper
.Processor(m
)
3131 method
, arguments
= processor
.method_arguments("wait_for_recent")
3132 self
.assertEqual(portfolio
.Portfolio
.wait_for_recent
, method
)
3133 self
.assertEqual(["delta"], arguments
)
3135 method
, arguments
= processor
.method_arguments("prepare_trades")
3136 self
.assertEqual(m
.prepare_trades
, method
)
3137 self
.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments
)
3139 method
, arguments
= processor
.method_arguments("prepare_orders")
3140 self
.assertEqual(m
.trades
.prepare_orders
, method
)
3142 method
, arguments
= processor
.method_arguments("move_balances")
3143 self
.assertEqual(m
.move_balances
, method
)
3145 method
, arguments
= processor
.method_arguments("run_orders")
3146 self
.assertEqual(m
.trades
.run_orders
, method
)
3148 method
, arguments
= processor
.method_arguments("follow_orders")
3149 self
.assertEqual(m
.follow_orders
, method
)
3151 method
, arguments
= processor
.method_arguments("close_trades")
3152 self
.assertEqual(m
.trades
.close_trades
, method
)
3154 def test_process_step(self
):
3155 processor
= helper
.Processor(self
.m
)
3157 with mock
.patch
.object(processor
, "run_action") as run_action
:
3158 step
= processor
.scenarios
["sell_needed"][1]
3160 processor
.process_step("foo", step
, {"foo":"bar"}
)
3162 self
.m
.report
.log_stage
.assert_has_calls([
3163 mock
.call("process_foo__1_sell_begin"),
3164 mock
.call("process_foo__1_sell_end"),
3166 self
.m
.balances
.fetch_balances
.assert_has_calls([
3167 mock
.call(tag
="process_foo__1_sell_begin"),
3168 mock
.call(tag
="process_foo__1_sell_end"),
3171 self
.assertEqual(5, run_action
.call_count
)
3173 run_action
.assert_has_calls([
3174 mock
.call('prepare_trades', {}, {'foo': 'bar'}
),
3175 mock
.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}
, {'foo': 'bar'}
),
3176 mock
.call('run_orders', {}, {'foo': 'bar'}
),
3177 mock
.call('follow_orders', {}, {'foo': 'bar'}
),
3178 mock
.call('close_trades', {}, {'foo': 'bar'}
),
3182 with mock
.patch
.object(processor
, "run_action") as run_action
:
3183 step
= processor
.scenarios
["sell_needed"][0]
3185 processor
.process_step("foo", step
, {"foo":"bar"}
)
3186 self
.m
.balances
.fetch_balances
.assert_not_called()
3188 def test_parse_args(self
):
3189 processor
= helper
.Processor(self
.m
)
3191 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3192 method_mock
= mock
.Mock()
3193 method_arguments
.return_value
= [
3197 method
, args
= processor
.parse_args("action", {"foo": "bar", "foo2": "bar"}
, {"foo": "bar2", "bla": "bla"}
)
3199 self
.assertEqual(method_mock
, method
)
3200 self
.assertEqual({"foo": "bar2", "foo2": "bar"}
, args
)
3202 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3203 method_mock
= mock
.Mock()
3204 method_arguments
.return_value
= [
3208 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {})
3210 self
.assertEqual(1, len(args
["repartition"]))
3211 self
.assertIn("BTC", args
["repartition"])
3213 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3214 method_mock
= mock
.Mock()
3215 method_arguments
.return_value
= [
3217 ["repartition", "base_currency"]
3219 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {"base_currency": "USDT"}
)
3221 self
.assertEqual(1, len(args
["repartition"]))
3222 self
.assertIn("USDT", args
["repartition"])
3224 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3225 method_mock
= mock
.Mock()
3226 method_arguments
.return_value
= [
3228 ["repartition", "base_currency"]
3230 method
, args
= processor
.parse_args("action", {"repartition": { "ETH": 1 }
}, {"base_currency": "USDT"}
)
3232 self
.assertEqual(1, len(args
["repartition"]))
3233 self
.assertIn("ETH", args
["repartition"])
3236 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3237 class AcceptanceTest(WebMockTestCase
):
3238 @unittest.expectedFailure
3239 def test_success_sell_only_necessary(self
):
3240 # FIXME: catch stdout
3241 self
.m
.report
.verbose_print
= False
3244 "exchange_free": D("1.0"),
3245 "exchange_used": D("0.0"),
3246 "exchange_total": D("1.0"),
3250 "exchange_free": D("4.0"),
3251 "exchange_used": D("0.0"),
3252 "exchange_total": D("4.0"),
3256 "exchange_free": D("1000.0"),
3257 "exchange_used": D("0.0"),
3258 "exchange_total": D("1000.0"),
3259 "total": D("1000.0"),
3263 "ETH": (D("0.25"), "long"),
3264 "ETC": (D("0.25"), "long"),
3265 "BTC": (D("0.4"), "long"),
3266 "BTD": (D("0.01"), "short"),
3267 "B2X": (D("0.04"), "long"),
3268 "USDT": (D("0.05"), "long"),
3271 def fetch_ticker(symbol
):
3272 if symbol
== "ETH/BTC":
3274 "symbol": "ETH/BTC",
3278 if symbol
== "ETC/BTC":
3280 "symbol": "ETC/BTC",
3284 if symbol
== "XVG/BTC":
3286 "symbol": "XVG/BTC",
3287 "bid": D("0.00003"),
3290 if symbol
== "BTD/BTC":
3292 "symbol": "BTD/BTC",
3296 if symbol
== "B2X/BTC":
3298 "symbol": "B2X/BTC",
3302 if symbol
== "USDT/BTC":
3303 raise helper
.ExchangeError
3304 if symbol
== "BTC/USDT":
3306 "symbol": "BTC/USDT",
3310 self
.fail("Shouldn't have been called with {}".format(symbol
))
3312 market
= mock
.Mock()
3313 market
.fetch_all_balances
.return_value
= fetch_balance
3314 market
.fetch_ticker
.side_effect
= fetch_ticker
3315 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3317 helper
.prepare_trades(market
)
3319 balances
= portfolio
.BalanceStore
.all
3320 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3321 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3322 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3325 trades
= portfolio
.TradeStore
.all
3326 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3327 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3328 self
.assertEqual("dispose", trades
[0].action
)
3330 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3331 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3332 self
.assertEqual("acquire", trades
[1].action
)
3334 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3335 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3336 self
.assertEqual("dispose", trades
[2].action
)
3338 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3339 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3340 self
.assertEqual("acquire", trades
[3].action
)
3342 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3343 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3344 self
.assertEqual("acquire", trades
[4].action
)
3346 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3347 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3348 self
.assertEqual("acquire", trades
[5].action
)
3351 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3353 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3354 self
.assertEqual(2, len(all_orders
))
3355 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3356 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3357 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3358 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3361 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3362 self
.assertEqual("limit", type)
3363 if symbol
== "ETH/BTC":
3364 self
.assertEqual("sell", action
)
3365 self
.assertEqual(D('0.66666666'), amount
)
3366 self
.assertEqual(D("0.14014"), price
)
3367 elif symbol
== "XVG/BTC":
3368 self
.assertEqual("sell", action
)
3369 self
.assertEqual(1000, amount
)
3370 self
.assertEqual(D("0.00003003"), price
)
3372 self
.fail("I shouldn't have been called")
3377 market
.create_order
.side_effect
= create_order
3378 market
.order_precision
.return_value
= 8
3381 portfolio
.TradeStore
.run_orders()
3383 self
.assertEqual("open", all_orders
[0].status
)
3384 self
.assertEqual("open", all_orders
[1].status
)
3386 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3387 market
.privatePostReturnOrderTrades
.return_value
= [
3389 "tradeID": 42, "type": "buy", "fee": "0.0015",
3390 "date": "2017-12-30 12:00:12", "rate": "0.1",
3391 "amount": "10", "total": "1"
3394 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3396 helper
.follow_orders(verbose
=False)
3398 sleep
.assert_called_with(30)
3400 for order
in all_orders
:
3401 self
.assertEqual("closed", order
.status
)
3405 "exchange_free": D("1.0") / 3,
3406 "exchange_used": D("0.0"),
3407 "exchange_total": D("1.0") / 3,
3409 "total": D("1.0") / 3,
3412 "exchange_free": D("0.134"),
3413 "exchange_used": D("0.0"),
3414 "exchange_total": D("0.134"),
3416 "total": D("0.134"),
3419 "exchange_free": D("4.0"),
3420 "exchange_used": D("0.0"),
3421 "exchange_total": D("4.0"),
3426 "exchange_free": D("0.0"),
3427 "exchange_used": D("0.0"),
3428 "exchange_total": D("0.0"),
3433 market
.fetch_all_balances
.return_value
= fetch_balance
3435 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3437 helper
.prepare_trades(market
, only
="acquire", compute_value
="average")
3439 balances
= portfolio
.BalanceStore
.all
3440 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3441 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3442 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3443 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3446 trades
= portfolio
.TradeStore
.all
3447 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3448 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3449 self
.assertEqual("dispose", trades
[0].action
)
3451 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3452 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3453 self
.assertEqual("acquire", trades
[1].action
)
3455 self
.assertNotIn("BTC", trades
)
3457 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3458 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3459 self
.assertEqual("dispose", trades
[2].action
)
3461 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3462 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3463 self
.assertEqual("acquire", trades
[3].action
)
3465 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3466 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3467 self
.assertEqual("acquire", trades
[4].action
)
3469 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3470 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3471 self
.assertEqual("acquire", trades
[5].action
)
3474 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3476 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3477 self
.assertEqual(4, len(all_orders
))
3478 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3479 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3480 self
.assertEqual("buy", all_orders
[0].action
)
3481 self
.assertEqual("long", all_orders
[0].trade_type
)
3483 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3484 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3485 self
.assertEqual("sell", all_orders
[1].action
)
3486 self
.assertEqual("short", all_orders
[1].trade_type
)
3488 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3489 self
.assertAlmostEqual(0, diff
.value
)
3490 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3491 self
.assertEqual("buy", all_orders
[2].action
)
3492 self
.assertEqual("long", all_orders
[2].trade_type
)
3494 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3495 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3496 self
.assertEqual("sell", all_orders
[3].action
)
3497 self
.assertEqual("long", all_orders
[3].trade_type
)
3501 # Move balances to margin
3505 # portfolio.TradeStore.run_orders()
3507 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3509 helper
.follow_orders(verbose
=False)
3511 sleep
.assert_called_with(30)
3513 if __name__
== '__main__':