5 from decimal
import Decimal
as D
6 from unittest
import mock
9 from io
import StringIO
10 import portfolio
, helper
, market
12 limits
= ["acceptance", "unit"]
13 for test_type
in limits
:
14 if "--no{}".format(test_type
) in sys
.argv
:
15 sys
.argv
.remove("--no{}".format(test_type
))
16 limits
.remove(test_type
)
17 if "--only{}".format(test_type
) in sys
.argv
:
18 sys
.argv
.remove("--only{}".format(test_type
))
22 class WebMockTestCase(unittest
.TestCase
):
26 super(WebMockTestCase
, self
).setUp()
27 self
.wm
= requests_mock
.Mocker()
31 self
.m
= mock
.Mock(name
="Market", spec
=market
.Market
)
35 mock
.patch
.multiple(portfolio
.Portfolio
, last_date
=None, data
=None, liquidities
={}),
36 mock
.patch
.multiple(portfolio
.Computation
,
37 computations
=portfolio
.Computation
.computations
),
39 for patcher
in self
.patchers
:
43 for patcher
in self
.patchers
:
46 super(WebMockTestCase
, self
).tearDown()
48 @unittest.skipUnless("unit" in limits
, "Unit skipped")
49 class poloniexETest(unittest
.TestCase
):
51 super(poloniexETest
, self
).setUp()
52 self
.wm
= requests_mock
.Mocker()
55 self
.s
= market
.ccxt
.poloniexE()
59 super(poloniexETest
, self
).tearDown()
61 def test_nanoseconds(self
):
62 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
63 time
.return_value
= 123456.7890123456
64 self
.assertEqual(123456789012345, self
.s
.nanoseconds())
67 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
68 time
.return_value
= 123456.7890123456
69 self
.assertEqual(123456789012345, self
.s
.nonce())
71 def test_order_precision(self
):
72 self
.assertEqual(8, self
.s
.order_precision("FOO"))
74 def test_transfer_balance(self
):
75 with self
.subTest(success
=True),\
76 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
77 t
.return_value
= { "success": 1 }
78 result
= self
.s
.transfer_balance("FOO", 12, "exchange", "margin")
79 t
.assert_called_once_with({
82 "fromAccount": "exchange",
83 "toAccount": "margin",
86 self
.assertTrue(result
)
88 with self
.subTest(success
=False),\
89 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
90 t
.return_value
= { "success": 0 }
91 self
.assertFalse(self
.s
.transfer_balance("FOO", 12, "exchange", "margin"))
93 def test_close_margin_position(self
):
94 with mock
.patch
.object(self
.s
, "privatePostCloseMarginPosition") as c
:
95 self
.s
.close_margin_position("FOO", "BAR")
96 c
.assert_called_with({"currencyPair": "BAR_FOO"}
)
98 def test_tradable_balances(self
):
99 with mock
.patch
.object(self
.s
, "privatePostReturnTradableBalances") as r
:
101 "FOO": { "exchange": "12.1234", "margin": "0.0123" }
,
102 "BAR": { "exchange": "1", "margin": "0" }
,
104 balances
= self
.s
.tradable_balances()
105 self
.assertEqual(["FOO", "BAR"], list(balances
.keys()))
106 self
.assertEqual(["exchange", "margin"], list(balances
["FOO"].keys()))
107 self
.assertEqual(D("12.1234"), balances
["FOO"]["exchange"])
108 self
.assertEqual(["exchange", "margin"], list(balances
["BAR"].keys()))
110 def test_margin_summary(self
):
111 with mock
.patch
.object(self
.s
, "privatePostReturnMarginAccountSummary") as r
:
113 "currentMargin": "1.49680968",
114 "lendingFees": "0.0000001",
116 "totalBorrowedValue": "0.00673602",
117 "totalValue": "0.01000000",
118 "netValue": "0.01008254",
121 'current_margin': D('1.49680968'),
122 'gains': D('0.00008254'),
123 'lending_fees': D('0.0000001'),
124 'total': D('0.01000000'),
125 'total_borrowed': D('0.00673602')
127 self
.assertEqual(expected
, self
.s
.margin_summary())
129 @unittest.skipUnless("unit" in limits
, "Unit skipped")
130 class PortfolioTest(WebMockTestCase
):
132 if self
.json_response
is not None:
133 portfolio
.Portfolio
.data
= self
.json_response
136 super(PortfolioTest
, self
).setUp()
138 with open("test_portfolio.json") as example
:
139 self
.json_response
= example
.read()
141 self
.wm
.get(portfolio
.Portfolio
.URL
, text
=self
.json_response
)
143 def test_get_cryptoportfolio(self
):
144 self
.wm
.get(portfolio
.Portfolio
.URL
, [
145 {"text":'{ "foo": "bar" }
', "status_code": 200},
146 {"text": "System Error", "status_code": 500},
147 {"exc": requests.exceptions.ConnectTimeout},
149 portfolio.Portfolio.get_cryptoportfolio(self.m)
150 self.assertIn("foo", portfolio.Portfolio.data)
151 self.assertEqual("bar", portfolio.Portfolio.data["foo"])
152 self.assertTrue(self.wm.called)
153 self.assertEqual(1, self.wm.call_count)
154 self.m.report.log_error.assert_not_called()
155 self.m.report.log_http_request.assert_called_once()
156 self.m.report.log_http_request.reset_mock()
158 portfolio.Portfolio.get_cryptoportfolio(self.m)
159 self.assertIsNone(portfolio.Portfolio.data)
160 self.assertEqual(2, self.wm.call_count)
161 self.m.report.log_error.assert_not_called()
162 self.m.report.log_http_request.assert_called_once()
163 self.m.report.log_http_request.reset_mock()
166 portfolio.Portfolio.data = "Foo"
167 portfolio.Portfolio.get_cryptoportfolio(self.m)
168 self.assertEqual("Foo", portfolio.Portfolio.data)
169 self.assertEqual(3, self.wm.call_count)
170 self.m.report.log_error.assert_called_once_with("get_cryptoportfolio",
172 self.m.report.log_http_request.assert_not_called()
174 def test_parse_cryptoportfolio(self):
175 portfolio.Portfolio.parse_cryptoportfolio(self.m)
177 self.assertListEqual(
179 list(portfolio.Portfolio.liquidities.keys()))
181 liquidities = portfolio.Portfolio.liquidities
182 self.assertEqual(10, len(liquidities["medium"].keys()))
183 self.assertEqual(10, len(liquidities["high"].keys()))
186 'BTC
': (D("0.2857"), "long"),
187 'DGB
': (D("0.1015"), "long"),
188 'DOGE
': (D("0.1805"), "long"),
189 'SC
': (D("0.0623"), "long"),
190 'ZEC
': (D("0.3701"), "long"),
192 date = portfolio.datetime(2018, 1, 8)
193 self.assertDictEqual(expected, liquidities["high"][date])
196 'BTC
': (D("1.1102e-16"), "long"),
197 'ETC
': (D("0.1"), "long"),
198 'FCT
': (D("0.1"), "long"),
199 'GAS
': (D("0.1"), "long"),
200 'NAV
': (D("0.1"), "long"),
201 'OMG
': (D("0.1"), "long"),
202 'OMNI
': (D("0.1"), "long"),
203 'PPC
': (D("0.1"), "long"),
204 'RIC
': (D("0.1"), "long"),
205 'VIA
': (D("0.1"), "long"),
206 'XCP
': (D("0.1"), "long"),
208 self.assertDictEqual(expected, liquidities["medium"][date])
209 self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date)
211 self.m.report.log_http_request.assert_called_once_with("GET",
212 portfolio.Portfolio.URL, None, mock.ANY, mock.ANY)
213 self.m.report.log_http_request.reset_mock()
215 # It doesn't refetch the data when available
216 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
)
217 self
.m
.report
.log_http_request
.assert_not_called()
219 self
.assertEqual(1, self
.wm
.call_count
)
221 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
, refetch
=True)
222 self
.assertEqual(2, self
.wm
.call_count
)
223 self
.m
.report
.log_http_request
.assert_called_once()
225 def test_repartition(self
):
227 'BTC': (D("1.1102e-16"), "long"),
228 'USDT': (D("0.1"), "long"),
229 'ETC': (D("0.1"), "long"),
230 'FCT': (D("0.1"), "long"),
231 'OMG': (D("0.1"), "long"),
232 'STEEM': (D("0.1"), "long"),
233 'STRAT': (D("0.1"), "long"),
234 'XEM': (D("0.1"), "long"),
235 'XMR': (D("0.1"), "long"),
236 'XVC': (D("0.1"), "long"),
237 'ZRX': (D("0.1"), "long"),
240 'USDT': (D("0.1226"), "long"),
241 'BTC': (D("0.1429"), "long"),
242 'ETC': (D("0.1127"), "long"),
243 'ETH': (D("0.1569"), "long"),
244 'FCT': (D("0.3341"), "long"),
245 'GAS': (D("0.1308"), "long"),
248 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
))
249 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="medium"))
250 self
.assertEqual(expected_high
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="high"))
252 self
.assertEqual(1, self
.wm
.call_count
)
254 portfolio
.Portfolio
.repartition(self
.m
)
255 self
.assertEqual(1, self
.wm
.call_count
)
257 portfolio
.Portfolio
.repartition(self
.m
, refetch
=True)
258 self
.assertEqual(2, self
.wm
.call_count
)
259 self
.m
.report
.log_http_request
.assert_called()
260 self
.assertEqual(2, self
.m
.report
.log_http_request
.call_count
)
262 @mock.patch.object(portfolio
.time
, "sleep")
263 @mock.patch.object(portfolio
.Portfolio
, "repartition")
264 def test_wait_for_recent(self
, repartition
, sleep
):
266 def _repartition(market
, refetch
):
267 self
.assertEqual(self
.m
, market
)
268 self
.assertTrue(refetch
)
270 portfolio
.Portfolio
.last_date
= portfolio
.datetime
.now()\
271 - portfolio
.timedelta(10)\
272 + portfolio
.timedelta(self
.call_count
)
273 repartition
.side_effect
= _repartition
275 portfolio
.Portfolio
.wait_for_recent(self
.m
)
276 sleep
.assert_called_with(30)
277 self
.assertEqual(6, sleep
.call_count
)
278 self
.assertEqual(7, repartition
.call_count
)
279 self
.m
.report
.print_log
.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
282 repartition
.reset_mock()
283 portfolio
.Portfolio
.last_date
= None
285 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=15)
286 sleep
.assert_not_called()
287 self
.assertEqual(1, repartition
.call_count
)
290 repartition
.reset_mock()
291 portfolio
.Portfolio
.last_date
= None
293 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=1)
294 sleep
.assert_called_with(30)
295 self
.assertEqual(9, sleep
.call_count
)
296 self
.assertEqual(10, repartition
.call_count
)
298 @unittest.skipUnless("unit" in limits
, "Unit skipped")
299 class AmountTest(WebMockTestCase
):
300 def test_values(self
):
301 amount
= portfolio
.Amount("BTC", "0.65")
302 self
.assertEqual(D("0.65"), amount
.value
)
303 self
.assertEqual("BTC", amount
.currency
)
305 def test_in_currency(self
):
306 amount
= portfolio
.Amount("ETC", 10)
308 self
.assertEqual(amount
, amount
.in_currency("ETC", self
.m
))
310 with self
.subTest(desc
="no ticker for currency"):
311 self
.m
.get_ticker
.return_value
= None
313 self
.assertRaises(Exception, amount
.in_currency
, "ETH", self
.m
)
315 with self
.subTest(desc
="nominal case"):
316 self
.m
.get_ticker
.return_value
= {
322 converted_amount
= amount
.in_currency("ETH", self
.m
)
324 self
.assertEqual(D("3.0"), converted_amount
.value
)
325 self
.assertEqual("ETH", converted_amount
.currency
)
326 self
.assertEqual(amount
, converted_amount
.linked_to
)
327 self
.assertEqual("bar", converted_amount
.ticker
["foo"])
329 converted_amount
= amount
.in_currency("ETH", self
.m
, action
="bid", compute_value
="default")
330 self
.assertEqual(D("2"), converted_amount
.value
)
332 converted_amount
= amount
.in_currency("ETH", self
.m
, compute_value
="ask")
333 self
.assertEqual(D("4"), converted_amount
.value
)
335 converted_amount
= amount
.in_currency("ETH", self
.m
, rate
=D("0.02"))
336 self
.assertEqual(D("0.2"), converted_amount
.value
)
338 def test__round(self
):
339 amount
= portfolio
.Amount("BAR", portfolio
.D("1.23456789876"))
340 self
.assertEqual(D("1.23456789"), round(amount
).value
)
341 self
.assertEqual(D("1.23"), round(amount
, 2).value
)
344 amount
= portfolio
.Amount("SC", -120)
345 self
.assertEqual(120, abs(amount
).value
)
346 self
.assertEqual("SC", abs(amount
).currency
)
348 amount
= portfolio
.Amount("SC", 10)
349 self
.assertEqual(10, abs(amount
).value
)
350 self
.assertEqual("SC", abs(amount
).currency
)
353 amount1
= portfolio
.Amount("XVG", "12.9")
354 amount2
= portfolio
.Amount("XVG", "13.1")
356 self
.assertEqual(26, (amount1
+ amount2
).value
)
357 self
.assertEqual("XVG", (amount1
+ amount2
).currency
)
359 amount3
= portfolio
.Amount("ETH", "1.6")
360 with self
.assertRaises(Exception):
363 amount4
= portfolio
.Amount("ETH", 0.0)
364 self
.assertEqual(amount1
, amount1
+ amount4
)
366 self
.assertEqual(amount1
, amount1
+ 0)
368 def test__radd(self
):
369 amount
= portfolio
.Amount("XVG", "12.9")
371 self
.assertEqual(amount
, 0 + amount
)
372 with self
.assertRaises(Exception):
376 amount1
= portfolio
.Amount("XVG", "13.3")
377 amount2
= portfolio
.Amount("XVG", "13.1")
379 self
.assertEqual(D("0.2"), (amount1
- amount2
).value
)
380 self
.assertEqual("XVG", (amount1
- amount2
).currency
)
382 amount3
= portfolio
.Amount("ETH", "1.6")
383 with self
.assertRaises(Exception):
386 amount4
= portfolio
.Amount("ETH", 0.0)
387 self
.assertEqual(amount1
, amount1
- amount4
)
389 def test__rsub(self
):
390 amount
= portfolio
.Amount("ETH", "1.6")
391 with self
.assertRaises(Exception):
394 self
.assertEqual(portfolio
.Amount("ETH", "-1.6"), 0-amount
)
397 amount
= portfolio
.Amount("XEM", 11)
399 self
.assertEqual(D("38.5"), (amount
* D("3.5")).value
)
400 self
.assertEqual(D("33"), (amount
* 3).value
)
402 with self
.assertRaises(Exception):
405 def test__rmul(self
):
406 amount
= portfolio
.Amount("XEM", 11)
408 self
.assertEqual(D("38.5"), (D("3.5") * amount
).value
)
409 self
.assertEqual(D("33"), (3 * amount
).value
)
411 def test__floordiv(self
):
412 amount
= portfolio
.Amount("XEM", 11)
414 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
415 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
417 with self
.assertRaises(Exception):
420 def test__truediv(self
):
421 amount
= portfolio
.Amount("XEM", 11)
423 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
424 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
427 amount1
= portfolio
.Amount("BTD", 11.3)
428 amount2
= portfolio
.Amount("BTD", 13.1)
430 self
.assertTrue(amount1
< amount2
)
431 self
.assertFalse(amount2
< amount1
)
432 self
.assertFalse(amount1
< amount1
)
434 amount3
= portfolio
.Amount("BTC", 1.6)
435 with self
.assertRaises(Exception):
439 amount1
= portfolio
.Amount("BTD", 11.3)
440 amount2
= portfolio
.Amount("BTD", 13.1)
442 self
.assertTrue(amount1
<= amount2
)
443 self
.assertFalse(amount2
<= amount1
)
444 self
.assertTrue(amount1
<= amount1
)
446 amount3
= portfolio
.Amount("BTC", 1.6)
447 with self
.assertRaises(Exception):
451 amount1
= portfolio
.Amount("BTD", 11.3)
452 amount2
= portfolio
.Amount("BTD", 13.1)
454 self
.assertTrue(amount2
> amount1
)
455 self
.assertFalse(amount1
> amount2
)
456 self
.assertFalse(amount1
> amount1
)
458 amount3
= portfolio
.Amount("BTC", 1.6)
459 with self
.assertRaises(Exception):
463 amount1
= portfolio
.Amount("BTD", 11.3)
464 amount2
= portfolio
.Amount("BTD", 13.1)
466 self
.assertTrue(amount2
>= amount1
)
467 self
.assertFalse(amount1
>= amount2
)
468 self
.assertTrue(amount1
>= amount1
)
470 amount3
= portfolio
.Amount("BTC", 1.6)
471 with self
.assertRaises(Exception):
475 amount1
= portfolio
.Amount("BTD", 11.3)
476 amount2
= portfolio
.Amount("BTD", 13.1)
477 amount3
= portfolio
.Amount("BTD", 11.3)
479 self
.assertFalse(amount1
== amount2
)
480 self
.assertFalse(amount2
== amount1
)
481 self
.assertTrue(amount1
== amount3
)
482 self
.assertFalse(amount2
== 0)
484 amount4
= portfolio
.Amount("BTC", 1.6)
485 with self
.assertRaises(Exception):
488 amount5
= portfolio
.Amount("BTD", 0)
489 self
.assertTrue(amount5
== 0)
492 amount1
= portfolio
.Amount("BTD", 11.3)
493 amount2
= portfolio
.Amount("BTD", 13.1)
494 amount3
= portfolio
.Amount("BTD", 11.3)
496 self
.assertTrue(amount1
!= amount2
)
497 self
.assertTrue(amount2
!= amount1
)
498 self
.assertFalse(amount1
!= amount3
)
499 self
.assertTrue(amount2
!= 0)
501 amount4
= portfolio
.Amount("BTC", 1.6)
502 with self
.assertRaises(Exception):
505 amount5
= portfolio
.Amount("BTD", 0)
506 self
.assertFalse(amount5
!= 0)
509 amount1
= portfolio
.Amount("BTD", "11.3")
511 self
.assertEqual(portfolio
.D("-11.3"), (-amount1
).value
)
514 amount1
= portfolio
.Amount("BTX", 32)
515 self
.assertEqual("32.00000000 BTX", str(amount1
))
517 amount2
= portfolio
.Amount("USDT", 12000)
518 amount1
.linked_to
= amount2
519 self
.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1
))
521 def test__repr(self
):
522 amount1
= portfolio
.Amount("BTX", 32)
523 self
.assertEqual("Amount(32.00000000 BTX)", repr(amount1
))
525 amount2
= portfolio
.Amount("USDT", 12000)
526 amount1
.linked_to
= amount2
527 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1
))
529 amount3
= portfolio
.Amount("BTC", 0.1)
530 amount2
.linked_to
= amount3
531 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1
))
533 def test_as_json(self
):
534 amount
= portfolio
.Amount("BTX", 32)
535 self
.assertEqual({"currency": "BTX", "value": D("32")}
, amount
.as_json())
537 amount
= portfolio
.Amount("BTX", "1E-10")
538 self
.assertEqual({"currency": "BTX", "value": D("0")}
, amount
.as_json())
540 amount
= portfolio
.Amount("BTX", "1E-5")
541 self
.assertEqual({"currency": "BTX", "value": D("0.00001")}
, amount
.as_json())
542 self
.assertEqual("0.00001", str(amount
.as_json()["value"]))
544 @unittest.skipUnless("unit" in limits
, "Unit skipped")
545 class BalanceTest(WebMockTestCase
):
546 def test_values(self
):
547 balance
= portfolio
.Balance("BTC", {
548 "exchange_total": "0.65",
549 "exchange_free": "0.35",
550 "exchange_used": "0.30",
551 "margin_total": "-10",
552 "margin_borrowed": "10",
553 "margin_available": "0",
554 "margin_in_position": "0",
555 "margin_position_type": "short",
556 "margin_borrowed_base_currency": "USDT",
557 "margin_liquidation_price": "1.20",
558 "margin_pending_gain": "10",
559 "margin_lending_fees": "0.4",
560 "margin_borrowed_base_price": "0.15",
562 self
.assertEqual(portfolio
.D("0.65"), balance
.exchange_total
.value
)
563 self
.assertEqual(portfolio
.D("0.35"), balance
.exchange_free
.value
)
564 self
.assertEqual(portfolio
.D("0.30"), balance
.exchange_used
.value
)
565 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
566 self
.assertEqual("BTC", balance
.exchange_free
.currency
)
567 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
569 self
.assertEqual(portfolio
.D("-10"), balance
.margin_total
.value
)
570 self
.assertEqual(portfolio
.D("10"), balance
.margin_borrowed
.value
)
571 self
.assertEqual(portfolio
.D("0"), balance
.margin_available
.value
)
572 self
.assertEqual("BTC", balance
.margin_total
.currency
)
573 self
.assertEqual("BTC", balance
.margin_borrowed
.currency
)
574 self
.assertEqual("BTC", balance
.margin_available
.currency
)
576 self
.assertEqual("BTC", balance
.currency
)
578 self
.assertEqual(portfolio
.D("0.4"), balance
.margin_lending_fees
.value
)
579 self
.assertEqual("USDT", balance
.margin_lending_fees
.currency
)
581 def test__repr(self
):
582 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
583 repr(portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)))
584 balance
= portfolio
.Balance("BTX", { "exchange_total": 3,
585 "exchange_used": 1, "exchange_free": 2 })
586 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
588 balance
= portfolio
.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}
)
589 self
.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance
))
591 balance
= portfolio
.Balance("BTX", { "margin_total": 3,
592 "margin_in_position": 1, "margin_available": 2 })
593 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
595 balance
= portfolio
.Balance("BTX", { "margin_total": 2, "margin_available": 2 }
)
596 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance
))
598 balance
= portfolio
.Balance("BTX", { "margin_total": -3,
599 "margin_borrowed_base_price": D("0.1"),
600 "margin_borrowed_base_currency": "BTC",
601 "margin_lending_fees": D("0.002") })
602 self
.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance
))
604 balance
= portfolio
.Balance("BTX", { "margin_total": 1,
605 "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2})
606 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance
))
608 def test_as_json(self
):
609 balance
= portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)
610 as_json
= balance
.as_json()
611 self
.assertEqual(set(portfolio
.Balance
.base_keys
), set(as_json
.keys()))
612 self
.assertEqual(D(0), as_json
["total"])
613 self
.assertEqual(D(2), as_json
["exchange_total"])
614 self
.assertEqual(D(2), as_json
["exchange_free"])
615 self
.assertEqual(D(0), as_json
["exchange_used"])
616 self
.assertEqual(D(0), as_json
["margin_total"])
617 self
.assertEqual(D(0), as_json
["margin_available"])
618 self
.assertEqual(D(0), as_json
["margin_borrowed"])
620 @unittest.skipUnless("unit" in limits
, "Unit skipped")
621 class MarketTest(WebMockTestCase
):
623 super(MarketTest
, self
).setUp()
625 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
627 def test_values(self
):
628 m
= market
.Market(self
.ccxt
)
630 self
.assertEqual(self
.ccxt
, m
.ccxt
)
631 self
.assertFalse(m
.debug
)
632 self
.assertIsInstance(m
.report
, market
.ReportStore
)
633 self
.assertIsInstance(m
.trades
, market
.TradeStore
)
634 self
.assertIsInstance(m
.balances
, market
.BalanceStore
)
635 self
.assertEqual(m
, m
.report
.market
)
636 self
.assertEqual(m
, m
.trades
.market
)
637 self
.assertEqual(m
, m
.balances
.market
)
638 self
.assertEqual(m
, m
.ccxt
._market
)
640 m
= market
.Market(self
.ccxt
, debug
=True)
641 self
.assertTrue(m
.debug
)
643 m
= market
.Market(self
.ccxt
, debug
=False)
644 self
.assertFalse(m
.debug
)
646 @mock.patch("market.ccxt")
647 def test_from_config(self
, ccxt
):
648 with mock
.patch("market.ReportStore"):
649 ccxt
.poloniexE
.return_value
= self
.ccxt
650 self
.ccxt
.session
.request
.return_value
= "response"
652 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
)
654 self
.assertEqual(self
.ccxt
, m
.ccxt
)
656 self
.ccxt
.session
.request("GET", "URL", data
="data",
658 m
.report
.log_http_request
.assert_called_with('GET', 'URL', 'data',
659 'headers', 'response')
661 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, debug
=True)
662 self
.assertEqual(True, m
.debug
)
664 def test_get_tickers(self
):
665 self
.ccxt
.fetch_tickers
.side_effect
= [
670 m
= market
.Market(self
.ccxt
)
671 self
.assertEqual("tickers", m
.get_tickers())
672 self
.assertEqual("tickers", m
.get_tickers())
673 self
.ccxt
.fetch_tickers
.assert_called_once()
675 self
.assertIsNone(m
.get_tickers(refresh
=self
.time
.time()))
677 def test_get_ticker(self
):
678 with self
.subTest(get_tickers
=True):
679 self
.ccxt
.fetch_tickers
.return_value
= {
680 "ETH/ETC": { "bid": 1, "ask": 3 }
,
681 "XVG/ETH": { "bid": 10, "ask": 40 }
,
683 m
= market
.Market(self
.ccxt
)
685 ticker
= m
.get_ticker("ETH", "ETC")
686 self
.assertEqual(1, ticker
["bid"])
687 self
.assertEqual(3, ticker
["ask"])
688 self
.assertEqual(2, ticker
["average"])
689 self
.assertFalse(ticker
["inverted"])
691 ticker
= m
.get_ticker("ETH", "XVG")
692 self
.assertEqual(0.0625, ticker
["average"])
693 self
.assertTrue(ticker
["inverted"])
694 self
.assertIn("original", ticker
)
695 self
.assertEqual(10, ticker
["original"]["bid"])
696 self
.assertEqual(25, ticker
["original"]["average"])
698 ticker
= m
.get_ticker("XVG", "XMR")
699 self
.assertIsNone(ticker
)
701 with self
.subTest(get_tickers
=False):
702 self
.ccxt
.fetch_tickers
.return_value
= None
703 self
.ccxt
.fetch_ticker
.side_effect
= [
704 { "bid": 1, "ask": 3 }
,
705 market
.ExchangeError("foo"),
706 { "bid": 10, "ask": 40 }
,
707 market
.ExchangeError("foo"),
708 market
.ExchangeError("foo"),
711 m
= market
.Market(self
.ccxt
)
713 ticker
= m
.get_ticker("ETH", "ETC")
714 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
715 self
.assertEqual(1, ticker
["bid"])
716 self
.assertEqual(3, ticker
["ask"])
717 self
.assertEqual(2, ticker
["average"])
718 self
.assertFalse(ticker
["inverted"])
720 ticker
= m
.get_ticker("ETH", "XVG")
721 self
.assertEqual(0.0625, ticker
["average"])
722 self
.assertTrue(ticker
["inverted"])
723 self
.assertIn("original", ticker
)
724 self
.assertEqual(10, ticker
["original"]["bid"])
725 self
.assertEqual(25, ticker
["original"]["average"])
727 ticker
= m
.get_ticker("XVG", "XMR")
728 self
.assertIsNone(ticker
)
730 def test_fetch_fees(self
):
731 m
= market
.Market(self
.ccxt
)
732 self
.ccxt
.fetch_fees
.return_value
= "Foo"
733 self
.assertEqual("Foo", m
.fetch_fees())
734 self
.ccxt
.fetch_fees
.assert_called_once()
735 self
.ccxt
.reset_mock()
736 self
.assertEqual("Foo", m
.fetch_fees())
737 self
.ccxt
.fetch_fees
.assert_not_called()
739 @mock.patch.object(portfolio
.Portfolio
, "repartition")
740 @mock.patch.object(market
.Market
, "get_ticker")
741 @mock.patch.object(market
.TradeStore
, "compute_trades")
742 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
743 repartition
.return_value
= {
744 "XEM": (D("0.75"), "long"),
745 "BTC": (D("0.25"), "long"),
747 def _get_ticker(c1
, c2
):
748 if c1
== "USDT" and c2
== "BTC":
749 return { "average": D("0.0001") }
750 if c1
== "XVG" and c2
== "BTC":
751 return { "average": D("0.000001") }
752 if c1
== "XEM" and c2
== "BTC":
753 return { "average": D("0.001") }
754 self
.fail("Should be called with {}, {}".format(c1
, c2
))
755 get_ticker
.side_effect
= _get_ticker
757 with mock
.patch("market.ReportStore"):
758 m
= market
.Market(self
.ccxt
)
759 self
.ccxt
.fetch_all_balances
.return_value
= {
761 "exchange_free": D("10000.0"),
762 "exchange_used": D("0.0"),
763 "exchange_total": D("10000.0"),
764 "total": D("10000.0")
767 "exchange_free": D("10000.0"),
768 "exchange_used": D("0.0"),
769 "exchange_total": D("10000.0"),
770 "total": D("10000.0")
774 m
.balances
.fetch_balances(tag
="tag")
777 compute_trades
.assert_called()
779 call
= compute_trades
.call_args
780 self
.assertEqual(1, call
[0][0]["USDT"].value
)
781 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
782 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
783 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
784 m
.report
.log_stage
.assert_called_once_with("prepare_trades",
785 base_currency
='BTC', compute_value
='average',
786 liquidity
='medium', only
=None, repartition
=None)
787 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
790 @mock.patch.object(portfolio
.time
, "sleep")
791 @mock.patch.object(market
.TradeStore
, "all_orders")
792 def test_follow_orders(self
, all_orders
, time_mock
):
793 for debug
, sleep
in [
794 (False, None), (True, None),
795 (False, 12), (True, 12)]:
796 with self
.subTest(sleep
=sleep
, debug
=debug
), \
797 mock
.patch("market.ReportStore"):
798 m
= market
.Market(self
.ccxt
, debug
=debug
)
800 order_mock1
= mock
.Mock()
801 order_mock2
= mock
.Mock()
802 order_mock3
= mock
.Mock()
803 all_orders
.side_effect
= [
804 [order_mock1
, order_mock2
],
805 [order_mock1
, order_mock2
],
807 [order_mock1
, order_mock3
],
808 [order_mock1
, order_mock3
],
810 [order_mock1
, order_mock3
],
811 [order_mock1
, order_mock3
],
816 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
817 order_mock2
.get_status
.side_effect
= ["open"]
818 order_mock3
.get_status
.side_effect
= ["open", "closed"]
820 order_mock1
.trade
= mock
.Mock()
821 order_mock2
.trade
= mock
.Mock()
822 order_mock3
.trade
= mock
.Mock()
824 m
.follow_orders(sleep
=sleep
)
826 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
827 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
828 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
829 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
831 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
832 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
833 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
835 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
836 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
837 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
838 m
.report
.log_stage
.assert_called()
840 mock
.call("follow_orders_begin"),
841 mock
.call("follow_orders_tick_1"),
842 mock
.call("follow_orders_tick_2"),
843 mock
.call("follow_orders_tick_3"),
844 mock
.call("follow_orders_end"),
846 m
.report
.log_stage
.assert_has_calls(calls
)
847 m
.report
.log_orders
.assert_called()
848 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
850 mock
.call([order_mock1
, order_mock2
], tick
=1),
851 mock
.call([order_mock1
, order_mock3
], tick
=2),
852 mock
.call([order_mock1
, order_mock3
], tick
=3),
854 m
.report
.log_orders
.assert_has_calls(calls
)
856 mock
.call(order_mock1
, 3, finished
=True),
857 mock
.call(order_mock3
, 3, finished
=True),
859 m
.report
.log_order
.assert_has_calls(calls
)
863 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
864 time_mock
.assert_called_with(7)
866 time_mock
.assert_called_with(30)
868 time_mock
.assert_called_with(sleep
)
870 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
871 def test_move_balance(self
, fetch_balances
):
872 for debug
in [True, False]:
873 with self
.subTest(debug
=debug
),\
874 mock
.patch("market.ReportStore"):
875 m
= market
.Market(self
.ccxt
, debug
=debug
)
877 value_from
= portfolio
.Amount("BTC", "1.0")
878 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
879 value_to
= portfolio
.Amount("BTC", "10.0")
880 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
882 value_from
= portfolio
.Amount("BTC", "0.0")
883 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
884 value_to
= portfolio
.Amount("BTC", "-3.0")
885 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
887 value_from
= portfolio
.Amount("USDT", "0.0")
888 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
889 value_to
= portfolio
.Amount("USDT", "-50.0")
890 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
892 m
.trades
.all
= [trade1
, trade2
, trade3
]
893 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
894 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
895 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
896 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
900 fetch_balances
.assert_called_with()
901 m
.report
.log_move_balances
.assert_called_once()
904 m
.report
.log_debug_action
.assert_called()
905 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
907 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
908 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
909 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
911 @unittest.skipUnless("unit" in limits
, "Unit skipped")
912 class TradeStoreTest(WebMockTestCase
):
913 def test_compute_trades(self
):
914 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
917 "XMR": portfolio
.Amount("BTC", D("0.9")),
918 "DASH": portfolio
.Amount("BTC", D("0.4")),
919 "XVG": portfolio
.Amount("BTC", D("-0.5")),
920 "BTC": portfolio
.Amount("BTC", D("0.5")),
923 "DASH": portfolio
.Amount("BTC", D("0.5")),
924 "XVG": portfolio
.Amount("BTC", D("0.1")),
925 "BTC": portfolio
.Amount("BTC", D("0.4")),
926 "ETH": portfolio
.Amount("BTC", D("0.3")),
936 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
937 trade_store
= market
.TradeStore(self
.m
)
938 trade_if_matching
.side_effect
= side_effect
940 trade_store
.compute_trades(values_in_base
,
941 new_repartition
, only
="only")
943 self
.assertEqual(5, trade_if_matching
.call_count
)
944 self
.assertEqual(3, len(trade_store
.all
))
945 self
.assertEqual([1, 4, 5], trade_store
.all
)
946 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
948 def test_trade_if_matching(self
):
950 with self
.subTest(only
="nope"):
951 trade_store
= market
.TradeStore(self
.m
)
952 result
= trade_store
.trade_if_matching(
953 portfolio
.Amount("BTC", D("0")),
954 portfolio
.Amount("BTC", D("0.3")),
956 self
.assertEqual(False, result
[0])
957 self
.assertIsInstance(result
[1], portfolio
.Trade
)
959 with self
.subTest(only
=None):
960 trade_store
= market
.TradeStore(self
.m
)
961 result
= trade_store
.trade_if_matching(
962 portfolio
.Amount("BTC", D("0")),
963 portfolio
.Amount("BTC", D("0.3")),
965 self
.assertEqual(True, result
[0])
967 with self
.subTest(only
="acquire"):
968 trade_store
= market
.TradeStore(self
.m
)
969 result
= trade_store
.trade_if_matching(
970 portfolio
.Amount("BTC", D("0")),
971 portfolio
.Amount("BTC", D("0.3")),
972 "ETH", only
="acquire")
973 self
.assertEqual(True, result
[0])
975 with self
.subTest(only
="dispose"):
976 trade_store
= market
.TradeStore(self
.m
)
977 result
= trade_store
.trade_if_matching(
978 portfolio
.Amount("BTC", D("0")),
979 portfolio
.Amount("BTC", D("0.3")),
980 "ETH", only
="dispose")
981 self
.assertEqual(False, result
[0])
983 def test_prepare_orders(self
):
984 trade_store
= market
.TradeStore(self
.m
)
986 trade_mock1
= mock
.Mock()
987 trade_mock2
= mock
.Mock()
988 trade_mock3
= mock
.Mock()
990 trade_mock1
.prepare_order
.return_value
= 1
991 trade_mock2
.prepare_order
.return_value
= 2
992 trade_mock3
.prepare_order
.return_value
= 3
994 trade_mock1
.pending
= True
995 trade_mock2
.pending
= True
996 trade_mock3
.pending
= False
998 trade_store
.all
.append(trade_mock1
)
999 trade_store
.all
.append(trade_mock2
)
1000 trade_store
.all
.append(trade_mock3
)
1002 trade_store
.prepare_orders()
1003 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1004 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1005 trade_mock3
.prepare_order
.assert_not_called()
1006 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1008 self
.m
.report
.log_orders
.reset_mock()
1010 trade_store
.prepare_orders(compute_value
="bla")
1011 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1012 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1013 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1015 trade_mock1
.prepare_order
.reset_mock()
1016 trade_mock2
.prepare_order
.reset_mock()
1017 self
.m
.report
.log_orders
.reset_mock()
1019 trade_mock1
.action
= "foo"
1020 trade_mock2
.action
= "bar"
1021 trade_store
.prepare_orders(only
="bar")
1022 trade_mock1
.prepare_order
.assert_not_called()
1023 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1024 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1026 def test_print_all_with_order(self
):
1027 trade_mock1
= mock
.Mock()
1028 trade_mock2
= mock
.Mock()
1029 trade_mock3
= mock
.Mock()
1030 trade_store
= market
.TradeStore(self
.m
)
1031 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1033 trade_store
.print_all_with_order()
1035 trade_mock1
.print_with_order
.assert_called()
1036 trade_mock2
.print_with_order
.assert_called()
1037 trade_mock3
.print_with_order
.assert_called()
1039 def test_run_orders(self
):
1040 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1041 order_mock1
= mock
.Mock()
1042 order_mock2
= mock
.Mock()
1043 order_mock3
= mock
.Mock()
1044 trade_store
= market
.TradeStore(self
.m
)
1046 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1048 trade_store
.run_orders()
1050 all_orders
.assert_called_with(state
="pending")
1052 order_mock1
.run
.assert_called()
1053 order_mock2
.run
.assert_called()
1054 order_mock3
.run
.assert_called()
1056 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1057 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1060 def test_all_orders(self
):
1061 trade_mock1
= mock
.Mock()
1062 trade_mock2
= mock
.Mock()
1064 order_mock1
= mock
.Mock()
1065 order_mock2
= mock
.Mock()
1066 order_mock3
= mock
.Mock()
1068 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1069 trade_mock2
.orders
= [order_mock3
]
1071 order_mock1
.status
= "pending"
1072 order_mock2
.status
= "open"
1073 order_mock3
.status
= "open"
1075 trade_store
= market
.TradeStore(self
.m
)
1076 trade_store
.all
.append(trade_mock1
)
1077 trade_store
.all
.append(trade_mock2
)
1079 orders
= trade_store
.all_orders()
1080 self
.assertEqual(3, len(orders
))
1082 open_orders
= trade_store
.all_orders(state
="open")
1083 self
.assertEqual(2, len(open_orders
))
1084 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1086 def test_update_all_orders_status(self
):
1087 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1088 order_mock1
= mock
.Mock()
1089 order_mock2
= mock
.Mock()
1090 order_mock3
= mock
.Mock()
1092 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1094 trade_store
= market
.TradeStore(self
.m
)
1096 trade_store
.update_all_orders_status()
1097 all_orders
.assert_called_with(state
="open")
1099 order_mock1
.get_status
.assert_called()
1100 order_mock2
.get_status
.assert_called()
1101 order_mock3
.get_status
.assert_called()
1103 def test_close_trades(self
):
1104 trade_mock1
= mock
.Mock()
1105 trade_mock2
= mock
.Mock()
1106 trade_mock3
= mock
.Mock()
1108 trade_store
= market
.TradeStore(self
.m
)
1110 trade_store
.all
.append(trade_mock1
)
1111 trade_store
.all
.append(trade_mock2
)
1112 trade_store
.all
.append(trade_mock3
)
1114 trade_store
.close_trades()
1116 trade_mock1
.close
.assert_called_once_with()
1117 trade_mock2
.close
.assert_called_once_with()
1118 trade_mock3
.close
.assert_called_once_with()
1120 def test_pending(self
):
1121 trade_mock1
= mock
.Mock()
1122 trade_mock1
.pending
= True
1123 trade_mock2
= mock
.Mock()
1124 trade_mock2
.pending
= True
1125 trade_mock3
= mock
.Mock()
1126 trade_mock3
.pending
= False
1128 trade_store
= market
.TradeStore(self
.m
)
1130 trade_store
.all
.append(trade_mock1
)
1131 trade_store
.all
.append(trade_mock2
)
1132 trade_store
.all
.append(trade_mock3
)
1134 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
1136 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1137 class BalanceStoreTest(WebMockTestCase
):
1139 super(BalanceStoreTest
, self
).setUp()
1141 self
.fetch_balance
= {
1145 "exchange_total": 0,
1149 "exchange_free": D("6.0"),
1150 "exchange_used": D("1.2"),
1151 "exchange_total": D("7.2"),
1155 "exchange_free": 16,
1157 "exchange_total": 16,
1163 "exchange_total": 0,
1164 "margin_total": D("-1.0"),
1169 def test_in_currency(self
):
1170 self
.m
.get_ticker
.return_value
= {
1173 "average": D("0.1"),
1176 balance_store
= market
.BalanceStore(self
.m
)
1177 balance_store
.all
= {
1178 "BTC": portfolio
.Balance("BTC", {
1180 "exchange_total":"0.65",
1181 "exchange_free": "0.35",
1182 "exchange_used": "0.30"}),
1183 "ETH": portfolio
.Balance("ETH", {
1185 "exchange_total": 3,
1187 "exchange_used": 0}),
1190 amounts
= balance_store
.in_currency("BTC")
1191 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1192 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1193 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1194 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1196 self
.m
.report
.log_tickers
.reset_mock()
1198 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1199 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1200 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1201 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1203 self
.m
.report
.log_tickers
.reset_mock()
1205 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1206 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1207 self
.assertEqual(0, amounts
["ETH"].value
)
1208 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1209 "bid", "exchange_used")
1210 self
.m
.report
.log_tickers
.reset_mock()
1212 def test_fetch_balances(self
):
1213 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1215 balance_store
= market
.BalanceStore(self
.m
)
1217 balance_store
.fetch_balances()
1218 self
.assertNotIn("ETC", balance_store
.currencies())
1219 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1221 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1222 "exchange_total": "1", "exchange_free": "0",
1223 "exchange_used": "1" })
1224 balance_store
.fetch_balances(tag
="foo")
1225 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1226 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1227 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1229 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1230 def test_dispatch_assets(self
, repartition
):
1231 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1233 balance_store
= market
.BalanceStore(self
.m
)
1234 balance_store
.fetch_balances()
1236 self
.assertNotIn("XEM", balance_store
.currencies())
1238 repartition_hash
= {
1239 "XEM": (D("0.75"), "long"),
1240 "BTC": (D("0.26"), "long"),
1241 "DASH": (D("0.10"), "short"),
1243 repartition
.return_value
= repartition_hash
1245 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1246 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1247 self
.assertIn("XEM", balance_store
.currencies())
1248 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1249 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1250 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1251 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1252 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1253 "11.1"), amounts
, "medium", repartition_hash
)
1255 def test_currencies(self
):
1256 balance_store
= market
.BalanceStore(self
.m
)
1258 balance_store
.all
= {
1259 "BTC": portfolio
.Balance("BTC", {
1261 "exchange_total":"0.65",
1262 "exchange_free": "0.35",
1263 "exchange_used": "0.30"}),
1264 "ETH": portfolio
.Balance("ETH", {
1266 "exchange_total": 3,
1268 "exchange_used": 0}),
1270 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1272 def test_as_json(self
):
1273 balance_mock1
= mock
.Mock()
1274 balance_mock1
.as_json
.return_value
= 1
1276 balance_mock2
= mock
.Mock()
1277 balance_mock2
.as_json
.return_value
= 2
1279 balance_store
= market
.BalanceStore(self
.m
)
1280 balance_store
.all
= {
1281 "BTC": balance_mock1
,
1282 "ETH": balance_mock2
,
1285 as_json
= balance_store
.as_json()
1286 self
.assertEqual(1, as_json
["BTC"])
1287 self
.assertEqual(2, as_json
["ETH"])
1290 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1291 class ComputationTest(WebMockTestCase
):
1292 def test_compute_value(self
):
1293 compute
= mock
.Mock()
1294 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1295 compute
.assert_called_with("foo", "ask")
1297 compute
.reset_mock()
1298 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1299 compute
.assert_called_with("foo", "bid")
1301 compute
.reset_mock()
1302 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1303 compute
.assert_called_with("foo", "ask")
1305 compute
.reset_mock()
1306 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1307 compute
.assert_called_with("foo", "bid")
1309 compute
.reset_mock()
1310 portfolio
.Computation
.computations
["test"] = compute
1311 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1312 compute
.assert_called_with("foo", "bid")
1315 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1316 class TradeTest(WebMockTestCase
):
1318 def test_values_assertion(self
):
1319 value_from
= portfolio
.Amount("BTC", "1.0")
1320 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1321 value_to
= portfolio
.Amount("BTC", "1.0")
1322 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1323 self
.assertEqual("BTC", trade
.base_currency
)
1324 self
.assertEqual("ETH", trade
.currency
)
1325 self
.assertEqual(self
.m
, trade
.market
)
1327 with self
.assertRaises(AssertionError):
1328 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
1329 with self
.assertRaises(AssertionError):
1330 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1331 with self
.assertRaises(AssertionError):
1332 value_from
.currency
= "ETH"
1333 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1334 value_from
.currency
= "BTC"
1335 with self
.assertRaises(AssertionError):
1336 value_from2
= portfolio
.Amount("BTC", "1.0")
1337 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
1339 value_from
= portfolio
.Amount("BTC", 0)
1340 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1341 self
.assertEqual(0, trade
.value_from
.linked_to
)
1343 def test_action(self
):
1344 value_from
= portfolio
.Amount("BTC", "1.0")
1345 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1346 value_to
= portfolio
.Amount("BTC", "1.0")
1347 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1349 self
.assertIsNone(trade
.action
)
1351 value_from
= portfolio
.Amount("BTC", "1.0")
1352 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1353 value_to
= portfolio
.Amount("BTC", "2.0")
1354 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1356 self
.assertIsNone(trade
.action
)
1358 value_from
= portfolio
.Amount("BTC", "0.5")
1359 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1360 value_to
= portfolio
.Amount("BTC", "1.0")
1361 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1363 self
.assertEqual("acquire", trade
.action
)
1365 value_from
= portfolio
.Amount("BTC", "0")
1366 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1367 value_to
= portfolio
.Amount("BTC", "-1.0")
1368 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1370 self
.assertEqual("acquire", trade
.action
)
1372 def test_order_action(self
):
1373 value_from
= portfolio
.Amount("BTC", "0.5")
1374 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1375 value_to
= portfolio
.Amount("BTC", "1.0")
1376 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1378 trade
.inverted
= False
1379 self
.assertEqual("buy", trade
.order_action())
1380 trade
.inverted
= True
1381 self
.assertEqual("sell", trade
.order_action())
1383 value_from
= portfolio
.Amount("BTC", "0")
1384 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1385 value_to
= portfolio
.Amount("BTC", "-1.0")
1386 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1388 trade
.inverted
= False
1389 self
.assertEqual("sell", trade
.order_action())
1390 trade
.inverted
= True
1391 self
.assertEqual("buy", trade
.order_action())
1393 def test_trade_type(self
):
1394 value_from
= portfolio
.Amount("BTC", "0.5")
1395 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1396 value_to
= portfolio
.Amount("BTC", "1.0")
1397 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1399 self
.assertEqual("long", trade
.trade_type
)
1401 value_from
= portfolio
.Amount("BTC", "0")
1402 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1403 value_to
= portfolio
.Amount("BTC", "-1.0")
1404 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1406 self
.assertEqual("short", trade
.trade_type
)
1408 def test_is_fullfiled(self
):
1409 with self
.subTest(inverted
=False):
1410 value_from
= portfolio
.Amount("BTC", "0.5")
1411 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1412 value_to
= portfolio
.Amount("BTC", "1.0")
1413 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1415 order1
= mock
.Mock()
1416 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1418 order2
= mock
.Mock()
1419 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1420 trade
.orders
.append(order1
)
1421 trade
.orders
.append(order2
)
1423 self
.assertFalse(trade
.is_fullfiled
)
1425 order3
= mock
.Mock()
1426 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1427 trade
.orders
.append(order3
)
1429 self
.assertTrue(trade
.is_fullfiled
)
1431 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1432 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1433 order3
.filled_amount
.assert_called_with(in_base_currency
=True)
1435 with self
.subTest(inverted
=True):
1436 value_from
= portfolio
.Amount("BTC", "0.5")
1437 value_from
.linked_to
= portfolio
.Amount("USDT", "1000.0")
1438 value_to
= portfolio
.Amount("BTC", "1.0")
1439 trade
= portfolio
.Trade(value_from
, value_to
, "USDT", self
.m
)
1440 trade
.inverted
= True
1442 order1
= mock
.Mock()
1443 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1445 order2
= mock
.Mock()
1446 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1447 trade
.orders
.append(order1
)
1448 trade
.orders
.append(order2
)
1450 self
.assertFalse(trade
.is_fullfiled
)
1452 order3
= mock
.Mock()
1453 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1454 trade
.orders
.append(order3
)
1456 self
.assertTrue(trade
.is_fullfiled
)
1458 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1459 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1460 order3
.filled_amount
.assert_called_with(in_base_currency
=False)
1463 def test_filled_amount(self
):
1464 value_from
= portfolio
.Amount("BTC", "0.5")
1465 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1466 value_to
= portfolio
.Amount("BTC", "1.0")
1467 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1469 order1
= mock
.Mock()
1470 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1472 order2
= mock
.Mock()
1473 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1474 trade
.orders
.append(order1
)
1475 trade
.orders
.append(order2
)
1477 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1478 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1479 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1481 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1482 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1483 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1485 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1486 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1487 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1489 @mock.patch.object(portfolio
.Computation
, "compute_value")
1490 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1491 @mock.patch.object(portfolio
, "Order")
1492 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1493 Order
.return_value
= "Order"
1495 with self
.subTest(desc
="Nothing to do"):
1496 value_from
= portfolio
.Amount("BTC", "10")
1497 value_from
.rate
= D("0.1")
1498 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1499 value_to
= portfolio
.Amount("BTC", "10")
1500 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1502 trade
.prepare_order()
1504 filled_amount
.assert_not_called()
1505 compute_value
.assert_not_called()
1506 self
.assertEqual(0, len(trade
.orders
))
1507 Order
.assert_not_called()
1509 self
.m
.get_ticker
.return_value
= { "inverted": False }
1510 with self
.subTest(desc
="Already filled"):
1511 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1512 compute_value
.return_value
= D("0.125")
1514 value_from
= portfolio
.Amount("BTC", "10")
1515 value_from
.rate
= D("0.1")
1516 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1517 value_to
= portfolio
.Amount("BTC", "0")
1518 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1520 trade
.prepare_order()
1522 filled_amount
.assert_called_with(in_base_currency
=False)
1523 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1524 self
.assertEqual(0, len(trade
.orders
))
1525 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1526 Order
.assert_not_called()
1528 with self
.subTest(action
="dispose", inverted
=False):
1529 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1530 compute_value
.return_value
= D("0.125")
1532 value_from
= portfolio
.Amount("BTC", "10")
1533 value_from
.rate
= D("0.1")
1534 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1535 value_to
= portfolio
.Amount("BTC", "1")
1536 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1538 trade
.prepare_order()
1540 filled_amount
.assert_called_with(in_base_currency
=False)
1541 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1542 self
.assertEqual(1, len(trade
.orders
))
1543 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1544 D("0.125"), "BTC", "long", self
.m
,
1545 trade
, close_if_possible
=False)
1547 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1548 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1549 compute_value
.return_value
= D("0.125")
1551 value_from
= portfolio
.Amount("BTC", "10")
1552 value_from
.rate
= D("0.1")
1553 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1554 value_to
= portfolio
.Amount("BTC", "1")
1555 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1557 trade
.prepare_order(close_if_possible
=True)
1559 filled_amount
.assert_called_with(in_base_currency
=False)
1560 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1561 self
.assertEqual(1, len(trade
.orders
))
1562 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1563 D("0.125"), "BTC", "long", self
.m
,
1564 trade
, close_if_possible
=True)
1566 with self
.subTest(action
="acquire", inverted
=False):
1567 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1568 compute_value
.return_value
= D("0.125")
1570 value_from
= portfolio
.Amount("BTC", "1")
1571 value_from
.rate
= D("0.1")
1572 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1573 value_to
= portfolio
.Amount("BTC", "10")
1574 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1576 trade
.prepare_order()
1578 filled_amount
.assert_called_with(in_base_currency
=True)
1579 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1580 self
.assertEqual(1, len(trade
.orders
))
1582 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1583 D("0.125"), "BTC", "long", self
.m
,
1584 trade
, close_if_possible
=False)
1586 with self
.subTest(close_if_possible
=True):
1587 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1588 compute_value
.return_value
= D("0.125")
1590 value_from
= portfolio
.Amount("BTC", "10")
1591 value_from
.rate
= D("0.1")
1592 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1593 value_to
= portfolio
.Amount("BTC", "0")
1594 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1596 trade
.prepare_order()
1598 filled_amount
.assert_called_with(in_base_currency
=False)
1599 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1600 self
.assertEqual(1, len(trade
.orders
))
1601 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1602 D("0.125"), "BTC", "long", self
.m
,
1603 trade
, close_if_possible
=True)
1605 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1606 with self
.subTest(action
="dispose", inverted
=True):
1607 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1608 compute_value
.return_value
= D("125")
1610 value_from
= portfolio
.Amount("BTC", "10")
1611 value_from
.rate
= D("0.01")
1612 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1613 value_to
= portfolio
.Amount("BTC", "1")
1614 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1616 trade
.prepare_order(compute_value
="foo")
1618 filled_amount
.assert_called_with(in_base_currency
=True)
1619 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1620 self
.assertEqual(1, len(trade
.orders
))
1621 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1622 D("125"), "FOO", "long", self
.m
,
1623 trade
, close_if_possible
=False)
1625 with self
.subTest(action
="acquire", inverted
=True):
1626 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1627 compute_value
.return_value
= D("125")
1629 value_from
= portfolio
.Amount("BTC", "1")
1630 value_from
.rate
= D("0.01")
1631 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1632 value_to
= portfolio
.Amount("BTC", "10")
1633 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1635 trade
.prepare_order(compute_value
="foo")
1637 filled_amount
.assert_called_with(in_base_currency
=False)
1638 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1639 self
.assertEqual(1, len(trade
.orders
))
1640 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1641 D("125"), "FOO", "long", self
.m
,
1642 trade
, close_if_possible
=False)
1645 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1646 def test_update_order(self
, prepare_order
):
1647 order_mock
= mock
.Mock()
1648 new_order_mock
= mock
.Mock()
1650 value_from
= portfolio
.Amount("BTC", "0.5")
1651 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1652 value_to
= portfolio
.Amount("BTC", "1.0")
1653 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1654 prepare_order
.return_value
= new_order_mock
1656 for i
in [0, 1, 3, 4, 6]:
1657 with self
.subTest(tick
=i
):
1658 trade
.update_order(order_mock
, i
)
1659 order_mock
.cancel
.assert_not_called()
1660 new_order_mock
.run
.assert_not_called()
1661 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1662 update
="waiting", compute_value
=None, new_order
=None)
1664 order_mock
.reset_mock()
1665 new_order_mock
.reset_mock()
1667 self
.m
.report
.log_order
.reset_mock()
1669 trade
.update_order(order_mock
, 2)
1670 order_mock
.cancel
.assert_called()
1671 new_order_mock
.run
.assert_called()
1672 prepare_order
.assert_called()
1673 self
.m
.report
.log_order
.assert_called()
1674 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1676 mock
.call(order_mock
, 2, update
="adjusting",
1677 compute_value
=mock
.ANY
,
1678 new_order
=new_order_mock
),
1679 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1681 self
.m
.report
.log_order
.assert_has_calls(calls
)
1683 order_mock
.reset_mock()
1684 new_order_mock
.reset_mock()
1686 self
.m
.report
.log_order
.reset_mock()
1688 trade
.update_order(order_mock
, 5)
1689 order_mock
.cancel
.assert_called()
1690 new_order_mock
.run
.assert_called()
1691 prepare_order
.assert_called()
1692 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1693 self
.m
.report
.log_order
.assert_called()
1695 mock
.call(order_mock
, 5, update
="adjusting",
1696 compute_value
=mock
.ANY
,
1697 new_order
=new_order_mock
),
1698 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1700 self
.m
.report
.log_order
.assert_has_calls(calls
)
1702 order_mock
.reset_mock()
1703 new_order_mock
.reset_mock()
1705 self
.m
.report
.log_order
.reset_mock()
1707 trade
.update_order(order_mock
, 7)
1708 order_mock
.cancel
.assert_called()
1709 new_order_mock
.run
.assert_called()
1710 prepare_order
.assert_called_with(compute_value
="default")
1711 self
.m
.report
.log_order
.assert_called()
1712 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1714 mock
.call(order_mock
, 7, update
="market_fallback",
1715 compute_value
='default',
1716 new_order
=new_order_mock
),
1717 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1719 self
.m
.report
.log_order
.assert_has_calls(calls
)
1721 order_mock
.reset_mock()
1722 new_order_mock
.reset_mock()
1724 self
.m
.report
.log_order
.reset_mock()
1726 for i
in [10, 13, 16]:
1727 with self
.subTest(tick
=i
):
1728 trade
.update_order(order_mock
, i
)
1729 order_mock
.cancel
.assert_called()
1730 new_order_mock
.run
.assert_called()
1731 prepare_order
.assert_called_with(compute_value
="default")
1732 self
.m
.report
.log_order
.assert_called()
1733 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1735 mock
.call(order_mock
, i
, update
="market_adjust",
1736 compute_value
='default',
1737 new_order
=new_order_mock
),
1738 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1740 self
.m
.report
.log_order
.assert_has_calls(calls
)
1742 order_mock
.reset_mock()
1743 new_order_mock
.reset_mock()
1745 self
.m
.report
.log_order
.reset_mock()
1747 for i
in [8, 9, 11, 12]:
1748 with self
.subTest(tick
=i
):
1749 trade
.update_order(order_mock
, i
)
1750 order_mock
.cancel
.assert_not_called()
1751 new_order_mock
.run
.assert_not_called()
1752 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1753 compute_value
=None, new_order
=None)
1755 order_mock
.reset_mock()
1756 new_order_mock
.reset_mock()
1758 self
.m
.report
.log_order
.reset_mock()
1761 def test_print_with_order(self
):
1762 value_from
= portfolio
.Amount("BTC", "0.5")
1763 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1764 value_to
= portfolio
.Amount("BTC", "1.0")
1765 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1767 order_mock1
= mock
.Mock()
1768 order_mock1
.__repr__
= mock
.Mock()
1769 order_mock1
.__repr__
.return_value
= "Mock 1"
1770 order_mock2
= mock
.Mock()
1771 order_mock2
.__repr__
= mock
.Mock()
1772 order_mock2
.__repr__
.return_value
= "Mock 2"
1773 order_mock1
.mouvements
= []
1774 mouvement_mock1
= mock
.Mock()
1775 mouvement_mock1
.__repr__
= mock
.Mock()
1776 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1777 mouvement_mock2
= mock
.Mock()
1778 mouvement_mock2
.__repr__
= mock
.Mock()
1779 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1780 order_mock2
.mouvements
= [
1781 mouvement_mock1
, mouvement_mock2
1783 trade
.orders
.append(order_mock1
)
1784 trade
.orders
.append(order_mock2
)
1786 with mock
.patch
.object(trade
, "filled_amount") as filled
:
1787 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
1789 trade
.print_with_order()
1791 self
.m
.report
.print_log
.assert_called()
1792 calls
= self
.m
.report
.print_log
.mock_calls
1793 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1794 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1795 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1796 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1797 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1799 self
.m
.report
.print_log
.reset_mock()
1801 filled
.return_value
= portfolio
.Amount("BTC", "0.5")
1802 trade
.print_with_order()
1803 calls
= self
.m
.report
.print_log
.mock_calls
1804 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls
[0][1][0]))
1806 self
.m
.report
.print_log
.reset_mock()
1808 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
1810 trade
.print_with_order()
1811 calls
= self
.m
.report
.print_log
.mock_calls
1812 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls
[0][1][0]))
1814 def test_close(self
):
1815 value_from
= portfolio
.Amount("BTC", "0.5")
1816 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1817 value_to
= portfolio
.Amount("BTC", "1.0")
1818 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1819 order1
= mock
.Mock()
1820 trade
.orders
.append(order1
)
1824 self
.assertEqual(True, trade
.closed
)
1825 order1
.cancel
.assert_called_once_with()
1827 def test_pending(self
):
1828 value_from
= portfolio
.Amount("BTC", "0.5")
1829 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1830 value_to
= portfolio
.Amount("BTC", "1.0")
1831 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1834 self
.assertEqual(False, trade
.pending
)
1836 trade
.closed
= False
1837 self
.assertEqual(True, trade
.pending
)
1839 order1
= mock
.Mock()
1840 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.5")
1841 trade
.orders
.append(order1
)
1842 self
.assertEqual(False, trade
.pending
)
1844 def test__repr(self
):
1845 value_from
= portfolio
.Amount("BTC", "0.5")
1846 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1847 value_to
= portfolio
.Amount("BTC", "1.0")
1848 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1850 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1852 def test_as_json(self
):
1853 value_from
= portfolio
.Amount("BTC", "0.5")
1854 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1855 value_to
= portfolio
.Amount("BTC", "1.0")
1856 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1858 as_json
= trade
.as_json()
1859 self
.assertEqual("acquire", as_json
["action"])
1860 self
.assertEqual(D("0.5"), as_json
["from"])
1861 self
.assertEqual(D("1.0"), as_json
["to"])
1862 self
.assertEqual("ETH", as_json
["currency"])
1863 self
.assertEqual("BTC", as_json
["base_currency"])
1865 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1866 class OrderTest(WebMockTestCase
):
1867 def test_values(self
):
1868 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1869 D("0.1"), "BTC", "long", "market", "trade")
1870 self
.assertEqual("buy", order
.action
)
1871 self
.assertEqual(10, order
.amount
.value
)
1872 self
.assertEqual("ETH", order
.amount
.currency
)
1873 self
.assertEqual(D("0.1"), order
.rate
)
1874 self
.assertEqual("BTC", order
.base_currency
)
1875 self
.assertEqual("market", order
.market
)
1876 self
.assertEqual("long", order
.trade_type
)
1877 self
.assertEqual("pending", order
.status
)
1878 self
.assertEqual("trade", order
.trade
)
1879 self
.assertIsNone(order
.id)
1880 self
.assertFalse(order
.close_if_possible
)
1882 def test__repr(self
):
1883 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1884 D("0.1"), "BTC", "long", "market", "trade")
1885 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1887 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1888 D("0.1"), "BTC", "long", "market", "trade",
1889 close_if_possible
=True)
1890 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1892 def test_as_json(self
):
1893 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1894 D("0.1"), "BTC", "long", "market", "trade")
1895 mouvement_mock1
= mock
.Mock()
1896 mouvement_mock1
.as_json
.return_value
= 1
1897 mouvement_mock2
= mock
.Mock()
1898 mouvement_mock2
.as_json
.return_value
= 2
1900 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1901 as_json
= order
.as_json()
1902 self
.assertEqual("buy", as_json
["action"])
1903 self
.assertEqual("long", as_json
["trade_type"])
1904 self
.assertEqual(10, as_json
["amount"])
1905 self
.assertEqual("ETH", as_json
["currency"])
1906 self
.assertEqual("BTC", as_json
["base_currency"])
1907 self
.assertEqual(D("0.1"), as_json
["rate"])
1908 self
.assertEqual("pending", as_json
["status"])
1909 self
.assertEqual(False, as_json
["close_if_possible"])
1910 self
.assertIsNone(as_json
["id"])
1911 self
.assertEqual([1, 2], as_json
["mouvements"])
1913 def test_account(self
):
1914 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1915 D("0.1"), "BTC", "long", "market", "trade")
1916 self
.assertEqual("exchange", order
.account
)
1918 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1919 D("0.1"), "BTC", "short", "market", "trade")
1920 self
.assertEqual("margin", order
.account
)
1922 def test_pending(self
):
1923 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1924 D("0.1"), "BTC", "long", "market", "trade")
1925 self
.assertTrue(order
.pending
)
1926 order
.status
= "open"
1927 self
.assertFalse(order
.pending
)
1929 def test_open(self
):
1930 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1931 D("0.1"), "BTC", "long", "market", "trade")
1932 self
.assertFalse(order
.open)
1933 order
.status
= "open"
1934 self
.assertTrue(order
.open)
1936 def test_finished(self
):
1937 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1938 D("0.1"), "BTC", "long", "market", "trade")
1939 self
.assertFalse(order
.finished
)
1940 order
.status
= "closed"
1941 self
.assertTrue(order
.finished
)
1942 order
.status
= "canceled"
1943 self
.assertTrue(order
.finished
)
1944 order
.status
= "error"
1945 self
.assertTrue(order
.finished
)
1947 @mock.patch.object(portfolio
.Order
, "fetch")
1948 def test_cancel(self
, fetch
):
1949 with self
.subTest(debug
=True):
1951 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1952 D("0.1"), "BTC", "long", self
.m
, "trade")
1953 order
.status
= "open"
1956 self
.m
.ccxt
.cancel_order
.assert_not_called()
1957 self
.m
.report
.log_debug_action
.assert_called_once()
1958 self
.m
.report
.log_debug_action
.reset_mock()
1959 self
.assertEqual("canceled", order
.status
)
1961 with self
.subTest(desc
="Nominal case"):
1962 self
.m
.debug
= False
1963 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1964 D("0.1"), "BTC", "long", self
.m
, "trade")
1965 order
.status
= "open"
1969 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1970 fetch
.assert_called_once_with()
1971 self
.m
.report
.log_debug_action
.assert_not_called()
1973 with self
.subTest(exception
=True):
1974 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
1975 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1976 D("0.1"), "BTC", "long", self
.m
, "trade")
1977 order
.status
= "open"
1980 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1981 self
.m
.report
.log_error
.assert_called_once()
1984 with self
.subTest(id=None):
1985 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
1986 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1987 D("0.1"), "BTC", "long", self
.m
, "trade")
1988 order
.status
= "open"
1990 self
.m
.ccxt
.cancel_order
.assert_not_called()
1993 with self
.subTest(open=False):
1994 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
1995 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1996 D("0.1"), "BTC", "long", self
.m
, "trade")
1997 order
.status
= "closed"
1999 self
.m
.ccxt
.cancel_order
.assert_not_called()
2001 def test_dust_amount_remaining(self
):
2002 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2003 D("0.1"), "BTC", "long", self
.m
, "trade")
2004 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
2005 self
.assertFalse(order
.dust_amount_remaining())
2007 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
2008 self
.assertTrue(order
.dust_amount_remaining())
2010 @mock.patch.object(portfolio
.Order
, "fetch")
2011 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
2012 def test_remaining_amount(self
, filled_amount
, fetch
):
2013 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2014 D("0.1"), "BTC", "long", self
.m
, "trade")
2016 self
.assertEqual(9, order
.remaining_amount().value
)
2018 order
.status
= "open"
2019 self
.assertEqual(9, order
.remaining_amount().value
)
2021 @mock.patch.object(portfolio
.Order
, "fetch")
2022 def test_filled_amount(self
, fetch
):
2023 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2024 D("0.1"), "BTC", "long", self
.m
, "trade")
2025 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
2026 "tradeID": 42, "type": "buy", "fee": "0.0015",
2027 "date": "2017-12-30 12:00:12", "rate": "0.1",
2028 "amount": "3", "total": "0.3"
2030 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
2031 "tradeID": 43, "type": "buy", "fee": "0.0015",
2032 "date": "2017-12-30 13:00:12", "rate": "0.2",
2033 "amount": "2", "total": "0.4"
2035 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
2036 fetch
.assert_not_called()
2037 order
.status
= "open"
2038 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
2039 fetch
.assert_called_once()
2040 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
2042 def test_fetch_mouvements(self
):
2043 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
2045 "tradeID": 42, "type": "buy", "fee": "0.0015",
2046 "date": "2017-12-30 12:00:12", "rate": "0.1",
2047 "amount": "3", "total": "0.3"
2050 "tradeID": 43, "type": "buy", "fee": "0.0015",
2051 "date": "2017-12-30 13:00:12", "rate": "0.2",
2052 "amount": "2", "total": "0.4"
2055 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2056 D("0.1"), "BTC", "long", self
.m
, "trade")
2058 order
.mouvements
= ["Foo", "Bar", "Baz"]
2060 order
.fetch_mouvements()
2062 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
2063 self
.assertEqual(2, len(order
.mouvements
))
2064 self
.assertEqual(42, order
.mouvements
[0].id)
2065 self
.assertEqual(43, order
.mouvements
[1].id)
2067 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
2068 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2069 D("0.1"), "BTC", "long", self
.m
, "trade")
2070 order
.fetch_mouvements()
2071 self
.assertEqual(0, len(order
.mouvements
))
2073 def test_mark_finished_order(self
):
2074 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2075 D("0.1"), "BTC", "short", self
.m
, "trade",
2076 close_if_possible
=True)
2077 order
.status
= "closed"
2078 self
.m
.debug
= False
2080 order
.mark_finished_order()
2081 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
2082 self
.m
.ccxt
.close_margin_position
.reset_mock()
2084 order
.status
= "open"
2085 order
.mark_finished_order()
2086 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2088 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2089 D("0.1"), "BTC", "short", self
.m
, "trade",
2090 close_if_possible
=False)
2091 order
.status
= "closed"
2092 order
.mark_finished_order()
2093 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2095 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2096 D("0.1"), "BTC", "short", self
.m
, "trade",
2097 close_if_possible
=True)
2098 order
.status
= "closed"
2099 order
.mark_finished_order()
2100 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2102 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2103 D("0.1"), "BTC", "long", self
.m
, "trade",
2104 close_if_possible
=True)
2105 order
.status
= "closed"
2106 order
.mark_finished_order()
2107 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2111 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2112 D("0.1"), "BTC", "short", self
.m
, "trade",
2113 close_if_possible
=True)
2114 order
.status
= "closed"
2116 order
.mark_finished_order()
2117 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2118 self
.m
.report
.log_debug_action
.assert_called_once()
2120 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
2121 def test_fetch(self
, fetch_mouvements
):
2122 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2123 D("0.1"), "BTC", "long", self
.m
, "trade")
2125 with self
.subTest(debug
=True):
2128 self
.m
.report
.log_debug_action
.assert_called_once()
2129 self
.m
.report
.log_debug_action
.reset_mock()
2130 self
.m
.ccxt
.fetch_order
.assert_not_called()
2131 fetch_mouvements
.assert_not_called()
2133 with self
.subTest(debug
=False):
2134 self
.m
.debug
= False
2135 self
.m
.ccxt
.fetch_order
.return_value
= {
2137 "datetime": "timestamp"
2141 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45)
2142 fetch_mouvements
.assert_called_once()
2143 self
.assertEqual("foo", order
.status
)
2144 self
.assertEqual("timestamp", order
.timestamp
)
2145 self
.assertEqual(1, len(order
.results
))
2146 self
.m
.report
.log_debug_action
.assert_not_called()
2148 with self
.subTest(missing_order
=True):
2149 self
.m
.ccxt
.fetch_order
.side_effect
= [
2150 portfolio
.OrderNotCached
,
2153 self
.assertEqual("closed_unknown", order
.status
)
2155 @mock.patch.object(portfolio
.Order
, "fetch")
2156 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2157 def test_get_status(self
, mark_finished_order
, fetch
):
2158 with self
.subTest(debug
=True):
2160 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2161 D("0.1"), "BTC", "long", self
.m
, "trade")
2162 self
.assertEqual("pending", order
.get_status())
2163 fetch
.assert_not_called()
2164 self
.m
.report
.log_debug_action
.assert_called_once()
2166 with self
.subTest(debug
=False, finished
=False):
2167 self
.m
.debug
= False
2168 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2169 D("0.1"), "BTC", "long", self
.m
, "trade")
2171 def update_status():
2172 order
.status
= "open"
2173 return update_status
2174 fetch
.side_effect
= _fetch(order
)
2175 self
.assertEqual("open", order
.get_status())
2176 mark_finished_order
.assert_not_called()
2177 fetch
.assert_called_once()
2179 mark_finished_order
.reset_mock()
2181 with self
.subTest(debug
=False, finished
=True):
2182 self
.m
.debug
= False
2183 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2184 D("0.1"), "BTC", "long", self
.m
, "trade")
2186 def update_status():
2187 order
.status
= "closed"
2188 return update_status
2189 fetch
.side_effect
= _fetch(order
)
2190 self
.assertEqual("closed", order
.get_status())
2191 mark_finished_order
.assert_called_once()
2192 fetch
.assert_called_once()
2195 self
.m
.ccxt
.order_precision
.return_value
= 4
2196 with self
.subTest(debug
=True):
2198 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2199 D("0.1"), "BTC", "long", self
.m
, "trade")
2201 self
.m
.ccxt
.create_order
.assert_not_called()
2202 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2203 self
.assertEqual("open", order
.status
)
2204 self
.assertEqual(1, len(order
.results
))
2205 self
.assertEqual(-1, order
.id)
2207 self
.m
.ccxt
.create_order
.reset_mock()
2208 with self
.subTest(debug
=False):
2209 self
.m
.debug
= False
2210 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2211 D("0.1"), "BTC", "long", self
.m
, "trade")
2212 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2214 self
.m
.ccxt
.create_order
.assert_called_once()
2215 self
.assertEqual(1, len(order
.results
))
2216 self
.assertEqual("open", order
.status
)
2218 self
.m
.ccxt
.create_order
.reset_mock()
2219 with self
.subTest(exception
=True):
2220 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2221 D("0.1"), "BTC", "long", self
.m
, "trade")
2222 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2224 self
.m
.ccxt
.create_order
.assert_called_once()
2225 self
.assertEqual(0, len(order
.results
))
2226 self
.assertEqual("error", order
.status
)
2227 self
.m
.report
.log_error
.assert_called_once()
2229 self
.m
.ccxt
.create_order
.reset_mock()
2230 with self
.subTest(dust_amount_exception
=True),\
2231 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2232 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2233 D("0.1"), "BTC", "long", self
.m
, "trade")
2234 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2236 self
.m
.ccxt
.create_order
.assert_called_once()
2237 self
.assertEqual(0, len(order
.results
))
2238 self
.assertEqual("closed", order
.status
)
2239 mark_finished_order
.assert_called_once()
2241 self
.m
.ccxt
.order_precision
.return_value
= 8
2242 self
.m
.ccxt
.create_order
.reset_mock()
2243 with self
.subTest(insufficient_funds
=True),\
2244 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2245 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2246 D("0.1"), "BTC", "long", self
.m
, "trade")
2247 self
.m
.ccxt
.create_order
.side_effect
= [
2248 portfolio
.InsufficientFunds
,
2249 portfolio
.InsufficientFunds
,
2250 portfolio
.InsufficientFunds
,
2254 self
.m
.ccxt
.create_order
.assert_has_calls([
2255 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2256 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2257 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2258 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2260 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2261 self
.assertEqual(1, len(order
.results
))
2262 self
.assertEqual("open", order
.status
)
2263 self
.assertEqual(4, order
.tries
)
2264 self
.m
.report
.log_error
.assert_called()
2265 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2267 self
.m
.ccxt
.order_precision
.return_value
= 8
2268 self
.m
.ccxt
.create_order
.reset_mock()
2269 self
.m
.report
.log_error
.reset_mock()
2270 with self
.subTest(insufficient_funds
=True),\
2271 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2272 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2273 D("0.1"), "BTC", "long", self
.m
, "trade")
2274 self
.m
.ccxt
.create_order
.side_effect
= [
2275 portfolio
.InsufficientFunds
,
2276 portfolio
.InsufficientFunds
,
2277 portfolio
.InsufficientFunds
,
2278 portfolio
.InsufficientFunds
,
2279 portfolio
.InsufficientFunds
,
2282 self
.m
.ccxt
.create_order
.assert_has_calls([
2283 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2284 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2285 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2286 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2287 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2289 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2290 self
.assertEqual(0, len(order
.results
))
2291 self
.assertEqual("error", order
.status
)
2292 self
.assertEqual(5, order
.tries
)
2293 self
.m
.report
.log_error
.assert_called()
2294 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2295 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
)
2298 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2299 class MouvementTest(WebMockTestCase
):
2300 def test_values(self
):
2301 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2302 "tradeID": 42, "type": "buy", "fee": "0.0015",
2303 "date": "2017-12-30 12:00:12", "rate": "0.1",
2304 "amount": "10", "total": "1"
2306 self
.assertEqual("ETH", mouvement
.currency
)
2307 self
.assertEqual("BTC", mouvement
.base_currency
)
2308 self
.assertEqual(42, mouvement
.id)
2309 self
.assertEqual("buy", mouvement
.action
)
2310 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2311 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2312 self
.assertEqual(D("0.1"), mouvement
.rate
)
2313 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2314 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2316 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2317 self
.assertIsNone(mouvement
.date
)
2318 self
.assertIsNone(mouvement
.id)
2319 self
.assertIsNone(mouvement
.action
)
2320 self
.assertEqual(-1, mouvement
.fee_rate
)
2321 self
.assertEqual(0, mouvement
.rate
)
2322 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2323 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2325 def test__repr(self
):
2326 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2327 "tradeID": 42, "type": "buy", "fee": "0.0015",
2328 "date": "2017-12-30 12:00:12", "rate": "0.1",
2329 "amount": "10", "total": "1"
2331 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2333 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2334 "tradeID": 42, "type": "buy",
2335 "date": "garbage", "rate": "0.1",
2336 "amount": "10", "total": "1"
2338 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2340 def test_as_json(self
):
2341 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2342 "tradeID": 42, "type": "buy", "fee": "0.0015",
2343 "date": "2017-12-30 12:00:12", "rate": "0.1",
2344 "amount": "10", "total": "1"
2346 as_json
= mouvement
.as_json()
2348 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2349 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2350 self
.assertEqual("buy", as_json
["action"])
2351 self
.assertEqual(D("10"), as_json
["total"])
2352 self
.assertEqual(D("1"), as_json
["total_in_base"])
2353 self
.assertEqual("BTC", as_json
["base_currency"])
2354 self
.assertEqual("ETH", as_json
["currency"])
2356 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2357 class ReportStoreTest(WebMockTestCase
):
2358 def test_add_log(self
):
2359 report_store
= market
.ReportStore(self
.m
)
2360 report_store
.add_log({"foo": "bar"}
)
2362 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2364 def test_set_verbose(self
):
2365 report_store
= market
.ReportStore(self
.m
)
2366 with self
.subTest(verbose
=True):
2367 report_store
.set_verbose(True)
2368 self
.assertTrue(report_store
.verbose_print
)
2370 with self
.subTest(verbose
=False):
2371 report_store
.set_verbose(False)
2372 self
.assertFalse(report_store
.verbose_print
)
2374 def test_print_log(self
):
2375 report_store
= market
.ReportStore(self
.m
)
2376 with self
.subTest(verbose
=True),\
2377 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2378 report_store
.set_verbose(True)
2379 report_store
.print_log("Coucou")
2380 report_store
.print_log(portfolio
.Amount("BTC", 1))
2381 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2383 with self
.subTest(verbose
=False),\
2384 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2385 report_store
.set_verbose(False)
2386 report_store
.print_log("Coucou")
2387 report_store
.print_log(portfolio
.Amount("BTC", 1))
2388 self
.assertEqual(stdout_mock
.getvalue(), "")
2390 def test_to_json(self
):
2391 report_store
= market
.ReportStore(self
.m
)
2392 report_store
.logs
.append({"foo": "bar"}
)
2393 self
.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store
.to_json())
2394 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2395 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store
.to_json())
2396 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2397 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store
.to_json())
2399 @mock.patch.object(market
.ReportStore
, "print_log")
2400 @mock.patch.object(market
.ReportStore
, "add_log")
2401 def test_log_stage(self
, add_log
, print_log
):
2402 report_store
= market
.ReportStore(self
.m
)
2404 report_store
.log_stage("foo", bar
="baz", c
=c
, d
=portfolio
.Amount("BTC", 1))
2405 print_log
.assert_has_calls([
2406 mock
.call("-----------"),
2407 mock
.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
2409 add_log
.assert_called_once_with({
2414 'c': 'c = lambda x: x',
2422 @mock.patch.object(market
.ReportStore
, "print_log")
2423 @mock.patch.object(market
.ReportStore
, "add_log")
2424 def test_log_balances(self
, add_log
, print_log
):
2425 report_store
= market
.ReportStore(self
.m
)
2426 self
.m
.balances
.as_json
.return_value
= "json"
2427 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2429 report_store
.log_balances(tag
="tag")
2430 print_log
.assert_has_calls([
2431 mock
.call("[Balance]"),
2435 add_log
.assert_called_once_with({
2441 @mock.patch.object(market
.ReportStore
, "print_log")
2442 @mock.patch.object(market
.ReportStore
, "add_log")
2443 def test_log_tickers(self
, add_log
, print_log
):
2444 report_store
= market
.ReportStore(self
.m
)
2446 "BTC": portfolio
.Amount("BTC", 10),
2447 "ETH": portfolio
.Amount("BTC", D("0.3"))
2449 amounts
["ETH"].rate
= D("0.1")
2451 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2452 print_log
.assert_not_called()
2453 add_log
.assert_called_once_with({
2455 'compute_value': 'default',
2456 'balance_type': 'total',
2469 add_log
.reset_mock()
2470 compute_value
= lambda x
: x
["bid"]
2471 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
2472 add_log
.assert_called_once_with({
2474 'compute_value': 'compute_value = lambda x: x["bid"]',
2475 'balance_type': 'total',
2488 @mock.patch.object(market
.ReportStore
, "print_log")
2489 @mock.patch.object(market
.ReportStore
, "add_log")
2490 def test_log_dispatch(self
, add_log
, print_log
):
2491 report_store
= market
.ReportStore(self
.m
)
2492 amount
= portfolio
.Amount("BTC", "10.3")
2494 "BTC": portfolio
.Amount("BTC", 10),
2495 "ETH": portfolio
.Amount("BTC", D("0.3"))
2497 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2498 print_log
.assert_not_called()
2499 add_log
.assert_called_once_with({
2501 'liquidity': 'medium',
2502 'repartition_ratio': 'repartition',
2513 @mock.patch.object(market
.ReportStore
, "print_log")
2514 @mock.patch.object(market
.ReportStore
, "add_log")
2515 def test_log_trades(self
, add_log
, print_log
):
2516 report_store
= market
.ReportStore(self
.m
)
2517 trade_mock1
= mock
.Mock()
2518 trade_mock2
= mock
.Mock()
2519 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2520 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2522 matching_and_trades
= [
2523 (True, trade_mock1
),
2524 (False, trade_mock2
),
2526 report_store
.log_trades(matching_and_trades
, "only")
2528 print_log
.assert_not_called()
2529 add_log
.assert_called_with({
2534 {'trade': '1', 'skipped': False}
,
2535 {'trade': '2', 'skipped': True}
2539 @mock.patch.object(market
.ReportStore
, "print_log")
2540 @mock.patch.object(market
.ReportStore
, "add_log")
2541 def test_log_orders(self
, add_log
, print_log
):
2542 report_store
= market
.ReportStore(self
.m
)
2544 order_mock1
= mock
.Mock()
2545 order_mock2
= mock
.Mock()
2547 order_mock1
.as_json
.return_value
= "order1"
2548 order_mock2
.as_json
.return_value
= "order2"
2550 orders
= [order_mock1
, order_mock2
]
2552 report_store
.log_orders(orders
, tick
="tick",
2553 only
="only", compute_value
="compute_value")
2555 print_log
.assert_called_once_with("[Orders]")
2556 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2558 add_log
.assert_called_with({
2561 'compute_value': 'compute_value',
2563 'orders': ['order1', 'order2']
2566 add_log
.reset_mock()
2567 def compute_value(x
, y
):
2569 report_store
.log_orders(orders
, tick
="tick",
2570 only
="only", compute_value
=compute_value
)
2571 add_log
.assert_called_with({
2574 'compute_value': 'def compute_value(x, y):\n return x[y]',
2576 'orders': ['order1', 'order2']
2580 @mock.patch.object(market
.ReportStore
, "print_log")
2581 @mock.patch.object(market
.ReportStore
, "add_log")
2582 def test_log_order(self
, add_log
, print_log
):
2583 report_store
= market
.ReportStore(self
.m
)
2584 order_mock
= mock
.Mock()
2585 order_mock
.as_json
.return_value
= "order"
2586 new_order_mock
= mock
.Mock()
2587 new_order_mock
.as_json
.return_value
= "new_order"
2588 order_mock
.__repr
__ = mock
.Mock()
2589 order_mock
.__repr
__.return_value
= "Order Mock"
2590 new_order_mock
.__repr
__ = mock
.Mock()
2591 new_order_mock
.__repr
__.return_value
= "New order Mock"
2593 with self
.subTest(finished
=True):
2594 report_store
.log_order(order_mock
, 1, finished
=True)
2595 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2596 add_log
.assert_called_once_with({
2601 'compute_value': None,
2605 add_log
.reset_mock()
2606 print_log
.reset_mock()
2608 with self
.subTest(update
="waiting"):
2609 report_store
.log_order(order_mock
, 1, update
="waiting")
2610 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2611 add_log
.assert_called_once_with({
2614 'update': 'waiting',
2616 'compute_value': None,
2620 add_log
.reset_mock()
2621 print_log
.reset_mock()
2622 with self
.subTest(update
="adjusting"):
2623 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
2624 report_store
.log_order(order_mock
, 3,
2625 update
="adjusting", new_order
=new_order_mock
,
2626 compute_value
=compute_value
)
2627 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2628 add_log
.assert_called_once_with({
2631 'update': 'adjusting',
2633 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
2634 'new_order': 'new_order'
2637 add_log
.reset_mock()
2638 print_log
.reset_mock()
2639 with self
.subTest(update
="market_fallback"):
2640 report_store
.log_order(order_mock
, 7,
2641 update
="market_fallback", new_order
=new_order_mock
)
2642 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2643 add_log
.assert_called_once_with({
2646 'update': 'market_fallback',
2648 'compute_value': None,
2649 'new_order': 'new_order'
2652 add_log
.reset_mock()
2653 print_log
.reset_mock()
2654 with self
.subTest(update
="market_adjusting"):
2655 report_store
.log_order(order_mock
, 17,
2656 update
="market_adjust", new_order
=new_order_mock
)
2657 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2658 add_log
.assert_called_once_with({
2661 'update': 'market_adjust',
2663 'compute_value': None,
2664 'new_order': 'new_order'
2667 @mock.patch.object(market
.ReportStore
, "print_log")
2668 @mock.patch.object(market
.ReportStore
, "add_log")
2669 def test_log_move_balances(self
, add_log
, print_log
):
2670 report_store
= market
.ReportStore(self
.m
)
2672 "BTC": portfolio
.Amount("BTC", 10),
2676 "BTC": portfolio
.Amount("BTC", 3),
2679 report_store
.log_move_balances(needed
, moving
)
2680 print_log
.assert_not_called()
2681 add_log
.assert_called_once_with({
2682 'type': 'move_balances',
2694 @mock.patch.object(market
.ReportStore
, "print_log")
2695 @mock.patch.object(market
.ReportStore
, "add_log")
2696 def test_log_http_request(self
, add_log
, print_log
):
2697 report_store
= market
.ReportStore(self
.m
)
2698 response
= mock
.Mock()
2699 response
.status_code
= 200
2700 response
.text
= "Hey"
2702 report_store
.log_http_request("method", "url", "body",
2703 "headers", response
)
2704 print_log
.assert_not_called()
2705 add_log
.assert_called_once_with({
2706 'type': 'http_request',
2710 'headers': 'headers',
2715 @mock.patch.object(market
.ReportStore
, "print_log")
2716 @mock.patch.object(market
.ReportStore
, "add_log")
2717 def test_log_error(self
, add_log
, print_log
):
2718 report_store
= market
.ReportStore(self
.m
)
2719 with self
.subTest(message
=None, exception
=None):
2720 report_store
.log_error("action")
2721 print_log
.assert_called_once_with("[Error] action")
2722 add_log
.assert_called_once_with({
2725 'exception_class': None,
2726 'exception_message': None,
2730 print_log
.reset_mock()
2731 add_log
.reset_mock()
2732 with self
.subTest(message
="Hey", exception
=None):
2733 report_store
.log_error("action", message
="Hey")
2734 print_log
.assert_has_calls([
2735 mock
.call("[Error] action"),
2738 add_log
.assert_called_once_with({
2741 'exception_class': None,
2742 'exception_message': None,
2746 print_log
.reset_mock()
2747 add_log
.reset_mock()
2748 with self
.subTest(message
=None, exception
=Exception("bouh")):
2749 report_store
.log_error("action", exception
=Exception("bouh"))
2750 print_log
.assert_has_calls([
2751 mock
.call("[Error] action"),
2752 mock
.call("\tException: bouh")
2754 add_log
.assert_called_once_with({
2757 'exception_class': "Exception",
2758 'exception_message': "bouh",
2762 print_log
.reset_mock()
2763 add_log
.reset_mock()
2764 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2765 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2766 print_log
.assert_has_calls([
2767 mock
.call("[Error] action"),
2768 mock
.call("\tException: bouh"),
2771 add_log
.assert_called_once_with({
2774 'exception_class': "Exception",
2775 'exception_message': "bouh",
2779 @mock.patch.object(market
.ReportStore
, "print_log")
2780 @mock.patch.object(market
.ReportStore
, "add_log")
2781 def test_log_debug_action(self
, add_log
, print_log
):
2782 report_store
= market
.ReportStore(self
.m
)
2783 report_store
.log_debug_action("Hey")
2785 print_log
.assert_called_once_with("[Debug] Hey")
2786 add_log
.assert_called_once_with({
2787 'type': 'debug_action',
2791 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2792 class HelperTest(WebMockTestCase
):
2793 def test_make_order(self
):
2794 self
.m
.get_ticker
.return_value
= {
2796 "average": D("0.1"),
2801 with self
.subTest(description
="nominal case"):
2802 helper
.make_order(self
.m
, 10, "ETH")
2804 self
.m
.report
.log_stage
.assert_has_calls([
2805 mock
.call("make_order_begin"),
2806 mock
.call("make_order_end"),
2808 self
.m
.balances
.fetch_balances
.assert_has_calls([
2809 mock
.call(tag
="make_order_begin"),
2810 mock
.call(tag
="make_order_end"),
2812 self
.m
.trades
.all
.append
.assert_called_once()
2813 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2814 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2815 self
.assertEqual(0, trade
.value_from
)
2816 self
.assertEqual("ETH", trade
.currency
)
2817 self
.assertEqual("BTC", trade
.base_currency
)
2818 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2819 self
.m
.trades
.run_orders
.assert_called_once_with()
2820 self
.m
.follow_orders
.assert_called_once_with()
2822 order
= trade
.orders
[0]
2823 self
.assertEqual(D("0.10"), order
.rate
)
2826 with self
.subTest(compute_value
="default"):
2827 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2828 compute_value
="ask")
2830 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2831 order
= trade
.orders
[0]
2832 self
.assertEqual(D("0.11"), order
.rate
)
2835 with self
.subTest(follow
=False):
2836 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2838 self
.m
.report
.log_stage
.assert_has_calls([
2839 mock
.call("make_order_begin"),
2840 mock
.call("make_order_end_not_followed"),
2842 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2844 self
.m
.trades
.all
.append
.assert_called_once()
2845 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2846 self
.assertEqual(0, trade
.value_from
)
2847 self
.assertEqual("ETH", trade
.currency
)
2848 self
.assertEqual("BTC", trade
.base_currency
)
2849 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2850 self
.m
.trades
.run_orders
.assert_called_once_with()
2851 self
.m
.follow_orders
.assert_not_called()
2852 self
.assertEqual(trade
.orders
[0], result
)
2855 with self
.subTest(base_currency
="USDT"):
2856 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2858 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2859 self
.assertEqual("BTC", trade
.currency
)
2860 self
.assertEqual("USDT", trade
.base_currency
)
2863 with self
.subTest(close_if_possible
=True):
2864 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2866 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2867 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2870 with self
.subTest(action
="dispose"):
2871 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2873 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2874 self
.assertEqual(0, trade
.value_to
)
2875 self
.assertEqual(1, trade
.value_from
.value
)
2876 self
.assertEqual("ETH", trade
.currency
)
2877 self
.assertEqual("BTC", trade
.base_currency
)
2880 with self
.subTest(compute_value
="default"):
2881 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2882 compute_value
="bid")
2884 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2885 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2887 def test_user_market(self
):
2888 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2889 mock
.patch("helper.main_parse_config") as main_parse_config
:
2890 with self
.subTest(debug
=False):
2891 main_parse_config
.return_value
= ["pg_config", "report_path"]
2892 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2893 m
= helper
.get_user_market("config_path.ini", 1)
2895 self
.assertIsInstance(m
, market
.Market
)
2896 self
.assertFalse(m
.debug
)
2898 with self
.subTest(debug
=True):
2899 main_parse_config
.return_value
= ["pg_config", "report_path"]
2900 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2901 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2903 self
.assertIsInstance(m
, market
.Market
)
2904 self
.assertTrue(m
.debug
)
2906 def test_main_store_report(self
):
2907 file_open
= mock
.mock_open()
2908 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2909 helper
.main_store_report(None, 1, self
.m
)
2910 file_open
.assert_not_called()
2912 file_open
= mock
.mock_open()
2913 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2914 mock
.patch
.object(helper
, "datetime") as time_mock
:
2915 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2916 self
.m
.report
.to_json
.return_value
= "json_content"
2918 helper
.main_store_report("present", 1, self
.m
)
2920 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2921 file_open().write
.assert_called_once_with("json_content")
2922 self
.m
.report
.to_json
.assert_called_once_with()
2924 with self
.subTest(file="error"),\
2925 mock
.patch("helper.open") as file_open
,\
2926 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2927 file_open
.side_effect
= FileNotFoundError
2929 helper
.main_store_report("error", 1, self
.m
)
2931 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2933 @mock.patch("helper.Processor.process")
2934 def test_main_process_market(self
, process
):
2935 with self
.subTest(before
=False, after
=False):
2937 helper
.main_process_market(m
, None)
2939 process
.assert_not_called()
2941 process
.reset_mock()
2942 with self
.subTest(before
=True, after
=False):
2943 helper
.main_process_market(m
, None, before
=True)
2945 process
.assert_called_once_with("sell_all", steps
="before")
2947 process
.reset_mock()
2948 with self
.subTest(before
=False, after
=True):
2949 helper
.main_process_market(m
, None, after
=True)
2951 process
.assert_called_once_with("sell_all", steps
="after")
2953 process
.reset_mock()
2954 with self
.subTest(before
=True, after
=True):
2955 helper
.main_process_market(m
, None, before
=True, after
=True)
2957 process
.assert_has_calls([
2958 mock
.call("sell_all", steps
="before"),
2959 mock
.call("sell_all", steps
="after"),
2962 process
.reset_mock()
2963 with self
.subTest(action
="print_balances"),\
2964 mock
.patch("helper.print_balances") as print_balances
:
2965 helper
.main_process_market("user", ["print_balances"])
2967 process
.assert_not_called()
2968 print_balances
.assert_called_once_with("user")
2970 with self
.subTest(action
="print_orders"),\
2971 mock
.patch("helper.print_orders") as print_orders
,\
2972 mock
.patch("helper.print_balances") as print_balances
:
2973 helper
.main_process_market("user", ["print_orders", "print_balances"])
2975 process
.assert_not_called()
2976 print_orders
.assert_called_once_with("user")
2977 print_balances
.assert_called_once_with("user")
2979 with self
.subTest(action
="unknown"),\
2980 self
.assertRaises(NotImplementedError):
2981 helper
.main_process_market("user", ["unknown"])
2983 @mock.patch.object(helper
, "psycopg2")
2984 def test_fetch_markets(self
, psycopg2
):
2985 connect_mock
= mock
.Mock()
2986 cursor_mock
= mock
.MagicMock()
2987 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2989 connect_mock
.cursor
.return_value
= cursor_mock
2990 psycopg2
.connect
.return_value
= connect_mock
2992 with self
.subTest(user
=None):
2993 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2995 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2996 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2998 self
.assertEqual(["row_1", "row_2"], rows
)
3000 psycopg2
.connect
.reset_mock()
3001 cursor_mock
.execute
.reset_mock()
3002 with self
.subTest(user
=1):
3003 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
3005 psycopg2
.connect
.assert_called_once_with(foo
="bar")
3006 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
3008 self
.assertEqual(["row_1", "row_2"], rows
)
3010 @mock.patch.object(helper
.sys
, "exit")
3011 def test_main_parse_args(self
, exit
):
3012 with self
.subTest(config
="config.ini"):
3013 args
= helper
.main_parse_args([])
3014 self
.assertEqual("config.ini", args
.config
)
3015 self
.assertFalse(args
.before
)
3016 self
.assertFalse(args
.after
)
3017 self
.assertFalse(args
.debug
)
3019 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
3020 self
.assertTrue(args
.before
)
3021 self
.assertTrue(args
.after
)
3022 self
.assertTrue(args
.debug
)
3024 exit
.assert_not_called()
3026 with self
.subTest(config
="inexistant"),\
3027 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3028 args
= helper
.main_parse_args(["--config", "foo.bar"])
3029 exit
.assert_called_once_with(1)
3030 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
3032 @mock.patch.object(helper
.sys
, "exit")
3033 @mock.patch("helper.configparser")
3034 @mock.patch("helper.os")
3035 def test_main_parse_config(self
, os
, configparser
, exit
):
3036 with self
.subTest(pg_config
=True, report_path
=None):
3037 config_mock
= mock
.MagicMock()
3038 configparser
.ConfigParser
.return_value
= config_mock
3039 def config(element
):
3040 return element
== "postgresql"
3042 config_mock
.__contains
__.side_effect
= config
3043 config_mock
.__getitem
__.return_value
= "pg_config"
3045 result
= helper
.main_parse_config("configfile")
3047 config_mock
.read
.assert_called_with("configfile")
3049 self
.assertEqual(["pg_config", None], result
)
3051 with self
.subTest(pg_config
=True, report_path
="present"):
3052 config_mock
= mock
.MagicMock()
3053 configparser
.ConfigParser
.return_value
= config_mock
3055 config_mock
.__contains
__.return_value
= True
3056 config_mock
.__getitem
__.side_effect
= [
3057 {"report_path": "report_path"}
,
3058 {"report_path": "report_path"}
,
3062 os
.path
.exists
.return_value
= False
3063 result
= helper
.main_parse_config("configfile")
3065 config_mock
.read
.assert_called_with("configfile")
3066 self
.assertEqual(["pg_config", "report_path"], result
)
3067 os
.path
.exists
.assert_called_once_with("report_path")
3068 os
.makedirs
.assert_called_once_with("report_path")
3070 with self
.subTest(pg_config
=False),\
3071 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3072 config_mock
= mock
.MagicMock()
3073 configparser
.ConfigParser
.return_value
= config_mock
3074 result
= helper
.main_parse_config("configfile")
3076 config_mock
.read
.assert_called_with("configfile")
3077 exit
.assert_called_once_with(1)
3078 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
3081 def test_print_orders(self
):
3082 helper
.print_orders(self
.m
)
3084 self
.m
.report
.log_stage
.assert_called_with("print_orders")
3085 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
3086 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3087 compute_value
="average")
3088 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3090 def test_print_balances(self
):
3091 self
.m
.balances
.in_currency
.return_value
= {
3092 "BTC": portfolio
.Amount("BTC", "0.65"),
3093 "ETH": portfolio
.Amount("BTC", "0.3"),
3096 helper
.print_balances(self
.m
)
3098 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
3099 self
.m
.balances
.fetch_balances
.assert_called_with()
3100 self
.m
.report
.print_log
.assert_has_calls([
3101 mock
.call("total:"),
3102 mock
.call(portfolio
.Amount("BTC", "0.95")),
3105 @unittest.skipUnless("unit" in limits
, "Unit skipped")
3106 class ProcessorTest(WebMockTestCase
):
3107 def test_values(self
):
3108 processor
= helper
.Processor(self
.m
)
3110 self
.assertEqual(self
.m
, processor
.market
)
3112 def test_run_action(self
):
3113 processor
= helper
.Processor(self
.m
)
3115 with mock
.patch
.object(processor
, "parse_args") as parse_args
:
3116 method_mock
= mock
.Mock()
3117 parse_args
.return_value
= [method_mock
, { "foo": "bar" }
]
3119 processor
.run_action("foo", "bar", "baz")
3121 parse_args
.assert_called_with("foo", "bar", "baz")
3123 method_mock
.assert_called_with(foo
="bar")
3125 processor
.run_action("wait_for_recent", "bar", "baz")
3127 method_mock
.assert_called_with(self
.m
, foo
="bar")
3129 def test_select_step(self
):
3130 processor
= helper
.Processor(self
.m
)
3132 scenario
= processor
.scenarios
["sell_all"]
3134 self
.assertEqual(scenario
, processor
.select_steps(scenario
, "all"))
3135 self
.assertEqual(["all_sell"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "before"))))
3136 self
.assertEqual(["wait", "all_buy"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "after"))))
3137 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, 2))))
3138 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "wait"))))
3140 with self
.assertRaises(TypeError):
3141 processor
.select_steps(scenario
, ["wait"])
3143 @mock.patch("helper.Processor.process_step")
3144 def test_process(self
, process_step
):
3145 processor
= helper
.Processor(self
.m
)
3147 processor
.process("sell_all", foo
="bar")
3148 self
.assertEqual(3, process_step
.call_count
)
3150 steps
= list(map(lambda x
: x
[1][1]["name"], process_step
.mock_calls
))
3151 scenario_names
= list(map(lambda x
: x
[1][0], process_step
.mock_calls
))
3152 kwargs
= list(map(lambda x
: x
[1][2], process_step
.mock_calls
))
3153 self
.assertEqual(["all_sell", "wait", "all_buy"], steps
)
3154 self
.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names
)
3155 self
.assertEqual([{"foo":"bar"}
, {"foo":"bar"}
, {"foo":"bar"}
], kwargs
)
3157 process_step
.reset_mock()
3159 processor
.process("sell_needed", steps
=["before", "after"])
3160 self
.assertEqual(3, process_step
.call_count
)
3162 def test_method_arguments(self
):
3163 ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
3164 m
= market
.Market(ccxt
)
3166 processor
= helper
.Processor(m
)
3168 method
, arguments
= processor
.method_arguments("wait_for_recent")
3169 self
.assertEqual(portfolio
.Portfolio
.wait_for_recent
, method
)
3170 self
.assertEqual(["delta"], arguments
)
3172 method
, arguments
= processor
.method_arguments("prepare_trades")
3173 self
.assertEqual(m
.prepare_trades
, method
)
3174 self
.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments
)
3176 method
, arguments
= processor
.method_arguments("prepare_orders")
3177 self
.assertEqual(m
.trades
.prepare_orders
, method
)
3179 method
, arguments
= processor
.method_arguments("move_balances")
3180 self
.assertEqual(m
.move_balances
, method
)
3182 method
, arguments
= processor
.method_arguments("run_orders")
3183 self
.assertEqual(m
.trades
.run_orders
, method
)
3185 method
, arguments
= processor
.method_arguments("follow_orders")
3186 self
.assertEqual(m
.follow_orders
, method
)
3188 method
, arguments
= processor
.method_arguments("close_trades")
3189 self
.assertEqual(m
.trades
.close_trades
, method
)
3191 def test_process_step(self
):
3192 processor
= helper
.Processor(self
.m
)
3194 with mock
.patch
.object(processor
, "run_action") as run_action
:
3195 step
= processor
.scenarios
["sell_needed"][1]
3197 processor
.process_step("foo", step
, {"foo":"bar"}
)
3199 self
.m
.report
.log_stage
.assert_has_calls([
3200 mock
.call("process_foo__1_sell_begin"),
3201 mock
.call("process_foo__1_sell_end"),
3203 self
.m
.balances
.fetch_balances
.assert_has_calls([
3204 mock
.call(tag
="process_foo__1_sell_begin"),
3205 mock
.call(tag
="process_foo__1_sell_end"),
3208 self
.assertEqual(5, run_action
.call_count
)
3210 run_action
.assert_has_calls([
3211 mock
.call('prepare_trades', {}, {'foo': 'bar'}
),
3212 mock
.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}
, {'foo': 'bar'}
),
3213 mock
.call('run_orders', {}, {'foo': 'bar'}
),
3214 mock
.call('follow_orders', {}, {'foo': 'bar'}
),
3215 mock
.call('close_trades', {}, {'foo': 'bar'}
),
3219 with mock
.patch
.object(processor
, "run_action") as run_action
:
3220 step
= processor
.scenarios
["sell_needed"][0]
3222 processor
.process_step("foo", step
, {"foo":"bar"}
)
3223 self
.m
.balances
.fetch_balances
.assert_not_called()
3225 def test_parse_args(self
):
3226 processor
= helper
.Processor(self
.m
)
3228 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3229 method_mock
= mock
.Mock()
3230 method_arguments
.return_value
= [
3234 method
, args
= processor
.parse_args("action", {"foo": "bar", "foo2": "bar"}
, {"foo": "bar2", "bla": "bla"}
)
3236 self
.assertEqual(method_mock
, method
)
3237 self
.assertEqual({"foo": "bar2", "foo2": "bar"}
, args
)
3239 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3240 method_mock
= mock
.Mock()
3241 method_arguments
.return_value
= [
3245 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {})
3247 self
.assertEqual(1, len(args
["repartition"]))
3248 self
.assertIn("BTC", args
["repartition"])
3250 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3251 method_mock
= mock
.Mock()
3252 method_arguments
.return_value
= [
3254 ["repartition", "base_currency"]
3256 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {"base_currency": "USDT"}
)
3258 self
.assertEqual(1, len(args
["repartition"]))
3259 self
.assertIn("USDT", args
["repartition"])
3261 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
3262 method_mock
= mock
.Mock()
3263 method_arguments
.return_value
= [
3265 ["repartition", "base_currency"]
3267 method
, args
= processor
.parse_args("action", {"repartition": { "ETH": 1 }
}, {"base_currency": "USDT"}
)
3269 self
.assertEqual(1, len(args
["repartition"]))
3270 self
.assertIn("ETH", args
["repartition"])
3273 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3274 class AcceptanceTest(WebMockTestCase
):
3275 @unittest.expectedFailure
3276 def test_success_sell_only_necessary(self
):
3277 # FIXME: catch stdout
3278 self
.m
.report
.verbose_print
= False
3281 "exchange_free": D("1.0"),
3282 "exchange_used": D("0.0"),
3283 "exchange_total": D("1.0"),
3287 "exchange_free": D("4.0"),
3288 "exchange_used": D("0.0"),
3289 "exchange_total": D("4.0"),
3293 "exchange_free": D("1000.0"),
3294 "exchange_used": D("0.0"),
3295 "exchange_total": D("1000.0"),
3296 "total": D("1000.0"),
3300 "ETH": (D("0.25"), "long"),
3301 "ETC": (D("0.25"), "long"),
3302 "BTC": (D("0.4"), "long"),
3303 "BTD": (D("0.01"), "short"),
3304 "B2X": (D("0.04"), "long"),
3305 "USDT": (D("0.05"), "long"),
3308 def fetch_ticker(symbol
):
3309 if symbol
== "ETH/BTC":
3311 "symbol": "ETH/BTC",
3315 if symbol
== "ETC/BTC":
3317 "symbol": "ETC/BTC",
3321 if symbol
== "XVG/BTC":
3323 "symbol": "XVG/BTC",
3324 "bid": D("0.00003"),
3327 if symbol
== "BTD/BTC":
3329 "symbol": "BTD/BTC",
3333 if symbol
== "B2X/BTC":
3335 "symbol": "B2X/BTC",
3339 if symbol
== "USDT/BTC":
3340 raise helper
.ExchangeError
3341 if symbol
== "BTC/USDT":
3343 "symbol": "BTC/USDT",
3347 self
.fail("Shouldn't have been called with {}".format(symbol
))
3349 market
= mock
.Mock()
3350 market
.fetch_all_balances
.return_value
= fetch_balance
3351 market
.fetch_ticker
.side_effect
= fetch_ticker
3352 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3354 helper
.prepare_trades(market
)
3356 balances
= portfolio
.BalanceStore
.all
3357 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3358 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3359 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3362 trades
= portfolio
.TradeStore
.all
3363 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3364 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3365 self
.assertEqual("dispose", trades
[0].action
)
3367 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3368 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3369 self
.assertEqual("acquire", trades
[1].action
)
3371 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3372 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3373 self
.assertEqual("dispose", trades
[2].action
)
3375 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3376 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3377 self
.assertEqual("acquire", trades
[3].action
)
3379 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3380 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3381 self
.assertEqual("acquire", trades
[4].action
)
3383 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3384 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3385 self
.assertEqual("acquire", trades
[5].action
)
3388 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3390 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3391 self
.assertEqual(2, len(all_orders
))
3392 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3393 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3394 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3395 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3398 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3399 self
.assertEqual("limit", type)
3400 if symbol
== "ETH/BTC":
3401 self
.assertEqual("sell", action
)
3402 self
.assertEqual(D('0.66666666'), amount
)
3403 self
.assertEqual(D("0.14014"), price
)
3404 elif symbol
== "XVG/BTC":
3405 self
.assertEqual("sell", action
)
3406 self
.assertEqual(1000, amount
)
3407 self
.assertEqual(D("0.00003003"), price
)
3409 self
.fail("I shouldn't have been called")
3414 market
.create_order
.side_effect
= create_order
3415 market
.order_precision
.return_value
= 8
3418 portfolio
.TradeStore
.run_orders()
3420 self
.assertEqual("open", all_orders
[0].status
)
3421 self
.assertEqual("open", all_orders
[1].status
)
3423 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3424 market
.privatePostReturnOrderTrades
.return_value
= [
3426 "tradeID": 42, "type": "buy", "fee": "0.0015",
3427 "date": "2017-12-30 12:00:12", "rate": "0.1",
3428 "amount": "10", "total": "1"
3431 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3433 helper
.follow_orders(verbose
=False)
3435 sleep
.assert_called_with(30)
3437 for order
in all_orders
:
3438 self
.assertEqual("closed", order
.status
)
3442 "exchange_free": D("1.0") / 3,
3443 "exchange_used": D("0.0"),
3444 "exchange_total": D("1.0") / 3,
3446 "total": D("1.0") / 3,
3449 "exchange_free": D("0.134"),
3450 "exchange_used": D("0.0"),
3451 "exchange_total": D("0.134"),
3453 "total": D("0.134"),
3456 "exchange_free": D("4.0"),
3457 "exchange_used": D("0.0"),
3458 "exchange_total": D("4.0"),
3463 "exchange_free": D("0.0"),
3464 "exchange_used": D("0.0"),
3465 "exchange_total": D("0.0"),
3470 market
.fetch_all_balances
.return_value
= fetch_balance
3472 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3474 helper
.prepare_trades(market
, only
="acquire", compute_value
="average")
3476 balances
= portfolio
.BalanceStore
.all
3477 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3478 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3479 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3480 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3483 trades
= portfolio
.TradeStore
.all
3484 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3485 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3486 self
.assertEqual("dispose", trades
[0].action
)
3488 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3489 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3490 self
.assertEqual("acquire", trades
[1].action
)
3492 self
.assertNotIn("BTC", trades
)
3494 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3495 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3496 self
.assertEqual("dispose", trades
[2].action
)
3498 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3499 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3500 self
.assertEqual("acquire", trades
[3].action
)
3502 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3503 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3504 self
.assertEqual("acquire", trades
[4].action
)
3506 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3507 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3508 self
.assertEqual("acquire", trades
[5].action
)
3511 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3513 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3514 self
.assertEqual(4, len(all_orders
))
3515 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3516 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3517 self
.assertEqual("buy", all_orders
[0].action
)
3518 self
.assertEqual("long", all_orders
[0].trade_type
)
3520 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3521 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3522 self
.assertEqual("sell", all_orders
[1].action
)
3523 self
.assertEqual("short", all_orders
[1].trade_type
)
3525 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3526 self
.assertAlmostEqual(0, diff
.value
)
3527 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3528 self
.assertEqual("buy", all_orders
[2].action
)
3529 self
.assertEqual("long", all_orders
[2].trade_type
)
3531 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3532 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3533 self
.assertEqual("sell", all_orders
[3].action
)
3534 self
.assertEqual("long", all_orders
[3].trade_type
)
3538 # Move balances to margin
3542 # portfolio.TradeStore.run_orders()
3544 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3546 helper
.follow_orders(verbose
=False)
3548 sleep
.assert_called_with(30)
3550 if __name__
== '__main__':