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"])
697 ticker
= m
.get_ticker("XVG", "XMR")
698 self
.assertIsNone(ticker
)
700 with self
.subTest(get_tickers
=False):
701 self
.ccxt
.fetch_tickers
.return_value
= None
702 self
.ccxt
.fetch_ticker
.side_effect
= [
703 { "bid": 1, "ask": 3 }
,
704 market
.ExchangeError("foo"),
705 { "bid": 10, "ask": 40 }
,
706 market
.ExchangeError("foo"),
707 market
.ExchangeError("foo"),
710 m
= market
.Market(self
.ccxt
)
712 ticker
= m
.get_ticker("ETH", "ETC")
713 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
714 self
.assertEqual(1, ticker
["bid"])
715 self
.assertEqual(3, ticker
["ask"])
716 self
.assertEqual(2, ticker
["average"])
717 self
.assertFalse(ticker
["inverted"])
719 ticker
= m
.get_ticker("ETH", "XVG")
720 self
.assertEqual(0.0625, ticker
["average"])
721 self
.assertTrue(ticker
["inverted"])
722 self
.assertIn("original", ticker
)
723 self
.assertEqual(10, ticker
["original"]["bid"])
725 ticker
= m
.get_ticker("XVG", "XMR")
726 self
.assertIsNone(ticker
)
728 def test_fetch_fees(self
):
729 m
= market
.Market(self
.ccxt
)
730 self
.ccxt
.fetch_fees
.return_value
= "Foo"
731 self
.assertEqual("Foo", m
.fetch_fees())
732 self
.ccxt
.fetch_fees
.assert_called_once()
733 self
.ccxt
.reset_mock()
734 self
.assertEqual("Foo", m
.fetch_fees())
735 self
.ccxt
.fetch_fees
.assert_not_called()
737 @mock.patch.object(portfolio
.Portfolio
, "repartition")
738 @mock.patch.object(market
.Market
, "get_ticker")
739 @mock.patch.object(market
.TradeStore
, "compute_trades")
740 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
741 repartition
.return_value
= {
742 "XEM": (D("0.75"), "long"),
743 "BTC": (D("0.25"), "long"),
745 def _get_ticker(c1
, c2
):
746 if c1
== "USDT" and c2
== "BTC":
747 return { "average": D("0.0001") }
748 if c1
== "XVG" and c2
== "BTC":
749 return { "average": D("0.000001") }
750 if c1
== "XEM" and c2
== "BTC":
751 return { "average": D("0.001") }
752 self
.fail("Should be called with {}, {}".format(c1
, c2
))
753 get_ticker
.side_effect
= _get_ticker
755 with mock
.patch("market.ReportStore"):
756 m
= market
.Market(self
.ccxt
)
757 self
.ccxt
.fetch_all_balances
.return_value
= {
759 "exchange_free": D("10000.0"),
760 "exchange_used": D("0.0"),
761 "exchange_total": D("10000.0"),
762 "total": D("10000.0")
765 "exchange_free": D("10000.0"),
766 "exchange_used": D("0.0"),
767 "exchange_total": D("10000.0"),
768 "total": D("10000.0")
772 m
.balances
.fetch_balances(tag
="tag")
775 compute_trades
.assert_called()
777 call
= compute_trades
.call_args
778 self
.assertEqual(1, call
[0][0]["USDT"].value
)
779 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
780 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
781 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
782 m
.report
.log_stage
.assert_called_once_with("prepare_trades")
783 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
785 @mock.patch.object(portfolio
.Portfolio
, "repartition")
786 @mock.patch.object(market
.Market
, "get_ticker")
787 @mock.patch.object(market
.TradeStore
, "compute_trades")
788 def test_update_trades(self
, compute_trades
, get_ticker
, repartition
):
789 repartition
.return_value
= {
790 "XEM": (D("0.75"), "long"),
791 "BTC": (D("0.25"), "long"),
793 def _get_ticker(c1
, c2
):
794 if c1
== "USDT" and c2
== "BTC":
795 return { "average": D("0.0001") }
796 if c1
== "XVG" and c2
== "BTC":
797 return { "average": D("0.000001") }
798 if c1
== "XEM" and c2
== "BTC":
799 return { "average": D("0.001") }
800 self
.fail("Should be called with {}, {}".format(c1
, c2
))
801 get_ticker
.side_effect
= _get_ticker
803 with mock
.patch("market.ReportStore"):
804 m
= market
.Market(self
.ccxt
)
805 self
.ccxt
.fetch_all_balances
.return_value
= {
807 "exchange_free": D("10000.0"),
808 "exchange_used": D("0.0"),
809 "exchange_total": D("10000.0"),
810 "total": D("10000.0")
813 "exchange_free": D("10000.0"),
814 "exchange_used": D("0.0"),
815 "exchange_total": D("10000.0"),
816 "total": D("10000.0")
820 m
.balances
.fetch_balances(tag
="tag")
823 compute_trades
.assert_called()
825 call
= compute_trades
.call_args
826 self
.assertEqual(1, call
[0][0]["USDT"].value
)
827 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
828 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
829 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
830 m
.report
.log_stage
.assert_called_once_with("update_trades")
831 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
833 @mock.patch.object(portfolio
.Portfolio
, "repartition")
834 @mock.patch.object(market
.Market
, "get_ticker")
835 @mock.patch.object(market
.TradeStore
, "compute_trades")
836 def test_prepare_trades_to_sell_all(self
, compute_trades
, get_ticker
, repartition
):
837 def _get_ticker(c1
, c2
):
838 if c1
== "USDT" and c2
== "BTC":
839 return { "average": D("0.0001") }
840 if c1
== "XVG" and c2
== "BTC":
841 return { "average": D("0.000001") }
842 self
.fail("Should be called with {}, {}".format(c1
, c2
))
843 get_ticker
.side_effect
= _get_ticker
845 with mock
.patch("market.ReportStore"):
846 m
= market
.Market(self
.ccxt
)
847 self
.ccxt
.fetch_all_balances
.return_value
= {
849 "exchange_free": D("10000.0"),
850 "exchange_used": D("0.0"),
851 "exchange_total": D("10000.0"),
852 "total": D("10000.0")
855 "exchange_free": D("10000.0"),
856 "exchange_used": D("0.0"),
857 "exchange_total": D("10000.0"),
858 "total": D("10000.0")
862 m
.balances
.fetch_balances(tag
="tag")
864 m
.prepare_trades_to_sell_all()
866 repartition
.assert_not_called()
867 compute_trades
.assert_called()
869 call
= compute_trades
.call_args
870 self
.assertEqual(1, call
[0][0]["USDT"].value
)
871 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
872 self
.assertEqual(D("1.01"), call
[0][1]["BTC"].value
)
873 m
.report
.log_stage
.assert_called_once_with("prepare_trades_to_sell_all")
874 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
876 @mock.patch.object(portfolio
.time
, "sleep")
877 @mock.patch.object(market
.TradeStore
, "all_orders")
878 def test_follow_orders(self
, all_orders
, time_mock
):
879 for debug
, sleep
in [
880 (False, None), (True, None),
881 (False, 12), (True, 12)]:
882 with self
.subTest(sleep
=sleep
, debug
=debug
), \
883 mock
.patch("market.ReportStore"):
884 m
= market
.Market(self
.ccxt
, debug
=debug
)
886 order_mock1
= mock
.Mock()
887 order_mock2
= mock
.Mock()
888 order_mock3
= mock
.Mock()
889 all_orders
.side_effect
= [
890 [order_mock1
, order_mock2
],
891 [order_mock1
, order_mock2
],
893 [order_mock1
, order_mock3
],
894 [order_mock1
, order_mock3
],
896 [order_mock1
, order_mock3
],
897 [order_mock1
, order_mock3
],
902 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
903 order_mock2
.get_status
.side_effect
= ["open"]
904 order_mock3
.get_status
.side_effect
= ["open", "closed"]
906 order_mock1
.trade
= mock
.Mock()
907 order_mock2
.trade
= mock
.Mock()
908 order_mock3
.trade
= mock
.Mock()
910 m
.follow_orders(sleep
=sleep
)
912 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
913 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
914 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
915 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
917 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
918 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
919 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
921 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
922 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
923 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
924 m
.report
.log_stage
.assert_called()
926 mock
.call("follow_orders_begin"),
927 mock
.call("follow_orders_tick_1"),
928 mock
.call("follow_orders_tick_2"),
929 mock
.call("follow_orders_tick_3"),
930 mock
.call("follow_orders_end"),
932 m
.report
.log_stage
.assert_has_calls(calls
)
933 m
.report
.log_orders
.assert_called()
934 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
936 mock
.call([order_mock1
, order_mock2
], tick
=1),
937 mock
.call([order_mock1
, order_mock3
], tick
=2),
938 mock
.call([order_mock1
, order_mock3
], tick
=3),
940 m
.report
.log_orders
.assert_has_calls(calls
)
942 mock
.call(order_mock1
, 3, finished
=True),
943 mock
.call(order_mock3
, 3, finished
=True),
945 m
.report
.log_order
.assert_has_calls(calls
)
949 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
950 time_mock
.assert_called_with(7)
952 time_mock
.assert_called_with(30)
954 time_mock
.assert_called_with(sleep
)
956 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
957 def test_move_balance(self
, fetch_balances
):
958 for debug
in [True, False]:
959 with self
.subTest(debug
=debug
),\
960 mock
.patch("market.ReportStore"):
961 m
= market
.Market(self
.ccxt
, debug
=debug
)
963 value_from
= portfolio
.Amount("BTC", "1.0")
964 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
965 value_to
= portfolio
.Amount("BTC", "10.0")
966 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
968 value_from
= portfolio
.Amount("BTC", "0.0")
969 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
970 value_to
= portfolio
.Amount("BTC", "-3.0")
971 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
973 value_from
= portfolio
.Amount("USDT", "0.0")
974 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
975 value_to
= portfolio
.Amount("USDT", "-50.0")
976 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
978 m
.trades
.all
= [trade1
, trade2
, trade3
]
979 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
980 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
981 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
982 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
986 fetch_balances
.assert_called_with()
987 m
.report
.log_move_balances
.assert_called_once()
990 m
.report
.log_debug_action
.assert_called()
991 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
993 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
994 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
995 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
997 @unittest.skipUnless("unit" in limits
, "Unit skipped")
998 class TradeStoreTest(WebMockTestCase
):
999 def test_compute_trades(self
):
1000 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
1003 "XMR": portfolio
.Amount("BTC", D("0.9")),
1004 "DASH": portfolio
.Amount("BTC", D("0.4")),
1005 "XVG": portfolio
.Amount("BTC", D("-0.5")),
1006 "BTC": portfolio
.Amount("BTC", D("0.5")),
1009 "DASH": portfolio
.Amount("BTC", D("0.5")),
1010 "XVG": portfolio
.Amount("BTC", D("0.1")),
1011 "BTC": portfolio
.Amount("BTC", D("0.4")),
1012 "ETH": portfolio
.Amount("BTC", D("0.3")),
1022 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
1023 trade_store
= market
.TradeStore(self
.m
)
1024 trade_if_matching
.side_effect
= side_effect
1026 trade_store
.compute_trades(values_in_base
,
1027 new_repartition
, only
="only")
1029 self
.assertEqual(5, trade_if_matching
.call_count
)
1030 self
.assertEqual(3, len(trade_store
.all
))
1031 self
.assertEqual([1, 4, 5], trade_store
.all
)
1032 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
1034 def test_trade_if_matching(self
):
1036 with self
.subTest(only
="nope"):
1037 trade_store
= market
.TradeStore(self
.m
)
1038 result
= trade_store
.trade_if_matching(
1039 portfolio
.Amount("BTC", D("0")),
1040 portfolio
.Amount("BTC", D("0.3")),
1042 self
.assertEqual(False, result
[0])
1043 self
.assertIsInstance(result
[1], portfolio
.Trade
)
1045 with self
.subTest(only
=None):
1046 trade_store
= market
.TradeStore(self
.m
)
1047 result
= trade_store
.trade_if_matching(
1048 portfolio
.Amount("BTC", D("0")),
1049 portfolio
.Amount("BTC", D("0.3")),
1051 self
.assertEqual(True, result
[0])
1053 with self
.subTest(only
="acquire"):
1054 trade_store
= market
.TradeStore(self
.m
)
1055 result
= trade_store
.trade_if_matching(
1056 portfolio
.Amount("BTC", D("0")),
1057 portfolio
.Amount("BTC", D("0.3")),
1058 "ETH", only
="acquire")
1059 self
.assertEqual(True, result
[0])
1061 with self
.subTest(only
="dispose"):
1062 trade_store
= market
.TradeStore(self
.m
)
1063 result
= trade_store
.trade_if_matching(
1064 portfolio
.Amount("BTC", D("0")),
1065 portfolio
.Amount("BTC", D("0.3")),
1066 "ETH", only
="dispose")
1067 self
.assertEqual(False, result
[0])
1069 def test_prepare_orders(self
):
1070 trade_store
= market
.TradeStore(self
.m
)
1072 trade_mock1
= mock
.Mock()
1073 trade_mock2
= mock
.Mock()
1074 trade_mock3
= mock
.Mock()
1076 trade_mock1
.prepare_order
.return_value
= 1
1077 trade_mock2
.prepare_order
.return_value
= 2
1078 trade_mock3
.prepare_order
.return_value
= 3
1080 trade_mock1
.is_fullfiled
= False
1081 trade_mock2
.is_fullfiled
= False
1082 trade_mock3
.is_fullfiled
= True
1084 trade_store
.all
.append(trade_mock1
)
1085 trade_store
.all
.append(trade_mock2
)
1086 trade_store
.all
.append(trade_mock3
)
1088 trade_store
.prepare_orders()
1089 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1090 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1091 trade_mock3
.prepare_order
.assert_not_called()
1092 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1094 self
.m
.report
.log_orders
.reset_mock()
1096 trade_store
.prepare_orders(compute_value
="bla")
1097 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1098 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1099 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1101 trade_mock1
.prepare_order
.reset_mock()
1102 trade_mock2
.prepare_order
.reset_mock()
1103 self
.m
.report
.log_orders
.reset_mock()
1105 trade_mock1
.action
= "foo"
1106 trade_mock2
.action
= "bar"
1107 trade_store
.prepare_orders(only
="bar")
1108 trade_mock1
.prepare_order
.assert_not_called()
1109 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1110 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1112 def test_print_all_with_order(self
):
1113 trade_mock1
= mock
.Mock()
1114 trade_mock2
= mock
.Mock()
1115 trade_mock3
= mock
.Mock()
1116 trade_store
= market
.TradeStore(self
.m
)
1117 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1119 trade_store
.print_all_with_order()
1121 trade_mock1
.print_with_order
.assert_called()
1122 trade_mock2
.print_with_order
.assert_called()
1123 trade_mock3
.print_with_order
.assert_called()
1125 def test_run_orders(self
):
1126 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1127 order_mock1
= mock
.Mock()
1128 order_mock2
= mock
.Mock()
1129 order_mock3
= mock
.Mock()
1130 trade_store
= market
.TradeStore(self
.m
)
1132 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1134 trade_store
.run_orders()
1136 all_orders
.assert_called_with(state
="pending")
1138 order_mock1
.run
.assert_called()
1139 order_mock2
.run
.assert_called()
1140 order_mock3
.run
.assert_called()
1142 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1143 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1146 def test_all_orders(self
):
1147 trade_mock1
= mock
.Mock()
1148 trade_mock2
= mock
.Mock()
1150 order_mock1
= mock
.Mock()
1151 order_mock2
= mock
.Mock()
1152 order_mock3
= mock
.Mock()
1154 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1155 trade_mock2
.orders
= [order_mock3
]
1157 order_mock1
.status
= "pending"
1158 order_mock2
.status
= "open"
1159 order_mock3
.status
= "open"
1161 trade_store
= market
.TradeStore(self
.m
)
1162 trade_store
.all
.append(trade_mock1
)
1163 trade_store
.all
.append(trade_mock2
)
1165 orders
= trade_store
.all_orders()
1166 self
.assertEqual(3, len(orders
))
1168 open_orders
= trade_store
.all_orders(state
="open")
1169 self
.assertEqual(2, len(open_orders
))
1170 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1172 def test_update_all_orders_status(self
):
1173 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1174 order_mock1
= mock
.Mock()
1175 order_mock2
= mock
.Mock()
1176 order_mock3
= mock
.Mock()
1178 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1180 trade_store
= market
.TradeStore(self
.m
)
1182 trade_store
.update_all_orders_status()
1183 all_orders
.assert_called_with(state
="open")
1185 order_mock1
.get_status
.assert_called()
1186 order_mock2
.get_status
.assert_called()
1187 order_mock3
.get_status
.assert_called()
1189 def test_pending(self
):
1190 trade_mock1
= mock
.Mock()
1191 trade_mock1
.is_fullfiled
= False
1192 trade_mock2
= mock
.Mock()
1193 trade_mock2
.is_fullfiled
= False
1194 trade_mock3
= mock
.Mock()
1195 trade_mock3
.is_fullfiled
= True
1197 trade_store
= market
.TradeStore(self
.m
)
1199 trade_store
.all
.append(trade_mock1
)
1200 trade_store
.all
.append(trade_mock2
)
1201 trade_store
.all
.append(trade_mock3
)
1203 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
1205 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1206 class BalanceStoreTest(WebMockTestCase
):
1208 super(BalanceStoreTest
, self
).setUp()
1210 self
.fetch_balance
= {
1214 "exchange_total": 0,
1218 "exchange_free": D("6.0"),
1219 "exchange_used": D("1.2"),
1220 "exchange_total": D("7.2"),
1224 "exchange_free": 16,
1226 "exchange_total": 16,
1232 "exchange_total": 0,
1233 "margin_total": D("-1.0"),
1238 def test_in_currency(self
):
1239 self
.m
.get_ticker
.return_value
= {
1242 "average": D("0.1"),
1245 balance_store
= market
.BalanceStore(self
.m
)
1246 balance_store
.all
= {
1247 "BTC": portfolio
.Balance("BTC", {
1249 "exchange_total":"0.65",
1250 "exchange_free": "0.35",
1251 "exchange_used": "0.30"}),
1252 "ETH": portfolio
.Balance("ETH", {
1254 "exchange_total": 3,
1256 "exchange_used": 0}),
1259 amounts
= balance_store
.in_currency("BTC")
1260 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1261 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1262 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1263 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1265 self
.m
.report
.log_tickers
.reset_mock()
1267 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1268 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1269 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1270 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1272 self
.m
.report
.log_tickers
.reset_mock()
1274 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1275 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1276 self
.assertEqual(0, amounts
["ETH"].value
)
1277 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1278 "bid", "exchange_used")
1279 self
.m
.report
.log_tickers
.reset_mock()
1281 def test_fetch_balances(self
):
1282 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1284 balance_store
= market
.BalanceStore(self
.m
)
1286 balance_store
.fetch_balances()
1287 self
.assertNotIn("ETC", balance_store
.currencies())
1288 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1290 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1291 "exchange_total": "1", "exchange_free": "0",
1292 "exchange_used": "1" })
1293 balance_store
.fetch_balances(tag
="foo")
1294 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1295 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1296 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1298 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1299 def test_dispatch_assets(self
, repartition
):
1300 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1302 balance_store
= market
.BalanceStore(self
.m
)
1303 balance_store
.fetch_balances()
1305 self
.assertNotIn("XEM", balance_store
.currencies())
1307 repartition_hash
= {
1308 "XEM": (D("0.75"), "long"),
1309 "BTC": (D("0.26"), "long"),
1310 "DASH": (D("0.10"), "short"),
1312 repartition
.return_value
= repartition_hash
1314 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1315 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1316 self
.assertIn("XEM", balance_store
.currencies())
1317 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1318 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1319 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1320 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1321 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1322 "11.1"), amounts
, "medium", repartition_hash
)
1324 def test_currencies(self
):
1325 balance_store
= market
.BalanceStore(self
.m
)
1327 balance_store
.all
= {
1328 "BTC": portfolio
.Balance("BTC", {
1330 "exchange_total":"0.65",
1331 "exchange_free": "0.35",
1332 "exchange_used": "0.30"}),
1333 "ETH": portfolio
.Balance("ETH", {
1335 "exchange_total": 3,
1337 "exchange_used": 0}),
1339 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1341 def test_as_json(self
):
1342 balance_mock1
= mock
.Mock()
1343 balance_mock1
.as_json
.return_value
= 1
1345 balance_mock2
= mock
.Mock()
1346 balance_mock2
.as_json
.return_value
= 2
1348 balance_store
= market
.BalanceStore(self
.m
)
1349 balance_store
.all
= {
1350 "BTC": balance_mock1
,
1351 "ETH": balance_mock2
,
1354 as_json
= balance_store
.as_json()
1355 self
.assertEqual(1, as_json
["BTC"])
1356 self
.assertEqual(2, as_json
["ETH"])
1359 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1360 class ComputationTest(WebMockTestCase
):
1361 def test_compute_value(self
):
1362 compute
= mock
.Mock()
1363 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1364 compute
.assert_called_with("foo", "ask")
1366 compute
.reset_mock()
1367 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1368 compute
.assert_called_with("foo", "bid")
1370 compute
.reset_mock()
1371 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1372 compute
.assert_called_with("foo", "ask")
1374 compute
.reset_mock()
1375 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1376 compute
.assert_called_with("foo", "bid")
1378 compute
.reset_mock()
1379 portfolio
.Computation
.computations
["test"] = compute
1380 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1381 compute
.assert_called_with("foo", "bid")
1384 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1385 class TradeTest(WebMockTestCase
):
1387 def test_values_assertion(self
):
1388 value_from
= portfolio
.Amount("BTC", "1.0")
1389 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1390 value_to
= portfolio
.Amount("BTC", "1.0")
1391 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1392 self
.assertEqual("BTC", trade
.base_currency
)
1393 self
.assertEqual("ETH", trade
.currency
)
1394 self
.assertEqual(self
.m
, trade
.market
)
1396 with self
.assertRaises(AssertionError):
1397 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
1398 with self
.assertRaises(AssertionError):
1399 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1400 with self
.assertRaises(AssertionError):
1401 value_from
.currency
= "ETH"
1402 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1403 value_from
.currency
= "BTC"
1404 with self
.assertRaises(AssertionError):
1405 value_from2
= portfolio
.Amount("BTC", "1.0")
1406 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
1408 value_from
= portfolio
.Amount("BTC", 0)
1409 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1410 self
.assertEqual(0, trade
.value_from
.linked_to
)
1412 def test_action(self
):
1413 value_from
= portfolio
.Amount("BTC", "1.0")
1414 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1415 value_to
= portfolio
.Amount("BTC", "1.0")
1416 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1418 self
.assertIsNone(trade
.action
)
1420 value_from
= portfolio
.Amount("BTC", "1.0")
1421 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1422 value_to
= portfolio
.Amount("BTC", "2.0")
1423 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1425 self
.assertIsNone(trade
.action
)
1427 value_from
= portfolio
.Amount("BTC", "0.5")
1428 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1429 value_to
= portfolio
.Amount("BTC", "1.0")
1430 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1432 self
.assertEqual("acquire", trade
.action
)
1434 value_from
= portfolio
.Amount("BTC", "0")
1435 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1436 value_to
= portfolio
.Amount("BTC", "-1.0")
1437 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1439 self
.assertEqual("acquire", trade
.action
)
1441 def test_order_action(self
):
1442 value_from
= portfolio
.Amount("BTC", "0.5")
1443 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1444 value_to
= portfolio
.Amount("BTC", "1.0")
1445 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1447 self
.assertEqual("buy", trade
.order_action(False))
1448 self
.assertEqual("sell", trade
.order_action(True))
1450 value_from
= portfolio
.Amount("BTC", "0")
1451 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1452 value_to
= portfolio
.Amount("BTC", "-1.0")
1453 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1455 self
.assertEqual("sell", trade
.order_action(False))
1456 self
.assertEqual("buy", trade
.order_action(True))
1458 def test_trade_type(self
):
1459 value_from
= portfolio
.Amount("BTC", "0.5")
1460 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1461 value_to
= portfolio
.Amount("BTC", "1.0")
1462 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1464 self
.assertEqual("long", trade
.trade_type
)
1466 value_from
= portfolio
.Amount("BTC", "0")
1467 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1468 value_to
= portfolio
.Amount("BTC", "-1.0")
1469 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1471 self
.assertEqual("short", trade
.trade_type
)
1473 def test_is_fullfiled(self
):
1474 value_from
= portfolio
.Amount("BTC", "0.5")
1475 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1476 value_to
= portfolio
.Amount("BTC", "1.0")
1477 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1479 order1
= mock
.Mock()
1480 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1482 order2
= mock
.Mock()
1483 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1484 trade
.orders
.append(order1
)
1485 trade
.orders
.append(order2
)
1487 self
.assertFalse(trade
.is_fullfiled
)
1489 order3
= mock
.Mock()
1490 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1491 trade
.orders
.append(order3
)
1493 self
.assertTrue(trade
.is_fullfiled
)
1495 def test_filled_amount(self
):
1496 value_from
= portfolio
.Amount("BTC", "0.5")
1497 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1498 value_to
= portfolio
.Amount("BTC", "1.0")
1499 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1501 order1
= mock
.Mock()
1502 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1504 order2
= mock
.Mock()
1505 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1506 trade
.orders
.append(order1
)
1507 trade
.orders
.append(order2
)
1509 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1510 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1511 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1513 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1514 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1515 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1517 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1518 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1519 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1521 @mock.patch.object(portfolio
.Computation
, "compute_value")
1522 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1523 @mock.patch.object(portfolio
, "Order")
1524 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1525 Order
.return_value
= "Order"
1527 with self
.subTest(desc
="Nothing to do"):
1528 value_from
= portfolio
.Amount("BTC", "10")
1529 value_from
.rate
= D("0.1")
1530 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1531 value_to
= portfolio
.Amount("BTC", "10")
1532 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1534 trade
.prepare_order()
1536 filled_amount
.assert_not_called()
1537 compute_value
.assert_not_called()
1538 self
.assertEqual(0, len(trade
.orders
))
1539 Order
.assert_not_called()
1541 self
.m
.get_ticker
.return_value
= { "inverted": False }
1542 with self
.subTest(desc
="Already filled"):
1543 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1544 compute_value
.return_value
= D("0.125")
1546 value_from
= portfolio
.Amount("BTC", "10")
1547 value_from
.rate
= D("0.1")
1548 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1549 value_to
= portfolio
.Amount("BTC", "0")
1550 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1552 trade
.prepare_order()
1554 filled_amount
.assert_called_with(in_base_currency
=False)
1555 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1556 self
.assertEqual(0, len(trade
.orders
))
1557 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1558 Order
.assert_not_called()
1560 with self
.subTest(action
="dispose", inverted
=False):
1561 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1562 compute_value
.return_value
= D("0.125")
1564 value_from
= portfolio
.Amount("BTC", "10")
1565 value_from
.rate
= D("0.1")
1566 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1567 value_to
= portfolio
.Amount("BTC", "1")
1568 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1570 trade
.prepare_order()
1572 filled_amount
.assert_called_with(in_base_currency
=False)
1573 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1574 self
.assertEqual(1, len(trade
.orders
))
1575 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1576 D("0.125"), "BTC", "long", self
.m
,
1577 trade
, close_if_possible
=False)
1579 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1580 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1581 compute_value
.return_value
= D("0.125")
1583 value_from
= portfolio
.Amount("BTC", "10")
1584 value_from
.rate
= D("0.1")
1585 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1586 value_to
= portfolio
.Amount("BTC", "1")
1587 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1589 trade
.prepare_order(close_if_possible
=True)
1591 filled_amount
.assert_called_with(in_base_currency
=False)
1592 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1593 self
.assertEqual(1, len(trade
.orders
))
1594 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1595 D("0.125"), "BTC", "long", self
.m
,
1596 trade
, close_if_possible
=True)
1598 with self
.subTest(action
="acquire", inverted
=False):
1599 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1600 compute_value
.return_value
= D("0.125")
1602 value_from
= portfolio
.Amount("BTC", "1")
1603 value_from
.rate
= D("0.1")
1604 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1605 value_to
= portfolio
.Amount("BTC", "10")
1606 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1608 trade
.prepare_order()
1610 filled_amount
.assert_called_with(in_base_currency
=True)
1611 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1612 self
.assertEqual(1, len(trade
.orders
))
1614 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1615 D("0.125"), "BTC", "long", self
.m
,
1616 trade
, close_if_possible
=False)
1618 with self
.subTest(close_if_possible
=True):
1619 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1620 compute_value
.return_value
= D("0.125")
1622 value_from
= portfolio
.Amount("BTC", "10")
1623 value_from
.rate
= D("0.1")
1624 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1625 value_to
= portfolio
.Amount("BTC", "0")
1626 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1628 trade
.prepare_order()
1630 filled_amount
.assert_called_with(in_base_currency
=False)
1631 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1632 self
.assertEqual(1, len(trade
.orders
))
1633 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1634 D("0.125"), "BTC", "long", self
.m
,
1635 trade
, close_if_possible
=True)
1637 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1638 with self
.subTest(action
="dispose", inverted
=True):
1639 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1640 compute_value
.return_value
= D("125")
1642 value_from
= portfolio
.Amount("BTC", "10")
1643 value_from
.rate
= D("0.01")
1644 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1645 value_to
= portfolio
.Amount("BTC", "1")
1646 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1648 trade
.prepare_order(compute_value
="foo")
1650 filled_amount
.assert_called_with(in_base_currency
=True)
1651 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1652 self
.assertEqual(1, len(trade
.orders
))
1653 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1654 D("125"), "FOO", "long", self
.m
,
1655 trade
, close_if_possible
=False)
1657 with self
.subTest(action
="acquire", inverted
=True):
1658 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1659 compute_value
.return_value
= D("125")
1661 value_from
= portfolio
.Amount("BTC", "1")
1662 value_from
.rate
= D("0.01")
1663 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1664 value_to
= portfolio
.Amount("BTC", "10")
1665 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1667 trade
.prepare_order(compute_value
="foo")
1669 filled_amount
.assert_called_with(in_base_currency
=False)
1670 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1671 self
.assertEqual(1, len(trade
.orders
))
1672 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1673 D("125"), "FOO", "long", self
.m
,
1674 trade
, close_if_possible
=False)
1677 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1678 def test_update_order(self
, prepare_order
):
1679 order_mock
= mock
.Mock()
1680 new_order_mock
= mock
.Mock()
1682 value_from
= portfolio
.Amount("BTC", "0.5")
1683 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1684 value_to
= portfolio
.Amount("BTC", "1.0")
1685 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1686 prepare_order
.return_value
= new_order_mock
1688 for i
in [0, 1, 3, 4, 6]:
1689 with self
.subTest(tick
=i
):
1690 trade
.update_order(order_mock
, i
)
1691 order_mock
.cancel
.assert_not_called()
1692 new_order_mock
.run
.assert_not_called()
1693 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1694 update
="waiting", compute_value
=None, new_order
=None)
1696 order_mock
.reset_mock()
1697 new_order_mock
.reset_mock()
1699 self
.m
.report
.log_order
.reset_mock()
1701 trade
.update_order(order_mock
, 2)
1702 order_mock
.cancel
.assert_called()
1703 new_order_mock
.run
.assert_called()
1704 prepare_order
.assert_called()
1705 self
.m
.report
.log_order
.assert_called()
1706 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1708 mock
.call(order_mock
, 2, update
="adjusting",
1709 compute_value
=mock
.ANY
,
1710 new_order
=new_order_mock
),
1711 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1713 self
.m
.report
.log_order
.assert_has_calls(calls
)
1715 order_mock
.reset_mock()
1716 new_order_mock
.reset_mock()
1718 self
.m
.report
.log_order
.reset_mock()
1720 trade
.update_order(order_mock
, 5)
1721 order_mock
.cancel
.assert_called()
1722 new_order_mock
.run
.assert_called()
1723 prepare_order
.assert_called()
1724 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1725 self
.m
.report
.log_order
.assert_called()
1727 mock
.call(order_mock
, 5, update
="adjusting",
1728 compute_value
=mock
.ANY
,
1729 new_order
=new_order_mock
),
1730 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1732 self
.m
.report
.log_order
.assert_has_calls(calls
)
1734 order_mock
.reset_mock()
1735 new_order_mock
.reset_mock()
1737 self
.m
.report
.log_order
.reset_mock()
1739 trade
.update_order(order_mock
, 7)
1740 order_mock
.cancel
.assert_called()
1741 new_order_mock
.run
.assert_called()
1742 prepare_order
.assert_called_with(compute_value
="default")
1743 self
.m
.report
.log_order
.assert_called()
1744 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1746 mock
.call(order_mock
, 7, update
="market_fallback",
1747 compute_value
='default',
1748 new_order
=new_order_mock
),
1749 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1751 self
.m
.report
.log_order
.assert_has_calls(calls
)
1753 order_mock
.reset_mock()
1754 new_order_mock
.reset_mock()
1756 self
.m
.report
.log_order
.reset_mock()
1758 for i
in [10, 13, 16]:
1759 with self
.subTest(tick
=i
):
1760 trade
.update_order(order_mock
, i
)
1761 order_mock
.cancel
.assert_called()
1762 new_order_mock
.run
.assert_called()
1763 prepare_order
.assert_called_with(compute_value
="default")
1764 self
.m
.report
.log_order
.assert_called()
1765 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1767 mock
.call(order_mock
, i
, update
="market_adjust",
1768 compute_value
='default',
1769 new_order
=new_order_mock
),
1770 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1772 self
.m
.report
.log_order
.assert_has_calls(calls
)
1774 order_mock
.reset_mock()
1775 new_order_mock
.reset_mock()
1777 self
.m
.report
.log_order
.reset_mock()
1779 for i
in [8, 9, 11, 12]:
1780 with self
.subTest(tick
=i
):
1781 trade
.update_order(order_mock
, i
)
1782 order_mock
.cancel
.assert_not_called()
1783 new_order_mock
.run
.assert_not_called()
1784 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1785 compute_value
=None, new_order
=None)
1787 order_mock
.reset_mock()
1788 new_order_mock
.reset_mock()
1790 self
.m
.report
.log_order
.reset_mock()
1793 def test_print_with_order(self
):
1794 value_from
= portfolio
.Amount("BTC", "0.5")
1795 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1796 value_to
= portfolio
.Amount("BTC", "1.0")
1797 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1799 order_mock1
= mock
.Mock()
1800 order_mock1
.__repr__
= mock
.Mock()
1801 order_mock1
.__repr__
.return_value
= "Mock 1"
1802 order_mock2
= mock
.Mock()
1803 order_mock2
.__repr__
= mock
.Mock()
1804 order_mock2
.__repr__
.return_value
= "Mock 2"
1805 order_mock1
.mouvements
= []
1806 mouvement_mock1
= mock
.Mock()
1807 mouvement_mock1
.__repr__
= mock
.Mock()
1808 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1809 mouvement_mock2
= mock
.Mock()
1810 mouvement_mock2
.__repr__
= mock
.Mock()
1811 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1812 order_mock2
.mouvements
= [
1813 mouvement_mock1
, mouvement_mock2
1815 trade
.orders
.append(order_mock1
)
1816 trade
.orders
.append(order_mock2
)
1818 trade
.print_with_order()
1820 self
.m
.report
.print_log
.assert_called()
1821 calls
= self
.m
.report
.print_log
.mock_calls
1822 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1823 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1824 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1825 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1826 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1828 def test__repr(self
):
1829 value_from
= portfolio
.Amount("BTC", "0.5")
1830 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1831 value_to
= portfolio
.Amount("BTC", "1.0")
1832 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1834 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1836 def test_as_json(self
):
1837 value_from
= portfolio
.Amount("BTC", "0.5")
1838 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1839 value_to
= portfolio
.Amount("BTC", "1.0")
1840 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1842 as_json
= trade
.as_json()
1843 self
.assertEqual("acquire", as_json
["action"])
1844 self
.assertEqual(D("0.5"), as_json
["from"])
1845 self
.assertEqual(D("1.0"), as_json
["to"])
1846 self
.assertEqual("ETH", as_json
["currency"])
1847 self
.assertEqual("BTC", as_json
["base_currency"])
1849 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1850 class OrderTest(WebMockTestCase
):
1851 def test_values(self
):
1852 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1853 D("0.1"), "BTC", "long", "market", "trade")
1854 self
.assertEqual("buy", order
.action
)
1855 self
.assertEqual(10, order
.amount
.value
)
1856 self
.assertEqual("ETH", order
.amount
.currency
)
1857 self
.assertEqual(D("0.1"), order
.rate
)
1858 self
.assertEqual("BTC", order
.base_currency
)
1859 self
.assertEqual("market", order
.market
)
1860 self
.assertEqual("long", order
.trade_type
)
1861 self
.assertEqual("pending", order
.status
)
1862 self
.assertEqual("trade", order
.trade
)
1863 self
.assertIsNone(order
.id)
1864 self
.assertFalse(order
.close_if_possible
)
1866 def test__repr(self
):
1867 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1868 D("0.1"), "BTC", "long", "market", "trade")
1869 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1871 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1872 D("0.1"), "BTC", "long", "market", "trade",
1873 close_if_possible
=True)
1874 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1876 def test_as_json(self
):
1877 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1878 D("0.1"), "BTC", "long", "market", "trade")
1879 mouvement_mock1
= mock
.Mock()
1880 mouvement_mock1
.as_json
.return_value
= 1
1881 mouvement_mock2
= mock
.Mock()
1882 mouvement_mock2
.as_json
.return_value
= 2
1884 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1885 as_json
= order
.as_json()
1886 self
.assertEqual("buy", as_json
["action"])
1887 self
.assertEqual("long", as_json
["trade_type"])
1888 self
.assertEqual(10, as_json
["amount"])
1889 self
.assertEqual("ETH", as_json
["currency"])
1890 self
.assertEqual("BTC", as_json
["base_currency"])
1891 self
.assertEqual(D("0.1"), as_json
["rate"])
1892 self
.assertEqual("pending", as_json
["status"])
1893 self
.assertEqual(False, as_json
["close_if_possible"])
1894 self
.assertIsNone(as_json
["id"])
1895 self
.assertEqual([1, 2], as_json
["mouvements"])
1897 def test_account(self
):
1898 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1899 D("0.1"), "BTC", "long", "market", "trade")
1900 self
.assertEqual("exchange", order
.account
)
1902 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1903 D("0.1"), "BTC", "short", "market", "trade")
1904 self
.assertEqual("margin", order
.account
)
1906 def test_pending(self
):
1907 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1908 D("0.1"), "BTC", "long", "market", "trade")
1909 self
.assertTrue(order
.pending
)
1910 order
.status
= "open"
1911 self
.assertFalse(order
.pending
)
1913 def test_open(self
):
1914 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1915 D("0.1"), "BTC", "long", "market", "trade")
1916 self
.assertFalse(order
.open)
1917 order
.status
= "open"
1918 self
.assertTrue(order
.open)
1920 def test_finished(self
):
1921 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1922 D("0.1"), "BTC", "long", "market", "trade")
1923 self
.assertFalse(order
.finished
)
1924 order
.status
= "closed"
1925 self
.assertTrue(order
.finished
)
1926 order
.status
= "canceled"
1927 self
.assertTrue(order
.finished
)
1928 order
.status
= "error"
1929 self
.assertTrue(order
.finished
)
1931 @mock.patch.object(portfolio
.Order
, "fetch")
1932 def test_cancel(self
, fetch
):
1934 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1935 D("0.1"), "BTC", "long", self
.m
, "trade")
1936 order
.status
= "open"
1939 self
.m
.ccxt
.cancel_order
.assert_not_called()
1940 self
.m
.report
.log_debug_action
.assert_called_once()
1941 self
.m
.report
.log_debug_action
.reset_mock()
1942 self
.assertEqual("canceled", order
.status
)
1944 self
.m
.debug
= False
1945 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1946 D("0.1"), "BTC", "long", self
.m
, "trade")
1947 order
.status
= "open"
1951 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1952 fetch
.assert_called_once_with()
1953 self
.m
.report
.log_debug_action
.assert_not_called()
1955 def test_dust_amount_remaining(self
):
1956 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1957 D("0.1"), "BTC", "long", self
.m
, "trade")
1958 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1959 self
.assertFalse(order
.dust_amount_remaining())
1961 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1962 self
.assertTrue(order
.dust_amount_remaining())
1964 @mock.patch.object(portfolio
.Order
, "fetch")
1965 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1966 def test_remaining_amount(self
, filled_amount
, fetch
):
1967 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1968 D("0.1"), "BTC", "long", self
.m
, "trade")
1970 self
.assertEqual(9, order
.remaining_amount().value
)
1972 order
.status
= "open"
1973 self
.assertEqual(9, order
.remaining_amount().value
)
1975 @mock.patch.object(portfolio
.Order
, "fetch")
1976 def test_filled_amount(self
, fetch
):
1977 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1978 D("0.1"), "BTC", "long", self
.m
, "trade")
1979 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1980 "tradeID": 42, "type": "buy", "fee": "0.0015",
1981 "date": "2017-12-30 12:00:12", "rate": "0.1",
1982 "amount": "3", "total": "0.3"
1984 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1985 "tradeID": 43, "type": "buy", "fee": "0.0015",
1986 "date": "2017-12-30 13:00:12", "rate": "0.2",
1987 "amount": "2", "total": "0.4"
1989 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1990 fetch
.assert_not_called()
1991 order
.status
= "open"
1992 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1993 fetch
.assert_called_once()
1994 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1996 def test_fetch_mouvements(self
):
1997 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
1999 "tradeID": 42, "type": "buy", "fee": "0.0015",
2000 "date": "2017-12-30 12:00:12", "rate": "0.1",
2001 "amount": "3", "total": "0.3"
2004 "tradeID": 43, "type": "buy", "fee": "0.0015",
2005 "date": "2017-12-30 13:00:12", "rate": "0.2",
2006 "amount": "2", "total": "0.4"
2009 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2010 D("0.1"), "BTC", "long", self
.m
, "trade")
2012 order
.mouvements
= ["Foo", "Bar", "Baz"]
2014 order
.fetch_mouvements()
2016 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
2017 self
.assertEqual(2, len(order
.mouvements
))
2018 self
.assertEqual(42, order
.mouvements
[0].id)
2019 self
.assertEqual(43, order
.mouvements
[1].id)
2021 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
2022 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2023 D("0.1"), "BTC", "long", self
.m
, "trade")
2024 order
.fetch_mouvements()
2025 self
.assertEqual(0, len(order
.mouvements
))
2027 def test_mark_finished_order(self
):
2028 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2029 D("0.1"), "BTC", "short", self
.m
, "trade",
2030 close_if_possible
=True)
2031 order
.status
= "closed"
2032 self
.m
.debug
= False
2034 order
.mark_finished_order()
2035 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
2036 self
.m
.ccxt
.close_margin_position
.reset_mock()
2038 order
.status
= "open"
2039 order
.mark_finished_order()
2040 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2042 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2043 D("0.1"), "BTC", "short", self
.m
, "trade",
2044 close_if_possible
=False)
2045 order
.status
= "closed"
2046 order
.mark_finished_order()
2047 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2049 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2050 D("0.1"), "BTC", "short", self
.m
, "trade",
2051 close_if_possible
=True)
2052 order
.status
= "closed"
2053 order
.mark_finished_order()
2054 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2056 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2057 D("0.1"), "BTC", "long", self
.m
, "trade",
2058 close_if_possible
=True)
2059 order
.status
= "closed"
2060 order
.mark_finished_order()
2061 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2065 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2066 D("0.1"), "BTC", "short", self
.m
, "trade",
2067 close_if_possible
=True)
2068 order
.status
= "closed"
2070 order
.mark_finished_order()
2071 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2072 self
.m
.report
.log_debug_action
.assert_called_once()
2074 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
2075 def test_fetch(self
, fetch_mouvements
):
2076 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2077 D("0.1"), "BTC", "long", self
.m
, "trade")
2079 with self
.subTest(debug
=True):
2082 self
.m
.report
.log_debug_action
.assert_called_once()
2083 self
.m
.report
.log_debug_action
.reset_mock()
2084 self
.m
.ccxt
.fetch_order
.assert_not_called()
2085 fetch_mouvements
.assert_not_called()
2087 with self
.subTest(debug
=False):
2088 self
.m
.debug
= False
2089 self
.m
.ccxt
.fetch_order
.return_value
= {
2091 "datetime": "timestamp"
2095 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
2096 fetch_mouvements
.assert_called_once()
2097 self
.assertEqual("foo", order
.status
)
2098 self
.assertEqual("timestamp", order
.timestamp
)
2099 self
.assertEqual(1, len(order
.results
))
2100 self
.m
.report
.log_debug_action
.assert_not_called()
2102 with self
.subTest(missing_order
=True):
2103 self
.m
.ccxt
.fetch_order
.side_effect
= [
2104 portfolio
.OrderNotCached
,
2107 self
.assertEqual("closed_unknown", order
.status
)
2109 @mock.patch.object(portfolio
.Order
, "fetch")
2110 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2111 def test_get_status(self
, mark_finished_order
, fetch
):
2112 with self
.subTest(debug
=True):
2114 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2115 D("0.1"), "BTC", "long", self
.m
, "trade")
2116 self
.assertEqual("pending", order
.get_status())
2117 fetch
.assert_not_called()
2118 self
.m
.report
.log_debug_action
.assert_called_once()
2120 with self
.subTest(debug
=False, finished
=False):
2121 self
.m
.debug
= False
2122 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2123 D("0.1"), "BTC", "long", self
.m
, "trade")
2125 def update_status():
2126 order
.status
= "open"
2127 return update_status
2128 fetch
.side_effect
= _fetch(order
)
2129 self
.assertEqual("open", order
.get_status())
2130 mark_finished_order
.assert_not_called()
2131 fetch
.assert_called_once()
2133 mark_finished_order
.reset_mock()
2135 with self
.subTest(debug
=False, finished
=True):
2136 self
.m
.debug
= False
2137 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2138 D("0.1"), "BTC", "long", self
.m
, "trade")
2140 def update_status():
2141 order
.status
= "closed"
2142 return update_status
2143 fetch
.side_effect
= _fetch(order
)
2144 self
.assertEqual("closed", order
.get_status())
2145 mark_finished_order
.assert_called_once()
2146 fetch
.assert_called_once()
2149 self
.m
.ccxt
.order_precision
.return_value
= 4
2150 with self
.subTest(debug
=True):
2152 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2153 D("0.1"), "BTC", "long", self
.m
, "trade")
2155 self
.m
.ccxt
.create_order
.assert_not_called()
2156 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2157 self
.assertEqual("open", order
.status
)
2158 self
.assertEqual(1, len(order
.results
))
2159 self
.assertEqual(-1, order
.id)
2161 self
.m
.ccxt
.create_order
.reset_mock()
2162 with self
.subTest(debug
=False):
2163 self
.m
.debug
= False
2164 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2165 D("0.1"), "BTC", "long", self
.m
, "trade")
2166 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2168 self
.m
.ccxt
.create_order
.assert_called_once()
2169 self
.assertEqual(1, len(order
.results
))
2170 self
.assertEqual("open", order
.status
)
2172 self
.m
.ccxt
.create_order
.reset_mock()
2173 with self
.subTest(exception
=True):
2174 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2175 D("0.1"), "BTC", "long", self
.m
, "trade")
2176 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2178 self
.m
.ccxt
.create_order
.assert_called_once()
2179 self
.assertEqual(0, len(order
.results
))
2180 self
.assertEqual("error", order
.status
)
2181 self
.m
.report
.log_error
.assert_called_once()
2183 self
.m
.ccxt
.create_order
.reset_mock()
2184 with self
.subTest(dust_amount_exception
=True),\
2185 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2186 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2187 D("0.1"), "BTC", "long", self
.m
, "trade")
2188 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2190 self
.m
.ccxt
.create_order
.assert_called_once()
2191 self
.assertEqual(0, len(order
.results
))
2192 self
.assertEqual("closed", order
.status
)
2193 mark_finished_order
.assert_called_once()
2195 self
.m
.ccxt
.order_precision
.return_value
= 8
2196 self
.m
.ccxt
.create_order
.reset_mock()
2197 with self
.subTest(insufficient_funds
=True),\
2198 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2199 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2200 D("0.1"), "BTC", "long", self
.m
, "trade")
2201 self
.m
.ccxt
.create_order
.side_effect
= [
2202 portfolio
.InsufficientFunds
,
2203 portfolio
.InsufficientFunds
,
2204 portfolio
.InsufficientFunds
,
2208 self
.m
.ccxt
.create_order
.assert_has_calls([
2209 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2210 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2211 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2212 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2214 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2215 self
.assertEqual(1, len(order
.results
))
2216 self
.assertEqual("open", order
.status
)
2217 self
.assertEqual(4, order
.tries
)
2218 self
.m
.report
.log_error
.assert_called()
2219 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2221 self
.m
.ccxt
.order_precision
.return_value
= 8
2222 self
.m
.ccxt
.create_order
.reset_mock()
2223 self
.m
.report
.log_error
.reset_mock()
2224 with self
.subTest(insufficient_funds
=True),\
2225 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2226 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2227 D("0.1"), "BTC", "long", self
.m
, "trade")
2228 self
.m
.ccxt
.create_order
.side_effect
= [
2229 portfolio
.InsufficientFunds
,
2230 portfolio
.InsufficientFunds
,
2231 portfolio
.InsufficientFunds
,
2232 portfolio
.InsufficientFunds
,
2233 portfolio
.InsufficientFunds
,
2236 self
.m
.ccxt
.create_order
.assert_has_calls([
2237 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2238 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2239 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2240 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2241 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2243 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2244 self
.assertEqual(0, len(order
.results
))
2245 self
.assertEqual("error", order
.status
)
2246 self
.assertEqual(5, order
.tries
)
2247 self
.m
.report
.log_error
.assert_called()
2248 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2249 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
)
2252 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2253 class MouvementTest(WebMockTestCase
):
2254 def test_values(self
):
2255 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2256 "tradeID": 42, "type": "buy", "fee": "0.0015",
2257 "date": "2017-12-30 12:00:12", "rate": "0.1",
2258 "amount": "10", "total": "1"
2260 self
.assertEqual("ETH", mouvement
.currency
)
2261 self
.assertEqual("BTC", mouvement
.base_currency
)
2262 self
.assertEqual(42, mouvement
.id)
2263 self
.assertEqual("buy", mouvement
.action
)
2264 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2265 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2266 self
.assertEqual(D("0.1"), mouvement
.rate
)
2267 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2268 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2270 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2271 self
.assertIsNone(mouvement
.date
)
2272 self
.assertIsNone(mouvement
.id)
2273 self
.assertIsNone(mouvement
.action
)
2274 self
.assertEqual(-1, mouvement
.fee_rate
)
2275 self
.assertEqual(0, mouvement
.rate
)
2276 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2277 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2279 def test__repr(self
):
2280 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2281 "tradeID": 42, "type": "buy", "fee": "0.0015",
2282 "date": "2017-12-30 12:00:12", "rate": "0.1",
2283 "amount": "10", "total": "1"
2285 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2287 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2288 "tradeID": 42, "type": "buy",
2289 "date": "garbage", "rate": "0.1",
2290 "amount": "10", "total": "1"
2292 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2294 def test_as_json(self
):
2295 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2296 "tradeID": 42, "type": "buy", "fee": "0.0015",
2297 "date": "2017-12-30 12:00:12", "rate": "0.1",
2298 "amount": "10", "total": "1"
2300 as_json
= mouvement
.as_json()
2302 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2303 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2304 self
.assertEqual("buy", as_json
["action"])
2305 self
.assertEqual(D("10"), as_json
["total"])
2306 self
.assertEqual(D("1"), as_json
["total_in_base"])
2307 self
.assertEqual("BTC", as_json
["base_currency"])
2308 self
.assertEqual("ETH", as_json
["currency"])
2310 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2311 class ReportStoreTest(WebMockTestCase
):
2312 def test_add_log(self
):
2313 report_store
= market
.ReportStore(self
.m
)
2314 report_store
.add_log({"foo": "bar"}
)
2316 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2318 def test_set_verbose(self
):
2319 report_store
= market
.ReportStore(self
.m
)
2320 with self
.subTest(verbose
=True):
2321 report_store
.set_verbose(True)
2322 self
.assertTrue(report_store
.verbose_print
)
2324 with self
.subTest(verbose
=False):
2325 report_store
.set_verbose(False)
2326 self
.assertFalse(report_store
.verbose_print
)
2328 def test_print_log(self
):
2329 report_store
= market
.ReportStore(self
.m
)
2330 with self
.subTest(verbose
=True),\
2331 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2332 report_store
.set_verbose(True)
2333 report_store
.print_log("Coucou")
2334 report_store
.print_log(portfolio
.Amount("BTC", 1))
2335 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2337 with self
.subTest(verbose
=False),\
2338 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2339 report_store
.set_verbose(False)
2340 report_store
.print_log("Coucou")
2341 report_store
.print_log(portfolio
.Amount("BTC", 1))
2342 self
.assertEqual(stdout_mock
.getvalue(), "")
2344 def test_to_json(self
):
2345 report_store
= market
.ReportStore(self
.m
)
2346 report_store
.logs
.append({"foo": "bar"}
)
2347 self
.assertEqual('[{"foo": "bar"}]', report_store
.to_json())
2348 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2349 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}]', report_store
.to_json())
2350 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2351 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}, {"amount": "1.00000000 BTC"}]', report_store
.to_json())
2353 @mock.patch.object(market
.ReportStore
, "print_log")
2354 @mock.patch.object(market
.ReportStore
, "add_log")
2355 def test_log_stage(self
, add_log
, print_log
):
2356 report_store
= market
.ReportStore(self
.m
)
2357 report_store
.log_stage("foo")
2358 print_log
.assert_has_calls([
2359 mock
.call("-----------"),
2360 mock
.call("[Stage] foo"),
2362 add_log
.assert_called_once_with({'type': 'stage', 'stage': 'foo'}
)
2364 @mock.patch.object(market
.ReportStore
, "print_log")
2365 @mock.patch.object(market
.ReportStore
, "add_log")
2366 def test_log_balances(self
, add_log
, print_log
):
2367 report_store
= market
.ReportStore(self
.m
)
2368 self
.m
.balances
.as_json
.return_value
= "json"
2369 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2371 report_store
.log_balances(tag
="tag")
2372 print_log
.assert_has_calls([
2373 mock
.call("[Balance]"),
2377 add_log
.assert_called_once_with({
2383 @mock.patch.object(market
.ReportStore
, "print_log")
2384 @mock.patch.object(market
.ReportStore
, "add_log")
2385 def test_log_tickers(self
, add_log
, print_log
):
2386 report_store
= market
.ReportStore(self
.m
)
2388 "BTC": portfolio
.Amount("BTC", 10),
2389 "ETH": portfolio
.Amount("BTC", D("0.3"))
2391 amounts
["ETH"].rate
= D("0.1")
2393 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2394 print_log
.assert_not_called()
2395 add_log
.assert_called_once_with({
2397 'compute_value': 'default',
2398 'balance_type': 'total',
2411 add_log
.reset_mock()
2412 compute_value
= lambda x
: x
["bid"]
2413 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
2414 add_log
.assert_called_once_with({
2416 'compute_value': 'compute_value = lambda x: x["bid"]',
2417 'balance_type': 'total',
2430 @mock.patch.object(market
.ReportStore
, "print_log")
2431 @mock.patch.object(market
.ReportStore
, "add_log")
2432 def test_log_dispatch(self
, add_log
, print_log
):
2433 report_store
= market
.ReportStore(self
.m
)
2434 amount
= portfolio
.Amount("BTC", "10.3")
2436 "BTC": portfolio
.Amount("BTC", 10),
2437 "ETH": portfolio
.Amount("BTC", D("0.3"))
2439 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2440 print_log
.assert_not_called()
2441 add_log
.assert_called_once_with({
2443 'liquidity': 'medium',
2444 'repartition_ratio': 'repartition',
2455 @mock.patch.object(market
.ReportStore
, "print_log")
2456 @mock.patch.object(market
.ReportStore
, "add_log")
2457 def test_log_trades(self
, add_log
, print_log
):
2458 report_store
= market
.ReportStore(self
.m
)
2459 trade_mock1
= mock
.Mock()
2460 trade_mock2
= mock
.Mock()
2461 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2462 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2464 matching_and_trades
= [
2465 (True, trade_mock1
),
2466 (False, trade_mock2
),
2468 report_store
.log_trades(matching_and_trades
, "only")
2470 print_log
.assert_not_called()
2471 add_log
.assert_called_with({
2476 {'trade': '1', 'skipped': False}
,
2477 {'trade': '2', 'skipped': True}
2481 @mock.patch.object(market
.ReportStore
, "print_log")
2482 @mock.patch.object(market
.ReportStore
, "add_log")
2483 def test_log_orders(self
, add_log
, print_log
):
2484 report_store
= market
.ReportStore(self
.m
)
2486 order_mock1
= mock
.Mock()
2487 order_mock2
= mock
.Mock()
2489 order_mock1
.as_json
.return_value
= "order1"
2490 order_mock2
.as_json
.return_value
= "order2"
2492 orders
= [order_mock1
, order_mock2
]
2494 report_store
.log_orders(orders
, tick
="tick",
2495 only
="only", compute_value
="compute_value")
2497 print_log
.assert_called_once_with("[Orders]")
2498 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2500 add_log
.assert_called_with({
2503 'compute_value': 'compute_value',
2505 'orders': ['order1', 'order2']
2508 add_log
.reset_mock()
2509 def compute_value(x
, y
):
2511 report_store
.log_orders(orders
, tick
="tick",
2512 only
="only", compute_value
=compute_value
)
2513 add_log
.assert_called_with({
2516 'compute_value': 'def compute_value(x, y):\n return x[y]',
2518 'orders': ['order1', 'order2']
2522 @mock.patch.object(market
.ReportStore
, "print_log")
2523 @mock.patch.object(market
.ReportStore
, "add_log")
2524 def test_log_order(self
, add_log
, print_log
):
2525 report_store
= market
.ReportStore(self
.m
)
2526 order_mock
= mock
.Mock()
2527 order_mock
.as_json
.return_value
= "order"
2528 new_order_mock
= mock
.Mock()
2529 new_order_mock
.as_json
.return_value
= "new_order"
2530 order_mock
.__repr
__ = mock
.Mock()
2531 order_mock
.__repr
__.return_value
= "Order Mock"
2532 new_order_mock
.__repr
__ = mock
.Mock()
2533 new_order_mock
.__repr
__.return_value
= "New order Mock"
2535 with self
.subTest(finished
=True):
2536 report_store
.log_order(order_mock
, 1, finished
=True)
2537 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2538 add_log
.assert_called_once_with({
2543 'compute_value': None,
2547 add_log
.reset_mock()
2548 print_log
.reset_mock()
2550 with self
.subTest(update
="waiting"):
2551 report_store
.log_order(order_mock
, 1, update
="waiting")
2552 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2553 add_log
.assert_called_once_with({
2556 'update': 'waiting',
2558 'compute_value': None,
2562 add_log
.reset_mock()
2563 print_log
.reset_mock()
2564 with self
.subTest(update
="adjusting"):
2565 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
2566 report_store
.log_order(order_mock
, 3,
2567 update
="adjusting", new_order
=new_order_mock
,
2568 compute_value
=compute_value
)
2569 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2570 add_log
.assert_called_once_with({
2573 'update': 'adjusting',
2575 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
2576 'new_order': 'new_order'
2579 add_log
.reset_mock()
2580 print_log
.reset_mock()
2581 with self
.subTest(update
="market_fallback"):
2582 report_store
.log_order(order_mock
, 7,
2583 update
="market_fallback", new_order
=new_order_mock
)
2584 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2585 add_log
.assert_called_once_with({
2588 'update': 'market_fallback',
2590 'compute_value': None,
2591 'new_order': 'new_order'
2594 add_log
.reset_mock()
2595 print_log
.reset_mock()
2596 with self
.subTest(update
="market_adjusting"):
2597 report_store
.log_order(order_mock
, 17,
2598 update
="market_adjust", new_order
=new_order_mock
)
2599 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2600 add_log
.assert_called_once_with({
2603 'update': 'market_adjust',
2605 'compute_value': None,
2606 'new_order': 'new_order'
2609 @mock.patch.object(market
.ReportStore
, "print_log")
2610 @mock.patch.object(market
.ReportStore
, "add_log")
2611 def test_log_move_balances(self
, add_log
, print_log
):
2612 report_store
= market
.ReportStore(self
.m
)
2614 "BTC": portfolio
.Amount("BTC", 10),
2618 "BTC": portfolio
.Amount("BTC", 3),
2621 report_store
.log_move_balances(needed
, moving
)
2622 print_log
.assert_not_called()
2623 add_log
.assert_called_once_with({
2624 'type': 'move_balances',
2636 @mock.patch.object(market
.ReportStore
, "print_log")
2637 @mock.patch.object(market
.ReportStore
, "add_log")
2638 def test_log_http_request(self
, add_log
, print_log
):
2639 report_store
= market
.ReportStore(self
.m
)
2640 response
= mock
.Mock()
2641 response
.status_code
= 200
2642 response
.text
= "Hey"
2644 report_store
.log_http_request("method", "url", "body",
2645 "headers", response
)
2646 print_log
.assert_not_called()
2647 add_log
.assert_called_once_with({
2648 'type': 'http_request',
2652 'headers': 'headers',
2657 @mock.patch.object(market
.ReportStore
, "print_log")
2658 @mock.patch.object(market
.ReportStore
, "add_log")
2659 def test_log_error(self
, add_log
, print_log
):
2660 report_store
= market
.ReportStore(self
.m
)
2661 with self
.subTest(message
=None, exception
=None):
2662 report_store
.log_error("action")
2663 print_log
.assert_called_once_with("[Error] action")
2664 add_log
.assert_called_once_with({
2667 'exception_class': None,
2668 'exception_message': None,
2672 print_log
.reset_mock()
2673 add_log
.reset_mock()
2674 with self
.subTest(message
="Hey", exception
=None):
2675 report_store
.log_error("action", message
="Hey")
2676 print_log
.assert_has_calls([
2677 mock
.call("[Error] action"),
2680 add_log
.assert_called_once_with({
2683 'exception_class': None,
2684 'exception_message': None,
2688 print_log
.reset_mock()
2689 add_log
.reset_mock()
2690 with self
.subTest(message
=None, exception
=Exception("bouh")):
2691 report_store
.log_error("action", exception
=Exception("bouh"))
2692 print_log
.assert_has_calls([
2693 mock
.call("[Error] action"),
2694 mock
.call("\tException: bouh")
2696 add_log
.assert_called_once_with({
2699 'exception_class': "Exception",
2700 'exception_message': "bouh",
2704 print_log
.reset_mock()
2705 add_log
.reset_mock()
2706 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2707 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2708 print_log
.assert_has_calls([
2709 mock
.call("[Error] action"),
2710 mock
.call("\tException: bouh"),
2713 add_log
.assert_called_once_with({
2716 'exception_class': "Exception",
2717 'exception_message': "bouh",
2721 @mock.patch.object(market
.ReportStore
, "print_log")
2722 @mock.patch.object(market
.ReportStore
, "add_log")
2723 def test_log_debug_action(self
, add_log
, print_log
):
2724 report_store
= market
.ReportStore(self
.m
)
2725 report_store
.log_debug_action("Hey")
2727 print_log
.assert_called_once_with("[Debug] Hey")
2728 add_log
.assert_called_once_with({
2729 'type': 'debug_action',
2733 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2734 class HelperTest(WebMockTestCase
):
2735 def test_make_order(self
):
2736 self
.m
.get_ticker
.return_value
= {
2738 "average": D("0.1"),
2743 with self
.subTest(description
="nominal case"):
2744 helper
.make_order(self
.m
, 10, "ETH")
2746 self
.m
.report
.log_stage
.assert_has_calls([
2747 mock
.call("make_order_begin"),
2748 mock
.call("make_order_end"),
2750 self
.m
.balances
.fetch_balances
.assert_has_calls([
2751 mock
.call(tag
="make_order_begin"),
2752 mock
.call(tag
="make_order_end"),
2754 self
.m
.trades
.all
.append
.assert_called_once()
2755 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2756 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2757 self
.assertEqual(0, trade
.value_from
)
2758 self
.assertEqual("ETH", trade
.currency
)
2759 self
.assertEqual("BTC", trade
.base_currency
)
2760 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2761 self
.m
.trades
.run_orders
.assert_called_once_with()
2762 self
.m
.follow_orders
.assert_called_once_with()
2764 order
= trade
.orders
[0]
2765 self
.assertEqual(D("0.10"), order
.rate
)
2768 with self
.subTest(compute_value
="default"):
2769 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2770 compute_value
="ask")
2772 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2773 order
= trade
.orders
[0]
2774 self
.assertEqual(D("0.11"), order
.rate
)
2777 with self
.subTest(follow
=False):
2778 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2780 self
.m
.report
.log_stage
.assert_has_calls([
2781 mock
.call("make_order_begin"),
2782 mock
.call("make_order_end_not_followed"),
2784 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2786 self
.m
.trades
.all
.append
.assert_called_once()
2787 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2788 self
.assertEqual(0, trade
.value_from
)
2789 self
.assertEqual("ETH", trade
.currency
)
2790 self
.assertEqual("BTC", trade
.base_currency
)
2791 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2792 self
.m
.trades
.run_orders
.assert_called_once_with()
2793 self
.m
.follow_orders
.assert_not_called()
2794 self
.assertEqual(trade
.orders
[0], result
)
2797 with self
.subTest(base_currency
="USDT"):
2798 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2800 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2801 self
.assertEqual("BTC", trade
.currency
)
2802 self
.assertEqual("USDT", trade
.base_currency
)
2805 with self
.subTest(close_if_possible
=True):
2806 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2808 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2809 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2812 with self
.subTest(action
="dispose"):
2813 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2815 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2816 self
.assertEqual(0, trade
.value_to
)
2817 self
.assertEqual(1, trade
.value_from
.value
)
2818 self
.assertEqual("ETH", trade
.currency
)
2819 self
.assertEqual("BTC", trade
.base_currency
)
2822 with self
.subTest(compute_value
="default"):
2823 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2824 compute_value
="bid")
2826 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2827 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2829 def test_user_market(self
):
2830 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2831 mock
.patch("helper.main_parse_config") as main_parse_config
:
2832 with self
.subTest(debug
=False):
2833 main_parse_config
.return_value
= ["pg_config", "report_path"]
2834 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2835 m
= helper
.get_user_market("config_path.ini", 1)
2837 self
.assertIsInstance(m
, market
.Market
)
2838 self
.assertFalse(m
.debug
)
2840 with self
.subTest(debug
=True):
2841 main_parse_config
.return_value
= ["pg_config", "report_path"]
2842 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2843 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2845 self
.assertIsInstance(m
, market
.Market
)
2846 self
.assertTrue(m
.debug
)
2848 def test_main_store_report(self
):
2849 file_open
= mock
.mock_open()
2850 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2851 helper
.main_store_report(None, 1, self
.m
)
2852 file_open
.assert_not_called()
2854 file_open
= mock
.mock_open()
2855 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2856 mock
.patch
.object(helper
, "datetime") as time_mock
:
2857 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2858 self
.m
.report
.to_json
.return_value
= "json_content"
2860 helper
.main_store_report("present", 1, self
.m
)
2862 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2863 file_open().write
.assert_called_once_with("json_content")
2864 self
.m
.report
.to_json
.assert_called_once_with()
2866 with self
.subTest(file="error"),\
2867 mock
.patch("helper.open") as file_open
,\
2868 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2869 file_open
.side_effect
= FileNotFoundError
2871 helper
.main_store_report("error", 1, self
.m
)
2873 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2875 @mock.patch("helper.process_sell_all__1_all_sell")
2876 @mock.patch("helper.process_sell_all__2_all_buy")
2877 @mock.patch("portfolio.Portfolio.wait_for_recent")
2878 def test_main_process_market(self
, wait
, buy
, sell
):
2879 with self
.subTest(before
=False, after
=False):
2880 helper
.main_process_market("user", None)
2882 wait
.assert_not_called()
2883 buy
.assert_not_called()
2884 sell
.assert_not_called()
2889 with self
.subTest(before
=True, after
=False):
2890 helper
.main_process_market("user", None, before
=True)
2892 wait
.assert_not_called()
2893 buy
.assert_not_called()
2894 sell
.assert_called_once_with("user")
2899 with self
.subTest(before
=False, after
=True):
2900 helper
.main_process_market("user", None, after
=True)
2902 wait
.assert_called_once_with("user")
2903 buy
.assert_called_once_with("user")
2904 sell
.assert_not_called()
2909 with self
.subTest(before
=True, after
=True):
2910 helper
.main_process_market("user", None, before
=True, after
=True)
2912 wait
.assert_called_once_with("user")
2913 buy
.assert_called_once_with("user")
2914 sell
.assert_called_once_with("user")
2919 with self
.subTest(action
="print_balances"),\
2920 mock
.patch("helper.print_balances") as print_balances
:
2921 helper
.main_process_market("user", "print_balances")
2923 buy
.assert_not_called()
2924 wait
.assert_not_called()
2925 sell
.assert_not_called()
2926 print_balances
.assert_called_once_with("user")
2928 with self
.subTest(action
="print_orders"),\
2929 mock
.patch("helper.print_orders") as print_orders
:
2930 helper
.main_process_market("user", "print_orders")
2932 buy
.assert_not_called()
2933 wait
.assert_not_called()
2934 sell
.assert_not_called()
2935 print_orders
.assert_called_once_with("user")
2937 with self
.subTest(action
="unknown"),\
2938 self
.assertRaises(NotImplementedError):
2939 helper
.main_process_market("user", "unknown")
2941 @mock.patch.object(helper
, "psycopg2")
2942 def test_fetch_markets(self
, psycopg2
):
2943 connect_mock
= mock
.Mock()
2944 cursor_mock
= mock
.MagicMock()
2945 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2947 connect_mock
.cursor
.return_value
= cursor_mock
2948 psycopg2
.connect
.return_value
= connect_mock
2950 with self
.subTest(user
=None):
2951 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2953 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2954 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2956 self
.assertEqual(["row_1", "row_2"], rows
)
2958 psycopg2
.connect
.reset_mock()
2959 cursor_mock
.execute
.reset_mock()
2960 with self
.subTest(user
=1):
2961 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
2963 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2964 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
2966 self
.assertEqual(["row_1", "row_2"], rows
)
2968 @mock.patch.object(helper
.sys
, "exit")
2969 def test_main_parse_args(self
, exit
):
2970 with self
.subTest(config
="config.ini"):
2971 args
= helper
.main_parse_args([])
2972 self
.assertEqual("config.ini", args
.config
)
2973 self
.assertFalse(args
.before
)
2974 self
.assertFalse(args
.after
)
2975 self
.assertFalse(args
.debug
)
2977 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
2978 self
.assertTrue(args
.before
)
2979 self
.assertTrue(args
.after
)
2980 self
.assertTrue(args
.debug
)
2982 exit
.assert_not_called()
2984 with self
.subTest(config
="inexistant"),\
2985 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2986 args
= helper
.main_parse_args(["--config", "foo.bar"])
2987 exit
.assert_called_once_with(1)
2988 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
2990 @mock.patch.object(helper
.sys
, "exit")
2991 @mock.patch("helper.configparser")
2992 @mock.patch("helper.os")
2993 def test_main_parse_config(self
, os
, configparser
, exit
):
2994 with self
.subTest(pg_config
=True, report_path
=None):
2995 config_mock
= mock
.MagicMock()
2996 configparser
.ConfigParser
.return_value
= config_mock
2997 def config(element
):
2998 return element
== "postgresql"
3000 config_mock
.__contains
__.side_effect
= config
3001 config_mock
.__getitem
__.return_value
= "pg_config"
3003 result
= helper
.main_parse_config("configfile")
3005 config_mock
.read
.assert_called_with("configfile")
3007 self
.assertEqual(["pg_config", None], result
)
3009 with self
.subTest(pg_config
=True, report_path
="present"):
3010 config_mock
= mock
.MagicMock()
3011 configparser
.ConfigParser
.return_value
= config_mock
3013 config_mock
.__contains
__.return_value
= True
3014 config_mock
.__getitem
__.side_effect
= [
3015 {"report_path": "report_path"}
,
3016 {"report_path": "report_path"}
,
3020 os
.path
.exists
.return_value
= False
3021 result
= helper
.main_parse_config("configfile")
3023 config_mock
.read
.assert_called_with("configfile")
3024 self
.assertEqual(["pg_config", "report_path"], result
)
3025 os
.path
.exists
.assert_called_once_with("report_path")
3026 os
.makedirs
.assert_called_once_with("report_path")
3028 with self
.subTest(pg_config
=False),\
3029 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3030 config_mock
= mock
.MagicMock()
3031 configparser
.ConfigParser
.return_value
= config_mock
3032 result
= helper
.main_parse_config("configfile")
3034 config_mock
.read
.assert_called_with("configfile")
3035 exit
.assert_called_once_with(1)
3036 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
3039 def test_print_orders(self
):
3040 helper
.print_orders(self
.m
)
3042 self
.m
.report
.log_stage
.assert_called_with("print_orders")
3043 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
3044 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3045 compute_value
="average")
3046 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3048 def test_print_balances(self
):
3049 self
.m
.balances
.in_currency
.return_value
= {
3050 "BTC": portfolio
.Amount("BTC", "0.65"),
3051 "ETH": portfolio
.Amount("BTC", "0.3"),
3054 helper
.print_balances(self
.m
)
3056 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
3057 self
.m
.balances
.fetch_balances
.assert_called_with()
3058 self
.m
.report
.print_log
.assert_has_calls([
3059 mock
.call("total:"),
3060 mock
.call(portfolio
.Amount("BTC", "0.95")),
3063 def test_process_sell_needed__1_sell(self
):
3064 helper
.process_sell_needed__1_sell(self
.m
)
3066 self
.m
.balances
.fetch_balances
.assert_has_calls([
3067 mock
.call(tag
="process_sell_needed__1_sell_begin"),
3068 mock
.call(tag
="process_sell_needed__1_sell_end"),
3070 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3072 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3074 self
.m
.trades
.run_orders
.assert_called()
3075 self
.m
.follow_orders
.assert_called()
3076 self
.m
.report
.log_stage
.assert_has_calls([
3077 mock
.call("process_sell_needed__1_sell_begin"),
3078 mock
.call("process_sell_needed__1_sell_end")
3081 def test_process_sell_needed__2_buy(self
):
3082 helper
.process_sell_needed__2_buy(self
.m
)
3084 self
.m
.balances
.fetch_balances
.assert_has_calls([
3085 mock
.call(tag
="process_sell_needed__2_buy_begin"),
3086 mock
.call(tag
="process_sell_needed__2_buy_end"),
3088 self
.m
.update_trades
.assert_called_with(base_currency
="BTC",
3089 liquidity
="medium", only
="acquire")
3090 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3092 self
.m
.move_balances
.assert_called_with()
3093 self
.m
.trades
.run_orders
.assert_called()
3094 self
.m
.follow_orders
.assert_called()
3095 self
.m
.report
.log_stage
.assert_has_calls([
3096 mock
.call("process_sell_needed__2_buy_begin"),
3097 mock
.call("process_sell_needed__2_buy_end")
3100 def test_process_sell_all__1_sell(self
):
3101 helper
.process_sell_all__1_all_sell(self
.m
)
3103 self
.m
.balances
.fetch_balances
.assert_has_calls([
3104 mock
.call(tag
="process_sell_all__1_all_sell_begin"),
3105 mock
.call(tag
="process_sell_all__1_all_sell_end"),
3107 self
.m
.prepare_trades_to_sell_all
.assert_called_with(base_currency
="BTC")
3108 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3109 self
.m
.trades
.run_orders
.assert_called()
3110 self
.m
.follow_orders
.assert_called()
3111 self
.m
.report
.log_stage
.assert_has_calls([
3112 mock
.call("process_sell_all__1_all_sell_begin"),
3113 mock
.call("process_sell_all__1_all_sell_end")
3116 def test_process_sell_all__2_all_buy(self
):
3117 helper
.process_sell_all__2_all_buy(self
.m
)
3119 self
.m
.balances
.fetch_balances
.assert_has_calls([
3120 mock
.call(tag
="process_sell_all__2_all_buy_begin"),
3121 mock
.call(tag
="process_sell_all__2_all_buy_end"),
3123 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3125 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3126 self
.m
.move_balances
.assert_called_with()
3127 self
.m
.trades
.run_orders
.assert_called()
3128 self
.m
.follow_orders
.assert_called()
3129 self
.m
.report
.log_stage
.assert_has_calls([
3130 mock
.call("process_sell_all__2_all_buy_begin"),
3131 mock
.call("process_sell_all__2_all_buy_end")
3134 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3135 class AcceptanceTest(WebMockTestCase
):
3136 @unittest.expectedFailure
3137 def test_success_sell_only_necessary(self
):
3138 # FIXME: catch stdout
3139 self
.m
.report
.verbose_print
= False
3142 "exchange_free": D("1.0"),
3143 "exchange_used": D("0.0"),
3144 "exchange_total": D("1.0"),
3148 "exchange_free": D("4.0"),
3149 "exchange_used": D("0.0"),
3150 "exchange_total": D("4.0"),
3154 "exchange_free": D("1000.0"),
3155 "exchange_used": D("0.0"),
3156 "exchange_total": D("1000.0"),
3157 "total": D("1000.0"),
3161 "ETH": (D("0.25"), "long"),
3162 "ETC": (D("0.25"), "long"),
3163 "BTC": (D("0.4"), "long"),
3164 "BTD": (D("0.01"), "short"),
3165 "B2X": (D("0.04"), "long"),
3166 "USDT": (D("0.05"), "long"),
3169 def fetch_ticker(symbol
):
3170 if symbol
== "ETH/BTC":
3172 "symbol": "ETH/BTC",
3176 if symbol
== "ETC/BTC":
3178 "symbol": "ETC/BTC",
3182 if symbol
== "XVG/BTC":
3184 "symbol": "XVG/BTC",
3185 "bid": D("0.00003"),
3188 if symbol
== "BTD/BTC":
3190 "symbol": "BTD/BTC",
3194 if symbol
== "B2X/BTC":
3196 "symbol": "B2X/BTC",
3200 if symbol
== "USDT/BTC":
3201 raise helper
.ExchangeError
3202 if symbol
== "BTC/USDT":
3204 "symbol": "BTC/USDT",
3208 self
.fail("Shouldn't have been called with {}".format(symbol
))
3210 market
= mock
.Mock()
3211 market
.fetch_all_balances
.return_value
= fetch_balance
3212 market
.fetch_ticker
.side_effect
= fetch_ticker
3213 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3215 helper
.prepare_trades(market
)
3217 balances
= portfolio
.BalanceStore
.all
3218 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3219 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3220 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3223 trades
= portfolio
.TradeStore
.all
3224 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3225 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3226 self
.assertEqual("dispose", trades
[0].action
)
3228 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3229 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3230 self
.assertEqual("acquire", trades
[1].action
)
3232 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3233 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3234 self
.assertEqual("dispose", trades
[2].action
)
3236 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3237 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3238 self
.assertEqual("acquire", trades
[3].action
)
3240 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3241 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3242 self
.assertEqual("acquire", trades
[4].action
)
3244 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3245 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3246 self
.assertEqual("acquire", trades
[5].action
)
3249 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3251 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3252 self
.assertEqual(2, len(all_orders
))
3253 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3254 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3255 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3256 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3259 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3260 self
.assertEqual("limit", type)
3261 if symbol
== "ETH/BTC":
3262 self
.assertEqual("sell", action
)
3263 self
.assertEqual(D('0.66666666'), amount
)
3264 self
.assertEqual(D("0.14014"), price
)
3265 elif symbol
== "XVG/BTC":
3266 self
.assertEqual("sell", action
)
3267 self
.assertEqual(1000, amount
)
3268 self
.assertEqual(D("0.00003003"), price
)
3270 self
.fail("I shouldn't have been called")
3275 market
.create_order
.side_effect
= create_order
3276 market
.order_precision
.return_value
= 8
3279 portfolio
.TradeStore
.run_orders()
3281 self
.assertEqual("open", all_orders
[0].status
)
3282 self
.assertEqual("open", all_orders
[1].status
)
3284 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3285 market
.privatePostReturnOrderTrades
.return_value
= [
3287 "tradeID": 42, "type": "buy", "fee": "0.0015",
3288 "date": "2017-12-30 12:00:12", "rate": "0.1",
3289 "amount": "10", "total": "1"
3292 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3294 helper
.follow_orders(verbose
=False)
3296 sleep
.assert_called_with(30)
3298 for order
in all_orders
:
3299 self
.assertEqual("closed", order
.status
)
3303 "exchange_free": D("1.0") / 3,
3304 "exchange_used": D("0.0"),
3305 "exchange_total": D("1.0") / 3,
3307 "total": D("1.0") / 3,
3310 "exchange_free": D("0.134"),
3311 "exchange_used": D("0.0"),
3312 "exchange_total": D("0.134"),
3314 "total": D("0.134"),
3317 "exchange_free": D("4.0"),
3318 "exchange_used": D("0.0"),
3319 "exchange_total": D("4.0"),
3324 "exchange_free": D("0.0"),
3325 "exchange_used": D("0.0"),
3326 "exchange_total": D("0.0"),
3331 market
.fetch_all_balances
.return_value
= fetch_balance
3333 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3335 helper
.update_trades(market
, only
="acquire", compute_value
="average")
3337 balances
= portfolio
.BalanceStore
.all
3338 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3339 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3340 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3341 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3344 trades
= portfolio
.TradeStore
.all
3345 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3346 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3347 self
.assertEqual("dispose", trades
[0].action
)
3349 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3350 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3351 self
.assertEqual("acquire", trades
[1].action
)
3353 self
.assertNotIn("BTC", trades
)
3355 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3356 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3357 self
.assertEqual("dispose", trades
[2].action
)
3359 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3360 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3361 self
.assertEqual("acquire", trades
[3].action
)
3363 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3364 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3365 self
.assertEqual("acquire", trades
[4].action
)
3367 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3368 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3369 self
.assertEqual("acquire", trades
[5].action
)
3372 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3374 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3375 self
.assertEqual(4, len(all_orders
))
3376 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3377 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3378 self
.assertEqual("buy", all_orders
[0].action
)
3379 self
.assertEqual("long", all_orders
[0].trade_type
)
3381 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3382 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3383 self
.assertEqual("sell", all_orders
[1].action
)
3384 self
.assertEqual("short", all_orders
[1].trade_type
)
3386 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3387 self
.assertAlmostEqual(0, diff
.value
)
3388 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3389 self
.assertEqual("buy", all_orders
[2].action
)
3390 self
.assertEqual("long", all_orders
[2].trade_type
)
3392 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3393 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3394 self
.assertEqual("sell", all_orders
[3].action
)
3395 self
.assertEqual("long", all_orders
[3].trade_type
)
3399 # Move balances to margin
3403 # portfolio.TradeStore.run_orders()
3405 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3407 helper
.follow_orders(verbose
=False)
3409 sleep
.assert_called_with(30)
3411 if __name__
== '__main__':