5 from decimal
import Decimal
as D
6 from unittest
import mock
9 from io
import StringIO
10 import portfolio
, helper
, market
12 limits
= ["acceptance", "unit"]
13 for test_type
in limits
:
14 if "--no{}".format(test_type
) in sys
.argv
:
15 sys
.argv
.remove("--no{}".format(test_type
))
16 limits
.remove(test_type
)
17 if "--only{}".format(test_type
) in sys
.argv
:
18 sys
.argv
.remove("--only{}".format(test_type
))
22 class WebMockTestCase(unittest
.TestCase
):
26 super(WebMockTestCase
, self
).setUp()
27 self
.wm
= requests_mock
.Mocker()
31 self
.m
= mock
.Mock(name
="Market", spec
=market
.Market
)
35 mock
.patch
.multiple(portfolio
.Portfolio
, last_date
=None, data
=None, liquidities
={}),
36 mock
.patch
.multiple(portfolio
.Computation
,
37 computations
=portfolio
.Computation
.computations
),
39 for patcher
in self
.patchers
:
43 for patcher
in self
.patchers
:
46 super(WebMockTestCase
, self
).tearDown()
48 @unittest.skipUnless("unit" in limits
, "Unit skipped")
49 class poloniexETest(unittest
.TestCase
):
51 super(poloniexETest
, self
).setUp()
52 self
.wm
= requests_mock
.Mocker()
55 self
.s
= market
.ccxt
.poloniexE()
59 super(poloniexETest
, self
).tearDown()
61 def test_nanoseconds(self
):
62 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
63 time
.return_value
= 123456.7890123456
64 self
.assertEqual(123456789012345, self
.s
.nanoseconds())
67 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
68 time
.return_value
= 123456.7890123456
69 self
.assertEqual(123456789012345, self
.s
.nonce())
71 def test_order_precision(self
):
72 self
.assertEqual(8, self
.s
.order_precision("FOO"))
74 def test_transfer_balance(self
):
75 with self
.subTest(success
=True),\
76 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
77 t
.return_value
= { "success": 1 }
78 result
= self
.s
.transfer_balance("FOO", 12, "exchange", "margin")
79 t
.assert_called_once_with({
82 "fromAccount": "exchange",
83 "toAccount": "margin",
86 self
.assertTrue(result
)
88 with self
.subTest(success
=False),\
89 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
90 t
.return_value
= { "success": 0 }
91 self
.assertFalse(self
.s
.transfer_balance("FOO", 12, "exchange", "margin"))
93 def test_close_margin_position(self
):
94 with mock
.patch
.object(self
.s
, "privatePostCloseMarginPosition") as c
:
95 self
.s
.close_margin_position("FOO", "BAR")
96 c
.assert_called_with({"currencyPair": "BAR_FOO"}
)
98 def test_tradable_balances(self
):
99 with mock
.patch
.object(self
.s
, "privatePostReturnTradableBalances") as r
:
101 "FOO": { "exchange": "12.1234", "margin": "0.0123" }
,
102 "BAR": { "exchange": "1", "margin": "0" }
,
104 balances
= self
.s
.tradable_balances()
105 self
.assertEqual(["FOO", "BAR"], list(balances
.keys()))
106 self
.assertEqual(["exchange", "margin"], list(balances
["FOO"].keys()))
107 self
.assertEqual(D("12.1234"), balances
["FOO"]["exchange"])
108 self
.assertEqual(["exchange", "margin"], list(balances
["BAR"].keys()))
110 def test_margin_summary(self
):
111 with mock
.patch
.object(self
.s
, "privatePostReturnMarginAccountSummary") as r
:
113 "currentMargin": "1.49680968",
114 "lendingFees": "0.0000001",
116 "totalBorrowedValue": "0.00673602",
117 "totalValue": "0.01000000",
118 "netValue": "0.01008254",
121 'current_margin': D('1.49680968'),
122 'gains': D('0.00008254'),
123 'lending_fees': D('0.0000001'),
124 'total': D('0.01000000'),
125 'total_borrowed': D('0.00673602')
127 self
.assertEqual(expected
, self
.s
.margin_summary())
129 @unittest.skipUnless("unit" in limits
, "Unit skipped")
130 class PortfolioTest(WebMockTestCase
):
132 if self
.json_response
is not None:
133 portfolio
.Portfolio
.data
= self
.json_response
136 super(PortfolioTest
, self
).setUp()
138 with open("test_portfolio.json") as example
:
139 self
.json_response
= example
.read()
141 self
.wm
.get(portfolio
.Portfolio
.URL
, text
=self
.json_response
)
143 def test_get_cryptoportfolio(self
):
144 self
.wm
.get(portfolio
.Portfolio
.URL
, [
145 {"text":'{ "foo": "bar" }
', "status_code": 200},
146 {"text": "System Error", "status_code": 500},
147 {"exc": requests.exceptions.ConnectTimeout},
149 portfolio.Portfolio.get_cryptoportfolio(self.m)
150 self.assertIn("foo", portfolio.Portfolio.data)
151 self.assertEqual("bar", portfolio.Portfolio.data["foo"])
152 self.assertTrue(self.wm.called)
153 self.assertEqual(1, self.wm.call_count)
154 self.m.report.log_error.assert_not_called()
155 self.m.report.log_http_request.assert_called_once()
156 self.m.report.log_http_request.reset_mock()
158 portfolio.Portfolio.get_cryptoportfolio(self.m)
159 self.assertIsNone(portfolio.Portfolio.data)
160 self.assertEqual(2, self.wm.call_count)
161 self.m.report.log_error.assert_not_called()
162 self.m.report.log_http_request.assert_called_once()
163 self.m.report.log_http_request.reset_mock()
166 portfolio.Portfolio.data = "Foo"
167 portfolio.Portfolio.get_cryptoportfolio(self.m)
168 self.assertEqual("Foo", portfolio.Portfolio.data)
169 self.assertEqual(3, self.wm.call_count)
170 self.m.report.log_error.assert_called_once_with("get_cryptoportfolio",
172 self.m.report.log_http_request.assert_not_called()
174 def test_parse_cryptoportfolio(self):
175 portfolio.Portfolio.parse_cryptoportfolio(self.m)
177 self.assertListEqual(
179 list(portfolio.Portfolio.liquidities.keys()))
181 liquidities = portfolio.Portfolio.liquidities
182 self.assertEqual(10, len(liquidities["medium"].keys()))
183 self.assertEqual(10, len(liquidities["high"].keys()))
186 'BTC
': (D("0.2857"), "long"),
187 'DGB
': (D("0.1015"), "long"),
188 'DOGE
': (D("0.1805"), "long"),
189 'SC
': (D("0.0623"), "long"),
190 'ZEC
': (D("0.3701"), "long"),
192 date = portfolio.datetime(2018, 1, 8)
193 self.assertDictEqual(expected, liquidities["high"][date])
196 'BTC
': (D("1.1102e-16"), "long"),
197 'ETC
': (D("0.1"), "long"),
198 'FCT
': (D("0.1"), "long"),
199 'GAS
': (D("0.1"), "long"),
200 'NAV
': (D("0.1"), "long"),
201 'OMG
': (D("0.1"), "long"),
202 'OMNI
': (D("0.1"), "long"),
203 'PPC
': (D("0.1"), "long"),
204 'RIC
': (D("0.1"), "long"),
205 'VIA
': (D("0.1"), "long"),
206 'XCP
': (D("0.1"), "long"),
208 self.assertDictEqual(expected, liquidities["medium"][date])
209 self.assertEqual(portfolio.datetime(2018, 1, 15), portfolio.Portfolio.last_date)
211 self.m.report.log_http_request.assert_called_once_with("GET",
212 portfolio.Portfolio.URL, None, mock.ANY, mock.ANY)
213 self.m.report.log_http_request.reset_mock()
215 # It doesn't refetch the data when available
216 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
)
217 self
.m
.report
.log_http_request
.assert_not_called()
219 self
.assertEqual(1, self
.wm
.call_count
)
221 portfolio
.Portfolio
.parse_cryptoportfolio(self
.m
, refetch
=True)
222 self
.assertEqual(2, self
.wm
.call_count
)
223 self
.m
.report
.log_http_request
.assert_called_once()
225 def test_repartition(self
):
227 'BTC': (D("1.1102e-16"), "long"),
228 'USDT': (D("0.1"), "long"),
229 'ETC': (D("0.1"), "long"),
230 'FCT': (D("0.1"), "long"),
231 'OMG': (D("0.1"), "long"),
232 'STEEM': (D("0.1"), "long"),
233 'STRAT': (D("0.1"), "long"),
234 'XEM': (D("0.1"), "long"),
235 'XMR': (D("0.1"), "long"),
236 'XVC': (D("0.1"), "long"),
237 'ZRX': (D("0.1"), "long"),
240 'USDT': (D("0.1226"), "long"),
241 'BTC': (D("0.1429"), "long"),
242 'ETC': (D("0.1127"), "long"),
243 'ETH': (D("0.1569"), "long"),
244 'FCT': (D("0.3341"), "long"),
245 'GAS': (D("0.1308"), "long"),
248 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
))
249 self
.assertEqual(expected_medium
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="medium"))
250 self
.assertEqual(expected_high
, portfolio
.Portfolio
.repartition(self
.m
, liquidity
="high"))
252 self
.assertEqual(1, self
.wm
.call_count
)
254 portfolio
.Portfolio
.repartition(self
.m
)
255 self
.assertEqual(1, self
.wm
.call_count
)
257 portfolio
.Portfolio
.repartition(self
.m
, refetch
=True)
258 self
.assertEqual(2, self
.wm
.call_count
)
259 self
.m
.report
.log_http_request
.assert_called()
260 self
.assertEqual(2, self
.m
.report
.log_http_request
.call_count
)
262 @mock.patch.object(portfolio
.time
, "sleep")
263 @mock.patch.object(portfolio
.Portfolio
, "repartition")
264 def test_wait_for_recent(self
, repartition
, sleep
):
266 def _repartition(market
, refetch
):
267 self
.assertEqual(self
.m
, market
)
268 self
.assertTrue(refetch
)
270 portfolio
.Portfolio
.last_date
= portfolio
.datetime
.now()\
271 - portfolio
.timedelta(10)\
272 + portfolio
.timedelta(self
.call_count
)
273 repartition
.side_effect
= _repartition
275 portfolio
.Portfolio
.wait_for_recent(self
.m
)
276 sleep
.assert_called_with(30)
277 self
.assertEqual(6, sleep
.call_count
)
278 self
.assertEqual(7, repartition
.call_count
)
279 self
.m
.report
.print_log
.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
282 repartition
.reset_mock()
283 portfolio
.Portfolio
.last_date
= None
285 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=15)
286 sleep
.assert_not_called()
287 self
.assertEqual(1, repartition
.call_count
)
290 repartition
.reset_mock()
291 portfolio
.Portfolio
.last_date
= None
293 portfolio
.Portfolio
.wait_for_recent(self
.m
, delta
=1)
294 sleep
.assert_called_with(30)
295 self
.assertEqual(9, sleep
.call_count
)
296 self
.assertEqual(10, repartition
.call_count
)
298 @unittest.skipUnless("unit" in limits
, "Unit skipped")
299 class AmountTest(WebMockTestCase
):
300 def test_values(self
):
301 amount
= portfolio
.Amount("BTC", "0.65")
302 self
.assertEqual(D("0.65"), amount
.value
)
303 self
.assertEqual("BTC", amount
.currency
)
305 def test_in_currency(self
):
306 amount
= portfolio
.Amount("ETC", 10)
308 self
.assertEqual(amount
, amount
.in_currency("ETC", self
.m
))
310 with self
.subTest(desc
="no ticker for currency"):
311 self
.m
.get_ticker
.return_value
= None
313 self
.assertRaises(Exception, amount
.in_currency
, "ETH", self
.m
)
315 with self
.subTest(desc
="nominal case"):
316 self
.m
.get_ticker
.return_value
= {
322 converted_amount
= amount
.in_currency("ETH", self
.m
)
324 self
.assertEqual(D("3.0"), converted_amount
.value
)
325 self
.assertEqual("ETH", converted_amount
.currency
)
326 self
.assertEqual(amount
, converted_amount
.linked_to
)
327 self
.assertEqual("bar", converted_amount
.ticker
["foo"])
329 converted_amount
= amount
.in_currency("ETH", self
.m
, action
="bid", compute_value
="default")
330 self
.assertEqual(D("2"), converted_amount
.value
)
332 converted_amount
= amount
.in_currency("ETH", self
.m
, compute_value
="ask")
333 self
.assertEqual(D("4"), converted_amount
.value
)
335 converted_amount
= amount
.in_currency("ETH", self
.m
, rate
=D("0.02"))
336 self
.assertEqual(D("0.2"), converted_amount
.value
)
338 def test__round(self
):
339 amount
= portfolio
.Amount("BAR", portfolio
.D("1.23456789876"))
340 self
.assertEqual(D("1.23456789"), round(amount
).value
)
341 self
.assertEqual(D("1.23"), round(amount
, 2).value
)
344 amount
= portfolio
.Amount("SC", -120)
345 self
.assertEqual(120, abs(amount
).value
)
346 self
.assertEqual("SC", abs(amount
).currency
)
348 amount
= portfolio
.Amount("SC", 10)
349 self
.assertEqual(10, abs(amount
).value
)
350 self
.assertEqual("SC", abs(amount
).currency
)
353 amount1
= portfolio
.Amount("XVG", "12.9")
354 amount2
= portfolio
.Amount("XVG", "13.1")
356 self
.assertEqual(26, (amount1
+ amount2
).value
)
357 self
.assertEqual("XVG", (amount1
+ amount2
).currency
)
359 amount3
= portfolio
.Amount("ETH", "1.6")
360 with self
.assertRaises(Exception):
363 amount4
= portfolio
.Amount("ETH", 0.0)
364 self
.assertEqual(amount1
, amount1
+ amount4
)
366 self
.assertEqual(amount1
, amount1
+ 0)
368 def test__radd(self
):
369 amount
= portfolio
.Amount("XVG", "12.9")
371 self
.assertEqual(amount
, 0 + amount
)
372 with self
.assertRaises(Exception):
376 amount1
= portfolio
.Amount("XVG", "13.3")
377 amount2
= portfolio
.Amount("XVG", "13.1")
379 self
.assertEqual(D("0.2"), (amount1
- amount2
).value
)
380 self
.assertEqual("XVG", (amount1
- amount2
).currency
)
382 amount3
= portfolio
.Amount("ETH", "1.6")
383 with self
.assertRaises(Exception):
386 amount4
= portfolio
.Amount("ETH", 0.0)
387 self
.assertEqual(amount1
, amount1
- amount4
)
389 def test__rsub(self
):
390 amount
= portfolio
.Amount("ETH", "1.6")
391 with self
.assertRaises(Exception):
394 self
.assertEqual(portfolio
.Amount("ETH", "-1.6"), 0-amount
)
397 amount
= portfolio
.Amount("XEM", 11)
399 self
.assertEqual(D("38.5"), (amount
* D("3.5")).value
)
400 self
.assertEqual(D("33"), (amount
* 3).value
)
402 with self
.assertRaises(Exception):
405 def test__rmul(self
):
406 amount
= portfolio
.Amount("XEM", 11)
408 self
.assertEqual(D("38.5"), (D("3.5") * amount
).value
)
409 self
.assertEqual(D("33"), (3 * amount
).value
)
411 def test__floordiv(self
):
412 amount
= portfolio
.Amount("XEM", 11)
414 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
415 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
417 with self
.assertRaises(Exception):
420 def test__truediv(self
):
421 amount
= portfolio
.Amount("XEM", 11)
423 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
424 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
427 amount1
= portfolio
.Amount("BTD", 11.3)
428 amount2
= portfolio
.Amount("BTD", 13.1)
430 self
.assertTrue(amount1
< amount2
)
431 self
.assertFalse(amount2
< amount1
)
432 self
.assertFalse(amount1
< amount1
)
434 amount3
= portfolio
.Amount("BTC", 1.6)
435 with self
.assertRaises(Exception):
439 amount1
= portfolio
.Amount("BTD", 11.3)
440 amount2
= portfolio
.Amount("BTD", 13.1)
442 self
.assertTrue(amount1
<= amount2
)
443 self
.assertFalse(amount2
<= amount1
)
444 self
.assertTrue(amount1
<= amount1
)
446 amount3
= portfolio
.Amount("BTC", 1.6)
447 with self
.assertRaises(Exception):
451 amount1
= portfolio
.Amount("BTD", 11.3)
452 amount2
= portfolio
.Amount("BTD", 13.1)
454 self
.assertTrue(amount2
> amount1
)
455 self
.assertFalse(amount1
> amount2
)
456 self
.assertFalse(amount1
> amount1
)
458 amount3
= portfolio
.Amount("BTC", 1.6)
459 with self
.assertRaises(Exception):
463 amount1
= portfolio
.Amount("BTD", 11.3)
464 amount2
= portfolio
.Amount("BTD", 13.1)
466 self
.assertTrue(amount2
>= amount1
)
467 self
.assertFalse(amount1
>= amount2
)
468 self
.assertTrue(amount1
>= amount1
)
470 amount3
= portfolio
.Amount("BTC", 1.6)
471 with self
.assertRaises(Exception):
475 amount1
= portfolio
.Amount("BTD", 11.3)
476 amount2
= portfolio
.Amount("BTD", 13.1)
477 amount3
= portfolio
.Amount("BTD", 11.3)
479 self
.assertFalse(amount1
== amount2
)
480 self
.assertFalse(amount2
== amount1
)
481 self
.assertTrue(amount1
== amount3
)
482 self
.assertFalse(amount2
== 0)
484 amount4
= portfolio
.Amount("BTC", 1.6)
485 with self
.assertRaises(Exception):
488 amount5
= portfolio
.Amount("BTD", 0)
489 self
.assertTrue(amount5
== 0)
492 amount1
= portfolio
.Amount("BTD", 11.3)
493 amount2
= portfolio
.Amount("BTD", 13.1)
494 amount3
= portfolio
.Amount("BTD", 11.3)
496 self
.assertTrue(amount1
!= amount2
)
497 self
.assertTrue(amount2
!= amount1
)
498 self
.assertFalse(amount1
!= amount3
)
499 self
.assertTrue(amount2
!= 0)
501 amount4
= portfolio
.Amount("BTC", 1.6)
502 with self
.assertRaises(Exception):
505 amount5
= portfolio
.Amount("BTD", 0)
506 self
.assertFalse(amount5
!= 0)
509 amount1
= portfolio
.Amount("BTD", "11.3")
511 self
.assertEqual(portfolio
.D("-11.3"), (-amount1
).value
)
514 amount1
= portfolio
.Amount("BTX", 32)
515 self
.assertEqual("32.00000000 BTX", str(amount1
))
517 amount2
= portfolio
.Amount("USDT", 12000)
518 amount1
.linked_to
= amount2
519 self
.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1
))
521 def test__repr(self
):
522 amount1
= portfolio
.Amount("BTX", 32)
523 self
.assertEqual("Amount(32.00000000 BTX)", repr(amount1
))
525 amount2
= portfolio
.Amount("USDT", 12000)
526 amount1
.linked_to
= amount2
527 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1
))
529 amount3
= portfolio
.Amount("BTC", 0.1)
530 amount2
.linked_to
= amount3
531 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1
))
533 def test_as_json(self
):
534 amount
= portfolio
.Amount("BTX", 32)
535 self
.assertEqual({"currency": "BTX", "value": D("32")}
, amount
.as_json())
537 amount
= portfolio
.Amount("BTX", "1E-10")
538 self
.assertEqual({"currency": "BTX", "value": D("0")}
, amount
.as_json())
540 amount
= portfolio
.Amount("BTX", "1E-5")
541 self
.assertEqual({"currency": "BTX", "value": D("0.00001")}
, amount
.as_json())
542 self
.assertEqual("0.00001", str(amount
.as_json()["value"]))
544 @unittest.skipUnless("unit" in limits
, "Unit skipped")
545 class BalanceTest(WebMockTestCase
):
546 def test_values(self
):
547 balance
= portfolio
.Balance("BTC", {
548 "exchange_total": "0.65",
549 "exchange_free": "0.35",
550 "exchange_used": "0.30",
551 "margin_total": "-10",
552 "margin_borrowed": "10",
553 "margin_available": "0",
554 "margin_in_position": "0",
555 "margin_position_type": "short",
556 "margin_borrowed_base_currency": "USDT",
557 "margin_liquidation_price": "1.20",
558 "margin_pending_gain": "10",
559 "margin_lending_fees": "0.4",
560 "margin_borrowed_base_price": "0.15",
562 self
.assertEqual(portfolio
.D("0.65"), balance
.exchange_total
.value
)
563 self
.assertEqual(portfolio
.D("0.35"), balance
.exchange_free
.value
)
564 self
.assertEqual(portfolio
.D("0.30"), balance
.exchange_used
.value
)
565 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
566 self
.assertEqual("BTC", balance
.exchange_free
.currency
)
567 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
569 self
.assertEqual(portfolio
.D("-10"), balance
.margin_total
.value
)
570 self
.assertEqual(portfolio
.D("10"), balance
.margin_borrowed
.value
)
571 self
.assertEqual(portfolio
.D("0"), balance
.margin_available
.value
)
572 self
.assertEqual("BTC", balance
.margin_total
.currency
)
573 self
.assertEqual("BTC", balance
.margin_borrowed
.currency
)
574 self
.assertEqual("BTC", balance
.margin_available
.currency
)
576 self
.assertEqual("BTC", balance
.currency
)
578 self
.assertEqual(portfolio
.D("0.4"), balance
.margin_lending_fees
.value
)
579 self
.assertEqual("USDT", balance
.margin_lending_fees
.currency
)
581 def test__repr(self
):
582 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
583 repr(portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)))
584 balance
= portfolio
.Balance("BTX", { "exchange_total": 3,
585 "exchange_used": 1, "exchange_free": 2 })
586 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
588 balance
= portfolio
.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}
)
589 self
.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance
))
591 balance
= portfolio
.Balance("BTX", { "margin_total": 3,
592 "margin_in_position": 1, "margin_available": 2 })
593 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
595 balance
= portfolio
.Balance("BTX", { "margin_total": 2, "margin_available": 2 }
)
596 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance
))
598 balance
= portfolio
.Balance("BTX", { "margin_total": -3,
599 "margin_borrowed_base_price": D("0.1"),
600 "margin_borrowed_base_currency": "BTC",
601 "margin_lending_fees": D("0.002") })
602 self
.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance
))
604 balance
= portfolio
.Balance("BTX", { "margin_total": 1,
605 "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2})
606 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance
))
608 def test_as_json(self
):
609 balance
= portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)
610 as_json
= balance
.as_json()
611 self
.assertEqual(set(portfolio
.Balance
.base_keys
), set(as_json
.keys()))
612 self
.assertEqual(D(0), as_json
["total"])
613 self
.assertEqual(D(2), as_json
["exchange_total"])
614 self
.assertEqual(D(2), as_json
["exchange_free"])
615 self
.assertEqual(D(0), as_json
["exchange_used"])
616 self
.assertEqual(D(0), as_json
["margin_total"])
617 self
.assertEqual(D(0), as_json
["margin_available"])
618 self
.assertEqual(D(0), as_json
["margin_borrowed"])
620 @unittest.skipUnless("unit" in limits
, "Unit skipped")
621 class MarketTest(WebMockTestCase
):
623 super(MarketTest
, self
).setUp()
625 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
627 def test_values(self
):
628 m
= market
.Market(self
.ccxt
)
630 self
.assertEqual(self
.ccxt
, m
.ccxt
)
631 self
.assertFalse(m
.debug
)
632 self
.assertIsInstance(m
.report
, market
.ReportStore
)
633 self
.assertIsInstance(m
.trades
, market
.TradeStore
)
634 self
.assertIsInstance(m
.balances
, market
.BalanceStore
)
635 self
.assertEqual(m
, m
.report
.market
)
636 self
.assertEqual(m
, m
.trades
.market
)
637 self
.assertEqual(m
, m
.balances
.market
)
638 self
.assertEqual(m
, m
.ccxt
._market
)
640 m
= market
.Market(self
.ccxt
, debug
=True)
641 self
.assertTrue(m
.debug
)
643 m
= market
.Market(self
.ccxt
, debug
=False)
644 self
.assertFalse(m
.debug
)
646 @mock.patch("market.ccxt")
647 def test_from_config(self
, ccxt
):
648 with mock
.patch("market.ReportStore"):
649 ccxt
.poloniexE
.return_value
= self
.ccxt
650 self
.ccxt
.session
.request
.return_value
= "response"
652 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
)
654 self
.assertEqual(self
.ccxt
, m
.ccxt
)
656 self
.ccxt
.session
.request("GET", "URL", data
="data",
658 m
.report
.log_http_request
.assert_called_with('GET', 'URL', 'data',
659 'headers', 'response')
661 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, debug
=True)
662 self
.assertEqual(True, m
.debug
)
664 def test_get_tickers(self
):
665 self
.ccxt
.fetch_tickers
.side_effect
= [
670 m
= market
.Market(self
.ccxt
)
671 self
.assertEqual("tickers", m
.get_tickers())
672 self
.assertEqual("tickers", m
.get_tickers())
673 self
.ccxt
.fetch_tickers
.assert_called_once()
675 self
.assertIsNone(m
.get_tickers(refresh
=self
.time
.time()))
677 def test_get_ticker(self
):
678 with self
.subTest(get_tickers
=True):
679 self
.ccxt
.fetch_tickers
.return_value
= {
680 "ETH/ETC": { "bid": 1, "ask": 3 }
,
681 "XVG/ETH": { "bid": 10, "ask": 40 }
,
683 m
= market
.Market(self
.ccxt
)
685 ticker
= m
.get_ticker("ETH", "ETC")
686 self
.assertEqual(1, ticker
["bid"])
687 self
.assertEqual(3, ticker
["ask"])
688 self
.assertEqual(2, ticker
["average"])
689 self
.assertFalse(ticker
["inverted"])
691 ticker
= m
.get_ticker("ETH", "XVG")
692 self
.assertEqual(0.0625, ticker
["average"])
693 self
.assertTrue(ticker
["inverted"])
694 self
.assertIn("original", ticker
)
695 self
.assertEqual(10, ticker
["original"]["bid"])
696 self
.assertEqual(25, ticker
["original"]["average"])
698 ticker
= m
.get_ticker("XVG", "XMR")
699 self
.assertIsNone(ticker
)
701 with self
.subTest(get_tickers
=False):
702 self
.ccxt
.fetch_tickers
.return_value
= None
703 self
.ccxt
.fetch_ticker
.side_effect
= [
704 { "bid": 1, "ask": 3 }
,
705 market
.ExchangeError("foo"),
706 { "bid": 10, "ask": 40 }
,
707 market
.ExchangeError("foo"),
708 market
.ExchangeError("foo"),
711 m
= market
.Market(self
.ccxt
)
713 ticker
= m
.get_ticker("ETH", "ETC")
714 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
715 self
.assertEqual(1, ticker
["bid"])
716 self
.assertEqual(3, ticker
["ask"])
717 self
.assertEqual(2, ticker
["average"])
718 self
.assertFalse(ticker
["inverted"])
720 ticker
= m
.get_ticker("ETH", "XVG")
721 self
.assertEqual(0.0625, ticker
["average"])
722 self
.assertTrue(ticker
["inverted"])
723 self
.assertIn("original", ticker
)
724 self
.assertEqual(10, ticker
["original"]["bid"])
725 self
.assertEqual(25, ticker
["original"]["average"])
727 ticker
= m
.get_ticker("XVG", "XMR")
728 self
.assertIsNone(ticker
)
730 def test_fetch_fees(self
):
731 m
= market
.Market(self
.ccxt
)
732 self
.ccxt
.fetch_fees
.return_value
= "Foo"
733 self
.assertEqual("Foo", m
.fetch_fees())
734 self
.ccxt
.fetch_fees
.assert_called_once()
735 self
.ccxt
.reset_mock()
736 self
.assertEqual("Foo", m
.fetch_fees())
737 self
.ccxt
.fetch_fees
.assert_not_called()
739 @mock.patch.object(portfolio
.Portfolio
, "repartition")
740 @mock.patch.object(market
.Market
, "get_ticker")
741 @mock.patch.object(market
.TradeStore
, "compute_trades")
742 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
743 repartition
.return_value
= {
744 "XEM": (D("0.75"), "long"),
745 "BTC": (D("0.25"), "long"),
747 def _get_ticker(c1
, c2
):
748 if c1
== "USDT" and c2
== "BTC":
749 return { "average": D("0.0001") }
750 if c1
== "XVG" and c2
== "BTC":
751 return { "average": D("0.000001") }
752 if c1
== "XEM" and c2
== "BTC":
753 return { "average": D("0.001") }
754 self
.fail("Should be called with {}, {}".format(c1
, c2
))
755 get_ticker
.side_effect
= _get_ticker
757 with mock
.patch("market.ReportStore"):
758 m
= market
.Market(self
.ccxt
)
759 self
.ccxt
.fetch_all_balances
.return_value
= {
761 "exchange_free": D("10000.0"),
762 "exchange_used": D("0.0"),
763 "exchange_total": D("10000.0"),
764 "total": D("10000.0")
767 "exchange_free": D("10000.0"),
768 "exchange_used": D("0.0"),
769 "exchange_total": D("10000.0"),
770 "total": D("10000.0")
774 m
.balances
.fetch_balances(tag
="tag")
777 compute_trades
.assert_called()
779 call
= compute_trades
.call_args
780 self
.assertEqual(1, call
[0][0]["USDT"].value
)
781 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
782 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
783 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
784 m
.report
.log_stage
.assert_called_once_with("prepare_trades")
785 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
787 @mock.patch.object(portfolio
.Portfolio
, "repartition")
788 @mock.patch.object(market
.Market
, "get_ticker")
789 @mock.patch.object(market
.TradeStore
, "compute_trades")
790 def test_update_trades(self
, compute_trades
, get_ticker
, repartition
):
791 repartition
.return_value
= {
792 "XEM": (D("0.75"), "long"),
793 "BTC": (D("0.25"), "long"),
795 def _get_ticker(c1
, c2
):
796 if c1
== "USDT" and c2
== "BTC":
797 return { "average": D("0.0001") }
798 if c1
== "XVG" and c2
== "BTC":
799 return { "average": D("0.000001") }
800 if c1
== "XEM" and c2
== "BTC":
801 return { "average": D("0.001") }
802 self
.fail("Should be called with {}, {}".format(c1
, c2
))
803 get_ticker
.side_effect
= _get_ticker
805 with mock
.patch("market.ReportStore"):
806 m
= market
.Market(self
.ccxt
)
807 self
.ccxt
.fetch_all_balances
.return_value
= {
809 "exchange_free": D("10000.0"),
810 "exchange_used": D("0.0"),
811 "exchange_total": D("10000.0"),
812 "total": D("10000.0")
815 "exchange_free": D("10000.0"),
816 "exchange_used": D("0.0"),
817 "exchange_total": D("10000.0"),
818 "total": D("10000.0")
822 m
.balances
.fetch_balances(tag
="tag")
825 compute_trades
.assert_called()
827 call
= compute_trades
.call_args
828 self
.assertEqual(1, call
[0][0]["USDT"].value
)
829 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
830 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
831 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
832 m
.report
.log_stage
.assert_called_once_with("update_trades")
833 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
835 @mock.patch.object(portfolio
.Portfolio
, "repartition")
836 @mock.patch.object(market
.Market
, "get_ticker")
837 @mock.patch.object(market
.TradeStore
, "compute_trades")
838 def test_prepare_trades_to_sell_all(self
, compute_trades
, get_ticker
, repartition
):
839 def _get_ticker(c1
, c2
):
840 if c1
== "USDT" and c2
== "BTC":
841 return { "average": D("0.0001") }
842 if c1
== "XVG" and c2
== "BTC":
843 return { "average": D("0.000001") }
844 self
.fail("Should be called with {}, {}".format(c1
, c2
))
845 get_ticker
.side_effect
= _get_ticker
847 with mock
.patch("market.ReportStore"):
848 m
= market
.Market(self
.ccxt
)
849 self
.ccxt
.fetch_all_balances
.return_value
= {
851 "exchange_free": D("10000.0"),
852 "exchange_used": D("0.0"),
853 "exchange_total": D("10000.0"),
854 "total": D("10000.0")
857 "exchange_free": D("10000.0"),
858 "exchange_used": D("0.0"),
859 "exchange_total": D("10000.0"),
860 "total": D("10000.0")
864 m
.balances
.fetch_balances(tag
="tag")
866 m
.prepare_trades_to_sell_all()
868 repartition
.assert_not_called()
869 compute_trades
.assert_called()
871 call
= compute_trades
.call_args
872 self
.assertEqual(1, call
[0][0]["USDT"].value
)
873 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
874 self
.assertEqual(D("1.01"), call
[0][1]["BTC"].value
)
875 m
.report
.log_stage
.assert_called_once_with("prepare_trades_to_sell_all")
876 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
878 @mock.patch.object(portfolio
.time
, "sleep")
879 @mock.patch.object(market
.TradeStore
, "all_orders")
880 def test_follow_orders(self
, all_orders
, time_mock
):
881 for debug
, sleep
in [
882 (False, None), (True, None),
883 (False, 12), (True, 12)]:
884 with self
.subTest(sleep
=sleep
, debug
=debug
), \
885 mock
.patch("market.ReportStore"):
886 m
= market
.Market(self
.ccxt
, debug
=debug
)
888 order_mock1
= mock
.Mock()
889 order_mock2
= mock
.Mock()
890 order_mock3
= mock
.Mock()
891 all_orders
.side_effect
= [
892 [order_mock1
, order_mock2
],
893 [order_mock1
, order_mock2
],
895 [order_mock1
, order_mock3
],
896 [order_mock1
, order_mock3
],
898 [order_mock1
, order_mock3
],
899 [order_mock1
, order_mock3
],
904 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
905 order_mock2
.get_status
.side_effect
= ["open"]
906 order_mock3
.get_status
.side_effect
= ["open", "closed"]
908 order_mock1
.trade
= mock
.Mock()
909 order_mock2
.trade
= mock
.Mock()
910 order_mock3
.trade
= mock
.Mock()
912 m
.follow_orders(sleep
=sleep
)
914 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
915 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
916 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
917 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
919 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
920 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
921 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
923 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
924 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
925 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
926 m
.report
.log_stage
.assert_called()
928 mock
.call("follow_orders_begin"),
929 mock
.call("follow_orders_tick_1"),
930 mock
.call("follow_orders_tick_2"),
931 mock
.call("follow_orders_tick_3"),
932 mock
.call("follow_orders_end"),
934 m
.report
.log_stage
.assert_has_calls(calls
)
935 m
.report
.log_orders
.assert_called()
936 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
938 mock
.call([order_mock1
, order_mock2
], tick
=1),
939 mock
.call([order_mock1
, order_mock3
], tick
=2),
940 mock
.call([order_mock1
, order_mock3
], tick
=3),
942 m
.report
.log_orders
.assert_has_calls(calls
)
944 mock
.call(order_mock1
, 3, finished
=True),
945 mock
.call(order_mock3
, 3, finished
=True),
947 m
.report
.log_order
.assert_has_calls(calls
)
951 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
952 time_mock
.assert_called_with(7)
954 time_mock
.assert_called_with(30)
956 time_mock
.assert_called_with(sleep
)
958 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
959 def test_move_balance(self
, fetch_balances
):
960 for debug
in [True, False]:
961 with self
.subTest(debug
=debug
),\
962 mock
.patch("market.ReportStore"):
963 m
= market
.Market(self
.ccxt
, debug
=debug
)
965 value_from
= portfolio
.Amount("BTC", "1.0")
966 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
967 value_to
= portfolio
.Amount("BTC", "10.0")
968 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
970 value_from
= portfolio
.Amount("BTC", "0.0")
971 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
972 value_to
= portfolio
.Amount("BTC", "-3.0")
973 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
975 value_from
= portfolio
.Amount("USDT", "0.0")
976 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
977 value_to
= portfolio
.Amount("USDT", "-50.0")
978 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
980 m
.trades
.all
= [trade1
, trade2
, trade3
]
981 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
982 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
983 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
984 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
988 fetch_balances
.assert_called_with()
989 m
.report
.log_move_balances
.assert_called_once()
992 m
.report
.log_debug_action
.assert_called()
993 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
995 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
996 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
997 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
999 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1000 class TradeStoreTest(WebMockTestCase
):
1001 def test_compute_trades(self
):
1002 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
1005 "XMR": portfolio
.Amount("BTC", D("0.9")),
1006 "DASH": portfolio
.Amount("BTC", D("0.4")),
1007 "XVG": portfolio
.Amount("BTC", D("-0.5")),
1008 "BTC": portfolio
.Amount("BTC", D("0.5")),
1011 "DASH": portfolio
.Amount("BTC", D("0.5")),
1012 "XVG": portfolio
.Amount("BTC", D("0.1")),
1013 "BTC": portfolio
.Amount("BTC", D("0.4")),
1014 "ETH": portfolio
.Amount("BTC", D("0.3")),
1024 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
1025 trade_store
= market
.TradeStore(self
.m
)
1026 trade_if_matching
.side_effect
= side_effect
1028 trade_store
.compute_trades(values_in_base
,
1029 new_repartition
, only
="only")
1031 self
.assertEqual(5, trade_if_matching
.call_count
)
1032 self
.assertEqual(3, len(trade_store
.all
))
1033 self
.assertEqual([1, 4, 5], trade_store
.all
)
1034 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
1036 def test_trade_if_matching(self
):
1038 with self
.subTest(only
="nope"):
1039 trade_store
= market
.TradeStore(self
.m
)
1040 result
= trade_store
.trade_if_matching(
1041 portfolio
.Amount("BTC", D("0")),
1042 portfolio
.Amount("BTC", D("0.3")),
1044 self
.assertEqual(False, result
[0])
1045 self
.assertIsInstance(result
[1], portfolio
.Trade
)
1047 with self
.subTest(only
=None):
1048 trade_store
= market
.TradeStore(self
.m
)
1049 result
= trade_store
.trade_if_matching(
1050 portfolio
.Amount("BTC", D("0")),
1051 portfolio
.Amount("BTC", D("0.3")),
1053 self
.assertEqual(True, result
[0])
1055 with self
.subTest(only
="acquire"):
1056 trade_store
= market
.TradeStore(self
.m
)
1057 result
= trade_store
.trade_if_matching(
1058 portfolio
.Amount("BTC", D("0")),
1059 portfolio
.Amount("BTC", D("0.3")),
1060 "ETH", only
="acquire")
1061 self
.assertEqual(True, result
[0])
1063 with self
.subTest(only
="dispose"):
1064 trade_store
= market
.TradeStore(self
.m
)
1065 result
= trade_store
.trade_if_matching(
1066 portfolio
.Amount("BTC", D("0")),
1067 portfolio
.Amount("BTC", D("0.3")),
1068 "ETH", only
="dispose")
1069 self
.assertEqual(False, result
[0])
1071 def test_prepare_orders(self
):
1072 trade_store
= market
.TradeStore(self
.m
)
1074 trade_mock1
= mock
.Mock()
1075 trade_mock2
= mock
.Mock()
1076 trade_mock3
= mock
.Mock()
1078 trade_mock1
.prepare_order
.return_value
= 1
1079 trade_mock2
.prepare_order
.return_value
= 2
1080 trade_mock3
.prepare_order
.return_value
= 3
1082 trade_mock1
.is_fullfiled
= False
1083 trade_mock2
.is_fullfiled
= False
1084 trade_mock3
.is_fullfiled
= True
1086 trade_store
.all
.append(trade_mock1
)
1087 trade_store
.all
.append(trade_mock2
)
1088 trade_store
.all
.append(trade_mock3
)
1090 trade_store
.prepare_orders()
1091 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1092 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1093 trade_mock3
.prepare_order
.assert_not_called()
1094 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1096 self
.m
.report
.log_orders
.reset_mock()
1098 trade_store
.prepare_orders(compute_value
="bla")
1099 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1100 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1101 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1103 trade_mock1
.prepare_order
.reset_mock()
1104 trade_mock2
.prepare_order
.reset_mock()
1105 self
.m
.report
.log_orders
.reset_mock()
1107 trade_mock1
.action
= "foo"
1108 trade_mock2
.action
= "bar"
1109 trade_store
.prepare_orders(only
="bar")
1110 trade_mock1
.prepare_order
.assert_not_called()
1111 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1112 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1114 def test_print_all_with_order(self
):
1115 trade_mock1
= mock
.Mock()
1116 trade_mock2
= mock
.Mock()
1117 trade_mock3
= mock
.Mock()
1118 trade_store
= market
.TradeStore(self
.m
)
1119 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1121 trade_store
.print_all_with_order()
1123 trade_mock1
.print_with_order
.assert_called()
1124 trade_mock2
.print_with_order
.assert_called()
1125 trade_mock3
.print_with_order
.assert_called()
1127 def test_run_orders(self
):
1128 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1129 order_mock1
= mock
.Mock()
1130 order_mock2
= mock
.Mock()
1131 order_mock3
= mock
.Mock()
1132 trade_store
= market
.TradeStore(self
.m
)
1134 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1136 trade_store
.run_orders()
1138 all_orders
.assert_called_with(state
="pending")
1140 order_mock1
.run
.assert_called()
1141 order_mock2
.run
.assert_called()
1142 order_mock3
.run
.assert_called()
1144 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1145 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1148 def test_all_orders(self
):
1149 trade_mock1
= mock
.Mock()
1150 trade_mock2
= mock
.Mock()
1152 order_mock1
= mock
.Mock()
1153 order_mock2
= mock
.Mock()
1154 order_mock3
= mock
.Mock()
1156 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1157 trade_mock2
.orders
= [order_mock3
]
1159 order_mock1
.status
= "pending"
1160 order_mock2
.status
= "open"
1161 order_mock3
.status
= "open"
1163 trade_store
= market
.TradeStore(self
.m
)
1164 trade_store
.all
.append(trade_mock1
)
1165 trade_store
.all
.append(trade_mock2
)
1167 orders
= trade_store
.all_orders()
1168 self
.assertEqual(3, len(orders
))
1170 open_orders
= trade_store
.all_orders(state
="open")
1171 self
.assertEqual(2, len(open_orders
))
1172 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
1174 def test_update_all_orders_status(self
):
1175 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1176 order_mock1
= mock
.Mock()
1177 order_mock2
= mock
.Mock()
1178 order_mock3
= mock
.Mock()
1180 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1182 trade_store
= market
.TradeStore(self
.m
)
1184 trade_store
.update_all_orders_status()
1185 all_orders
.assert_called_with(state
="open")
1187 order_mock1
.get_status
.assert_called()
1188 order_mock2
.get_status
.assert_called()
1189 order_mock3
.get_status
.assert_called()
1191 def test_pending(self
):
1192 trade_mock1
= mock
.Mock()
1193 trade_mock1
.is_fullfiled
= False
1194 trade_mock2
= mock
.Mock()
1195 trade_mock2
.is_fullfiled
= False
1196 trade_mock3
= mock
.Mock()
1197 trade_mock3
.is_fullfiled
= True
1199 trade_store
= market
.TradeStore(self
.m
)
1201 trade_store
.all
.append(trade_mock1
)
1202 trade_store
.all
.append(trade_mock2
)
1203 trade_store
.all
.append(trade_mock3
)
1205 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
1207 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1208 class BalanceStoreTest(WebMockTestCase
):
1210 super(BalanceStoreTest
, self
).setUp()
1212 self
.fetch_balance
= {
1216 "exchange_total": 0,
1220 "exchange_free": D("6.0"),
1221 "exchange_used": D("1.2"),
1222 "exchange_total": D("7.2"),
1226 "exchange_free": 16,
1228 "exchange_total": 16,
1234 "exchange_total": 0,
1235 "margin_total": D("-1.0"),
1240 def test_in_currency(self
):
1241 self
.m
.get_ticker
.return_value
= {
1244 "average": D("0.1"),
1247 balance_store
= market
.BalanceStore(self
.m
)
1248 balance_store
.all
= {
1249 "BTC": portfolio
.Balance("BTC", {
1251 "exchange_total":"0.65",
1252 "exchange_free": "0.35",
1253 "exchange_used": "0.30"}),
1254 "ETH": portfolio
.Balance("ETH", {
1256 "exchange_total": 3,
1258 "exchange_used": 0}),
1261 amounts
= balance_store
.in_currency("BTC")
1262 self
.assertEqual("BTC", amounts
["ETH"].currency
)
1263 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1264 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
1265 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1267 self
.m
.report
.log_tickers
.reset_mock()
1269 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
1270 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
1271 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
1272 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1274 self
.m
.report
.log_tickers
.reset_mock()
1276 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
1277 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
1278 self
.assertEqual(0, amounts
["ETH"].value
)
1279 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
1280 "bid", "exchange_used")
1281 self
.m
.report
.log_tickers
.reset_mock()
1283 def test_fetch_balances(self
):
1284 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1286 balance_store
= market
.BalanceStore(self
.m
)
1288 balance_store
.fetch_balances()
1289 self
.assertNotIn("ETC", balance_store
.currencies())
1290 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
1292 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
1293 "exchange_total": "1", "exchange_free": "0",
1294 "exchange_used": "1" })
1295 balance_store
.fetch_balances(tag
="foo")
1296 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
1297 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
1298 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
1300 @mock.patch.object(portfolio
.Portfolio
, "repartition")
1301 def test_dispatch_assets(self
, repartition
):
1302 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
1304 balance_store
= market
.BalanceStore(self
.m
)
1305 balance_store
.fetch_balances()
1307 self
.assertNotIn("XEM", balance_store
.currencies())
1309 repartition_hash
= {
1310 "XEM": (D("0.75"), "long"),
1311 "BTC": (D("0.26"), "long"),
1312 "DASH": (D("0.10"), "short"),
1314 repartition
.return_value
= repartition_hash
1316 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
1317 repartition
.assert_called_with(self
.m
, liquidity
="medium")
1318 self
.assertIn("XEM", balance_store
.currencies())
1319 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
1320 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
1321 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
1322 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
1323 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
1324 "11.1"), amounts
, "medium", repartition_hash
)
1326 def test_currencies(self
):
1327 balance_store
= market
.BalanceStore(self
.m
)
1329 balance_store
.all
= {
1330 "BTC": portfolio
.Balance("BTC", {
1332 "exchange_total":"0.65",
1333 "exchange_free": "0.35",
1334 "exchange_used": "0.30"}),
1335 "ETH": portfolio
.Balance("ETH", {
1337 "exchange_total": 3,
1339 "exchange_used": 0}),
1341 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
1343 def test_as_json(self
):
1344 balance_mock1
= mock
.Mock()
1345 balance_mock1
.as_json
.return_value
= 1
1347 balance_mock2
= mock
.Mock()
1348 balance_mock2
.as_json
.return_value
= 2
1350 balance_store
= market
.BalanceStore(self
.m
)
1351 balance_store
.all
= {
1352 "BTC": balance_mock1
,
1353 "ETH": balance_mock2
,
1356 as_json
= balance_store
.as_json()
1357 self
.assertEqual(1, as_json
["BTC"])
1358 self
.assertEqual(2, as_json
["ETH"])
1361 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1362 class ComputationTest(WebMockTestCase
):
1363 def test_compute_value(self
):
1364 compute
= mock
.Mock()
1365 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
1366 compute
.assert_called_with("foo", "ask")
1368 compute
.reset_mock()
1369 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
1370 compute
.assert_called_with("foo", "bid")
1372 compute
.reset_mock()
1373 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
1374 compute
.assert_called_with("foo", "ask")
1376 compute
.reset_mock()
1377 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
1378 compute
.assert_called_with("foo", "bid")
1380 compute
.reset_mock()
1381 portfolio
.Computation
.computations
["test"] = compute
1382 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
1383 compute
.assert_called_with("foo", "bid")
1386 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1387 class TradeTest(WebMockTestCase
):
1389 def test_values_assertion(self
):
1390 value_from
= portfolio
.Amount("BTC", "1.0")
1391 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1392 value_to
= portfolio
.Amount("BTC", "1.0")
1393 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1394 self
.assertEqual("BTC", trade
.base_currency
)
1395 self
.assertEqual("ETH", trade
.currency
)
1396 self
.assertEqual(self
.m
, trade
.market
)
1398 with self
.assertRaises(AssertionError):
1399 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
1400 with self
.assertRaises(AssertionError):
1401 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
1402 with self
.assertRaises(AssertionError):
1403 value_from
.currency
= "ETH"
1404 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1405 value_from
.currency
= "BTC"
1406 with self
.assertRaises(AssertionError):
1407 value_from2
= portfolio
.Amount("BTC", "1.0")
1408 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
1410 value_from
= portfolio
.Amount("BTC", 0)
1411 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1412 self
.assertEqual(0, trade
.value_from
.linked_to
)
1414 def test_action(self
):
1415 value_from
= portfolio
.Amount("BTC", "1.0")
1416 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1417 value_to
= portfolio
.Amount("BTC", "1.0")
1418 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1420 self
.assertIsNone(trade
.action
)
1422 value_from
= portfolio
.Amount("BTC", "1.0")
1423 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
1424 value_to
= portfolio
.Amount("BTC", "2.0")
1425 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
1427 self
.assertIsNone(trade
.action
)
1429 value_from
= portfolio
.Amount("BTC", "0.5")
1430 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1431 value_to
= portfolio
.Amount("BTC", "1.0")
1432 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1434 self
.assertEqual("acquire", trade
.action
)
1436 value_from
= portfolio
.Amount("BTC", "0")
1437 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1438 value_to
= portfolio
.Amount("BTC", "-1.0")
1439 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1441 self
.assertEqual("acquire", trade
.action
)
1443 def test_order_action(self
):
1444 value_from
= portfolio
.Amount("BTC", "0.5")
1445 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1446 value_to
= portfolio
.Amount("BTC", "1.0")
1447 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1449 self
.assertEqual("buy", trade
.order_action(False))
1450 self
.assertEqual("sell", trade
.order_action(True))
1452 value_from
= portfolio
.Amount("BTC", "0")
1453 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1454 value_to
= portfolio
.Amount("BTC", "-1.0")
1455 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1457 self
.assertEqual("sell", trade
.order_action(False))
1458 self
.assertEqual("buy", trade
.order_action(True))
1460 def test_trade_type(self
):
1461 value_from
= portfolio
.Amount("BTC", "0.5")
1462 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1463 value_to
= portfolio
.Amount("BTC", "1.0")
1464 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1466 self
.assertEqual("long", trade
.trade_type
)
1468 value_from
= portfolio
.Amount("BTC", "0")
1469 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
1470 value_to
= portfolio
.Amount("BTC", "-1.0")
1471 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1473 self
.assertEqual("short", trade
.trade_type
)
1475 def test_is_fullfiled(self
):
1476 value_from
= portfolio
.Amount("BTC", "0.5")
1477 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1478 value_to
= portfolio
.Amount("BTC", "1.0")
1479 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1481 order1
= mock
.Mock()
1482 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
1484 order2
= mock
.Mock()
1485 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
1486 trade
.orders
.append(order1
)
1487 trade
.orders
.append(order2
)
1489 self
.assertFalse(trade
.is_fullfiled
)
1491 order3
= mock
.Mock()
1492 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
1493 trade
.orders
.append(order3
)
1495 self
.assertTrue(trade
.is_fullfiled
)
1497 def test_filled_amount(self
):
1498 value_from
= portfolio
.Amount("BTC", "0.5")
1499 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1500 value_to
= portfolio
.Amount("BTC", "1.0")
1501 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1503 order1
= mock
.Mock()
1504 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
1506 order2
= mock
.Mock()
1507 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
1508 trade
.orders
.append(order1
)
1509 trade
.orders
.append(order2
)
1511 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
1512 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1513 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1515 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
1516 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
1517 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
1519 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
1520 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
1521 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
1523 @mock.patch.object(portfolio
.Computation
, "compute_value")
1524 @mock.patch.object(portfolio
.Trade
, "filled_amount")
1525 @mock.patch.object(portfolio
, "Order")
1526 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
1527 Order
.return_value
= "Order"
1529 with self
.subTest(desc
="Nothing to do"):
1530 value_from
= portfolio
.Amount("BTC", "10")
1531 value_from
.rate
= D("0.1")
1532 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1533 value_to
= portfolio
.Amount("BTC", "10")
1534 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1536 trade
.prepare_order()
1538 filled_amount
.assert_not_called()
1539 compute_value
.assert_not_called()
1540 self
.assertEqual(0, len(trade
.orders
))
1541 Order
.assert_not_called()
1543 self
.m
.get_ticker
.return_value
= { "inverted": False }
1544 with self
.subTest(desc
="Already filled"):
1545 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
1546 compute_value
.return_value
= D("0.125")
1548 value_from
= portfolio
.Amount("BTC", "10")
1549 value_from
.rate
= D("0.1")
1550 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1551 value_to
= portfolio
.Amount("BTC", "0")
1552 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1554 trade
.prepare_order()
1556 filled_amount
.assert_called_with(in_base_currency
=False)
1557 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1558 self
.assertEqual(0, len(trade
.orders
))
1559 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
1560 Order
.assert_not_called()
1562 with self
.subTest(action
="dispose", inverted
=False):
1563 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1564 compute_value
.return_value
= D("0.125")
1566 value_from
= portfolio
.Amount("BTC", "10")
1567 value_from
.rate
= D("0.1")
1568 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1569 value_to
= portfolio
.Amount("BTC", "1")
1570 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1572 trade
.prepare_order()
1574 filled_amount
.assert_called_with(in_base_currency
=False)
1575 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1576 self
.assertEqual(1, len(trade
.orders
))
1577 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1578 D("0.125"), "BTC", "long", self
.m
,
1579 trade
, close_if_possible
=False)
1581 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
1582 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
1583 compute_value
.return_value
= D("0.125")
1585 value_from
= portfolio
.Amount("BTC", "10")
1586 value_from
.rate
= D("0.1")
1587 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1588 value_to
= portfolio
.Amount("BTC", "1")
1589 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1591 trade
.prepare_order(close_if_possible
=True)
1593 filled_amount
.assert_called_with(in_base_currency
=False)
1594 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1595 self
.assertEqual(1, len(trade
.orders
))
1596 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
1597 D("0.125"), "BTC", "long", self
.m
,
1598 trade
, close_if_possible
=True)
1600 with self
.subTest(action
="acquire", inverted
=False):
1601 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
1602 compute_value
.return_value
= D("0.125")
1604 value_from
= portfolio
.Amount("BTC", "1")
1605 value_from
.rate
= D("0.1")
1606 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
1607 value_to
= portfolio
.Amount("BTC", "10")
1608 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1610 trade
.prepare_order()
1612 filled_amount
.assert_called_with(in_base_currency
=True)
1613 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
1614 self
.assertEqual(1, len(trade
.orders
))
1616 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
1617 D("0.125"), "BTC", "long", self
.m
,
1618 trade
, close_if_possible
=False)
1620 with self
.subTest(close_if_possible
=True):
1621 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
1622 compute_value
.return_value
= D("0.125")
1624 value_from
= portfolio
.Amount("BTC", "10")
1625 value_from
.rate
= D("0.1")
1626 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1627 value_to
= portfolio
.Amount("BTC", "0")
1628 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1630 trade
.prepare_order()
1632 filled_amount
.assert_called_with(in_base_currency
=False)
1633 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
1634 self
.assertEqual(1, len(trade
.orders
))
1635 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
1636 D("0.125"), "BTC", "long", self
.m
,
1637 trade
, close_if_possible
=True)
1639 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
1640 with self
.subTest(action
="dispose", inverted
=True):
1641 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
1642 compute_value
.return_value
= D("125")
1644 value_from
= portfolio
.Amount("BTC", "10")
1645 value_from
.rate
= D("0.01")
1646 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
1647 value_to
= portfolio
.Amount("BTC", "1")
1648 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1650 trade
.prepare_order(compute_value
="foo")
1652 filled_amount
.assert_called_with(in_base_currency
=True)
1653 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
1654 self
.assertEqual(1, len(trade
.orders
))
1655 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
1656 D("125"), "FOO", "long", self
.m
,
1657 trade
, close_if_possible
=False)
1659 with self
.subTest(action
="acquire", inverted
=True):
1660 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
1661 compute_value
.return_value
= D("125")
1663 value_from
= portfolio
.Amount("BTC", "1")
1664 value_from
.rate
= D("0.01")
1665 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
1666 value_to
= portfolio
.Amount("BTC", "10")
1667 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
1669 trade
.prepare_order(compute_value
="foo")
1671 filled_amount
.assert_called_with(in_base_currency
=False)
1672 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
1673 self
.assertEqual(1, len(trade
.orders
))
1674 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
1675 D("125"), "FOO", "long", self
.m
,
1676 trade
, close_if_possible
=False)
1679 @mock.patch.object(portfolio
.Trade
, "prepare_order")
1680 def test_update_order(self
, prepare_order
):
1681 order_mock
= mock
.Mock()
1682 new_order_mock
= mock
.Mock()
1684 value_from
= portfolio
.Amount("BTC", "0.5")
1685 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1686 value_to
= portfolio
.Amount("BTC", "1.0")
1687 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1688 prepare_order
.return_value
= new_order_mock
1690 for i
in [0, 1, 3, 4, 6]:
1691 with self
.subTest(tick
=i
):
1692 trade
.update_order(order_mock
, i
)
1693 order_mock
.cancel
.assert_not_called()
1694 new_order_mock
.run
.assert_not_called()
1695 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
1696 update
="waiting", compute_value
=None, new_order
=None)
1698 order_mock
.reset_mock()
1699 new_order_mock
.reset_mock()
1701 self
.m
.report
.log_order
.reset_mock()
1703 trade
.update_order(order_mock
, 2)
1704 order_mock
.cancel
.assert_called()
1705 new_order_mock
.run
.assert_called()
1706 prepare_order
.assert_called()
1707 self
.m
.report
.log_order
.assert_called()
1708 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1710 mock
.call(order_mock
, 2, update
="adjusting",
1711 compute_value
=mock
.ANY
,
1712 new_order
=new_order_mock
),
1713 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
1715 self
.m
.report
.log_order
.assert_has_calls(calls
)
1717 order_mock
.reset_mock()
1718 new_order_mock
.reset_mock()
1720 self
.m
.report
.log_order
.reset_mock()
1722 trade
.update_order(order_mock
, 5)
1723 order_mock
.cancel
.assert_called()
1724 new_order_mock
.run
.assert_called()
1725 prepare_order
.assert_called()
1726 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1727 self
.m
.report
.log_order
.assert_called()
1729 mock
.call(order_mock
, 5, update
="adjusting",
1730 compute_value
=mock
.ANY
,
1731 new_order
=new_order_mock
),
1732 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
1734 self
.m
.report
.log_order
.assert_has_calls(calls
)
1736 order_mock
.reset_mock()
1737 new_order_mock
.reset_mock()
1739 self
.m
.report
.log_order
.reset_mock()
1741 trade
.update_order(order_mock
, 7)
1742 order_mock
.cancel
.assert_called()
1743 new_order_mock
.run
.assert_called()
1744 prepare_order
.assert_called_with(compute_value
="default")
1745 self
.m
.report
.log_order
.assert_called()
1746 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1748 mock
.call(order_mock
, 7, update
="market_fallback",
1749 compute_value
='default',
1750 new_order
=new_order_mock
),
1751 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
1753 self
.m
.report
.log_order
.assert_has_calls(calls
)
1755 order_mock
.reset_mock()
1756 new_order_mock
.reset_mock()
1758 self
.m
.report
.log_order
.reset_mock()
1760 for i
in [10, 13, 16]:
1761 with self
.subTest(tick
=i
):
1762 trade
.update_order(order_mock
, i
)
1763 order_mock
.cancel
.assert_called()
1764 new_order_mock
.run
.assert_called()
1765 prepare_order
.assert_called_with(compute_value
="default")
1766 self
.m
.report
.log_order
.assert_called()
1767 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
1769 mock
.call(order_mock
, i
, update
="market_adjust",
1770 compute_value
='default',
1771 new_order
=new_order_mock
),
1772 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
1774 self
.m
.report
.log_order
.assert_has_calls(calls
)
1776 order_mock
.reset_mock()
1777 new_order_mock
.reset_mock()
1779 self
.m
.report
.log_order
.reset_mock()
1781 for i
in [8, 9, 11, 12]:
1782 with self
.subTest(tick
=i
):
1783 trade
.update_order(order_mock
, i
)
1784 order_mock
.cancel
.assert_not_called()
1785 new_order_mock
.run
.assert_not_called()
1786 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
1787 compute_value
=None, new_order
=None)
1789 order_mock
.reset_mock()
1790 new_order_mock
.reset_mock()
1792 self
.m
.report
.log_order
.reset_mock()
1795 def test_print_with_order(self
):
1796 value_from
= portfolio
.Amount("BTC", "0.5")
1797 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1798 value_to
= portfolio
.Amount("BTC", "1.0")
1799 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1801 order_mock1
= mock
.Mock()
1802 order_mock1
.__repr__
= mock
.Mock()
1803 order_mock1
.__repr__
.return_value
= "Mock 1"
1804 order_mock2
= mock
.Mock()
1805 order_mock2
.__repr__
= mock
.Mock()
1806 order_mock2
.__repr__
.return_value
= "Mock 2"
1807 order_mock1
.mouvements
= []
1808 mouvement_mock1
= mock
.Mock()
1809 mouvement_mock1
.__repr__
= mock
.Mock()
1810 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
1811 mouvement_mock2
= mock
.Mock()
1812 mouvement_mock2
.__repr__
= mock
.Mock()
1813 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
1814 order_mock2
.mouvements
= [
1815 mouvement_mock1
, mouvement_mock2
1817 trade
.orders
.append(order_mock1
)
1818 trade
.orders
.append(order_mock2
)
1820 trade
.print_with_order()
1822 self
.m
.report
.print_log
.assert_called()
1823 calls
= self
.m
.report
.print_log
.mock_calls
1824 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
1825 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
1826 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
1827 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
1828 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
1830 def test__repr(self
):
1831 value_from
= portfolio
.Amount("BTC", "0.5")
1832 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1833 value_to
= portfolio
.Amount("BTC", "1.0")
1834 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1836 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
1838 def test_as_json(self
):
1839 value_from
= portfolio
.Amount("BTC", "0.5")
1840 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1841 value_to
= portfolio
.Amount("BTC", "1.0")
1842 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
1844 as_json
= trade
.as_json()
1845 self
.assertEqual("acquire", as_json
["action"])
1846 self
.assertEqual(D("0.5"), as_json
["from"])
1847 self
.assertEqual(D("1.0"), as_json
["to"])
1848 self
.assertEqual("ETH", as_json
["currency"])
1849 self
.assertEqual("BTC", as_json
["base_currency"])
1851 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1852 class OrderTest(WebMockTestCase
):
1853 def test_values(self
):
1854 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1855 D("0.1"), "BTC", "long", "market", "trade")
1856 self
.assertEqual("buy", order
.action
)
1857 self
.assertEqual(10, order
.amount
.value
)
1858 self
.assertEqual("ETH", order
.amount
.currency
)
1859 self
.assertEqual(D("0.1"), order
.rate
)
1860 self
.assertEqual("BTC", order
.base_currency
)
1861 self
.assertEqual("market", order
.market
)
1862 self
.assertEqual("long", order
.trade_type
)
1863 self
.assertEqual("pending", order
.status
)
1864 self
.assertEqual("trade", order
.trade
)
1865 self
.assertIsNone(order
.id)
1866 self
.assertFalse(order
.close_if_possible
)
1868 def test__repr(self
):
1869 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1870 D("0.1"), "BTC", "long", "market", "trade")
1871 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
1873 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1874 D("0.1"), "BTC", "long", "market", "trade",
1875 close_if_possible
=True)
1876 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
1878 def test_as_json(self
):
1879 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1880 D("0.1"), "BTC", "long", "market", "trade")
1881 mouvement_mock1
= mock
.Mock()
1882 mouvement_mock1
.as_json
.return_value
= 1
1883 mouvement_mock2
= mock
.Mock()
1884 mouvement_mock2
.as_json
.return_value
= 2
1886 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
1887 as_json
= order
.as_json()
1888 self
.assertEqual("buy", as_json
["action"])
1889 self
.assertEqual("long", as_json
["trade_type"])
1890 self
.assertEqual(10, as_json
["amount"])
1891 self
.assertEqual("ETH", as_json
["currency"])
1892 self
.assertEqual("BTC", as_json
["base_currency"])
1893 self
.assertEqual(D("0.1"), as_json
["rate"])
1894 self
.assertEqual("pending", as_json
["status"])
1895 self
.assertEqual(False, as_json
["close_if_possible"])
1896 self
.assertIsNone(as_json
["id"])
1897 self
.assertEqual([1, 2], as_json
["mouvements"])
1899 def test_account(self
):
1900 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1901 D("0.1"), "BTC", "long", "market", "trade")
1902 self
.assertEqual("exchange", order
.account
)
1904 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
1905 D("0.1"), "BTC", "short", "market", "trade")
1906 self
.assertEqual("margin", order
.account
)
1908 def test_pending(self
):
1909 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1910 D("0.1"), "BTC", "long", "market", "trade")
1911 self
.assertTrue(order
.pending
)
1912 order
.status
= "open"
1913 self
.assertFalse(order
.pending
)
1915 def test_open(self
):
1916 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1917 D("0.1"), "BTC", "long", "market", "trade")
1918 self
.assertFalse(order
.open)
1919 order
.status
= "open"
1920 self
.assertTrue(order
.open)
1922 def test_finished(self
):
1923 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1924 D("0.1"), "BTC", "long", "market", "trade")
1925 self
.assertFalse(order
.finished
)
1926 order
.status
= "closed"
1927 self
.assertTrue(order
.finished
)
1928 order
.status
= "canceled"
1929 self
.assertTrue(order
.finished
)
1930 order
.status
= "error"
1931 self
.assertTrue(order
.finished
)
1933 @mock.patch.object(portfolio
.Order
, "fetch")
1934 def test_cancel(self
, fetch
):
1936 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1937 D("0.1"), "BTC", "long", self
.m
, "trade")
1938 order
.status
= "open"
1941 self
.m
.ccxt
.cancel_order
.assert_not_called()
1942 self
.m
.report
.log_debug_action
.assert_called_once()
1943 self
.m
.report
.log_debug_action
.reset_mock()
1944 self
.assertEqual("canceled", order
.status
)
1946 self
.m
.debug
= False
1947 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1948 D("0.1"), "BTC", "long", self
.m
, "trade")
1949 order
.status
= "open"
1953 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
1954 fetch
.assert_called_once_with()
1955 self
.m
.report
.log_debug_action
.assert_not_called()
1957 def test_dust_amount_remaining(self
):
1958 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1959 D("0.1"), "BTC", "long", self
.m
, "trade")
1960 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
1961 self
.assertFalse(order
.dust_amount_remaining())
1963 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
1964 self
.assertTrue(order
.dust_amount_remaining())
1966 @mock.patch.object(portfolio
.Order
, "fetch")
1967 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
1968 def test_remaining_amount(self
, filled_amount
, fetch
):
1969 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1970 D("0.1"), "BTC", "long", self
.m
, "trade")
1972 self
.assertEqual(9, order
.remaining_amount().value
)
1974 order
.status
= "open"
1975 self
.assertEqual(9, order
.remaining_amount().value
)
1977 @mock.patch.object(portfolio
.Order
, "fetch")
1978 def test_filled_amount(self
, fetch
):
1979 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
1980 D("0.1"), "BTC", "long", self
.m
, "trade")
1981 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1982 "tradeID": 42, "type": "buy", "fee": "0.0015",
1983 "date": "2017-12-30 12:00:12", "rate": "0.1",
1984 "amount": "3", "total": "0.3"
1986 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
1987 "tradeID": 43, "type": "buy", "fee": "0.0015",
1988 "date": "2017-12-30 13:00:12", "rate": "0.2",
1989 "amount": "2", "total": "0.4"
1991 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
1992 fetch
.assert_not_called()
1993 order
.status
= "open"
1994 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
1995 fetch
.assert_called_once()
1996 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
1998 def test_fetch_mouvements(self
):
1999 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
2001 "tradeID": 42, "type": "buy", "fee": "0.0015",
2002 "date": "2017-12-30 12:00:12", "rate": "0.1",
2003 "amount": "3", "total": "0.3"
2006 "tradeID": 43, "type": "buy", "fee": "0.0015",
2007 "date": "2017-12-30 13:00:12", "rate": "0.2",
2008 "amount": "2", "total": "0.4"
2011 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2012 D("0.1"), "BTC", "long", self
.m
, "trade")
2014 order
.mouvements
= ["Foo", "Bar", "Baz"]
2016 order
.fetch_mouvements()
2018 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
2019 self
.assertEqual(2, len(order
.mouvements
))
2020 self
.assertEqual(42, order
.mouvements
[0].id)
2021 self
.assertEqual(43, order
.mouvements
[1].id)
2023 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
2024 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2025 D("0.1"), "BTC", "long", self
.m
, "trade")
2026 order
.fetch_mouvements()
2027 self
.assertEqual(0, len(order
.mouvements
))
2029 def test_mark_finished_order(self
):
2030 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2031 D("0.1"), "BTC", "short", self
.m
, "trade",
2032 close_if_possible
=True)
2033 order
.status
= "closed"
2034 self
.m
.debug
= False
2036 order
.mark_finished_order()
2037 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
2038 self
.m
.ccxt
.close_margin_position
.reset_mock()
2040 order
.status
= "open"
2041 order
.mark_finished_order()
2042 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2044 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2045 D("0.1"), "BTC", "short", self
.m
, "trade",
2046 close_if_possible
=False)
2047 order
.status
= "closed"
2048 order
.mark_finished_order()
2049 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2051 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2052 D("0.1"), "BTC", "short", self
.m
, "trade",
2053 close_if_possible
=True)
2054 order
.status
= "closed"
2055 order
.mark_finished_order()
2056 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2058 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2059 D("0.1"), "BTC", "long", self
.m
, "trade",
2060 close_if_possible
=True)
2061 order
.status
= "closed"
2062 order
.mark_finished_order()
2063 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2067 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2068 D("0.1"), "BTC", "short", self
.m
, "trade",
2069 close_if_possible
=True)
2070 order
.status
= "closed"
2072 order
.mark_finished_order()
2073 self
.m
.ccxt
.close_margin_position
.assert_not_called()
2074 self
.m
.report
.log_debug_action
.assert_called_once()
2076 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
2077 def test_fetch(self
, fetch_mouvements
):
2078 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2079 D("0.1"), "BTC", "long", self
.m
, "trade")
2081 with self
.subTest(debug
=True):
2084 self
.m
.report
.log_debug_action
.assert_called_once()
2085 self
.m
.report
.log_debug_action
.reset_mock()
2086 self
.m
.ccxt
.fetch_order
.assert_not_called()
2087 fetch_mouvements
.assert_not_called()
2089 with self
.subTest(debug
=False):
2090 self
.m
.debug
= False
2091 self
.m
.ccxt
.fetch_order
.return_value
= {
2093 "datetime": "timestamp"
2097 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45, symbol
="ETH")
2098 fetch_mouvements
.assert_called_once()
2099 self
.assertEqual("foo", order
.status
)
2100 self
.assertEqual("timestamp", order
.timestamp
)
2101 self
.assertEqual(1, len(order
.results
))
2102 self
.m
.report
.log_debug_action
.assert_not_called()
2104 with self
.subTest(missing_order
=True):
2105 self
.m
.ccxt
.fetch_order
.side_effect
= [
2106 portfolio
.OrderNotCached
,
2109 self
.assertEqual("closed_unknown", order
.status
)
2111 @mock.patch.object(portfolio
.Order
, "fetch")
2112 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
2113 def test_get_status(self
, mark_finished_order
, fetch
):
2114 with self
.subTest(debug
=True):
2116 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2117 D("0.1"), "BTC", "long", self
.m
, "trade")
2118 self
.assertEqual("pending", order
.get_status())
2119 fetch
.assert_not_called()
2120 self
.m
.report
.log_debug_action
.assert_called_once()
2122 with self
.subTest(debug
=False, finished
=False):
2123 self
.m
.debug
= False
2124 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2125 D("0.1"), "BTC", "long", self
.m
, "trade")
2127 def update_status():
2128 order
.status
= "open"
2129 return update_status
2130 fetch
.side_effect
= _fetch(order
)
2131 self
.assertEqual("open", order
.get_status())
2132 mark_finished_order
.assert_not_called()
2133 fetch
.assert_called_once()
2135 mark_finished_order
.reset_mock()
2137 with self
.subTest(debug
=False, finished
=True):
2138 self
.m
.debug
= False
2139 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2140 D("0.1"), "BTC", "long", self
.m
, "trade")
2142 def update_status():
2143 order
.status
= "closed"
2144 return update_status
2145 fetch
.side_effect
= _fetch(order
)
2146 self
.assertEqual("closed", order
.get_status())
2147 mark_finished_order
.assert_called_once()
2148 fetch
.assert_called_once()
2151 self
.m
.ccxt
.order_precision
.return_value
= 4
2152 with self
.subTest(debug
=True):
2154 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2155 D("0.1"), "BTC", "long", self
.m
, "trade")
2157 self
.m
.ccxt
.create_order
.assert_not_called()
2158 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
2159 self
.assertEqual("open", order
.status
)
2160 self
.assertEqual(1, len(order
.results
))
2161 self
.assertEqual(-1, order
.id)
2163 self
.m
.ccxt
.create_order
.reset_mock()
2164 with self
.subTest(debug
=False):
2165 self
.m
.debug
= False
2166 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2167 D("0.1"), "BTC", "long", self
.m
, "trade")
2168 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
2170 self
.m
.ccxt
.create_order
.assert_called_once()
2171 self
.assertEqual(1, len(order
.results
))
2172 self
.assertEqual("open", order
.status
)
2174 self
.m
.ccxt
.create_order
.reset_mock()
2175 with self
.subTest(exception
=True):
2176 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2177 D("0.1"), "BTC", "long", self
.m
, "trade")
2178 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
2180 self
.m
.ccxt
.create_order
.assert_called_once()
2181 self
.assertEqual(0, len(order
.results
))
2182 self
.assertEqual("error", order
.status
)
2183 self
.m
.report
.log_error
.assert_called_once()
2185 self
.m
.ccxt
.create_order
.reset_mock()
2186 with self
.subTest(dust_amount_exception
=True),\
2187 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2188 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
2189 D("0.1"), "BTC", "long", self
.m
, "trade")
2190 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
2192 self
.m
.ccxt
.create_order
.assert_called_once()
2193 self
.assertEqual(0, len(order
.results
))
2194 self
.assertEqual("closed", order
.status
)
2195 mark_finished_order
.assert_called_once()
2197 self
.m
.ccxt
.order_precision
.return_value
= 8
2198 self
.m
.ccxt
.create_order
.reset_mock()
2199 with self
.subTest(insufficient_funds
=True),\
2200 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2201 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2202 D("0.1"), "BTC", "long", self
.m
, "trade")
2203 self
.m
.ccxt
.create_order
.side_effect
= [
2204 portfolio
.InsufficientFunds
,
2205 portfolio
.InsufficientFunds
,
2206 portfolio
.InsufficientFunds
,
2210 self
.m
.ccxt
.create_order
.assert_has_calls([
2211 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2212 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2213 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2214 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2216 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
2217 self
.assertEqual(1, len(order
.results
))
2218 self
.assertEqual("open", order
.status
)
2219 self
.assertEqual(4, order
.tries
)
2220 self
.m
.report
.log_error
.assert_called()
2221 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
2223 self
.m
.ccxt
.order_precision
.return_value
= 8
2224 self
.m
.ccxt
.create_order
.reset_mock()
2225 self
.m
.report
.log_error
.reset_mock()
2226 with self
.subTest(insufficient_funds
=True),\
2227 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
2228 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
2229 D("0.1"), "BTC", "long", self
.m
, "trade")
2230 self
.m
.ccxt
.create_order
.side_effect
= [
2231 portfolio
.InsufficientFunds
,
2232 portfolio
.InsufficientFunds
,
2233 portfolio
.InsufficientFunds
,
2234 portfolio
.InsufficientFunds
,
2235 portfolio
.InsufficientFunds
,
2238 self
.m
.ccxt
.create_order
.assert_has_calls([
2239 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
2240 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
2241 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
2242 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
2243 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
2245 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
2246 self
.assertEqual(0, len(order
.results
))
2247 self
.assertEqual("error", order
.status
)
2248 self
.assertEqual(5, order
.tries
)
2249 self
.m
.report
.log_error
.assert_called()
2250 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
2251 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
)
2254 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2255 class MouvementTest(WebMockTestCase
):
2256 def test_values(self
):
2257 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2258 "tradeID": 42, "type": "buy", "fee": "0.0015",
2259 "date": "2017-12-30 12:00:12", "rate": "0.1",
2260 "amount": "10", "total": "1"
2262 self
.assertEqual("ETH", mouvement
.currency
)
2263 self
.assertEqual("BTC", mouvement
.base_currency
)
2264 self
.assertEqual(42, mouvement
.id)
2265 self
.assertEqual("buy", mouvement
.action
)
2266 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
2267 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
2268 self
.assertEqual(D("0.1"), mouvement
.rate
)
2269 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
2270 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
2272 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
2273 self
.assertIsNone(mouvement
.date
)
2274 self
.assertIsNone(mouvement
.id)
2275 self
.assertIsNone(mouvement
.action
)
2276 self
.assertEqual(-1, mouvement
.fee_rate
)
2277 self
.assertEqual(0, mouvement
.rate
)
2278 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
2279 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
2281 def test__repr(self
):
2282 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2283 "tradeID": 42, "type": "buy", "fee": "0.0015",
2284 "date": "2017-12-30 12:00:12", "rate": "0.1",
2285 "amount": "10", "total": "1"
2287 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
2289 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2290 "tradeID": 42, "type": "buy",
2291 "date": "garbage", "rate": "0.1",
2292 "amount": "10", "total": "1"
2294 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
2296 def test_as_json(self
):
2297 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
2298 "tradeID": 42, "type": "buy", "fee": "0.0015",
2299 "date": "2017-12-30 12:00:12", "rate": "0.1",
2300 "amount": "10", "total": "1"
2302 as_json
= mouvement
.as_json()
2304 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
2305 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
2306 self
.assertEqual("buy", as_json
["action"])
2307 self
.assertEqual(D("10"), as_json
["total"])
2308 self
.assertEqual(D("1"), as_json
["total_in_base"])
2309 self
.assertEqual("BTC", as_json
["base_currency"])
2310 self
.assertEqual("ETH", as_json
["currency"])
2312 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2313 class ReportStoreTest(WebMockTestCase
):
2314 def test_add_log(self
):
2315 report_store
= market
.ReportStore(self
.m
)
2316 report_store
.add_log({"foo": "bar"}
)
2318 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
2320 def test_set_verbose(self
):
2321 report_store
= market
.ReportStore(self
.m
)
2322 with self
.subTest(verbose
=True):
2323 report_store
.set_verbose(True)
2324 self
.assertTrue(report_store
.verbose_print
)
2326 with self
.subTest(verbose
=False):
2327 report_store
.set_verbose(False)
2328 self
.assertFalse(report_store
.verbose_print
)
2330 def test_print_log(self
):
2331 report_store
= market
.ReportStore(self
.m
)
2332 with self
.subTest(verbose
=True),\
2333 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2334 report_store
.set_verbose(True)
2335 report_store
.print_log("Coucou")
2336 report_store
.print_log(portfolio
.Amount("BTC", 1))
2337 self
.assertEqual(stdout_mock
.getvalue(), "Coucou\n1.00000000 BTC\n")
2339 with self
.subTest(verbose
=False),\
2340 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2341 report_store
.set_verbose(False)
2342 report_store
.print_log("Coucou")
2343 report_store
.print_log(portfolio
.Amount("BTC", 1))
2344 self
.assertEqual(stdout_mock
.getvalue(), "")
2346 def test_to_json(self
):
2347 report_store
= market
.ReportStore(self
.m
)
2348 report_store
.logs
.append({"foo": "bar"}
)
2349 self
.assertEqual('[{"foo": "bar"}]', report_store
.to_json())
2350 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
2351 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}]', report_store
.to_json())
2352 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
2353 self
.assertEqual('[{"foo": "bar"}, {"date": "2018-02-24T00:00:00"}, {"amount": "1.00000000 BTC"}]', report_store
.to_json())
2355 @mock.patch.object(market
.ReportStore
, "print_log")
2356 @mock.patch.object(market
.ReportStore
, "add_log")
2357 def test_log_stage(self
, add_log
, print_log
):
2358 report_store
= market
.ReportStore(self
.m
)
2359 report_store
.log_stage("foo")
2360 print_log
.assert_has_calls([
2361 mock
.call("-----------"),
2362 mock
.call("[Stage] foo"),
2364 add_log
.assert_called_once_with({'type': 'stage', 'stage': 'foo'}
)
2366 @mock.patch.object(market
.ReportStore
, "print_log")
2367 @mock.patch.object(market
.ReportStore
, "add_log")
2368 def test_log_balances(self
, add_log
, print_log
):
2369 report_store
= market
.ReportStore(self
.m
)
2370 self
.m
.balances
.as_json
.return_value
= "json"
2371 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
2373 report_store
.log_balances(tag
="tag")
2374 print_log
.assert_has_calls([
2375 mock
.call("[Balance]"),
2379 add_log
.assert_called_once_with({
2385 @mock.patch.object(market
.ReportStore
, "print_log")
2386 @mock.patch.object(market
.ReportStore
, "add_log")
2387 def test_log_tickers(self
, add_log
, print_log
):
2388 report_store
= market
.ReportStore(self
.m
)
2390 "BTC": portfolio
.Amount("BTC", 10),
2391 "ETH": portfolio
.Amount("BTC", D("0.3"))
2393 amounts
["ETH"].rate
= D("0.1")
2395 report_store
.log_tickers(amounts
, "BTC", "default", "total")
2396 print_log
.assert_not_called()
2397 add_log
.assert_called_once_with({
2399 'compute_value': 'default',
2400 'balance_type': 'total',
2413 add_log
.reset_mock()
2414 compute_value
= lambda x
: x
["bid"]
2415 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
2416 add_log
.assert_called_once_with({
2418 'compute_value': 'compute_value = lambda x: x["bid"]',
2419 'balance_type': 'total',
2432 @mock.patch.object(market
.ReportStore
, "print_log")
2433 @mock.patch.object(market
.ReportStore
, "add_log")
2434 def test_log_dispatch(self
, add_log
, print_log
):
2435 report_store
= market
.ReportStore(self
.m
)
2436 amount
= portfolio
.Amount("BTC", "10.3")
2438 "BTC": portfolio
.Amount("BTC", 10),
2439 "ETH": portfolio
.Amount("BTC", D("0.3"))
2441 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
2442 print_log
.assert_not_called()
2443 add_log
.assert_called_once_with({
2445 'liquidity': 'medium',
2446 'repartition_ratio': 'repartition',
2457 @mock.patch.object(market
.ReportStore
, "print_log")
2458 @mock.patch.object(market
.ReportStore
, "add_log")
2459 def test_log_trades(self
, add_log
, print_log
):
2460 report_store
= market
.ReportStore(self
.m
)
2461 trade_mock1
= mock
.Mock()
2462 trade_mock2
= mock
.Mock()
2463 trade_mock1
.as_json
.return_value
= { "trade": "1" }
2464 trade_mock2
.as_json
.return_value
= { "trade": "2" }
2466 matching_and_trades
= [
2467 (True, trade_mock1
),
2468 (False, trade_mock2
),
2470 report_store
.log_trades(matching_and_trades
, "only")
2472 print_log
.assert_not_called()
2473 add_log
.assert_called_with({
2478 {'trade': '1', 'skipped': False}
,
2479 {'trade': '2', 'skipped': True}
2483 @mock.patch.object(market
.ReportStore
, "print_log")
2484 @mock.patch.object(market
.ReportStore
, "add_log")
2485 def test_log_orders(self
, add_log
, print_log
):
2486 report_store
= market
.ReportStore(self
.m
)
2488 order_mock1
= mock
.Mock()
2489 order_mock2
= mock
.Mock()
2491 order_mock1
.as_json
.return_value
= "order1"
2492 order_mock2
.as_json
.return_value
= "order2"
2494 orders
= [order_mock1
, order_mock2
]
2496 report_store
.log_orders(orders
, tick
="tick",
2497 only
="only", compute_value
="compute_value")
2499 print_log
.assert_called_once_with("[Orders]")
2500 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
2502 add_log
.assert_called_with({
2505 'compute_value': 'compute_value',
2507 'orders': ['order1', 'order2']
2510 add_log
.reset_mock()
2511 def compute_value(x
, y
):
2513 report_store
.log_orders(orders
, tick
="tick",
2514 only
="only", compute_value
=compute_value
)
2515 add_log
.assert_called_with({
2518 'compute_value': 'def compute_value(x, y):\n return x[y]',
2520 'orders': ['order1', 'order2']
2524 @mock.patch.object(market
.ReportStore
, "print_log")
2525 @mock.patch.object(market
.ReportStore
, "add_log")
2526 def test_log_order(self
, add_log
, print_log
):
2527 report_store
= market
.ReportStore(self
.m
)
2528 order_mock
= mock
.Mock()
2529 order_mock
.as_json
.return_value
= "order"
2530 new_order_mock
= mock
.Mock()
2531 new_order_mock
.as_json
.return_value
= "new_order"
2532 order_mock
.__repr
__ = mock
.Mock()
2533 order_mock
.__repr
__.return_value
= "Order Mock"
2534 new_order_mock
.__repr
__ = mock
.Mock()
2535 new_order_mock
.__repr
__.return_value
= "New order Mock"
2537 with self
.subTest(finished
=True):
2538 report_store
.log_order(order_mock
, 1, finished
=True)
2539 print_log
.assert_called_once_with("[Order] Finished Order Mock")
2540 add_log
.assert_called_once_with({
2545 'compute_value': None,
2549 add_log
.reset_mock()
2550 print_log
.reset_mock()
2552 with self
.subTest(update
="waiting"):
2553 report_store
.log_order(order_mock
, 1, update
="waiting")
2554 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
2555 add_log
.assert_called_once_with({
2558 'update': 'waiting',
2560 'compute_value': None,
2564 add_log
.reset_mock()
2565 print_log
.reset_mock()
2566 with self
.subTest(update
="adjusting"):
2567 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
2568 report_store
.log_order(order_mock
, 3,
2569 update
="adjusting", new_order
=new_order_mock
,
2570 compute_value
=compute_value
)
2571 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
2572 add_log
.assert_called_once_with({
2575 'update': 'adjusting',
2577 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
2578 'new_order': 'new_order'
2581 add_log
.reset_mock()
2582 print_log
.reset_mock()
2583 with self
.subTest(update
="market_fallback"):
2584 report_store
.log_order(order_mock
, 7,
2585 update
="market_fallback", new_order
=new_order_mock
)
2586 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
2587 add_log
.assert_called_once_with({
2590 'update': 'market_fallback',
2592 'compute_value': None,
2593 'new_order': 'new_order'
2596 add_log
.reset_mock()
2597 print_log
.reset_mock()
2598 with self
.subTest(update
="market_adjusting"):
2599 report_store
.log_order(order_mock
, 17,
2600 update
="market_adjust", new_order
=new_order_mock
)
2601 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
2602 add_log
.assert_called_once_with({
2605 'update': 'market_adjust',
2607 'compute_value': None,
2608 'new_order': 'new_order'
2611 @mock.patch.object(market
.ReportStore
, "print_log")
2612 @mock.patch.object(market
.ReportStore
, "add_log")
2613 def test_log_move_balances(self
, add_log
, print_log
):
2614 report_store
= market
.ReportStore(self
.m
)
2616 "BTC": portfolio
.Amount("BTC", 10),
2620 "BTC": portfolio
.Amount("BTC", 3),
2623 report_store
.log_move_balances(needed
, moving
)
2624 print_log
.assert_not_called()
2625 add_log
.assert_called_once_with({
2626 'type': 'move_balances',
2638 @mock.patch.object(market
.ReportStore
, "print_log")
2639 @mock.patch.object(market
.ReportStore
, "add_log")
2640 def test_log_http_request(self
, add_log
, print_log
):
2641 report_store
= market
.ReportStore(self
.m
)
2642 response
= mock
.Mock()
2643 response
.status_code
= 200
2644 response
.text
= "Hey"
2646 report_store
.log_http_request("method", "url", "body",
2647 "headers", response
)
2648 print_log
.assert_not_called()
2649 add_log
.assert_called_once_with({
2650 'type': 'http_request',
2654 'headers': 'headers',
2659 @mock.patch.object(market
.ReportStore
, "print_log")
2660 @mock.patch.object(market
.ReportStore
, "add_log")
2661 def test_log_error(self
, add_log
, print_log
):
2662 report_store
= market
.ReportStore(self
.m
)
2663 with self
.subTest(message
=None, exception
=None):
2664 report_store
.log_error("action")
2665 print_log
.assert_called_once_with("[Error] action")
2666 add_log
.assert_called_once_with({
2669 'exception_class': None,
2670 'exception_message': None,
2674 print_log
.reset_mock()
2675 add_log
.reset_mock()
2676 with self
.subTest(message
="Hey", exception
=None):
2677 report_store
.log_error("action", message
="Hey")
2678 print_log
.assert_has_calls([
2679 mock
.call("[Error] action"),
2682 add_log
.assert_called_once_with({
2685 'exception_class': None,
2686 'exception_message': None,
2690 print_log
.reset_mock()
2691 add_log
.reset_mock()
2692 with self
.subTest(message
=None, exception
=Exception("bouh")):
2693 report_store
.log_error("action", exception
=Exception("bouh"))
2694 print_log
.assert_has_calls([
2695 mock
.call("[Error] action"),
2696 mock
.call("\tException: bouh")
2698 add_log
.assert_called_once_with({
2701 'exception_class': "Exception",
2702 'exception_message': "bouh",
2706 print_log
.reset_mock()
2707 add_log
.reset_mock()
2708 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
2709 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
2710 print_log
.assert_has_calls([
2711 mock
.call("[Error] action"),
2712 mock
.call("\tException: bouh"),
2715 add_log
.assert_called_once_with({
2718 'exception_class': "Exception",
2719 'exception_message': "bouh",
2723 @mock.patch.object(market
.ReportStore
, "print_log")
2724 @mock.patch.object(market
.ReportStore
, "add_log")
2725 def test_log_debug_action(self
, add_log
, print_log
):
2726 report_store
= market
.ReportStore(self
.m
)
2727 report_store
.log_debug_action("Hey")
2729 print_log
.assert_called_once_with("[Debug] Hey")
2730 add_log
.assert_called_once_with({
2731 'type': 'debug_action',
2735 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2736 class HelperTest(WebMockTestCase
):
2737 def test_make_order(self
):
2738 self
.m
.get_ticker
.return_value
= {
2740 "average": D("0.1"),
2745 with self
.subTest(description
="nominal case"):
2746 helper
.make_order(self
.m
, 10, "ETH")
2748 self
.m
.report
.log_stage
.assert_has_calls([
2749 mock
.call("make_order_begin"),
2750 mock
.call("make_order_end"),
2752 self
.m
.balances
.fetch_balances
.assert_has_calls([
2753 mock
.call(tag
="make_order_begin"),
2754 mock
.call(tag
="make_order_end"),
2756 self
.m
.trades
.all
.append
.assert_called_once()
2757 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2758 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
2759 self
.assertEqual(0, trade
.value_from
)
2760 self
.assertEqual("ETH", trade
.currency
)
2761 self
.assertEqual("BTC", trade
.base_currency
)
2762 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2763 self
.m
.trades
.run_orders
.assert_called_once_with()
2764 self
.m
.follow_orders
.assert_called_once_with()
2766 order
= trade
.orders
[0]
2767 self
.assertEqual(D("0.10"), order
.rate
)
2770 with self
.subTest(compute_value
="default"):
2771 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2772 compute_value
="ask")
2774 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2775 order
= trade
.orders
[0]
2776 self
.assertEqual(D("0.11"), order
.rate
)
2779 with self
.subTest(follow
=False):
2780 result
= helper
.make_order(self
.m
, 10, "ETH", follow
=False)
2782 self
.m
.report
.log_stage
.assert_has_calls([
2783 mock
.call("make_order_begin"),
2784 mock
.call("make_order_end_not_followed"),
2786 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
2788 self
.m
.trades
.all
.append
.assert_called_once()
2789 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2790 self
.assertEqual(0, trade
.value_from
)
2791 self
.assertEqual("ETH", trade
.currency
)
2792 self
.assertEqual("BTC", trade
.base_currency
)
2793 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
2794 self
.m
.trades
.run_orders
.assert_called_once_with()
2795 self
.m
.follow_orders
.assert_not_called()
2796 self
.assertEqual(trade
.orders
[0], result
)
2799 with self
.subTest(base_currency
="USDT"):
2800 helper
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
2802 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2803 self
.assertEqual("BTC", trade
.currency
)
2804 self
.assertEqual("USDT", trade
.base_currency
)
2807 with self
.subTest(close_if_possible
=True):
2808 helper
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
2810 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2811 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
2814 with self
.subTest(action
="dispose"):
2815 helper
.make_order(self
.m
, 10, "ETH", action
="dispose")
2817 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2818 self
.assertEqual(0, trade
.value_to
)
2819 self
.assertEqual(1, trade
.value_from
.value
)
2820 self
.assertEqual("ETH", trade
.currency
)
2821 self
.assertEqual("BTC", trade
.base_currency
)
2824 with self
.subTest(compute_value
="default"):
2825 helper
.make_order(self
.m
, 10, "ETH", action
="dispose",
2826 compute_value
="bid")
2828 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
2829 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
2831 def test_user_market(self
):
2832 with mock
.patch("helper.main_fetch_markets") as main_fetch_markets
,\
2833 mock
.patch("helper.main_parse_config") as main_parse_config
:
2834 with self
.subTest(debug
=False):
2835 main_parse_config
.return_value
= ["pg_config", "report_path"]
2836 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2837 m
= helper
.get_user_market("config_path.ini", 1)
2839 self
.assertIsInstance(m
, market
.Market
)
2840 self
.assertFalse(m
.debug
)
2842 with self
.subTest(debug
=True):
2843 main_parse_config
.return_value
= ["pg_config", "report_path"]
2844 main_fetch_markets
.return_value
= [({"key": "market_config"}
,)]
2845 m
= helper
.get_user_market("config_path.ini", 1, debug
=True)
2847 self
.assertIsInstance(m
, market
.Market
)
2848 self
.assertTrue(m
.debug
)
2850 def test_main_store_report(self
):
2851 file_open
= mock
.mock_open()
2852 with self
.subTest(file=None), mock
.patch("__main__.open", file_open
):
2853 helper
.main_store_report(None, 1, self
.m
)
2854 file_open
.assert_not_called()
2856 file_open
= mock
.mock_open()
2857 with self
.subTest(file="present"), mock
.patch("helper.open", file_open
),\
2858 mock
.patch
.object(helper
, "datetime") as time_mock
:
2859 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
2860 self
.m
.report
.to_json
.return_value
= "json_content"
2862 helper
.main_store_report("present", 1, self
.m
)
2864 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
2865 file_open().write
.assert_called_once_with("json_content")
2866 self
.m
.report
.to_json
.assert_called_once_with()
2868 with self
.subTest(file="error"),\
2869 mock
.patch("helper.open") as file_open
,\
2870 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2871 file_open
.side_effect
= FileNotFoundError
2873 helper
.main_store_report("error", 1, self
.m
)
2875 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
2877 @mock.patch("helper.process_sell_all__1_all_sell")
2878 @mock.patch("helper.process_sell_all__2_all_buy")
2879 @mock.patch("portfolio.Portfolio.wait_for_recent")
2880 def test_main_process_market(self
, wait
, buy
, sell
):
2881 with self
.subTest(before
=False, after
=False):
2882 helper
.main_process_market("user", None)
2884 wait
.assert_not_called()
2885 buy
.assert_not_called()
2886 sell
.assert_not_called()
2891 with self
.subTest(before
=True, after
=False):
2892 helper
.main_process_market("user", None, before
=True)
2894 wait
.assert_not_called()
2895 buy
.assert_not_called()
2896 sell
.assert_called_once_with("user")
2901 with self
.subTest(before
=False, after
=True):
2902 helper
.main_process_market("user", None, after
=True)
2904 wait
.assert_called_once_with("user")
2905 buy
.assert_called_once_with("user")
2906 sell
.assert_not_called()
2911 with self
.subTest(before
=True, after
=True):
2912 helper
.main_process_market("user", None, before
=True, after
=True)
2914 wait
.assert_called_once_with("user")
2915 buy
.assert_called_once_with("user")
2916 sell
.assert_called_once_with("user")
2921 with self
.subTest(action
="print_balances"),\
2922 mock
.patch("helper.print_balances") as print_balances
:
2923 helper
.main_process_market("user", ["print_balances"])
2925 buy
.assert_not_called()
2926 wait
.assert_not_called()
2927 sell
.assert_not_called()
2928 print_balances
.assert_called_once_with("user")
2930 with self
.subTest(action
="print_orders"),\
2931 mock
.patch("helper.print_orders") as print_orders
,\
2932 mock
.patch("helper.print_balances") as print_balances
:
2933 helper
.main_process_market("user", ["print_orders", "print_balances"])
2935 buy
.assert_not_called()
2936 wait
.assert_not_called()
2937 sell
.assert_not_called()
2938 print_orders
.assert_called_once_with("user")
2939 print_balances
.assert_called_once_with("user")
2941 with self
.subTest(action
="unknown"),\
2942 self
.assertRaises(NotImplementedError):
2943 helper
.main_process_market("user", ["unknown"])
2945 @mock.patch.object(helper
, "psycopg2")
2946 def test_fetch_markets(self
, psycopg2
):
2947 connect_mock
= mock
.Mock()
2948 cursor_mock
= mock
.MagicMock()
2949 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
2951 connect_mock
.cursor
.return_value
= cursor_mock
2952 psycopg2
.connect
.return_value
= connect_mock
2954 with self
.subTest(user
=None):
2955 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, None))
2957 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2958 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs")
2960 self
.assertEqual(["row_1", "row_2"], rows
)
2962 psycopg2
.connect
.reset_mock()
2963 cursor_mock
.execute
.reset_mock()
2964 with self
.subTest(user
=1):
2965 rows
= list(helper
.main_fetch_markets({"foo": "bar"}
, 1))
2967 psycopg2
.connect
.assert_called_once_with(foo
="bar")
2968 cursor_mock
.execute
.assert_called_once_with("SELECT config,user_id FROM market_configs WHERE user_id = %s", 1)
2970 self
.assertEqual(["row_1", "row_2"], rows
)
2972 @mock.patch.object(helper
.sys
, "exit")
2973 def test_main_parse_args(self
, exit
):
2974 with self
.subTest(config
="config.ini"):
2975 args
= helper
.main_parse_args([])
2976 self
.assertEqual("config.ini", args
.config
)
2977 self
.assertFalse(args
.before
)
2978 self
.assertFalse(args
.after
)
2979 self
.assertFalse(args
.debug
)
2981 args
= helper
.main_parse_args(["--before", "--after", "--debug"])
2982 self
.assertTrue(args
.before
)
2983 self
.assertTrue(args
.after
)
2984 self
.assertTrue(args
.debug
)
2986 exit
.assert_not_called()
2988 with self
.subTest(config
="inexistant"),\
2989 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
2990 args
= helper
.main_parse_args(["--config", "foo.bar"])
2991 exit
.assert_called_once_with(1)
2992 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
2994 @mock.patch.object(helper
.sys
, "exit")
2995 @mock.patch("helper.configparser")
2996 @mock.patch("helper.os")
2997 def test_main_parse_config(self
, os
, configparser
, exit
):
2998 with self
.subTest(pg_config
=True, report_path
=None):
2999 config_mock
= mock
.MagicMock()
3000 configparser
.ConfigParser
.return_value
= config_mock
3001 def config(element
):
3002 return element
== "postgresql"
3004 config_mock
.__contains
__.side_effect
= config
3005 config_mock
.__getitem
__.return_value
= "pg_config"
3007 result
= helper
.main_parse_config("configfile")
3009 config_mock
.read
.assert_called_with("configfile")
3011 self
.assertEqual(["pg_config", None], result
)
3013 with self
.subTest(pg_config
=True, report_path
="present"):
3014 config_mock
= mock
.MagicMock()
3015 configparser
.ConfigParser
.return_value
= config_mock
3017 config_mock
.__contains
__.return_value
= True
3018 config_mock
.__getitem
__.side_effect
= [
3019 {"report_path": "report_path"}
,
3020 {"report_path": "report_path"}
,
3024 os
.path
.exists
.return_value
= False
3025 result
= helper
.main_parse_config("configfile")
3027 config_mock
.read
.assert_called_with("configfile")
3028 self
.assertEqual(["pg_config", "report_path"], result
)
3029 os
.path
.exists
.assert_called_once_with("report_path")
3030 os
.makedirs
.assert_called_once_with("report_path")
3032 with self
.subTest(pg_config
=False),\
3033 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3034 config_mock
= mock
.MagicMock()
3035 configparser
.ConfigParser
.return_value
= config_mock
3036 result
= helper
.main_parse_config("configfile")
3038 config_mock
.read
.assert_called_with("configfile")
3039 exit
.assert_called_once_with(1)
3040 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
3043 def test_print_orders(self
):
3044 helper
.print_orders(self
.m
)
3046 self
.m
.report
.log_stage
.assert_called_with("print_orders")
3047 self
.m
.balances
.fetch_balances
.assert_called_with(tag
="print_orders")
3048 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3049 compute_value
="average")
3050 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3052 def test_print_balances(self
):
3053 self
.m
.balances
.in_currency
.return_value
= {
3054 "BTC": portfolio
.Amount("BTC", "0.65"),
3055 "ETH": portfolio
.Amount("BTC", "0.3"),
3058 helper
.print_balances(self
.m
)
3060 self
.m
.report
.log_stage
.assert_called_once_with("print_balances")
3061 self
.m
.balances
.fetch_balances
.assert_called_with()
3062 self
.m
.report
.print_log
.assert_has_calls([
3063 mock
.call("total:"),
3064 mock
.call(portfolio
.Amount("BTC", "0.95")),
3067 def test_process_sell_needed__1_sell(self
):
3068 helper
.process_sell_needed__1_sell(self
.m
)
3070 self
.m
.balances
.fetch_balances
.assert_has_calls([
3071 mock
.call(tag
="process_sell_needed__1_sell_begin"),
3072 mock
.call(tag
="process_sell_needed__1_sell_end"),
3074 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3076 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3078 self
.m
.trades
.run_orders
.assert_called()
3079 self
.m
.follow_orders
.assert_called()
3080 self
.m
.report
.log_stage
.assert_has_calls([
3081 mock
.call("process_sell_needed__1_sell_begin"),
3082 mock
.call("process_sell_needed__1_sell_end")
3085 def test_process_sell_needed__2_buy(self
):
3086 helper
.process_sell_needed__2_buy(self
.m
)
3088 self
.m
.balances
.fetch_balances
.assert_has_calls([
3089 mock
.call(tag
="process_sell_needed__2_buy_begin"),
3090 mock
.call(tag
="process_sell_needed__2_buy_end"),
3092 self
.m
.update_trades
.assert_called_with(base_currency
="BTC",
3093 liquidity
="medium", only
="acquire")
3094 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average",
3096 self
.m
.move_balances
.assert_called_with()
3097 self
.m
.trades
.run_orders
.assert_called()
3098 self
.m
.follow_orders
.assert_called()
3099 self
.m
.report
.log_stage
.assert_has_calls([
3100 mock
.call("process_sell_needed__2_buy_begin"),
3101 mock
.call("process_sell_needed__2_buy_end")
3104 def test_process_sell_all__1_sell(self
):
3105 helper
.process_sell_all__1_all_sell(self
.m
)
3107 self
.m
.balances
.fetch_balances
.assert_has_calls([
3108 mock
.call(tag
="process_sell_all__1_all_sell_begin"),
3109 mock
.call(tag
="process_sell_all__1_all_sell_end"),
3111 self
.m
.prepare_trades_to_sell_all
.assert_called_with(base_currency
="BTC")
3112 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3113 self
.m
.trades
.run_orders
.assert_called()
3114 self
.m
.follow_orders
.assert_called()
3115 self
.m
.report
.log_stage
.assert_has_calls([
3116 mock
.call("process_sell_all__1_all_sell_begin"),
3117 mock
.call("process_sell_all__1_all_sell_end")
3120 def test_process_sell_all__2_all_buy(self
):
3121 helper
.process_sell_all__2_all_buy(self
.m
)
3123 self
.m
.balances
.fetch_balances
.assert_has_calls([
3124 mock
.call(tag
="process_sell_all__2_all_buy_begin"),
3125 mock
.call(tag
="process_sell_all__2_all_buy_end"),
3127 self
.m
.prepare_trades
.assert_called_with(base_currency
="BTC",
3129 self
.m
.trades
.prepare_orders
.assert_called_with(compute_value
="average")
3130 self
.m
.move_balances
.assert_called_with()
3131 self
.m
.trades
.run_orders
.assert_called()
3132 self
.m
.follow_orders
.assert_called()
3133 self
.m
.report
.log_stage
.assert_has_calls([
3134 mock
.call("process_sell_all__2_all_buy_begin"),
3135 mock
.call("process_sell_all__2_all_buy_end")
3138 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
3139 class AcceptanceTest(WebMockTestCase
):
3140 @unittest.expectedFailure
3141 def test_success_sell_only_necessary(self
):
3142 # FIXME: catch stdout
3143 self
.m
.report
.verbose_print
= False
3146 "exchange_free": D("1.0"),
3147 "exchange_used": D("0.0"),
3148 "exchange_total": D("1.0"),
3152 "exchange_free": D("4.0"),
3153 "exchange_used": D("0.0"),
3154 "exchange_total": D("4.0"),
3158 "exchange_free": D("1000.0"),
3159 "exchange_used": D("0.0"),
3160 "exchange_total": D("1000.0"),
3161 "total": D("1000.0"),
3165 "ETH": (D("0.25"), "long"),
3166 "ETC": (D("0.25"), "long"),
3167 "BTC": (D("0.4"), "long"),
3168 "BTD": (D("0.01"), "short"),
3169 "B2X": (D("0.04"), "long"),
3170 "USDT": (D("0.05"), "long"),
3173 def fetch_ticker(symbol
):
3174 if symbol
== "ETH/BTC":
3176 "symbol": "ETH/BTC",
3180 if symbol
== "ETC/BTC":
3182 "symbol": "ETC/BTC",
3186 if symbol
== "XVG/BTC":
3188 "symbol": "XVG/BTC",
3189 "bid": D("0.00003"),
3192 if symbol
== "BTD/BTC":
3194 "symbol": "BTD/BTC",
3198 if symbol
== "B2X/BTC":
3200 "symbol": "B2X/BTC",
3204 if symbol
== "USDT/BTC":
3205 raise helper
.ExchangeError
3206 if symbol
== "BTC/USDT":
3208 "symbol": "BTC/USDT",
3212 self
.fail("Shouldn't have been called with {}".format(symbol
))
3214 market
= mock
.Mock()
3215 market
.fetch_all_balances
.return_value
= fetch_balance
3216 market
.fetch_ticker
.side_effect
= fetch_ticker
3217 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3219 helper
.prepare_trades(market
)
3221 balances
= portfolio
.BalanceStore
.all
3222 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
3223 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3224 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
3227 trades
= portfolio
.TradeStore
.all
3228 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3229 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3230 self
.assertEqual("dispose", trades
[0].action
)
3232 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3233 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3234 self
.assertEqual("acquire", trades
[1].action
)
3236 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3237 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3238 self
.assertEqual("dispose", trades
[2].action
)
3240 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3241 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3242 self
.assertEqual("acquire", trades
[3].action
)
3244 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3245 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3246 self
.assertEqual("acquire", trades
[4].action
)
3248 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3249 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3250 self
.assertEqual("acquire", trades
[5].action
)
3253 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
3255 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3256 self
.assertEqual(2, len(all_orders
))
3257 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
3258 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
3259 self
.assertEqual(1000, all_orders
[1].amount
.value
)
3260 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
3263 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
3264 self
.assertEqual("limit", type)
3265 if symbol
== "ETH/BTC":
3266 self
.assertEqual("sell", action
)
3267 self
.assertEqual(D('0.66666666'), amount
)
3268 self
.assertEqual(D("0.14014"), price
)
3269 elif symbol
== "XVG/BTC":
3270 self
.assertEqual("sell", action
)
3271 self
.assertEqual(1000, amount
)
3272 self
.assertEqual(D("0.00003003"), price
)
3274 self
.fail("I shouldn't have been called")
3279 market
.create_order
.side_effect
= create_order
3280 market
.order_precision
.return_value
= 8
3283 portfolio
.TradeStore
.run_orders()
3285 self
.assertEqual("open", all_orders
[0].status
)
3286 self
.assertEqual("open", all_orders
[1].status
)
3288 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
3289 market
.privatePostReturnOrderTrades
.return_value
= [
3291 "tradeID": 42, "type": "buy", "fee": "0.0015",
3292 "date": "2017-12-30 12:00:12", "rate": "0.1",
3293 "amount": "10", "total": "1"
3296 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3298 helper
.follow_orders(verbose
=False)
3300 sleep
.assert_called_with(30)
3302 for order
in all_orders
:
3303 self
.assertEqual("closed", order
.status
)
3307 "exchange_free": D("1.0") / 3,
3308 "exchange_used": D("0.0"),
3309 "exchange_total": D("1.0") / 3,
3311 "total": D("1.0") / 3,
3314 "exchange_free": D("0.134"),
3315 "exchange_used": D("0.0"),
3316 "exchange_total": D("0.134"),
3318 "total": D("0.134"),
3321 "exchange_free": D("4.0"),
3322 "exchange_used": D("0.0"),
3323 "exchange_total": D("4.0"),
3328 "exchange_free": D("0.0"),
3329 "exchange_used": D("0.0"),
3330 "exchange_total": D("0.0"),
3335 market
.fetch_all_balances
.return_value
= fetch_balance
3337 with mock
.patch
.object(portfolio
.Portfolio
, "repartition", return_value
=repartition
):
3339 helper
.update_trades(market
, only
="acquire", compute_value
="average")
3341 balances
= portfolio
.BalanceStore
.all
3342 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
3343 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
3344 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
3345 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
3348 trades
= portfolio
.TradeStore
.all
3349 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
3350 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
3351 self
.assertEqual("dispose", trades
[0].action
)
3353 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
3354 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
3355 self
.assertEqual("acquire", trades
[1].action
)
3357 self
.assertNotIn("BTC", trades
)
3359 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
3360 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
3361 self
.assertEqual("dispose", trades
[2].action
)
3363 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
3364 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
3365 self
.assertEqual("acquire", trades
[3].action
)
3367 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
3368 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
3369 self
.assertEqual("acquire", trades
[4].action
)
3371 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
3372 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
3373 self
.assertEqual("acquire", trades
[5].action
)
3376 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
3378 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
3379 self
.assertEqual(4, len(all_orders
))
3380 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
3381 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
3382 self
.assertEqual("buy", all_orders
[0].action
)
3383 self
.assertEqual("long", all_orders
[0].trade_type
)
3385 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
3386 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
3387 self
.assertEqual("sell", all_orders
[1].action
)
3388 self
.assertEqual("short", all_orders
[1].trade_type
)
3390 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
3391 self
.assertAlmostEqual(0, diff
.value
)
3392 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
3393 self
.assertEqual("buy", all_orders
[2].action
)
3394 self
.assertEqual("long", all_orders
[2].trade_type
)
3396 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
3397 self
.assertEqual(D("16000"), all_orders
[3].rate
)
3398 self
.assertEqual("sell", all_orders
[3].action
)
3399 self
.assertEqual("long", all_orders
[3].trade_type
)
3403 # Move balances to margin
3407 # portfolio.TradeStore.run_orders()
3409 with mock
.patch
.object(portfolio
.time
, "sleep") as sleep
:
3411 helper
.follow_orders(verbose
=False)
3413 sleep
.assert_called_with(30)
3415 if __name__
== '__main__':