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)
787 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
789 @mock.patch.object(portfolio
.Portfolio
, "repartition")
790 @mock.patch.object(market
.Market
, "get_ticker")
791 @mock.patch.object(market
.TradeStore
, "compute_trades")
792 def test_prepare_trades_to_sell_all(self
, compute_trades
, get_ticker
, repartition
):
793 def _get_ticker(c1
, c2
):
794 if c1
== "USDT" and c2
== "BTC":
795 return { "average": D("0.0001") }
796 if c1
== "XVG" and c2
== "BTC":
797 return { "average": D("0.000001") }
798 self
.fail("Should be called with {}, {}".format(c1
, c2
))
799 get_ticker
.side_effect
= _get_ticker
801 with mock
.patch("market.ReportStore"):
802 m
= market
.Market(self
.ccxt
)
803 self
.ccxt
.fetch_all_balances
.return_value
= {
805 "exchange_free": D("10000.0"),
806 "exchange_used": D("0.0"),
807 "exchange_total": D("10000.0"),
808 "total": D("10000.0")
811 "exchange_free": D("10000.0"),
812 "exchange_used": D("0.0"),
813 "exchange_total": D("10000.0"),
814 "total": D("10000.0")
818 m
.balances
.fetch_balances(tag
="tag")
820 m
.prepare_trades_to_sell_all()
822 repartition
.assert_not_called()
823 compute_trades
.assert_called()
825 call
= compute_trades
.call_args
826 self
.assertEqual(1, call
[0][0]["USDT"].value
)
827 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
828 self
.assertEqual(D("1.01"), call
[0][1]["BTC"].value
)
829 m
.report
.log_stage
.assert_called_once_with("prepare_trades_to_sell_all")
830 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
832 @mock.patch.object(portfolio
.time
, "sleep")
833 @mock.patch.object(market
.TradeStore
, "all_orders")
834 def test_follow_orders(self
, all_orders
, time_mock
):
835 for debug
, sleep
in [
836 (False, None), (True, None),
837 (False, 12), (True, 12)]:
838 with self
.subTest(sleep
=sleep
, debug
=debug
), \
839 mock
.patch("market.ReportStore"):
840 m
= market
.Market(self
.ccxt
, debug
=debug
)
842 order_mock1
= mock
.Mock()
843 order_mock2
= mock
.Mock()
844 order_mock3
= mock
.Mock()
845 all_orders
.side_effect
= [
846 [order_mock1
, order_mock2
],
847 [order_mock1
, order_mock2
],
849 [order_mock1
, order_mock3
],
850 [order_mock1
, order_mock3
],
852 [order_mock1
, order_mock3
],
853 [order_mock1
, order_mock3
],
858 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
859 order_mock2
.get_status
.side_effect
= ["open"]
860 order_mock3
.get_status
.side_effect
= ["open", "closed"]
862 order_mock1
.trade
= mock
.Mock()
863 order_mock2
.trade
= mock
.Mock()
864 order_mock3
.trade
= mock
.Mock()
866 m
.follow_orders(sleep
=sleep
)
868 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
869 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
870 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
871 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
873 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
874 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
875 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
877 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
878 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
879 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
880 m
.report
.log_stage
.assert_called()
882 mock
.call("follow_orders_begin"),
883 mock
.call("follow_orders_tick_1"),
884 mock
.call("follow_orders_tick_2"),
885 mock
.call("follow_orders_tick_3"),
886 mock
.call("follow_orders_end"),
888 m
.report
.log_stage
.assert_has_calls(calls
)
889 m
.report
.log_orders
.assert_called()
890 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
892 mock
.call([order_mock1
, order_mock2
], tick
=1),
893 mock
.call([order_mock1
, order_mock3
], tick
=2),
894 mock
.call([order_mock1
, order_mock3
], tick
=3),
896 m
.report
.log_orders
.assert_has_calls(calls
)
898 mock
.call(order_mock1
, 3, finished
=True),
899 mock
.call(order_mock3
, 3, finished
=True),
901 m
.report
.log_order
.assert_has_calls(calls
)
905 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
906 time_mock
.assert_called_with(7)
908 time_mock
.assert_called_with(30)
910 time_mock
.assert_called_with(sleep
)
912 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
913 def test_move_balance(self
, fetch_balances
):
914 for debug
in [True, False]:
915 with self
.subTest(debug
=debug
),\
916 mock
.patch("market.ReportStore"):
917 m
= market
.Market(self
.ccxt
, debug
=debug
)
919 value_from
= portfolio
.Amount("BTC", "1.0")
920 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
921 value_to
= portfolio
.Amount("BTC", "10.0")
922 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
924 value_from
= portfolio
.Amount("BTC", "0.0")
925 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
926 value_to
= portfolio
.Amount("BTC", "-3.0")
927 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
929 value_from
= portfolio
.Amount("USDT", "0.0")
930 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
931 value_to
= portfolio
.Amount("USDT", "-50.0")
932 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
934 m
.trades
.all
= [trade1
, trade2
, trade3
]
935 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
936 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
937 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
938 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
942 fetch_balances
.assert_called_with()
943 m
.report
.log_move_balances
.assert_called_once()
946 m
.report
.log_debug_action
.assert_called()
947 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
949 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
950 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
951 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
953 @unittest.skipUnless("unit" in limits
, "Unit skipped")
954 class TradeStoreTest(WebMockTestCase
):
955 def test_compute_trades(self
):
956 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
959 "XMR": portfolio
.Amount("BTC", D("0.9")),
960 "DASH": portfolio
.Amount("BTC", D("0.4")),
961 "XVG": portfolio
.Amount("BTC", D("-0.5")),
962 "BTC": portfolio
.Amount("BTC", D("0.5")),
965 "DASH": portfolio
.Amount("BTC", D("0.5")),
966 "XVG": portfolio
.Amount("BTC", D("0.1")),
967 "BTC": portfolio
.Amount("BTC", D("0.4")),
968 "ETH": portfolio
.Amount("BTC", D("0.3")),
978 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
979 trade_store
= market
.TradeStore(self
.m
)
980 trade_if_matching
.side_effect
= side_effect
982 trade_store
.compute_trades(values_in_base
,
983 new_repartition
, only
="only")
985 self
.assertEqual(5, trade_if_matching
.call_count
)
986 self
.assertEqual(3, len(trade_store
.all
))
987 self
.assertEqual([1, 4, 5], trade_store
.all
)
988 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
990 def test_trade_if_matching(self
):
992 with self
.subTest(only
="nope"):
993 trade_store
= market
.TradeStore(self
.m
)
994 result
= trade_store
.trade_if_matching(
995 portfolio
.Amount("BTC", D("0")),
996 portfolio
.Amount("BTC", D("0.3")),
998 self
.assertEqual(False, result
[0])
999 self
.assertIsInstance(result
[1], portfolio
.Trade
)
1001 with self
.subTest(only
=None):
1002 trade_store
= market
.TradeStore(self
.m
)
1003 result
= trade_store
.trade_if_matching(
1004 portfolio
.Amount("BTC", D("0")),
1005 portfolio
.Amount("BTC", D("0.3")),
1007 self
.assertEqual(True, result
[0])
1009 with self
.subTest(only
="acquire"):
1010 trade_store
= market
.TradeStore(self
.m
)
1011 result
= trade_store
.trade_if_matching(
1012 portfolio
.Amount("BTC", D("0")),
1013 portfolio
.Amount("BTC", D("0.3")),
1014 "ETH", only
="acquire")
1015 self
.assertEqual(True, result
[0])
1017 with self
.subTest(only
="dispose"):
1018 trade_store
= market
.TradeStore(self
.m
)
1019 result
= trade_store
.trade_if_matching(
1020 portfolio
.Amount("BTC", D("0")),
1021 portfolio
.Amount("BTC", D("0.3")),
1022 "ETH", only
="dispose")
1023 self
.assertEqual(False, result
[0])
1025 def test_prepare_orders(self
):
1026 trade_store
= market
.TradeStore(self
.m
)
1028 trade_mock1
= mock
.Mock()
1029 trade_mock2
= mock
.Mock()
1030 trade_mock3
= mock
.Mock()
1032 trade_mock1
.prepare_order
.return_value
= 1
1033 trade_mock2
.prepare_order
.return_value
= 2
1034 trade_mock3
.prepare_order
.return_value
= 3
1036 trade_mock1
.is_fullfiled
= False
1037 trade_mock2
.is_fullfiled
= False
1038 trade_mock3
.is_fullfiled
= True
1040 trade_store
.all
.append(trade_mock1
)
1041 trade_store
.all
.append(trade_mock2
)
1042 trade_store
.all
.append(trade_mock3
)
1044 trade_store
.prepare_orders()
1045 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1046 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1047 trade_mock3
.prepare_order
.assert_not_called()
1048 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1050 self
.m
.report
.log_orders
.reset_mock()
1052 trade_store
.prepare_orders(compute_value
="bla")
1053 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1054 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1055 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1057 trade_mock1
.prepare_order
.reset_mock()
1058 trade_mock2
.prepare_order
.reset_mock()
1059 self
.m
.report
.log_orders
.reset_mock()
1061 trade_mock1
.action
= "foo"
1062 trade_mock2
.action
= "bar"
1063 trade_store
.prepare_orders(only
="bar")
1064 trade_mock1
.prepare_order
.assert_not_called()
1065 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1066 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1068 def test_print_all_with_order(self
):
1069 trade_mock1
= mock
.Mock()
1070 trade_mock2
= mock
.Mock()
1071 trade_mock3
= mock
.Mock()
1072 trade_store
= market
.TradeStore(self
.m
)
1073 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1075 trade_store
.print_all_with_order()
1077 trade_mock1
.print_with_order
.assert_called()
1078 trade_mock2
.print_with_order
.assert_called()
1079 trade_mock3
.print_with_order
.assert_called()
1081 def test_run_orders(self
):
1082 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1083 order_mock1
= mock
.Mock()
1084 order_mock2
= mock
.Mock()
1085 order_mock3
= mock
.Mock()
1086 trade_store
= market
.TradeStore(self
.m
)
1088 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1090 trade_store
.run_orders()
1092 all_orders
.assert_called_with(state
="pending")
1094 order_mock1
.run
.assert_called()
1095 order_mock2
.run
.assert_called()
1096 order_mock3
.run
.assert_called()
1098 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1099 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1102 def test_all_orders(self
):
1103 trade_mock1
= mock
.Mock()
1104 trade_mock2
= mock
.Mock()
1106 order_mock1
= mock
.Mock()
1107 order_mock2
= mock
.Mock()
1108 order_mock3
= mock
.Mock()
1110 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1111 trade_mock2
.orders
= [order_mock3
]
1113 order_mock1
.status
= "pending"
1114 order_mock2
.status
= "open"
1115 order_mock3
.status
= "open"
1117 trade_store
= market
.TradeStore(self
.m
)
1118 trade_store
.all
.append(trade_mock1
)
1119 trade_store
.all
.append(trade_mock2
)
1121 orders
= trade_store
.all_orders()
1122 self
.assertEqual(3, len(orders
))
1124 open_orders
= trade_store
.all_orders(state
="open")
1125 self
.assertEqual(2, len(open_orders
))
1126 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1128 def test_update_all_orders_status(self
):
1129 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1130 order_mock1
= mock
.Mock()
1131 order_mock2
= mock
.Mock()
1132 order_mock3
= mock
.Mock()
1134 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1136 trade_store
= market
.TradeStore(self
.m
)
1138 trade_store
.update_all_orders_status()
1139 all_orders
.assert_called_with(state
="open")
1141 order_mock1
.get_status
.assert_called()
1142 order_mock2
.get_status
.assert_called()
1143 order_mock3
.get_status
.assert_called()
1145 def test_pending(self
):
1146 trade_mock1
= mock
.Mock()
1147 trade_mock1
.is_fullfiled
= False
1148 trade_mock2
= mock
.Mock()
1149 trade_mock2
.is_fullfiled
= False
1150 trade_mock3
= mock
.Mock()
1151 trade_mock3
.is_fullfiled
= True
1153 trade_store
= market
.TradeStore(self
.m
)
1155 trade_store
.all
.append(trade_mock1
)
1156 trade_store
.all
.append(trade_mock2
)
1157 trade_store
.all
.append(trade_mock3
)
1159 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
1161 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1162 class BalanceStoreTest(WebMockTestCase
):
1164 super(BalanceStoreTest
, self
).setUp()
1166 self
.fetch_balance
= {
1170 "exchange_total": 0,
1174 "exchange_free": D("6.0"),
1175 "exchange_used": D("1.2"),
1176 "exchange_total": D("7.2"),
1180 "exchange_free": 16,
1182 "exchange_total": 16,
1188 "exchange_total": 0,
1189 "margin_total": D("-1.0"),
1194 def test_in_currency(self
):
1195 self
.m
.get_ticker
.return_value
= {
1198 "average": D("0.1"),
1201 balance_store
= market
.BalanceStore(self
.m
)
1202 balance_store
.all
= {
1203 "BTC": portfolio
.Balance("BTC", {
1205 "exchange_total":"0.65",
1206 "exchange_free": "0.35",
1207 "exchange_used": "0.30"}),
1208 "ETH": portfolio
.Balance("ETH", {
1210 "exchange_total": 3,
1212 "exchange_used": 0}),
1215 amounts
= balance_store
.in_currency("BTC")
1216 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1217 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1218 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1219 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1221 self
.m
.report
.log_tickers
.reset_mock()
1223 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1224 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1225 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1226 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1228 self
.m
.report
.log_tickers
.reset_mock()
1230 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1231 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1232 self
.assertEqual(0, amounts
["ETH"].value
)
1233 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1234 "bid", "exchange_used")
1235 self
.m
.report
.log_tickers
.reset_mock()
1237 def test_fetch_balances(self
):
1238 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1240 balance_store
= market
.BalanceStore(self
.m
)
1242 balance_store
.fetch_balances()
1243 self
.assertNotIn("ETC", balance_store
.currencies())
1244 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1246 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1247 "exchange_total": "1", "exchange_free": "0",
1248 "exchange_used": "1" })
1249 balance_store
.fetch_balances(tag
="foo")
1250 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1251 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1252 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1254 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1255 def test_dispatch_assets(self
, repartition
):
1256 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1258 balance_store
= market
.BalanceStore(self
.m
)
1259 balance_store
.fetch_balances()
1261 self
.assertNotIn("XEM", balance_store
.currencies())
1263 repartition_hash
= {
1264 "XEM": (D("0.75"), "long"),
1265 "BTC": (D("0.26"), "long"),
1266 "DASH": (D("0.10"), "short"),
1268 repartition
.return_value
= repartition_hash
1270 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1271 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1272 self
.assertIn("XEM", balance_store
.currencies())
1273 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1274 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1275 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1276 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1277 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1278 "11.1"), amounts
, "medium", repartition_hash
)
1280 def test_currencies(self
):
1281 balance_store
= market
.BalanceStore(self
.m
)
1283 balance_store
.all
= {
1284 "BTC": portfolio
.Balance("BTC", {
1286 "exchange_total":"0.65",
1287 "exchange_free": "0.35",
1288 "exchange_used": "0.30"}),
1289 "ETH": portfolio
.Balance("ETH", {
1291 "exchange_total": 3,
1293 "exchange_used": 0}),
1295 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1297 def test_as_json(self
):
1298 balance_mock1
= mock
.Mock()
1299 balance_mock1
.as_json
.return_value
= 1
1301 balance_mock2
= mock
.Mock()
1302 balance_mock2
.as_json
.return_value
= 2
1304 balance_store
= market
.BalanceStore(self
.m
)
1305 balance_store
.all
= {
1306 "BTC": balance_mock1
,
1307 "ETH": balance_mock2
,
1310 as_json
= balance_store
.as_json()
1311 self
.assertEqual(1, as_json
["BTC"])
1312 self
.assertEqual(2, as_json
["ETH"])
1315 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1316 class ComputationTest(WebMockTestCase
):
1317 def test_compute_value(self
):
1318 compute
= mock
.Mock()
1319 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1320 compute
.assert_called_with("foo", "ask")
1322 compute
.reset_mock()
1323 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1324 compute
.assert_called_with("foo", "bid")
1326 compute
.reset_mock()
1327 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1328 compute
.assert_called_with("foo", "ask")
1330 compute
.reset_mock()
1331 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1332 compute
.assert_called_with("foo", "bid")
1334 compute
.reset_mock()
1335 portfolio
.Computation
.computations
["test"] = compute
1336 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1337 compute
.assert_called_with("foo", "bid")
1340 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1341 class TradeTest(WebMockTestCase
):
1343 def test_values_assertion(self
):
1344 value_from
= portfolio
.Amount("BTC", "1.0")
1345 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1346 value_to
= portfolio
.Amount("BTC", "1.0")
1347 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1348 self
.assertEqual("BTC", trade
.base_currency
)
1349 self
.assertEqual("ETH", trade
.currency
)
1350 self
.assertEqual(self
.m
, trade
.market
)
1352 with self
.assertRaises(AssertionError):
1353 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
1354 with self
.assertRaises(AssertionError):
1355 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1356 with self
.assertRaises(AssertionError):
1357 value_from
.currency
= "ETH"
1358 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1359 value_from
.currency
= "BTC"
1360 with self
.assertRaises(AssertionError):
1361 value_from2
= portfolio
.Amount("BTC", "1.0")
1362 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
1364 value_from
= portfolio
.Amount("BTC", 0)
1365 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1366 self
.assertEqual(0, trade
.value_from
.linked_to
)
1368 def test_action(self
):
1369 value_from
= portfolio
.Amount("BTC", "1.0")
1370 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1371 value_to
= portfolio
.Amount("BTC", "1.0")
1372 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1374 self
.assertIsNone(trade
.action
)
1376 value_from
= portfolio
.Amount("BTC", "1.0")
1377 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1378 value_to
= portfolio
.Amount("BTC", "2.0")
1379 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1381 self
.assertIsNone(trade
.action
)
1383 value_from
= portfolio
.Amount("BTC", "0.5")
1384 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1385 value_to
= portfolio
.Amount("BTC", "1.0")
1386 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1388 self
.assertEqual("acquire", trade
.action
)
1390 value_from
= portfolio
.Amount("BTC", "0")
1391 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1392 value_to
= portfolio
.Amount("BTC", "-1.0")
1393 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1395 self
.assertEqual("acquire", trade
.action
)
1397 def test_order_action(self
):
1398 value_from
= portfolio
.Amount("BTC", "0.5")
1399 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1400 value_to
= portfolio
.Amount("BTC", "1.0")
1401 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1403 self
.assertEqual("buy", trade
.order_action(False))
1404 self
.assertEqual("sell", trade
.order_action(True))
1406 value_from
= portfolio
.Amount("BTC", "0")
1407 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1408 value_to
= portfolio
.Amount("BTC", "-1.0")
1409 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1411 self
.assertEqual("sell", trade
.order_action(False))
1412 self
.assertEqual("buy", trade
.order_action(True))
1414 def test_trade_type(self
):
1415 value_from
= portfolio
.Amount("BTC", "0.5")
1416 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1417 value_to
= portfolio
.Amount("BTC", "1.0")
1418 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1420 self
.assertEqual("long", trade
.trade_type
)
1422 value_from
= portfolio
.Amount("BTC", "0")
1423 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1424 value_to
= portfolio
.Amount("BTC", "-1.0")
1425 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1427 self
.assertEqual("short", trade
.trade_type
)
1429 def test_is_fullfiled(self
):
1430 value_from
= portfolio
.Amount("BTC", "0.5")
1431 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1432 value_to
= portfolio
.Amount("BTC", "1.0")
1433 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1435 order1
= mock
.Mock()
1436 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1438 order2
= mock
.Mock()
1439 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1440 trade
.orders
.append(order1
)
1441 trade
.orders
.append(order2
)
1443 self
.assertFalse(trade
.is_fullfiled
)
1445 order3
= mock
.Mock()
1446 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1447 trade
.orders
.append(order3
)
1449 self
.assertTrue(trade
.is_fullfiled
)
1451 def test_filled_amount(self
):
1452 value_from
= portfolio
.Amount("BTC", "0.5")
1453 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1454 value_to
= portfolio
.Amount("BTC", "1.0")
1455 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1457 order1
= mock
.Mock()
1458 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1460 order2
= mock
.Mock()
1461 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1462 trade
.orders
.append(order1
)
1463 trade
.orders
.append(order2
)
1465 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1466 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1467 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1469 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1470 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1471 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1473 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1474 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1475 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1477 @mock.patch.object(portfolio
.Computation
, "compute_value")
1478 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1479 @mock.patch.object(portfolio
, "Order")
1480 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1481 Order
.return_value
= "Order"
1483 with self
.subTest(desc
="Nothing to do"):
1484 value_from
= portfolio
.Amount("BTC", "10")
1485 value_from
.rate
= D("0.1")
1486 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1487 value_to
= portfolio
.Amount("BTC", "10")
1488 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1490 trade
.prepare_order()
1492 filled_amount
.assert_not_called()
1493 compute_value
.assert_not_called()
1494 self
.assertEqual(0, len(trade
.orders
))
1495 Order
.assert_not_called()
1497 self
.m
.get_ticker
.return_value
= { "inverted": False }
1498 with self
.subTest(desc
="Already filled"):
1499 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1500 compute_value
.return_value
= D("0.125")
1502 value_from
= portfolio
.Amount("BTC", "10")
1503 value_from
.rate
= D("0.1")
1504 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1505 value_to
= portfolio
.Amount("BTC", "0")
1506 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1508 trade
.prepare_order()
1510 filled_amount
.assert_called_with(in_base_currency
=False)
1511 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1512 self
.assertEqual(0, len(trade
.orders
))
1513 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1514 Order
.assert_not_called()
1516 with self
.subTest(action
="dispose", inverted
=False):
1517 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1518 compute_value
.return_value
= D("0.125")
1520 value_from
= portfolio
.Amount("BTC", "10")
1521 value_from
.rate
= D("0.1")
1522 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1523 value_to
= portfolio
.Amount("BTC", "1")
1524 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1526 trade
.prepare_order()
1528 filled_amount
.assert_called_with(in_base_currency
=False)
1529 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1530 self
.assertEqual(1, len(trade
.orders
))
1531 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1532 D("0.125"), "BTC", "long", self
.m
,
1533 trade
, close_if_possible
=False)
1535 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1536 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1537 compute_value
.return_value
= D("0.125")
1539 value_from
= portfolio
.Amount("BTC", "10")
1540 value_from
.rate
= D("0.1")
1541 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1542 value_to
= portfolio
.Amount("BTC", "1")
1543 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1545 trade
.prepare_order(close_if_possible
=True)
1547 filled_amount
.assert_called_with(in_base_currency
=False)
1548 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1549 self
.assertEqual(1, len(trade
.orders
))
1550 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1551 D("0.125"), "BTC", "long", self
.m
,
1552 trade
, close_if_possible
=True)
1554 with self
.subTest(action
="acquire", inverted
=False):
1555 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1556 compute_value
.return_value
= D("0.125")
1558 value_from
= portfolio
.Amount("BTC", "1")
1559 value_from
.rate
= D("0.1")
1560 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1561 value_to
= portfolio
.Amount("BTC", "10")
1562 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1564 trade
.prepare_order()
1566 filled_amount
.assert_called_with(in_base_currency
=True)
1567 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1568 self
.assertEqual(1, len(trade
.orders
))
1570 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1571 D("0.125"), "BTC", "long", self
.m
,
1572 trade
, close_if_possible
=False)
1574 with self
.subTest(close_if_possible
=True):
1575 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1576 compute_value
.return_value
= D("0.125")
1578 value_from
= portfolio
.Amount("BTC", "10")
1579 value_from
.rate
= D("0.1")
1580 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1581 value_to
= portfolio
.Amount("BTC", "0")
1582 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1584 trade
.prepare_order()
1586 filled_amount
.assert_called_with(in_base_currency
=False)
1587 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1588 self
.assertEqual(1, len(trade
.orders
))
1589 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1590 D("0.125"), "BTC", "long", self
.m
,
1591 trade
, close_if_possible
=True)
1593 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1594 with self
.subTest(action
="dispose", inverted
=True):
1595 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1596 compute_value
.return_value
= D("125")
1598 value_from
= portfolio
.Amount("BTC", "10")
1599 value_from
.rate
= D("0.01")
1600 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1601 value_to
= portfolio
.Amount("BTC", "1")
1602 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1604 trade
.prepare_order(compute_value
="foo")
1606 filled_amount
.assert_called_with(in_base_currency
=True)
1607 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1608 self
.assertEqual(1, len(trade
.orders
))
1609 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1610 D("125"), "FOO", "long", self
.m
,
1611 trade
, close_if_possible
=False)
1613 with self
.subTest(action
="acquire", inverted
=True):
1614 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1615 compute_value
.return_value
= D("125")
1617 value_from
= portfolio
.Amount("BTC", "1")
1618 value_from
.rate
= D("0.01")
1619 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1620 value_to
= portfolio
.Amount("BTC", "10")
1621 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1623 trade
.prepare_order(compute_value
="foo")
1625 filled_amount
.assert_called_with(in_base_currency
=False)
1626 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1627 self
.assertEqual(1, len(trade
.orders
))
1628 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1629 D("125"), "FOO", "long", self
.m
,
1630 trade
, close_if_possible
=False)
1633 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1634 def test_update_order(self
, prepare_order
):
1635 order_mock
= mock
.Mock()
1636 new_order_mock
= mock
.Mock()
1638 value_from
= portfolio
.Amount("BTC", "0.5")
1639 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1640 value_to
= portfolio
.Amount("BTC", "1.0")
1641 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1642 prepare_order
.return_value
= new_order_mock
1644 for i
in [0, 1, 3, 4, 6]:
1645 with self
.subTest(tick
=i
):
1646 trade
.update_order(order_mock
, i
)
1647 order_mock
.cancel
.assert_not_called()
1648 new_order_mock
.run
.assert_not_called()
1649 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1650 update
="waiting", compute_value
=None, new_order
=None)
1652 order_mock
.reset_mock()
1653 new_order_mock
.reset_mock()
1655 self
.m
.report
.log_order
.reset_mock()
1657 trade
.update_order(order_mock
, 2)
1658 order_mock
.cancel
.assert_called()
1659 new_order_mock
.run
.assert_called()
1660 prepare_order
.assert_called()
1661 self
.m
.report
.log_order
.assert_called()
1662 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1664 mock
.call(order_mock
, 2, update
="adjusting",
1665 compute_value
=mock
.ANY
,
1666 new_order
=new_order_mock
),
1667 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1669 self
.m
.report
.log_order
.assert_has_calls(calls
)
1671 order_mock
.reset_mock()
1672 new_order_mock
.reset_mock()
1674 self
.m
.report
.log_order
.reset_mock()
1676 trade
.update_order(order_mock
, 5)
1677 order_mock
.cancel
.assert_called()
1678 new_order_mock
.run
.assert_called()
1679 prepare_order
.assert_called()
1680 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1681 self
.m
.report
.log_order
.assert_called()
1683 mock
.call(order_mock
, 5, update
="adjusting",
1684 compute_value
=mock
.ANY
,
1685 new_order
=new_order_mock
),
1686 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1688 self
.m
.report
.log_order
.assert_has_calls(calls
)
1690 order_mock
.reset_mock()
1691 new_order_mock
.reset_mock()
1693 self
.m
.report
.log_order
.reset_mock()
1695 trade
.update_order(order_mock
, 7)
1696 order_mock
.cancel
.assert_called()
1697 new_order_mock
.run
.assert_called()
1698 prepare_order
.assert_called_with(compute_value
="default")
1699 self
.m
.report
.log_order
.assert_called()
1700 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1702 mock
.call(order_mock
, 7, update
="market_fallback",
1703 compute_value
='default',
1704 new_order
=new_order_mock
),
1705 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1707 self
.m
.report
.log_order
.assert_has_calls(calls
)
1709 order_mock
.reset_mock()
1710 new_order_mock
.reset_mock()
1712 self
.m
.report
.log_order
.reset_mock()
1714 for i
in [10, 13, 16]:
1715 with self
.subTest(tick
=i
):
1716 trade
.update_order(order_mock
, i
)
1717 order_mock
.cancel
.assert_called()
1718 new_order_mock
.run
.assert_called()
1719 prepare_order
.assert_called_with(compute_value
="default")
1720 self
.m
.report
.log_order
.assert_called()
1721 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1723 mock
.call(order_mock
, i
, update
="market_adjust",
1724 compute_value
='default',
1725 new_order
=new_order_mock
),
1726 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1728 self
.m
.report
.log_order
.assert_has_calls(calls
)
1730 order_mock
.reset_mock()
1731 new_order_mock
.reset_mock()
1733 self
.m
.report
.log_order
.reset_mock()
1735 for i
in [8, 9, 11, 12]:
1736 with self
.subTest(tick
=i
):
1737 trade
.update_order(order_mock
, i
)
1738 order_mock
.cancel
.assert_not_called()
1739 new_order_mock
.run
.assert_not_called()
1740 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1741 compute_value
=None, new_order
=None)
1743 order_mock
.reset_mock()
1744 new_order_mock
.reset_mock()
1746 self
.m
.report
.log_order
.reset_mock()
1749 def test_print_with_order(self
):
1750 value_from
= portfolio
.Amount("BTC", "0.5")
1751 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1752 value_to
= portfolio
.Amount("BTC", "1.0")
1753 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1755 order_mock1
= mock
.Mock()
1756 order_mock1
.__repr__
= mock
.Mock()
1757 order_mock1
.__repr__
.return_value
= "Mock 1"
1758 order_mock2
= mock
.Mock()
1759 order_mock2
.__repr__
= mock
.Mock()
1760 order_mock2
.__repr__
.return_value
= "Mock 2"
1761 order_mock1
.mouvements
= []
1762 mouvement_mock1
= mock
.Mock()
1763 mouvement_mock1
.__repr__
= mock
.Mock()
1764 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1765 mouvement_mock2
= mock
.Mock()
1766 mouvement_mock2
.__repr__
= mock
.Mock()
1767 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1768 order_mock2
.mouvements
= [
1769 mouvement_mock1
, mouvement_mock2
1771 trade
.orders
.append(order_mock1
)
1772 trade
.orders
.append(order_mock2
)
1774 trade
.print_with_order()
1776 self
.m
.report
.print_log
.assert_called()
1777 calls
= self
.m
.report
.print_log
.mock_calls
1778 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1779 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1780 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1781 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1782 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1784 def test__repr(self
):
1785 value_from
= portfolio
.Amount("BTC", "0.5")
1786 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1787 value_to
= portfolio
.Amount("BTC", "1.0")
1788 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1790 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1792 def test_as_json(self
):
1793 value_from
= portfolio
.Amount("BTC", "0.5")
1794 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1795 value_to
= portfolio
.Amount("BTC", "1.0")
1796 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1798 as_json
= trade
.as_json()
1799 self
.assertEqual("acquire", as_json
["action"])
1800 self
.assertEqual(D("0.5"), as_json
["from"])
1801 self
.assertEqual(D("1.0"), as_json
["to"])
1802 self
.assertEqual("ETH", as_json
["currency"])
1803 self
.assertEqual("BTC", as_json
["base_currency"])
1805 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1806 class OrderTest(WebMockTestCase
):
1807 def test_values(self
):
1808 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1809 D("0.1"), "BTC", "long", "market", "trade")
1810 self
.assertEqual("buy", order
.action
)
1811 self
.assertEqual(10, order
.amount
.value
)
1812 self
.assertEqual("ETH", order
.amount
.currency
)
1813 self
.assertEqual(D("0.1"), order
.rate
)
1814 self
.assertEqual("BTC", order
.base_currency
)
1815 self
.assertEqual("market", order
.market
)
1816 self
.assertEqual("long", order
.trade_type
)
1817 self
.assertEqual("pending", order
.status
)
1818 self
.assertEqual("trade", order
.trade
)
1819 self
.assertIsNone(order
.id)
1820 self
.assertFalse(order
.close_if_possible
)
1822 def test__repr(self
):
1823 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1824 D("0.1"), "BTC", "long", "market", "trade")
1825 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1827 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1828 D("0.1"), "BTC", "long", "market", "trade",
1829 close_if_possible
=True)
1830 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1832 def test_as_json(self
):
1833 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1834 D("0.1"), "BTC", "long", "market", "trade")
1835 mouvement_mock1
= mock
.Mock()
1836 mouvement_mock1
.as_json
.return_value
= 1
1837 mouvement_mock2
= mock
.Mock()
1838 mouvement_mock2
.as_json
.return_value
= 2
1840 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1841 as_json
= order
.as_json()
1842 self
.assertEqual("buy", as_json
["action"])
1843 self
.assertEqual("long", as_json
["trade_type"])
1844 self
.assertEqual(10, as_json
["amount"])
1845 self
.assertEqual("ETH", as_json
["currency"])
1846 self
.assertEqual("BTC", as_json
["base_currency"])
1847 self
.assertEqual(D("0.1"), as_json
["rate"])
1848 self
.assertEqual("pending", as_json
["status"])
1849 self
.assertEqual(False, as_json
["close_if_possible"])
1850 self
.assertIsNone(as_json
["id"])
1851 self
.assertEqual([1, 2], as_json
["mouvements"])
1853 def test_account(self
):
1854 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1855 D("0.1"), "BTC", "long", "market", "trade")
1856 self
.assertEqual("exchange", order
.account
)
1858 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1859 D("0.1"), "BTC", "short", "market", "trade")
1860 self
.assertEqual("margin", order
.account
)
1862 def test_pending(self
):
1863 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1864 D("0.1"), "BTC", "long", "market", "trade")
1865 self
.assertTrue(order
.pending
)
1866 order
.status
= "open"
1867 self
.assertFalse(order
.pending
)
1869 def test_open(self
):
1870 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1871 D("0.1"), "BTC", "long", "market", "trade")
1872 self
.assertFalse(order
.open)
1873 order
.status
= "open"
1874 self
.assertTrue(order
.open)
1876 def test_finished(self
):
1877 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1878 D("0.1"), "BTC", "long", "market", "trade")
1879 self
.assertFalse(order
.finished
)
1880 order
.status
= "closed"
1881 self
.assertTrue(order
.finished
)
1882 order
.status
= "canceled"
1883 self
.assertTrue(order
.finished
)
1884 order
.status
= "error"
1885 self
.assertTrue(order
.finished
)
1887 @mock.patch.object(portfolio
.Order
, "fetch")
1888 def test_cancel(self
, fetch
):
1890 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1891 D("0.1"), "BTC", "long", self
.m
, "trade")
1892 order
.status
= "open"
1895 self
.m
.ccxt
.cancel_order
.assert_not_called()
1896 self
.m
.report
.log_debug_action
.assert_called_once()
1897 self
.m
.report
.log_debug_action
.reset_mock()
1898 self
.assertEqual("canceled", order
.status
)
1900 self
.m
.debug
= False
1901 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1902 D("0.1"), "BTC", "long", self
.m
, "trade")
1903 order
.status
= "open"
1907 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1908 fetch
.assert_called_once_with()
1909 self
.m
.report
.log_debug_action
.assert_not_called()
1911 def test_dust_amount_remaining(self
):
1912 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1913 D("0.1"), "BTC", "long", self
.m
, "trade")
1914 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1915 self
.assertFalse(order
.dust_amount_remaining())
1917 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1918 self
.assertTrue(order
.dust_amount_remaining())
1920 @mock.patch.object(portfolio
.Order
, "fetch")
1921 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1922 def test_remaining_amount(self
, filled_amount
, fetch
):
1923 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1924 D("0.1"), "BTC", "long", self
.m
, "trade")
1926 self
.assertEqual(9, order
.remaining_amount().value
)
1928 order
.status
= "open"
1929 self
.assertEqual(9, order
.remaining_amount().value
)
1931 @mock.patch.object(portfolio
.Order
, "fetch")
1932 def test_filled_amount(self
, fetch
):
1933 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1934 D("0.1"), "BTC", "long", self
.m
, "trade")
1935 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1936 "tradeID": 42, "type": "buy", "fee": "0.0015",
1937 "date": "2017-12-30 12:00:12", "rate": "0.1",
1938 "amount": "3", "total": "0.3"
1940 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1941 "tradeID": 43, "type": "buy", "fee": "0.0015",
1942 "date": "2017-12-30 13:00:12", "rate": "0.2",
1943 "amount": "2", "total": "0.4"
1945 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1946 fetch
.assert_not_called()
1947 order
.status
= "open"
1948 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1949 fetch
.assert_called_once()
1950 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1952 def test_fetch_mouvements(self
):
1953 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
1955 "tradeID": 42, "type": "buy", "fee": "0.0015",
1956 "date": "2017-12-30 12:00:12", "rate": "0.1",
1957 "amount": "3", "total": "0.3"
1960 "tradeID": 43, "type": "buy", "fee": "0.0015",
1961 "date": "2017-12-30 13:00:12", "rate": "0.2",
1962 "amount": "2", "total": "0.4"
1965 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1966 D("0.1"), "BTC", "long", self
.m
, "trade")
1968 order
.mouvements
= ["Foo", "Bar", "Baz"]
1970 order
.fetch_mouvements()
1972 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
1973 self
.assertEqual(2, len(order
.mouvements
))
1974 self
.assertEqual(42, order
.mouvements
[0].id)
1975 self
.assertEqual(43, order
.mouvements
[1].id)
1977 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
1978 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1979 D("0.1"), "BTC", "long", self
.m
, "trade")
1980 order
.fetch_mouvements()
1981 self
.assertEqual(0, len(order
.mouvements
))
1983 def test_mark_finished_order(self
):
1984 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1985 D("0.1"), "BTC", "short", self
.m
, "trade",
1986 close_if_possible
=True)
1987 order
.status
= "closed"
1988 self
.m
.debug
= False
1990 order
.mark_finished_order()
1991 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
1992 self
.m
.ccxt
.close_margin_position
.reset_mock()
1994 order
.status
= "open"
1995 order
.mark_finished_order()
1996 self
.m
.ccxt
.close_margin_position
.assert_not_called()
1998 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1999 D("0.1"), "BTC", "short", self
.m
, "trade",
2000 close_if_possible
=False)
2001 order
.status
= "closed"
2002 order
.mark_finished_order()
2003 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2005 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2006 D("0.1"), "BTC", "short", self
.m
, "trade",
2007 close_if_possible
=True)
2008 order
.status
= "closed"
2009 order
.mark_finished_order()
2010 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2012 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2013 D("0.1"), "BTC", "long", self
.m
, "trade",
2014 close_if_possible
=True)
2015 order
.status
= "closed"
2016 order
.mark_finished_order()
2017 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2021 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2022 D("0.1"), "BTC", "short", self
.m
, "trade",
2023 close_if_possible
=True)
2024 order
.status
= "closed"
2026 order
.mark_finished_order()
2027 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2028 self
.m
.report
.log_debug_action
.assert_called_once()
2030 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
2031 def test_fetch(self
, fetch_mouvements
):
2032 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2033 D("0.1"), "BTC", "long", self
.m
, "trade")
2035 with self
.subTest(debug
=True):
2038 self
.m
.report
.log_debug_action
.assert_called_once()
2039 self
.m
.report
.log_debug_action
.reset_mock()
2040 self
.m
.ccxt
.fetch_order
.assert_not_called()
2041 fetch_mouvements
.assert_not_called()
2043 with self
.subTest(debug
=False):
2044 self
.m
.debug
= False
2045 self
.m
.ccxt
.fetch_order
.return_value
= {
2047 "datetime": "timestamp"
2051 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
2052 fetch_mouvements
.assert_called_once()
2053 self
.assertEqual("foo", order
.status
)
2054 self
.assertEqual("timestamp", order
.timestamp
)
2055 self
.assertEqual(1, len(order
.results
))
2056 self
.m
.report
.log_debug_action
.assert_not_called()
2058 with self
.subTest(missing_order
=True):
2059 self
.m
.ccxt
.fetch_order
.side_effect
= [
2060 portfolio
.OrderNotCached
,
2063 self
.assertEqual("closed_unknown", order
.status
)
2065 @mock.patch.object(portfolio
.Order
, "fetch")
2066 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2067 def test_get_status(self
, mark_finished_order
, fetch
):
2068 with self
.subTest(debug
=True):
2070 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2071 D("0.1"), "BTC", "long", self
.m
, "trade")
2072 self
.assertEqual("pending", order
.get_status())
2073 fetch
.assert_not_called()
2074 self
.m
.report
.log_debug_action
.assert_called_once()
2076 with self
.subTest(debug
=False, finished
=False):
2077 self
.m
.debug
= False
2078 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2079 D("0.1"), "BTC", "long", self
.m
, "trade")
2081 def update_status():
2082 order
.status
= "open"
2083 return update_status
2084 fetch
.side_effect
= _fetch(order
)
2085 self
.assertEqual("open", order
.get_status())
2086 mark_finished_order
.assert_not_called()
2087 fetch
.assert_called_once()
2089 mark_finished_order
.reset_mock()
2091 with self
.subTest(debug
=False, finished
=True):
2092 self
.m
.debug
= False
2093 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2094 D("0.1"), "BTC", "long", self
.m
, "trade")
2096 def update_status():
2097 order
.status
= "closed"
2098 return update_status
2099 fetch
.side_effect
= _fetch(order
)
2100 self
.assertEqual("closed", order
.get_status())
2101 mark_finished_order
.assert_called_once()
2102 fetch
.assert_called_once()
2105 self
.m
.ccxt
.order_precision
.return_value
= 4
2106 with self
.subTest(debug
=True):
2108 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2109 D("0.1"), "BTC", "long", self
.m
, "trade")
2111 self
.m
.ccxt
.create_order
.assert_not_called()
2112 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2113 self
.assertEqual("open", order
.status
)
2114 self
.assertEqual(1, len(order
.results
))
2115 self
.assertEqual(-1, order
.id)
2117 self
.m
.ccxt
.create_order
.reset_mock()
2118 with self
.subTest(debug
=False):
2119 self
.m
.debug
= False
2120 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2121 D("0.1"), "BTC", "long", self
.m
, "trade")
2122 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2124 self
.m
.ccxt
.create_order
.assert_called_once()
2125 self
.assertEqual(1, len(order
.results
))
2126 self
.assertEqual("open", order
.status
)
2128 self
.m
.ccxt
.create_order
.reset_mock()
2129 with self
.subTest(exception
=True):
2130 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2131 D("0.1"), "BTC", "long", self
.m
, "trade")
2132 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2134 self
.m
.ccxt
.create_order
.assert_called_once()
2135 self
.assertEqual(0, len(order
.results
))
2136 self
.assertEqual("error", order
.status
)
2137 self
.m
.report
.log_error
.assert_called_once()
2139 self
.m
.ccxt
.create_order
.reset_mock()
2140 with self
.subTest(dust_amount_exception
=True),\
2141 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2142 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2143 D("0.1"), "BTC", "long", self
.m
, "trade")
2144 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2146 self
.m
.ccxt
.create_order
.assert_called_once()
2147 self
.assertEqual(0, len(order
.results
))
2148 self
.assertEqual("closed", order
.status
)
2149 mark_finished_order
.assert_called_once()
2151 self
.m
.ccxt
.order_precision
.return_value
= 8
2152 self
.m
.ccxt
.create_order
.reset_mock()
2153 with self
.subTest(insufficient_funds
=True),\
2154 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2155 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2156 D("0.1"), "BTC", "long", self
.m
, "trade")
2157 self
.m
.ccxt
.create_order
.side_effect
= [
2158 portfolio
.InsufficientFunds
,
2159 portfolio
.InsufficientFunds
,
2160 portfolio
.InsufficientFunds
,
2164 self
.m
.ccxt
.create_order
.assert_has_calls([
2165 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2166 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2167 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2168 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2170 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2171 self
.assertEqual(1, len(order
.results
))
2172 self
.assertEqual("open", order
.status
)
2173 self
.assertEqual(4, order
.tries
)
2174 self
.m
.report
.log_error
.assert_called()
2175 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2177 self
.m
.ccxt
.order_precision
.return_value
= 8
2178 self
.m
.ccxt
.create_order
.reset_mock()
2179 self
.m
.report
.log_error
.reset_mock()
2180 with self
.subTest(insufficient_funds
=True),\
2181 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2182 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2183 D("0.1"), "BTC", "long", self
.m
, "trade")
2184 self
.m
.ccxt
.create_order
.side_effect
= [
2185 portfolio
.InsufficientFunds
,
2186 portfolio
.InsufficientFunds
,
2187 portfolio
.InsufficientFunds
,
2188 portfolio
.InsufficientFunds
,
2189 portfolio
.InsufficientFunds
,
2192 self
.m
.ccxt
.create_order
.assert_has_calls([
2193 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2194 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2195 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2196 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2197 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2199 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2200 self
.assertEqual(0, len(order
.results
))
2201 self
.assertEqual("error", order
.status
)
2202 self
.assertEqual(5, order
.tries
)
2203 self
.m
.report
.log_error
.assert_called()
2204 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2205 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
)
2208 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2209 class MouvementTest(WebMockTestCase
):
2210 def test_values(self
):
2211 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2212 "tradeID": 42, "type": "buy", "fee": "0.0015",
2213 "date": "2017-12-30 12:00:12", "rate": "0.1",
2214 "amount": "10", "total": "1"
2216 self
.assertEqual("ETH", mouvement
.currency
)
2217 self
.assertEqual("BTC", mouvement
.base_currency
)
2218 self
.assertEqual(42, mouvement
.id)
2219 self
.assertEqual("buy", mouvement
.action
)
2220 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2221 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2222 self
.assertEqual(D("0.1"), mouvement
.rate
)
2223 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2224 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2226 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2227 self
.assertIsNone(mouvement
.date
)
2228 self
.assertIsNone(mouvement
.id)
2229 self
.assertIsNone(mouvement
.action
)
2230 self
.assertEqual(-1, mouvement
.fee_rate
)
2231 self
.assertEqual(0, mouvement
.rate
)
2232 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2233 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2235 def test__repr(self
):
2236 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2237 "tradeID": 42, "type": "buy", "fee": "0.0015",
2238 "date": "2017-12-30 12:00:12", "rate": "0.1",
2239 "amount": "10", "total": "1"
2241 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2243 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2244 "tradeID": 42, "type": "buy",
2245 "date": "garbage", "rate": "0.1",
2246 "amount": "10", "total": "1"
2248 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2250 def test_as_json(self
):
2251 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2252 "tradeID": 42, "type": "buy", "fee": "0.0015",
2253 "date": "2017-12-30 12:00:12", "rate": "0.1",
2254 "amount": "10", "total": "1"
2256 as_json
= mouvement
.as_json()
2258 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2259 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2260 self
.assertEqual("buy", as_json
["action"])
2261 self
.assertEqual(D("10"), as_json
["total"])
2262 self
.assertEqual(D("1"), as_json
["total_in_base"])
2263 self
.assertEqual("BTC", as_json
["base_currency"])
2264 self
.assertEqual("ETH", as_json
["currency"])
2266 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2267 class ReportStoreTest(WebMockTestCase
):
2268 def test_add_log(self
):
2269 report_store
= market
.ReportStore(self
.m
)
2270 report_store
.add_log({"foo": "bar"}
)
2272 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2274 def test_set_verbose(self
):
2275 report_store
= market
.ReportStore(self
.m
)
2276 with self
.subTest(verbose
=True):
2277 report_store
.set_verbose(True)
2278 self
.assertTrue(report_store
.verbose_print
)
2280 with self
.subTest(verbose
=False):
2281 report_store
.set_verbose(False)
2282 self
.assertFalse(report_store
.verbose_print
)
2284 def test_print_log(self
):
2285 report_store
= market
.ReportStore(self
.m
)
2286 with self
.subTest(verbose
=True),\
2287 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2288 report_store
.set_verbose(True)
2289 report_store
.print_log("Coucou")
2290 report_store
.print_log(portfolio
.Amount("BTC", 1))
2291 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2293 with self
.subTest(verbose
=False),\
2294 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2295 report_store
.set_verbose(False)
2296 report_store
.print_log("Coucou")
2297 report_store
.print_log(portfolio
.Amount("BTC", 1))
2298 self
.assertEqual(stdout_mock
.getvalue(), "")
2300 def test_to_json(self
):
2301 report_store
= market
.ReportStore(self
.m
)
2302 report_store
.logs
.append({"foo": "bar"}
)
2303 self
.assertEqual('[{"foo": "bar"}]', report_store
.to_json())
2304 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2305 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}]', report_store
.to_json())
2306 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2307 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}, {"amount": "1.00000000 BTC"}]', report_store
.to_json())
2309 @mock.patch.object(market
.ReportStore
, "print_log")
2310 @mock.patch.object(market
.ReportStore
, "add_log")
2311 def test_log_stage(self
, add_log
, print_log
):
2312 report_store
= market
.ReportStore(self
.m
)
2314 report_store
.log_stage("foo", bar
="baz", c
=c
, d
=portfolio
.Amount("BTC", 1))
2315 print_log
.assert_has_calls([
2316 mock
.call("-----------"),
2317 mock
.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
2319 add_log
.assert_called_once_with({
2324 'c': 'c = lambda x: x',
2332 @mock.patch.object(market
.ReportStore
, "print_log")
2333 @mock.patch.object(market
.ReportStore
, "add_log")
2334 def test_log_balances(self
, add_log
, print_log
):
2335 report_store
= market
.ReportStore(self
.m
)
2336 self
.m
.balances
.as_json
.return_value
= "json"
2337 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2339 report_store
.log_balances(tag
="tag")
2340 print_log
.assert_has_calls([
2341 mock
.call("[Balance]"),
2345 add_log
.assert_called_once_with({
2351 @mock.patch.object(market
.ReportStore
, "print_log")
2352 @mock.patch.object(market
.ReportStore
, "add_log")
2353 def test_log_tickers(self
, add_log
, print_log
):
2354 report_store
= market
.ReportStore(self
.m
)
2356 "BTC": portfolio
.Amount("BTC", 10),
2357 "ETH": portfolio
.Amount("BTC", D("0.3"))
2359 amounts
["ETH"].rate
= D("0.1")
2361 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2362 print_log
.assert_not_called()
2363 add_log
.assert_called_once_with({
2365 'compute_value': 'default',
2366 'balance_type': 'total',
2379 add_log
.reset_mock()
2380 compute_value
= lambda x
: x
["bid"]
2381 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
2382 add_log
.assert_called_once_with({
2384 'compute_value': 'compute_value = lambda x: x["bid"]',
2385 'balance_type': 'total',
2398 @mock.patch.object(market
.ReportStore
, "print_log")
2399 @mock.patch.object(market
.ReportStore
, "add_log")
2400 def test_log_dispatch(self
, add_log
, print_log
):
2401 report_store
= market
.ReportStore(self
.m
)
2402 amount
= portfolio
.Amount("BTC", "10.3")
2404 "BTC": portfolio
.Amount("BTC", 10),
2405 "ETH": portfolio
.Amount("BTC", D("0.3"))
2407 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2408 print_log
.assert_not_called()
2409 add_log
.assert_called_once_with({
2411 'liquidity': 'medium',
2412 'repartition_ratio': 'repartition',
2423 @mock.patch.object(market
.ReportStore
, "print_log")
2424 @mock.patch.object(market
.ReportStore
, "add_log")
2425 def test_log_trades(self
, add_log
, print_log
):
2426 report_store
= market
.ReportStore(self
.m
)
2427 trade_mock1
= mock
.Mock()
2428 trade_mock2
= mock
.Mock()
2429 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2430 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2432 matching_and_trades
= [
2433 (True, trade_mock1
),
2434 (False, trade_mock2
),
2436 report_store
.log_trades(matching_and_trades
, "only")
2438 print_log
.assert_not_called()
2439 add_log
.assert_called_with({
2444 {'trade': '1', 'skipped': False}
,
2445 {'trade': '2', 'skipped': True}
2449 @mock.patch.object(market
.ReportStore
, "print_log")
2450 @mock.patch.object(market
.ReportStore
, "add_log")
2451 def test_log_orders(self
, add_log
, print_log
):
2452 report_store
= market
.ReportStore(self
.m
)
2454 order_mock1
= mock
.Mock()
2455 order_mock2
= mock
.Mock()
2457 order_mock1
.as_json
.return_value
= "order1"
2458 order_mock2
.as_json
.return_value
= "order2"
2460 orders
= [order_mock1
, order_mock2
]
2462 report_store
.log_orders(orders
, tick
="tick",
2463 only
="only", compute_value
="compute_value")
2465 print_log
.assert_called_once_with("[Orders]")
2466 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2468 add_log
.assert_called_with({
2471 'compute_value': 'compute_value',
2473 'orders': ['order1', 'order2']
2476 add_log
.reset_mock()
2477 def compute_value(x
, y
):
2479 report_store
.log_orders(orders
, tick
="tick",
2480 only
="only", compute_value
=compute_value
)
2481 add_log
.assert_called_with({
2484 'compute_value': 'def compute_value(x, y):\n return x[y]',
2486 'orders': ['order1', 'order2']
2490 @mock.patch.object(market
.ReportStore
, "print_log")
2491 @mock.patch.object(market
.ReportStore
, "add_log")
2492 def test_log_order(self
, add_log
, print_log
):
2493 report_store
= market
.ReportStore(self
.m
)
2494 order_mock
= mock
.Mock()
2495 order_mock
.as_json
.return_value
= "order"
2496 new_order_mock
= mock
.Mock()
2497 new_order_mock
.as_json
.return_value
= "new_order"
2498 order_mock
.__repr
__ = mock
.Mock()
2499 order_mock
.__repr
__.return_value
= "Order Mock"
2500 new_order_mock
.__repr
__ = mock
.Mock()
2501 new_order_mock
.__repr
__.return_value
= "New order Mock"
2503 with self
.subTest(finished
=True):
2504 report_store
.log_order(order_mock
, 1, finished
=True)
2505 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2506 add_log
.assert_called_once_with({
2511 'compute_value': None,
2515 add_log
.reset_mock()
2516 print_log
.reset_mock()
2518 with self
.subTest(update
="waiting"):
2519 report_store
.log_order(order_mock
, 1, update
="waiting")
2520 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2521 add_log
.assert_called_once_with({
2524 'update': 'waiting',
2526 'compute_value': None,
2530 add_log
.reset_mock()
2531 print_log
.reset_mock()
2532 with self
.subTest(update
="adjusting"):
2533 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
2534 report_store
.log_order(order_mock
, 3,
2535 update
="adjusting", new_order
=new_order_mock
,
2536 compute_value
=compute_value
)
2537 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2538 add_log
.assert_called_once_with({
2541 'update': 'adjusting',
2543 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
2544 'new_order': 'new_order'
2547 add_log
.reset_mock()
2548 print_log
.reset_mock()
2549 with self
.subTest(update
="market_fallback"):
2550 report_store
.log_order(order_mock
, 7,
2551 update
="market_fallback", new_order
=new_order_mock
)
2552 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2553 add_log
.assert_called_once_with({
2556 'update': 'market_fallback',
2558 'compute_value': None,
2559 'new_order': 'new_order'
2562 add_log
.reset_mock()
2563 print_log
.reset_mock()
2564 with self
.subTest(update
="market_adjusting"):
2565 report_store
.log_order(order_mock
, 17,
2566 update
="market_adjust", new_order
=new_order_mock
)
2567 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2568 add_log
.assert_called_once_with({
2571 'update': 'market_adjust',
2573 'compute_value': None,
2574 'new_order': 'new_order'
2577 @mock.patch.object(market
.ReportStore
, "print_log")
2578 @mock.patch.object(market
.ReportStore
, "add_log")
2579 def test_log_move_balances(self
, add_log
, print_log
):
2580 report_store
= market
.ReportStore(self
.m
)
2582 "BTC": portfolio
.Amount("BTC", 10),
2586 "BTC": portfolio
.Amount("BTC", 3),
2589 report_store
.log_move_balances(needed
, moving
)
2590 print_log
.assert_not_called()
2591 add_log
.assert_called_once_with({
2592 'type': 'move_balances',
2604 @mock.patch.object(market
.ReportStore
, "print_log")
2605 @mock.patch.object(market
.ReportStore
, "add_log")
2606 def test_log_http_request(self
, add_log
, print_log
):
2607 report_store
= market
.ReportStore(self
.m
)
2608 response
= mock
.Mock()
2609 response
.status_code
= 200
2610 response
.text
= "Hey"
2612 report_store
.log_http_request("method", "url", "body",
2613 "headers", response
)
2614 print_log
.assert_not_called()
2615 add_log
.assert_called_once_with({
2616 'type': 'http_request',
2620 'headers': 'headers',
2625 @mock.patch.object(market
.ReportStore
, "print_log")
2626 @mock.patch.object(market
.ReportStore
, "add_log")
2627 def test_log_error(self
, add_log
, print_log
):
2628 report_store
= market
.ReportStore(self
.m
)
2629 with self
.subTest(message
=None, exception
=None):
2630 report_store
.log_error("action")
2631 print_log
.assert_called_once_with("[Error] action")
2632 add_log
.assert_called_once_with({
2635 'exception_class': None,
2636 'exception_message': None,
2640 print_log
.reset_mock()
2641 add_log
.reset_mock()
2642 with self
.subTest(message
="Hey", exception
=None):
2643 report_store
.log_error("action", message
="Hey")
2644 print_log
.assert_has_calls([
2645 mock
.call("[Error] action"),
2648 add_log
.assert_called_once_with({
2651 'exception_class': None,
2652 'exception_message': None,
2656 print_log
.reset_mock()
2657 add_log
.reset_mock()
2658 with self
.subTest(message
=None, exception
=Exception("bouh")):
2659 report_store
.log_error("action", exception
=Exception("bouh"))
2660 print_log
.assert_has_calls([
2661 mock
.call("[Error] action"),
2662 mock
.call("\tException: bouh")
2664 add_log
.assert_called_once_with({
2667 'exception_class': "Exception",
2668 'exception_message': "bouh",
2672 print_log
.reset_mock()
2673 add_log
.reset_mock()
2674 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2675 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2676 print_log
.assert_has_calls([
2677 mock
.call("[Error] action"),
2678 mock
.call("\tException: bouh"),
2681 add_log
.assert_called_once_with({
2684 'exception_class': "Exception",
2685 'exception_message': "bouh",
2689 @mock.patch.object(market
.ReportStore
, "print_log")
2690 @mock.patch.object(market
.ReportStore
, "add_log")
2691 def test_log_debug_action(self
, add_log
, print_log
):
2692 report_store
= market
.ReportStore(self
.m
)
2693 report_store
.log_debug_action("Hey")
2695 print_log
.assert_called_once_with("[Debug] Hey")
2696 add_log
.assert_called_once_with({
2697 'type': 'debug_action',
2701 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2702 class HelperTest(WebMockTestCase
):
2703 def test_make_order(self
):
2704 self
.m
.get_ticker
.return_value
= {
2706 "average": D("0.1"),
2711 with self
.subTest(description
="nominal case"):
2712 helper
.make_order(self
.m
, 10, "ETH")
2714 self
.m
.report
.log_stage
.assert_has_calls([
2715 mock
.call("make_order_begin"),
2716 mock
.call("make_order_end"),
2718 self
.m
.balances
.fetch_balances
.assert_has_calls([
2719 mock
.call(tag
="make_order_begin"),
2720 mock
.call(tag
="make_order_end"),
2722 self
.m
.trades
.all
.append
.assert_called_once()
2723 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2724 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2725 self
.assertEqual(0, trade
.value_from
)
2726 self
.assertEqual("ETH", trade
.currency
)
2727 self
.assertEqual("BTC", trade
.base_currency
)
2728 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2729 self
.m
.trades
.run_orders
.assert_called_once_with()
2730 self
.m
.follow_orders
.assert_called_once_with()
2732 order
= trade
.orders
[0]
2733 self
.assertEqual(D("0.10"), order
.rate
)
2736 with self
.subTest(compute_value
="default"):
2737 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2738 compute_value
="ask")
2740 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2741 order
= trade
.orders
[0]
2742 self
.assertEqual(D("0.11"), order
.rate
)
2745 with self
.subTest(follow
=False):
2746 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2748 self
.m
.report
.log_stage
.assert_has_calls([
2749 mock
.call("make_order_begin"),
2750 mock
.call("make_order_end_not_followed"),
2752 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2754 self
.m
.trades
.all
.append
.assert_called_once()
2755 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2756 self
.assertEqual(0, trade
.value_from
)
2757 self
.assertEqual("ETH", trade
.currency
)
2758 self
.assertEqual("BTC", trade
.base_currency
)
2759 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2760 self
.m
.trades
.run_orders
.assert_called_once_with()
2761 self
.m
.follow_orders
.assert_not_called()
2762 self
.assertEqual(trade
.orders
[0], result
)
2765 with self
.subTest(base_currency
="USDT"):
2766 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2768 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2769 self
.assertEqual("BTC", trade
.currency
)
2770 self
.assertEqual("USDT", trade
.base_currency
)
2773 with self
.subTest(close_if_possible
=True):
2774 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2776 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2777 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2780 with self
.subTest(action
="dispose"):
2781 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2783 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2784 self
.assertEqual(0, trade
.value_to
)
2785 self
.assertEqual(1, trade
.value_from
.value
)
2786 self
.assertEqual("ETH", trade
.currency
)
2787 self
.assertEqual("BTC", trade
.base_currency
)
2790 with self
.subTest(compute_value
="default"):
2791 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2792 compute_value
="bid")
2794 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2795 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2797 def test_user_market(self
):
2798 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2799 mock
.patch("helper.main_parse_config") as main_parse_config
:
2800 with self
.subTest(debug
=False):
2801 main_parse_config
.return_value
= ["pg_config", "report_path"]
2802 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2803 m
= helper
.get_user_market("config_path.ini", 1)
2805 self
.assertIsInstance(m
, market
.Market
)
2806 self
.assertFalse(m
.debug
)
2808 with self
.subTest(debug
=True):
2809 main_parse_config
.return_value
= ["pg_config", "report_path"]
2810 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2811 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2813 self
.assertIsInstance(m
, market
.Market
)
2814 self
.assertTrue(m
.debug
)
2816 def test_main_store_report(self
):
2817 file_open
= mock
.mock_open()
2818 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2819 helper
.main_store_report(None, 1, self
.m
)
2820 file_open
.assert_not_called()
2822 file_open
= mock
.mock_open()
2823 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2824 mock
.patch
.object(helper
, "datetime") as time_mock
:
2825 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2826 self
.m
.report
.to_json
.return_value
= "json_content"
2828 helper
.main_store_report("present", 1, self
.m
)
2830 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2831 file_open().write
.assert_called_once_with("json_content")
2832 self
.m
.report
.to_json
.assert_called_once_with()
2834 with self
.subTest(file="error"),\
2835 mock
.patch("helper.open") as file_open
,\
2836 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2837 file_open
.side_effect
= FileNotFoundError
2839 helper
.main_store_report("error", 1, self
.m
)
2841 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2843 @mock.patch("helper.process_sell_all__1_all_sell")
2844 @mock.patch("helper.process_sell_all__2_wait")
2845 @mock.patch("helper.process_sell_all__3_all_buy")
2846 def test_main_process_market(self
, buy
, wait
, sell
):
2847 with self
.subTest(before
=False, after
=False):
2848 helper
.main_process_market("user", None)
2850 wait
.assert_not_called()
2851 buy
.assert_not_called()
2852 sell
.assert_not_called()
2857 with self
.subTest(before
=True, after
=False):
2858 helper
.main_process_market("user", None, before
=True)
2860 wait
.assert_not_called()
2861 buy
.assert_not_called()
2862 sell
.assert_called_once_with("user")
2867 with self
.subTest(before
=False, after
=True):
2868 helper
.main_process_market("user", None, after
=True)
2870 wait
.assert_called_once_with("user")
2871 buy
.assert_called_once_with("user")
2872 sell
.assert_not_called()
2877 with self
.subTest(before
=True, after
=True):
2878 helper
.main_process_market("user", None, before
=True, after
=True)
2880 wait
.assert_called_once_with("user")
2881 buy
.assert_called_once_with("user")
2882 sell
.assert_called_once_with("user")
2887 with self
.subTest(action
="print_balances"),\
2888 mock
.patch("helper.print_balances") as print_balances
:
2889 helper
.main_process_market("user", ["print_balances"])
2891 buy
.assert_not_called()
2892 wait
.assert_not_called()
2893 sell
.assert_not_called()
2894 print_balances
.assert_called_once_with("user")
2896 with self
.subTest(action
="print_orders"),\
2897 mock
.patch("helper.print_orders") as print_orders
,\
2898 mock
.patch("helper.print_balances") as print_balances
:
2899 helper
.main_process_market("user", ["print_orders", "print_balances"])
2901 buy
.assert_not_called()
2902 wait
.assert_not_called()
2903 sell
.assert_not_called()
2904 print_orders
.assert_called_once_with("user")
2905 print_balances
.assert_called_once_with("user")
2907 with self
.subTest(action
="unknown"),\
2908 self
.assertRaises(NotImplementedError):
2909 helper
.main_process_market("user", ["unknown"])
2911 @mock.patch.object(helper
, "psycopg2")
2912 def test_fetch_markets(self
, psycopg2
):
2913 connect_mock
= mock
.Mock()
2914 cursor_mock
= mock
.MagicMock()
2915 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2917 connect_mock
.cursor
.return_value
= cursor_mock
2918 psycopg2
.connect
.return_value
= connect_mock
2920 with self
.subTest(user
=None):
2921 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2923 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2924 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2926 self
.assertEqual(["row_1", "row_2"], rows
)
2928 psycopg2
.connect
.reset_mock()
2929 cursor_mock
.execute
.reset_mock()
2930 with self
.subTest(user
=1):
2931 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
2933 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2934 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
2936 self
.assertEqual(["row_1", "row_2"], rows
)
2938 @mock.patch.object(helper
.sys
, "exit")
2939 def test_main_parse_args(self
, exit
):
2940 with self
.subTest(config
="config.ini"):
2941 args
= helper
.main_parse_args([])
2942 self
.assertEqual("config.ini", args
.config
)
2943 self
.assertFalse(args
.before
)
2944 self
.assertFalse(args
.after
)
2945 self
.assertFalse(args
.debug
)
2947 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
2948 self
.assertTrue(args
.before
)
2949 self
.assertTrue(args
.after
)
2950 self
.assertTrue(args
.debug
)
2952 exit
.assert_not_called()
2954 with self
.subTest(config
="inexistant"),\
2955 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2956 args
= helper
.main_parse_args(["--config", "foo.bar"])
2957 exit
.assert_called_once_with(1)
2958 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
2960 @mock.patch.object(helper
.sys
, "exit")
2961 @mock.patch("helper.configparser")
2962 @mock.patch("helper.os")
2963 def test_main_parse_config(self
, os
, configparser
, exit
):
2964 with self
.subTest(pg_config
=True, report_path
=None):
2965 config_mock
= mock
.MagicMock()
2966 configparser
.ConfigParser
.return_value
= config_mock
2967 def config(element
):
2968 return element
== "postgresql"
2970 config_mock
.__contains
__.side_effect
= config
2971 config_mock
.__getitem
__.return_value
= "pg_config"
2973 result
= helper
.main_parse_config("configfile")
2975 config_mock
.read
.assert_called_with("configfile")
2977 self
.assertEqual(["pg_config", None], result
)
2979 with self
.subTest(pg_config
=True, report_path
="present"):
2980 config_mock
= mock
.MagicMock()
2981 configparser
.ConfigParser
.return_value
= config_mock
2983 config_mock
.__contains
__.return_value
= True
2984 config_mock
.__getitem
__.side_effect
= [
2985 {"report_path": "report_path"}
,
2986 {"report_path": "report_path"}
,
2990 os
.path
.exists
.return_value
= False
2991 result
= helper
.main_parse_config("configfile")
2993 config_mock
.read
.assert_called_with("configfile")
2994 self
.assertEqual(["pg_config", "report_path"], result
)
2995 os
.path
.exists
.assert_called_once_with("report_path")
2996 os
.makedirs
.assert_called_once_with("report_path")
2998 with self
.subTest(pg_config
=False),\
2999 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3000 config_mock
= mock
.MagicMock()
3001 configparser
.ConfigParser
.return_value
= config_mock
3002 result
= helper
.main_parse_config("configfile")
3004 config_mock
.read
.assert_called_with("configfile")
3005 exit
.assert_called_once_with(1)
3006 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
3009 def test_print_orders(self
):
3010 helper
.print_orders(self
.m
)
3012 self
.m
.report
.log_stage
.assert_called_with("print_orders")
3013 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
3014 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3015 compute_value
="average")
3016 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3018 def test_print_balances(self
):
3019 self
.m
.balances
.in_currency
.return_value
= {
3020 "BTC": portfolio
.Amount("BTC", "0.65"),
3021 "ETH": portfolio
.Amount("BTC", "0.3"),
3024 helper
.print_balances(self
.m
)
3026 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
3027 self
.m
.balances
.fetch_balances
.assert_called_with()
3028 self
.m
.report
.print_log
.assert_has_calls([
3029 mock
.call("total:"),
3030 mock
.call(portfolio
.Amount("BTC", "0.95")),
3033 def test_process_sell_needed__1_sell(self
):
3034 helper
.process_sell_needed__1_sell(self
.m
)
3036 self
.m
.balances
.fetch_balances
.assert_has_calls([
3037 mock
.call(tag
="process_sell_needed__1_sell_begin"),
3038 mock
.call(tag
="process_sell_needed__1_sell_end"),
3040 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3042 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3044 self
.m
.trades
.run_orders
.assert_called()
3045 self
.m
.follow_orders
.assert_called()
3046 self
.m
.report
.log_stage
.assert_has_calls([
3047 mock
.call("process_sell_needed__1_sell_begin"),
3048 mock
.call("process_sell_needed__1_sell_end")
3051 def test_process_sell_needed__2_buy(self
):
3052 helper
.process_sell_needed__2_buy(self
.m
)
3054 self
.m
.balances
.fetch_balances
.assert_has_calls([
3055 mock
.call(tag
="process_sell_needed__2_buy_begin"),
3056 mock
.call(tag
="process_sell_needed__2_buy_end"),
3058 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3059 liquidity
="medium", only
="acquire")
3060 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3062 self
.m
.move_balances
.assert_called_with()
3063 self
.m
.trades
.run_orders
.assert_called()
3064 self
.m
.follow_orders
.assert_called()
3065 self
.m
.report
.log_stage
.assert_has_calls([
3066 mock
.call("process_sell_needed__2_buy_begin"),
3067 mock
.call("process_sell_needed__2_buy_end")
3070 def test_process_sell_all__1_sell(self
):
3071 helper
.process_sell_all__1_all_sell(self
.m
)
3073 self
.m
.balances
.fetch_balances
.assert_has_calls([
3074 mock
.call(tag
="process_sell_all__1_all_sell_begin"),
3075 mock
.call(tag
="process_sell_all__1_all_sell_end"),
3077 self
.m
.prepare_trades_to_sell_all
.assert_called_with(base_currency
="BTC")
3078 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3079 self
.m
.trades
.run_orders
.assert_called()
3080 self
.m
.follow_orders
.assert_called()
3081 self
.m
.report
.log_stage
.assert_has_calls([
3082 mock
.call("process_sell_all__1_all_sell_begin"),
3083 mock
.call("process_sell_all__1_all_sell_end")
3086 @mock.patch("portfolio.Portfolio.wait_for_recent")
3087 def test_process_sell_all__2_wait(self
, wait
):
3088 helper
.process_sell_all__2_wait(self
.m
)
3090 wait
.assert_called_once_with(self
.m
)
3091 self
.m
.report
.log_stage
.assert_has_calls([
3092 mock
.call("process_sell_all__2_wait_begin"),
3093 mock
.call("process_sell_all__2_wait_end")
3096 def test_process_sell_all__3_all_buy(self
):
3097 helper
.process_sell_all__3_all_buy(self
.m
)
3099 self
.m
.balances
.fetch_balances
.assert_has_calls([
3100 mock
.call(tag
="process_sell_all__3_all_buy_begin"),
3101 mock
.call(tag
="process_sell_all__3_all_buy_end"),
3103 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3105 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3106 self
.m
.move_balances
.assert_called_with()
3107 self
.m
.trades
.run_orders
.assert_called()
3108 self
.m
.follow_orders
.assert_called()
3109 self
.m
.report
.log_stage
.assert_has_calls([
3110 mock
.call("process_sell_all__3_all_buy_begin"),
3111 mock
.call("process_sell_all__3_all_buy_end")
3114 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3115 class AcceptanceTest(WebMockTestCase
):
3116 @unittest.expectedFailure
3117 def test_success_sell_only_necessary(self
):
3118 # FIXME: catch stdout
3119 self
.m
.report
.verbose_print
= False
3122 "exchange_free": D("1.0"),
3123 "exchange_used": D("0.0"),
3124 "exchange_total": D("1.0"),
3128 "exchange_free": D("4.0"),
3129 "exchange_used": D("0.0"),
3130 "exchange_total": D("4.0"),
3134 "exchange_free": D("1000.0"),
3135 "exchange_used": D("0.0"),
3136 "exchange_total": D("1000.0"),
3137 "total": D("1000.0"),
3141 "ETH": (D("0.25"), "long"),
3142 "ETC": (D("0.25"), "long"),
3143 "BTC": (D("0.4"), "long"),
3144 "BTD": (D("0.01"), "short"),
3145 "B2X": (D("0.04"), "long"),
3146 "USDT": (D("0.05"), "long"),
3149 def fetch_ticker(symbol
):
3150 if symbol
== "ETH/BTC":
3152 "symbol": "ETH/BTC",
3156 if symbol
== "ETC/BTC":
3158 "symbol": "ETC/BTC",
3162 if symbol
== "XVG/BTC":
3164 "symbol": "XVG/BTC",
3165 "bid": D("0.00003"),
3168 if symbol
== "BTD/BTC":
3170 "symbol": "BTD/BTC",
3174 if symbol
== "B2X/BTC":
3176 "symbol": "B2X/BTC",
3180 if symbol
== "USDT/BTC":
3181 raise helper
.ExchangeError
3182 if symbol
== "BTC/USDT":
3184 "symbol": "BTC/USDT",
3188 self
.fail("Shouldn't have been called with {}".format(symbol
))
3190 market
= mock
.Mock()
3191 market
.fetch_all_balances
.return_value
= fetch_balance
3192 market
.fetch_ticker
.side_effect
= fetch_ticker
3193 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3195 helper
.prepare_trades(market
)
3197 balances
= portfolio
.BalanceStore
.all
3198 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3199 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3200 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3203 trades
= portfolio
.TradeStore
.all
3204 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3205 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3206 self
.assertEqual("dispose", trades
[0].action
)
3208 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3209 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3210 self
.assertEqual("acquire", trades
[1].action
)
3212 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3213 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3214 self
.assertEqual("dispose", trades
[2].action
)
3216 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3217 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3218 self
.assertEqual("acquire", trades
[3].action
)
3220 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3221 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3222 self
.assertEqual("acquire", trades
[4].action
)
3224 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3225 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3226 self
.assertEqual("acquire", trades
[5].action
)
3229 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3231 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3232 self
.assertEqual(2, len(all_orders
))
3233 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3234 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3235 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3236 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3239 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3240 self
.assertEqual("limit", type)
3241 if symbol
== "ETH/BTC":
3242 self
.assertEqual("sell", action
)
3243 self
.assertEqual(D('0.66666666'), amount
)
3244 self
.assertEqual(D("0.14014"), price
)
3245 elif symbol
== "XVG/BTC":
3246 self
.assertEqual("sell", action
)
3247 self
.assertEqual(1000, amount
)
3248 self
.assertEqual(D("0.00003003"), price
)
3250 self
.fail("I shouldn't have been called")
3255 market
.create_order
.side_effect
= create_order
3256 market
.order_precision
.return_value
= 8
3259 portfolio
.TradeStore
.run_orders()
3261 self
.assertEqual("open", all_orders
[0].status
)
3262 self
.assertEqual("open", all_orders
[1].status
)
3264 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3265 market
.privatePostReturnOrderTrades
.return_value
= [
3267 "tradeID": 42, "type": "buy", "fee": "0.0015",
3268 "date": "2017-12-30 12:00:12", "rate": "0.1",
3269 "amount": "10", "total": "1"
3272 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3274 helper
.follow_orders(verbose
=False)
3276 sleep
.assert_called_with(30)
3278 for order
in all_orders
:
3279 self
.assertEqual("closed", order
.status
)
3283 "exchange_free": D("1.0") / 3,
3284 "exchange_used": D("0.0"),
3285 "exchange_total": D("1.0") / 3,
3287 "total": D("1.0") / 3,
3290 "exchange_free": D("0.134"),
3291 "exchange_used": D("0.0"),
3292 "exchange_total": D("0.134"),
3294 "total": D("0.134"),
3297 "exchange_free": D("4.0"),
3298 "exchange_used": D("0.0"),
3299 "exchange_total": D("4.0"),
3304 "exchange_free": D("0.0"),
3305 "exchange_used": D("0.0"),
3306 "exchange_total": D("0.0"),
3311 market
.fetch_all_balances
.return_value
= fetch_balance
3313 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3315 helper
.prepare_trades(market
, only
="acquire", compute_value
="average")
3317 balances
= portfolio
.BalanceStore
.all
3318 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3319 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3320 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3321 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3324 trades
= portfolio
.TradeStore
.all
3325 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3326 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3327 self
.assertEqual("dispose", trades
[0].action
)
3329 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3330 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3331 self
.assertEqual("acquire", trades
[1].action
)
3333 self
.assertNotIn("BTC", trades
)
3335 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3336 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3337 self
.assertEqual("dispose", trades
[2].action
)
3339 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3340 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3341 self
.assertEqual("acquire", trades
[3].action
)
3343 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3344 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3345 self
.assertEqual("acquire", trades
[4].action
)
3347 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3348 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3349 self
.assertEqual("acquire", trades
[5].action
)
3352 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3354 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3355 self
.assertEqual(4, len(all_orders
))
3356 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3357 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3358 self
.assertEqual("buy", all_orders
[0].action
)
3359 self
.assertEqual("long", all_orders
[0].trade_type
)
3361 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3362 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3363 self
.assertEqual("sell", all_orders
[1].action
)
3364 self
.assertEqual("short", all_orders
[1].trade_type
)
3366 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3367 self
.assertAlmostEqual(0, diff
.value
)
3368 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3369 self
.assertEqual("buy", all_orders
[2].action
)
3370 self
.assertEqual("long", all_orders
[2].trade_type
)
3372 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3373 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3374 self
.assertEqual("sell", all_orders
[3].action
)
3375 self
.assertEqual("long", all_orders
[3].trade_type
)
3379 # Move balances to margin
3383 # portfolio.TradeStore.run_orders()
3385 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3387 helper
.follow_orders(verbose
=False)
3389 sleep
.assert_called_with(30)
3391 if __name__
== '__main__':