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
.is_fullfiled
= False
995 trade_mock2
.is_fullfiled
= False
996 trade_mock3
.is_fullfiled
= True
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_pending(self
):
1104 trade_mock1
= mock
.Mock()
1105 trade_mock1
.is_fullfiled
= False
1106 trade_mock2
= mock
.Mock()
1107 trade_mock2
.is_fullfiled
= False
1108 trade_mock3
= mock
.Mock()
1109 trade_mock3
.is_fullfiled
= True
1111 trade_store
= market
.TradeStore(self
.m
)
1113 trade_store
.all
.append(trade_mock1
)
1114 trade_store
.all
.append(trade_mock2
)
1115 trade_store
.all
.append(trade_mock3
)
1117 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
1119 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1120 class BalanceStoreTest(WebMockTestCase
):
1122 super(BalanceStoreTest
, self
).setUp()
1124 self
.fetch_balance
= {
1128 "exchange_total": 0,
1132 "exchange_free": D("6.0"),
1133 "exchange_used": D("1.2"),
1134 "exchange_total": D("7.2"),
1138 "exchange_free": 16,
1140 "exchange_total": 16,
1146 "exchange_total": 0,
1147 "margin_total": D("-1.0"),
1152 def test_in_currency(self
):
1153 self
.m
.get_ticker
.return_value
= {
1156 "average": D("0.1"),
1159 balance_store
= market
.BalanceStore(self
.m
)
1160 balance_store
.all
= {
1161 "BTC": portfolio
.Balance("BTC", {
1163 "exchange_total":"0.65",
1164 "exchange_free": "0.35",
1165 "exchange_used": "0.30"}),
1166 "ETH": portfolio
.Balance("ETH", {
1168 "exchange_total": 3,
1170 "exchange_used": 0}),
1173 amounts
= balance_store
.in_currency("BTC")
1174 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1175 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1176 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1177 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1179 self
.m
.report
.log_tickers
.reset_mock()
1181 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1182 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1183 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1184 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1186 self
.m
.report
.log_tickers
.reset_mock()
1188 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1189 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1190 self
.assertEqual(0, amounts
["ETH"].value
)
1191 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1192 "bid", "exchange_used")
1193 self
.m
.report
.log_tickers
.reset_mock()
1195 def test_fetch_balances(self
):
1196 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1198 balance_store
= market
.BalanceStore(self
.m
)
1200 balance_store
.fetch_balances()
1201 self
.assertNotIn("ETC", balance_store
.currencies())
1202 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1204 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1205 "exchange_total": "1", "exchange_free": "0",
1206 "exchange_used": "1" })
1207 balance_store
.fetch_balances(tag
="foo")
1208 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1209 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1210 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1212 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1213 def test_dispatch_assets(self
, repartition
):
1214 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1216 balance_store
= market
.BalanceStore(self
.m
)
1217 balance_store
.fetch_balances()
1219 self
.assertNotIn("XEM", balance_store
.currencies())
1221 repartition_hash
= {
1222 "XEM": (D("0.75"), "long"),
1223 "BTC": (D("0.26"), "long"),
1224 "DASH": (D("0.10"), "short"),
1226 repartition
.return_value
= repartition_hash
1228 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1229 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1230 self
.assertIn("XEM", balance_store
.currencies())
1231 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1232 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1233 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1234 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1235 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1236 "11.1"), amounts
, "medium", repartition_hash
)
1238 def test_currencies(self
):
1239 balance_store
= market
.BalanceStore(self
.m
)
1241 balance_store
.all
= {
1242 "BTC": portfolio
.Balance("BTC", {
1244 "exchange_total":"0.65",
1245 "exchange_free": "0.35",
1246 "exchange_used": "0.30"}),
1247 "ETH": portfolio
.Balance("ETH", {
1249 "exchange_total": 3,
1251 "exchange_used": 0}),
1253 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1255 def test_as_json(self
):
1256 balance_mock1
= mock
.Mock()
1257 balance_mock1
.as_json
.return_value
= 1
1259 balance_mock2
= mock
.Mock()
1260 balance_mock2
.as_json
.return_value
= 2
1262 balance_store
= market
.BalanceStore(self
.m
)
1263 balance_store
.all
= {
1264 "BTC": balance_mock1
,
1265 "ETH": balance_mock2
,
1268 as_json
= balance_store
.as_json()
1269 self
.assertEqual(1, as_json
["BTC"])
1270 self
.assertEqual(2, as_json
["ETH"])
1273 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1274 class ComputationTest(WebMockTestCase
):
1275 def test_compute_value(self
):
1276 compute
= mock
.Mock()
1277 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1278 compute
.assert_called_with("foo", "ask")
1280 compute
.reset_mock()
1281 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1282 compute
.assert_called_with("foo", "bid")
1284 compute
.reset_mock()
1285 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1286 compute
.assert_called_with("foo", "ask")
1288 compute
.reset_mock()
1289 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1290 compute
.assert_called_with("foo", "bid")
1292 compute
.reset_mock()
1293 portfolio
.Computation
.computations
["test"] = compute
1294 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1295 compute
.assert_called_with("foo", "bid")
1298 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1299 class TradeTest(WebMockTestCase
):
1301 def test_values_assertion(self
):
1302 value_from
= portfolio
.Amount("BTC", "1.0")
1303 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1304 value_to
= portfolio
.Amount("BTC", "1.0")
1305 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1306 self
.assertEqual("BTC", trade
.base_currency
)
1307 self
.assertEqual("ETH", trade
.currency
)
1308 self
.assertEqual(self
.m
, trade
.market
)
1310 with self
.assertRaises(AssertionError):
1311 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
1312 with self
.assertRaises(AssertionError):
1313 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1314 with self
.assertRaises(AssertionError):
1315 value_from
.currency
= "ETH"
1316 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1317 value_from
.currency
= "BTC"
1318 with self
.assertRaises(AssertionError):
1319 value_from2
= portfolio
.Amount("BTC", "1.0")
1320 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
1322 value_from
= portfolio
.Amount("BTC", 0)
1323 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1324 self
.assertEqual(0, trade
.value_from
.linked_to
)
1326 def test_action(self
):
1327 value_from
= portfolio
.Amount("BTC", "1.0")
1328 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1329 value_to
= portfolio
.Amount("BTC", "1.0")
1330 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1332 self
.assertIsNone(trade
.action
)
1334 value_from
= portfolio
.Amount("BTC", "1.0")
1335 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1336 value_to
= portfolio
.Amount("BTC", "2.0")
1337 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1339 self
.assertIsNone(trade
.action
)
1341 value_from
= portfolio
.Amount("BTC", "0.5")
1342 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1343 value_to
= portfolio
.Amount("BTC", "1.0")
1344 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1346 self
.assertEqual("acquire", trade
.action
)
1348 value_from
= portfolio
.Amount("BTC", "0")
1349 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1350 value_to
= portfolio
.Amount("BTC", "-1.0")
1351 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1353 self
.assertEqual("acquire", trade
.action
)
1355 def test_order_action(self
):
1356 value_from
= portfolio
.Amount("BTC", "0.5")
1357 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1358 value_to
= portfolio
.Amount("BTC", "1.0")
1359 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1361 self
.assertEqual("buy", trade
.order_action(False))
1362 self
.assertEqual("sell", trade
.order_action(True))
1364 value_from
= portfolio
.Amount("BTC", "0")
1365 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1366 value_to
= portfolio
.Amount("BTC", "-1.0")
1367 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1369 self
.assertEqual("sell", trade
.order_action(False))
1370 self
.assertEqual("buy", trade
.order_action(True))
1372 def test_trade_type(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("long", trade
.trade_type
)
1380 value_from
= portfolio
.Amount("BTC", "0")
1381 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1382 value_to
= portfolio
.Amount("BTC", "-1.0")
1383 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1385 self
.assertEqual("short", trade
.trade_type
)
1387 def test_is_fullfiled(self
):
1388 value_from
= portfolio
.Amount("BTC", "0.5")
1389 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1390 value_to
= portfolio
.Amount("BTC", "1.0")
1391 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1393 order1
= mock
.Mock()
1394 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1396 order2
= mock
.Mock()
1397 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1398 trade
.orders
.append(order1
)
1399 trade
.orders
.append(order2
)
1401 self
.assertFalse(trade
.is_fullfiled
)
1403 order3
= mock
.Mock()
1404 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1405 trade
.orders
.append(order3
)
1407 self
.assertTrue(trade
.is_fullfiled
)
1409 def test_filled_amount(self
):
1410 value_from
= portfolio
.Amount("BTC", "0.5")
1411 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1412 value_to
= portfolio
.Amount("BTC", "1.0")
1413 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1415 order1
= mock
.Mock()
1416 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1418 order2
= mock
.Mock()
1419 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1420 trade
.orders
.append(order1
)
1421 trade
.orders
.append(order2
)
1423 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1424 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1425 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1427 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1428 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1429 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1431 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1432 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1433 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1435 @mock.patch.object(portfolio
.Computation
, "compute_value")
1436 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1437 @mock.patch.object(portfolio
, "Order")
1438 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1439 Order
.return_value
= "Order"
1441 with self
.subTest(desc
="Nothing to do"):
1442 value_from
= portfolio
.Amount("BTC", "10")
1443 value_from
.rate
= D("0.1")
1444 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1445 value_to
= portfolio
.Amount("BTC", "10")
1446 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1448 trade
.prepare_order()
1450 filled_amount
.assert_not_called()
1451 compute_value
.assert_not_called()
1452 self
.assertEqual(0, len(trade
.orders
))
1453 Order
.assert_not_called()
1455 self
.m
.get_ticker
.return_value
= { "inverted": False }
1456 with self
.subTest(desc
="Already filled"):
1457 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1458 compute_value
.return_value
= D("0.125")
1460 value_from
= portfolio
.Amount("BTC", "10")
1461 value_from
.rate
= D("0.1")
1462 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1463 value_to
= portfolio
.Amount("BTC", "0")
1464 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1466 trade
.prepare_order()
1468 filled_amount
.assert_called_with(in_base_currency
=False)
1469 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1470 self
.assertEqual(0, len(trade
.orders
))
1471 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1472 Order
.assert_not_called()
1474 with self
.subTest(action
="dispose", inverted
=False):
1475 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1476 compute_value
.return_value
= D("0.125")
1478 value_from
= portfolio
.Amount("BTC", "10")
1479 value_from
.rate
= D("0.1")
1480 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1481 value_to
= portfolio
.Amount("BTC", "1")
1482 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1484 trade
.prepare_order()
1486 filled_amount
.assert_called_with(in_base_currency
=False)
1487 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1488 self
.assertEqual(1, len(trade
.orders
))
1489 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1490 D("0.125"), "BTC", "long", self
.m
,
1491 trade
, close_if_possible
=False)
1493 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1494 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1495 compute_value
.return_value
= D("0.125")
1497 value_from
= portfolio
.Amount("BTC", "10")
1498 value_from
.rate
= D("0.1")
1499 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1500 value_to
= portfolio
.Amount("BTC", "1")
1501 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1503 trade
.prepare_order(close_if_possible
=True)
1505 filled_amount
.assert_called_with(in_base_currency
=False)
1506 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1507 self
.assertEqual(1, len(trade
.orders
))
1508 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1509 D("0.125"), "BTC", "long", self
.m
,
1510 trade
, close_if_possible
=True)
1512 with self
.subTest(action
="acquire", inverted
=False):
1513 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1514 compute_value
.return_value
= D("0.125")
1516 value_from
= portfolio
.Amount("BTC", "1")
1517 value_from
.rate
= D("0.1")
1518 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1519 value_to
= portfolio
.Amount("BTC", "10")
1520 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1522 trade
.prepare_order()
1524 filled_amount
.assert_called_with(in_base_currency
=True)
1525 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1526 self
.assertEqual(1, len(trade
.orders
))
1528 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1529 D("0.125"), "BTC", "long", self
.m
,
1530 trade
, close_if_possible
=False)
1532 with self
.subTest(close_if_possible
=True):
1533 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1534 compute_value
.return_value
= D("0.125")
1536 value_from
= portfolio
.Amount("BTC", "10")
1537 value_from
.rate
= D("0.1")
1538 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1539 value_to
= portfolio
.Amount("BTC", "0")
1540 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1542 trade
.prepare_order()
1544 filled_amount
.assert_called_with(in_base_currency
=False)
1545 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1546 self
.assertEqual(1, len(trade
.orders
))
1547 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1548 D("0.125"), "BTC", "long", self
.m
,
1549 trade
, close_if_possible
=True)
1551 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1552 with self
.subTest(action
="dispose", inverted
=True):
1553 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1554 compute_value
.return_value
= D("125")
1556 value_from
= portfolio
.Amount("BTC", "10")
1557 value_from
.rate
= D("0.01")
1558 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1559 value_to
= portfolio
.Amount("BTC", "1")
1560 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1562 trade
.prepare_order(compute_value
="foo")
1564 filled_amount
.assert_called_with(in_base_currency
=True)
1565 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1566 self
.assertEqual(1, len(trade
.orders
))
1567 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1568 D("125"), "FOO", "long", self
.m
,
1569 trade
, close_if_possible
=False)
1571 with self
.subTest(action
="acquire", inverted
=True):
1572 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1573 compute_value
.return_value
= D("125")
1575 value_from
= portfolio
.Amount("BTC", "1")
1576 value_from
.rate
= D("0.01")
1577 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1578 value_to
= portfolio
.Amount("BTC", "10")
1579 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1581 trade
.prepare_order(compute_value
="foo")
1583 filled_amount
.assert_called_with(in_base_currency
=False)
1584 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1585 self
.assertEqual(1, len(trade
.orders
))
1586 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1587 D("125"), "FOO", "long", self
.m
,
1588 trade
, close_if_possible
=False)
1591 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1592 def test_update_order(self
, prepare_order
):
1593 order_mock
= mock
.Mock()
1594 new_order_mock
= mock
.Mock()
1596 value_from
= portfolio
.Amount("BTC", "0.5")
1597 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1598 value_to
= portfolio
.Amount("BTC", "1.0")
1599 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1600 prepare_order
.return_value
= new_order_mock
1602 for i
in [0, 1, 3, 4, 6]:
1603 with self
.subTest(tick
=i
):
1604 trade
.update_order(order_mock
, i
)
1605 order_mock
.cancel
.assert_not_called()
1606 new_order_mock
.run
.assert_not_called()
1607 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1608 update
="waiting", compute_value
=None, new_order
=None)
1610 order_mock
.reset_mock()
1611 new_order_mock
.reset_mock()
1613 self
.m
.report
.log_order
.reset_mock()
1615 trade
.update_order(order_mock
, 2)
1616 order_mock
.cancel
.assert_called()
1617 new_order_mock
.run
.assert_called()
1618 prepare_order
.assert_called()
1619 self
.m
.report
.log_order
.assert_called()
1620 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1622 mock
.call(order_mock
, 2, update
="adjusting",
1623 compute_value
=mock
.ANY
,
1624 new_order
=new_order_mock
),
1625 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1627 self
.m
.report
.log_order
.assert_has_calls(calls
)
1629 order_mock
.reset_mock()
1630 new_order_mock
.reset_mock()
1632 self
.m
.report
.log_order
.reset_mock()
1634 trade
.update_order(order_mock
, 5)
1635 order_mock
.cancel
.assert_called()
1636 new_order_mock
.run
.assert_called()
1637 prepare_order
.assert_called()
1638 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1639 self
.m
.report
.log_order
.assert_called()
1641 mock
.call(order_mock
, 5, update
="adjusting",
1642 compute_value
=mock
.ANY
,
1643 new_order
=new_order_mock
),
1644 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1646 self
.m
.report
.log_order
.assert_has_calls(calls
)
1648 order_mock
.reset_mock()
1649 new_order_mock
.reset_mock()
1651 self
.m
.report
.log_order
.reset_mock()
1653 trade
.update_order(order_mock
, 7)
1654 order_mock
.cancel
.assert_called()
1655 new_order_mock
.run
.assert_called()
1656 prepare_order
.assert_called_with(compute_value
="default")
1657 self
.m
.report
.log_order
.assert_called()
1658 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1660 mock
.call(order_mock
, 7, update
="market_fallback",
1661 compute_value
='default',
1662 new_order
=new_order_mock
),
1663 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1665 self
.m
.report
.log_order
.assert_has_calls(calls
)
1667 order_mock
.reset_mock()
1668 new_order_mock
.reset_mock()
1670 self
.m
.report
.log_order
.reset_mock()
1672 for i
in [10, 13, 16]:
1673 with self
.subTest(tick
=i
):
1674 trade
.update_order(order_mock
, i
)
1675 order_mock
.cancel
.assert_called()
1676 new_order_mock
.run
.assert_called()
1677 prepare_order
.assert_called_with(compute_value
="default")
1678 self
.m
.report
.log_order
.assert_called()
1679 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1681 mock
.call(order_mock
, i
, update
="market_adjust",
1682 compute_value
='default',
1683 new_order
=new_order_mock
),
1684 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1686 self
.m
.report
.log_order
.assert_has_calls(calls
)
1688 order_mock
.reset_mock()
1689 new_order_mock
.reset_mock()
1691 self
.m
.report
.log_order
.reset_mock()
1693 for i
in [8, 9, 11, 12]:
1694 with self
.subTest(tick
=i
):
1695 trade
.update_order(order_mock
, i
)
1696 order_mock
.cancel
.assert_not_called()
1697 new_order_mock
.run
.assert_not_called()
1698 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1699 compute_value
=None, new_order
=None)
1701 order_mock
.reset_mock()
1702 new_order_mock
.reset_mock()
1704 self
.m
.report
.log_order
.reset_mock()
1707 def test_print_with_order(self
):
1708 value_from
= portfolio
.Amount("BTC", "0.5")
1709 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1710 value_to
= portfolio
.Amount("BTC", "1.0")
1711 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1713 order_mock1
= mock
.Mock()
1714 order_mock1
.__repr__
= mock
.Mock()
1715 order_mock1
.__repr__
.return_value
= "Mock 1"
1716 order_mock2
= mock
.Mock()
1717 order_mock2
.__repr__
= mock
.Mock()
1718 order_mock2
.__repr__
.return_value
= "Mock 2"
1719 order_mock1
.mouvements
= []
1720 mouvement_mock1
= mock
.Mock()
1721 mouvement_mock1
.__repr__
= mock
.Mock()
1722 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1723 mouvement_mock2
= mock
.Mock()
1724 mouvement_mock2
.__repr__
= mock
.Mock()
1725 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1726 order_mock2
.mouvements
= [
1727 mouvement_mock1
, mouvement_mock2
1729 trade
.orders
.append(order_mock1
)
1730 trade
.orders
.append(order_mock2
)
1732 trade
.print_with_order()
1734 self
.m
.report
.print_log
.assert_called()
1735 calls
= self
.m
.report
.print_log
.mock_calls
1736 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1737 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1738 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1739 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1740 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1742 def test__repr(self
):
1743 value_from
= portfolio
.Amount("BTC", "0.5")
1744 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1745 value_to
= portfolio
.Amount("BTC", "1.0")
1746 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1748 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1750 def test_as_json(self
):
1751 value_from
= portfolio
.Amount("BTC", "0.5")
1752 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1753 value_to
= portfolio
.Amount("BTC", "1.0")
1754 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1756 as_json
= trade
.as_json()
1757 self
.assertEqual("acquire", as_json
["action"])
1758 self
.assertEqual(D("0.5"), as_json
["from"])
1759 self
.assertEqual(D("1.0"), as_json
["to"])
1760 self
.assertEqual("ETH", as_json
["currency"])
1761 self
.assertEqual("BTC", as_json
["base_currency"])
1763 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1764 class OrderTest(WebMockTestCase
):
1765 def test_values(self
):
1766 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1767 D("0.1"), "BTC", "long", "market", "trade")
1768 self
.assertEqual("buy", order
.action
)
1769 self
.assertEqual(10, order
.amount
.value
)
1770 self
.assertEqual("ETH", order
.amount
.currency
)
1771 self
.assertEqual(D("0.1"), order
.rate
)
1772 self
.assertEqual("BTC", order
.base_currency
)
1773 self
.assertEqual("market", order
.market
)
1774 self
.assertEqual("long", order
.trade_type
)
1775 self
.assertEqual("pending", order
.status
)
1776 self
.assertEqual("trade", order
.trade
)
1777 self
.assertIsNone(order
.id)
1778 self
.assertFalse(order
.close_if_possible
)
1780 def test__repr(self
):
1781 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1782 D("0.1"), "BTC", "long", "market", "trade")
1783 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1785 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1786 D("0.1"), "BTC", "long", "market", "trade",
1787 close_if_possible
=True)
1788 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1790 def test_as_json(self
):
1791 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1792 D("0.1"), "BTC", "long", "market", "trade")
1793 mouvement_mock1
= mock
.Mock()
1794 mouvement_mock1
.as_json
.return_value
= 1
1795 mouvement_mock2
= mock
.Mock()
1796 mouvement_mock2
.as_json
.return_value
= 2
1798 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1799 as_json
= order
.as_json()
1800 self
.assertEqual("buy", as_json
["action"])
1801 self
.assertEqual("long", as_json
["trade_type"])
1802 self
.assertEqual(10, as_json
["amount"])
1803 self
.assertEqual("ETH", as_json
["currency"])
1804 self
.assertEqual("BTC", as_json
["base_currency"])
1805 self
.assertEqual(D("0.1"), as_json
["rate"])
1806 self
.assertEqual("pending", as_json
["status"])
1807 self
.assertEqual(False, as_json
["close_if_possible"])
1808 self
.assertIsNone(as_json
["id"])
1809 self
.assertEqual([1, 2], as_json
["mouvements"])
1811 def test_account(self
):
1812 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1813 D("0.1"), "BTC", "long", "market", "trade")
1814 self
.assertEqual("exchange", order
.account
)
1816 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1817 D("0.1"), "BTC", "short", "market", "trade")
1818 self
.assertEqual("margin", order
.account
)
1820 def test_pending(self
):
1821 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1822 D("0.1"), "BTC", "long", "market", "trade")
1823 self
.assertTrue(order
.pending
)
1824 order
.status
= "open"
1825 self
.assertFalse(order
.pending
)
1827 def test_open(self
):
1828 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1829 D("0.1"), "BTC", "long", "market", "trade")
1830 self
.assertFalse(order
.open)
1831 order
.status
= "open"
1832 self
.assertTrue(order
.open)
1834 def test_finished(self
):
1835 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1836 D("0.1"), "BTC", "long", "market", "trade")
1837 self
.assertFalse(order
.finished
)
1838 order
.status
= "closed"
1839 self
.assertTrue(order
.finished
)
1840 order
.status
= "canceled"
1841 self
.assertTrue(order
.finished
)
1842 order
.status
= "error"
1843 self
.assertTrue(order
.finished
)
1845 @mock.patch.object(portfolio
.Order
, "fetch")
1846 def test_cancel(self
, fetch
):
1848 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1849 D("0.1"), "BTC", "long", self
.m
, "trade")
1850 order
.status
= "open"
1853 self
.m
.ccxt
.cancel_order
.assert_not_called()
1854 self
.m
.report
.log_debug_action
.assert_called_once()
1855 self
.m
.report
.log_debug_action
.reset_mock()
1856 self
.assertEqual("canceled", order
.status
)
1858 self
.m
.debug
= False
1859 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1860 D("0.1"), "BTC", "long", self
.m
, "trade")
1861 order
.status
= "open"
1865 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1866 fetch
.assert_called_once_with()
1867 self
.m
.report
.log_debug_action
.assert_not_called()
1869 def test_dust_amount_remaining(self
):
1870 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1871 D("0.1"), "BTC", "long", self
.m
, "trade")
1872 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1873 self
.assertFalse(order
.dust_amount_remaining())
1875 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1876 self
.assertTrue(order
.dust_amount_remaining())
1878 @mock.patch.object(portfolio
.Order
, "fetch")
1879 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1880 def test_remaining_amount(self
, filled_amount
, fetch
):
1881 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1882 D("0.1"), "BTC", "long", self
.m
, "trade")
1884 self
.assertEqual(9, order
.remaining_amount().value
)
1886 order
.status
= "open"
1887 self
.assertEqual(9, order
.remaining_amount().value
)
1889 @mock.patch.object(portfolio
.Order
, "fetch")
1890 def test_filled_amount(self
, fetch
):
1891 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1892 D("0.1"), "BTC", "long", self
.m
, "trade")
1893 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1894 "tradeID": 42, "type": "buy", "fee": "0.0015",
1895 "date": "2017-12-30 12:00:12", "rate": "0.1",
1896 "amount": "3", "total": "0.3"
1898 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1899 "tradeID": 43, "type": "buy", "fee": "0.0015",
1900 "date": "2017-12-30 13:00:12", "rate": "0.2",
1901 "amount": "2", "total": "0.4"
1903 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1904 fetch
.assert_not_called()
1905 order
.status
= "open"
1906 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1907 fetch
.assert_called_once()
1908 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1910 def test_fetch_mouvements(self
):
1911 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
1913 "tradeID": 42, "type": "buy", "fee": "0.0015",
1914 "date": "2017-12-30 12:00:12", "rate": "0.1",
1915 "amount": "3", "total": "0.3"
1918 "tradeID": 43, "type": "buy", "fee": "0.0015",
1919 "date": "2017-12-30 13:00:12", "rate": "0.2",
1920 "amount": "2", "total": "0.4"
1923 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1924 D("0.1"), "BTC", "long", self
.m
, "trade")
1926 order
.mouvements
= ["Foo", "Bar", "Baz"]
1928 order
.fetch_mouvements()
1930 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
1931 self
.assertEqual(2, len(order
.mouvements
))
1932 self
.assertEqual(42, order
.mouvements
[0].id)
1933 self
.assertEqual(43, order
.mouvements
[1].id)
1935 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
1936 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1937 D("0.1"), "BTC", "long", self
.m
, "trade")
1938 order
.fetch_mouvements()
1939 self
.assertEqual(0, len(order
.mouvements
))
1941 def test_mark_finished_order(self
):
1942 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1943 D("0.1"), "BTC", "short", self
.m
, "trade",
1944 close_if_possible
=True)
1945 order
.status
= "closed"
1946 self
.m
.debug
= False
1948 order
.mark_finished_order()
1949 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
1950 self
.m
.ccxt
.close_margin_position
.reset_mock()
1952 order
.status
= "open"
1953 order
.mark_finished_order()
1954 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1956 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1957 D("0.1"), "BTC", "short", self
.m
, "trade",
1958 close_if_possible
=False)
1959 order
.status
= "closed"
1960 order
.mark_finished_order()
1961 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1963 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1964 D("0.1"), "BTC", "short", self
.m
, "trade",
1965 close_if_possible
=True)
1966 order
.status
= "closed"
1967 order
.mark_finished_order()
1968 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1970 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1971 D("0.1"), "BTC", "long", self
.m
, "trade",
1972 close_if_possible
=True)
1973 order
.status
= "closed"
1974 order
.mark_finished_order()
1975 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1979 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1980 D("0.1"), "BTC", "short", self
.m
, "trade",
1981 close_if_possible
=True)
1982 order
.status
= "closed"
1984 order
.mark_finished_order()
1985 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1986 self
.m
.report
.log_debug_action
.assert_called_once()
1988 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
1989 def test_fetch(self
, fetch_mouvements
):
1990 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1991 D("0.1"), "BTC", "long", self
.m
, "trade")
1993 with self
.subTest(debug
=True):
1996 self
.m
.report
.log_debug_action
.assert_called_once()
1997 self
.m
.report
.log_debug_action
.reset_mock()
1998 self
.m
.ccxt
.fetch_order
.assert_not_called()
1999 fetch_mouvements
.assert_not_called()
2001 with self
.subTest(debug
=False):
2002 self
.m
.debug
= False
2003 self
.m
.ccxt
.fetch_order
.return_value
= {
2005 "datetime": "timestamp"
2009 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
2010 fetch_mouvements
.assert_called_once()
2011 self
.assertEqual("foo", order
.status
)
2012 self
.assertEqual("timestamp", order
.timestamp
)
2013 self
.assertEqual(1, len(order
.results
))
2014 self
.m
.report
.log_debug_action
.assert_not_called()
2016 with self
.subTest(missing_order
=True):
2017 self
.m
.ccxt
.fetch_order
.side_effect
= [
2018 portfolio
.OrderNotCached
,
2021 self
.assertEqual("closed_unknown", order
.status
)
2023 @mock.patch.object(portfolio
.Order
, "fetch")
2024 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2025 def test_get_status(self
, mark_finished_order
, fetch
):
2026 with self
.subTest(debug
=True):
2028 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2029 D("0.1"), "BTC", "long", self
.m
, "trade")
2030 self
.assertEqual("pending", order
.get_status())
2031 fetch
.assert_not_called()
2032 self
.m
.report
.log_debug_action
.assert_called_once()
2034 with self
.subTest(debug
=False, finished
=False):
2035 self
.m
.debug
= False
2036 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2037 D("0.1"), "BTC", "long", self
.m
, "trade")
2039 def update_status():
2040 order
.status
= "open"
2041 return update_status
2042 fetch
.side_effect
= _fetch(order
)
2043 self
.assertEqual("open", order
.get_status())
2044 mark_finished_order
.assert_not_called()
2045 fetch
.assert_called_once()
2047 mark_finished_order
.reset_mock()
2049 with self
.subTest(debug
=False, finished
=True):
2050 self
.m
.debug
= False
2051 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2052 D("0.1"), "BTC", "long", self
.m
, "trade")
2054 def update_status():
2055 order
.status
= "closed"
2056 return update_status
2057 fetch
.side_effect
= _fetch(order
)
2058 self
.assertEqual("closed", order
.get_status())
2059 mark_finished_order
.assert_called_once()
2060 fetch
.assert_called_once()
2063 self
.m
.ccxt
.order_precision
.return_value
= 4
2064 with self
.subTest(debug
=True):
2066 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2067 D("0.1"), "BTC", "long", self
.m
, "trade")
2069 self
.m
.ccxt
.create_order
.assert_not_called()
2070 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2071 self
.assertEqual("open", order
.status
)
2072 self
.assertEqual(1, len(order
.results
))
2073 self
.assertEqual(-1, order
.id)
2075 self
.m
.ccxt
.create_order
.reset_mock()
2076 with self
.subTest(debug
=False):
2077 self
.m
.debug
= False
2078 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2079 D("0.1"), "BTC", "long", self
.m
, "trade")
2080 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2082 self
.m
.ccxt
.create_order
.assert_called_once()
2083 self
.assertEqual(1, len(order
.results
))
2084 self
.assertEqual("open", order
.status
)
2086 self
.m
.ccxt
.create_order
.reset_mock()
2087 with self
.subTest(exception
=True):
2088 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2089 D("0.1"), "BTC", "long", self
.m
, "trade")
2090 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2092 self
.m
.ccxt
.create_order
.assert_called_once()
2093 self
.assertEqual(0, len(order
.results
))
2094 self
.assertEqual("error", order
.status
)
2095 self
.m
.report
.log_error
.assert_called_once()
2097 self
.m
.ccxt
.create_order
.reset_mock()
2098 with self
.subTest(dust_amount_exception
=True),\
2099 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2100 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2101 D("0.1"), "BTC", "long", self
.m
, "trade")
2102 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2104 self
.m
.ccxt
.create_order
.assert_called_once()
2105 self
.assertEqual(0, len(order
.results
))
2106 self
.assertEqual("closed", order
.status
)
2107 mark_finished_order
.assert_called_once()
2109 self
.m
.ccxt
.order_precision
.return_value
= 8
2110 self
.m
.ccxt
.create_order
.reset_mock()
2111 with self
.subTest(insufficient_funds
=True),\
2112 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2113 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2114 D("0.1"), "BTC", "long", self
.m
, "trade")
2115 self
.m
.ccxt
.create_order
.side_effect
= [
2116 portfolio
.InsufficientFunds
,
2117 portfolio
.InsufficientFunds
,
2118 portfolio
.InsufficientFunds
,
2122 self
.m
.ccxt
.create_order
.assert_has_calls([
2123 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2124 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2125 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2126 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2128 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2129 self
.assertEqual(1, len(order
.results
))
2130 self
.assertEqual("open", order
.status
)
2131 self
.assertEqual(4, order
.tries
)
2132 self
.m
.report
.log_error
.assert_called()
2133 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2135 self
.m
.ccxt
.order_precision
.return_value
= 8
2136 self
.m
.ccxt
.create_order
.reset_mock()
2137 self
.m
.report
.log_error
.reset_mock()
2138 with self
.subTest(insufficient_funds
=True),\
2139 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2140 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2141 D("0.1"), "BTC", "long", self
.m
, "trade")
2142 self
.m
.ccxt
.create_order
.side_effect
= [
2143 portfolio
.InsufficientFunds
,
2144 portfolio
.InsufficientFunds
,
2145 portfolio
.InsufficientFunds
,
2146 portfolio
.InsufficientFunds
,
2147 portfolio
.InsufficientFunds
,
2150 self
.m
.ccxt
.create_order
.assert_has_calls([
2151 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2152 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2153 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2154 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2155 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2157 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2158 self
.assertEqual(0, len(order
.results
))
2159 self
.assertEqual("error", order
.status
)
2160 self
.assertEqual(5, order
.tries
)
2161 self
.m
.report
.log_error
.assert_called()
2162 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2163 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
)
2166 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2167 class MouvementTest(WebMockTestCase
):
2168 def test_values(self
):
2169 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2170 "tradeID": 42, "type": "buy", "fee": "0.0015",
2171 "date": "2017-12-30 12:00:12", "rate": "0.1",
2172 "amount": "10", "total": "1"
2174 self
.assertEqual("ETH", mouvement
.currency
)
2175 self
.assertEqual("BTC", mouvement
.base_currency
)
2176 self
.assertEqual(42, mouvement
.id)
2177 self
.assertEqual("buy", mouvement
.action
)
2178 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2179 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2180 self
.assertEqual(D("0.1"), mouvement
.rate
)
2181 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2182 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2184 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2185 self
.assertIsNone(mouvement
.date
)
2186 self
.assertIsNone(mouvement
.id)
2187 self
.assertIsNone(mouvement
.action
)
2188 self
.assertEqual(-1, mouvement
.fee_rate
)
2189 self
.assertEqual(0, mouvement
.rate
)
2190 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2191 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2193 def test__repr(self
):
2194 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2195 "tradeID": 42, "type": "buy", "fee": "0.0015",
2196 "date": "2017-12-30 12:00:12", "rate": "0.1",
2197 "amount": "10", "total": "1"
2199 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2201 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2202 "tradeID": 42, "type": "buy",
2203 "date": "garbage", "rate": "0.1",
2204 "amount": "10", "total": "1"
2206 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2208 def test_as_json(self
):
2209 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2210 "tradeID": 42, "type": "buy", "fee": "0.0015",
2211 "date": "2017-12-30 12:00:12", "rate": "0.1",
2212 "amount": "10", "total": "1"
2214 as_json
= mouvement
.as_json()
2216 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2217 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2218 self
.assertEqual("buy", as_json
["action"])
2219 self
.assertEqual(D("10"), as_json
["total"])
2220 self
.assertEqual(D("1"), as_json
["total_in_base"])
2221 self
.assertEqual("BTC", as_json
["base_currency"])
2222 self
.assertEqual("ETH", as_json
["currency"])
2224 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2225 class ReportStoreTest(WebMockTestCase
):
2226 def test_add_log(self
):
2227 report_store
= market
.ReportStore(self
.m
)
2228 report_store
.add_log({"foo": "bar"}
)
2230 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2232 def test_set_verbose(self
):
2233 report_store
= market
.ReportStore(self
.m
)
2234 with self
.subTest(verbose
=True):
2235 report_store
.set_verbose(True)
2236 self
.assertTrue(report_store
.verbose_print
)
2238 with self
.subTest(verbose
=False):
2239 report_store
.set_verbose(False)
2240 self
.assertFalse(report_store
.verbose_print
)
2242 def test_print_log(self
):
2243 report_store
= market
.ReportStore(self
.m
)
2244 with self
.subTest(verbose
=True),\
2245 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2246 report_store
.set_verbose(True)
2247 report_store
.print_log("Coucou")
2248 report_store
.print_log(portfolio
.Amount("BTC", 1))
2249 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2251 with self
.subTest(verbose
=False),\
2252 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2253 report_store
.set_verbose(False)
2254 report_store
.print_log("Coucou")
2255 report_store
.print_log(portfolio
.Amount("BTC", 1))
2256 self
.assertEqual(stdout_mock
.getvalue(), "")
2258 def test_to_json(self
):
2259 report_store
= market
.ReportStore(self
.m
)
2260 report_store
.logs
.append({"foo": "bar"}
)
2261 self
.assertEqual('[{"foo": "bar"}]', report_store
.to_json())
2262 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2263 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}]', report_store
.to_json())
2264 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2265 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}, {"amount": "1.00000000 BTC"}]', report_store
.to_json())
2267 @mock.patch.object(market
.ReportStore
, "print_log")
2268 @mock.patch.object(market
.ReportStore
, "add_log")
2269 def test_log_stage(self
, add_log
, print_log
):
2270 report_store
= market
.ReportStore(self
.m
)
2272 report_store
.log_stage("foo", bar
="baz", c
=c
, d
=portfolio
.Amount("BTC", 1))
2273 print_log
.assert_has_calls([
2274 mock
.call("-----------"),
2275 mock
.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
2277 add_log
.assert_called_once_with({
2282 'c': 'c = lambda x: x',
2290 @mock.patch.object(market
.ReportStore
, "print_log")
2291 @mock.patch.object(market
.ReportStore
, "add_log")
2292 def test_log_balances(self
, add_log
, print_log
):
2293 report_store
= market
.ReportStore(self
.m
)
2294 self
.m
.balances
.as_json
.return_value
= "json"
2295 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2297 report_store
.log_balances(tag
="tag")
2298 print_log
.assert_has_calls([
2299 mock
.call("[Balance]"),
2303 add_log
.assert_called_once_with({
2309 @mock.patch.object(market
.ReportStore
, "print_log")
2310 @mock.patch.object(market
.ReportStore
, "add_log")
2311 def test_log_tickers(self
, add_log
, print_log
):
2312 report_store
= market
.ReportStore(self
.m
)
2314 "BTC": portfolio
.Amount("BTC", 10),
2315 "ETH": portfolio
.Amount("BTC", D("0.3"))
2317 amounts
["ETH"].rate
= D("0.1")
2319 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2320 print_log
.assert_not_called()
2321 add_log
.assert_called_once_with({
2323 'compute_value': 'default',
2324 'balance_type': 'total',
2337 add_log
.reset_mock()
2338 compute_value
= lambda x
: x
["bid"]
2339 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
2340 add_log
.assert_called_once_with({
2342 'compute_value': 'compute_value = lambda x: x["bid"]',
2343 'balance_type': 'total',
2356 @mock.patch.object(market
.ReportStore
, "print_log")
2357 @mock.patch.object(market
.ReportStore
, "add_log")
2358 def test_log_dispatch(self
, add_log
, print_log
):
2359 report_store
= market
.ReportStore(self
.m
)
2360 amount
= portfolio
.Amount("BTC", "10.3")
2362 "BTC": portfolio
.Amount("BTC", 10),
2363 "ETH": portfolio
.Amount("BTC", D("0.3"))
2365 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2366 print_log
.assert_not_called()
2367 add_log
.assert_called_once_with({
2369 'liquidity': 'medium',
2370 'repartition_ratio': 'repartition',
2381 @mock.patch.object(market
.ReportStore
, "print_log")
2382 @mock.patch.object(market
.ReportStore
, "add_log")
2383 def test_log_trades(self
, add_log
, print_log
):
2384 report_store
= market
.ReportStore(self
.m
)
2385 trade_mock1
= mock
.Mock()
2386 trade_mock2
= mock
.Mock()
2387 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2388 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2390 matching_and_trades
= [
2391 (True, trade_mock1
),
2392 (False, trade_mock2
),
2394 report_store
.log_trades(matching_and_trades
, "only")
2396 print_log
.assert_not_called()
2397 add_log
.assert_called_with({
2402 {'trade': '1', 'skipped': False}
,
2403 {'trade': '2', 'skipped': True}
2407 @mock.patch.object(market
.ReportStore
, "print_log")
2408 @mock.patch.object(market
.ReportStore
, "add_log")
2409 def test_log_orders(self
, add_log
, print_log
):
2410 report_store
= market
.ReportStore(self
.m
)
2412 order_mock1
= mock
.Mock()
2413 order_mock2
= mock
.Mock()
2415 order_mock1
.as_json
.return_value
= "order1"
2416 order_mock2
.as_json
.return_value
= "order2"
2418 orders
= [order_mock1
, order_mock2
]
2420 report_store
.log_orders(orders
, tick
="tick",
2421 only
="only", compute_value
="compute_value")
2423 print_log
.assert_called_once_with("[Orders]")
2424 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2426 add_log
.assert_called_with({
2429 'compute_value': 'compute_value',
2431 'orders': ['order1', 'order2']
2434 add_log
.reset_mock()
2435 def compute_value(x
, y
):
2437 report_store
.log_orders(orders
, tick
="tick",
2438 only
="only", compute_value
=compute_value
)
2439 add_log
.assert_called_with({
2442 'compute_value': 'def compute_value(x, y):\n return x[y]',
2444 'orders': ['order1', 'order2']
2448 @mock.patch.object(market
.ReportStore
, "print_log")
2449 @mock.patch.object(market
.ReportStore
, "add_log")
2450 def test_log_order(self
, add_log
, print_log
):
2451 report_store
= market
.ReportStore(self
.m
)
2452 order_mock
= mock
.Mock()
2453 order_mock
.as_json
.return_value
= "order"
2454 new_order_mock
= mock
.Mock()
2455 new_order_mock
.as_json
.return_value
= "new_order"
2456 order_mock
.__repr
__ = mock
.Mock()
2457 order_mock
.__repr
__.return_value
= "Order Mock"
2458 new_order_mock
.__repr
__ = mock
.Mock()
2459 new_order_mock
.__repr
__.return_value
= "New order Mock"
2461 with self
.subTest(finished
=True):
2462 report_store
.log_order(order_mock
, 1, finished
=True)
2463 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2464 add_log
.assert_called_once_with({
2469 'compute_value': None,
2473 add_log
.reset_mock()
2474 print_log
.reset_mock()
2476 with self
.subTest(update
="waiting"):
2477 report_store
.log_order(order_mock
, 1, update
="waiting")
2478 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2479 add_log
.assert_called_once_with({
2482 'update': 'waiting',
2484 'compute_value': None,
2488 add_log
.reset_mock()
2489 print_log
.reset_mock()
2490 with self
.subTest(update
="adjusting"):
2491 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
2492 report_store
.log_order(order_mock
, 3,
2493 update
="adjusting", new_order
=new_order_mock
,
2494 compute_value
=compute_value
)
2495 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2496 add_log
.assert_called_once_with({
2499 'update': 'adjusting',
2501 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
2502 'new_order': 'new_order'
2505 add_log
.reset_mock()
2506 print_log
.reset_mock()
2507 with self
.subTest(update
="market_fallback"):
2508 report_store
.log_order(order_mock
, 7,
2509 update
="market_fallback", new_order
=new_order_mock
)
2510 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2511 add_log
.assert_called_once_with({
2514 'update': 'market_fallback',
2516 'compute_value': None,
2517 'new_order': 'new_order'
2520 add_log
.reset_mock()
2521 print_log
.reset_mock()
2522 with self
.subTest(update
="market_adjusting"):
2523 report_store
.log_order(order_mock
, 17,
2524 update
="market_adjust", new_order
=new_order_mock
)
2525 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2526 add_log
.assert_called_once_with({
2529 'update': 'market_adjust',
2531 'compute_value': None,
2532 'new_order': 'new_order'
2535 @mock.patch.object(market
.ReportStore
, "print_log")
2536 @mock.patch.object(market
.ReportStore
, "add_log")
2537 def test_log_move_balances(self
, add_log
, print_log
):
2538 report_store
= market
.ReportStore(self
.m
)
2540 "BTC": portfolio
.Amount("BTC", 10),
2544 "BTC": portfolio
.Amount("BTC", 3),
2547 report_store
.log_move_balances(needed
, moving
)
2548 print_log
.assert_not_called()
2549 add_log
.assert_called_once_with({
2550 'type': 'move_balances',
2562 @mock.patch.object(market
.ReportStore
, "print_log")
2563 @mock.patch.object(market
.ReportStore
, "add_log")
2564 def test_log_http_request(self
, add_log
, print_log
):
2565 report_store
= market
.ReportStore(self
.m
)
2566 response
= mock
.Mock()
2567 response
.status_code
= 200
2568 response
.text
= "Hey"
2570 report_store
.log_http_request("method", "url", "body",
2571 "headers", response
)
2572 print_log
.assert_not_called()
2573 add_log
.assert_called_once_with({
2574 'type': 'http_request',
2578 'headers': 'headers',
2583 @mock.patch.object(market
.ReportStore
, "print_log")
2584 @mock.patch.object(market
.ReportStore
, "add_log")
2585 def test_log_error(self
, add_log
, print_log
):
2586 report_store
= market
.ReportStore(self
.m
)
2587 with self
.subTest(message
=None, exception
=None):
2588 report_store
.log_error("action")
2589 print_log
.assert_called_once_with("[Error] action")
2590 add_log
.assert_called_once_with({
2593 'exception_class': None,
2594 'exception_message': None,
2598 print_log
.reset_mock()
2599 add_log
.reset_mock()
2600 with self
.subTest(message
="Hey", exception
=None):
2601 report_store
.log_error("action", message
="Hey")
2602 print_log
.assert_has_calls([
2603 mock
.call("[Error] action"),
2606 add_log
.assert_called_once_with({
2609 'exception_class': None,
2610 'exception_message': None,
2614 print_log
.reset_mock()
2615 add_log
.reset_mock()
2616 with self
.subTest(message
=None, exception
=Exception("bouh")):
2617 report_store
.log_error("action", exception
=Exception("bouh"))
2618 print_log
.assert_has_calls([
2619 mock
.call("[Error] action"),
2620 mock
.call("\tException: bouh")
2622 add_log
.assert_called_once_with({
2625 'exception_class': "Exception",
2626 'exception_message': "bouh",
2630 print_log
.reset_mock()
2631 add_log
.reset_mock()
2632 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2633 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2634 print_log
.assert_has_calls([
2635 mock
.call("[Error] action"),
2636 mock
.call("\tException: bouh"),
2639 add_log
.assert_called_once_with({
2642 'exception_class': "Exception",
2643 'exception_message': "bouh",
2647 @mock.patch.object(market
.ReportStore
, "print_log")
2648 @mock.patch.object(market
.ReportStore
, "add_log")
2649 def test_log_debug_action(self
, add_log
, print_log
):
2650 report_store
= market
.ReportStore(self
.m
)
2651 report_store
.log_debug_action("Hey")
2653 print_log
.assert_called_once_with("[Debug] Hey")
2654 add_log
.assert_called_once_with({
2655 'type': 'debug_action',
2659 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2660 class HelperTest(WebMockTestCase
):
2661 def test_make_order(self
):
2662 self
.m
.get_ticker
.return_value
= {
2664 "average": D("0.1"),
2669 with self
.subTest(description
="nominal case"):
2670 helper
.make_order(self
.m
, 10, "ETH")
2672 self
.m
.report
.log_stage
.assert_has_calls([
2673 mock
.call("make_order_begin"),
2674 mock
.call("make_order_end"),
2676 self
.m
.balances
.fetch_balances
.assert_has_calls([
2677 mock
.call(tag
="make_order_begin"),
2678 mock
.call(tag
="make_order_end"),
2680 self
.m
.trades
.all
.append
.assert_called_once()
2681 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2682 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2683 self
.assertEqual(0, trade
.value_from
)
2684 self
.assertEqual("ETH", trade
.currency
)
2685 self
.assertEqual("BTC", trade
.base_currency
)
2686 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2687 self
.m
.trades
.run_orders
.assert_called_once_with()
2688 self
.m
.follow_orders
.assert_called_once_with()
2690 order
= trade
.orders
[0]
2691 self
.assertEqual(D("0.10"), order
.rate
)
2694 with self
.subTest(compute_value
="default"):
2695 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2696 compute_value
="ask")
2698 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2699 order
= trade
.orders
[0]
2700 self
.assertEqual(D("0.11"), order
.rate
)
2703 with self
.subTest(follow
=False):
2704 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2706 self
.m
.report
.log_stage
.assert_has_calls([
2707 mock
.call("make_order_begin"),
2708 mock
.call("make_order_end_not_followed"),
2710 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2712 self
.m
.trades
.all
.append
.assert_called_once()
2713 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2714 self
.assertEqual(0, trade
.value_from
)
2715 self
.assertEqual("ETH", trade
.currency
)
2716 self
.assertEqual("BTC", trade
.base_currency
)
2717 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2718 self
.m
.trades
.run_orders
.assert_called_once_with()
2719 self
.m
.follow_orders
.assert_not_called()
2720 self
.assertEqual(trade
.orders
[0], result
)
2723 with self
.subTest(base_currency
="USDT"):
2724 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2726 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2727 self
.assertEqual("BTC", trade
.currency
)
2728 self
.assertEqual("USDT", trade
.base_currency
)
2731 with self
.subTest(close_if_possible
=True):
2732 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2734 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2735 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2738 with self
.subTest(action
="dispose"):
2739 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2741 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2742 self
.assertEqual(0, trade
.value_to
)
2743 self
.assertEqual(1, trade
.value_from
.value
)
2744 self
.assertEqual("ETH", trade
.currency
)
2745 self
.assertEqual("BTC", trade
.base_currency
)
2748 with self
.subTest(compute_value
="default"):
2749 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2750 compute_value
="bid")
2752 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2753 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2755 def test_user_market(self
):
2756 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2757 mock
.patch("helper.main_parse_config") as main_parse_config
:
2758 with self
.subTest(debug
=False):
2759 main_parse_config
.return_value
= ["pg_config", "report_path"]
2760 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2761 m
= helper
.get_user_market("config_path.ini", 1)
2763 self
.assertIsInstance(m
, market
.Market
)
2764 self
.assertFalse(m
.debug
)
2766 with self
.subTest(debug
=True):
2767 main_parse_config
.return_value
= ["pg_config", "report_path"]
2768 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2769 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2771 self
.assertIsInstance(m
, market
.Market
)
2772 self
.assertTrue(m
.debug
)
2774 def test_main_store_report(self
):
2775 file_open
= mock
.mock_open()
2776 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2777 helper
.main_store_report(None, 1, self
.m
)
2778 file_open
.assert_not_called()
2780 file_open
= mock
.mock_open()
2781 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2782 mock
.patch
.object(helper
, "datetime") as time_mock
:
2783 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2784 self
.m
.report
.to_json
.return_value
= "json_content"
2786 helper
.main_store_report("present", 1, self
.m
)
2788 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2789 file_open().write
.assert_called_once_with("json_content")
2790 self
.m
.report
.to_json
.assert_called_once_with()
2792 with self
.subTest(file="error"),\
2793 mock
.patch("helper.open") as file_open
,\
2794 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2795 file_open
.side_effect
= FileNotFoundError
2797 helper
.main_store_report("error", 1, self
.m
)
2799 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2801 @mock.patch("helper.Processor.process")
2802 def test_main_process_market(self
, process
):
2803 with self
.subTest(before
=False, after
=False):
2805 helper
.main_process_market(m
, None)
2807 process
.assert_not_called()
2809 process
.reset_mock()
2810 with self
.subTest(before
=True, after
=False):
2811 helper
.main_process_market(m
, None, before
=True)
2813 process
.assert_called_once_with("sell_all", steps
="before")
2815 process
.reset_mock()
2816 with self
.subTest(before
=False, after
=True):
2817 helper
.main_process_market(m
, None, after
=True)
2819 process
.assert_called_once_with("sell_all", steps
="after")
2821 process
.reset_mock()
2822 with self
.subTest(before
=True, after
=True):
2823 helper
.main_process_market(m
, None, before
=True, after
=True)
2825 process
.assert_has_calls([
2826 mock
.call("sell_all", steps
="before"),
2827 mock
.call("sell_all", steps
="after"),
2830 process
.reset_mock()
2831 with self
.subTest(action
="print_balances"),\
2832 mock
.patch("helper.print_balances") as print_balances
:
2833 helper
.main_process_market("user", ["print_balances"])
2835 process
.assert_not_called()
2836 print_balances
.assert_called_once_with("user")
2838 with self
.subTest(action
="print_orders"),\
2839 mock
.patch("helper.print_orders") as print_orders
,\
2840 mock
.patch("helper.print_balances") as print_balances
:
2841 helper
.main_process_market("user", ["print_orders", "print_balances"])
2843 process
.assert_not_called()
2844 print_orders
.assert_called_once_with("user")
2845 print_balances
.assert_called_once_with("user")
2847 with self
.subTest(action
="unknown"),\
2848 self
.assertRaises(NotImplementedError):
2849 helper
.main_process_market("user", ["unknown"])
2851 @mock.patch.object(helper
, "psycopg2")
2852 def test_fetch_markets(self
, psycopg2
):
2853 connect_mock
= mock
.Mock()
2854 cursor_mock
= mock
.MagicMock()
2855 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2857 connect_mock
.cursor
.return_value
= cursor_mock
2858 psycopg2
.connect
.return_value
= connect_mock
2860 with self
.subTest(user
=None):
2861 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2863 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2864 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2866 self
.assertEqual(["row_1", "row_2"], rows
)
2868 psycopg2
.connect
.reset_mock()
2869 cursor_mock
.execute
.reset_mock()
2870 with self
.subTest(user
=1):
2871 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
2873 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2874 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
2876 self
.assertEqual(["row_1", "row_2"], rows
)
2878 @mock.patch.object(helper
.sys
, "exit")
2879 def test_main_parse_args(self
, exit
):
2880 with self
.subTest(config
="config.ini"):
2881 args
= helper
.main_parse_args([])
2882 self
.assertEqual("config.ini", args
.config
)
2883 self
.assertFalse(args
.before
)
2884 self
.assertFalse(args
.after
)
2885 self
.assertFalse(args
.debug
)
2887 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
2888 self
.assertTrue(args
.before
)
2889 self
.assertTrue(args
.after
)
2890 self
.assertTrue(args
.debug
)
2892 exit
.assert_not_called()
2894 with self
.subTest(config
="inexistant"),\
2895 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2896 args
= helper
.main_parse_args(["--config", "foo.bar"])
2897 exit
.assert_called_once_with(1)
2898 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
2900 @mock.patch.object(helper
.sys
, "exit")
2901 @mock.patch("helper.configparser")
2902 @mock.patch("helper.os")
2903 def test_main_parse_config(self
, os
, configparser
, exit
):
2904 with self
.subTest(pg_config
=True, report_path
=None):
2905 config_mock
= mock
.MagicMock()
2906 configparser
.ConfigParser
.return_value
= config_mock
2907 def config(element
):
2908 return element
== "postgresql"
2910 config_mock
.__contains
__.side_effect
= config
2911 config_mock
.__getitem
__.return_value
= "pg_config"
2913 result
= helper
.main_parse_config("configfile")
2915 config_mock
.read
.assert_called_with("configfile")
2917 self
.assertEqual(["pg_config", None], result
)
2919 with self
.subTest(pg_config
=True, report_path
="present"):
2920 config_mock
= mock
.MagicMock()
2921 configparser
.ConfigParser
.return_value
= config_mock
2923 config_mock
.__contains
__.return_value
= True
2924 config_mock
.__getitem
__.side_effect
= [
2925 {"report_path": "report_path"}
,
2926 {"report_path": "report_path"}
,
2930 os
.path
.exists
.return_value
= False
2931 result
= helper
.main_parse_config("configfile")
2933 config_mock
.read
.assert_called_with("configfile")
2934 self
.assertEqual(["pg_config", "report_path"], result
)
2935 os
.path
.exists
.assert_called_once_with("report_path")
2936 os
.makedirs
.assert_called_once_with("report_path")
2938 with self
.subTest(pg_config
=False),\
2939 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2940 config_mock
= mock
.MagicMock()
2941 configparser
.ConfigParser
.return_value
= config_mock
2942 result
= helper
.main_parse_config("configfile")
2944 config_mock
.read
.assert_called_with("configfile")
2945 exit
.assert_called_once_with(1)
2946 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
2949 def test_print_orders(self
):
2950 helper
.print_orders(self
.m
)
2952 self
.m
.report
.log_stage
.assert_called_with("print_orders")
2953 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
2954 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
2955 compute_value
="average")
2956 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
2958 def test_print_balances(self
):
2959 self
.m
.balances
.in_currency
.return_value
= {
2960 "BTC": portfolio
.Amount("BTC", "0.65"),
2961 "ETH": portfolio
.Amount("BTC", "0.3"),
2964 helper
.print_balances(self
.m
)
2966 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
2967 self
.m
.balances
.fetch_balances
.assert_called_with()
2968 self
.m
.report
.print_log
.assert_has_calls([
2969 mock
.call("total:"),
2970 mock
.call(portfolio
.Amount("BTC", "0.95")),
2973 def test_process_sell_needed__1_sell(self
):
2974 helper
.process_sell_needed__1_sell(self
.m
)
2976 self
.m
.balances
.fetch_balances
.assert_has_calls([
2977 mock
.call(tag
="process_sell_needed__1_sell_begin"),
2978 mock
.call(tag
="process_sell_needed__1_sell_end"),
2980 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
2982 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
2984 self
.m
.trades
.run_orders
.assert_called()
2985 self
.m
.follow_orders
.assert_called()
2986 self
.m
.report
.log_stage
.assert_has_calls([
2987 mock
.call("process_sell_needed__1_sell_begin"),
2988 mock
.call("process_sell_needed__1_sell_end")
2991 def test_process_sell_needed__2_buy(self
):
2992 helper
.process_sell_needed__2_buy(self
.m
)
2994 self
.m
.balances
.fetch_balances
.assert_has_calls([
2995 mock
.call(tag
="process_sell_needed__2_buy_begin"),
2996 mock
.call(tag
="process_sell_needed__2_buy_end"),
2998 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
2999 liquidity
="medium", only
="acquire")
3000 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3002 self
.m
.move_balances
.assert_called_with()
3003 self
.m
.trades
.run_orders
.assert_called()
3004 self
.m
.follow_orders
.assert_called()
3005 self
.m
.report
.log_stage
.assert_has_calls([
3006 mock
.call("process_sell_needed__2_buy_begin"),
3007 mock
.call("process_sell_needed__2_buy_end")
3010 def test_process_sell_all__1_sell(self
):
3011 helper
.process_sell_all__1_all_sell(self
.m
)
3013 self
.m
.balances
.fetch_balances
.assert_has_calls([
3014 mock
.call(tag
="process_sell_all__1_all_sell_begin"),
3015 mock
.call(tag
="process_sell_all__1_all_sell_end"),
3017 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3018 liquidity
="medium", repartition
={'BTC': (1, 'long')}
)
3019 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3020 self
.m
.trades
.run_orders
.assert_called()
3021 self
.m
.follow_orders
.assert_called()
3022 self
.m
.report
.log_stage
.assert_has_calls([
3023 mock
.call("process_sell_all__1_all_sell_begin"),
3024 mock
.call("process_sell_all__1_all_sell_end")
3027 @mock.patch("portfolio.Portfolio.wait_for_recent")
3028 def test_process_sell_all__2_wait(self
, wait
):
3029 helper
.process_sell_all__2_wait(self
.m
)
3031 wait
.assert_called_once_with(self
.m
)
3032 self
.m
.report
.log_stage
.assert_has_calls([
3033 mock
.call("process_sell_all__2_wait_begin"),
3034 mock
.call("process_sell_all__2_wait_end")
3037 def test_process_sell_all__3_all_buy(self
):
3038 helper
.process_sell_all__3_all_buy(self
.m
)
3040 self
.m
.balances
.fetch_balances
.assert_has_calls([
3041 mock
.call(tag
="process_sell_all__3_all_buy_begin"),
3042 mock
.call(tag
="process_sell_all__3_all_buy_end"),
3044 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3046 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3047 self
.m
.move_balances
.assert_called_with()
3048 self
.m
.trades
.run_orders
.assert_called()
3049 self
.m
.follow_orders
.assert_called()
3050 self
.m
.report
.log_stage
.assert_has_calls([
3051 mock
.call("process_sell_all__3_all_buy_begin"),
3052 mock
.call("process_sell_all__3_all_buy_end")
3055 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3056 class AcceptanceTest(WebMockTestCase
):
3057 @unittest.expectedFailure
3058 def test_success_sell_only_necessary(self
):
3059 # FIXME: catch stdout
3060 self
.m
.report
.verbose_print
= False
3063 "exchange_free": D("1.0"),
3064 "exchange_used": D("0.0"),
3065 "exchange_total": D("1.0"),
3069 "exchange_free": D("4.0"),
3070 "exchange_used": D("0.0"),
3071 "exchange_total": D("4.0"),
3075 "exchange_free": D("1000.0"),
3076 "exchange_used": D("0.0"),
3077 "exchange_total": D("1000.0"),
3078 "total": D("1000.0"),
3082 "ETH": (D("0.25"), "long"),
3083 "ETC": (D("0.25"), "long"),
3084 "BTC": (D("0.4"), "long"),
3085 "BTD": (D("0.01"), "short"),
3086 "B2X": (D("0.04"), "long"),
3087 "USDT": (D("0.05"), "long"),
3090 def fetch_ticker(symbol
):
3091 if symbol
== "ETH/BTC":
3093 "symbol": "ETH/BTC",
3097 if symbol
== "ETC/BTC":
3099 "symbol": "ETC/BTC",
3103 if symbol
== "XVG/BTC":
3105 "symbol": "XVG/BTC",
3106 "bid": D("0.00003"),
3109 if symbol
== "BTD/BTC":
3111 "symbol": "BTD/BTC",
3115 if symbol
== "B2X/BTC":
3117 "symbol": "B2X/BTC",
3121 if symbol
== "USDT/BTC":
3122 raise helper
.ExchangeError
3123 if symbol
== "BTC/USDT":
3125 "symbol": "BTC/USDT",
3129 self
.fail("Shouldn't have been called with {}".format(symbol
))
3131 market
= mock
.Mock()
3132 market
.fetch_all_balances
.return_value
= fetch_balance
3133 market
.fetch_ticker
.side_effect
= fetch_ticker
3134 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3136 helper
.prepare_trades(market
)
3138 balances
= portfolio
.BalanceStore
.all
3139 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3140 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3141 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3144 trades
= portfolio
.TradeStore
.all
3145 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3146 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3147 self
.assertEqual("dispose", trades
[0].action
)
3149 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3150 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3151 self
.assertEqual("acquire", trades
[1].action
)
3153 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3154 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3155 self
.assertEqual("dispose", trades
[2].action
)
3157 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3158 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3159 self
.assertEqual("acquire", trades
[3].action
)
3161 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3162 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3163 self
.assertEqual("acquire", trades
[4].action
)
3165 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3166 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3167 self
.assertEqual("acquire", trades
[5].action
)
3170 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3172 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3173 self
.assertEqual(2, len(all_orders
))
3174 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3175 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3176 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3177 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3180 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3181 self
.assertEqual("limit", type)
3182 if symbol
== "ETH/BTC":
3183 self
.assertEqual("sell", action
)
3184 self
.assertEqual(D('0.66666666'), amount
)
3185 self
.assertEqual(D("0.14014"), price
)
3186 elif symbol
== "XVG/BTC":
3187 self
.assertEqual("sell", action
)
3188 self
.assertEqual(1000, amount
)
3189 self
.assertEqual(D("0.00003003"), price
)
3191 self
.fail("I shouldn't have been called")
3196 market
.create_order
.side_effect
= create_order
3197 market
.order_precision
.return_value
= 8
3200 portfolio
.TradeStore
.run_orders()
3202 self
.assertEqual("open", all_orders
[0].status
)
3203 self
.assertEqual("open", all_orders
[1].status
)
3205 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3206 market
.privatePostReturnOrderTrades
.return_value
= [
3208 "tradeID": 42, "type": "buy", "fee": "0.0015",
3209 "date": "2017-12-30 12:00:12", "rate": "0.1",
3210 "amount": "10", "total": "1"
3213 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3215 helper
.follow_orders(verbose
=False)
3217 sleep
.assert_called_with(30)
3219 for order
in all_orders
:
3220 self
.assertEqual("closed", order
.status
)
3224 "exchange_free": D("1.0") / 3,
3225 "exchange_used": D("0.0"),
3226 "exchange_total": D("1.0") / 3,
3228 "total": D("1.0") / 3,
3231 "exchange_free": D("0.134"),
3232 "exchange_used": D("0.0"),
3233 "exchange_total": D("0.134"),
3235 "total": D("0.134"),
3238 "exchange_free": D("4.0"),
3239 "exchange_used": D("0.0"),
3240 "exchange_total": D("4.0"),
3245 "exchange_free": D("0.0"),
3246 "exchange_used": D("0.0"),
3247 "exchange_total": D("0.0"),
3252 market
.fetch_all_balances
.return_value
= fetch_balance
3254 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3256 helper
.prepare_trades(market
, only
="acquire", compute_value
="average")
3258 balances
= portfolio
.BalanceStore
.all
3259 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3260 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3261 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3262 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3265 trades
= portfolio
.TradeStore
.all
3266 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3267 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3268 self
.assertEqual("dispose", trades
[0].action
)
3270 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3271 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3272 self
.assertEqual("acquire", trades
[1].action
)
3274 self
.assertNotIn("BTC", trades
)
3276 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3277 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3278 self
.assertEqual("dispose", trades
[2].action
)
3280 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3281 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3282 self
.assertEqual("acquire", trades
[3].action
)
3284 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3285 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3286 self
.assertEqual("acquire", trades
[4].action
)
3288 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3289 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3290 self
.assertEqual("acquire", trades
[5].action
)
3293 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3295 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3296 self
.assertEqual(4, len(all_orders
))
3297 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3298 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3299 self
.assertEqual("buy", all_orders
[0].action
)
3300 self
.assertEqual("long", all_orders
[0].trade_type
)
3302 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3303 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3304 self
.assertEqual("sell", all_orders
[1].action
)
3305 self
.assertEqual("short", all_orders
[1].trade_type
)
3307 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3308 self
.assertAlmostEqual(0, diff
.value
)
3309 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3310 self
.assertEqual("buy", all_orders
[2].action
)
3311 self
.assertEqual("long", all_orders
[2].trade_type
)
3313 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3314 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3315 self
.assertEqual("sell", all_orders
[3].action
)
3316 self
.assertEqual("long", all_orders
[3].trade_type
)
3320 # Move balances to margin
3324 # portfolio.TradeStore.run_orders()
3326 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3328 helper
.follow_orders(verbose
=False)
3330 sleep
.assert_called_with(30)
3332 if __name__
== '__main__':