5 from decimal
import Decimal
as D
6 from unittest
import mock
9 from io
import StringIO
11 import portfolio
, market
, main
, store
13 limits
= ["acceptance", "unit"]
14 for test_type
in limits
:
15 if "--no{}".format(test_type
) in sys
.argv
:
16 sys
.argv
.remove("--no{}".format(test_type
))
17 limits
.remove(test_type
)
18 if "--only{}".format(test_type
) in sys
.argv
:
19 sys
.argv
.remove("--only{}".format(test_type
))
23 class WebMockTestCase(unittest
.TestCase
):
26 def market_args(self
, debug
=False, quiet
=False):
27 return type('Args', (object,), { "debug": debug, "quiet": quiet }
)()
30 super(WebMockTestCase
, self
).setUp()
31 self
.wm
= requests_mock
.Mocker()
35 self
.m
= mock
.Mock(name
="Market", spec
=market
.Market
)
39 mock
.patch
.multiple(market
.Portfolio
,
40 data
=store
.LockedVar(None),
41 liquidities
=store
.LockedVar({}),
42 last_date
=store
.LockedVar(None),
48 mock
.patch
.multiple(portfolio
.Computation
,
49 computations
=portfolio
.Computation
.computations
),
51 for patcher
in self
.patchers
:
55 for patcher
in self
.patchers
:
58 super(WebMockTestCase
, self
).tearDown()
60 @unittest.skipUnless("unit" in limits
, "Unit skipped")
61 class poloniexETest(unittest
.TestCase
):
63 super(poloniexETest
, self
).setUp()
64 self
.wm
= requests_mock
.Mocker()
67 self
.s
= market
.ccxt
.poloniexE()
71 super(poloniexETest
, self
).tearDown()
74 with mock
.patch("market.ccxt.poloniexE.session") as session
:
75 session
.request
.return_value
= "response"
76 ccxt
= market
.ccxt
.poloniexE()
77 ccxt
._market
= mock
.Mock
78 ccxt
._market
.report
= mock
.Mock()
80 ccxt
.session
.request("GET", "URL", data
="data",
82 ccxt
._market
.report
.log_http_request
.assert_called_with('GET', 'URL', 'data',
83 'headers', 'response')
85 def test_nanoseconds(self
):
86 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
87 time
.return_value
= 123456.7890123456
88 self
.assertEqual(123456789012345, self
.s
.nanoseconds())
91 with mock
.patch
.object(market
.ccxt
.time
, "time") as time
:
92 time
.return_value
= 123456.7890123456
93 self
.assertEqual(123456789012345, self
.s
.nonce())
95 def test_request(self
):
96 with mock
.patch
.object(market
.ccxt
.poloniex
, "request") as request
,\
97 mock
.patch("market.ccxt.retry_call") as retry_call
:
98 with self
.subTest(wrapped
=True):
99 with self
.subTest(desc
="public"):
100 self
.s
.request("foo")
101 retry_call
.assert_called_with(request
,
102 delay
=1, tries
=10, fargs
=["foo"],
103 fkwargs
={'api': 'public', 'method': 'GET', 'params': {}
, 'headers': None, 'body': None},
104 exceptions
=(market
.ccxt
.RequestTimeout
, market
.ccxt
.InvalidNonce
))
105 request
.assert_not_called()
107 with self
.subTest(desc
="private GET"):
108 self
.s
.request("foo", api
="private")
109 retry_call
.assert_called_with(request
,
110 delay
=1, tries
=10, fargs
=["foo"],
111 fkwargs
={'api': 'private', 'method': 'GET', 'params': {}
, 'headers': None, 'body': None},
112 exceptions
=(market
.ccxt
.RequestTimeout
, market
.ccxt
.InvalidNonce
))
113 request
.assert_not_called()
115 with self
.subTest(desc
="private POST regexp"):
116 self
.s
.request("returnFoo", api
="private", method
="POST")
117 retry_call
.assert_called_with(request
,
118 delay
=1, tries
=10, fargs
=["returnFoo"],
119 fkwargs
={'api': 'private', 'method': 'POST', 'params': {}
, 'headers': None, 'body': None},
120 exceptions
=(market
.ccxt
.RequestTimeout
, market
.ccxt
.InvalidNonce
))
121 request
.assert_not_called()
123 with self
.subTest(desc
="private POST non-regexp"):
124 self
.s
.request("getMarginPosition", api
="private", method
="POST")
125 retry_call
.assert_called_with(request
,
126 delay
=1, tries
=10, fargs
=["getMarginPosition"],
127 fkwargs
={'api': 'private', 'method': 'POST', 'params': {}
, 'headers': None, 'body': None},
128 exceptions
=(market
.ccxt
.RequestTimeout
, market
.ccxt
.InvalidNonce
))
129 request
.assert_not_called()
130 retry_call
.reset_mock()
132 with self
.subTest(wrapped
=False):
133 with self
.subTest(desc
="private POST non-matching regexp"):
134 self
.s
.request("marginBuy", api
="private", method
="POST")
135 request
.assert_called_with("marginBuy",
136 api
="private", method
="POST", params
={},
137 headers
=None, body
=None)
138 retry_call
.assert_not_called()
140 with self
.subTest(desc
="private POST non-matching non-regexp"):
141 self
.s
.request("closeMarginPositionOther", api
="private", method
="POST")
142 request
.assert_called_with("closeMarginPositionOther",
143 api
="private", method
="POST", params
={},
144 headers
=None, body
=None)
145 retry_call
.assert_not_called()
147 def test_order_precision(self
):
148 self
.assertEqual(8, self
.s
.order_precision("FOO"))
150 def test_transfer_balance(self
):
151 with self
.subTest(success
=True),\
152 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
153 t
.return_value
= { "success": 1 }
154 result
= self
.s
.transfer_balance("FOO", 12, "exchange", "margin")
155 t
.assert_called_once_with({
158 "fromAccount": "exchange",
159 "toAccount": "margin",
162 self
.assertTrue(result
)
164 with self
.subTest(success
=False),\
165 mock
.patch
.object(self
.s
, "privatePostTransferBalance") as t
:
166 t
.return_value
= { "success": 0 }
167 self
.assertFalse(self
.s
.transfer_balance("FOO", 12, "exchange", "margin"))
169 def test_close_margin_position(self
):
170 with mock
.patch
.object(self
.s
, "privatePostCloseMarginPosition") as c
:
171 self
.s
.close_margin_position("FOO", "BAR")
172 c
.assert_called_with({"currencyPair": "BAR_FOO"}
)
174 def test_tradable_balances(self
):
175 with mock
.patch
.object(self
.s
, "privatePostReturnTradableBalances") as r
:
177 "FOO": { "exchange": "12.1234", "margin": "0.0123" }
,
178 "BAR": { "exchange": "1", "margin": "0" }
,
180 balances
= self
.s
.tradable_balances()
181 self
.assertEqual(["FOO", "BAR"], list(balances
.keys()))
182 self
.assertEqual(["exchange", "margin"], list(balances
["FOO"].keys()))
183 self
.assertEqual(D("12.1234"), balances
["FOO"]["exchange"])
184 self
.assertEqual(["exchange", "margin"], list(balances
["BAR"].keys()))
186 def test_margin_summary(self
):
187 with mock
.patch
.object(self
.s
, "privatePostReturnMarginAccountSummary") as r
:
189 "currentMargin": "1.49680968",
190 "lendingFees": "0.0000001",
192 "totalBorrowedValue": "0.00673602",
193 "totalValue": "0.01000000",
194 "netValue": "0.01008254",
197 'current_margin': D('1.49680968'),
198 'gains': D('0.00008254'),
199 'lending_fees': D('0.0000001'),
200 'total': D('0.01000000'),
201 'total_borrowed': D('0.00673602')
203 self
.assertEqual(expected
, self
.s
.margin_summary())
205 def test_create_order(self
):
206 with mock
.patch
.object(self
.s
, "create_exchange_order") as exchange
,\
207 mock
.patch
.object(self
.s
, "create_margin_order") as margin
:
208 with self
.subTest(account
="unspecified"):
209 self
.s
.create_order("symbol", "type", "side", "amount", price
="price", lending_rate
="lending_rate", params
="params")
210 exchange
.assert_called_once_with("symbol", "type", "side", "amount", price
="price", params
="params")
211 margin
.assert_not_called()
212 exchange
.reset_mock()
215 with self
.subTest(account
="exchange"):
216 self
.s
.create_order("symbol", "type", "side", "amount", account
="exchange", price
="price", lending_rate
="lending_rate", params
="params")
217 exchange
.assert_called_once_with("symbol", "type", "side", "amount", price
="price", params
="params")
218 margin
.assert_not_called()
219 exchange
.reset_mock()
222 with self
.subTest(account
="margin"):
223 self
.s
.create_order("symbol", "type", "side", "amount", account
="margin", price
="price", lending_rate
="lending_rate", params
="params")
224 margin
.assert_called_once_with("symbol", "type", "side", "amount", lending_rate
="lending_rate", price
="price", params
="params")
225 exchange
.assert_not_called()
226 exchange
.reset_mock()
229 with self
.subTest(account
="unknown"), self
.assertRaises(NotImplementedError):
230 self
.s
.create_order("symbol", "type", "side", "amount", account
="unknown")
232 def test_parse_ticker(self
):
236 "highestBid": "10.5",
239 "percentChange": "0.1",
246 with mock
.patch
.object(self
.s
, "milliseconds") as ms
:
247 ms
.return_value
= 1520292715123
248 result
= self
.s
.parse_ticker(ticker
, market
)
252 "timestamp": 1520292715123,
253 "datetime": "2018-03-05T23:31:55.123Z",
266 "baseVolume": D("10"),
267 "quoteVolume": D("20"),
270 self
.assertEqual(expected
, result
)
272 def test_fetch_margin_balance(self
):
273 with mock
.patch
.object(self
.s
, "privatePostGetMarginPosition") as get_margin_position
:
274 get_margin_position
.return_value
= {
277 "basePrice": "0.06818560",
278 "lendingFees": "0.00000001",
279 "liquidationPrice": "0.15107132",
281 "total": "0.00681856",
287 "lendingFees": "0.00000001",
288 "liquidationPrice": "0.6",
297 "liquidationPrice": "-1",
303 balances
= self
.s
.fetch_margin_balance()
304 self
.assertEqual(2, len(balances
))
308 "borrowedPrice": D("0.06818560"),
309 "lendingFees": D("1E-8"),
310 "pl": D("-0.00000371"),
311 "liquidationPrice": D("0.15107132"),
313 "total": D("0.00681856"),
314 "baseCurrency": "BTC"
318 "borrowedPrice": D("0.1"),
319 "lendingFees": D("1E-8"),
320 "pl": D("0.00000371"),
321 "liquidationPrice": D("0.6"),
324 "baseCurrency": "BTC"
327 self
.assertEqual(expected
, balances
)
330 self
.assertEqual(D("1.1"), self
.s
.sum(D("1"), D("0.1")))
332 def test_fetch_balance(self
):
333 with mock
.patch
.object(self
.s
, "load_markets") as load_markets
,\
334 mock
.patch
.object(self
.s
, "privatePostReturnCompleteBalances") as balances
,\
335 mock
.patch
.object(self
.s
, "common_currency_code") as ccc
:
336 ccc
.side_effect
= ["ETH", "BTC", "DASH"]
337 balances
.return_value
= {
354 "ETH": {"available": "10", "onOrders": "1"}
,
355 "BTC": {"available": "1", "onOrders": "0"}
,
356 "DASH": {"available": "0", "onOrders": "3"}
358 "ETH": {"free": D("10"), "used": D("1"), "total": D("11")}
,
359 "BTC": {"free": D("1"), "used": D("0"), "total": D("1")}
,
360 "DASH": {"free": D("0"), "used": D("3"), "total": D("3")}
,
361 "free": {"ETH": D("10"), "BTC": D("1"), "DASH": D("0")}
,
362 "used": {"ETH": D("1"), "BTC": D("0"), "DASH": D("3")}
,
363 "total": {"ETH": D("11"), "BTC": D("1"), "DASH": D("3")}
365 result
= self
.s
.fetch_balance()
366 load_markets
.assert_called_once()
367 self
.assertEqual(expected
, result
)
369 def test_fetch_balance_per_type(self
):
370 with mock
.patch
.object(self
.s
, "privatePostReturnAvailableAccountBalances") as balances
:
371 balances
.return_value
= {
373 "BLK": "159.83673869",
375 "USDT": "0.00002625",
385 "BLK": "159.83673869",
387 "USDT": "0.00002625",
395 "BLK": D("159.83673869"),
396 "BTC": D("0.00005959"),
397 "USDT": D("0.00002625"),
398 "XMR": D("0.18719303")
400 "margin": {"BTC": D("0.03019227")}
,
401 "BLK": {"exchange": D("159.83673869")}
,
402 "BTC": {"exchange": D("0.00005959"), "margin": D("0.03019227")}
,
403 "USDT": {"exchange": D("0.00002625")}
,
404 "XMR": {"exchange": D("0.18719303")}
406 result
= self
.s
.fetch_balance_per_type()
407 self
.assertEqual(expected
, result
)
409 def test_fetch_all_balances(self
):
411 with mock
.patch
.object(self
.s
, "load_markets") as load_markets
,\
412 mock
.patch
.object(self
.s
, "privatePostGetMarginPosition") as margin_balance
,\
413 mock
.patch
.object(self
.s
, "privatePostReturnCompleteBalances") as balance
,\
414 mock
.patch
.object(self
.s
, "privatePostReturnAvailableAccountBalances") as balance_per_type
:
416 with open("test_samples/poloniexETest.test_fetch_all_balances.1.json") as f
:
417 balance
.return_value
= json
.load(f
)
418 with open("test_samples/poloniexETest.test_fetch_all_balances.2.json") as f
:
419 margin_balance
.return_value
= json
.load(f
)
420 with open("test_samples/poloniexETest.test_fetch_all_balances.3.json") as f
:
421 balance_per_type
.return_value
= json
.load(f
)
423 result
= self
.s
.fetch_all_balances()
425 "total": D("-12779.79821852"),
426 "exchange_used": D("0E-8"),
427 "exchange_total": D("0E-8"),
428 "exchange_free": D("0E-8"),
429 "margin_available": 0,
430 "margin_in_position": 0,
431 "margin_borrowed": D("12779.79821852"),
432 "margin_total": D("-12779.79821852"),
433 "margin_pending_gain": 0,
434 "margin_lending_fees": D("-9E-8"),
435 "margin_pending_base_gain": D("0.00024059"),
436 "margin_position_type": "short",
437 "margin_liquidation_price": D("0.00000246"),
438 "margin_borrowed_base_price": D("0.00599149"),
439 "margin_borrowed_base_currency": "BTC"
441 expected_btc
= {"total": D("0.05432165"),
442 "exchange_used": D("0E-8"),
443 "exchange_total": D("0.00005959"),
444 "exchange_free": D("0.00005959"),
445 "margin_available": D("0.03019227"),
446 "margin_in_position": D("0.02406979"),
447 "margin_borrowed": 0,
448 "margin_total": D("0.05426206"),
449 "margin_pending_gain": D("0.00093955"),
450 "margin_lending_fees": 0,
451 "margin_pending_base_gain": 0,
452 "margin_position_type": None,
453 "margin_liquidation_price": 0,
454 "margin_borrowed_base_price": 0,
455 "margin_borrowed_base_currency": None
457 expected_xmr
= {"total": D("0.18719303"),
458 "exchange_used": D("0E-8"),
459 "exchange_total": D("0.18719303"),
460 "exchange_free": D("0.18719303"),
461 "margin_available": 0,
462 "margin_in_position": 0,
463 "margin_borrowed": 0,
465 "margin_pending_gain": 0,
466 "margin_lending_fees": 0,
467 "margin_pending_base_gain": 0,
468 "margin_position_type": None,
469 "margin_liquidation_price": 0,
470 "margin_borrowed_base_price": 0,
471 "margin_borrowed_base_currency": None
473 self
.assertEqual(expected_xmr
, result
["XMR"])
474 self
.assertEqual(expected_doge
, result
["DOGE"])
475 self
.assertEqual(expected_btc
, result
["BTC"])
477 def test_create_margin_order(self
):
478 with self
.assertRaises(market
.ExchangeError
):
479 self
.s
.create_margin_order("FOO", "market", "buy", "10")
481 with mock
.patch
.object(self
.s
, "load_markets") as load_markets
,\
482 mock
.patch
.object(self
.s
, "privatePostMarginBuy") as margin_buy
,\
483 mock
.patch
.object(self
.s
, "privatePostMarginSell") as margin_sell
,\
484 mock
.patch
.object(self
.s
, "market") as market_mock
,\
485 mock
.patch
.object(self
.s
, "price_to_precision") as ptp
,\
486 mock
.patch
.object(self
.s
, "amount_to_precision") as atp
:
488 margin_buy
.return_value
= {
491 margin_sell
.return_value
= {
494 market_mock
.return_value
= { "id": "BTC_ETC", "symbol": "BTC_ETC" }
495 ptp
.return_value
= D("0.1")
496 atp
.return_value
= D("12")
498 order
= self
.s
.create_margin_order("BTC_ETC", "margin", "buy", "12", price
="0.1")
499 self
.assertEqual(123, order
["id"])
500 margin_buy
.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12")}
)
501 margin_sell
.assert_not_called()
502 margin_buy
.reset_mock()
503 margin_sell
.reset_mock()
505 order
= self
.s
.create_margin_order("BTC_ETC", "margin", "sell", "12", lending_rate
="0.01", price
="0.1")
506 self
.assertEqual(456, order
["id"])
507 margin_sell
.assert_called_once_with({"currencyPair": "BTC_ETC", "rate": D("0.1"), "amount": D("12"), "lendingRate": "0.01"}
)
508 margin_buy
.assert_not_called()
510 def test_create_exchange_order(self
):
511 with mock
.patch
.object(market
.ccxt
.poloniex
, "create_order") as create_order
:
512 self
.s
.create_order("symbol", "type", "side", "amount", price
="price", params
="params")
514 create_order
.assert_called_once_with("symbol", "type", "side", "amount", price
="price", params
="params")
516 @unittest.skipUnless("unit" in limits
, "Unit skipped")
517 class NoopLockTest(unittest
.TestCase
):
519 noop_lock
= store
.NoopLock()
521 self
.assertTrue(True)
523 @unittest.skipUnless("unit" in limits
, "Unit skipped")
524 class LockedVar(unittest
.TestCase
):
526 def test_values(self
):
527 locked_var
= store
.LockedVar("Foo")
528 self
.assertIsInstance(locked_var
.lock
, store
.NoopLock
)
529 self
.assertEqual("Foo", locked_var
.val
)
532 with self
.subTest(desc
="Normal case"):
533 locked_var
= store
.LockedVar("Foo")
534 self
.assertEqual("Foo", locked_var
.get())
535 with self
.subTest(desc
="Dict"):
536 locked_var
= store
.LockedVar({"foo": "bar"}
)
537 self
.assertEqual({"foo": "bar"}
, locked_var
.get())
538 self
.assertEqual("bar", locked_var
.get("foo"))
539 self
.assertIsNone(locked_var
.get("other"))
542 locked_var
= store
.LockedVar("Foo")
543 locked_var
.set("Bar")
544 self
.assertEqual("Bar", locked_var
.get())
546 def test__getattr(self
):
547 dummy
= type('Dummy', (object,), {})()
548 dummy
.attribute
= "Hey"
550 locked_var
= store
.LockedVar(dummy
)
551 self
.assertEqual("Hey", locked_var
.attribute
)
552 with self
.assertRaises(AttributeError):
555 def test_start_lock(self
):
556 locked_var
= store
.LockedVar("Foo")
557 locked_var
.start_lock()
558 self
.assertEqual("lock", locked_var
.lock
.__class
__.__name
__)
560 thread1
= threading
.Thread(target
=locked_var
.set, args
=["Bar1"])
561 thread2
= threading
.Thread(target
=locked_var
.set, args
=["Bar2"])
562 thread3
= threading
.Thread(target
=locked_var
.set, args
=["Bar3"])
564 with locked_var
.lock
:
569 self
.assertEqual("Foo", locked_var
.val
)
573 self
.assertEqual("Bar", locked_var
.get()[0:3])
575 def test_wait_for_notification(self
):
576 with self
.assertRaises(RuntimeError):
577 store
.Portfolio
.wait_for_notification()
579 with mock
.patch
.object(store
.Portfolio
, "get_cryptoportfolio") as get
,\
580 mock
.patch
.object(store
.Portfolio
, "report") as report
,\
581 mock
.patch
.object(store
.time
, "sleep") as sleep
:
582 store
.Portfolio
.start_worker(poll
=3)
584 store
.Portfolio
.worker_notify
.set()
586 store
.Portfolio
.callback
.wait()
588 report
.print_log
.assert_called_once_with("Fetching cryptoportfolio")
589 get
.assert_called_once_with(refetch
=True)
590 sleep
.assert_called_once_with(3)
591 self
.assertFalse(store
.Portfolio
.worker_notify
.is_set())
592 self
.assertTrue(store
.Portfolio
.worker
.is_alive())
594 store
.Portfolio
.callback
.clear()
595 store
.Portfolio
.worker_started
= False
596 store
.Portfolio
.worker_notify
.set()
597 store
.Portfolio
.callback
.wait()
599 self
.assertFalse(store
.Portfolio
.worker
.is_alive())
601 def test_notify_and_wait(self
):
602 with mock
.patch
.object(store
.Portfolio
, "callback") as callback
,\
603 mock
.patch
.object(store
.Portfolio
, "worker_notify") as worker_notify
:
604 store
.Portfolio
.notify_and_wait()
605 callback
.clear
.assert_called_once_with()
606 worker_notify
.set.assert_called_once_with()
607 callback
.wait
.assert_called_once_with()
609 @unittest.skipUnless("unit" in limits
, "Unit skipped")
610 class PortfolioTest(WebMockTestCase
):
612 super(PortfolioTest
, self
).setUp()
614 with open("test_samples/test_portfolio.json") as example
:
615 self
.json_response
= example
.read()
617 self
.wm
.get(market
.Portfolio
.URL
, text
=self
.json_response
)
619 @mock.patch.object(market
.Portfolio
, "parse_cryptoportfolio")
620 def test_get_cryptoportfolio(self
, parse_cryptoportfolio
):
621 with self
.subTest(parallel
=False):
622 self
.wm
.get(market
.Portfolio
.URL
, [
623 {"text":'{ "foo": "bar" }
', "status_code": 200},
624 {"text": "System Error", "status_code": 500},
625 {"exc": requests.exceptions.ConnectTimeout},
627 market.Portfolio.get_cryptoportfolio()
628 self.assertIn("foo", market.Portfolio.data.get())
629 self.assertEqual("bar", market.Portfolio.data.get()["foo"])
630 self.assertTrue(self.wm.called)
631 self.assertEqual(1, self.wm.call_count)
632 market.Portfolio.report.log_error.assert_not_called()
633 market.Portfolio.report.log_http_request.assert_called_once()
634 parse_cryptoportfolio.assert_called_once_with()
635 market.Portfolio.report.log_http_request.reset_mock()
636 parse_cryptoportfolio.reset_mock()
637 market.Portfolio.data = store.LockedVar(None)
639 market.Portfolio.get_cryptoportfolio()
640 self.assertIsNone(market.Portfolio.data.get())
641 self.assertEqual(2, self.wm.call_count)
642 parse_cryptoportfolio.assert_not_called()
643 market.Portfolio.report.log_error.assert_not_called()
644 market.Portfolio.report.log_http_request.assert_called_once()
645 market.Portfolio.report.log_http_request.reset_mock()
646 parse_cryptoportfolio.reset_mock()
648 market.Portfolio.data = store.LockedVar("Foo")
649 market.Portfolio.get_cryptoportfolio()
650 self.assertEqual(2, self.wm.call_count)
651 parse_cryptoportfolio.assert_not_called()
653 market.Portfolio.get_cryptoportfolio(refetch=True)
654 self.assertEqual("Foo", market.Portfolio.data.get())
655 self.assertEqual(3, self.wm.call_count)
656 market.Portfolio.report.log_error.assert_called_once_with("get_cryptoportfolio",
658 market.Portfolio.report.log_http_request.assert_not_called()
659 with self.subTest(parallel=True):
660 with mock.patch.object(market.Portfolio, "is_worker_thread") as is_worker,\
661 mock.patch.object(market.Portfolio, "notify_and_wait") as notify:
662 with self.subTest(worker=True):
663 market.Portfolio.data = store.LockedVar(None)
664 market.Portfolio.worker = mock.Mock()
665 is_worker.return_value = True
666 self.wm.get(market.Portfolio.URL, [
667 {"text":'{ "foo": "bar" }', "status_code": 200},
669 market
.Portfolio
.get_cryptoportfolio()
670 self
.assertIn("foo", market
.Portfolio
.data
.get())
671 parse_cryptoportfolio
.reset_mock()
672 with self
.subTest(worker
=False):
673 market
.Portfolio
.data
= store
.LockedVar(None)
674 market
.Portfolio
.worker
= mock
.Mock()
675 is_worker
.return_value
= False
676 market
.Portfolio
.get_cryptoportfolio()
677 notify
.assert_called_once_with()
678 parse_cryptoportfolio
.assert_not_called()
680 def test_parse_cryptoportfolio(self
):
681 with self
.subTest(description
="Normal case"):
682 market
.Portfolio
.data
= store
.LockedVar(store
.json
.loads(
683 self
.json_response
, parse_int
=D
, parse_float
=D
))
684 market
.Portfolio
.parse_cryptoportfolio()
686 self
.assertListEqual(
688 list(market
.Portfolio
.liquidities
.get().keys()))
690 liquidities
= market
.Portfolio
.liquidities
.get()
691 self
.assertEqual(10, len(liquidities
["medium"].keys()))
692 self
.assertEqual(10, len(liquidities
["high"].keys()))
695 'BTC': (D("0.2857"), "long"),
696 'DGB': (D("0.1015"), "long"),
697 'DOGE': (D("0.1805"), "long"),
698 'SC': (D("0.0623"), "long"),
699 'ZEC': (D("0.3701"), "long"),
701 date
= portfolio
.datetime(2018, 1, 8)
702 self
.assertDictEqual(expected
, liquidities
["high"][date
])
705 'BTC': (D("1.1102e-16"), "long"),
706 'ETC': (D("0.1"), "long"),
707 'FCT': (D("0.1"), "long"),
708 'GAS': (D("0.1"), "long"),
709 'NAV': (D("0.1"), "long"),
710 'OMG': (D("0.1"), "long"),
711 'OMNI': (D("0.1"), "long"),
712 'PPC': (D("0.1"), "long"),
713 'RIC': (D("0.1"), "long"),
714 'VIA': (D("0.1"), "long"),
715 'XCP': (D("0.1"), "long"),
717 self
.assertDictEqual(expected
, liquidities
["medium"][date
])
718 self
.assertEqual(portfolio
.datetime(2018, 1, 15), market
.Portfolio
.last_date
.get())
720 with self
.subTest(description
="Missing weight"):
721 data
= store
.json
.loads(self
.json_response
, parse_int
=D
, parse_float
=D
)
722 del(data
["portfolio_2"]["weights"])
723 market
.Portfolio
.data
= store
.LockedVar(data
)
725 market
.Portfolio
.parse_cryptoportfolio()
726 self
.assertListEqual(
728 list(market
.Portfolio
.liquidities
.get().keys()))
729 self
.assertEqual({}, market
.Portfolio
.liquidities
.get("medium"))
731 with self
.subTest(description
="All missing weights"):
732 data
= store
.json
.loads(self
.json_response
, parse_int
=D
, parse_float
=D
)
733 del(data
["portfolio_1"]["weights"])
734 del(data
["portfolio_2"]["weights"])
735 market
.Portfolio
.data
= store
.LockedVar(data
)
737 market
.Portfolio
.parse_cryptoportfolio()
738 self
.assertEqual({}, market
.Portfolio
.liquidities
.get("medium"))
739 self
.assertEqual({}, market
.Portfolio
.liquidities
.get("high"))
740 self
.assertEqual(datetime
.datetime(1,1,1), market
.Portfolio
.last_date
.get())
743 @mock.patch.object(market
.Portfolio
, "get_cryptoportfolio")
744 def test_repartition(self
, get_cryptoportfolio
):
745 market
.Portfolio
.liquidities
= store
.LockedVar({
747 "2018-03-01": "medium_2018-03-01",
748 "2018-03-08": "medium_2018-03-08",
751 "2018-03-01": "high_2018-03-01",
752 "2018-03-08": "high_2018-03-08",
755 market
.Portfolio
.last_date
= store
.LockedVar("2018-03-08")
757 self
.assertEqual("medium_2018-03-08", market
.Portfolio
.repartition())
758 get_cryptoportfolio
.assert_called_once_with()
759 self
.assertEqual("medium_2018-03-08", market
.Portfolio
.repartition(liquidity
="medium"))
760 self
.assertEqual("high_2018-03-08", market
.Portfolio
.repartition(liquidity
="high"))
762 @mock.patch.object(market
.time
, "sleep")
763 @mock.patch.object(market
.Portfolio
, "get_cryptoportfolio")
764 def test_wait_for_recent(self
, get_cryptoportfolio
, sleep
):
766 def _get(refetch
=False):
767 if self
.call_count
!= 0:
768 self
.assertTrue(refetch
)
770 self
.assertFalse(refetch
)
772 market
.Portfolio
.last_date
= store
.LockedVar(store
.datetime
.now()\
773 - store
.timedelta(10)\
774 + store
.timedelta(self
.call_count
))
775 get_cryptoportfolio
.side_effect
= _get
777 market
.Portfolio
.wait_for_recent()
778 sleep
.assert_called_with(30)
779 self
.assertEqual(6, sleep
.call_count
)
780 self
.assertEqual(7, get_cryptoportfolio
.call_count
)
781 market
.Portfolio
.report
.print_log
.assert_called_with("Attempt to fetch up-to-date cryptoportfolio")
784 get_cryptoportfolio
.reset_mock()
785 market
.Portfolio
.last_date
= store
.LockedVar(None)
787 market
.Portfolio
.wait_for_recent(delta
=15)
788 sleep
.assert_not_called()
789 self
.assertEqual(1, get_cryptoportfolio
.call_count
)
792 get_cryptoportfolio
.reset_mock()
793 market
.Portfolio
.last_date
= store
.LockedVar(None)
795 market
.Portfolio
.wait_for_recent(delta
=1)
796 sleep
.assert_called_with(30)
797 self
.assertEqual(9, sleep
.call_count
)
798 self
.assertEqual(10, get_cryptoportfolio
.call_count
)
800 def test_is_worker_thread(self
):
801 with self
.subTest(worker
=None):
802 self
.assertFalse(store
.Portfolio
.is_worker_thread())
804 with self
.subTest(worker
="not self"),\
805 mock
.patch("threading.current_thread") as current_thread
:
806 current
= mock
.Mock()
807 current_thread
.return_value
= current
808 store
.Portfolio
.worker
= mock
.Mock()
809 self
.assertFalse(store
.Portfolio
.is_worker_thread())
811 with self
.subTest(worker
="self"),\
812 mock
.patch("threading.current_thread") as current_thread
:
813 current
= mock
.Mock()
814 current_thread
.return_value
= current
815 store
.Portfolio
.worker
= current
816 self
.assertTrue(store
.Portfolio
.is_worker_thread())
818 def test_start_worker(self
):
819 with mock
.patch
.object(store
.Portfolio
, "wait_for_notification") as notification
:
820 store
.Portfolio
.start_worker()
821 notification
.assert_called_once_with(poll
=30)
823 self
.assertEqual("lock", store
.Portfolio
.last_date
.lock
.__class
__.__name
__)
824 self
.assertEqual("lock", store
.Portfolio
.liquidities
.lock
.__class
__.__name
__)
825 store
.Portfolio
.report
.start_lock
.assert_called_once_with()
827 self
.assertIsNotNone(store
.Portfolio
.worker
)
828 self
.assertIsNotNone(store
.Portfolio
.worker_notify
)
829 self
.assertIsNotNone(store
.Portfolio
.callback
)
830 self
.assertTrue(store
.Portfolio
.worker_started
)
832 @unittest.skipUnless("unit" in limits
, "Unit skipped")
833 class AmountTest(WebMockTestCase
):
834 def test_values(self
):
835 amount
= portfolio
.Amount("BTC", "0.65")
836 self
.assertEqual(D("0.65"), amount
.value
)
837 self
.assertEqual("BTC", amount
.currency
)
839 def test_in_currency(self
):
840 amount
= portfolio
.Amount("ETC", 10)
842 self
.assertEqual(amount
, amount
.in_currency("ETC", self
.m
))
844 with self
.subTest(desc
="no ticker for currency"):
845 self
.m
.get_ticker
.return_value
= None
847 self
.assertRaises(Exception, amount
.in_currency
, "ETH", self
.m
)
849 with self
.subTest(desc
="nominal case"):
850 self
.m
.get_ticker
.return_value
= {
856 converted_amount
= amount
.in_currency("ETH", self
.m
)
858 self
.assertEqual(D("3.0"), converted_amount
.value
)
859 self
.assertEqual("ETH", converted_amount
.currency
)
860 self
.assertEqual(amount
, converted_amount
.linked_to
)
861 self
.assertEqual("bar", converted_amount
.ticker
["foo"])
863 converted_amount
= amount
.in_currency("ETH", self
.m
, action
="bid", compute_value
="default")
864 self
.assertEqual(D("2"), converted_amount
.value
)
866 converted_amount
= amount
.in_currency("ETH", self
.m
, compute_value
="ask")
867 self
.assertEqual(D("4"), converted_amount
.value
)
869 converted_amount
= amount
.in_currency("ETH", self
.m
, rate
=D("0.02"))
870 self
.assertEqual(D("0.2"), converted_amount
.value
)
872 def test__round(self
):
873 amount
= portfolio
.Amount("BAR", portfolio
.D("1.23456789876"))
874 self
.assertEqual(D("1.23456789"), round(amount
).value
)
875 self
.assertEqual(D("1.23"), round(amount
, 2).value
)
878 amount
= portfolio
.Amount("SC", -120)
879 self
.assertEqual(120, abs(amount
).value
)
880 self
.assertEqual("SC", abs(amount
).currency
)
882 amount
= portfolio
.Amount("SC", 10)
883 self
.assertEqual(10, abs(amount
).value
)
884 self
.assertEqual("SC", abs(amount
).currency
)
887 amount1
= portfolio
.Amount("XVG", "12.9")
888 amount2
= portfolio
.Amount("XVG", "13.1")
890 self
.assertEqual(26, (amount1
+ amount2
).value
)
891 self
.assertEqual("XVG", (amount1
+ amount2
).currency
)
893 amount3
= portfolio
.Amount("ETH", "1.6")
894 with self
.assertRaises(Exception):
897 amount4
= portfolio
.Amount("ETH", 0.0)
898 self
.assertEqual(amount1
, amount1
+ amount4
)
900 self
.assertEqual(amount1
, amount1
+ 0)
902 def test__radd(self
):
903 amount
= portfolio
.Amount("XVG", "12.9")
905 self
.assertEqual(amount
, 0 + amount
)
906 with self
.assertRaises(Exception):
910 amount1
= portfolio
.Amount("XVG", "13.3")
911 amount2
= portfolio
.Amount("XVG", "13.1")
913 self
.assertEqual(D("0.2"), (amount1
- amount2
).value
)
914 self
.assertEqual("XVG", (amount1
- amount2
).currency
)
916 amount3
= portfolio
.Amount("ETH", "1.6")
917 with self
.assertRaises(Exception):
920 amount4
= portfolio
.Amount("ETH", 0.0)
921 self
.assertEqual(amount1
, amount1
- amount4
)
923 def test__rsub(self
):
924 amount
= portfolio
.Amount("ETH", "1.6")
925 with self
.assertRaises(Exception):
928 self
.assertEqual(portfolio
.Amount("ETH", "-1.6"), 0-amount
)
931 amount
= portfolio
.Amount("XEM", 11)
933 self
.assertEqual(D("38.5"), (amount
* D("3.5")).value
)
934 self
.assertEqual(D("33"), (amount
* 3).value
)
936 with self
.assertRaises(Exception):
939 def test__rmul(self
):
940 amount
= portfolio
.Amount("XEM", 11)
942 self
.assertEqual(D("38.5"), (D("3.5") * amount
).value
)
943 self
.assertEqual(D("33"), (3 * amount
).value
)
945 def test__floordiv(self
):
946 amount
= portfolio
.Amount("XEM", 11)
948 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
949 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
951 with self
.assertRaises(Exception):
954 def test__truediv(self
):
955 amount
= portfolio
.Amount("XEM", 11)
957 self
.assertEqual(D("5.5"), (amount
/ 2).value
)
958 self
.assertEqual(D("4.4"), (amount
/ D("2.5")).value
)
961 amount1
= portfolio
.Amount("BTD", 11.3)
962 amount2
= portfolio
.Amount("BTD", 13.1)
964 self
.assertTrue(amount1
< amount2
)
965 self
.assertFalse(amount2
< amount1
)
966 self
.assertFalse(amount1
< amount1
)
968 amount3
= portfolio
.Amount("BTC", 1.6)
969 with self
.assertRaises(Exception):
973 amount1
= portfolio
.Amount("BTD", 11.3)
974 amount2
= portfolio
.Amount("BTD", 13.1)
976 self
.assertTrue(amount1
<= amount2
)
977 self
.assertFalse(amount2
<= amount1
)
978 self
.assertTrue(amount1
<= amount1
)
980 amount3
= portfolio
.Amount("BTC", 1.6)
981 with self
.assertRaises(Exception):
985 amount1
= portfolio
.Amount("BTD", 11.3)
986 amount2
= portfolio
.Amount("BTD", 13.1)
988 self
.assertTrue(amount2
> amount1
)
989 self
.assertFalse(amount1
> amount2
)
990 self
.assertFalse(amount1
> amount1
)
992 amount3
= portfolio
.Amount("BTC", 1.6)
993 with self
.assertRaises(Exception):
997 amount1
= portfolio
.Amount("BTD", 11.3)
998 amount2
= portfolio
.Amount("BTD", 13.1)
1000 self
.assertTrue(amount2
>= amount1
)
1001 self
.assertFalse(amount1
>= amount2
)
1002 self
.assertTrue(amount1
>= amount1
)
1004 amount3
= portfolio
.Amount("BTC", 1.6)
1005 with self
.assertRaises(Exception):
1009 amount1
= portfolio
.Amount("BTD", 11.3)
1010 amount2
= portfolio
.Amount("BTD", 13.1)
1011 amount3
= portfolio
.Amount("BTD", 11.3)
1013 self
.assertFalse(amount1
== amount2
)
1014 self
.assertFalse(amount2
== amount1
)
1015 self
.assertTrue(amount1
== amount3
)
1016 self
.assertFalse(amount2
== 0)
1018 amount4
= portfolio
.Amount("BTC", 1.6)
1019 with self
.assertRaises(Exception):
1022 amount5
= portfolio
.Amount("BTD", 0)
1023 self
.assertTrue(amount5
== 0)
1026 amount1
= portfolio
.Amount("BTD", 11.3)
1027 amount2
= portfolio
.Amount("BTD", 13.1)
1028 amount3
= portfolio
.Amount("BTD", 11.3)
1030 self
.assertTrue(amount1
!= amount2
)
1031 self
.assertTrue(amount2
!= amount1
)
1032 self
.assertFalse(amount1
!= amount3
)
1033 self
.assertTrue(amount2
!= 0)
1035 amount4
= portfolio
.Amount("BTC", 1.6)
1036 with self
.assertRaises(Exception):
1039 amount5
= portfolio
.Amount("BTD", 0)
1040 self
.assertFalse(amount5
!= 0)
1042 def test__neg(self
):
1043 amount1
= portfolio
.Amount("BTD", "11.3")
1045 self
.assertEqual(portfolio
.D("-11.3"), (-amount1
).value
)
1047 def test__str(self
):
1048 amount1
= portfolio
.Amount("BTX", 32)
1049 self
.assertEqual("32.00000000 BTX", str(amount1
))
1051 amount2
= portfolio
.Amount("USDT", 12000)
1052 amount1
.linked_to
= amount2
1053 self
.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1
))
1055 def test__repr(self
):
1056 amount1
= portfolio
.Amount("BTX", 32)
1057 self
.assertEqual("Amount(32.00000000 BTX)", repr(amount1
))
1059 amount2
= portfolio
.Amount("USDT", 12000)
1060 amount1
.linked_to
= amount2
1061 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1
))
1063 amount3
= portfolio
.Amount("BTC", 0.1)
1064 amount2
.linked_to
= amount3
1065 self
.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1
))
1067 def test_as_json(self
):
1068 amount
= portfolio
.Amount("BTX", 32)
1069 self
.assertEqual({"currency": "BTX", "value": D("32")}
, amount
.as_json())
1071 amount
= portfolio
.Amount("BTX", "1E-10")
1072 self
.assertEqual({"currency": "BTX", "value": D("0")}
, amount
.as_json())
1074 amount
= portfolio
.Amount("BTX", "1E-5")
1075 self
.assertEqual({"currency": "BTX", "value": D("0.00001")}
, amount
.as_json())
1076 self
.assertEqual("0.00001", str(amount
.as_json()["value"]))
1078 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1079 class BalanceTest(WebMockTestCase
):
1080 def test_values(self
):
1081 balance
= portfolio
.Balance("BTC", {
1082 "exchange_total": "0.65",
1083 "exchange_free": "0.35",
1084 "exchange_used": "0.30",
1085 "margin_total": "-10",
1086 "margin_borrowed": "10",
1087 "margin_available": "0",
1088 "margin_in_position": "0",
1089 "margin_position_type": "short",
1090 "margin_borrowed_base_currency": "USDT",
1091 "margin_liquidation_price": "1.20",
1092 "margin_pending_gain": "10",
1093 "margin_lending_fees": "0.4",
1094 "margin_borrowed_base_price": "0.15",
1096 self
.assertEqual(portfolio
.D("0.65"), balance
.exchange_total
.value
)
1097 self
.assertEqual(portfolio
.D("0.35"), balance
.exchange_free
.value
)
1098 self
.assertEqual(portfolio
.D("0.30"), balance
.exchange_used
.value
)
1099 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
1100 self
.assertEqual("BTC", balance
.exchange_free
.currency
)
1101 self
.assertEqual("BTC", balance
.exchange_total
.currency
)
1103 self
.assertEqual(portfolio
.D("-10"), balance
.margin_total
.value
)
1104 self
.assertEqual(portfolio
.D("10"), balance
.margin_borrowed
.value
)
1105 self
.assertEqual(portfolio
.D("0"), balance
.margin_available
.value
)
1106 self
.assertEqual("BTC", balance
.margin_total
.currency
)
1107 self
.assertEqual("BTC", balance
.margin_borrowed
.currency
)
1108 self
.assertEqual("BTC", balance
.margin_available
.currency
)
1110 self
.assertEqual("BTC", balance
.currency
)
1112 self
.assertEqual(portfolio
.D("0.4"), balance
.margin_lending_fees
.value
)
1113 self
.assertEqual("USDT", balance
.margin_lending_fees
.currency
)
1115 def test__repr(self
):
1116 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX])",
1117 repr(portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)))
1118 balance
= portfolio
.Balance("BTX", { "exchange_total": 3,
1119 "exchange_used": 1, "exchange_free": 2 })
1120 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
1122 balance
= portfolio
.Balance("BTX", { "exchange_total": 1, "exchange_used": 1}
)
1123 self
.assertEqual("Balance(BTX Exch: [❌1.00000000 BTX])", repr(balance
))
1125 balance
= portfolio
.Balance("BTX", { "margin_total": 3,
1126 "margin_in_position": 1, "margin_available": 2 })
1127 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX + ❌1.00000000 BTX = 3.00000000 BTX])", repr(balance
))
1129 balance
= portfolio
.Balance("BTX", { "margin_total": 2, "margin_available": 2 }
)
1130 self
.assertEqual("Balance(BTX Margin: [✔2.00000000 BTX])", repr(balance
))
1132 balance
= portfolio
.Balance("BTX", { "margin_total": -3,
1133 "margin_borrowed_base_price": D("0.1"),
1134 "margin_borrowed_base_currency": "BTC",
1135 "margin_lending_fees": D("0.002") })
1136 self
.assertEqual("Balance(BTX Margin: [-3.00000000 BTX @@ 0.10000000 BTC/0.00200000 BTC])", repr(balance
))
1138 balance
= portfolio
.Balance("BTX", { "margin_total": 1,
1139 "margin_in_position": 1, "exchange_free": 2, "exchange_total": 2})
1140 self
.assertEqual("Balance(BTX Exch: [✔2.00000000 BTX] Margin: [❌1.00000000 BTX] Total: [0.00000000 BTX])", repr(balance
))
1142 def test_as_json(self
):
1143 balance
= portfolio
.Balance("BTX", { "exchange_free": 2, "exchange_total": 2 }
)
1144 as_json
= balance
.as_json()
1145 self
.assertEqual(set(portfolio
.Balance
.base_keys
), set(as_json
.keys()))
1146 self
.assertEqual(D(0), as_json
["total"])
1147 self
.assertEqual(D(2), as_json
["exchange_total"])
1148 self
.assertEqual(D(2), as_json
["exchange_free"])
1149 self
.assertEqual(D(0), as_json
["exchange_used"])
1150 self
.assertEqual(D(0), as_json
["margin_total"])
1151 self
.assertEqual(D(0), as_json
["margin_available"])
1152 self
.assertEqual(D(0), as_json
["margin_borrowed"])
1154 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1155 class MarketTest(WebMockTestCase
):
1157 super(MarketTest
, self
).setUp()
1159 self
.ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
1161 def test_values(self
):
1162 m
= market
.Market(self
.ccxt
, self
.market_args())
1164 self
.assertEqual(self
.ccxt
, m
.ccxt
)
1165 self
.assertFalse(m
.debug
)
1166 self
.assertIsInstance(m
.report
, market
.ReportStore
)
1167 self
.assertIsInstance(m
.trades
, market
.TradeStore
)
1168 self
.assertIsInstance(m
.balances
, market
.BalanceStore
)
1169 self
.assertEqual(m
, m
.report
.market
)
1170 self
.assertEqual(m
, m
.trades
.market
)
1171 self
.assertEqual(m
, m
.balances
.market
)
1172 self
.assertEqual(m
, m
.ccxt
._market
)
1174 m
= market
.Market(self
.ccxt
, self
.market_args(debug
=True))
1175 self
.assertTrue(m
.debug
)
1177 m
= market
.Market(self
.ccxt
, self
.market_args(debug
=False))
1178 self
.assertFalse(m
.debug
)
1180 with mock
.patch("market.ReportStore") as report_store
:
1181 with self
.subTest(quiet
=False):
1182 m
= market
.Market(self
.ccxt
, self
.market_args(quiet
=False))
1183 report_store
.assert_called_with(m
, verbose_print
=True)
1184 with self
.subTest(quiet
=True):
1185 m
= market
.Market(self
.ccxt
, self
.market_args(quiet
=True))
1186 report_store
.assert_called_with(m
, verbose_print
=False)
1188 @mock.patch("market.ccxt")
1189 def test_from_config(self
, ccxt
):
1190 with mock
.patch("market.ReportStore"):
1191 ccxt
.poloniexE
.return_value
= self
.ccxt
1193 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, self
.market_args())
1195 self
.assertEqual(self
.ccxt
, m
.ccxt
)
1197 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, self
.market_args(debug
=True))
1198 self
.assertEqual(True, m
.debug
)
1200 def test_get_tickers(self
):
1201 self
.ccxt
.fetch_tickers
.side_effect
= [
1206 m
= market
.Market(self
.ccxt
, self
.market_args())
1207 self
.assertEqual("tickers", m
.get_tickers())
1208 self
.assertEqual("tickers", m
.get_tickers())
1209 self
.ccxt
.fetch_tickers
.assert_called_once()
1211 self
.assertIsNone(m
.get_tickers(refresh
=self
.time
.time()))
1213 def test_get_ticker(self
):
1214 with self
.subTest(get_tickers
=True):
1215 self
.ccxt
.fetch_tickers
.return_value
= {
1216 "ETH/ETC": { "bid": 1, "ask": 3 }
,
1217 "XVG/ETH": { "bid": 10, "ask": 40 }
,
1219 m
= market
.Market(self
.ccxt
, self
.market_args())
1221 ticker
= m
.get_ticker("ETH", "ETC")
1222 self
.assertEqual(1, ticker
["bid"])
1223 self
.assertEqual(3, ticker
["ask"])
1224 self
.assertEqual(2, ticker
["average"])
1225 self
.assertFalse(ticker
["inverted"])
1227 ticker
= m
.get_ticker("ETH", "XVG")
1228 self
.assertEqual(0.0625, ticker
["average"])
1229 self
.assertTrue(ticker
["inverted"])
1230 self
.assertIn("original", ticker
)
1231 self
.assertEqual(10, ticker
["original"]["bid"])
1232 self
.assertEqual(25, ticker
["original"]["average"])
1234 ticker
= m
.get_ticker("XVG", "XMR")
1235 self
.assertIsNone(ticker
)
1237 with self
.subTest(get_tickers
=False):
1238 self
.ccxt
.fetch_tickers
.return_value
= None
1239 self
.ccxt
.fetch_ticker
.side_effect
= [
1240 { "bid": 1, "ask": 3 }
,
1241 market
.ExchangeError("foo"),
1242 { "bid": 10, "ask": 40 }
,
1243 market
.ExchangeError("foo"),
1244 market
.ExchangeError("foo"),
1247 m
= market
.Market(self
.ccxt
, self
.market_args())
1249 ticker
= m
.get_ticker("ETH", "ETC")
1250 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
1251 self
.assertEqual(1, ticker
["bid"])
1252 self
.assertEqual(3, ticker
["ask"])
1253 self
.assertEqual(2, ticker
["average"])
1254 self
.assertFalse(ticker
["inverted"])
1256 ticker
= m
.get_ticker("ETH", "XVG")
1257 self
.assertEqual(0.0625, ticker
["average"])
1258 self
.assertTrue(ticker
["inverted"])
1259 self
.assertIn("original", ticker
)
1260 self
.assertEqual(10, ticker
["original"]["bid"])
1261 self
.assertEqual(25, ticker
["original"]["average"])
1263 ticker
= m
.get_ticker("XVG", "XMR")
1264 self
.assertIsNone(ticker
)
1266 def test_fetch_fees(self
):
1267 m
= market
.Market(self
.ccxt
, self
.market_args())
1268 self
.ccxt
.fetch_fees
.return_value
= "Foo"
1269 self
.assertEqual("Foo", m
.fetch_fees())
1270 self
.ccxt
.fetch_fees
.assert_called_once()
1271 self
.ccxt
.reset_mock()
1272 self
.assertEqual("Foo", m
.fetch_fees())
1273 self
.ccxt
.fetch_fees
.assert_not_called()
1275 @mock.patch.object(market
.Portfolio
, "repartition")
1276 @mock.patch.object(market
.Market
, "get_ticker")
1277 @mock.patch.object(market
.TradeStore
, "compute_trades")
1278 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
1279 repartition
.return_value
= {
1280 "XEM": (D("0.75"), "long"),
1281 "BTC": (D("0.25"), "long"),
1283 def _get_ticker(c1
, c2
):
1284 if c1
== "USDT" and c2
== "BTC":
1285 return { "average": D("0.0001") }
1286 if c1
== "XVG" and c2
== "BTC":
1287 return { "average": D("0.000001") }
1288 if c1
== "XEM" and c2
== "BTC":
1289 return { "average": D("0.001") }
1290 self
.fail("Should be called with {}, {}".format(c1
, c2
))
1291 get_ticker
.side_effect
= _get_ticker
1293 with mock
.patch("market.ReportStore"):
1294 m
= market
.Market(self
.ccxt
, self
.market_args())
1295 self
.ccxt
.fetch_all_balances
.return_value
= {
1297 "exchange_free": D("10000.0"),
1298 "exchange_used": D("0.0"),
1299 "exchange_total": D("10000.0"),
1300 "total": D("10000.0")
1303 "exchange_free": D("10000.0"),
1304 "exchange_used": D("0.0"),
1305 "exchange_total": D("10000.0"),
1306 "total": D("10000.0")
1310 m
.balances
.fetch_balances(tag
="tag")
1313 compute_trades
.assert_called()
1315 call
= compute_trades
.call_args
1316 self
.assertEqual(1, call
[0][0]["USDT"].value
)
1317 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
1318 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
1319 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
1320 m
.report
.log_stage
.assert_called_once_with("prepare_trades",
1321 base_currency
='BTC', compute_value
='average',
1322 liquidity
='medium', only
=None, repartition
=None)
1323 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
1326 @mock.patch.object(market
.time
, "sleep")
1327 @mock.patch.object(market
.TradeStore
, "all_orders")
1328 def test_follow_orders(self
, all_orders
, time_mock
):
1329 for debug
, sleep
in [
1330 (False, None), (True, None),
1331 (False, 12), (True, 12)]:
1332 with self
.subTest(sleep
=sleep
, debug
=debug
), \
1333 mock
.patch("market.ReportStore"):
1334 m
= market
.Market(self
.ccxt
, self
.market_args(debug
=debug
))
1336 order_mock1
= mock
.Mock()
1337 order_mock2
= mock
.Mock()
1338 order_mock3
= mock
.Mock()
1339 all_orders
.side_effect
= [
1340 [order_mock1
, order_mock2
],
1341 [order_mock1
, order_mock2
],
1343 [order_mock1
, order_mock3
],
1344 [order_mock1
, order_mock3
],
1346 [order_mock1
, order_mock3
],
1347 [order_mock1
, order_mock3
],
1352 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
1353 order_mock2
.get_status
.side_effect
= ["open"]
1354 order_mock3
.get_status
.side_effect
= ["open", "closed"]
1356 order_mock1
.trade
= mock
.Mock()
1357 order_mock2
.trade
= mock
.Mock()
1358 order_mock3
.trade
= mock
.Mock()
1360 m
.follow_orders(sleep
=sleep
)
1362 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
1363 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
1364 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
1365 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
1367 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
1368 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
1369 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
1371 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
1372 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
1373 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
1374 m
.report
.log_stage
.assert_called()
1376 mock
.call("follow_orders_begin"),
1377 mock
.call("follow_orders_tick_1"),
1378 mock
.call("follow_orders_tick_2"),
1379 mock
.call("follow_orders_tick_3"),
1380 mock
.call("follow_orders_end"),
1382 m
.report
.log_stage
.assert_has_calls(calls
)
1383 m
.report
.log_orders
.assert_called()
1384 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
1386 mock
.call([order_mock1
, order_mock2
], tick
=1),
1387 mock
.call([order_mock1
, order_mock3
], tick
=2),
1388 mock
.call([order_mock1
, order_mock3
], tick
=3),
1390 m
.report
.log_orders
.assert_has_calls(calls
)
1392 mock
.call(order_mock1
, 3, finished
=True),
1393 mock
.call(order_mock3
, 3, finished
=True),
1395 m
.report
.log_order
.assert_has_calls(calls
)
1399 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
1400 time_mock
.assert_called_with(7)
1402 time_mock
.assert_called_with(30)
1404 time_mock
.assert_called_with(sleep
)
1406 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
1407 def test_move_balance(self
, fetch_balances
):
1408 for debug
in [True, False]:
1409 with self
.subTest(debug
=debug
),\
1410 mock
.patch("market.ReportStore"):
1411 m
= market
.Market(self
.ccxt
, self
.market_args(debug
=debug
))
1413 value_from
= portfolio
.Amount("BTC", "1.0")
1414 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1415 value_to
= portfolio
.Amount("BTC", "10.0")
1416 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1418 value_from
= portfolio
.Amount("BTC", "0.0")
1419 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1420 value_to
= portfolio
.Amount("BTC", "-3.0")
1421 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1423 value_from
= portfolio
.Amount("USDT", "0.0")
1424 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
1425 value_to
= portfolio
.Amount("USDT", "-50.0")
1426 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
1428 m
.trades
.all
= [trade1
, trade2
, trade3
]
1429 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1430 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
1431 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
1432 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
1436 fetch_balances
.assert_called_with()
1437 m
.report
.log_move_balances
.assert_called_once()
1440 m
.report
.log_debug_action
.assert_called()
1441 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
1443 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
1444 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
1445 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
1447 m
.report
.reset_mock()
1448 fetch_balances
.reset_mock()
1449 with self
.subTest(retry
=True):
1450 with mock
.patch("market.ReportStore"):
1451 m
= market
.Market(self
.ccxt
, self
.market_args())
1453 value_from
= portfolio
.Amount("BTC", "0.0")
1454 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1455 value_to
= portfolio
.Amount("BTC", "-3.0")
1456 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1458 m
.trades
.all
= [trade
]
1459 balance
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1460 m
.balances
.all
= {"BTC": balance}
1462 m
.ccxt
.transfer_balance
.side_effect
= [
1463 market
.ccxt
.RequestTimeout
,
1464 market
.ccxt
.InvalidNonce
,
1468 self
.ccxt
.transfer_balance
.assert_has_calls([
1469 mock
.call("BTC", 3, "exchange", "margin"),
1470 mock
.call("BTC", 3, "exchange", "margin"),
1471 mock
.call("BTC", 3, "exchange", "margin")
1473 self
.assertEqual(3, fetch_balances
.call_count
)
1474 m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying", exception
=mock
.ANY
)
1475 self
.assertEqual(3, m
.report
.log_move_balances
.call_count
)
1477 self
.ccxt
.transfer_balance
.reset_mock()
1478 m
.report
.reset_mock()
1479 fetch_balances
.reset_mock()
1480 with self
.subTest(retry
=True, too_much
=True):
1481 with mock
.patch("market.ReportStore"):
1482 m
= market
.Market(self
.ccxt
, self
.market_args())
1484 value_from
= portfolio
.Amount("BTC", "0.0")
1485 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1486 value_to
= portfolio
.Amount("BTC", "-3.0")
1487 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1489 m
.trades
.all
= [trade
]
1490 balance
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1491 m
.balances
.all
= {"BTC": balance}
1493 m
.ccxt
.transfer_balance
.side_effect
= [
1494 market
.ccxt
.RequestTimeout
,
1495 market
.ccxt
.RequestTimeout
,
1496 market
.ccxt
.RequestTimeout
,
1497 market
.ccxt
.RequestTimeout
,
1498 market
.ccxt
.RequestTimeout
,
1500 with self
.assertRaises(market
.ccxt
.RequestTimeout
):
1503 self
.ccxt
.transfer_balance
.reset_mock()
1504 m
.report
.reset_mock()
1505 fetch_balances
.reset_mock()
1506 with self
.subTest(retry
=True, partial_result
=True):
1507 with mock
.patch("market.ReportStore"):
1508 m
= market
.Market(self
.ccxt
, self
.market_args())
1510 value_from
= portfolio
.Amount("BTC", "1.0")
1511 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1512 value_to
= portfolio
.Amount("BTC", "10.0")
1513 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1515 value_from
= portfolio
.Amount("BTC", "0.0")
1516 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1517 value_to
= portfolio
.Amount("BTC", "-3.0")
1518 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1520 value_from
= portfolio
.Amount("USDT", "0.0")
1521 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
1522 value_to
= portfolio
.Amount("USDT", "-50.0")
1523 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
1525 m
.trades
.all
= [trade1
, trade2
, trade3
]
1526 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1527 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
1528 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
1529 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
1531 call_counts
= { "BTC": 0, "USDT": 0, "ETC": 0 }
1532 def _transfer_balance(currency
, amount
, from_
, to_
):
1533 call_counts
[currency
] += 1
1534 if currency
== "BTC":
1535 m
.balances
.all
["BTC"] = portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "3" }
)
1536 if currency
== "USDT":
1537 if call_counts
["USDT"] == 1:
1538 raise market
.ccxt
.RequestTimeout
1540 m
.balances
.all
["USDT"] = portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "150" }
)
1541 if currency
== "ETC":
1542 m
.balances
.all
["ETC"] = portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "10" }
)
1545 m
.ccxt
.transfer_balance
.side_effect
= _transfer_balance
1548 self
.ccxt
.transfer_balance
.assert_has_calls([
1549 mock
.call("BTC", 3, "exchange", "margin"),
1550 mock
.call('USDT', 100, 'exchange', 'margin'),
1551 mock
.call('USDT', 100, 'exchange', 'margin'),
1552 mock
.call("ETC", 5, "margin", "exchange")
1554 self
.assertEqual(2, fetch_balances
.call_count
)
1555 m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying", exception
=mock
.ANY
)
1556 self
.assertEqual(2, m
.report
.log_move_balances
.call_count
)
1557 m
.report
.log_move_balances
.asser_has_calls([
1560 'BTC': portfolio
.Amount("BTC", "3"),
1561 'USDT': portfolio
.Amount("USDT", "150"),
1562 'ETC': portfolio
.Amount("ETC", "10"),
1565 'BTC': portfolio
.Amount("BTC", "3"),
1566 'USDT': portfolio
.Amount("USDT", "100"),
1570 'BTC': portfolio
.Amount("BTC", "3"),
1571 'USDT': portfolio
.Amount("USDT", "150"),
1572 'ETC': portfolio
.Amount("ETC", "10"),
1575 'BTC': portfolio
.Amount("BTC", "0"),
1576 'USDT': portfolio
.Amount("USDT", "100"),
1577 'ETC': portfolio
.Amount("ETC", "-5"),
1582 def test_store_file_report(self
):
1583 file_open
= mock
.mock_open()
1584 m
= market
.Market(self
.ccxt
, self
.market_args(), report_path
="present", user_id
=1)
1585 with self
.subTest(file="present"),\
1586 mock
.patch("market.open", file_open
),\
1587 mock
.patch
.object(m
, "report") as report
,\
1588 mock
.patch
.object(market
, "datetime") as time_mock
:
1590 report
.print_logs
= [[time_mock
.now(), "Foo"], [time_mock
.now(), "Bar"]]
1591 report
.to_json
.return_value
= "json_content"
1593 m
.store_file_report(datetime
.datetime(2018, 2, 25))
1595 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
1596 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.log", "w")
1597 file_open().write
.assert_any_call("json_content")
1598 file_open().write
.assert_any_call("Foo\nBar")
1599 m
.report
.to_json
.assert_called_once_with()
1601 m
= market
.Market(self
.ccxt
, self
.market_args(), report_path
="error", user_id
=1)
1602 with self
.subTest(file="error"),\
1603 mock
.patch("market.open") as file_open
,\
1604 mock
.patch
.object(m
, "report") as report
,\
1605 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1606 file_open
.side_effect
= FileNotFoundError
1608 m
.store_file_report(datetime
.datetime(2018, 2, 25))
1610 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
1612 @mock.patch.object(market
, "psycopg2")
1613 def test_store_database_report(self
, psycopg2
):
1614 connect_mock
= mock
.Mock()
1615 cursor_mock
= mock
.MagicMock()
1617 connect_mock
.cursor
.return_value
= cursor_mock
1618 psycopg2
.connect
.return_value
= connect_mock
1619 m
= market
.Market(self
.ccxt
, self
.market_args(),
1620 pg_config
={"config": "pg_config"}
, user_id
=1)
1621 cursor_mock
.fetchone
.return_value
= [42]
1623 with self
.subTest(error
=False),\
1624 mock
.patch
.object(m
, "report") as report
:
1625 report
.to_json_array
.return_value
= [
1626 ("date1", "type1", "payload1"),
1627 ("date2", "type2", "payload2"),
1629 m
.store_database_report(datetime
.datetime(2018, 3, 24))
1630 connect_mock
.assert_has_calls([
1632 mock
.call
.cursor().execute('INSERT INTO reports("date", "market_config_id", "debug") VALUES (%s, %s, %s) RETURNING id;', (datetime
.datetime(2018, 3, 24), None, False)),
1633 mock
.call
.cursor().fetchone(),
1634 mock
.call
.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date1', 42, 'type1', 'payload1')),
1635 mock
.call
.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date2', 42, 'type2', 'payload2')),
1637 mock
.call
.cursor().close(),
1641 connect_mock
.reset_mock()
1642 with self
.subTest(error
=True),\
1643 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1644 psycopg2
.connect
.side_effect
= Exception("Bouh")
1645 m
.store_database_report(datetime
.datetime(2018, 3, 24))
1646 self
.assertEqual(stdout_mock
.getvalue(), "impossible to store report to database: Exception; Bouh\n")
1648 def test_store_report(self
):
1649 m
= market
.Market(self
.ccxt
, self
.market_args(), user_id
=1)
1650 with self
.subTest(file=None, pg_config
=None),\
1651 mock
.patch
.object(m
, "report") as report
,\
1652 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1653 mock
.patch
.object(m
, "store_file_report") as file_report
:
1655 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1657 file_report
.assert_not_called()
1658 db_report
.assert_not_called()
1661 m
= market
.Market(self
.ccxt
, self
.market_args(), report_path
="present", user_id
=1)
1662 with self
.subTest(file="present", pg_config
=None),\
1663 mock
.patch
.object(m
, "report") as report
,\
1664 mock
.patch
.object(m
, "store_file_report") as file_report
,\
1665 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1666 mock
.patch
.object(market
, "datetime") as time_mock
:
1668 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
1672 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1673 file_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1674 db_report
.assert_not_called()
1677 m
= market
.Market(self
.ccxt
, self
.market_args(), pg_config
="present", user_id
=1)
1678 with self
.subTest(file=None, pg_config
="present"),\
1679 mock
.patch
.object(m
, "report") as report
,\
1680 mock
.patch
.object(m
, "store_file_report") as file_report
,\
1681 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1682 mock
.patch
.object(market
, "datetime") as time_mock
:
1684 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
1688 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1689 file_report
.assert_not_called()
1690 db_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1693 m
= market
.Market(self
.ccxt
, self
.market_args(),
1694 pg_config
="pg_config", report_path
="present", user_id
=1)
1695 with self
.subTest(file="present", pg_config
="present"),\
1696 mock
.patch
.object(m
, "report") as report
,\
1697 mock
.patch
.object(m
, "store_file_report") as file_report
,\
1698 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1699 mock
.patch
.object(market
, "datetime") as time_mock
:
1701 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
1705 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1706 file_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1707 db_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1709 def test_print_orders(self
):
1710 m
= market
.Market(self
.ccxt
, self
.market_args())
1711 with mock
.patch
.object(m
.report
, "log_stage") as log_stage
,\
1712 mock
.patch
.object(m
.balances
, "fetch_balances") as fetch_balances
,\
1713 mock
.patch
.object(m
, "prepare_trades") as prepare_trades
,\
1714 mock
.patch
.object(m
.trades
, "prepare_orders") as prepare_orders
:
1717 log_stage
.assert_called_with("print_orders")
1718 fetch_balances
.assert_called_with(tag
="print_orders")
1719 prepare_trades
.assert_called_with(base_currency
="BTC",
1720 compute_value
="average")
1721 prepare_orders
.assert_called_with(compute_value
="average")
1723 def test_print_balances(self
):
1724 m
= market
.Market(self
.ccxt
, self
.market_args())
1726 with mock
.patch
.object(m
.balances
, "in_currency") as in_currency
,\
1727 mock
.patch
.object(m
.report
, "log_stage") as log_stage
,\
1728 mock
.patch
.object(m
.balances
, "fetch_balances") as fetch_balances
,\
1729 mock
.patch
.object(m
.report
, "print_log") as print_log
:
1731 in_currency
.return_value
= {
1732 "BTC": portfolio
.Amount("BTC", "0.65"),
1733 "ETH": portfolio
.Amount("BTC", "0.3"),
1738 log_stage
.assert_called_once_with("print_balances")
1739 fetch_balances
.assert_called_with()
1740 print_log
.assert_has_calls([
1741 mock
.call("total:"),
1742 mock
.call(portfolio
.Amount("BTC", "0.95")),
1745 @mock.patch("market.Processor.process")
1746 @mock.patch("market.ReportStore.log_error")
1747 @mock.patch("market.Market.store_report")
1748 def test_process(self
, store_report
, log_error
, process
):
1749 m
= market
.Market(self
.ccxt
, self
.market_args())
1750 with self
.subTest(before
=False, after
=False):
1753 process
.assert_not_called()
1754 store_report
.assert_called_once()
1755 log_error
.assert_not_called()
1757 process
.reset_mock()
1758 log_error
.reset_mock()
1759 store_report
.reset_mock()
1760 with self
.subTest(before
=True, after
=False):
1761 m
.process(None, before
=True)
1763 process
.assert_called_once_with("sell_all", steps
="before")
1764 store_report
.assert_called_once()
1765 log_error
.assert_not_called()
1767 process
.reset_mock()
1768 log_error
.reset_mock()
1769 store_report
.reset_mock()
1770 with self
.subTest(before
=False, after
=True):
1771 m
.process(None, after
=True)
1773 process
.assert_called_once_with("sell_all", steps
="after")
1774 store_report
.assert_called_once()
1775 log_error
.assert_not_called()
1777 process
.reset_mock()
1778 log_error
.reset_mock()
1779 store_report
.reset_mock()
1780 with self
.subTest(before
=True, after
=True):
1781 m
.process(None, before
=True, after
=True)
1783 process
.assert_has_calls([
1784 mock
.call("sell_all", steps
="before"),
1785 mock
.call("sell_all", steps
="after"),
1787 store_report
.assert_called_once()
1788 log_error
.assert_not_called()
1790 process
.reset_mock()
1791 log_error
.reset_mock()
1792 store_report
.reset_mock()
1793 with self
.subTest(action
="print_balances"),\
1794 mock
.patch
.object(m
, "print_balances") as print_balances
:
1795 m
.process(["print_balances"])
1797 process
.assert_not_called()
1798 log_error
.assert_not_called()
1799 store_report
.assert_called_once()
1800 print_balances
.assert_called_once_with()
1802 log_error
.reset_mock()
1803 store_report
.reset_mock()
1804 with self
.subTest(action
="print_orders"),\
1805 mock
.patch
.object(m
, "print_orders") as print_orders
,\
1806 mock
.patch
.object(m
, "print_balances") as print_balances
:
1807 m
.process(["print_orders", "print_balances"])
1809 process
.assert_not_called()
1810 log_error
.assert_not_called()
1811 store_report
.assert_called_once()
1812 print_orders
.assert_called_once_with()
1813 print_balances
.assert_called_once_with()
1815 log_error
.reset_mock()
1816 store_report
.reset_mock()
1817 with self
.subTest(action
="unknown"):
1818 m
.process(["unknown"])
1819 log_error
.assert_called_once_with("market_process", message
="Unknown action unknown")
1820 store_report
.assert_called_once()
1822 log_error
.reset_mock()
1823 store_report
.reset_mock()
1824 with self
.subTest(unhandled_exception
=True):
1825 process
.side_effect
= Exception("bouh")
1827 m
.process(None, before
=True)
1828 log_error
.assert_called_with("market_process", exception
=mock
.ANY
)
1829 store_report
.assert_called_once()
1831 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1832 class TradeStoreTest(WebMockTestCase
):
1833 def test_compute_trades(self
):
1834 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
1837 "XMR": portfolio
.Amount("BTC", D("0.9")),
1838 "DASH": portfolio
.Amount("BTC", D("0.4")),
1839 "XVG": portfolio
.Amount("BTC", D("-0.5")),
1840 "BTC": portfolio
.Amount("BTC", D("0.5")),
1843 "DASH": portfolio
.Amount("BTC", D("0.5")),
1844 "XVG": portfolio
.Amount("BTC", D("0.1")),
1845 "BTC": portfolio
.Amount("BTC", D("0.4")),
1846 "ETH": portfolio
.Amount("BTC", D("0.3")),
1856 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
1857 trade_store
= market
.TradeStore(self
.m
)
1858 trade_if_matching
.side_effect
= side_effect
1860 trade_store
.compute_trades(values_in_base
,
1861 new_repartition
, only
="only")
1863 self
.assertEqual(5, trade_if_matching
.call_count
)
1864 self
.assertEqual(3, len(trade_store
.all
))
1865 self
.assertEqual([1, 4, 5], trade_store
.all
)
1866 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
1868 def test_trade_if_matching(self
):
1870 with self
.subTest(only
="nope"):
1871 trade_store
= market
.TradeStore(self
.m
)
1872 result
= trade_store
.trade_if_matching(
1873 portfolio
.Amount("BTC", D("0")),
1874 portfolio
.Amount("BTC", D("0.3")),
1876 self
.assertEqual(False, result
[0])
1877 self
.assertIsInstance(result
[1], portfolio
.Trade
)
1879 with self
.subTest(only
=None):
1880 trade_store
= market
.TradeStore(self
.m
)
1881 result
= trade_store
.trade_if_matching(
1882 portfolio
.Amount("BTC", D("0")),
1883 portfolio
.Amount("BTC", D("0.3")),
1885 self
.assertEqual(True, result
[0])
1887 with self
.subTest(only
="acquire"):
1888 trade_store
= market
.TradeStore(self
.m
)
1889 result
= trade_store
.trade_if_matching(
1890 portfolio
.Amount("BTC", D("0")),
1891 portfolio
.Amount("BTC", D("0.3")),
1892 "ETH", only
="acquire")
1893 self
.assertEqual(True, result
[0])
1895 with self
.subTest(only
="dispose"):
1896 trade_store
= market
.TradeStore(self
.m
)
1897 result
= trade_store
.trade_if_matching(
1898 portfolio
.Amount("BTC", D("0")),
1899 portfolio
.Amount("BTC", D("0.3")),
1900 "ETH", only
="dispose")
1901 self
.assertEqual(False, result
[0])
1903 def test_prepare_orders(self
):
1904 trade_store
= market
.TradeStore(self
.m
)
1906 trade_mock1
= mock
.Mock()
1907 trade_mock2
= mock
.Mock()
1908 trade_mock3
= mock
.Mock()
1910 trade_mock1
.prepare_order
.return_value
= 1
1911 trade_mock2
.prepare_order
.return_value
= 2
1912 trade_mock3
.prepare_order
.return_value
= 3
1914 trade_mock1
.pending
= True
1915 trade_mock2
.pending
= True
1916 trade_mock3
.pending
= False
1918 trade_store
.all
.append(trade_mock1
)
1919 trade_store
.all
.append(trade_mock2
)
1920 trade_store
.all
.append(trade_mock3
)
1922 trade_store
.prepare_orders()
1923 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1924 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1925 trade_mock3
.prepare_order
.assert_not_called()
1926 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1928 self
.m
.report
.log_orders
.reset_mock()
1930 trade_store
.prepare_orders(compute_value
="bla")
1931 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1932 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1933 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1935 trade_mock1
.prepare_order
.reset_mock()
1936 trade_mock2
.prepare_order
.reset_mock()
1937 self
.m
.report
.log_orders
.reset_mock()
1939 trade_mock1
.action
= "foo"
1940 trade_mock2
.action
= "bar"
1941 trade_store
.prepare_orders(only
="bar")
1942 trade_mock1
.prepare_order
.assert_not_called()
1943 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1944 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1946 def test_print_all_with_order(self
):
1947 trade_mock1
= mock
.Mock()
1948 trade_mock2
= mock
.Mock()
1949 trade_mock3
= mock
.Mock()
1950 trade_store
= market
.TradeStore(self
.m
)
1951 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1953 trade_store
.print_all_with_order()
1955 trade_mock1
.print_with_order
.assert_called()
1956 trade_mock2
.print_with_order
.assert_called()
1957 trade_mock3
.print_with_order
.assert_called()
1959 def test_run_orders(self
):
1960 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1961 order_mock1
= mock
.Mock()
1962 order_mock2
= mock
.Mock()
1963 order_mock3
= mock
.Mock()
1964 trade_store
= market
.TradeStore(self
.m
)
1966 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
1968 trade_store
.run_orders()
1970 all_orders
.assert_called_with(state
="pending")
1972 order_mock1
.run
.assert_called()
1973 order_mock2
.run
.assert_called()
1974 order_mock3
.run
.assert_called()
1976 self
.m
.report
.log_stage
.assert_called_with("run_orders")
1977 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
1980 def test_all_orders(self
):
1981 trade_mock1
= mock
.Mock()
1982 trade_mock2
= mock
.Mock()
1984 order_mock1
= mock
.Mock()
1985 order_mock2
= mock
.Mock()
1986 order_mock3
= mock
.Mock()
1988 trade_mock1
.orders
= [order_mock1
, order_mock2
]
1989 trade_mock2
.orders
= [order_mock3
]
1991 order_mock1
.status
= "pending"
1992 order_mock2
.status
= "open"
1993 order_mock3
.status
= "open"
1995 trade_store
= market
.TradeStore(self
.m
)
1996 trade_store
.all
.append(trade_mock1
)
1997 trade_store
.all
.append(trade_mock2
)
1999 orders
= trade_store
.all_orders()
2000 self
.assertEqual(3, len(orders
))
2002 open_orders
= trade_store
.all_orders(state
="open")
2003 self
.assertEqual(2, len(open_orders
))
2004 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
2006 def test_update_all_orders_status(self
):
2007 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
2008 order_mock1
= mock
.Mock()
2009 order_mock2
= mock
.Mock()
2010 order_mock3
= mock
.Mock()
2012 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
2014 trade_store
= market
.TradeStore(self
.m
)
2016 trade_store
.update_all_orders_status()
2017 all_orders
.assert_called_with(state
="open")
2019 order_mock1
.get_status
.assert_called()
2020 order_mock2
.get_status
.assert_called()
2021 order_mock3
.get_status
.assert_called()
2023 def test_close_trades(self
):
2024 trade_mock1
= mock
.Mock()
2025 trade_mock2
= mock
.Mock()
2026 trade_mock3
= mock
.Mock()
2028 trade_store
= market
.TradeStore(self
.m
)
2030 trade_store
.all
.append(trade_mock1
)
2031 trade_store
.all
.append(trade_mock2
)
2032 trade_store
.all
.append(trade_mock3
)
2034 trade_store
.close_trades()
2036 trade_mock1
.close
.assert_called_once_with()
2037 trade_mock2
.close
.assert_called_once_with()
2038 trade_mock3
.close
.assert_called_once_with()
2040 def test_pending(self
):
2041 trade_mock1
= mock
.Mock()
2042 trade_mock1
.pending
= True
2043 trade_mock2
= mock
.Mock()
2044 trade_mock2
.pending
= True
2045 trade_mock3
= mock
.Mock()
2046 trade_mock3
.pending
= False
2048 trade_store
= market
.TradeStore(self
.m
)
2050 trade_store
.all
.append(trade_mock1
)
2051 trade_store
.all
.append(trade_mock2
)
2052 trade_store
.all
.append(trade_mock3
)
2054 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
2056 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2057 class BalanceStoreTest(WebMockTestCase
):
2059 super(BalanceStoreTest
, self
).setUp()
2061 self
.fetch_balance
= {
2065 "exchange_total": 0,
2069 "exchange_free": D("6.0"),
2070 "exchange_used": D("1.2"),
2071 "exchange_total": D("7.2"),
2075 "exchange_free": 16,
2077 "exchange_total": 16,
2083 "exchange_total": 0,
2084 "margin_total": D("-1.0"),
2089 def test_in_currency(self
):
2090 self
.m
.get_ticker
.return_value
= {
2093 "average": D("0.1"),
2096 balance_store
= market
.BalanceStore(self
.m
)
2097 balance_store
.all
= {
2098 "BTC": portfolio
.Balance("BTC", {
2100 "exchange_total":"0.65",
2101 "exchange_free": "0.35",
2102 "exchange_used": "0.30"}),
2103 "ETH": portfolio
.Balance("ETH", {
2105 "exchange_total": 3,
2107 "exchange_used": 0}),
2110 amounts
= balance_store
.in_currency("BTC")
2111 self
.assertEqual("BTC", amounts
["ETH"].currency
)
2112 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
2113 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
2114 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
2116 self
.m
.report
.log_tickers
.reset_mock()
2118 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
2119 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
2120 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
2121 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
2123 self
.m
.report
.log_tickers
.reset_mock()
2125 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
2126 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
2127 self
.assertEqual(0, amounts
["ETH"].value
)
2128 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
2129 "bid", "exchange_used")
2130 self
.m
.report
.log_tickers
.reset_mock()
2132 def test_fetch_balances(self
):
2133 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
2135 balance_store
= market
.BalanceStore(self
.m
)
2137 balance_store
.fetch_balances()
2138 self
.assertNotIn("ETC", balance_store
.currencies())
2139 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
2141 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
2142 "exchange_total": "1", "exchange_free": "0",
2143 "exchange_used": "1" })
2144 balance_store
.fetch_balances(tag
="foo")
2145 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
2146 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
2147 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
2149 @mock.patch.object(market
.Portfolio
, "repartition")
2150 def test_dispatch_assets(self
, repartition
):
2151 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
2153 balance_store
= market
.BalanceStore(self
.m
)
2154 balance_store
.fetch_balances()
2156 self
.assertNotIn("XEM", balance_store
.currencies())
2158 repartition_hash
= {
2159 "XEM": (D("0.75"), "long"),
2160 "BTC": (D("0.26"), "long"),
2161 "DASH": (D("0.10"), "short"),
2163 repartition
.return_value
= repartition_hash
2165 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
2166 repartition
.assert_called_with(liquidity
="medium")
2167 self
.assertIn("XEM", balance_store
.currencies())
2168 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
2169 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
2170 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
2171 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
2172 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
2173 "11.1"), amounts
, "medium", repartition_hash
)
2175 def test_currencies(self
):
2176 balance_store
= market
.BalanceStore(self
.m
)
2178 balance_store
.all
= {
2179 "BTC": portfolio
.Balance("BTC", {
2181 "exchange_total":"0.65",
2182 "exchange_free": "0.35",
2183 "exchange_used": "0.30"}),
2184 "ETH": portfolio
.Balance("ETH", {
2186 "exchange_total": 3,
2188 "exchange_used": 0}),
2190 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
2192 def test_as_json(self
):
2193 balance_mock1
= mock
.Mock()
2194 balance_mock1
.as_json
.return_value
= 1
2196 balance_mock2
= mock
.Mock()
2197 balance_mock2
.as_json
.return_value
= 2
2199 balance_store
= market
.BalanceStore(self
.m
)
2200 balance_store
.all
= {
2201 "BTC": balance_mock1
,
2202 "ETH": balance_mock2
,
2205 as_json
= balance_store
.as_json()
2206 self
.assertEqual(1, as_json
["BTC"])
2207 self
.assertEqual(2, as_json
["ETH"])
2210 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2211 class ComputationTest(WebMockTestCase
):
2212 def test_compute_value(self
):
2213 compute
= mock
.Mock()
2214 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
2215 compute
.assert_called_with("foo", "ask")
2217 compute
.reset_mock()
2218 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
2219 compute
.assert_called_with("foo", "bid")
2221 compute
.reset_mock()
2222 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
2223 compute
.assert_called_with("foo", "ask")
2225 compute
.reset_mock()
2226 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
2227 compute
.assert_called_with("foo", "bid")
2229 compute
.reset_mock()
2230 portfolio
.Computation
.computations
["test"] = compute
2231 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
2232 compute
.assert_called_with("foo", "bid")
2235 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2236 class TradeTest(WebMockTestCase
):
2238 def test_values_assertion(self
):
2239 value_from
= portfolio
.Amount("BTC", "1.0")
2240 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2241 value_to
= portfolio
.Amount("BTC", "1.0")
2242 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2243 self
.assertEqual("BTC", trade
.base_currency
)
2244 self
.assertEqual("ETH", trade
.currency
)
2245 self
.assertEqual(self
.m
, trade
.market
)
2247 with self
.assertRaises(AssertionError):
2248 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
2249 with self
.assertRaises(AssertionError):
2250 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
2251 with self
.assertRaises(AssertionError):
2252 value_from
.currency
= "ETH"
2253 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2254 value_from
.currency
= "BTC"
2255 with self
.assertRaises(AssertionError):
2256 value_from2
= portfolio
.Amount("BTC", "1.0")
2257 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
2259 value_from
= portfolio
.Amount("BTC", 0)
2260 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2261 self
.assertEqual(0, trade
.value_from
.linked_to
)
2263 def test_action(self
):
2264 value_from
= portfolio
.Amount("BTC", "1.0")
2265 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2266 value_to
= portfolio
.Amount("BTC", "1.0")
2267 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2269 self
.assertIsNone(trade
.action
)
2271 value_from
= portfolio
.Amount("BTC", "1.0")
2272 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
2273 value_to
= portfolio
.Amount("BTC", "2.0")
2274 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
2276 self
.assertIsNone(trade
.action
)
2278 value_from
= portfolio
.Amount("BTC", "0.5")
2279 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2280 value_to
= portfolio
.Amount("BTC", "1.0")
2281 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2283 self
.assertEqual("acquire", trade
.action
)
2285 value_from
= portfolio
.Amount("BTC", "0")
2286 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
2287 value_to
= portfolio
.Amount("BTC", "-1.0")
2288 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2290 self
.assertEqual("acquire", trade
.action
)
2292 def test_order_action(self
):
2293 value_from
= portfolio
.Amount("BTC", "0.5")
2294 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2295 value_to
= portfolio
.Amount("BTC", "1.0")
2296 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2298 trade
.inverted
= False
2299 self
.assertEqual("buy", trade
.order_action())
2300 trade
.inverted
= True
2301 self
.assertEqual("sell", trade
.order_action())
2303 value_from
= portfolio
.Amount("BTC", "0")
2304 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
2305 value_to
= portfolio
.Amount("BTC", "-1.0")
2306 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2308 trade
.inverted
= False
2309 self
.assertEqual("sell", trade
.order_action())
2310 trade
.inverted
= True
2311 self
.assertEqual("buy", trade
.order_action())
2313 def test_trade_type(self
):
2314 value_from
= portfolio
.Amount("BTC", "0.5")
2315 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2316 value_to
= portfolio
.Amount("BTC", "1.0")
2317 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2319 self
.assertEqual("long", trade
.trade_type
)
2321 value_from
= portfolio
.Amount("BTC", "0")
2322 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
2323 value_to
= portfolio
.Amount("BTC", "-1.0")
2324 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2326 self
.assertEqual("short", trade
.trade_type
)
2328 def test_is_fullfiled(self
):
2329 with self
.subTest(inverted
=False):
2330 value_from
= portfolio
.Amount("BTC", "0.5")
2331 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2332 value_to
= portfolio
.Amount("BTC", "1.0")
2333 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2335 order1
= mock
.Mock()
2336 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
2338 order2
= mock
.Mock()
2339 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
2340 trade
.orders
.append(order1
)
2341 trade
.orders
.append(order2
)
2343 self
.assertFalse(trade
.is_fullfiled
)
2345 order3
= mock
.Mock()
2346 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
2347 trade
.orders
.append(order3
)
2349 self
.assertTrue(trade
.is_fullfiled
)
2351 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
2352 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
2353 order3
.filled_amount
.assert_called_with(in_base_currency
=True)
2355 with self
.subTest(inverted
=True):
2356 value_from
= portfolio
.Amount("BTC", "0.5")
2357 value_from
.linked_to
= portfolio
.Amount("USDT", "1000.0")
2358 value_to
= portfolio
.Amount("BTC", "1.0")
2359 trade
= portfolio
.Trade(value_from
, value_to
, "USDT", self
.m
)
2360 trade
.inverted
= True
2362 order1
= mock
.Mock()
2363 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
2365 order2
= mock
.Mock()
2366 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
2367 trade
.orders
.append(order1
)
2368 trade
.orders
.append(order2
)
2370 self
.assertFalse(trade
.is_fullfiled
)
2372 order3
= mock
.Mock()
2373 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
2374 trade
.orders
.append(order3
)
2376 self
.assertTrue(trade
.is_fullfiled
)
2378 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
2379 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
2380 order3
.filled_amount
.assert_called_with(in_base_currency
=False)
2383 def test_filled_amount(self
):
2384 value_from
= portfolio
.Amount("BTC", "0.5")
2385 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2386 value_to
= portfolio
.Amount("BTC", "1.0")
2387 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2389 order1
= mock
.Mock()
2390 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
2392 order2
= mock
.Mock()
2393 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
2394 trade
.orders
.append(order1
)
2395 trade
.orders
.append(order2
)
2397 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
2398 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
2399 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
2401 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
2402 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
2403 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
2405 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
2406 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
2407 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
2409 @mock.patch.object(portfolio
.Computation
, "compute_value")
2410 @mock.patch.object(portfolio
.Trade
, "filled_amount")
2411 @mock.patch.object(portfolio
, "Order")
2412 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
2413 Order
.return_value
= "Order"
2415 with self
.subTest(desc
="Nothing to do"):
2416 value_from
= portfolio
.Amount("BTC", "10")
2417 value_from
.rate
= D("0.1")
2418 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2419 value_to
= portfolio
.Amount("BTC", "10")
2420 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2422 trade
.prepare_order()
2424 filled_amount
.assert_not_called()
2425 compute_value
.assert_not_called()
2426 self
.assertEqual(0, len(trade
.orders
))
2427 Order
.assert_not_called()
2429 self
.m
.get_ticker
.return_value
= { "inverted": False }
2430 with self
.subTest(desc
="Already filled"):
2431 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
2432 compute_value
.return_value
= D("0.125")
2434 value_from
= portfolio
.Amount("BTC", "10")
2435 value_from
.rate
= D("0.1")
2436 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2437 value_to
= portfolio
.Amount("BTC", "0")
2438 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2440 trade
.prepare_order()
2442 filled_amount
.assert_called_with(in_base_currency
=False)
2443 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2444 self
.assertEqual(0, len(trade
.orders
))
2445 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
2446 Order
.assert_not_called()
2448 with self
.subTest(action
="dispose", inverted
=False):
2449 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
2450 compute_value
.return_value
= D("0.125")
2452 value_from
= portfolio
.Amount("BTC", "10")
2453 value_from
.rate
= D("0.1")
2454 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2455 value_to
= portfolio
.Amount("BTC", "1")
2456 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2458 trade
.prepare_order()
2460 filled_amount
.assert_called_with(in_base_currency
=False)
2461 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2462 self
.assertEqual(1, len(trade
.orders
))
2463 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
2464 D("0.125"), "BTC", "long", self
.m
,
2465 trade
, close_if_possible
=False)
2467 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
2468 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
2469 compute_value
.return_value
= D("0.125")
2471 value_from
= portfolio
.Amount("BTC", "10")
2472 value_from
.rate
= D("0.1")
2473 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2474 value_to
= portfolio
.Amount("BTC", "1")
2475 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2477 trade
.prepare_order(close_if_possible
=True)
2479 filled_amount
.assert_called_with(in_base_currency
=False)
2480 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2481 self
.assertEqual(1, len(trade
.orders
))
2482 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
2483 D("0.125"), "BTC", "long", self
.m
,
2484 trade
, close_if_possible
=True)
2486 with self
.subTest(action
="acquire", inverted
=False):
2487 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
2488 compute_value
.return_value
= D("0.125")
2490 value_from
= portfolio
.Amount("BTC", "1")
2491 value_from
.rate
= D("0.1")
2492 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
2493 value_to
= portfolio
.Amount("BTC", "10")
2494 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2496 trade
.prepare_order()
2498 filled_amount
.assert_called_with(in_base_currency
=True)
2499 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
2500 self
.assertEqual(1, len(trade
.orders
))
2502 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
2503 D("0.125"), "BTC", "long", self
.m
,
2504 trade
, close_if_possible
=False)
2506 with self
.subTest(close_if_possible
=True):
2507 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
2508 compute_value
.return_value
= D("0.125")
2510 value_from
= portfolio
.Amount("BTC", "10")
2511 value_from
.rate
= D("0.1")
2512 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2513 value_to
= portfolio
.Amount("BTC", "0")
2514 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2516 trade
.prepare_order()
2518 filled_amount
.assert_called_with(in_base_currency
=False)
2519 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2520 self
.assertEqual(1, len(trade
.orders
))
2521 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
2522 D("0.125"), "BTC", "long", self
.m
,
2523 trade
, close_if_possible
=True)
2525 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
2526 with self
.subTest(action
="dispose", inverted
=True):
2527 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
2528 compute_value
.return_value
= D("125")
2530 value_from
= portfolio
.Amount("BTC", "10")
2531 value_from
.rate
= D("0.01")
2532 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
2533 value_to
= portfolio
.Amount("BTC", "1")
2534 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2536 trade
.prepare_order(compute_value
="foo")
2538 filled_amount
.assert_called_with(in_base_currency
=True)
2539 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
2540 self
.assertEqual(1, len(trade
.orders
))
2541 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
2542 D("125"), "FOO", "long", self
.m
,
2543 trade
, close_if_possible
=False)
2545 with self
.subTest(action
="acquire", inverted
=True):
2546 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
2547 compute_value
.return_value
= D("125")
2549 value_from
= portfolio
.Amount("BTC", "1")
2550 value_from
.rate
= D("0.01")
2551 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2552 value_to
= portfolio
.Amount("BTC", "10")
2553 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2555 trade
.prepare_order(compute_value
="foo")
2557 filled_amount
.assert_called_with(in_base_currency
=False)
2558 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
2559 self
.assertEqual(1, len(trade
.orders
))
2560 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
2561 D("125"), "FOO", "long", self
.m
,
2562 trade
, close_if_possible
=False)
2565 @mock.patch.object(portfolio
.Trade
, "prepare_order")
2566 def test_update_order(self
, prepare_order
):
2567 order_mock
= mock
.Mock()
2568 new_order_mock
= mock
.Mock()
2570 value_from
= portfolio
.Amount("BTC", "0.5")
2571 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2572 value_to
= portfolio
.Amount("BTC", "1.0")
2573 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2574 prepare_order
.return_value
= new_order_mock
2576 for i
in [0, 1, 3, 4, 6]:
2577 with self
.subTest(tick
=i
):
2578 trade
.update_order(order_mock
, i
)
2579 order_mock
.cancel
.assert_not_called()
2580 new_order_mock
.run
.assert_not_called()
2581 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
2582 update
="waiting", compute_value
=None, new_order
=None)
2584 order_mock
.reset_mock()
2585 new_order_mock
.reset_mock()
2587 self
.m
.report
.log_order
.reset_mock()
2589 trade
.update_order(order_mock
, 2)
2590 order_mock
.cancel
.assert_called()
2591 new_order_mock
.run
.assert_called()
2592 prepare_order
.assert_called()
2593 self
.m
.report
.log_order
.assert_called()
2594 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2596 mock
.call(order_mock
, 2, update
="adjusting",
2597 compute_value
=mock
.ANY
,
2598 new_order
=new_order_mock
),
2599 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
2601 self
.m
.report
.log_order
.assert_has_calls(calls
)
2603 order_mock
.reset_mock()
2604 new_order_mock
.reset_mock()
2606 self
.m
.report
.log_order
.reset_mock()
2608 trade
.update_order(order_mock
, 5)
2609 order_mock
.cancel
.assert_called()
2610 new_order_mock
.run
.assert_called()
2611 prepare_order
.assert_called()
2612 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2613 self
.m
.report
.log_order
.assert_called()
2615 mock
.call(order_mock
, 5, update
="adjusting",
2616 compute_value
=mock
.ANY
,
2617 new_order
=new_order_mock
),
2618 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
2620 self
.m
.report
.log_order
.assert_has_calls(calls
)
2622 order_mock
.reset_mock()
2623 new_order_mock
.reset_mock()
2625 self
.m
.report
.log_order
.reset_mock()
2627 trade
.update_order(order_mock
, 7)
2628 order_mock
.cancel
.assert_called()
2629 new_order_mock
.run
.assert_called()
2630 prepare_order
.assert_called_with(compute_value
="default")
2631 self
.m
.report
.log_order
.assert_called()
2632 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2634 mock
.call(order_mock
, 7, update
="market_fallback",
2635 compute_value
='default',
2636 new_order
=new_order_mock
),
2637 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
2639 self
.m
.report
.log_order
.assert_has_calls(calls
)
2641 order_mock
.reset_mock()
2642 new_order_mock
.reset_mock()
2644 self
.m
.report
.log_order
.reset_mock()
2646 for i
in [10, 13, 16]:
2647 with self
.subTest(tick
=i
):
2648 trade
.update_order(order_mock
, i
)
2649 order_mock
.cancel
.assert_called()
2650 new_order_mock
.run
.assert_called()
2651 prepare_order
.assert_called_with(compute_value
="default")
2652 self
.m
.report
.log_order
.assert_called()
2653 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2655 mock
.call(order_mock
, i
, update
="market_adjust",
2656 compute_value
='default',
2657 new_order
=new_order_mock
),
2658 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
2660 self
.m
.report
.log_order
.assert_has_calls(calls
)
2662 order_mock
.reset_mock()
2663 new_order_mock
.reset_mock()
2665 self
.m
.report
.log_order
.reset_mock()
2667 for i
in [8, 9, 11, 12]:
2668 with self
.subTest(tick
=i
):
2669 trade
.update_order(order_mock
, i
)
2670 order_mock
.cancel
.assert_not_called()
2671 new_order_mock
.run
.assert_not_called()
2672 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
2673 compute_value
=None, new_order
=None)
2675 order_mock
.reset_mock()
2676 new_order_mock
.reset_mock()
2678 self
.m
.report
.log_order
.reset_mock()
2681 def test_print_with_order(self
):
2682 value_from
= portfolio
.Amount("BTC", "0.5")
2683 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2684 value_to
= portfolio
.Amount("BTC", "1.0")
2685 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2687 order_mock1
= mock
.Mock()
2688 order_mock1
.__repr__
= mock
.Mock()
2689 order_mock1
.__repr__
.return_value
= "Mock 1"
2690 order_mock2
= mock
.Mock()
2691 order_mock2
.__repr__
= mock
.Mock()
2692 order_mock2
.__repr__
.return_value
= "Mock 2"
2693 order_mock1
.mouvements
= []
2694 mouvement_mock1
= mock
.Mock()
2695 mouvement_mock1
.__repr__
= mock
.Mock()
2696 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
2697 mouvement_mock2
= mock
.Mock()
2698 mouvement_mock2
.__repr__
= mock
.Mock()
2699 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
2700 order_mock2
.mouvements
= [
2701 mouvement_mock1
, mouvement_mock2
2703 trade
.orders
.append(order_mock1
)
2704 trade
.orders
.append(order_mock2
)
2706 with mock
.patch
.object(trade
, "filled_amount") as filled
:
2707 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
2709 trade
.print_with_order()
2711 self
.m
.report
.print_log
.assert_called()
2712 calls
= self
.m
.report
.print_log
.mock_calls
2713 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
2714 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
2715 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
2716 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
2717 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
2719 self
.m
.report
.print_log
.reset_mock()
2721 filled
.return_value
= portfolio
.Amount("BTC", "0.5")
2722 trade
.print_with_order()
2723 calls
= self
.m
.report
.print_log
.mock_calls
2724 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls
[0][1][0]))
2726 self
.m
.report
.print_log
.reset_mock()
2728 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
2730 trade
.print_with_order()
2731 calls
= self
.m
.report
.print_log
.mock_calls
2732 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls
[0][1][0]))
2734 def test_close(self
):
2735 value_from
= portfolio
.Amount("BTC", "0.5")
2736 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2737 value_to
= portfolio
.Amount("BTC", "1.0")
2738 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2739 order1
= mock
.Mock()
2740 trade
.orders
.append(order1
)
2744 self
.assertEqual(True, trade
.closed
)
2745 order1
.cancel
.assert_called_once_with()
2747 def test_pending(self
):
2748 value_from
= portfolio
.Amount("BTC", "0.5")
2749 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2750 value_to
= portfolio
.Amount("BTC", "1.0")
2751 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2754 self
.assertEqual(False, trade
.pending
)
2756 trade
.closed
= False
2757 self
.assertEqual(True, trade
.pending
)
2759 order1
= mock
.Mock()
2760 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.5")
2761 trade
.orders
.append(order1
)
2762 self
.assertEqual(False, trade
.pending
)
2764 def test__repr(self
):
2765 value_from
= portfolio
.Amount("BTC", "0.5")
2766 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2767 value_to
= portfolio
.Amount("BTC", "1.0")
2768 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2770 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
2772 def test_as_json(self
):
2773 value_from
= portfolio
.Amount("BTC", "0.5")
2774 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2775 value_to
= portfolio
.Amount("BTC", "1.0")
2776 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2778 as_json
= trade
.as_json()
2779 self
.assertEqual("acquire", as_json
["action"])
2780 self
.assertEqual(D("0.5"), as_json
["from"])
2781 self
.assertEqual(D("1.0"), as_json
["to"])
2782 self
.assertEqual("ETH", as_json
["currency"])
2783 self
.assertEqual("BTC", as_json
["base_currency"])
2785 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2786 class OrderTest(WebMockTestCase
):
2787 def test_values(self
):
2788 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2789 D("0.1"), "BTC", "long", "market", "trade")
2790 self
.assertEqual("buy", order
.action
)
2791 self
.assertEqual(10, order
.amount
.value
)
2792 self
.assertEqual("ETH", order
.amount
.currency
)
2793 self
.assertEqual(D("0.1"), order
.rate
)
2794 self
.assertEqual("BTC", order
.base_currency
)
2795 self
.assertEqual("market", order
.market
)
2796 self
.assertEqual("long", order
.trade_type
)
2797 self
.assertEqual("pending", order
.status
)
2798 self
.assertEqual("trade", order
.trade
)
2799 self
.assertIsNone(order
.id)
2800 self
.assertFalse(order
.close_if_possible
)
2802 def test__repr(self
):
2803 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2804 D("0.1"), "BTC", "long", "market", "trade")
2805 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
2807 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2808 D("0.1"), "BTC", "long", "market", "trade",
2809 close_if_possible
=True)
2810 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
2812 def test_as_json(self
):
2813 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2814 D("0.1"), "BTC", "long", "market", "trade")
2815 mouvement_mock1
= mock
.Mock()
2816 mouvement_mock1
.as_json
.return_value
= 1
2817 mouvement_mock2
= mock
.Mock()
2818 mouvement_mock2
.as_json
.return_value
= 2
2820 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
2821 as_json
= order
.as_json()
2822 self
.assertEqual("buy", as_json
["action"])
2823 self
.assertEqual("long", as_json
["trade_type"])
2824 self
.assertEqual(10, as_json
["amount"])
2825 self
.assertEqual("ETH", as_json
["currency"])
2826 self
.assertEqual("BTC", as_json
["base_currency"])
2827 self
.assertEqual(D("0.1"), as_json
["rate"])
2828 self
.assertEqual("pending", as_json
["status"])
2829 self
.assertEqual(False, as_json
["close_if_possible"])
2830 self
.assertIsNone(as_json
["id"])
2831 self
.assertEqual([1, 2], as_json
["mouvements"])
2833 def test_account(self
):
2834 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2835 D("0.1"), "BTC", "long", "market", "trade")
2836 self
.assertEqual("exchange", order
.account
)
2838 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2839 D("0.1"), "BTC", "short", "market", "trade")
2840 self
.assertEqual("margin", order
.account
)
2842 def test_pending(self
):
2843 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2844 D("0.1"), "BTC", "long", "market", "trade")
2845 self
.assertTrue(order
.pending
)
2846 order
.status
= "open"
2847 self
.assertFalse(order
.pending
)
2849 def test_open(self
):
2850 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2851 D("0.1"), "BTC", "long", "market", "trade")
2852 self
.assertFalse(order
.open)
2853 order
.status
= "open"
2854 self
.assertTrue(order
.open)
2856 def test_finished(self
):
2857 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2858 D("0.1"), "BTC", "long", "market", "trade")
2859 self
.assertFalse(order
.finished
)
2860 order
.status
= "closed"
2861 self
.assertTrue(order
.finished
)
2862 order
.status
= "canceled"
2863 self
.assertTrue(order
.finished
)
2864 order
.status
= "error"
2865 self
.assertTrue(order
.finished
)
2867 @mock.patch.object(portfolio
.Order
, "fetch")
2868 def test_cancel(self
, fetch
):
2869 with self
.subTest(debug
=True):
2871 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2872 D("0.1"), "BTC", "long", self
.m
, "trade")
2873 order
.status
= "open"
2876 self
.m
.ccxt
.cancel_order
.assert_not_called()
2877 self
.m
.report
.log_debug_action
.assert_called_once()
2878 self
.m
.report
.log_debug_action
.reset_mock()
2879 self
.assertEqual("canceled", order
.status
)
2881 with self
.subTest(desc
="Nominal case"):
2882 self
.m
.debug
= False
2883 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2884 D("0.1"), "BTC", "long", self
.m
, "trade")
2885 order
.status
= "open"
2889 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
2890 fetch
.assert_called_once_with()
2891 self
.m
.report
.log_debug_action
.assert_not_called()
2893 with self
.subTest(exception
=True):
2894 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
2895 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2896 D("0.1"), "BTC", "long", self
.m
, "trade")
2897 order
.status
= "open"
2900 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
2901 self
.m
.report
.log_error
.assert_called_once()
2904 with self
.subTest(id=None):
2905 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
2906 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2907 D("0.1"), "BTC", "long", self
.m
, "trade")
2908 order
.status
= "open"
2910 self
.m
.ccxt
.cancel_order
.assert_not_called()
2913 with self
.subTest(open=False):
2914 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
2915 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2916 D("0.1"), "BTC", "long", self
.m
, "trade")
2917 order
.status
= "closed"
2919 self
.m
.ccxt
.cancel_order
.assert_not_called()
2921 def test_dust_amount_remaining(self
):
2922 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2923 D("0.1"), "BTC", "long", self
.m
, "trade")
2924 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
2925 self
.assertFalse(order
.dust_amount_remaining())
2927 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
2928 self
.assertTrue(order
.dust_amount_remaining())
2930 @mock.patch.object(portfolio
.Order
, "fetch")
2931 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
2932 def test_remaining_amount(self
, filled_amount
, fetch
):
2933 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2934 D("0.1"), "BTC", "long", self
.m
, "trade")
2936 self
.assertEqual(9, order
.remaining_amount().value
)
2938 order
.status
= "open"
2939 self
.assertEqual(9, order
.remaining_amount().value
)
2941 @mock.patch.object(portfolio
.Order
, "fetch")
2942 def test_filled_amount(self
, fetch
):
2943 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2944 D("0.1"), "BTC", "long", self
.m
, "trade")
2945 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
2946 "tradeID": 42, "type": "buy", "fee": "0.0015",
2947 "date": "2017-12-30 12:00:12", "rate": "0.1",
2948 "amount": "3", "total": "0.3"
2950 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
2951 "tradeID": 43, "type": "buy", "fee": "0.0015",
2952 "date": "2017-12-30 13:00:12", "rate": "0.2",
2953 "amount": "2", "total": "0.4"
2955 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
2956 fetch
.assert_not_called()
2957 order
.status
= "open"
2958 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
2959 fetch
.assert_called_once()
2960 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
2962 def test_fetch_mouvements(self
):
2963 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
2965 "tradeID": 42, "type": "buy", "fee": "0.0015",
2966 "date": "2017-12-30 12:00:12", "rate": "0.1",
2967 "amount": "3", "total": "0.3"
2970 "tradeID": 43, "type": "buy", "fee": "0.0015",
2971 "date": "2017-12-30 13:00:12", "rate": "0.2",
2972 "amount": "2", "total": "0.4"
2975 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2976 D("0.1"), "BTC", "long", self
.m
, "trade")
2978 order
.mouvements
= ["Foo", "Bar", "Baz"]
2980 order
.fetch_mouvements()
2982 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
2983 self
.assertEqual(2, len(order
.mouvements
))
2984 self
.assertEqual(42, order
.mouvements
[0].id)
2985 self
.assertEqual(43, order
.mouvements
[1].id)
2987 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
2988 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2989 D("0.1"), "BTC", "long", self
.m
, "trade")
2990 order
.fetch_mouvements()
2991 self
.assertEqual(0, len(order
.mouvements
))
2993 def test_mark_finished_order(self
):
2994 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2995 D("0.1"), "BTC", "short", self
.m
, "trade",
2996 close_if_possible
=True)
2997 order
.status
= "closed"
2998 self
.m
.debug
= False
3000 order
.mark_finished_order()
3001 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
3002 self
.m
.ccxt
.close_margin_position
.reset_mock()
3004 order
.status
= "open"
3005 order
.mark_finished_order()
3006 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3008 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3009 D("0.1"), "BTC", "short", self
.m
, "trade",
3010 close_if_possible
=False)
3011 order
.status
= "closed"
3012 order
.mark_finished_order()
3013 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3015 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
3016 D("0.1"), "BTC", "short", self
.m
, "trade",
3017 close_if_possible
=True)
3018 order
.status
= "closed"
3019 order
.mark_finished_order()
3020 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3022 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3023 D("0.1"), "BTC", "long", self
.m
, "trade",
3024 close_if_possible
=True)
3025 order
.status
= "closed"
3026 order
.mark_finished_order()
3027 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3031 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3032 D("0.1"), "BTC", "short", self
.m
, "trade",
3033 close_if_possible
=True)
3034 order
.status
= "closed"
3036 order
.mark_finished_order()
3037 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3038 self
.m
.report
.log_debug_action
.assert_called_once()
3040 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
3041 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
3042 def test_fetch(self
, mark_finished_order
, fetch_mouvements
):
3043 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3044 D("0.1"), "BTC", "long", self
.m
, "trade")
3046 with self
.subTest(debug
=True):
3049 self
.m
.report
.log_debug_action
.assert_called_once()
3050 self
.m
.report
.log_debug_action
.reset_mock()
3051 self
.m
.ccxt
.fetch_order
.assert_not_called()
3052 mark_finished_order
.assert_not_called()
3053 fetch_mouvements
.assert_not_called()
3055 with self
.subTest(debug
=False):
3056 self
.m
.debug
= False
3057 self
.m
.ccxt
.fetch_order
.return_value
= {
3059 "datetime": "timestamp"
3063 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45)
3064 fetch_mouvements
.assert_called_once()
3065 self
.assertEqual("foo", order
.status
)
3066 self
.assertEqual("timestamp", order
.timestamp
)
3067 self
.assertEqual(1, len(order
.results
))
3068 self
.m
.report
.log_debug_action
.assert_not_called()
3069 mark_finished_order
.assert_called_once()
3071 mark_finished_order
.reset_mock()
3072 with self
.subTest(missing_order
=True):
3073 self
.m
.ccxt
.fetch_order
.side_effect
= [
3074 portfolio
.OrderNotCached
,
3077 self
.assertEqual("closed_unknown", order
.status
)
3078 mark_finished_order
.assert_called_once()
3080 @mock.patch.object(portfolio
.Order
, "fetch")
3081 def test_get_status(self
, fetch
):
3082 with self
.subTest(debug
=True):
3084 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3085 D("0.1"), "BTC", "long", self
.m
, "trade")
3086 self
.assertEqual("pending", order
.get_status())
3087 fetch
.assert_not_called()
3088 self
.m
.report
.log_debug_action
.assert_called_once()
3090 with self
.subTest(debug
=False, finished
=False):
3091 self
.m
.debug
= False
3092 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3093 D("0.1"), "BTC", "long", self
.m
, "trade")
3095 def update_status():
3096 order
.status
= "open"
3097 return update_status
3098 fetch
.side_effect
= _fetch(order
)
3099 self
.assertEqual("open", order
.get_status())
3100 fetch
.assert_called_once()
3103 with self
.subTest(debug
=False, finished
=True):
3104 self
.m
.debug
= False
3105 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3106 D("0.1"), "BTC", "long", self
.m
, "trade")
3108 def update_status():
3109 order
.status
= "closed"
3110 return update_status
3111 fetch
.side_effect
= _fetch(order
)
3112 self
.assertEqual("closed", order
.get_status())
3113 fetch
.assert_called_once()
3116 self
.m
.ccxt
.order_precision
.return_value
= 4
3117 with self
.subTest(debug
=True):
3119 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3120 D("0.1"), "BTC", "long", self
.m
, "trade")
3122 self
.m
.ccxt
.create_order
.assert_not_called()
3123 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
3124 self
.assertEqual("open", order
.status
)
3125 self
.assertEqual(1, len(order
.results
))
3126 self
.assertEqual(-1, order
.id)
3128 self
.m
.ccxt
.create_order
.reset_mock()
3129 with self
.subTest(debug
=False):
3130 self
.m
.debug
= False
3131 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3132 D("0.1"), "BTC", "long", self
.m
, "trade")
3133 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
3135 self
.m
.ccxt
.create_order
.assert_called_once()
3136 self
.assertEqual(1, len(order
.results
))
3137 self
.assertEqual("open", order
.status
)
3139 self
.m
.ccxt
.create_order
.reset_mock()
3140 with self
.subTest(exception
=True):
3141 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3142 D("0.1"), "BTC", "long", self
.m
, "trade")
3143 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
3145 self
.m
.ccxt
.create_order
.assert_called_once()
3146 self
.assertEqual(0, len(order
.results
))
3147 self
.assertEqual("error", order
.status
)
3148 self
.m
.report
.log_error
.assert_called_once()
3150 self
.m
.ccxt
.create_order
.reset_mock()
3151 with self
.subTest(dust_amount_exception
=True),\
3152 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
3153 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
3154 D("0.1"), "BTC", "long", self
.m
, "trade")
3155 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
3157 self
.m
.ccxt
.create_order
.assert_called_once()
3158 self
.assertEqual(0, len(order
.results
))
3159 self
.assertEqual("closed", order
.status
)
3160 mark_finished_order
.assert_called_once()
3162 self
.m
.ccxt
.order_precision
.return_value
= 8
3163 self
.m
.ccxt
.create_order
.reset_mock()
3164 with self
.subTest(insufficient_funds
=True),\
3165 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
3166 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3167 D("0.1"), "BTC", "long", self
.m
, "trade")
3168 self
.m
.ccxt
.create_order
.side_effect
= [
3169 portfolio
.InsufficientFunds
,
3170 portfolio
.InsufficientFunds
,
3171 portfolio
.InsufficientFunds
,
3175 self
.m
.ccxt
.create_order
.assert_has_calls([
3176 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3177 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
3178 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
3179 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
3181 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
3182 self
.assertEqual(1, len(order
.results
))
3183 self
.assertEqual("open", order
.status
)
3184 self
.assertEqual(4, order
.tries
)
3185 self
.m
.report
.log_error
.assert_called()
3186 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
3188 self
.m
.ccxt
.order_precision
.return_value
= 8
3189 self
.m
.ccxt
.create_order
.reset_mock()
3190 self
.m
.report
.log_error
.reset_mock()
3191 with self
.subTest(insufficient_funds
=True),\
3192 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
3193 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3194 D("0.1"), "BTC", "long", self
.m
, "trade")
3195 self
.m
.ccxt
.create_order
.side_effect
= [
3196 portfolio
.InsufficientFunds
,
3197 portfolio
.InsufficientFunds
,
3198 portfolio
.InsufficientFunds
,
3199 portfolio
.InsufficientFunds
,
3200 portfolio
.InsufficientFunds
,
3203 self
.m
.ccxt
.create_order
.assert_has_calls([
3204 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3205 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
3206 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
3207 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
3208 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
3210 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
3211 self
.assertEqual(0, len(order
.results
))
3212 self
.assertEqual("error", order
.status
)
3213 self
.assertEqual(5, order
.tries
)
3214 self
.m
.report
.log_error
.assert_called()
3215 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
3216 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
)
3219 with self
.subTest(invalid_nonce
=True):
3220 with self
.subTest(retry_success
=True):
3221 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3222 D("0.1"), "BTC", "long", self
.m
, "trade")
3223 self
.m
.ccxt
.create_order
.side_effect
= [
3224 portfolio
.InvalidNonce
,
3225 portfolio
.InvalidNonce
,
3229 self
.m
.ccxt
.create_order
.assert_has_calls([
3230 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3231 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3232 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3234 self
.assertEqual(3, self
.m
.ccxt
.create_order
.call_count
)
3235 self
.assertEqual(3, order
.tries
)
3236 self
.m
.report
.log_error
.assert_called()
3237 self
.assertEqual(2, self
.m
.report
.log_error
.call_count
)
3238 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying after invalid nonce", exception
=mock
.ANY
)
3239 self
.assertEqual(123, order
.id)
3242 with self
.subTest(retry_success
=False):
3243 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3244 D("0.1"), "BTC", "long", self
.m
, "trade")
3245 self
.m
.ccxt
.create_order
.side_effect
= [
3246 portfolio
.InvalidNonce
,
3247 portfolio
.InvalidNonce
,
3248 portfolio
.InvalidNonce
,
3249 portfolio
.InvalidNonce
,
3250 portfolio
.InvalidNonce
,
3253 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
3254 self
.assertEqual(5, order
.tries
)
3255 self
.m
.report
.log_error
.assert_called()
3256 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
3257 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after invalid nonce", exception
=mock
.ANY
)
3258 self
.assertEqual("error", order
.status
)
3261 with self
.subTest(request_timeout
=True):
3262 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3263 D("0.1"), "BTC", "long", self
.m
, "trade")
3264 with self
.subTest(retrieved
=False), \
3265 mock
.patch
.object(order
, "retrieve_order") as retrieve
:
3266 self
.m
.ccxt
.create_order
.side_effect
= [
3267 portfolio
.RequestTimeout
,
3268 portfolio
.RequestTimeout
,
3271 retrieve
.return_value
= False
3273 self
.m
.ccxt
.create_order
.assert_has_calls([
3274 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3275 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3276 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3278 self
.assertEqual(3, self
.m
.ccxt
.create_order
.call_count
)
3279 self
.assertEqual(3, order
.tries
)
3280 self
.m
.report
.log_error
.assert_called()
3281 self
.assertEqual(2, self
.m
.report
.log_error
.call_count
)
3282 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying after timeout", exception
=mock
.ANY
)
3283 self
.assertEqual(123, order
.id)
3286 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3287 D("0.1"), "BTC", "long", self
.m
, "trade")
3288 with self
.subTest(retrieved
=True), \
3289 mock
.patch
.object(order
, "retrieve_order") as retrieve
:
3290 self
.m
.ccxt
.create_order
.side_effect
= [
3291 portfolio
.RequestTimeout
,
3294 order
.results
.append({"id": 123}
)
3296 retrieve
.side_effect
= _retrieve
3298 self
.m
.ccxt
.create_order
.assert_has_calls([
3299 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3301 self
.assertEqual(1, self
.m
.ccxt
.create_order
.call_count
)
3302 self
.assertEqual(1, order
.tries
)
3303 self
.m
.report
.log_error
.assert_called()
3304 self
.assertEqual(1, self
.m
.report
.log_error
.call_count
)
3305 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Timeout, found the order")
3306 self
.assertEqual(123, order
.id)
3309 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3310 D("0.1"), "BTC", "long", self
.m
, "trade")
3311 with self
.subTest(retrieved
=False), \
3312 mock
.patch
.object(order
, "retrieve_order") as retrieve
:
3313 self
.m
.ccxt
.create_order
.side_effect
= [
3314 portfolio
.RequestTimeout
,
3315 portfolio
.RequestTimeout
,
3316 portfolio
.RequestTimeout
,
3317 portfolio
.RequestTimeout
,
3318 portfolio
.RequestTimeout
,
3320 retrieve
.return_value
= False
3322 self
.m
.ccxt
.create_order
.assert_has_calls([
3323 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3324 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3325 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3326 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3327 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3329 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
3330 self
.assertEqual(5, order
.tries
)
3331 self
.m
.report
.log_error
.assert_called()
3332 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
3333 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Giving up Order(buy long 0.00100000 ETH at 0.1 BTC [pending]) after timeouts", exception
=mock
.ANY
)
3334 self
.assertEqual("error", order
.status
)
3336 def test_retrieve_order(self
):
3337 with self
.subTest(similar_open_order
=True):
3338 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3339 D("0.1"), "BTC", "long", self
.m
, "trade")
3340 order
.start_date
= datetime
.datetime(2018, 3, 25, 15, 15, 55)
3342 self
.m
.ccxt
.order_precision
.return_value
= 8
3343 self
.m
.ccxt
.fetch_orders
.return_value
= [
3345 'amount': 0.002, 'cost': 0.1,
3346 'datetime': '2018-03-25T15:15:51.000Z',
3347 'fee': None, 'filled': 0.0,
3351 'date': '2018-03-25 15:15:51',
3352 'margin': 0, 'orderNumber': '1',
3353 'price': '0.1', 'rate': '0.1',
3354 'side': 'buy', 'startingAmount': '0.002',
3355 'status': 'open', 'total': '0.0002',
3358 'price': 0.1, 'remaining': 0.002, 'side': 'buy',
3359 'status': 'open', 'symbol': 'ETH/BTC',
3360 'timestamp': 1521990951000, 'trades': None,
3364 'amount': 0.001, 'cost': 0.1,
3365 'datetime': '2018-03-25T15:15:51.000Z',
3366 'fee': None, 'filled': 0.0,
3370 'date': '2018-03-25 15:15:51',
3371 'margin': 1, 'orderNumber': '2',
3372 'price': '0.1', 'rate': '0.1',
3373 'side': 'buy', 'startingAmount': '0.001',
3374 'status': 'open', 'total': '0.0001',
3377 'price': 0.1, 'remaining': 0.001, 'side': 'buy',
3378 'status': 'open', 'symbol': 'ETH/BTC',
3379 'timestamp': 1521990951000, 'trades': None,
3383 'amount': 0.001, 'cost': 0.1,
3384 'datetime': '2018-03-25T15:15:51.000Z',
3385 'fee': None, 'filled': 0.0,
3389 'date': '2018-03-25 15:15:51',
3390 'margin': 0, 'orderNumber': '3',
3391 'price': '0.1', 'rate': '0.1',
3392 'side': 'sell', 'startingAmount': '0.001',
3393 'status': 'open', 'total': '0.0001',
3396 'price': 0.1, 'remaining': 0.001, 'side': 'sell',
3397 'status': 'open', 'symbol': 'ETH/BTC',
3398 'timestamp': 1521990951000, 'trades': None,
3402 'amount': 0.001, 'cost': 0.15,
3403 'datetime': '2018-03-25T15:15:51.000Z',
3404 'fee': None, 'filled': 0.0,
3408 'date': '2018-03-25 15:15:51',
3409 'margin': 0, 'orderNumber': '4',
3410 'price': '0.15', 'rate': '0.15',
3411 'side': 'buy', 'startingAmount': '0.001',
3412 'status': 'open', 'total': '0.0001',
3415 'price': 0.15, 'remaining': 0.001, 'side': 'buy',
3416 'status': 'open', 'symbol': 'ETH/BTC',
3417 'timestamp': 1521990951000, 'trades': None,
3421 'amount': 0.001, 'cost': 0.1,
3422 'datetime': '2018-03-25T15:15:51.000Z',
3423 'fee': None, 'filled': 0.0,
3427 'date': '2018-03-25 15:15:51',
3428 'margin': 0, 'orderNumber': '1',
3429 'price': '0.1', 'rate': '0.1',
3430 'side': 'buy', 'startingAmount': '0.001',
3431 'status': 'open', 'total': '0.0001',
3434 'price': 0.1, 'remaining': 0.001, 'side': 'buy',
3435 'status': 'open', 'symbol': 'ETH/BTC',
3436 'timestamp': 1521990951000, 'trades': None,
3440 result
= order
.retrieve_order()
3441 self
.assertTrue(result
)
3442 self
.assertEqual('5', order
.results
[0]["id"])
3443 self
.m
.ccxt
.fetch_my_trades
.assert_not_called()
3444 self
.m
.ccxt
.fetch_orders
.assert_called_once_with(symbol
="ETH/BTC", since
=1521983750)
3447 with self
.subTest(similar_open_order
=False, past_trades
=True):
3448 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3449 D("0.1"), "BTC", "long", self
.m
, "trade")
3450 order
.start_date
= datetime
.datetime(2018, 3, 25, 15, 15, 55)
3452 self
.m
.ccxt
.order_precision
.return_value
= 8
3453 self
.m
.ccxt
.fetch_orders
.return_value
= []
3454 self
.m
.ccxt
.fetch_my_trades
.return_value
= [
3455 { # Wrong timestamp 1
3458 'datetime': '2018-03-25T15:15:14.000Z',
3462 'category': 'exchange',
3463 'date': '2018-03-25 15:15:14',
3464 'fee': '0.00150000',
3475 'symbol': 'ETH/BTC',
3476 'timestamp': 1521983714,
3479 { # Wrong timestamp 2
3482 'datetime': '2018-03-25T15:16:54.000Z',
3486 'category': 'exchange',
3487 'date': '2018-03-25 15:16:54',
3488 'fee': '0.00150000',
3499 'symbol': 'ETH/BTC',
3500 'timestamp': 1521983814,
3506 'datetime': '2018-03-25T15:15:54.000Z',
3510 'category': 'exchange',
3511 'date': '2018-03-25 15:15:54',
3512 'fee': '0.00150000',
3523 'symbol': 'ETH/BTC',
3524 'timestamp': 1521983754,
3530 'datetime': '2018-03-25T15:16:54.000Z',
3534 'category': 'exchange',
3535 'date': '2018-03-25 15:16:54',
3536 'fee': '0.00150000',
3547 'symbol': 'ETH/BTC',
3548 'timestamp': 1521983814,
3554 'datetime': '2018-03-25T15:15:54.000Z',
3558 'category': 'marginTrade',
3559 'date': '2018-03-25 15:15:54',
3560 'fee': '0.00150000',
3571 'symbol': 'ETH/BTC',
3572 'timestamp': 1521983754,
3578 'datetime': '2018-03-25T15:16:54.000Z',
3582 'category': 'marginTrade',
3583 'date': '2018-03-25 15:16:54',
3584 'fee': '0.00150000',
3595 'symbol': 'ETH/BTC',
3596 'timestamp': 1521983814,
3602 'datetime': '2018-03-25T15:15:54.000Z',
3606 'category': 'exchange',
3607 'date': '2018-03-25 15:15:54',
3608 'fee': '0.00150000',
3619 'symbol': 'ETH/BTC',
3620 'timestamp': 1521983754,
3626 'datetime': '2018-03-25T15:16:54.000Z',
3630 'category': 'exchange',
3631 'date': '2018-03-25 15:16:54',
3632 'fee': '0.00150000',
3643 'symbol': 'ETH/BTC',
3644 'timestamp': 1521983814,
3650 'datetime': '2018-03-25T15:15:54.000Z',
3654 'category': 'exchange',
3655 'date': '2018-03-25 15:15:54',
3656 'fee': '0.00150000',
3660 'total': '0.000066',
3667 'symbol': 'ETH/BTC',
3668 'timestamp': 1521983754,
3674 'datetime': '2018-03-25T15:16:54.000Z',
3678 'category': 'exchange',
3679 'date': '2018-03-25 15:16:54',
3680 'fee': '0.00150000',
3691 'symbol': 'ETH/BTC',
3692 'timestamp': 1521983814,
3698 'datetime': '2018-03-25T15:15:54.000Z',
3702 'category': 'exchange',
3703 'date': '2018-03-25 15:15:54',
3704 'fee': '0.00150000',
3715 'symbol': 'ETH/BTC',
3716 'timestamp': 1521983754,
3722 'datetime': '2018-03-25T15:16:54.000Z',
3726 'category': 'exchange',
3727 'date': '2018-03-25 15:16:54',
3728 'fee': '0.00150000',
3732 'total': '0.000036',
3739 'symbol': 'ETH/BTC',
3740 'timestamp': 1521983814,
3745 result
= order
.retrieve_order()
3746 self
.assertTrue(result
)
3747 self
.assertEqual('7', order
.results
[0]["id"])
3748 self
.m
.ccxt
.fetch_orders
.assert_called_once_with(symbol
="ETH/BTC", since
=1521983750)
3751 with self
.subTest(similar_open_order
=False, past_trades
=False):
3752 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3753 D("0.1"), "BTC", "long", self
.m
, "trade")
3754 order
.start_date
= datetime
.datetime(2018, 3, 25, 15, 15, 55)
3756 self
.m
.ccxt
.order_precision
.return_value
= 8
3757 self
.m
.ccxt
.fetch_orders
.return_value
= []
3758 self
.m
.ccxt
.fetch_my_trades
.return_value
= []
3759 result
= order
.retrieve_order()
3760 self
.assertFalse(result
)
3762 @unittest.skipUnless("unit" in limits
, "Unit skipped")
3763 class MouvementTest(WebMockTestCase
):
3764 def test_values(self
):
3765 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3766 "tradeID": 42, "type": "buy", "fee": "0.0015",
3767 "date": "2017-12-30 12:00:12", "rate": "0.1",
3768 "amount": "10", "total": "1"
3770 self
.assertEqual("ETH", mouvement
.currency
)
3771 self
.assertEqual("BTC", mouvement
.base_currency
)
3772 self
.assertEqual(42, mouvement
.id)
3773 self
.assertEqual("buy", mouvement
.action
)
3774 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
3775 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
3776 self
.assertEqual(D("0.1"), mouvement
.rate
)
3777 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
3778 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
3780 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
3781 self
.assertIsNone(mouvement
.date
)
3782 self
.assertIsNone(mouvement
.id)
3783 self
.assertIsNone(mouvement
.action
)
3784 self
.assertEqual(-1, mouvement
.fee_rate
)
3785 self
.assertEqual(0, mouvement
.rate
)
3786 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
3787 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
3789 def test__repr(self
):
3790 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3791 "tradeID": 42, "type": "buy", "fee": "0.0015",
3792 "date": "2017-12-30 12:00:12", "rate": "0.1",
3793 "amount": "10", "total": "1"
3795 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
3797 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3798 "tradeID": 42, "type": "buy",
3799 "date": "garbage", "rate": "0.1",
3800 "amount": "10", "total": "1"
3802 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
3804 def test_as_json(self
):
3805 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3806 "tradeID": 42, "type": "buy", "fee": "0.0015",
3807 "date": "2017-12-30 12:00:12", "rate": "0.1",
3808 "amount": "10", "total": "1"
3810 as_json
= mouvement
.as_json()
3812 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
3813 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
3814 self
.assertEqual("buy", as_json
["action"])
3815 self
.assertEqual(D("10"), as_json
["total"])
3816 self
.assertEqual(D("1"), as_json
["total_in_base"])
3817 self
.assertEqual("BTC", as_json
["base_currency"])
3818 self
.assertEqual("ETH", as_json
["currency"])
3820 @unittest.skipUnless("unit" in limits
, "Unit skipped")
3821 class ReportStoreTest(WebMockTestCase
):
3822 def test_add_log(self
):
3823 report_store
= market
.ReportStore(self
.m
)
3824 report_store
.add_log({"foo": "bar"}
)
3826 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
3828 def test_set_verbose(self
):
3829 report_store
= market
.ReportStore(self
.m
)
3830 with self
.subTest(verbose
=True):
3831 report_store
.set_verbose(True)
3832 self
.assertTrue(report_store
.verbose_print
)
3834 with self
.subTest(verbose
=False):
3835 report_store
.set_verbose(False)
3836 self
.assertFalse(report_store
.verbose_print
)
3838 def test_merge(self
):
3839 report_store1
= market
.ReportStore(self
.m
, verbose_print
=False)
3840 report_store2
= market
.ReportStore(None, verbose_print
=False)
3842 report_store2
.log_stage("1")
3843 report_store1
.log_stage("2")
3844 report_store2
.log_stage("3")
3846 report_store1
.merge(report_store2
)
3848 self
.assertEqual(3, len(report_store1
.logs
))
3849 self
.assertEqual(["1", "2", "3"], list(map(lambda x
: x
["stage"], report_store1
.logs
)))
3850 self
.assertEqual(6, len(report_store1
.print_logs
))
3852 def test_print_log(self
):
3853 report_store
= market
.ReportStore(self
.m
)
3854 with self
.subTest(verbose
=True),\
3855 mock
.patch
.object(store
, "datetime") as time_mock
,\
3856 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3857 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25, 2, 20, 10)
3858 report_store
.set_verbose(True)
3859 report_store
.print_log("Coucou")
3860 report_store
.print_log(portfolio
.Amount("BTC", 1))
3861 self
.assertEqual(stdout_mock
.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n")
3863 with self
.subTest(verbose
=False),\
3864 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3865 report_store
.set_verbose(False)
3866 report_store
.print_log("Coucou")
3867 report_store
.print_log(portfolio
.Amount("BTC", 1))
3868 self
.assertEqual(stdout_mock
.getvalue(), "")
3870 def test_default_json_serial(self
):
3871 report_store
= market
.ReportStore(self
.m
)
3873 self
.assertEqual("2018-02-24T00:00:00",
3874 report_store
.default_json_serial(portfolio
.datetime(2018, 2, 24)))
3875 self
.assertEqual("1.00000000 BTC",
3876 report_store
.default_json_serial(portfolio
.Amount("BTC", 1)))
3878 def test_to_json(self
):
3879 report_store
= market
.ReportStore(self
.m
)
3880 report_store
.logs
.append({"foo": "bar"}
)
3881 self
.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store
.to_json())
3882 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
3883 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store
.to_json())
3884 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
3885 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n },\n {\n "amount": "1.00000000 BTC"\n }\n]', report_store
.to_json())
3887 def test_to_json_array(self
):
3888 report_store
= market
.ReportStore(self
.m
)
3889 report_store
.logs
.append({
3890 "date": "date1", "type": "type1", "foo": "bar", "bla": "bla"
3892 report_store
.logs
.append({
3893 "date": "date2", "type": "type2", "foo": "bar", "bla": "bla"
3895 logs
= list(report_store
.to_json_array())
3897 self
.assertEqual(2, len(logs
))
3898 self
.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs
[0])
3899 self
.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs
[1])
3901 @mock.patch.object(market
.ReportStore
, "print_log")
3902 @mock.patch.object(market
.ReportStore
, "add_log")
3903 def test_log_stage(self
, add_log
, print_log
):
3904 report_store
= market
.ReportStore(self
.m
)
3906 report_store
.log_stage("foo", bar
="baz", c
=c
, d
=portfolio
.Amount("BTC", 1))
3907 print_log
.assert_has_calls([
3908 mock
.call("-----------"),
3909 mock
.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
3911 add_log
.assert_called_once_with({
3916 'c': 'c = lambda x: x',
3924 @mock.patch.object(market
.ReportStore
, "print_log")
3925 @mock.patch.object(market
.ReportStore
, "add_log")
3926 def test_log_balances(self
, add_log
, print_log
):
3927 report_store
= market
.ReportStore(self
.m
)
3928 self
.m
.balances
.as_json
.return_value
= "json"
3929 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
3931 report_store
.log_balances(tag
="tag")
3932 print_log
.assert_has_calls([
3933 mock
.call("[Balance]"),
3937 add_log
.assert_called_once_with({
3943 @mock.patch.object(market
.ReportStore
, "print_log")
3944 @mock.patch.object(market
.ReportStore
, "add_log")
3945 def test_log_tickers(self
, add_log
, print_log
):
3946 report_store
= market
.ReportStore(self
.m
)
3948 "BTC": portfolio
.Amount("BTC", 10),
3949 "ETH": portfolio
.Amount("BTC", D("0.3"))
3951 amounts
["ETH"].rate
= D("0.1")
3953 report_store
.log_tickers(amounts
, "BTC", "default", "total")
3954 print_log
.assert_not_called()
3955 add_log
.assert_called_once_with({
3957 'compute_value': 'default',
3958 'balance_type': 'total',
3971 add_log
.reset_mock()
3972 compute_value
= lambda x
: x
["bid"]
3973 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
3974 add_log
.assert_called_once_with({
3976 'compute_value': 'compute_value = lambda x: x["bid"]',
3977 'balance_type': 'total',
3990 @mock.patch.object(market
.ReportStore
, "print_log")
3991 @mock.patch.object(market
.ReportStore
, "add_log")
3992 def test_log_dispatch(self
, add_log
, print_log
):
3993 report_store
= market
.ReportStore(self
.m
)
3994 amount
= portfolio
.Amount("BTC", "10.3")
3996 "BTC": portfolio
.Amount("BTC", 10),
3997 "ETH": portfolio
.Amount("BTC", D("0.3"))
3999 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
4000 print_log
.assert_not_called()
4001 add_log
.assert_called_once_with({
4003 'liquidity': 'medium',
4004 'repartition_ratio': 'repartition',
4015 @mock.patch.object(market
.ReportStore
, "print_log")
4016 @mock.patch.object(market
.ReportStore
, "add_log")
4017 def test_log_trades(self
, add_log
, print_log
):
4018 report_store
= market
.ReportStore(self
.m
)
4019 trade_mock1
= mock
.Mock()
4020 trade_mock2
= mock
.Mock()
4021 trade_mock1
.as_json
.return_value
= { "trade": "1" }
4022 trade_mock2
.as_json
.return_value
= { "trade": "2" }
4024 matching_and_trades
= [
4025 (True, trade_mock1
),
4026 (False, trade_mock2
),
4028 report_store
.log_trades(matching_and_trades
, "only")
4030 print_log
.assert_not_called()
4031 add_log
.assert_called_with({
4036 {'trade': '1', 'skipped': False}
,
4037 {'trade': '2', 'skipped': True}
4041 @mock.patch.object(market
.ReportStore
, "print_log")
4042 @mock.patch.object(market
.ReportStore
, "add_log")
4043 def test_log_orders(self
, add_log
, print_log
):
4044 report_store
= market
.ReportStore(self
.m
)
4046 order_mock1
= mock
.Mock()
4047 order_mock2
= mock
.Mock()
4049 order_mock1
.as_json
.return_value
= "order1"
4050 order_mock2
.as_json
.return_value
= "order2"
4052 orders
= [order_mock1
, order_mock2
]
4054 report_store
.log_orders(orders
, tick
="tick",
4055 only
="only", compute_value
="compute_value")
4057 print_log
.assert_called_once_with("[Orders]")
4058 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
4060 add_log
.assert_called_with({
4063 'compute_value': 'compute_value',
4065 'orders': ['order1', 'order2']
4068 add_log
.reset_mock()
4069 def compute_value(x
, y
):
4071 report_store
.log_orders(orders
, tick
="tick",
4072 only
="only", compute_value
=compute_value
)
4073 add_log
.assert_called_with({
4076 'compute_value': 'def compute_value(x, y):\n return x[y]',
4078 'orders': ['order1', 'order2']
4082 @mock.patch.object(market
.ReportStore
, "print_log")
4083 @mock.patch.object(market
.ReportStore
, "add_log")
4084 def test_log_order(self
, add_log
, print_log
):
4085 report_store
= market
.ReportStore(self
.m
)
4086 order_mock
= mock
.Mock()
4087 order_mock
.as_json
.return_value
= "order"
4088 new_order_mock
= mock
.Mock()
4089 new_order_mock
.as_json
.return_value
= "new_order"
4090 order_mock
.__repr
__ = mock
.Mock()
4091 order_mock
.__repr
__.return_value
= "Order Mock"
4092 new_order_mock
.__repr
__ = mock
.Mock()
4093 new_order_mock
.__repr
__.return_value
= "New order Mock"
4095 with self
.subTest(finished
=True):
4096 report_store
.log_order(order_mock
, 1, finished
=True)
4097 print_log
.assert_called_once_with("[Order] Finished Order Mock")
4098 add_log
.assert_called_once_with({
4103 'compute_value': None,
4107 add_log
.reset_mock()
4108 print_log
.reset_mock()
4110 with self
.subTest(update
="waiting"):
4111 report_store
.log_order(order_mock
, 1, update
="waiting")
4112 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
4113 add_log
.assert_called_once_with({
4116 'update': 'waiting',
4118 'compute_value': None,
4122 add_log
.reset_mock()
4123 print_log
.reset_mock()
4124 with self
.subTest(update
="adjusting"):
4125 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
4126 report_store
.log_order(order_mock
, 3,
4127 update
="adjusting", new_order
=new_order_mock
,
4128 compute_value
=compute_value
)
4129 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
4130 add_log
.assert_called_once_with({
4133 'update': 'adjusting',
4135 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
4136 'new_order': 'new_order'
4139 add_log
.reset_mock()
4140 print_log
.reset_mock()
4141 with self
.subTest(update
="market_fallback"):
4142 report_store
.log_order(order_mock
, 7,
4143 update
="market_fallback", new_order
=new_order_mock
)
4144 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
4145 add_log
.assert_called_once_with({
4148 'update': 'market_fallback',
4150 'compute_value': None,
4151 'new_order': 'new_order'
4154 add_log
.reset_mock()
4155 print_log
.reset_mock()
4156 with self
.subTest(update
="market_adjusting"):
4157 report_store
.log_order(order_mock
, 17,
4158 update
="market_adjust", new_order
=new_order_mock
)
4159 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
4160 add_log
.assert_called_once_with({
4163 'update': 'market_adjust',
4165 'compute_value': None,
4166 'new_order': 'new_order'
4169 @mock.patch.object(market
.ReportStore
, "print_log")
4170 @mock.patch.object(market
.ReportStore
, "add_log")
4171 def test_log_move_balances(self
, add_log
, print_log
):
4172 report_store
= market
.ReportStore(self
.m
)
4174 "BTC": portfolio
.Amount("BTC", 10),
4178 "BTC": portfolio
.Amount("BTC", 3),
4181 report_store
.log_move_balances(needed
, moving
)
4182 print_log
.assert_not_called()
4183 add_log
.assert_called_once_with({
4184 'type': 'move_balances',
4196 @mock.patch.object(market
.ReportStore
, "print_log")
4197 @mock.patch.object(market
.ReportStore
, "add_log")
4198 def test_log_http_request(self
, add_log
, print_log
):
4199 report_store
= market
.ReportStore(self
.m
)
4200 response
= mock
.Mock()
4201 response
.status_code
= 200
4202 response
.text
= "Hey"
4204 report_store
.log_http_request("method", "url", "body",
4205 "headers", response
)
4206 print_log
.assert_not_called()
4207 add_log
.assert_called_once_with({
4208 'type': 'http_request',
4212 'headers': 'headers',
4217 @mock.patch.object(market
.ReportStore
, "print_log")
4218 @mock.patch.object(market
.ReportStore
, "add_log")
4219 def test_log_error(self
, add_log
, print_log
):
4220 report_store
= market
.ReportStore(self
.m
)
4221 with self
.subTest(message
=None, exception
=None):
4222 report_store
.log_error("action")
4223 print_log
.assert_called_once_with("[Error] action")
4224 add_log
.assert_called_once_with({
4227 'exception_class': None,
4228 'exception_message': None,
4232 print_log
.reset_mock()
4233 add_log
.reset_mock()
4234 with self
.subTest(message
="Hey", exception
=None):
4235 report_store
.log_error("action", message
="Hey")
4236 print_log
.assert_has_calls([
4237 mock
.call("[Error] action"),
4240 add_log
.assert_called_once_with({
4243 'exception_class': None,
4244 'exception_message': None,
4248 print_log
.reset_mock()
4249 add_log
.reset_mock()
4250 with self
.subTest(message
=None, exception
=Exception("bouh")):
4251 report_store
.log_error("action", exception
=Exception("bouh"))
4252 print_log
.assert_has_calls([
4253 mock
.call("[Error] action"),
4254 mock
.call("\tException: bouh")
4256 add_log
.assert_called_once_with({
4259 'exception_class': "Exception",
4260 'exception_message': "bouh",
4264 print_log
.reset_mock()
4265 add_log
.reset_mock()
4266 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
4267 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
4268 print_log
.assert_has_calls([
4269 mock
.call("[Error] action"),
4270 mock
.call("\tException: bouh"),
4273 add_log
.assert_called_once_with({
4276 'exception_class': "Exception",
4277 'exception_message': "bouh",
4281 @mock.patch.object(market
.ReportStore
, "print_log")
4282 @mock.patch.object(market
.ReportStore
, "add_log")
4283 def test_log_debug_action(self
, add_log
, print_log
):
4284 report_store
= market
.ReportStore(self
.m
)
4285 report_store
.log_debug_action("Hey")
4287 print_log
.assert_called_once_with("[Debug] Hey")
4288 add_log
.assert_called_once_with({
4289 'type': 'debug_action',
4293 @unittest.skipUnless("unit" in limits
, "Unit skipped")
4294 class MainTest(WebMockTestCase
):
4295 def test_make_order(self
):
4296 self
.m
.get_ticker
.return_value
= {
4298 "average": D("0.1"),
4303 with self
.subTest(description
="nominal case"):
4304 main
.make_order(self
.m
, 10, "ETH")
4306 self
.m
.report
.log_stage
.assert_has_calls([
4307 mock
.call("make_order_begin"),
4308 mock
.call("make_order_end"),
4310 self
.m
.balances
.fetch_balances
.assert_has_calls([
4311 mock
.call(tag
="make_order_begin"),
4312 mock
.call(tag
="make_order_end"),
4314 self
.m
.trades
.all
.append
.assert_called_once()
4315 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4316 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
4317 self
.assertEqual(0, trade
.value_from
)
4318 self
.assertEqual("ETH", trade
.currency
)
4319 self
.assertEqual("BTC", trade
.base_currency
)
4320 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
4321 self
.m
.trades
.run_orders
.assert_called_once_with()
4322 self
.m
.follow_orders
.assert_called_once_with()
4324 order
= trade
.orders
[0]
4325 self
.assertEqual(D("0.10"), order
.rate
)
4328 with self
.subTest(compute_value
="default"):
4329 main
.make_order(self
.m
, 10, "ETH", action
="dispose",
4330 compute_value
="ask")
4332 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4333 order
= trade
.orders
[0]
4334 self
.assertEqual(D("0.11"), order
.rate
)
4337 with self
.subTest(follow
=False):
4338 result
= main
.make_order(self
.m
, 10, "ETH", follow
=False)
4340 self
.m
.report
.log_stage
.assert_has_calls([
4341 mock
.call("make_order_begin"),
4342 mock
.call("make_order_end_not_followed"),
4344 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
4346 self
.m
.trades
.all
.append
.assert_called_once()
4347 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4348 self
.assertEqual(0, trade
.value_from
)
4349 self
.assertEqual("ETH", trade
.currency
)
4350 self
.assertEqual("BTC", trade
.base_currency
)
4351 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
4352 self
.m
.trades
.run_orders
.assert_called_once_with()
4353 self
.m
.follow_orders
.assert_not_called()
4354 self
.assertEqual(trade
.orders
[0], result
)
4357 with self
.subTest(base_currency
="USDT"):
4358 main
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
4360 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4361 self
.assertEqual("BTC", trade
.currency
)
4362 self
.assertEqual("USDT", trade
.base_currency
)
4365 with self
.subTest(close_if_possible
=True):
4366 main
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
4368 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4369 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
4372 with self
.subTest(action
="dispose"):
4373 main
.make_order(self
.m
, 10, "ETH", action
="dispose")
4375 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4376 self
.assertEqual(0, trade
.value_to
)
4377 self
.assertEqual(1, trade
.value_from
.value
)
4378 self
.assertEqual("ETH", trade
.currency
)
4379 self
.assertEqual("BTC", trade
.base_currency
)
4382 with self
.subTest(compute_value
="default"):
4383 main
.make_order(self
.m
, 10, "ETH", action
="dispose",
4384 compute_value
="bid")
4386 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4387 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
4389 def test_get_user_market(self
):
4390 with mock
.patch("main.fetch_markets") as main_fetch_markets
,\
4391 mock
.patch("main.parse_config") as main_parse_config
:
4392 with self
.subTest(debug
=False):
4393 main_parse_config
.return_value
= ["pg_config", "report_path"]
4394 main_fetch_markets
.return_value
= [(1, {"key": "market_config"}
, 3)]
4395 m
= main
.get_user_market("config_path.ini", 1)
4397 self
.assertIsInstance(m
, market
.Market
)
4398 self
.assertFalse(m
.debug
)
4400 with self
.subTest(debug
=True):
4401 main_parse_config
.return_value
= ["pg_config", "report_path"]
4402 main_fetch_markets
.return_value
= [(1, {"key": "market_config"}
, 3)]
4403 m
= main
.get_user_market("config_path.ini", 1, debug
=True)
4405 self
.assertIsInstance(m
, market
.Market
)
4406 self
.assertTrue(m
.debug
)
4408 def test_process(self
):
4409 with mock
.patch("market.Market") as market_mock
,\
4410 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4412 args_mock
= mock
.Mock()
4413 args_mock
.action
= "action"
4414 args_mock
.config
= "config"
4415 args_mock
.user
= "user"
4416 args_mock
.debug
= "debug"
4417 args_mock
.before
= "before"
4418 args_mock
.after
= "after"
4419 self
.assertEqual("", stdout_mock
.getvalue())
4421 main
.process("config", 3, 1, args_mock
, "report_path", "pg_config")
4423 market_mock
.from_config
.assert_has_calls([
4424 mock
.call("config", args_mock
, pg_config
="pg_config", market_id
=3, user_id
=1, report_path
="report_path"),
4425 mock
.call().process("action", before
="before", after
="after"),
4428 with self
.subTest(exception
=True):
4429 market_mock
.from_config
.side_effect
= Exception("boo")
4430 main
.process(3, "config", 1, "report_path", args_mock
, "pg_config")
4431 self
.assertEqual("Exception: boo\n", stdout_mock
.getvalue())
4433 def test_main(self
):
4434 with self
.subTest(parallel
=False):
4435 with mock
.patch("main.parse_args") as parse_args
,\
4436 mock
.patch("main.parse_config") as parse_config
,\
4437 mock
.patch("main.fetch_markets") as fetch_markets
,\
4438 mock
.patch("main.process") as process
:
4440 args_mock
= mock
.Mock()
4441 args_mock
.parallel
= False
4442 args_mock
.config
= "config"
4443 args_mock
.user
= "user"
4444 parse_args
.return_value
= args_mock
4446 parse_config
.return_value
= ["pg_config", "report_path"]
4448 fetch_markets
.return_value
= [[3, "config1", 1], [1, "config2", 2]]
4450 main
.main(["Foo", "Bar"])
4452 parse_args
.assert_called_with(["Foo", "Bar"])
4453 parse_config
.assert_called_with("config")
4454 fetch_markets
.assert_called_with("pg_config", "user")
4456 self
.assertEqual(2, process
.call_count
)
4457 process
.assert_has_calls([
4458 mock
.call("config1", 3, 1, args_mock
, "report_path", "pg_config"),
4459 mock
.call("config2", 1, 2, args_mock
, "report_path", "pg_config"),
4461 with self
.subTest(parallel
=True):
4462 with mock
.patch("main.parse_args") as parse_args
,\
4463 mock
.patch("main.parse_config") as parse_config
,\
4464 mock
.patch("main.fetch_markets") as fetch_markets
,\
4465 mock
.patch("main.process") as process
,\
4466 mock
.patch("store.Portfolio.start_worker") as start
:
4468 args_mock
= mock
.Mock()
4469 args_mock
.parallel
= True
4470 args_mock
.config
= "config"
4471 args_mock
.user
= "user"
4472 parse_args
.return_value
= args_mock
4474 parse_config
.return_value
= ["pg_config", "report_path"]
4476 fetch_markets
.return_value
= [[3, "config1", 1], [1, "config2", 2]]
4478 main
.main(["Foo", "Bar"])
4480 parse_args
.assert_called_with(["Foo", "Bar"])
4481 parse_config
.assert_called_with("config")
4482 fetch_markets
.assert_called_with("pg_config", "user")
4484 start
.assert_called_once_with()
4485 self
.assertEqual(2, process
.call_count
)
4486 process
.assert_has_calls([
4487 mock
.call
.__bool
__(),
4488 mock
.call("config1", 3, 1, args_mock
, "report_path", "pg_config"),
4489 mock
.call
.__bool
__(),
4490 mock
.call("config2", 1, 2, args_mock
, "report_path", "pg_config"),
4493 @mock.patch.object(main
.sys
, "exit")
4494 @mock.patch("main.configparser")
4495 @mock.patch("main.os")
4496 def test_parse_config(self
, os
, configparser
, exit
):
4497 with self
.subTest(pg_config
=True, report_path
=None):
4498 config_mock
= mock
.MagicMock()
4499 configparser
.ConfigParser
.return_value
= config_mock
4500 def config(element
):
4501 return element
== "postgresql"
4503 config_mock
.__contains
__.side_effect
= config
4504 config_mock
.__getitem
__.return_value
= "pg_config"
4506 result
= main
.parse_config("configfile")
4508 config_mock
.read
.assert_called_with("configfile")
4510 self
.assertEqual(["pg_config", None], result
)
4512 with self
.subTest(pg_config
=True, report_path
="present"):
4513 config_mock
= mock
.MagicMock()
4514 configparser
.ConfigParser
.return_value
= config_mock
4516 config_mock
.__contains
__.return_value
= True
4517 config_mock
.__getitem
__.side_effect
= [
4518 {"report_path": "report_path"}
,
4519 {"report_path": "report_path"}
,
4523 os
.path
.exists
.return_value
= False
4524 result
= main
.parse_config("configfile")
4526 config_mock
.read
.assert_called_with("configfile")
4527 self
.assertEqual(["pg_config", "report_path"], result
)
4528 os
.path
.exists
.assert_called_once_with("report_path")
4529 os
.makedirs
.assert_called_once_with("report_path")
4531 with self
.subTest(pg_config
=False),\
4532 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4533 config_mock
= mock
.MagicMock()
4534 configparser
.ConfigParser
.return_value
= config_mock
4535 result
= main
.parse_config("configfile")
4537 config_mock
.read
.assert_called_with("configfile")
4538 exit
.assert_called_once_with(1)
4539 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
4541 @mock.patch.object(main
.sys
, "exit")
4542 def test_parse_args(self
, exit
):
4543 with self
.subTest(config
="config.ini"):
4544 args
= main
.parse_args([])
4545 self
.assertEqual("config.ini", args
.config
)
4546 self
.assertFalse(args
.before
)
4547 self
.assertFalse(args
.after
)
4548 self
.assertFalse(args
.debug
)
4550 args
= main
.parse_args(["--before", "--after", "--debug"])
4551 self
.assertTrue(args
.before
)
4552 self
.assertTrue(args
.after
)
4553 self
.assertTrue(args
.debug
)
4555 exit
.assert_not_called()
4557 with self
.subTest(config
="inexistant"),\
4558 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4559 args
= main
.parse_args(["--config", "foo.bar"])
4560 exit
.assert_called_once_with(1)
4561 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
4563 @mock.patch.object(main
, "psycopg2")
4564 def test_fetch_markets(self
, psycopg2
):
4565 connect_mock
= mock
.Mock()
4566 cursor_mock
= mock
.MagicMock()
4567 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
4569 connect_mock
.cursor
.return_value
= cursor_mock
4570 psycopg2
.connect
.return_value
= connect_mock
4572 with self
.subTest(user
=None):
4573 rows
= list(main
.fetch_markets({"foo": "bar"}
, None))
4575 psycopg2
.connect
.assert_called_once_with(foo
="bar")
4576 cursor_mock
.execute
.assert_called_once_with("SELECT id,config,user_id FROM market_configs")
4578 self
.assertEqual(["row_1", "row_2"], rows
)
4580 psycopg2
.connect
.reset_mock()
4581 cursor_mock
.execute
.reset_mock()
4582 with self
.subTest(user
=1):
4583 rows
= list(main
.fetch_markets({"foo": "bar"}
, 1))
4585 psycopg2
.connect
.assert_called_once_with(foo
="bar")
4586 cursor_mock
.execute
.assert_called_once_with("SELECT id,config,user_id FROM market_configs WHERE user_id = %s", 1)
4588 self
.assertEqual(["row_1", "row_2"], rows
)
4591 @unittest.skipUnless("unit" in limits
, "Unit skipped")
4592 class ProcessorTest(WebMockTestCase
):
4593 def test_values(self
):
4594 processor
= market
.Processor(self
.m
)
4596 self
.assertEqual(self
.m
, processor
.market
)
4598 def test_run_action(self
):
4599 processor
= market
.Processor(self
.m
)
4601 with mock
.patch
.object(processor
, "parse_args") as parse_args
:
4602 method_mock
= mock
.Mock()
4603 parse_args
.return_value
= [method_mock
, { "foo": "bar" }
]
4605 processor
.run_action("foo", "bar", "baz")
4607 parse_args
.assert_called_with("foo", "bar", "baz")
4609 method_mock
.assert_called_with(foo
="bar")
4611 processor
.run_action("wait_for_recent", "bar", "baz")
4613 method_mock
.assert_called_with(foo
="bar")
4615 def test_select_step(self
):
4616 processor
= market
.Processor(self
.m
)
4618 scenario
= processor
.scenarios
["sell_all"]
4620 self
.assertEqual(scenario
, processor
.select_steps(scenario
, "all"))
4621 self
.assertEqual(["all_sell"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "before"))))
4622 self
.assertEqual(["wait", "all_buy"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "after"))))
4623 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, 2))))
4624 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "wait"))))
4626 with self
.assertRaises(TypeError):
4627 processor
.select_steps(scenario
, ["wait"])
4629 @mock.patch("market.Processor.process_step")
4630 def test_process(self
, process_step
):
4631 processor
= market
.Processor(self
.m
)
4633 processor
.process("sell_all", foo
="bar")
4634 self
.assertEqual(3, process_step
.call_count
)
4636 steps
= list(map(lambda x
: x
[1][1]["name"], process_step
.mock_calls
))
4637 scenario_names
= list(map(lambda x
: x
[1][0], process_step
.mock_calls
))
4638 kwargs
= list(map(lambda x
: x
[1][2], process_step
.mock_calls
))
4639 self
.assertEqual(["all_sell", "wait", "all_buy"], steps
)
4640 self
.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names
)
4641 self
.assertEqual([{"foo":"bar"}
, {"foo":"bar"}
, {"foo":"bar"}
], kwargs
)
4643 process_step
.reset_mock()
4645 processor
.process("sell_needed", steps
=["before", "after"])
4646 self
.assertEqual(3, process_step
.call_count
)
4648 def test_method_arguments(self
):
4649 ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
4650 m
= market
.Market(ccxt
, self
.market_args())
4652 processor
= market
.Processor(m
)
4654 method
, arguments
= processor
.method_arguments("wait_for_recent")
4655 self
.assertEqual(market
.Portfolio
.wait_for_recent
, method
)
4656 self
.assertEqual(["delta", "poll"], arguments
)
4658 method
, arguments
= processor
.method_arguments("prepare_trades")
4659 self
.assertEqual(m
.prepare_trades
, method
)
4660 self
.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments
)
4662 method
, arguments
= processor
.method_arguments("prepare_orders")
4663 self
.assertEqual(m
.trades
.prepare_orders
, method
)
4665 method
, arguments
= processor
.method_arguments("move_balances")
4666 self
.assertEqual(m
.move_balances
, method
)
4668 method
, arguments
= processor
.method_arguments("run_orders")
4669 self
.assertEqual(m
.trades
.run_orders
, method
)
4671 method
, arguments
= processor
.method_arguments("follow_orders")
4672 self
.assertEqual(m
.follow_orders
, method
)
4674 method
, arguments
= processor
.method_arguments("close_trades")
4675 self
.assertEqual(m
.trades
.close_trades
, method
)
4677 def test_process_step(self
):
4678 processor
= market
.Processor(self
.m
)
4680 with mock
.patch
.object(processor
, "run_action") as run_action
:
4681 step
= processor
.scenarios
["sell_needed"][1]
4683 processor
.process_step("foo", step
, {"foo":"bar"}
)
4685 self
.m
.report
.log_stage
.assert_has_calls([
4686 mock
.call("process_foo__1_sell_begin"),
4687 mock
.call("process_foo__1_sell_end"),
4689 self
.m
.balances
.fetch_balances
.assert_has_calls([
4690 mock
.call(tag
="process_foo__1_sell_begin"),
4691 mock
.call(tag
="process_foo__1_sell_end"),
4694 self
.assertEqual(5, run_action
.call_count
)
4696 run_action
.assert_has_calls([
4697 mock
.call('prepare_trades', {}, {'foo': 'bar'}
),
4698 mock
.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}
, {'foo': 'bar'}
),
4699 mock
.call('run_orders', {}, {'foo': 'bar'}
),
4700 mock
.call('follow_orders', {}, {'foo': 'bar'}
),
4701 mock
.call('close_trades', {}, {'foo': 'bar'}
),
4705 with mock
.patch
.object(processor
, "run_action") as run_action
:
4706 step
= processor
.scenarios
["sell_needed"][0]
4708 processor
.process_step("foo", step
, {"foo":"bar"}
)
4709 self
.m
.balances
.fetch_balances
.assert_not_called()
4711 def test_parse_args(self
):
4712 processor
= market
.Processor(self
.m
)
4714 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4715 method_mock
= mock
.Mock()
4716 method_arguments
.return_value
= [
4720 method
, args
= processor
.parse_args("action", {"foo": "bar", "foo2": "bar"}
, {"foo": "bar2", "bla": "bla"}
)
4722 self
.assertEqual(method_mock
, method
)
4723 self
.assertEqual({"foo": "bar2", "foo2": "bar"}
, args
)
4725 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4726 method_mock
= mock
.Mock()
4727 method_arguments
.return_value
= [
4731 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {})
4733 self
.assertEqual(1, len(args
["repartition"]))
4734 self
.assertIn("BTC", args
["repartition"])
4736 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4737 method_mock
= mock
.Mock()
4738 method_arguments
.return_value
= [
4740 ["repartition", "base_currency"]
4742 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {"base_currency": "USDT"}
)
4744 self
.assertEqual(1, len(args
["repartition"]))
4745 self
.assertIn("USDT", args
["repartition"])
4747 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4748 method_mock
= mock
.Mock()
4749 method_arguments
.return_value
= [
4751 ["repartition", "base_currency"]
4753 method
, args
= processor
.parse_args("action", {"repartition": { "ETH": 1 }
}, {"base_currency": "USDT"}
)
4755 self
.assertEqual(1, len(args
["repartition"]))
4756 self
.assertIn("ETH", args
["repartition"])
4759 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
4760 class AcceptanceTest(WebMockTestCase
):
4761 @unittest.expectedFailure
4762 def test_success_sell_only_necessary(self
):
4763 # FIXME: catch stdout
4764 self
.m
.report
.verbose_print
= False
4767 "exchange_free": D("1.0"),
4768 "exchange_used": D("0.0"),
4769 "exchange_total": D("1.0"),
4773 "exchange_free": D("4.0"),
4774 "exchange_used": D("0.0"),
4775 "exchange_total": D("4.0"),
4779 "exchange_free": D("1000.0"),
4780 "exchange_used": D("0.0"),
4781 "exchange_total": D("1000.0"),
4782 "total": D("1000.0"),
4786 "ETH": (D("0.25"), "long"),
4787 "ETC": (D("0.25"), "long"),
4788 "BTC": (D("0.4"), "long"),
4789 "BTD": (D("0.01"), "short"),
4790 "B2X": (D("0.04"), "long"),
4791 "USDT": (D("0.05"), "long"),
4794 def fetch_ticker(symbol
):
4795 if symbol
== "ETH/BTC":
4797 "symbol": "ETH/BTC",
4801 if symbol
== "ETC/BTC":
4803 "symbol": "ETC/BTC",
4807 if symbol
== "XVG/BTC":
4809 "symbol": "XVG/BTC",
4810 "bid": D("0.00003"),
4813 if symbol
== "BTD/BTC":
4815 "symbol": "BTD/BTC",
4819 if symbol
== "B2X/BTC":
4821 "symbol": "B2X/BTC",
4825 if symbol
== "USDT/BTC":
4826 raise helper
.ExchangeError
4827 if symbol
== "BTC/USDT":
4829 "symbol": "BTC/USDT",
4833 self
.fail("Shouldn't have been called with {}".format(symbol
))
4835 market
= mock
.Mock()
4836 market
.fetch_all_balances
.return_value
= fetch_balance
4837 market
.fetch_ticker
.side_effect
= fetch_ticker
4838 with mock
.patch
.object(market
.Portfolio
, "repartition", return_value
=repartition
):
4840 helper
.prepare_trades(market
)
4842 balances
= portfolio
.BalanceStore
.all
4843 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
4844 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
4845 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
4848 trades
= portfolio
.TradeStore
.all
4849 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
4850 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
4851 self
.assertEqual("dispose", trades
[0].action
)
4853 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
4854 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
4855 self
.assertEqual("acquire", trades
[1].action
)
4857 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
4858 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
4859 self
.assertEqual("dispose", trades
[2].action
)
4861 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
4862 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
4863 self
.assertEqual("acquire", trades
[3].action
)
4865 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
4866 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
4867 self
.assertEqual("acquire", trades
[4].action
)
4869 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
4870 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
4871 self
.assertEqual("acquire", trades
[5].action
)
4874 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
4876 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
4877 self
.assertEqual(2, len(all_orders
))
4878 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
4879 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
4880 self
.assertEqual(1000, all_orders
[1].amount
.value
)
4881 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
4884 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
4885 self
.assertEqual("limit", type)
4886 if symbol
== "ETH/BTC":
4887 self
.assertEqual("sell", action
)
4888 self
.assertEqual(D('0.66666666'), amount
)
4889 self
.assertEqual(D("0.14014"), price
)
4890 elif symbol
== "XVG/BTC":
4891 self
.assertEqual("sell", action
)
4892 self
.assertEqual(1000, amount
)
4893 self
.assertEqual(D("0.00003003"), price
)
4895 self
.fail("I shouldn't have been called")
4900 market
.create_order
.side_effect
= create_order
4901 market
.order_precision
.return_value
= 8
4904 portfolio
.TradeStore
.run_orders()
4906 self
.assertEqual("open", all_orders
[0].status
)
4907 self
.assertEqual("open", all_orders
[1].status
)
4909 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
4910 market
.privatePostReturnOrderTrades
.return_value
= [
4912 "tradeID": 42, "type": "buy", "fee": "0.0015",
4913 "date": "2017-12-30 12:00:12", "rate": "0.1",
4914 "amount": "10", "total": "1"
4917 with mock
.patch
.object(market
.time
, "sleep") as sleep
:
4919 helper
.follow_orders(verbose
=False)
4921 sleep
.assert_called_with(30)
4923 for order
in all_orders
:
4924 self
.assertEqual("closed", order
.status
)
4928 "exchange_free": D("1.0") / 3,
4929 "exchange_used": D("0.0"),
4930 "exchange_total": D("1.0") / 3,
4932 "total": D("1.0") / 3,
4935 "exchange_free": D("0.134"),
4936 "exchange_used": D("0.0"),
4937 "exchange_total": D("0.134"),
4939 "total": D("0.134"),
4942 "exchange_free": D("4.0"),
4943 "exchange_used": D("0.0"),
4944 "exchange_total": D("4.0"),
4949 "exchange_free": D("0.0"),
4950 "exchange_used": D("0.0"),
4951 "exchange_total": D("0.0"),
4956 market
.fetch_all_balances
.return_value
= fetch_balance
4958 with mock
.patch
.object(market
.Portfolio
, "repartition", return_value
=repartition
):
4960 helper
.prepare_trades(market
, only
="acquire", compute_value
="average")
4962 balances
= portfolio
.BalanceStore
.all
4963 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
4964 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
4965 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
4966 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
4969 trades
= portfolio
.TradeStore
.all
4970 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
4971 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
4972 self
.assertEqual("dispose", trades
[0].action
)
4974 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
4975 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
4976 self
.assertEqual("acquire", trades
[1].action
)
4978 self
.assertNotIn("BTC", trades
)
4980 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
4981 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
4982 self
.assertEqual("dispose", trades
[2].action
)
4984 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
4985 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
4986 self
.assertEqual("acquire", trades
[3].action
)
4988 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
4989 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
4990 self
.assertEqual("acquire", trades
[4].action
)
4992 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
4993 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
4994 self
.assertEqual("acquire", trades
[5].action
)
4997 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
4999 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
5000 self
.assertEqual(4, len(all_orders
))
5001 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
5002 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
5003 self
.assertEqual("buy", all_orders
[0].action
)
5004 self
.assertEqual("long", all_orders
[0].trade_type
)
5006 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
5007 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
5008 self
.assertEqual("sell", all_orders
[1].action
)
5009 self
.assertEqual("short", all_orders
[1].trade_type
)
5011 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
5012 self
.assertAlmostEqual(0, diff
.value
)
5013 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
5014 self
.assertEqual("buy", all_orders
[2].action
)
5015 self
.assertEqual("long", all_orders
[2].trade_type
)
5017 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
5018 self
.assertEqual(D("16000"), all_orders
[3].rate
)
5019 self
.assertEqual("sell", all_orders
[3].action
)
5020 self
.assertEqual("long", all_orders
[3].trade_type
)
5024 # Move balances to margin
5028 # portfolio.TradeStore.run_orders()
5030 with mock
.patch
.object(market
.time
, "sleep") as sleep
:
5032 helper
.follow_orders(verbose
=False)
5034 sleep
.assert_called_with(30)
5036 if __name__
== '__main__':