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 }
)()
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
:
60 @unittest.skipUnless("unit" in limits
, "Unit skipped")
61 class poloniexETest(unittest
.TestCase
):
64 self
.wm
= requests_mock
.Mocker()
67 self
.s
= market
.ccxt
.poloniexE()
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
):
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
):
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 report_store().log_market
.assert_called_once()
1185 report_store
.reset_mock()
1186 with self
.subTest(quiet
=True):
1187 m
= market
.Market(self
.ccxt
, self
.market_args(quiet
=True))
1188 report_store
.assert_called_with(m
, verbose_print
=False)
1189 report_store().log_market
.assert_called_once()
1191 @mock.patch("market.ccxt")
1192 def test_from_config(self
, ccxt
):
1193 with mock
.patch("market.ReportStore"):
1194 ccxt
.poloniexE
.return_value
= self
.ccxt
1196 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, self
.market_args())
1198 self
.assertEqual(self
.ccxt
, m
.ccxt
)
1200 m
= market
.Market
.from_config({"key": "key", "secred": "secret"}
, self
.market_args(debug
=True))
1201 self
.assertEqual(True, m
.debug
)
1203 def test_get_tickers(self
):
1204 self
.ccxt
.fetch_tickers
.side_effect
= [
1209 m
= market
.Market(self
.ccxt
, self
.market_args())
1210 self
.assertEqual("tickers", m
.get_tickers())
1211 self
.assertEqual("tickers", m
.get_tickers())
1212 self
.ccxt
.fetch_tickers
.assert_called_once()
1214 self
.assertIsNone(m
.get_tickers(refresh
=self
.time
.time()))
1216 def test_get_ticker(self
):
1217 with self
.subTest(get_tickers
=True):
1218 self
.ccxt
.fetch_tickers
.return_value
= {
1219 "ETH/ETC": { "bid": 1, "ask": 3 }
,
1220 "XVG/ETH": { "bid": 10, "ask": 40 }
,
1222 m
= market
.Market(self
.ccxt
, self
.market_args())
1224 ticker
= m
.get_ticker("ETH", "ETC")
1225 self
.assertEqual(1, ticker
["bid"])
1226 self
.assertEqual(3, ticker
["ask"])
1227 self
.assertEqual(2, ticker
["average"])
1228 self
.assertFalse(ticker
["inverted"])
1230 ticker
= m
.get_ticker("ETH", "XVG")
1231 self
.assertEqual(0.0625, ticker
["average"])
1232 self
.assertTrue(ticker
["inverted"])
1233 self
.assertIn("original", ticker
)
1234 self
.assertEqual(10, ticker
["original"]["bid"])
1235 self
.assertEqual(25, ticker
["original"]["average"])
1237 ticker
= m
.get_ticker("XVG", "XMR")
1238 self
.assertIsNone(ticker
)
1240 with self
.subTest(get_tickers
=False):
1241 self
.ccxt
.fetch_tickers
.return_value
= None
1242 self
.ccxt
.fetch_ticker
.side_effect
= [
1243 { "bid": 1, "ask": 3 }
,
1244 market
.ExchangeError("foo"),
1245 { "bid": 10, "ask": 40 }
,
1246 market
.ExchangeError("foo"),
1247 market
.ExchangeError("foo"),
1250 m
= market
.Market(self
.ccxt
, self
.market_args())
1252 ticker
= m
.get_ticker("ETH", "ETC")
1253 self
.ccxt
.fetch_ticker
.assert_called_with("ETH/ETC")
1254 self
.assertEqual(1, ticker
["bid"])
1255 self
.assertEqual(3, ticker
["ask"])
1256 self
.assertEqual(2, ticker
["average"])
1257 self
.assertFalse(ticker
["inverted"])
1259 ticker
= m
.get_ticker("ETH", "XVG")
1260 self
.assertEqual(0.0625, ticker
["average"])
1261 self
.assertTrue(ticker
["inverted"])
1262 self
.assertIn("original", ticker
)
1263 self
.assertEqual(10, ticker
["original"]["bid"])
1264 self
.assertEqual(25, ticker
["original"]["average"])
1266 ticker
= m
.get_ticker("XVG", "XMR")
1267 self
.assertIsNone(ticker
)
1269 def test_fetch_fees(self
):
1270 m
= market
.Market(self
.ccxt
, self
.market_args())
1271 self
.ccxt
.fetch_fees
.return_value
= "Foo"
1272 self
.assertEqual("Foo", m
.fetch_fees())
1273 self
.ccxt
.fetch_fees
.assert_called_once()
1274 self
.ccxt
.reset_mock()
1275 self
.assertEqual("Foo", m
.fetch_fees())
1276 self
.ccxt
.fetch_fees
.assert_not_called()
1278 @mock.patch.object(market
.Portfolio
, "repartition")
1279 @mock.patch.object(market
.Market
, "get_ticker")
1280 @mock.patch.object(market
.TradeStore
, "compute_trades")
1281 def test_prepare_trades(self
, compute_trades
, get_ticker
, repartition
):
1282 repartition
.return_value
= {
1283 "XEM": (D("0.75"), "long"),
1284 "BTC": (D("0.25"), "long"),
1286 def _get_ticker(c1
, c2
):
1287 if c1
== "USDT" and c2
== "BTC":
1288 return { "average": D("0.0001") }
1289 if c1
== "XVG" and c2
== "BTC":
1290 return { "average": D("0.000001") }
1291 if c1
== "XEM" and c2
== "BTC":
1292 return { "average": D("0.001") }
1293 self
.fail("Should be called with {}, {}".format(c1
, c2
))
1294 get_ticker
.side_effect
= _get_ticker
1296 with mock
.patch("market.ReportStore"):
1297 m
= market
.Market(self
.ccxt
, self
.market_args())
1298 self
.ccxt
.fetch_all_balances
.return_value
= {
1300 "exchange_free": D("10000.0"),
1301 "exchange_used": D("0.0"),
1302 "exchange_total": D("10000.0"),
1303 "total": D("10000.0")
1306 "exchange_free": D("10000.0"),
1307 "exchange_used": D("0.0"),
1308 "exchange_total": D("10000.0"),
1309 "total": D("10000.0")
1313 m
.balances
.fetch_balances(tag
="tag")
1316 compute_trades
.assert_called()
1318 call
= compute_trades
.call_args
1319 self
.assertEqual(1, call
[0][0]["USDT"].value
)
1320 self
.assertEqual(D("0.01"), call
[0][0]["XVG"].value
)
1321 self
.assertEqual(D("0.2525"), call
[0][1]["BTC"].value
)
1322 self
.assertEqual(D("0.7575"), call
[0][1]["XEM"].value
)
1323 m
.report
.log_stage
.assert_called_once_with("prepare_trades",
1324 base_currency
='BTC', compute_value
='average',
1325 liquidity
='medium', only
=None, repartition
=None)
1326 m
.report
.log_balances
.assert_called_once_with(tag
="tag")
1329 @mock.patch.object(market
.time
, "sleep")
1330 @mock.patch.object(market
.TradeStore
, "all_orders")
1331 def test_follow_orders(self
, all_orders
, time_mock
):
1332 for debug
, sleep
in [
1333 (False, None), (True, None),
1334 (False, 12), (True, 12)]:
1335 with self
.subTest(sleep
=sleep
, debug
=debug
), \
1336 mock
.patch("market.ReportStore"):
1337 m
= market
.Market(self
.ccxt
, self
.market_args(debug
=debug
))
1339 order_mock1
= mock
.Mock()
1340 order_mock2
= mock
.Mock()
1341 order_mock3
= mock
.Mock()
1342 all_orders
.side_effect
= [
1343 [order_mock1
, order_mock2
],
1344 [order_mock1
, order_mock2
],
1346 [order_mock1
, order_mock3
],
1347 [order_mock1
, order_mock3
],
1349 [order_mock1
, order_mock3
],
1350 [order_mock1
, order_mock3
],
1355 order_mock1
.get_status
.side_effect
= ["open", "open", "closed"]
1356 order_mock2
.get_status
.side_effect
= ["open"]
1357 order_mock3
.get_status
.side_effect
= ["open", "closed"]
1359 order_mock1
.trade
= mock
.Mock()
1360 order_mock2
.trade
= mock
.Mock()
1361 order_mock3
.trade
= mock
.Mock()
1363 m
.follow_orders(sleep
=sleep
)
1365 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 1)
1366 order_mock1
.trade
.update_order
.assert_any_call(order_mock1
, 2)
1367 self
.assertEqual(2, order_mock1
.trade
.update_order
.call_count
)
1368 self
.assertEqual(3, order_mock1
.get_status
.call_count
)
1370 order_mock2
.trade
.update_order
.assert_any_call(order_mock2
, 1)
1371 self
.assertEqual(1, order_mock2
.trade
.update_order
.call_count
)
1372 self
.assertEqual(1, order_mock2
.get_status
.call_count
)
1374 order_mock3
.trade
.update_order
.assert_any_call(order_mock3
, 2)
1375 self
.assertEqual(1, order_mock3
.trade
.update_order
.call_count
)
1376 self
.assertEqual(2, order_mock3
.get_status
.call_count
)
1377 m
.report
.log_stage
.assert_called()
1379 mock
.call("follow_orders_begin"),
1380 mock
.call("follow_orders_tick_1"),
1381 mock
.call("follow_orders_tick_2"),
1382 mock
.call("follow_orders_tick_3"),
1383 mock
.call("follow_orders_end"),
1385 m
.report
.log_stage
.assert_has_calls(calls
)
1386 m
.report
.log_orders
.assert_called()
1387 self
.assertEqual(3, m
.report
.log_orders
.call_count
)
1389 mock
.call([order_mock1
, order_mock2
], tick
=1),
1390 mock
.call([order_mock1
, order_mock3
], tick
=2),
1391 mock
.call([order_mock1
, order_mock3
], tick
=3),
1393 m
.report
.log_orders
.assert_has_calls(calls
)
1395 mock
.call(order_mock1
, 3, finished
=True),
1396 mock
.call(order_mock3
, 3, finished
=True),
1398 m
.report
.log_order
.assert_has_calls(calls
)
1402 m
.report
.log_debug_action
.assert_called_with("Set follow_orders tick to 7s")
1403 time_mock
.assert_called_with(7)
1405 time_mock
.assert_called_with(30)
1407 time_mock
.assert_called_with(sleep
)
1409 with self
.subTest("disappearing order"), \
1410 mock
.patch("market.ReportStore"):
1411 all_orders
.reset_mock()
1412 m
= market
.Market(self
.ccxt
, self
.market_args())
1414 order_mock1
= mock
.Mock()
1415 order_mock2
= mock
.Mock()
1416 all_orders
.side_effect
= [
1417 [order_mock1
, order_mock2
],
1418 [order_mock1
, order_mock2
],
1420 [order_mock1
, order_mock2
],
1421 [order_mock1
, order_mock2
],
1426 order_mock1
.get_status
.side_effect
= ["open", "closed"]
1427 order_mock2
.get_status
.side_effect
= ["open", "error_disappeared"]
1429 order_mock1
.trade
= mock
.Mock()
1430 trade_mock
= mock
.Mock()
1431 order_mock2
.trade
= trade_mock
1433 trade_mock
.tick_actions_recreate
.return_value
= "tick1"
1437 trade_mock
.tick_actions_recreate
.assert_called_once_with(2)
1438 trade_mock
.prepare_order
.assert_called_once_with(compute_value
="tick1")
1439 m
.report
.log_error
.assert_called_once_with("follow_orders", message
=mock
.ANY
)
1441 @mock.patch.object(market
.BalanceStore
, "fetch_balances")
1442 def test_move_balance(self
, fetch_balances
):
1443 for debug
in [True, False]:
1444 with self
.subTest(debug
=debug
),\
1445 mock
.patch("market.ReportStore"):
1446 m
= market
.Market(self
.ccxt
, self
.market_args(debug
=debug
))
1448 value_from
= portfolio
.Amount("BTC", "1.0")
1449 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1450 value_to
= portfolio
.Amount("BTC", "10.0")
1451 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
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 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1458 value_from
= portfolio
.Amount("USDT", "0.0")
1459 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
1460 value_to
= portfolio
.Amount("USDT", "-50.0")
1461 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
1463 m
.trades
.all
= [trade1
, trade2
, trade3
]
1464 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1465 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
1466 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
1467 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
1471 fetch_balances
.assert_called_with()
1472 m
.report
.log_move_balances
.assert_called_once()
1475 m
.report
.log_debug_action
.assert_called()
1476 self
.assertEqual(3, m
.report
.log_debug_action
.call_count
)
1478 self
.ccxt
.transfer_balance
.assert_any_call("BTC", 3, "exchange", "margin")
1479 self
.ccxt
.transfer_balance
.assert_any_call("USDT", 100, "exchange", "margin")
1480 self
.ccxt
.transfer_balance
.assert_any_call("ETC", 5, "margin", "exchange")
1482 m
.report
.reset_mock()
1483 fetch_balances
.reset_mock()
1484 with self
.subTest(retry
=True):
1485 with mock
.patch("market.ReportStore"):
1486 m
= market
.Market(self
.ccxt
, self
.market_args())
1488 value_from
= portfolio
.Amount("BTC", "0.0")
1489 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1490 value_to
= portfolio
.Amount("BTC", "-3.0")
1491 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1493 m
.trades
.all
= [trade
]
1494 balance
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1495 m
.balances
.all
= {"BTC": balance}
1497 m
.ccxt
.transfer_balance
.side_effect
= [
1498 market
.ccxt
.RequestTimeout
,
1499 market
.ccxt
.InvalidNonce
,
1503 self
.ccxt
.transfer_balance
.assert_has_calls([
1504 mock
.call("BTC", 3, "exchange", "margin"),
1505 mock
.call("BTC", 3, "exchange", "margin"),
1506 mock
.call("BTC", 3, "exchange", "margin")
1508 self
.assertEqual(3, fetch_balances
.call_count
)
1509 m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying", exception
=mock
.ANY
)
1510 self
.assertEqual(3, m
.report
.log_move_balances
.call_count
)
1512 self
.ccxt
.transfer_balance
.reset_mock()
1513 m
.report
.reset_mock()
1514 fetch_balances
.reset_mock()
1515 with self
.subTest(retry
=True, too_much
=True):
1516 with mock
.patch("market.ReportStore"):
1517 m
= market
.Market(self
.ccxt
, self
.market_args())
1519 value_from
= portfolio
.Amount("BTC", "0.0")
1520 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1521 value_to
= portfolio
.Amount("BTC", "-3.0")
1522 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1524 m
.trades
.all
= [trade
]
1525 balance
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1526 m
.balances
.all
= {"BTC": balance}
1528 m
.ccxt
.transfer_balance
.side_effect
= [
1529 market
.ccxt
.RequestTimeout
,
1530 market
.ccxt
.RequestTimeout
,
1531 market
.ccxt
.RequestTimeout
,
1532 market
.ccxt
.RequestTimeout
,
1533 market
.ccxt
.RequestTimeout
,
1535 with self
.assertRaises(market
.ccxt
.RequestTimeout
):
1538 self
.ccxt
.transfer_balance
.reset_mock()
1539 m
.report
.reset_mock()
1540 fetch_balances
.reset_mock()
1541 with self
.subTest(retry
=True, partial_result
=True):
1542 with mock
.patch("market.ReportStore"):
1543 m
= market
.Market(self
.ccxt
, self
.market_args())
1545 value_from
= portfolio
.Amount("BTC", "1.0")
1546 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
1547 value_to
= portfolio
.Amount("BTC", "10.0")
1548 trade1
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1550 value_from
= portfolio
.Amount("BTC", "0.0")
1551 value_from
.linked_to
= portfolio
.Amount("ETH", "0.0")
1552 value_to
= portfolio
.Amount("BTC", "-3.0")
1553 trade2
= portfolio
.Trade(value_from
, value_to
, "ETH", m
)
1555 value_from
= portfolio
.Amount("USDT", "0.0")
1556 value_from
.linked_to
= portfolio
.Amount("XVG", "0.0")
1557 value_to
= portfolio
.Amount("USDT", "-50.0")
1558 trade3
= portfolio
.Trade(value_from
, value_to
, "XVG", m
)
1560 m
.trades
.all
= [trade1
, trade2
, trade3
]
1561 balance1
= portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "0" }
)
1562 balance2
= portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "50" }
)
1563 balance3
= portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "15" }
)
1564 m
.balances
.all
= {"BTC": balance1, "USDT": balance2, "ETC": balance3}
1566 call_counts
= { "BTC": 0, "USDT": 0, "ETC": 0 }
1567 def _transfer_balance(currency
, amount
, from_
, to_
):
1568 call_counts
[currency
] += 1
1569 if currency
== "BTC":
1570 m
.balances
.all
["BTC"] = portfolio
.Balance("BTC", { "margin_in_position": "0", "margin_available": "3" }
)
1571 if currency
== "USDT":
1572 if call_counts
["USDT"] == 1:
1573 raise market
.ccxt
.RequestTimeout
1575 m
.balances
.all
["USDT"] = portfolio
.Balance("USDT", { "margin_in_position": "100", "margin_available": "150" }
)
1576 if currency
== "ETC":
1577 m
.balances
.all
["ETC"] = portfolio
.Balance("ETC", { "margin_in_position": "10", "margin_available": "10" }
)
1580 m
.ccxt
.transfer_balance
.side_effect
= _transfer_balance
1583 self
.ccxt
.transfer_balance
.assert_has_calls([
1584 mock
.call("BTC", 3, "exchange", "margin"),
1585 mock
.call('USDT', 100, 'exchange', 'margin'),
1586 mock
.call('USDT', 100, 'exchange', 'margin'),
1587 mock
.call("ETC", 5, "margin", "exchange")
1589 self
.assertEqual(2, fetch_balances
.call_count
)
1590 m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying", exception
=mock
.ANY
)
1591 self
.assertEqual(2, m
.report
.log_move_balances
.call_count
)
1592 m
.report
.log_move_balances
.asser_has_calls([
1595 'BTC': portfolio
.Amount("BTC", "3"),
1596 'USDT': portfolio
.Amount("USDT", "150"),
1597 'ETC': portfolio
.Amount("ETC", "10"),
1600 'BTC': portfolio
.Amount("BTC", "3"),
1601 'USDT': portfolio
.Amount("USDT", "100"),
1605 'BTC': portfolio
.Amount("BTC", "3"),
1606 'USDT': portfolio
.Amount("USDT", "150"),
1607 'ETC': portfolio
.Amount("ETC", "10"),
1610 'BTC': portfolio
.Amount("BTC", "0"),
1611 'USDT': portfolio
.Amount("USDT", "100"),
1612 'ETC': portfolio
.Amount("ETC", "-5"),
1617 def test_store_file_report(self
):
1618 file_open
= mock
.mock_open()
1619 m
= market
.Market(self
.ccxt
, self
.market_args(), report_path
="present", user_id
=1)
1620 with self
.subTest(file="present"),\
1621 mock
.patch("market.open", file_open
),\
1622 mock
.patch
.object(m
, "report") as report
,\
1623 mock
.patch
.object(market
, "datetime") as time_mock
:
1625 report
.print_logs
= [[time_mock
.now(), "Foo"], [time_mock
.now(), "Bar"]]
1626 report
.to_json
.return_value
= "json_content"
1628 m
.store_file_report(datetime
.datetime(2018, 2, 25))
1630 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.json", "w")
1631 file_open
.assert_any_call("present/2018-02-25T00:00:00_1.log", "w")
1632 file_open().write
.assert_any_call("json_content")
1633 file_open().write
.assert_any_call("Foo\nBar")
1634 m
.report
.to_json
.assert_called_once_with()
1636 m
= market
.Market(self
.ccxt
, self
.market_args(), report_path
="error", user_id
=1)
1637 with self
.subTest(file="error"),\
1638 mock
.patch("market.open") as file_open
,\
1639 mock
.patch
.object(m
, "report") as report
,\
1640 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1641 file_open
.side_effect
= FileNotFoundError
1643 m
.store_file_report(datetime
.datetime(2018, 2, 25))
1645 self
.assertRegex(stdout_mock
.getvalue(), "impossible to store report file: FileNotFoundError;")
1647 @mock.patch.object(market
, "psycopg2")
1648 def test_store_database_report(self
, psycopg2
):
1649 connect_mock
= mock
.Mock()
1650 cursor_mock
= mock
.MagicMock()
1652 connect_mock
.cursor
.return_value
= cursor_mock
1653 psycopg2
.connect
.return_value
= connect_mock
1654 m
= market
.Market(self
.ccxt
, self
.market_args(),
1655 pg_config
={"config": "pg_config"}
, user_id
=1)
1656 cursor_mock
.fetchone
.return_value
= [42]
1658 with self
.subTest(error
=False),\
1659 mock
.patch
.object(m
, "report") as report
:
1660 report
.to_json_array
.return_value
= [
1661 ("date1", "type1", "payload1"),
1662 ("date2", "type2", "payload2"),
1664 m
.store_database_report(datetime
.datetime(2018, 3, 24))
1665 connect_mock
.assert_has_calls([
1667 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)),
1668 mock
.call
.cursor().fetchone(),
1669 mock
.call
.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date1', 42, 'type1', 'payload1')),
1670 mock
.call
.cursor().execute('INSERT INTO report_lines("date", "report_id", "type", "payload") VALUES (%s, %s, %s, %s);', ('date2', 42, 'type2', 'payload2')),
1672 mock
.call
.cursor().close(),
1676 connect_mock
.reset_mock()
1677 with self
.subTest(error
=True),\
1678 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
1679 psycopg2
.connect
.side_effect
= Exception("Bouh")
1680 m
.store_database_report(datetime
.datetime(2018, 3, 24))
1681 self
.assertEqual(stdout_mock
.getvalue(), "impossible to store report to database: Exception; Bouh\n")
1683 def test_store_report(self
):
1684 m
= market
.Market(self
.ccxt
, self
.market_args(), user_id
=1)
1685 with self
.subTest(file=None, pg_config
=None),\
1686 mock
.patch
.object(m
, "report") as report
,\
1687 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1688 mock
.patch
.object(m
, "store_file_report") as file_report
:
1690 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1692 file_report
.assert_not_called()
1693 db_report
.assert_not_called()
1696 m
= market
.Market(self
.ccxt
, self
.market_args(), report_path
="present", user_id
=1)
1697 with self
.subTest(file="present", pg_config
=None),\
1698 mock
.patch
.object(m
, "report") as report
,\
1699 mock
.patch
.object(m
, "store_file_report") as file_report
,\
1700 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1701 mock
.patch
.object(market
, "datetime") as time_mock
:
1703 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
1707 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1708 file_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1709 db_report
.assert_not_called()
1712 m
= market
.Market(self
.ccxt
, self
.market_args(), pg_config
="present", user_id
=1)
1713 with self
.subTest(file=None, pg_config
="present"),\
1714 mock
.patch
.object(m
, "report") as report
,\
1715 mock
.patch
.object(m
, "store_file_report") as file_report
,\
1716 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1717 mock
.patch
.object(market
, "datetime") as time_mock
:
1719 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
1723 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1724 file_report
.assert_not_called()
1725 db_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1728 m
= market
.Market(self
.ccxt
, self
.market_args(),
1729 pg_config
="pg_config", report_path
="present", user_id
=1)
1730 with self
.subTest(file="present", pg_config
="present"),\
1731 mock
.patch
.object(m
, "report") as report
,\
1732 mock
.patch
.object(m
, "store_file_report") as file_report
,\
1733 mock
.patch
.object(m
, "store_database_report") as db_report
,\
1734 mock
.patch
.object(market
, "datetime") as time_mock
:
1736 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25)
1740 report
.merge
.assert_called_with(store
.Portfolio
.report
)
1741 file_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1742 db_report
.assert_called_once_with(datetime
.datetime(2018, 2, 25))
1744 def test_print_orders(self
):
1745 m
= market
.Market(self
.ccxt
, self
.market_args())
1746 with mock
.patch
.object(m
.report
, "log_stage") as log_stage
,\
1747 mock
.patch
.object(m
.balances
, "fetch_balances") as fetch_balances
,\
1748 mock
.patch
.object(m
, "prepare_trades") as prepare_trades
,\
1749 mock
.patch
.object(m
.trades
, "prepare_orders") as prepare_orders
:
1752 log_stage
.assert_called_with("print_orders")
1753 fetch_balances
.assert_called_with(tag
="print_orders")
1754 prepare_trades
.assert_called_with(base_currency
="BTC",
1755 compute_value
="average")
1756 prepare_orders
.assert_called_with(compute_value
="average")
1758 def test_print_balances(self
):
1759 m
= market
.Market(self
.ccxt
, self
.market_args())
1761 with mock
.patch
.object(m
.balances
, "in_currency") as in_currency
,\
1762 mock
.patch
.object(m
.report
, "log_stage") as log_stage
,\
1763 mock
.patch
.object(m
.balances
, "fetch_balances") as fetch_balances
,\
1764 mock
.patch
.object(m
.report
, "print_log") as print_log
:
1766 in_currency
.return_value
= {
1767 "BTC": portfolio
.Amount("BTC", "0.65"),
1768 "ETH": portfolio
.Amount("BTC", "0.3"),
1773 log_stage
.assert_called_once_with("print_balances")
1774 fetch_balances
.assert_called_with()
1775 print_log
.assert_has_calls([
1776 mock
.call("total:"),
1777 mock
.call(portfolio
.Amount("BTC", "0.95")),
1780 @mock.patch("market.Processor.process")
1781 @mock.patch("market.ReportStore.log_error")
1782 @mock.patch("market.Market.store_report")
1783 def test_process(self
, store_report
, log_error
, process
):
1784 m
= market
.Market(self
.ccxt
, self
.market_args())
1785 with self
.subTest(before
=False, after
=False):
1788 process
.assert_not_called()
1789 store_report
.assert_called_once()
1790 log_error
.assert_not_called()
1792 process
.reset_mock()
1793 log_error
.reset_mock()
1794 store_report
.reset_mock()
1795 with self
.subTest(before
=True, after
=False):
1796 m
.process(None, before
=True)
1798 process
.assert_called_once_with("sell_all", steps
="before")
1799 store_report
.assert_called_once()
1800 log_error
.assert_not_called()
1802 process
.reset_mock()
1803 log_error
.reset_mock()
1804 store_report
.reset_mock()
1805 with self
.subTest(before
=False, after
=True):
1806 m
.process(None, after
=True)
1808 process
.assert_called_once_with("sell_all", steps
="after")
1809 store_report
.assert_called_once()
1810 log_error
.assert_not_called()
1812 process
.reset_mock()
1813 log_error
.reset_mock()
1814 store_report
.reset_mock()
1815 with self
.subTest(before
=True, after
=True):
1816 m
.process(None, before
=True, after
=True)
1818 process
.assert_has_calls([
1819 mock
.call("sell_all", steps
="before"),
1820 mock
.call("sell_all", steps
="after"),
1822 store_report
.assert_called_once()
1823 log_error
.assert_not_called()
1825 process
.reset_mock()
1826 log_error
.reset_mock()
1827 store_report
.reset_mock()
1828 with self
.subTest(action
="print_balances"),\
1829 mock
.patch
.object(m
, "print_balances") as print_balances
:
1830 m
.process(["print_balances"])
1832 process
.assert_not_called()
1833 log_error
.assert_not_called()
1834 store_report
.assert_called_once()
1835 print_balances
.assert_called_once_with()
1837 log_error
.reset_mock()
1838 store_report
.reset_mock()
1839 with self
.subTest(action
="print_orders"),\
1840 mock
.patch
.object(m
, "print_orders") as print_orders
,\
1841 mock
.patch
.object(m
, "print_balances") as print_balances
:
1842 m
.process(["print_orders", "print_balances"])
1844 process
.assert_not_called()
1845 log_error
.assert_not_called()
1846 store_report
.assert_called_once()
1847 print_orders
.assert_called_once_with()
1848 print_balances
.assert_called_once_with()
1850 log_error
.reset_mock()
1851 store_report
.reset_mock()
1852 with self
.subTest(action
="unknown"):
1853 m
.process(["unknown"])
1854 log_error
.assert_called_once_with("market_process", message
="Unknown action unknown")
1855 store_report
.assert_called_once()
1857 log_error
.reset_mock()
1858 store_report
.reset_mock()
1859 with self
.subTest(unhandled_exception
=True):
1860 process
.side_effect
= Exception("bouh")
1862 m
.process(None, before
=True)
1863 log_error
.assert_called_with("market_process", exception
=mock
.ANY
)
1864 store_report
.assert_called_once()
1866 @unittest.skipUnless("unit" in limits
, "Unit skipped")
1867 class TradeStoreTest(WebMockTestCase
):
1868 def test_compute_trades(self
):
1869 self
.m
.balances
.currencies
.return_value
= ["XMR", "DASH", "XVG", "BTC", "ETH"]
1872 "XMR": portfolio
.Amount("BTC", D("0.9")),
1873 "DASH": portfolio
.Amount("BTC", D("0.4")),
1874 "XVG": portfolio
.Amount("BTC", D("-0.5")),
1875 "BTC": portfolio
.Amount("BTC", D("0.5")),
1878 "DASH": portfolio
.Amount("BTC", D("0.5")),
1879 "XVG": portfolio
.Amount("BTC", D("0.1")),
1880 "BTC": portfolio
.Amount("BTC", D("0.4")),
1881 "ETH": portfolio
.Amount("BTC", D("0.3")),
1891 with mock
.patch
.object(market
.TradeStore
, "trade_if_matching") as trade_if_matching
:
1892 trade_store
= market
.TradeStore(self
.m
)
1893 trade_if_matching
.side_effect
= side_effect
1895 trade_store
.compute_trades(values_in_base
,
1896 new_repartition
, only
="only")
1898 self
.assertEqual(5, trade_if_matching
.call_count
)
1899 self
.assertEqual(3, len(trade_store
.all
))
1900 self
.assertEqual([1, 4, 5], trade_store
.all
)
1901 self
.m
.report
.log_trades
.assert_called_with(side_effect
, "only")
1903 def test_trade_if_matching(self
):
1905 with self
.subTest(only
="nope"):
1906 trade_store
= market
.TradeStore(self
.m
)
1907 result
= trade_store
.trade_if_matching(
1908 portfolio
.Amount("BTC", D("0")),
1909 portfolio
.Amount("BTC", D("0.3")),
1911 self
.assertEqual(False, result
[0])
1912 self
.assertIsInstance(result
[1], portfolio
.Trade
)
1914 with self
.subTest(only
=None):
1915 trade_store
= market
.TradeStore(self
.m
)
1916 result
= trade_store
.trade_if_matching(
1917 portfolio
.Amount("BTC", D("0")),
1918 portfolio
.Amount("BTC", D("0.3")),
1920 self
.assertEqual(True, result
[0])
1922 with self
.subTest(only
="acquire"):
1923 trade_store
= market
.TradeStore(self
.m
)
1924 result
= trade_store
.trade_if_matching(
1925 portfolio
.Amount("BTC", D("0")),
1926 portfolio
.Amount("BTC", D("0.3")),
1927 "ETH", only
="acquire")
1928 self
.assertEqual(True, result
[0])
1930 with self
.subTest(only
="dispose"):
1931 trade_store
= market
.TradeStore(self
.m
)
1932 result
= trade_store
.trade_if_matching(
1933 portfolio
.Amount("BTC", D("0")),
1934 portfolio
.Amount("BTC", D("0.3")),
1935 "ETH", only
="dispose")
1936 self
.assertEqual(False, result
[0])
1938 def test_prepare_orders(self
):
1939 trade_store
= market
.TradeStore(self
.m
)
1941 trade_mock1
= mock
.Mock()
1942 trade_mock2
= mock
.Mock()
1943 trade_mock3
= mock
.Mock()
1945 trade_mock1
.prepare_order
.return_value
= 1
1946 trade_mock2
.prepare_order
.return_value
= 2
1947 trade_mock3
.prepare_order
.return_value
= 3
1949 trade_mock1
.pending
= True
1950 trade_mock2
.pending
= True
1951 trade_mock3
.pending
= False
1953 trade_store
.all
.append(trade_mock1
)
1954 trade_store
.all
.append(trade_mock2
)
1955 trade_store
.all
.append(trade_mock3
)
1957 trade_store
.prepare_orders()
1958 trade_mock1
.prepare_order
.assert_called_with(compute_value
="default")
1959 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1960 trade_mock3
.prepare_order
.assert_not_called()
1961 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "default")
1963 self
.m
.report
.log_orders
.reset_mock()
1965 trade_store
.prepare_orders(compute_value
="bla")
1966 trade_mock1
.prepare_order
.assert_called_with(compute_value
="bla")
1967 trade_mock2
.prepare_order
.assert_called_with(compute_value
="bla")
1968 self
.m
.report
.log_orders
.assert_called_once_with([1, 2], None, "bla")
1970 trade_mock1
.prepare_order
.reset_mock()
1971 trade_mock2
.prepare_order
.reset_mock()
1972 self
.m
.report
.log_orders
.reset_mock()
1974 trade_mock1
.action
= "foo"
1975 trade_mock2
.action
= "bar"
1976 trade_store
.prepare_orders(only
="bar")
1977 trade_mock1
.prepare_order
.assert_not_called()
1978 trade_mock2
.prepare_order
.assert_called_with(compute_value
="default")
1979 self
.m
.report
.log_orders
.assert_called_once_with([2], "bar", "default")
1981 def test_print_all_with_order(self
):
1982 trade_mock1
= mock
.Mock()
1983 trade_mock2
= mock
.Mock()
1984 trade_mock3
= mock
.Mock()
1985 trade_store
= market
.TradeStore(self
.m
)
1986 trade_store
.all
= [trade_mock1
, trade_mock2
, trade_mock3
]
1988 trade_store
.print_all_with_order()
1990 trade_mock1
.print_with_order
.assert_called()
1991 trade_mock2
.print_with_order
.assert_called()
1992 trade_mock3
.print_with_order
.assert_called()
1994 def test_run_orders(self
):
1995 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
1996 order_mock1
= mock
.Mock()
1997 order_mock2
= mock
.Mock()
1998 order_mock3
= mock
.Mock()
1999 trade_store
= market
.TradeStore(self
.m
)
2001 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
2003 trade_store
.run_orders()
2005 all_orders
.assert_called_with(state
="pending")
2007 order_mock1
.run
.assert_called()
2008 order_mock2
.run
.assert_called()
2009 order_mock3
.run
.assert_called()
2011 self
.m
.report
.log_stage
.assert_called_with("run_orders")
2012 self
.m
.report
.log_orders
.assert_called_with([order_mock1
, order_mock2
,
2015 def test_all_orders(self
):
2016 trade_mock1
= mock
.Mock()
2017 trade_mock2
= mock
.Mock()
2019 order_mock1
= mock
.Mock()
2020 order_mock2
= mock
.Mock()
2021 order_mock3
= mock
.Mock()
2023 trade_mock1
.orders
= [order_mock1
, order_mock2
]
2024 trade_mock2
.orders
= [order_mock3
]
2026 order_mock1
.status
= "pending"
2027 order_mock2
.status
= "open"
2028 order_mock3
.status
= "open"
2030 trade_store
= market
.TradeStore(self
.m
)
2031 trade_store
.all
.append(trade_mock1
)
2032 trade_store
.all
.append(trade_mock2
)
2034 orders
= trade_store
.all_orders()
2035 self
.assertEqual(3, len(orders
))
2037 open_orders
= trade_store
.all_orders(state
="open")
2038 self
.assertEqual(2, len(open_orders
))
2039 self
.assertEqual([order_mock2
, order_mock3
], open_orders
)
2041 def test_update_all_orders_status(self
):
2042 with mock
.patch
.object(market
.TradeStore
, "all_orders") as all_orders
:
2043 order_mock1
= mock
.Mock()
2044 order_mock2
= mock
.Mock()
2045 order_mock3
= mock
.Mock()
2047 all_orders
.return_value
= [order_mock1
, order_mock2
, order_mock3
]
2049 trade_store
= market
.TradeStore(self
.m
)
2051 trade_store
.update_all_orders_status()
2052 all_orders
.assert_called_with(state
="open")
2054 order_mock1
.get_status
.assert_called()
2055 order_mock2
.get_status
.assert_called()
2056 order_mock3
.get_status
.assert_called()
2058 def test_close_trades(self
):
2059 trade_mock1
= mock
.Mock()
2060 trade_mock2
= mock
.Mock()
2061 trade_mock3
= mock
.Mock()
2063 trade_store
= market
.TradeStore(self
.m
)
2065 trade_store
.all
.append(trade_mock1
)
2066 trade_store
.all
.append(trade_mock2
)
2067 trade_store
.all
.append(trade_mock3
)
2069 trade_store
.close_trades()
2071 trade_mock1
.close
.assert_called_once_with()
2072 trade_mock2
.close
.assert_called_once_with()
2073 trade_mock3
.close
.assert_called_once_with()
2075 def test_pending(self
):
2076 trade_mock1
= mock
.Mock()
2077 trade_mock1
.pending
= True
2078 trade_mock2
= mock
.Mock()
2079 trade_mock2
.pending
= True
2080 trade_mock3
= mock
.Mock()
2081 trade_mock3
.pending
= False
2083 trade_store
= market
.TradeStore(self
.m
)
2085 trade_store
.all
.append(trade_mock1
)
2086 trade_store
.all
.append(trade_mock2
)
2087 trade_store
.all
.append(trade_mock3
)
2089 self
.assertEqual([trade_mock1
, trade_mock2
], trade_store
.pending
)
2091 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2092 class BalanceStoreTest(WebMockTestCase
):
2096 self
.fetch_balance
= {
2100 "exchange_total": 0,
2104 "exchange_free": D("6.0"),
2105 "exchange_used": D("1.2"),
2106 "exchange_total": D("7.2"),
2110 "exchange_free": 16,
2112 "exchange_total": 16,
2118 "exchange_total": 0,
2119 "margin_total": D("-1.0"),
2124 def test_in_currency(self
):
2125 self
.m
.get_ticker
.return_value
= {
2128 "average": D("0.1"),
2131 balance_store
= market
.BalanceStore(self
.m
)
2132 balance_store
.all
= {
2133 "BTC": portfolio
.Balance("BTC", {
2135 "exchange_total":"0.65",
2136 "exchange_free": "0.35",
2137 "exchange_used": "0.30"}),
2138 "ETH": portfolio
.Balance("ETH", {
2140 "exchange_total": 3,
2142 "exchange_used": 0}),
2145 amounts
= balance_store
.in_currency("BTC")
2146 self
.assertEqual("BTC", amounts
["ETH"].currency
)
2147 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
2148 self
.assertEqual(D("0.30"), amounts
["ETH"].value
)
2149 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
2151 self
.m
.report
.log_tickers
.reset_mock()
2153 amounts
= balance_store
.in_currency("BTC", compute_value
="bid")
2154 self
.assertEqual(D("0.65"), amounts
["BTC"].value
)
2155 self
.assertEqual(D("0.27"), amounts
["ETH"].value
)
2156 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
2158 self
.m
.report
.log_tickers
.reset_mock()
2160 amounts
= balance_store
.in_currency("BTC", compute_value
="bid", type="exchange_used")
2161 self
.assertEqual(D("0.30"), amounts
["BTC"].value
)
2162 self
.assertEqual(0, amounts
["ETH"].value
)
2163 self
.m
.report
.log_tickers
.assert_called_once_with(amounts
, "BTC",
2164 "bid", "exchange_used")
2165 self
.m
.report
.log_tickers
.reset_mock()
2167 def test_fetch_balances(self
):
2168 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
2170 balance_store
= market
.BalanceStore(self
.m
)
2172 balance_store
.fetch_balances()
2173 self
.assertNotIn("ETC", balance_store
.currencies())
2174 self
.assertListEqual(["USDT", "XVG", "XMR"], list(balance_store
.currencies()))
2176 balance_store
.all
["ETC"] = portfolio
.Balance("ETC", {
2177 "exchange_total": "1", "exchange_free": "0",
2178 "exchange_used": "1" })
2179 balance_store
.fetch_balances(tag
="foo")
2180 self
.assertEqual(0, balance_store
.all
["ETC"].total
)
2181 self
.assertListEqual(["USDT", "XVG", "XMR", "ETC"], list(balance_store
.currencies()))
2182 self
.m
.report
.log_balances
.assert_called_with(tag
="foo")
2184 @mock.patch.object(market
.Portfolio
, "repartition")
2185 def test_dispatch_assets(self
, repartition
):
2186 self
.m
.ccxt
.fetch_all_balances
.return_value
= self
.fetch_balance
2188 balance_store
= market
.BalanceStore(self
.m
)
2189 balance_store
.fetch_balances()
2191 self
.assertNotIn("XEM", balance_store
.currencies())
2193 repartition_hash
= {
2194 "XEM": (D("0.75"), "long"),
2195 "BTC": (D("0.26"), "long"),
2196 "DASH": (D("0.10"), "short"),
2198 repartition
.return_value
= repartition_hash
2200 amounts
= balance_store
.dispatch_assets(portfolio
.Amount("BTC", "11.1"))
2201 repartition
.assert_called_with(liquidity
="medium")
2202 self
.assertIn("XEM", balance_store
.currencies())
2203 self
.assertEqual(D("2.6"), amounts
["BTC"].value
)
2204 self
.assertEqual(D("7.5"), amounts
["XEM"].value
)
2205 self
.assertEqual(D("-1.0"), amounts
["DASH"].value
)
2206 self
.m
.report
.log_balances
.assert_called_with(tag
=None)
2207 self
.m
.report
.log_dispatch
.assert_called_once_with(portfolio
.Amount("BTC",
2208 "11.1"), amounts
, "medium", repartition_hash
)
2210 def test_currencies(self
):
2211 balance_store
= market
.BalanceStore(self
.m
)
2213 balance_store
.all
= {
2214 "BTC": portfolio
.Balance("BTC", {
2216 "exchange_total":"0.65",
2217 "exchange_free": "0.35",
2218 "exchange_used": "0.30"}),
2219 "ETH": portfolio
.Balance("ETH", {
2221 "exchange_total": 3,
2223 "exchange_used": 0}),
2225 self
.assertListEqual(["BTC", "ETH"], list(balance_store
.currencies()))
2227 def test_as_json(self
):
2228 balance_mock1
= mock
.Mock()
2229 balance_mock1
.as_json
.return_value
= 1
2231 balance_mock2
= mock
.Mock()
2232 balance_mock2
.as_json
.return_value
= 2
2234 balance_store
= market
.BalanceStore(self
.m
)
2235 balance_store
.all
= {
2236 "BTC": balance_mock1
,
2237 "ETH": balance_mock2
,
2240 as_json
= balance_store
.as_json()
2241 self
.assertEqual(1, as_json
["BTC"])
2242 self
.assertEqual(2, as_json
["ETH"])
2245 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2246 class ComputationTest(WebMockTestCase
):
2247 def test_compute_value(self
):
2248 compute
= mock
.Mock()
2249 portfolio
.Computation
.compute_value("foo", "buy", compute_value
=compute
)
2250 compute
.assert_called_with("foo", "ask")
2252 compute
.reset_mock()
2253 portfolio
.Computation
.compute_value("foo", "sell", compute_value
=compute
)
2254 compute
.assert_called_with("foo", "bid")
2256 compute
.reset_mock()
2257 portfolio
.Computation
.compute_value("foo", "ask", compute_value
=compute
)
2258 compute
.assert_called_with("foo", "ask")
2260 compute
.reset_mock()
2261 portfolio
.Computation
.compute_value("foo", "bid", compute_value
=compute
)
2262 compute
.assert_called_with("foo", "bid")
2264 compute
.reset_mock()
2265 portfolio
.Computation
.computations
["test"] = compute
2266 portfolio
.Computation
.compute_value("foo", "bid", compute_value
="test")
2267 compute
.assert_called_with("foo", "bid")
2270 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2271 class TradeTest(WebMockTestCase
):
2273 def test_values_assertion(self
):
2274 value_from
= portfolio
.Amount("BTC", "1.0")
2275 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2276 value_to
= portfolio
.Amount("BTC", "1.0")
2277 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2278 self
.assertEqual("BTC", trade
.base_currency
)
2279 self
.assertEqual("ETH", trade
.currency
)
2280 self
.assertEqual(self
.m
, trade
.market
)
2282 with self
.assertRaises(AssertionError):
2283 portfolio
.Trade(value_from
, -value_to
, "ETH", self
.m
)
2284 with self
.assertRaises(AssertionError):
2285 portfolio
.Trade(value_from
, value_to
, "ETC", self
.m
)
2286 with self
.assertRaises(AssertionError):
2287 value_from
.currency
= "ETH"
2288 portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2289 value_from
.currency
= "BTC"
2290 with self
.assertRaises(AssertionError):
2291 value_from2
= portfolio
.Amount("BTC", "1.0")
2292 portfolio
.Trade(value_from2
, value_to
, "ETH", self
.m
)
2294 value_from
= portfolio
.Amount("BTC", 0)
2295 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2296 self
.assertEqual(0, trade
.value_from
.linked_to
)
2298 def test_action(self
):
2299 value_from
= portfolio
.Amount("BTC", "1.0")
2300 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2301 value_to
= portfolio
.Amount("BTC", "1.0")
2302 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2304 self
.assertIsNone(trade
.action
)
2306 value_from
= portfolio
.Amount("BTC", "1.0")
2307 value_from
.linked_to
= portfolio
.Amount("BTC", "1.0")
2308 value_to
= portfolio
.Amount("BTC", "2.0")
2309 trade
= portfolio
.Trade(value_from
, value_to
, "BTC", self
.m
)
2311 self
.assertIsNone(trade
.action
)
2313 value_from
= portfolio
.Amount("BTC", "0.5")
2314 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2315 value_to
= portfolio
.Amount("BTC", "1.0")
2316 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2318 self
.assertEqual("acquire", trade
.action
)
2320 value_from
= portfolio
.Amount("BTC", "0")
2321 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
2322 value_to
= portfolio
.Amount("BTC", "-1.0")
2323 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2325 self
.assertEqual("acquire", trade
.action
)
2327 def test_order_action(self
):
2328 value_from
= portfolio
.Amount("BTC", "0.5")
2329 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2330 value_to
= portfolio
.Amount("BTC", "1.0")
2331 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2333 trade
.inverted
= False
2334 self
.assertEqual("buy", trade
.order_action())
2335 trade
.inverted
= True
2336 self
.assertEqual("sell", trade
.order_action())
2338 value_from
= portfolio
.Amount("BTC", "0")
2339 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
2340 value_to
= portfolio
.Amount("BTC", "-1.0")
2341 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2343 trade
.inverted
= False
2344 self
.assertEqual("sell", trade
.order_action())
2345 trade
.inverted
= True
2346 self
.assertEqual("buy", trade
.order_action())
2348 def test_trade_type(self
):
2349 value_from
= portfolio
.Amount("BTC", "0.5")
2350 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2351 value_to
= portfolio
.Amount("BTC", "1.0")
2352 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2354 self
.assertEqual("long", trade
.trade_type
)
2356 value_from
= portfolio
.Amount("BTC", "0")
2357 value_from
.linked_to
= portfolio
.Amount("ETH", "0")
2358 value_to
= portfolio
.Amount("BTC", "-1.0")
2359 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2361 self
.assertEqual("short", trade
.trade_type
)
2363 def test_is_fullfiled(self
):
2364 with self
.subTest(inverted
=False):
2365 value_from
= portfolio
.Amount("BTC", "0.5")
2366 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2367 value_to
= portfolio
.Amount("BTC", "1.0")
2368 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2370 order1
= mock
.Mock()
2371 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
2373 order2
= mock
.Mock()
2374 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
2375 trade
.orders
.append(order1
)
2376 trade
.orders
.append(order2
)
2378 self
.assertFalse(trade
.is_fullfiled
)
2380 order3
= mock
.Mock()
2381 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
2382 trade
.orders
.append(order3
)
2384 self
.assertTrue(trade
.is_fullfiled
)
2386 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
2387 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
2388 order3
.filled_amount
.assert_called_with(in_base_currency
=True)
2390 with self
.subTest(inverted
=True):
2391 value_from
= portfolio
.Amount("BTC", "0.5")
2392 value_from
.linked_to
= portfolio
.Amount("USDT", "1000.0")
2393 value_to
= portfolio
.Amount("BTC", "1.0")
2394 trade
= portfolio
.Trade(value_from
, value_to
, "USDT", self
.m
)
2395 trade
.inverted
= True
2397 order1
= mock
.Mock()
2398 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.3")
2400 order2
= mock
.Mock()
2401 order2
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.01")
2402 trade
.orders
.append(order1
)
2403 trade
.orders
.append(order2
)
2405 self
.assertFalse(trade
.is_fullfiled
)
2407 order3
= mock
.Mock()
2408 order3
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.19")
2409 trade
.orders
.append(order3
)
2411 self
.assertTrue(trade
.is_fullfiled
)
2413 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
2414 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
2415 order3
.filled_amount
.assert_called_with(in_base_currency
=False)
2418 def test_filled_amount(self
):
2419 value_from
= portfolio
.Amount("BTC", "0.5")
2420 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2421 value_to
= portfolio
.Amount("BTC", "1.0")
2422 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2424 order1
= mock
.Mock()
2425 order1
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.3")
2427 order2
= mock
.Mock()
2428 order2
.filled_amount
.return_value
= portfolio
.Amount("ETH", "0.01")
2429 trade
.orders
.append(order1
)
2430 trade
.orders
.append(order2
)
2432 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount())
2433 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
2434 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
2436 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=False))
2437 order1
.filled_amount
.assert_called_with(in_base_currency
=False)
2438 order2
.filled_amount
.assert_called_with(in_base_currency
=False)
2440 self
.assertEqual(portfolio
.Amount("ETH", "0.31"), trade
.filled_amount(in_base_currency
=True))
2441 order1
.filled_amount
.assert_called_with(in_base_currency
=True)
2442 order2
.filled_amount
.assert_called_with(in_base_currency
=True)
2444 @mock.patch.object(portfolio
.Computation
, "compute_value")
2445 @mock.patch.object(portfolio
.Trade
, "filled_amount")
2446 @mock.patch.object(portfolio
, "Order")
2447 def test_prepare_order(self
, Order
, filled_amount
, compute_value
):
2448 Order
.return_value
= "Order"
2450 with self
.subTest(desc
="Nothing to do"):
2451 value_from
= portfolio
.Amount("BTC", "10")
2452 value_from
.rate
= D("0.1")
2453 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2454 value_to
= portfolio
.Amount("BTC", "10")
2455 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2457 trade
.prepare_order()
2459 filled_amount
.assert_not_called()
2460 compute_value
.assert_not_called()
2461 self
.assertEqual(0, len(trade
.orders
))
2462 Order
.assert_not_called()
2464 self
.m
.get_ticker
.return_value
= { "inverted": False }
2465 with self
.subTest(desc
="Already filled"):
2466 filled_amount
.return_value
= portfolio
.Amount("FOO", "100")
2467 compute_value
.return_value
= D("0.125")
2469 value_from
= portfolio
.Amount("BTC", "10")
2470 value_from
.rate
= D("0.1")
2471 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2472 value_to
= portfolio
.Amount("BTC", "0")
2473 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2475 trade
.prepare_order()
2477 filled_amount
.assert_called_with(in_base_currency
=False)
2478 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2479 self
.assertEqual(0, len(trade
.orders
))
2480 self
.m
.report
.log_error
.assert_called_with("prepare_order", message
=mock
.ANY
)
2481 Order
.assert_not_called()
2483 with self
.subTest(action
="dispose", inverted
=False):
2484 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
2485 compute_value
.return_value
= D("0.125")
2487 value_from
= portfolio
.Amount("BTC", "10")
2488 value_from
.rate
= D("0.1")
2489 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2490 value_to
= portfolio
.Amount("BTC", "1")
2491 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2493 trade
.prepare_order()
2495 filled_amount
.assert_called_with(in_base_currency
=False)
2496 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2497 self
.assertEqual(1, len(trade
.orders
))
2498 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
2499 D("0.125"), "BTC", "long", self
.m
,
2500 trade
, close_if_possible
=False)
2502 with self
.subTest(action
="dispose", inverted
=False, close_if_possible
=True):
2503 filled_amount
.return_value
= portfolio
.Amount("FOO", "60")
2504 compute_value
.return_value
= D("0.125")
2506 value_from
= portfolio
.Amount("BTC", "10")
2507 value_from
.rate
= D("0.1")
2508 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2509 value_to
= portfolio
.Amount("BTC", "1")
2510 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2512 trade
.prepare_order(close_if_possible
=True)
2514 filled_amount
.assert_called_with(in_base_currency
=False)
2515 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2516 self
.assertEqual(1, len(trade
.orders
))
2517 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 30),
2518 D("0.125"), "BTC", "long", self
.m
,
2519 trade
, close_if_possible
=True)
2521 with self
.subTest(action
="acquire", inverted
=False):
2522 filled_amount
.return_value
= portfolio
.Amount("BTC", "3")
2523 compute_value
.return_value
= D("0.125")
2525 value_from
= portfolio
.Amount("BTC", "1")
2526 value_from
.rate
= D("0.1")
2527 value_from
.linked_to
= portfolio
.Amount("FOO", "10")
2528 value_to
= portfolio
.Amount("BTC", "10")
2529 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2531 trade
.prepare_order()
2533 filled_amount
.assert_called_with(in_base_currency
=True)
2534 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "buy", compute_value
="default")
2535 self
.assertEqual(1, len(trade
.orders
))
2537 Order
.assert_called_with("buy", portfolio
.Amount("FOO", 48),
2538 D("0.125"), "BTC", "long", self
.m
,
2539 trade
, close_if_possible
=False)
2541 with self
.subTest(close_if_possible
=True):
2542 filled_amount
.return_value
= portfolio
.Amount("FOO", "0")
2543 compute_value
.return_value
= D("0.125")
2545 value_from
= portfolio
.Amount("BTC", "10")
2546 value_from
.rate
= D("0.1")
2547 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2548 value_to
= portfolio
.Amount("BTC", "0")
2549 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2551 trade
.prepare_order()
2553 filled_amount
.assert_called_with(in_base_currency
=False)
2554 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
, "sell", compute_value
="default")
2555 self
.assertEqual(1, len(trade
.orders
))
2556 Order
.assert_called_with("sell", portfolio
.Amount("FOO", 100),
2557 D("0.125"), "BTC", "long", self
.m
,
2558 trade
, close_if_possible
=True)
2560 self
.m
.get_ticker
.return_value
= { "inverted": True, "original": {}
}
2561 with self
.subTest(action
="dispose", inverted
=True):
2562 filled_amount
.return_value
= portfolio
.Amount("FOO", "300")
2563 compute_value
.return_value
= D("125")
2565 value_from
= portfolio
.Amount("BTC", "10")
2566 value_from
.rate
= D("0.01")
2567 value_from
.linked_to
= portfolio
.Amount("FOO", "1000")
2568 value_to
= portfolio
.Amount("BTC", "1")
2569 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2571 trade
.prepare_order(compute_value
="foo")
2573 filled_amount
.assert_called_with(in_base_currency
=True)
2574 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "buy", compute_value
="foo")
2575 self
.assertEqual(1, len(trade
.orders
))
2576 Order
.assert_called_with("buy", portfolio
.Amount("BTC", D("4.8")),
2577 D("125"), "FOO", "long", self
.m
,
2578 trade
, close_if_possible
=False)
2580 with self
.subTest(action
="acquire", inverted
=True):
2581 filled_amount
.return_value
= portfolio
.Amount("BTC", "4")
2582 compute_value
.return_value
= D("125")
2584 value_from
= portfolio
.Amount("BTC", "1")
2585 value_from
.rate
= D("0.01")
2586 value_from
.linked_to
= portfolio
.Amount("FOO", "100")
2587 value_to
= portfolio
.Amount("BTC", "10")
2588 trade
= portfolio
.Trade(value_from
, value_to
, "FOO", self
.m
)
2590 trade
.prepare_order(compute_value
="foo")
2592 filled_amount
.assert_called_with(in_base_currency
=False)
2593 compute_value
.assert_called_with(self
.m
.get_ticker
.return_value
["original"], "sell", compute_value
="foo")
2594 self
.assertEqual(1, len(trade
.orders
))
2595 Order
.assert_called_with("sell", portfolio
.Amount("BTC", D("5")),
2596 D("125"), "FOO", "long", self
.m
,
2597 trade
, close_if_possible
=False)
2599 def test_tick_actions_recreate(self
):
2600 value_from
= portfolio
.Amount("BTC", "0.5")
2601 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2602 value_to
= portfolio
.Amount("BTC", "1.0")
2603 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2605 self
.assertEqual("average", trade
.tick_actions_recreate(0))
2606 self
.assertEqual("foo", trade
.tick_actions_recreate(0, default
="foo"))
2607 self
.assertEqual("average", trade
.tick_actions_recreate(1))
2608 self
.assertEqual(trade
.tick_actions
[2][1], trade
.tick_actions_recreate(2))
2609 self
.assertEqual(trade
.tick_actions
[2][1], trade
.tick_actions_recreate(3))
2610 self
.assertEqual(trade
.tick_actions
[5][1], trade
.tick_actions_recreate(5))
2611 self
.assertEqual(trade
.tick_actions
[5][1], trade
.tick_actions_recreate(6))
2612 self
.assertEqual("default", trade
.tick_actions_recreate(7))
2613 self
.assertEqual("default", trade
.tick_actions_recreate(8))
2615 @mock.patch.object(portfolio
.Trade
, "prepare_order")
2616 def test_update_order(self
, prepare_order
):
2617 order_mock
= mock
.Mock()
2618 new_order_mock
= mock
.Mock()
2620 value_from
= portfolio
.Amount("BTC", "0.5")
2621 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2622 value_to
= portfolio
.Amount("BTC", "1.0")
2623 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2624 prepare_order
.return_value
= new_order_mock
2626 for i
in [0, 1, 3, 4, 6]:
2627 with self
.subTest(tick
=i
):
2628 trade
.update_order(order_mock
, i
)
2629 order_mock
.cancel
.assert_not_called()
2630 new_order_mock
.run
.assert_not_called()
2631 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
,
2632 update
="waiting", compute_value
=None, new_order
=None)
2634 order_mock
.reset_mock()
2635 new_order_mock
.reset_mock()
2637 self
.m
.report
.log_order
.reset_mock()
2639 trade
.update_order(order_mock
, 2)
2640 order_mock
.cancel
.assert_called()
2641 new_order_mock
.run
.assert_called()
2642 prepare_order
.assert_called()
2643 self
.m
.report
.log_order
.assert_called()
2644 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2646 mock
.call(order_mock
, 2, update
="adjusting",
2647 compute_value
=mock
.ANY
,
2648 new_order
=new_order_mock
),
2649 mock
.call(order_mock
, 2, new_order
=new_order_mock
),
2651 self
.m
.report
.log_order
.assert_has_calls(calls
)
2653 order_mock
.reset_mock()
2654 new_order_mock
.reset_mock()
2656 self
.m
.report
.log_order
.reset_mock()
2658 trade
.update_order(order_mock
, 5)
2659 order_mock
.cancel
.assert_called()
2660 new_order_mock
.run
.assert_called()
2661 prepare_order
.assert_called()
2662 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2663 self
.m
.report
.log_order
.assert_called()
2665 mock
.call(order_mock
, 5, update
="adjusting",
2666 compute_value
=mock
.ANY
,
2667 new_order
=new_order_mock
),
2668 mock
.call(order_mock
, 5, new_order
=new_order_mock
),
2670 self
.m
.report
.log_order
.assert_has_calls(calls
)
2672 order_mock
.reset_mock()
2673 new_order_mock
.reset_mock()
2675 self
.m
.report
.log_order
.reset_mock()
2677 trade
.update_order(order_mock
, 7)
2678 order_mock
.cancel
.assert_called()
2679 new_order_mock
.run
.assert_called()
2680 prepare_order
.assert_called_with(compute_value
="default")
2681 self
.m
.report
.log_order
.assert_called()
2682 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2684 mock
.call(order_mock
, 7, update
="market_fallback",
2685 compute_value
='default',
2686 new_order
=new_order_mock
),
2687 mock
.call(order_mock
, 7, new_order
=new_order_mock
),
2689 self
.m
.report
.log_order
.assert_has_calls(calls
)
2691 order_mock
.reset_mock()
2692 new_order_mock
.reset_mock()
2694 self
.m
.report
.log_order
.reset_mock()
2696 for i
in [10, 13, 16]:
2697 with self
.subTest(tick
=i
):
2698 trade
.update_order(order_mock
, i
)
2699 order_mock
.cancel
.assert_called()
2700 new_order_mock
.run
.assert_called()
2701 prepare_order
.assert_called_with(compute_value
="default")
2702 self
.m
.report
.log_order
.assert_called()
2703 self
.assertEqual(2, self
.m
.report
.log_order
.call_count
)
2705 mock
.call(order_mock
, i
, update
="market_adjust",
2706 compute_value
='default',
2707 new_order
=new_order_mock
),
2708 mock
.call(order_mock
, i
, new_order
=new_order_mock
),
2710 self
.m
.report
.log_order
.assert_has_calls(calls
)
2712 order_mock
.reset_mock()
2713 new_order_mock
.reset_mock()
2715 self
.m
.report
.log_order
.reset_mock()
2717 for i
in [8, 9, 11, 12]:
2718 with self
.subTest(tick
=i
):
2719 trade
.update_order(order_mock
, i
)
2720 order_mock
.cancel
.assert_not_called()
2721 new_order_mock
.run
.assert_not_called()
2722 self
.m
.report
.log_order
.assert_called_once_with(order_mock
, i
, update
="waiting",
2723 compute_value
=None, new_order
=None)
2725 order_mock
.reset_mock()
2726 new_order_mock
.reset_mock()
2728 self
.m
.report
.log_order
.reset_mock()
2731 def test_print_with_order(self
):
2732 value_from
= portfolio
.Amount("BTC", "0.5")
2733 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2734 value_to
= portfolio
.Amount("BTC", "1.0")
2735 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2737 order_mock1
= mock
.Mock()
2738 order_mock1
.__repr__
= mock
.Mock()
2739 order_mock1
.__repr__
.return_value
= "Mock 1"
2740 order_mock2
= mock
.Mock()
2741 order_mock2
.__repr__
= mock
.Mock()
2742 order_mock2
.__repr__
.return_value
= "Mock 2"
2743 order_mock1
.mouvements
= []
2744 mouvement_mock1
= mock
.Mock()
2745 mouvement_mock1
.__repr__
= mock
.Mock()
2746 mouvement_mock1
.__repr__
.return_value
= "Mouvement 1"
2747 mouvement_mock2
= mock
.Mock()
2748 mouvement_mock2
.__repr__
= mock
.Mock()
2749 mouvement_mock2
.__repr__
.return_value
= "Mouvement 2"
2750 order_mock2
.mouvements
= [
2751 mouvement_mock1
, mouvement_mock2
2753 trade
.orders
.append(order_mock1
)
2754 trade
.orders
.append(order_mock2
)
2756 with mock
.patch
.object(trade
, "filled_amount") as filled
:
2757 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
2759 trade
.print_with_order()
2761 self
.m
.report
.print_log
.assert_called()
2762 calls
= self
.m
.report
.print_log
.mock_calls
2763 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(calls
[0][1][0]))
2764 self
.assertEqual("\tMock 1", str(calls
[1][1][0]))
2765 self
.assertEqual("\tMock 2", str(calls
[2][1][0]))
2766 self
.assertEqual("\t\tMouvement 1", str(calls
[3][1][0]))
2767 self
.assertEqual("\t\tMouvement 2", str(calls
[4][1][0]))
2769 self
.m
.report
.print_log
.reset_mock()
2771 filled
.return_value
= portfolio
.Amount("BTC", "0.5")
2772 trade
.print_with_order()
2773 calls
= self
.m
.report
.print_log
.mock_calls
2774 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ✔)", str(calls
[0][1][0]))
2776 self
.m
.report
.print_log
.reset_mock()
2778 filled
.return_value
= portfolio
.Amount("BTC", "0.1")
2780 trade
.print_with_order()
2781 calls
= self
.m
.report
.print_log
.mock_calls
2782 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire ❌)", str(calls
[0][1][0]))
2784 def test_close(self
):
2785 value_from
= portfolio
.Amount("BTC", "0.5")
2786 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2787 value_to
= portfolio
.Amount("BTC", "1.0")
2788 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2789 order1
= mock
.Mock()
2790 trade
.orders
.append(order1
)
2794 self
.assertEqual(True, trade
.closed
)
2795 order1
.cancel
.assert_called_once_with()
2797 def test_pending(self
):
2798 value_from
= portfolio
.Amount("BTC", "0.5")
2799 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2800 value_to
= portfolio
.Amount("BTC", "1.0")
2801 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2804 self
.assertEqual(False, trade
.pending
)
2806 trade
.closed
= False
2807 self
.assertEqual(True, trade
.pending
)
2809 order1
= mock
.Mock()
2810 order1
.filled_amount
.return_value
= portfolio
.Amount("BTC", "0.5")
2811 trade
.orders
.append(order1
)
2812 self
.assertEqual(False, trade
.pending
)
2814 def test__repr(self
):
2815 value_from
= portfolio
.Amount("BTC", "0.5")
2816 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2817 value_to
= portfolio
.Amount("BTC", "1.0")
2818 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2820 self
.assertEqual("Trade(0.50000000 BTC [10.00000000 ETH] -> 1.00000000 BTC in ETH, acquire)", str(trade
))
2822 def test_as_json(self
):
2823 value_from
= portfolio
.Amount("BTC", "0.5")
2824 value_from
.linked_to
= portfolio
.Amount("ETH", "10.0")
2825 value_to
= portfolio
.Amount("BTC", "1.0")
2826 trade
= portfolio
.Trade(value_from
, value_to
, "ETH", self
.m
)
2828 as_json
= trade
.as_json()
2829 self
.assertEqual("acquire", as_json
["action"])
2830 self
.assertEqual(D("0.5"), as_json
["from"])
2831 self
.assertEqual(D("1.0"), as_json
["to"])
2832 self
.assertEqual("ETH", as_json
["currency"])
2833 self
.assertEqual("BTC", as_json
["base_currency"])
2835 @unittest.skipUnless("unit" in limits
, "Unit skipped")
2836 class OrderTest(WebMockTestCase
):
2837 def test_values(self
):
2838 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2839 D("0.1"), "BTC", "long", "market", "trade")
2840 self
.assertEqual("buy", order
.action
)
2841 self
.assertEqual(10, order
.amount
.value
)
2842 self
.assertEqual("ETH", order
.amount
.currency
)
2843 self
.assertEqual(D("0.1"), order
.rate
)
2844 self
.assertEqual("BTC", order
.base_currency
)
2845 self
.assertEqual("market", order
.market
)
2846 self
.assertEqual("long", order
.trade_type
)
2847 self
.assertEqual("pending", order
.status
)
2848 self
.assertEqual("trade", order
.trade
)
2849 self
.assertIsNone(order
.id)
2850 self
.assertFalse(order
.close_if_possible
)
2852 def test__repr(self
):
2853 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2854 D("0.1"), "BTC", "long", "market", "trade")
2855 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending])", repr(order
))
2857 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2858 D("0.1"), "BTC", "long", "market", "trade",
2859 close_if_possible
=True)
2860 self
.assertEqual("Order(buy long 10.00000000 ETH at 0.1 BTC [pending] ✂)", repr(order
))
2862 def test_as_json(self
):
2863 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2864 D("0.1"), "BTC", "long", "market", "trade")
2865 mouvement_mock1
= mock
.Mock()
2866 mouvement_mock1
.as_json
.return_value
= 1
2867 mouvement_mock2
= mock
.Mock()
2868 mouvement_mock2
.as_json
.return_value
= 2
2870 order
.mouvements
= [mouvement_mock1
, mouvement_mock2
]
2871 as_json
= order
.as_json()
2872 self
.assertEqual("buy", as_json
["action"])
2873 self
.assertEqual("long", as_json
["trade_type"])
2874 self
.assertEqual(10, as_json
["amount"])
2875 self
.assertEqual("ETH", as_json
["currency"])
2876 self
.assertEqual("BTC", as_json
["base_currency"])
2877 self
.assertEqual(D("0.1"), as_json
["rate"])
2878 self
.assertEqual("pending", as_json
["status"])
2879 self
.assertEqual(False, as_json
["close_if_possible"])
2880 self
.assertIsNone(as_json
["id"])
2881 self
.assertEqual([1, 2], as_json
["mouvements"])
2883 def test_account(self
):
2884 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2885 D("0.1"), "BTC", "long", "market", "trade")
2886 self
.assertEqual("exchange", order
.account
)
2888 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
2889 D("0.1"), "BTC", "short", "market", "trade")
2890 self
.assertEqual("margin", order
.account
)
2892 def test_pending(self
):
2893 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2894 D("0.1"), "BTC", "long", "market", "trade")
2895 self
.assertTrue(order
.pending
)
2896 order
.status
= "open"
2897 self
.assertFalse(order
.pending
)
2899 def test_open(self
):
2900 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2901 D("0.1"), "BTC", "long", "market", "trade")
2902 self
.assertFalse(order
.open)
2903 order
.status
= "open"
2904 self
.assertTrue(order
.open)
2906 def test_finished(self
):
2907 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2908 D("0.1"), "BTC", "long", "market", "trade")
2909 self
.assertFalse(order
.finished
)
2910 order
.status
= "closed"
2911 self
.assertTrue(order
.finished
)
2912 order
.status
= "canceled"
2913 self
.assertTrue(order
.finished
)
2914 order
.status
= "error"
2915 self
.assertTrue(order
.finished
)
2917 @mock.patch.object(portfolio
.Order
, "fetch")
2918 def test_cancel(self
, fetch
):
2919 with self
.subTest(debug
=True):
2921 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2922 D("0.1"), "BTC", "long", self
.m
, "trade")
2923 order
.status
= "open"
2926 self
.m
.ccxt
.cancel_order
.assert_not_called()
2927 self
.m
.report
.log_debug_action
.assert_called_once()
2928 self
.m
.report
.log_debug_action
.reset_mock()
2929 self
.assertEqual("canceled", order
.status
)
2931 with self
.subTest(desc
="Nominal case"):
2932 self
.m
.debug
= False
2933 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2934 D("0.1"), "BTC", "long", self
.m
, "trade")
2935 order
.status
= "open"
2939 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
2940 fetch
.assert_called_once_with()
2941 self
.m
.report
.log_debug_action
.assert_not_called()
2943 with self
.subTest(exception
=True):
2944 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
2945 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2946 D("0.1"), "BTC", "long", self
.m
, "trade")
2947 order
.status
= "open"
2950 self
.m
.ccxt
.cancel_order
.assert_called_with(42)
2951 self
.m
.report
.log_error
.assert_called_once()
2954 with self
.subTest(id=None):
2955 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
2956 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2957 D("0.1"), "BTC", "long", self
.m
, "trade")
2958 order
.status
= "open"
2960 self
.m
.ccxt
.cancel_order
.assert_not_called()
2963 with self
.subTest(open=False):
2964 self
.m
.ccxt
.cancel_order
.side_effect
= portfolio
.OrderNotFound
2965 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2966 D("0.1"), "BTC", "long", self
.m
, "trade")
2967 order
.status
= "closed"
2969 self
.m
.ccxt
.cancel_order
.assert_not_called()
2971 def test_dust_amount_remaining(self
):
2972 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2973 D("0.1"), "BTC", "long", self
.m
, "trade")
2974 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", 1))
2975 self
.assertFalse(order
.dust_amount_remaining())
2977 order
.remaining_amount
= mock
.Mock(return_value
=portfolio
.Amount("ETH", D("0.0001")))
2978 self
.assertTrue(order
.dust_amount_remaining())
2980 @mock.patch.object(portfolio
.Order
, "fetch")
2981 @mock.patch.object(portfolio
.Order
, "filled_amount", return_value
=portfolio
.Amount("ETH", 1))
2982 def test_remaining_amount(self
, filled_amount
, fetch
):
2983 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2984 D("0.1"), "BTC", "long", self
.m
, "trade")
2986 self
.assertEqual(9, order
.remaining_amount().value
)
2988 order
.status
= "open"
2989 self
.assertEqual(9, order
.remaining_amount().value
)
2991 @mock.patch.object(portfolio
.Order
, "fetch")
2992 def test_filled_amount(self
, fetch
):
2993 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
2994 D("0.1"), "BTC", "long", self
.m
, "trade")
2995 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
2996 "tradeID": 42, "type": "buy", "fee": "0.0015",
2997 "date": "2017-12-30 12:00:12", "rate": "0.1",
2998 "amount": "3", "total": "0.3"
3000 order
.mouvements
.append(portfolio
.Mouvement("ETH", "BTC", {
3001 "tradeID": 43, "type": "buy", "fee": "0.0015",
3002 "date": "2017-12-30 13:00:12", "rate": "0.2",
3003 "amount": "2", "total": "0.4"
3005 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount())
3006 fetch
.assert_not_called()
3007 order
.status
= "open"
3008 self
.assertEqual(portfolio
.Amount("ETH", 5), order
.filled_amount(in_base_currency
=False))
3009 fetch
.assert_called_once()
3010 self
.assertEqual(portfolio
.Amount("BTC", "0.7"), order
.filled_amount(in_base_currency
=True))
3012 def test_fetch_mouvements(self
):
3013 self
.m
.ccxt
.privatePostReturnOrderTrades
.return_value
= [
3015 "tradeID": 42, "type": "buy", "fee": "0.0015",
3016 "date": "2017-12-30 13:00:12", "rate": "0.1",
3017 "amount": "3", "total": "0.3"
3020 "tradeID": 43, "type": "buy", "fee": "0.0015",
3021 "date": "2017-12-30 12:00:12", "rate": "0.2",
3022 "amount": "2", "total": "0.4"
3025 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3026 D("0.1"), "BTC", "long", self
.m
, "trade")
3028 order
.mouvements
= ["Foo", "Bar", "Baz"]
3030 order
.fetch_mouvements()
3032 self
.m
.ccxt
.privatePostReturnOrderTrades
.assert_called_with({"orderNumber": 12}
)
3033 self
.assertEqual(2, len(order
.mouvements
))
3034 self
.assertEqual(43, order
.mouvements
[0].id)
3035 self
.assertEqual(42, order
.mouvements
[1].id)
3037 self
.m
.ccxt
.privatePostReturnOrderTrades
.side_effect
= portfolio
.ExchangeError
3038 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3039 D("0.1"), "BTC", "long", self
.m
, "trade")
3040 order
.fetch_mouvements()
3041 self
.assertEqual(0, len(order
.mouvements
))
3043 def test_mark_finished_order(self
):
3044 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3045 D("0.1"), "BTC", "short", self
.m
, "trade",
3046 close_if_possible
=True)
3047 order
.status
= "closed"
3048 self
.m
.debug
= False
3050 order
.mark_finished_order()
3051 self
.m
.ccxt
.close_margin_position
.assert_called_with("ETH", "BTC")
3052 self
.m
.ccxt
.close_margin_position
.reset_mock()
3054 order
.status
= "open"
3055 order
.mark_finished_order()
3056 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3058 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3059 D("0.1"), "BTC", "short", self
.m
, "trade",
3060 close_if_possible
=False)
3061 order
.status
= "closed"
3062 order
.mark_finished_order()
3063 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3065 order
= portfolio
.Order("sell", portfolio
.Amount("ETH", 10),
3066 D("0.1"), "BTC", "short", self
.m
, "trade",
3067 close_if_possible
=True)
3068 order
.status
= "closed"
3069 order
.mark_finished_order()
3070 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3072 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3073 D("0.1"), "BTC", "long", self
.m
, "trade",
3074 close_if_possible
=True)
3075 order
.status
= "closed"
3076 order
.mark_finished_order()
3077 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3081 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3082 D("0.1"), "BTC", "short", self
.m
, "trade",
3083 close_if_possible
=True)
3084 order
.status
= "closed"
3086 order
.mark_finished_order()
3087 self
.m
.ccxt
.close_margin_position
.assert_not_called()
3088 self
.m
.report
.log_debug_action
.assert_called_once()
3090 @mock.patch.object(portfolio
.Order
, "fetch_mouvements")
3091 @mock.patch.object(portfolio
.Order
, "mark_disappeared_order")
3092 @mock.patch.object(portfolio
.Order
, "mark_finished_order")
3093 def test_fetch(self
, mark_finished_order
, mark_disappeared_order
, fetch_mouvements
):
3094 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3095 D("0.1"), "BTC", "long", self
.m
, "trade")
3097 with self
.subTest(debug
=True):
3100 self
.m
.report
.log_debug_action
.assert_called_once()
3101 self
.m
.report
.log_debug_action
.reset_mock()
3102 self
.m
.ccxt
.fetch_order
.assert_not_called()
3103 mark_finished_order
.assert_not_called()
3104 mark_disappeared_order
.assert_not_called()
3105 fetch_mouvements
.assert_not_called()
3107 with self
.subTest(debug
=False):
3108 self
.m
.debug
= False
3109 self
.m
.ccxt
.fetch_order
.return_value
= {
3111 "datetime": "timestamp"
3115 self
.m
.ccxt
.fetch_order
.assert_called_once_with(45)
3116 fetch_mouvements
.assert_called_once()
3117 self
.assertEqual("foo", order
.status
)
3118 self
.assertEqual("timestamp", order
.timestamp
)
3119 self
.assertEqual(1, len(order
.results
))
3120 self
.m
.report
.log_debug_action
.assert_not_called()
3121 mark_finished_order
.assert_called_once()
3122 mark_disappeared_order
.assert_called_once()
3124 mark_finished_order
.reset_mock()
3125 with self
.subTest(missing_order
=True):
3126 self
.m
.ccxt
.fetch_order
.side_effect
= [
3127 portfolio
.OrderNotCached
,
3130 self
.assertEqual("closed_unknown", order
.status
)
3131 mark_finished_order
.assert_called_once()
3133 def test_mark_disappeared_order(self
):
3134 with self
.subTest("Open order"):
3135 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3136 D("0.1"), "BTC", "long", self
.m
, "trade")
3138 order
.mouvements
.append(portfolio
.Mouvement("XRP", "BTC", {
3140 "currencyPair":"BTC_XRP",
3142 "rate":"0.00007013",
3143 "amount":"0.00000222",
3144 "total":"0.00000000",
3146 "date":"2018-04-02 00:09:13"
3148 order
.mark_disappeared_order()
3149 self
.assertEqual("pending", order
.status
)
3151 with self
.subTest("Non-zero amount"):
3152 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3153 D("0.1"), "BTC", "long", self
.m
, "trade")
3155 order
.status
= "closed"
3156 order
.mouvements
.append(portfolio
.Mouvement("XRP", "BTC", {
3158 "currencyPair":"BTC_XRP",
3160 "rate":"0.00007013",
3161 "amount":"0.00000222",
3162 "total":"0.00000010",
3164 "date":"2018-04-02 00:09:13"
3166 order
.mark_disappeared_order()
3167 self
.assertEqual("closed", order
.status
)
3169 with self
.subTest("Other mouvements"):
3170 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3171 D("0.1"), "BTC", "long", self
.m
, "trade")
3173 order
.status
= "closed"
3174 order
.mouvements
.append(portfolio
.Mouvement("XRP", "BTC", {
3176 "currencyPair":"BTC_XRP",
3178 "rate":"0.00007013",
3179 "amount":"0.00000222",
3180 "total":"0.00000001",
3182 "date":"2018-04-02 00:09:13"
3184 order
.mouvements
.append(portfolio
.Mouvement("XRP", "BTC", {
3186 "currencyPair":"BTC_XRP",
3188 "rate":"0.00007013",
3189 "amount":"0.00000222",
3190 "total":"0.00000000",
3192 "date":"2018-04-02 00:09:13"
3194 order
.mark_disappeared_order()
3195 self
.assertEqual("error_disappeared", order
.status
)
3197 with self
.subTest("Order disappeared"):
3198 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3199 D("0.1"), "BTC", "long", self
.m
, "trade")
3201 order
.status
= "closed"
3202 order
.mouvements
.append(portfolio
.Mouvement("XRP", "BTC", {
3204 "currencyPair":"BTC_XRP",
3206 "rate":"0.00007013",
3207 "amount":"0.00000222",
3208 "total":"0.00000000",
3210 "date":"2018-04-02 00:09:13"
3212 order
.mark_disappeared_order()
3213 self
.assertEqual("error_disappeared", order
.status
)
3215 @mock.patch.object(portfolio
.Order
, "fetch")
3216 def test_get_status(self
, fetch
):
3217 with self
.subTest(debug
=True):
3219 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3220 D("0.1"), "BTC", "long", self
.m
, "trade")
3221 self
.assertEqual("pending", order
.get_status())
3222 fetch
.assert_not_called()
3223 self
.m
.report
.log_debug_action
.assert_called_once()
3225 with self
.subTest(debug
=False, finished
=False):
3226 self
.m
.debug
= False
3227 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3228 D("0.1"), "BTC", "long", self
.m
, "trade")
3230 def update_status():
3231 order
.status
= "open"
3232 return update_status
3233 fetch
.side_effect
= _fetch(order
)
3234 self
.assertEqual("open", order
.get_status())
3235 fetch
.assert_called_once()
3238 with self
.subTest(debug
=False, finished
=True):
3239 self
.m
.debug
= False
3240 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3241 D("0.1"), "BTC", "long", self
.m
, "trade")
3243 def update_status():
3244 order
.status
= "closed"
3245 return update_status
3246 fetch
.side_effect
= _fetch(order
)
3247 self
.assertEqual("closed", order
.get_status())
3248 fetch
.assert_called_once()
3251 self
.m
.ccxt
.order_precision
.return_value
= 4
3252 with self
.subTest(debug
=True):
3254 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3255 D("0.1"), "BTC", "long", self
.m
, "trade")
3257 self
.m
.ccxt
.create_order
.assert_not_called()
3258 self
.m
.report
.log_debug_action
.assert_called_with("market.ccxt.create_order('ETH/BTC', 'limit', 'buy', 10.0000, price=0.1, account=exchange)")
3259 self
.assertEqual("open", order
.status
)
3260 self
.assertEqual(1, len(order
.results
))
3261 self
.assertEqual(-1, order
.id)
3263 self
.m
.ccxt
.create_order
.reset_mock()
3264 with self
.subTest(debug
=False):
3265 self
.m
.debug
= False
3266 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3267 D("0.1"), "BTC", "long", self
.m
, "trade")
3268 self
.m
.ccxt
.create_order
.return_value
= { "id": 123 }
3270 self
.m
.ccxt
.create_order
.assert_called_once()
3271 self
.assertEqual(1, len(order
.results
))
3272 self
.assertEqual("open", order
.status
)
3274 self
.m
.ccxt
.create_order
.reset_mock()
3275 with self
.subTest(exception
=True):
3276 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 10),
3277 D("0.1"), "BTC", "long", self
.m
, "trade")
3278 self
.m
.ccxt
.create_order
.side_effect
= Exception("bouh")
3280 self
.m
.ccxt
.create_order
.assert_called_once()
3281 self
.assertEqual(0, len(order
.results
))
3282 self
.assertEqual("error", order
.status
)
3283 self
.m
.report
.log_error
.assert_called_once()
3285 self
.m
.ccxt
.create_order
.reset_mock()
3286 with self
.subTest(dust_amount_exception
=True),\
3287 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
3288 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", 0.001),
3289 D("0.1"), "BTC", "long", self
.m
, "trade")
3290 self
.m
.ccxt
.create_order
.side_effect
= portfolio
.InvalidOrder
3292 self
.m
.ccxt
.create_order
.assert_called_once()
3293 self
.assertEqual(0, len(order
.results
))
3294 self
.assertEqual("closed", order
.status
)
3295 mark_finished_order
.assert_called_once()
3297 self
.m
.ccxt
.order_precision
.return_value
= 8
3298 self
.m
.ccxt
.create_order
.reset_mock()
3299 with self
.subTest(insufficient_funds
=True),\
3300 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
3301 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3302 D("0.1"), "BTC", "long", self
.m
, "trade")
3303 self
.m
.ccxt
.create_order
.side_effect
= [
3304 portfolio
.InsufficientFunds
,
3305 portfolio
.InsufficientFunds
,
3306 portfolio
.InsufficientFunds
,
3310 self
.m
.ccxt
.create_order
.assert_has_calls([
3311 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3312 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
3313 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
3314 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
3316 self
.assertEqual(4, self
.m
.ccxt
.create_order
.call_count
)
3317 self
.assertEqual(1, len(order
.results
))
3318 self
.assertEqual("open", order
.status
)
3319 self
.assertEqual(4, order
.tries
)
3320 self
.m
.report
.log_error
.assert_called()
3321 self
.assertEqual(4, self
.m
.report
.log_error
.call_count
)
3323 self
.m
.ccxt
.order_precision
.return_value
= 8
3324 self
.m
.ccxt
.create_order
.reset_mock()
3325 self
.m
.report
.log_error
.reset_mock()
3326 with self
.subTest(insufficient_funds
=True),\
3327 mock
.patch
.object(portfolio
.Order
, "mark_finished_order") as mark_finished_order
:
3328 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3329 D("0.1"), "BTC", "long", self
.m
, "trade")
3330 self
.m
.ccxt
.create_order
.side_effect
= [
3331 portfolio
.InsufficientFunds
,
3332 portfolio
.InsufficientFunds
,
3333 portfolio
.InsufficientFunds
,
3334 portfolio
.InsufficientFunds
,
3335 portfolio
.InsufficientFunds
,
3338 self
.m
.ccxt
.create_order
.assert_has_calls([
3339 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3340 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00099'), account
='exchange', price
=D('0.1')),
3341 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0009801'), account
='exchange', price
=D('0.1')),
3342 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00097029'), account
='exchange', price
=D('0.1')),
3343 mock
.call('ETH/BTC', 'limit', 'buy', D('0.00096059'), account
='exchange', price
=D('0.1')),
3345 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
3346 self
.assertEqual(0, len(order
.results
))
3347 self
.assertEqual("error", order
.status
)
3348 self
.assertEqual(5, order
.tries
)
3349 self
.m
.report
.log_error
.assert_called()
3350 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
3351 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
)
3354 with self
.subTest(invalid_nonce
=True):
3355 with self
.subTest(retry_success
=True):
3356 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3357 D("0.1"), "BTC", "long", self
.m
, "trade")
3358 self
.m
.ccxt
.create_order
.side_effect
= [
3359 portfolio
.InvalidNonce
,
3360 portfolio
.InvalidNonce
,
3364 self
.m
.ccxt
.create_order
.assert_has_calls([
3365 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3366 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3367 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3369 self
.assertEqual(3, self
.m
.ccxt
.create_order
.call_count
)
3370 self
.assertEqual(3, order
.tries
)
3371 self
.m
.report
.log_error
.assert_called()
3372 self
.assertEqual(2, self
.m
.report
.log_error
.call_count
)
3373 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying after invalid nonce", exception
=mock
.ANY
)
3374 self
.assertEqual(123, order
.id)
3377 with self
.subTest(retry_success
=False):
3378 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3379 D("0.1"), "BTC", "long", self
.m
, "trade")
3380 self
.m
.ccxt
.create_order
.side_effect
= [
3381 portfolio
.InvalidNonce
,
3382 portfolio
.InvalidNonce
,
3383 portfolio
.InvalidNonce
,
3384 portfolio
.InvalidNonce
,
3385 portfolio
.InvalidNonce
,
3388 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
3389 self
.assertEqual(5, order
.tries
)
3390 self
.m
.report
.log_error
.assert_called()
3391 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
3392 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
)
3393 self
.assertEqual("error", order
.status
)
3396 with self
.subTest(request_timeout
=True):
3397 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3398 D("0.1"), "BTC", "long", self
.m
, "trade")
3399 with self
.subTest(retrieved
=False), \
3400 mock
.patch
.object(order
, "retrieve_order") as retrieve
:
3401 self
.m
.ccxt
.create_order
.side_effect
= [
3402 portfolio
.RequestTimeout
,
3403 portfolio
.RequestTimeout
,
3406 retrieve
.return_value
= False
3408 self
.m
.ccxt
.create_order
.assert_has_calls([
3409 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3410 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3411 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3413 self
.assertEqual(3, self
.m
.ccxt
.create_order
.call_count
)
3414 self
.assertEqual(3, order
.tries
)
3415 self
.m
.report
.log_error
.assert_called()
3416 self
.assertEqual(2, self
.m
.report
.log_error
.call_count
)
3417 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Retrying after timeout", exception
=mock
.ANY
)
3418 self
.assertEqual(123, order
.id)
3421 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3422 D("0.1"), "BTC", "long", self
.m
, "trade")
3423 with self
.subTest(retrieved
=True), \
3424 mock
.patch
.object(order
, "retrieve_order") as retrieve
:
3425 self
.m
.ccxt
.create_order
.side_effect
= [
3426 portfolio
.RequestTimeout
,
3429 order
.results
.append({"id": 123}
)
3431 retrieve
.side_effect
= _retrieve
3433 self
.m
.ccxt
.create_order
.assert_has_calls([
3434 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3436 self
.assertEqual(1, self
.m
.ccxt
.create_order
.call_count
)
3437 self
.assertEqual(1, order
.tries
)
3438 self
.m
.report
.log_error
.assert_called()
3439 self
.assertEqual(1, self
.m
.report
.log_error
.call_count
)
3440 self
.m
.report
.log_error
.assert_called_with(mock
.ANY
, message
="Timeout, found the order")
3441 self
.assertEqual(123, order
.id)
3444 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3445 D("0.1"), "BTC", "long", self
.m
, "trade")
3446 with self
.subTest(retrieved
=False), \
3447 mock
.patch
.object(order
, "retrieve_order") as retrieve
:
3448 self
.m
.ccxt
.create_order
.side_effect
= [
3449 portfolio
.RequestTimeout
,
3450 portfolio
.RequestTimeout
,
3451 portfolio
.RequestTimeout
,
3452 portfolio
.RequestTimeout
,
3453 portfolio
.RequestTimeout
,
3455 retrieve
.return_value
= False
3457 self
.m
.ccxt
.create_order
.assert_has_calls([
3458 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3459 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3460 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3461 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3462 mock
.call('ETH/BTC', 'limit', 'buy', D('0.0010'), account
='exchange', price
=D('0.1')),
3464 self
.assertEqual(5, self
.m
.ccxt
.create_order
.call_count
)
3465 self
.assertEqual(5, order
.tries
)
3466 self
.m
.report
.log_error
.assert_called()
3467 self
.assertEqual(5, self
.m
.report
.log_error
.call_count
)
3468 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
)
3469 self
.assertEqual("error", order
.status
)
3471 def test_retrieve_order(self
):
3472 with self
.subTest(similar_open_order
=True):
3473 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3474 D("0.1"), "BTC", "long", self
.m
, "trade")
3475 order
.start_date
= datetime
.datetime(2018, 3, 25, 15, 15, 55)
3477 self
.m
.ccxt
.order_precision
.return_value
= 8
3478 self
.m
.ccxt
.fetch_orders
.return_value
= [
3480 'amount': 0.002, 'cost': 0.1,
3481 'datetime': '2018-03-25T15:15:51.000Z',
3482 'fee': None, 'filled': 0.0,
3486 'date': '2018-03-25 15:15:51',
3487 'margin': 0, 'orderNumber': '1',
3488 'price': '0.1', 'rate': '0.1',
3489 'side': 'buy', 'startingAmount': '0.002',
3490 'status': 'open', 'total': '0.0002',
3493 'price': 0.1, 'remaining': 0.002, 'side': 'buy',
3494 'status': 'open', 'symbol': 'ETH/BTC',
3495 'timestamp': 1521990951000, 'trades': None,
3499 'amount': 0.001, 'cost': 0.1,
3500 'datetime': '2018-03-25T15:15:51.000Z',
3501 'fee': None, 'filled': 0.0,
3505 'date': '2018-03-25 15:15:51',
3506 'margin': 1, 'orderNumber': '2',
3507 'price': '0.1', 'rate': '0.1',
3508 'side': 'buy', 'startingAmount': '0.001',
3509 'status': 'open', 'total': '0.0001',
3512 'price': 0.1, 'remaining': 0.001, 'side': 'buy',
3513 'status': 'open', 'symbol': 'ETH/BTC',
3514 'timestamp': 1521990951000, 'trades': None,
3518 'amount': 0.001, 'cost': 0.1,
3519 'datetime': '2018-03-25T15:15:51.000Z',
3520 'fee': None, 'filled': 0.0,
3524 'date': '2018-03-25 15:15:51',
3525 'margin': 0, 'orderNumber': '3',
3526 'price': '0.1', 'rate': '0.1',
3527 'side': 'sell', 'startingAmount': '0.001',
3528 'status': 'open', 'total': '0.0001',
3531 'price': 0.1, 'remaining': 0.001, 'side': 'sell',
3532 'status': 'open', 'symbol': 'ETH/BTC',
3533 'timestamp': 1521990951000, 'trades': None,
3537 'amount': 0.001, 'cost': 0.15,
3538 'datetime': '2018-03-25T15:15:51.000Z',
3539 'fee': None, 'filled': 0.0,
3543 'date': '2018-03-25 15:15:51',
3544 'margin': 0, 'orderNumber': '4',
3545 'price': '0.15', 'rate': '0.15',
3546 'side': 'buy', 'startingAmount': '0.001',
3547 'status': 'open', 'total': '0.0001',
3550 'price': 0.15, 'remaining': 0.001, 'side': 'buy',
3551 'status': 'open', 'symbol': 'ETH/BTC',
3552 'timestamp': 1521990951000, 'trades': None,
3556 'amount': 0.001, 'cost': 0.1,
3557 'datetime': '2018-03-25T15:15:51.000Z',
3558 'fee': None, 'filled': 0.0,
3562 'date': '2018-03-25 15:15:51',
3563 'margin': 0, 'orderNumber': '1',
3564 'price': '0.1', 'rate': '0.1',
3565 'side': 'buy', 'startingAmount': '0.001',
3566 'status': 'open', 'total': '0.0001',
3569 'price': 0.1, 'remaining': 0.001, 'side': 'buy',
3570 'status': 'open', 'symbol': 'ETH/BTC',
3571 'timestamp': 1521990951000, 'trades': None,
3575 result
= order
.retrieve_order()
3576 self
.assertTrue(result
)
3577 self
.assertEqual('5', order
.results
[0]["id"])
3578 self
.m
.ccxt
.fetch_my_trades
.assert_not_called()
3579 self
.m
.ccxt
.fetch_orders
.assert_called_once_with(symbol
="ETH/BTC", since
=1521983750)
3582 with self
.subTest(similar_open_order
=False, past_trades
=True):
3583 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3584 D("0.1"), "BTC", "long", self
.m
, "trade")
3585 order
.start_date
= datetime
.datetime(2018, 3, 25, 15, 15, 55)
3587 self
.m
.ccxt
.order_precision
.return_value
= 8
3588 self
.m
.ccxt
.fetch_orders
.return_value
= []
3589 self
.m
.ccxt
.fetch_my_trades
.return_value
= [
3590 { # Wrong timestamp 1
3593 'datetime': '2018-03-25T15:15:14.000Z',
3597 'category': 'exchange',
3598 'date': '2018-03-25 15:15:14',
3599 'fee': '0.00150000',
3610 'symbol': 'ETH/BTC',
3611 'timestamp': 1521983714,
3614 { # Wrong timestamp 2
3617 'datetime': '2018-03-25T15:16:54.000Z',
3621 'category': 'exchange',
3622 'date': '2018-03-25 15:16:54',
3623 'fee': '0.00150000',
3634 'symbol': 'ETH/BTC',
3635 'timestamp': 1521983814,
3641 'datetime': '2018-03-25T15:15:54.000Z',
3645 'category': 'exchange',
3646 'date': '2018-03-25 15:15:54',
3647 'fee': '0.00150000',
3658 'symbol': 'ETH/BTC',
3659 'timestamp': 1521983754,
3665 'datetime': '2018-03-25T15:16:54.000Z',
3669 'category': 'exchange',
3670 'date': '2018-03-25 15:16:54',
3671 'fee': '0.00150000',
3682 'symbol': 'ETH/BTC',
3683 'timestamp': 1521983814,
3689 'datetime': '2018-03-25T15:15:54.000Z',
3693 'category': 'marginTrade',
3694 'date': '2018-03-25 15:15:54',
3695 'fee': '0.00150000',
3706 'symbol': 'ETH/BTC',
3707 'timestamp': 1521983754,
3713 'datetime': '2018-03-25T15:16:54.000Z',
3717 'category': 'marginTrade',
3718 'date': '2018-03-25 15:16:54',
3719 'fee': '0.00150000',
3730 'symbol': 'ETH/BTC',
3731 'timestamp': 1521983814,
3737 'datetime': '2018-03-25T15:15:54.000Z',
3741 'category': 'exchange',
3742 'date': '2018-03-25 15:15:54',
3743 'fee': '0.00150000',
3754 'symbol': 'ETH/BTC',
3755 'timestamp': 1521983754,
3761 'datetime': '2018-03-25T15:16:54.000Z',
3765 'category': 'exchange',
3766 'date': '2018-03-25 15:16:54',
3767 'fee': '0.00150000',
3778 'symbol': 'ETH/BTC',
3779 'timestamp': 1521983814,
3785 'datetime': '2018-03-25T15:15:54.000Z',
3789 'category': 'exchange',
3790 'date': '2018-03-25 15:15:54',
3791 'fee': '0.00150000',
3795 'total': '0.000066',
3802 'symbol': 'ETH/BTC',
3803 'timestamp': 1521983754,
3809 'datetime': '2018-03-25T15:16:54.000Z',
3813 'category': 'exchange',
3814 'date': '2018-03-25 15:16:54',
3815 'fee': '0.00150000',
3826 'symbol': 'ETH/BTC',
3827 'timestamp': 1521983814,
3833 'datetime': '2018-03-25T15:15:54.000Z',
3837 'category': 'exchange',
3838 'date': '2018-03-25 15:15:54',
3839 'fee': '0.00150000',
3850 'symbol': 'ETH/BTC',
3851 'timestamp': 1521983754,
3857 'datetime': '2018-03-25T15:16:54.000Z',
3861 'category': 'exchange',
3862 'date': '2018-03-25 15:16:54',
3863 'fee': '0.00150000',
3867 'total': '0.000036',
3874 'symbol': 'ETH/BTC',
3875 'timestamp': 1521983814,
3880 result
= order
.retrieve_order()
3881 self
.assertTrue(result
)
3882 self
.assertEqual('7', order
.results
[0]["id"])
3883 self
.m
.ccxt
.fetch_orders
.assert_called_once_with(symbol
="ETH/BTC", since
=1521983750)
3886 with self
.subTest(similar_open_order
=False, past_trades
=False):
3887 order
= portfolio
.Order("buy", portfolio
.Amount("ETH", "0.001"),
3888 D("0.1"), "BTC", "long", self
.m
, "trade")
3889 order
.start_date
= datetime
.datetime(2018, 3, 25, 15, 15, 55)
3891 self
.m
.ccxt
.order_precision
.return_value
= 8
3892 self
.m
.ccxt
.fetch_orders
.return_value
= []
3893 self
.m
.ccxt
.fetch_my_trades
.return_value
= []
3894 result
= order
.retrieve_order()
3895 self
.assertFalse(result
)
3897 @unittest.skipUnless("unit" in limits
, "Unit skipped")
3898 class MouvementTest(WebMockTestCase
):
3899 def test_values(self
):
3900 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3901 "tradeID": 42, "type": "buy", "fee": "0.0015",
3902 "date": "2017-12-30 12:00:12", "rate": "0.1",
3903 "amount": "10", "total": "1"
3905 self
.assertEqual("ETH", mouvement
.currency
)
3906 self
.assertEqual("BTC", mouvement
.base_currency
)
3907 self
.assertEqual(42, mouvement
.id)
3908 self
.assertEqual("buy", mouvement
.action
)
3909 self
.assertEqual(D("0.0015"), mouvement
.fee_rate
)
3910 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), mouvement
.date
)
3911 self
.assertEqual(D("0.1"), mouvement
.rate
)
3912 self
.assertEqual(portfolio
.Amount("ETH", "10"), mouvement
.total
)
3913 self
.assertEqual(portfolio
.Amount("BTC", "1"), mouvement
.total_in_base
)
3915 mouvement
= portfolio
.Mouvement("ETH", "BTC", { "foo": "bar" }
)
3916 self
.assertIsNone(mouvement
.date
)
3917 self
.assertIsNone(mouvement
.id)
3918 self
.assertIsNone(mouvement
.action
)
3919 self
.assertEqual(-1, mouvement
.fee_rate
)
3920 self
.assertEqual(0, mouvement
.rate
)
3921 self
.assertEqual(portfolio
.Amount("ETH", 0), mouvement
.total
)
3922 self
.assertEqual(portfolio
.Amount("BTC", 0), mouvement
.total_in_base
)
3924 def test__repr(self
):
3925 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3926 "tradeID": 42, "type": "buy", "fee": "0.0015",
3927 "date": "2017-12-30 12:00:12", "rate": "0.1",
3928 "amount": "10", "total": "1"
3930 self
.assertEqual("Mouvement(2017-12-30 12:00:12 ; buy 10.00000000 ETH (1.00000000 BTC) fee: 0.1500%)", repr(mouvement
))
3932 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3933 "tradeID": 42, "type": "buy",
3934 "date": "garbage", "rate": "0.1",
3935 "amount": "10", "total": "1"
3937 self
.assertEqual("Mouvement(No date ; buy 10.00000000 ETH (1.00000000 BTC))", repr(mouvement
))
3939 def test_as_json(self
):
3940 mouvement
= portfolio
.Mouvement("ETH", "BTC", {
3941 "tradeID": 42, "type": "buy", "fee": "0.0015",
3942 "date": "2017-12-30 12:00:12", "rate": "0.1",
3943 "amount": "10", "total": "1"
3945 as_json
= mouvement
.as_json()
3947 self
.assertEqual(D("0.0015"), as_json
["fee_rate"])
3948 self
.assertEqual(portfolio
.datetime(2017, 12, 30, 12, 0, 12), as_json
["date"])
3949 self
.assertEqual("buy", as_json
["action"])
3950 self
.assertEqual(D("10"), as_json
["total"])
3951 self
.assertEqual(D("1"), as_json
["total_in_base"])
3952 self
.assertEqual("BTC", as_json
["base_currency"])
3953 self
.assertEqual("ETH", as_json
["currency"])
3955 @unittest.skipUnless("unit" in limits
, "Unit skipped")
3956 class ReportStoreTest(WebMockTestCase
):
3957 def test_add_log(self
):
3958 report_store
= market
.ReportStore(self
.m
)
3959 report_store
.add_log({"foo": "bar"}
)
3961 self
.assertEqual({"foo": "bar", "date": mock.ANY}
, report_store
.logs
[0])
3963 def test_set_verbose(self
):
3964 report_store
= market
.ReportStore(self
.m
)
3965 with self
.subTest(verbose
=True):
3966 report_store
.set_verbose(True)
3967 self
.assertTrue(report_store
.verbose_print
)
3969 with self
.subTest(verbose
=False):
3970 report_store
.set_verbose(False)
3971 self
.assertFalse(report_store
.verbose_print
)
3973 def test_merge(self
):
3974 report_store1
= market
.ReportStore(self
.m
, verbose_print
=False)
3975 report_store2
= market
.ReportStore(None, verbose_print
=False)
3977 report_store2
.log_stage("1")
3978 report_store1
.log_stage("2")
3979 report_store2
.log_stage("3")
3981 report_store1
.merge(report_store2
)
3983 self
.assertEqual(3, len(report_store1
.logs
))
3984 self
.assertEqual(["1", "2", "3"], list(map(lambda x
: x
["stage"], report_store1
.logs
)))
3985 self
.assertEqual(6, len(report_store1
.print_logs
))
3987 def test_print_log(self
):
3988 report_store
= market
.ReportStore(self
.m
)
3989 with self
.subTest(verbose
=True),\
3990 mock
.patch
.object(store
, "datetime") as time_mock
,\
3991 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
3992 time_mock
.now
.return_value
= datetime
.datetime(2018, 2, 25, 2, 20, 10)
3993 report_store
.set_verbose(True)
3994 report_store
.print_log("Coucou")
3995 report_store
.print_log(portfolio
.Amount("BTC", 1))
3996 self
.assertEqual(stdout_mock
.getvalue(), "2018-02-25 02:20:10: Coucou\n2018-02-25 02:20:10: 1.00000000 BTC\n")
3998 with self
.subTest(verbose
=False),\
3999 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4000 report_store
.set_verbose(False)
4001 report_store
.print_log("Coucou")
4002 report_store
.print_log(portfolio
.Amount("BTC", 1))
4003 self
.assertEqual(stdout_mock
.getvalue(), "")
4005 def test_default_json_serial(self
):
4006 report_store
= market
.ReportStore(self
.m
)
4008 self
.assertEqual("2018-02-24T00:00:00",
4009 report_store
.default_json_serial(portfolio
.datetime(2018, 2, 24)))
4010 self
.assertEqual("1.00000000 BTC",
4011 report_store
.default_json_serial(portfolio
.Amount("BTC", 1)))
4013 def test_to_json(self
):
4014 report_store
= market
.ReportStore(self
.m
)
4015 report_store
.logs
.append({"foo": "bar"}
)
4016 self
.assertEqual('[\n {\n "foo": "bar"\n }\n]', report_store
.to_json())
4017 report_store
.logs
.append({"date": portfolio.datetime(2018, 2, 24)}
)
4018 self
.assertEqual('[\n {\n "foo": "bar"\n },\n {\n "date": "2018-02-24T00:00:00"\n }\n]', report_store
.to_json())
4019 report_store
.logs
.append({"amount": portfolio.Amount("BTC", 1)}
)
4020 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())
4022 def test_to_json_array(self
):
4023 report_store
= market
.ReportStore(self
.m
)
4024 report_store
.logs
.append({
4025 "date": "date1", "type": "type1", "foo": "bar", "bla": "bla"
4027 report_store
.logs
.append({
4028 "date": "date2", "type": "type2", "foo": "bar", "bla": "bla"
4030 logs
= list(report_store
.to_json_array())
4032 self
.assertEqual(2, len(logs
))
4033 self
.assertEqual(("date1", "type1", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs
[0])
4034 self
.assertEqual(("date2", "type2", '{\n "foo": "bar",\n "bla": "bla"\n}'), logs
[1])
4036 @mock.patch.object(market
.ReportStore
, "print_log")
4037 @mock.patch.object(market
.ReportStore
, "add_log")
4038 def test_log_stage(self
, add_log
, print_log
):
4039 report_store
= market
.ReportStore(self
.m
)
4041 report_store
.log_stage("foo", bar
="baz", c
=c
, d
=portfolio
.Amount("BTC", 1))
4042 print_log
.assert_has_calls([
4043 mock
.call("-----------"),
4044 mock
.call("[Stage] foo bar=baz, c=c = lambda x: x, d={'currency': 'BTC', 'value': Decimal('1')}"),
4046 add_log
.assert_called_once_with({
4051 'c': 'c = lambda x: x',
4059 @mock.patch.object(market
.ReportStore
, "print_log")
4060 @mock.patch.object(market
.ReportStore
, "add_log")
4061 def test_log_balances(self
, add_log
, print_log
):
4062 report_store
= market
.ReportStore(self
.m
)
4063 self
.m
.balances
.as_json
.return_value
= "json"
4064 self
.m
.balances
.all
= { "FOO": "bar", "BAR": "baz" }
4066 report_store
.log_balances(tag
="tag")
4067 print_log
.assert_has_calls([
4068 mock
.call("[Balance]"),
4072 add_log
.assert_called_once_with({
4078 @mock.patch.object(market
.ReportStore
, "print_log")
4079 @mock.patch.object(market
.ReportStore
, "add_log")
4080 def test_log_tickers(self
, add_log
, print_log
):
4081 report_store
= market
.ReportStore(self
.m
)
4083 "BTC": portfolio
.Amount("BTC", 10),
4084 "ETH": portfolio
.Amount("BTC", D("0.3"))
4086 amounts
["ETH"].rate
= D("0.1")
4088 report_store
.log_tickers(amounts
, "BTC", "default", "total")
4089 print_log
.assert_not_called()
4090 add_log
.assert_called_once_with({
4092 'compute_value': 'default',
4093 'balance_type': 'total',
4106 add_log
.reset_mock()
4107 compute_value
= lambda x
: x
["bid"]
4108 report_store
.log_tickers(amounts
, "BTC", compute_value
, "total")
4109 add_log
.assert_called_once_with({
4111 'compute_value': 'compute_value = lambda x: x["bid"]',
4112 'balance_type': 'total',
4125 @mock.patch.object(market
.ReportStore
, "print_log")
4126 @mock.patch.object(market
.ReportStore
, "add_log")
4127 def test_log_dispatch(self
, add_log
, print_log
):
4128 report_store
= market
.ReportStore(self
.m
)
4129 amount
= portfolio
.Amount("BTC", "10.3")
4131 "BTC": portfolio
.Amount("BTC", 10),
4132 "ETH": portfolio
.Amount("BTC", D("0.3"))
4134 report_store
.log_dispatch(amount
, amounts
, "medium", "repartition")
4135 print_log
.assert_not_called()
4136 add_log
.assert_called_once_with({
4138 'liquidity': 'medium',
4139 'repartition_ratio': 'repartition',
4150 @mock.patch.object(market
.ReportStore
, "print_log")
4151 @mock.patch.object(market
.ReportStore
, "add_log")
4152 def test_log_trades(self
, add_log
, print_log
):
4153 report_store
= market
.ReportStore(self
.m
)
4154 trade_mock1
= mock
.Mock()
4155 trade_mock2
= mock
.Mock()
4156 trade_mock1
.as_json
.return_value
= { "trade": "1" }
4157 trade_mock2
.as_json
.return_value
= { "trade": "2" }
4159 matching_and_trades
= [
4160 (True, trade_mock1
),
4161 (False, trade_mock2
),
4163 report_store
.log_trades(matching_and_trades
, "only")
4165 print_log
.assert_not_called()
4166 add_log
.assert_called_with({
4171 {'trade': '1', 'skipped': False}
,
4172 {'trade': '2', 'skipped': True}
4176 @mock.patch.object(market
.ReportStore
, "print_log")
4177 @mock.patch.object(market
.ReportStore
, "add_log")
4178 def test_log_orders(self
, add_log
, print_log
):
4179 report_store
= market
.ReportStore(self
.m
)
4181 order_mock1
= mock
.Mock()
4182 order_mock2
= mock
.Mock()
4184 order_mock1
.as_json
.return_value
= "order1"
4185 order_mock2
.as_json
.return_value
= "order2"
4187 orders
= [order_mock1
, order_mock2
]
4189 report_store
.log_orders(orders
, tick
="tick",
4190 only
="only", compute_value
="compute_value")
4192 print_log
.assert_called_once_with("[Orders]")
4193 self
.m
.trades
.print_all_with_order
.assert_called_once_with(ind
="\t")
4195 add_log
.assert_called_with({
4198 'compute_value': 'compute_value',
4200 'orders': ['order1', 'order2']
4203 add_log
.reset_mock()
4204 def compute_value(x
, y
):
4206 report_store
.log_orders(orders
, tick
="tick",
4207 only
="only", compute_value
=compute_value
)
4208 add_log
.assert_called_with({
4211 'compute_value': 'def compute_value(x, y):\n return x[y]',
4213 'orders': ['order1', 'order2']
4217 @mock.patch.object(market
.ReportStore
, "print_log")
4218 @mock.patch.object(market
.ReportStore
, "add_log")
4219 def test_log_order(self
, add_log
, print_log
):
4220 report_store
= market
.ReportStore(self
.m
)
4221 order_mock
= mock
.Mock()
4222 order_mock
.as_json
.return_value
= "order"
4223 new_order_mock
= mock
.Mock()
4224 new_order_mock
.as_json
.return_value
= "new_order"
4225 order_mock
.__repr
__ = mock
.Mock()
4226 order_mock
.__repr
__.return_value
= "Order Mock"
4227 new_order_mock
.__repr
__ = mock
.Mock()
4228 new_order_mock
.__repr
__.return_value
= "New order Mock"
4230 with self
.subTest(finished
=True):
4231 report_store
.log_order(order_mock
, 1, finished
=True)
4232 print_log
.assert_called_once_with("[Order] Finished Order Mock")
4233 add_log
.assert_called_once_with({
4238 'compute_value': None,
4242 add_log
.reset_mock()
4243 print_log
.reset_mock()
4245 with self
.subTest(update
="waiting"):
4246 report_store
.log_order(order_mock
, 1, update
="waiting")
4247 print_log
.assert_called_once_with("[Order] Order Mock, tick 1, waiting")
4248 add_log
.assert_called_once_with({
4251 'update': 'waiting',
4253 'compute_value': None,
4257 add_log
.reset_mock()
4258 print_log
.reset_mock()
4259 with self
.subTest(update
="adjusting"):
4260 compute_value
= lambda x
: (x
["bid"] + x
["ask"]*2)/3
4261 report_store
.log_order(order_mock
, 3,
4262 update
="adjusting", new_order
=new_order_mock
,
4263 compute_value
=compute_value
)
4264 print_log
.assert_called_once_with("[Order] Order Mock, tick 3, cancelling and adjusting to New order Mock")
4265 add_log
.assert_called_once_with({
4268 'update': 'adjusting',
4270 'compute_value': 'compute_value = lambda x: (x["bid"] + x["ask"]*2)/3',
4271 'new_order': 'new_order'
4274 add_log
.reset_mock()
4275 print_log
.reset_mock()
4276 with self
.subTest(update
="market_fallback"):
4277 report_store
.log_order(order_mock
, 7,
4278 update
="market_fallback", new_order
=new_order_mock
)
4279 print_log
.assert_called_once_with("[Order] Order Mock, tick 7, fallbacking to market value")
4280 add_log
.assert_called_once_with({
4283 'update': 'market_fallback',
4285 'compute_value': None,
4286 'new_order': 'new_order'
4289 add_log
.reset_mock()
4290 print_log
.reset_mock()
4291 with self
.subTest(update
="market_adjusting"):
4292 report_store
.log_order(order_mock
, 17,
4293 update
="market_adjust", new_order
=new_order_mock
)
4294 print_log
.assert_called_once_with("[Order] Order Mock, tick 17, market value, cancelling and adjusting to New order Mock")
4295 add_log
.assert_called_once_with({
4298 'update': 'market_adjust',
4300 'compute_value': None,
4301 'new_order': 'new_order'
4304 @mock.patch.object(market
.ReportStore
, "print_log")
4305 @mock.patch.object(market
.ReportStore
, "add_log")
4306 def test_log_move_balances(self
, add_log
, print_log
):
4307 report_store
= market
.ReportStore(self
.m
)
4309 "BTC": portfolio
.Amount("BTC", 10),
4313 "BTC": portfolio
.Amount("BTC", 3),
4316 report_store
.log_move_balances(needed
, moving
)
4317 print_log
.assert_not_called()
4318 add_log
.assert_called_once_with({
4319 'type': 'move_balances',
4331 @mock.patch.object(market
.ReportStore
, "print_log")
4332 @mock.patch.object(market
.ReportStore
, "add_log")
4333 def test_log_http_request(self
, add_log
, print_log
):
4334 report_store
= market
.ReportStore(self
.m
)
4335 response
= mock
.Mock()
4336 response
.status_code
= 200
4337 response
.text
= "Hey"
4339 report_store
.log_http_request("method", "url", "body",
4340 "headers", response
)
4341 print_log
.assert_not_called()
4342 add_log
.assert_called_once_with({
4343 'type': 'http_request',
4347 'headers': 'headers',
4352 @mock.patch.object(market
.ReportStore
, "add_log")
4353 def test_log_market(self
, add_log
):
4354 report_store
= market
.ReportStore(self
.m
)
4360 report_store
.log_market(Args(), 4, 1, "report", True)
4361 add_log
.assert_called_once_with({
4363 "commit": "$Format:%H$",
4364 "args": { "debug": True, "quiet": False }
,
4367 "report_path": "report",
4371 @mock.patch.object(market
.ReportStore
, "print_log")
4372 @mock.patch.object(market
.ReportStore
, "add_log")
4373 def test_log_error(self
, add_log
, print_log
):
4374 report_store
= market
.ReportStore(self
.m
)
4375 with self
.subTest(message
=None, exception
=None):
4376 report_store
.log_error("action")
4377 print_log
.assert_called_once_with("[Error] action")
4378 add_log
.assert_called_once_with({
4381 'exception_class': None,
4382 'exception_message': None,
4386 print_log
.reset_mock()
4387 add_log
.reset_mock()
4388 with self
.subTest(message
="Hey", exception
=None):
4389 report_store
.log_error("action", message
="Hey")
4390 print_log
.assert_has_calls([
4391 mock
.call("[Error] action"),
4394 add_log
.assert_called_once_with({
4397 'exception_class': None,
4398 'exception_message': None,
4402 print_log
.reset_mock()
4403 add_log
.reset_mock()
4404 with self
.subTest(message
=None, exception
=Exception("bouh")):
4405 report_store
.log_error("action", exception
=Exception("bouh"))
4406 print_log
.assert_has_calls([
4407 mock
.call("[Error] action"),
4408 mock
.call("\tException: bouh")
4410 add_log
.assert_called_once_with({
4413 'exception_class': "Exception",
4414 'exception_message': "bouh",
4418 print_log
.reset_mock()
4419 add_log
.reset_mock()
4420 with self
.subTest(message
="Hey", exception
=Exception("bouh")):
4421 report_store
.log_error("action", message
="Hey", exception
=Exception("bouh"))
4422 print_log
.assert_has_calls([
4423 mock
.call("[Error] action"),
4424 mock
.call("\tException: bouh"),
4427 add_log
.assert_called_once_with({
4430 'exception_class': "Exception",
4431 'exception_message': "bouh",
4435 @mock.patch.object(market
.ReportStore
, "print_log")
4436 @mock.patch.object(market
.ReportStore
, "add_log")
4437 def test_log_debug_action(self
, add_log
, print_log
):
4438 report_store
= market
.ReportStore(self
.m
)
4439 report_store
.log_debug_action("Hey")
4441 print_log
.assert_called_once_with("[Debug] Hey")
4442 add_log
.assert_called_once_with({
4443 'type': 'debug_action',
4447 @unittest.skipUnless("unit" in limits
, "Unit skipped")
4448 class MainTest(WebMockTestCase
):
4449 def test_make_order(self
):
4450 self
.m
.get_ticker
.return_value
= {
4452 "average": D("0.1"),
4457 with self
.subTest(description
="nominal case"):
4458 main
.make_order(self
.m
, 10, "ETH")
4460 self
.m
.report
.log_stage
.assert_has_calls([
4461 mock
.call("make_order_begin"),
4462 mock
.call("make_order_end"),
4464 self
.m
.balances
.fetch_balances
.assert_has_calls([
4465 mock
.call(tag
="make_order_begin"),
4466 mock
.call(tag
="make_order_end"),
4468 self
.m
.trades
.all
.append
.assert_called_once()
4469 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4470 self
.assertEqual(False, trade
.orders
[0].close_if_possible
)
4471 self
.assertEqual(0, trade
.value_from
)
4472 self
.assertEqual("ETH", trade
.currency
)
4473 self
.assertEqual("BTC", trade
.base_currency
)
4474 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
4475 self
.m
.trades
.run_orders
.assert_called_once_with()
4476 self
.m
.follow_orders
.assert_called_once_with()
4478 order
= trade
.orders
[0]
4479 self
.assertEqual(D("0.10"), order
.rate
)
4482 with self
.subTest(compute_value
="default"):
4483 main
.make_order(self
.m
, 10, "ETH", action
="dispose",
4484 compute_value
="ask")
4486 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4487 order
= trade
.orders
[0]
4488 self
.assertEqual(D("0.11"), order
.rate
)
4491 with self
.subTest(follow
=False):
4492 result
= main
.make_order(self
.m
, 10, "ETH", follow
=False)
4494 self
.m
.report
.log_stage
.assert_has_calls([
4495 mock
.call("make_order_begin"),
4496 mock
.call("make_order_end_not_followed"),
4498 self
.m
.balances
.fetch_balances
.assert_called_once_with(tag
="make_order_begin")
4500 self
.m
.trades
.all
.append
.assert_called_once()
4501 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4502 self
.assertEqual(0, trade
.value_from
)
4503 self
.assertEqual("ETH", trade
.currency
)
4504 self
.assertEqual("BTC", trade
.base_currency
)
4505 self
.m
.report
.log_orders
.assert_called_once_with([trade
.orders
[0]], None, "average")
4506 self
.m
.trades
.run_orders
.assert_called_once_with()
4507 self
.m
.follow_orders
.assert_not_called()
4508 self
.assertEqual(trade
.orders
[0], result
)
4511 with self
.subTest(base_currency
="USDT"):
4512 main
.make_order(self
.m
, 1, "BTC", base_currency
="USDT")
4514 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4515 self
.assertEqual("BTC", trade
.currency
)
4516 self
.assertEqual("USDT", trade
.base_currency
)
4519 with self
.subTest(close_if_possible
=True):
4520 main
.make_order(self
.m
, 10, "ETH", close_if_possible
=True)
4522 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4523 self
.assertEqual(True, trade
.orders
[0].close_if_possible
)
4526 with self
.subTest(action
="dispose"):
4527 main
.make_order(self
.m
, 10, "ETH", action
="dispose")
4529 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4530 self
.assertEqual(0, trade
.value_to
)
4531 self
.assertEqual(1, trade
.value_from
.value
)
4532 self
.assertEqual("ETH", trade
.currency
)
4533 self
.assertEqual("BTC", trade
.base_currency
)
4536 with self
.subTest(compute_value
="default"):
4537 main
.make_order(self
.m
, 10, "ETH", action
="dispose",
4538 compute_value
="bid")
4540 trade
= self
.m
.trades
.all
.append
.mock_calls
[0][1][0]
4541 self
.assertEqual(D("0.9"), trade
.value_from
.value
)
4543 def test_get_user_market(self
):
4544 with mock
.patch("main.fetch_markets") as main_fetch_markets
,\
4545 mock
.patch("main.parse_config") as main_parse_config
:
4546 with self
.subTest(debug
=False):
4547 main_parse_config
.return_value
= ["pg_config", "report_path"]
4548 main_fetch_markets
.return_value
= [(1, {"key": "market_config"}
, 3)]
4549 m
= main
.get_user_market("config_path.ini", 1)
4551 self
.assertIsInstance(m
, market
.Market
)
4552 self
.assertFalse(m
.debug
)
4554 with self
.subTest(debug
=True):
4555 main_parse_config
.return_value
= ["pg_config", "report_path"]
4556 main_fetch_markets
.return_value
= [(1, {"key": "market_config"}
, 3)]
4557 m
= main
.get_user_market("config_path.ini", 1, debug
=True)
4559 self
.assertIsInstance(m
, market
.Market
)
4560 self
.assertTrue(m
.debug
)
4562 def test_process(self
):
4563 with mock
.patch("market.Market") as market_mock
,\
4564 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4566 args_mock
= mock
.Mock()
4567 args_mock
.action
= "action"
4568 args_mock
.config
= "config"
4569 args_mock
.user
= "user"
4570 args_mock
.debug
= "debug"
4571 args_mock
.before
= "before"
4572 args_mock
.after
= "after"
4573 self
.assertEqual("", stdout_mock
.getvalue())
4575 main
.process("config", 3, 1, args_mock
, "report_path", "pg_config")
4577 market_mock
.from_config
.assert_has_calls([
4578 mock
.call("config", args_mock
, pg_config
="pg_config", market_id
=3, user_id
=1, report_path
="report_path"),
4579 mock
.call().process("action", before
="before", after
="after"),
4582 with self
.subTest(exception
=True):
4583 market_mock
.from_config
.side_effect
= Exception("boo")
4584 main
.process(3, "config", 1, "report_path", args_mock
, "pg_config")
4585 self
.assertEqual("Exception: boo\n", stdout_mock
.getvalue())
4587 def test_main(self
):
4588 with self
.subTest(parallel
=False):
4589 with mock
.patch("main.parse_args") as parse_args
,\
4590 mock
.patch("main.parse_config") as parse_config
,\
4591 mock
.patch("main.fetch_markets") as fetch_markets
,\
4592 mock
.patch("main.process") as process
:
4594 args_mock
= mock
.Mock()
4595 args_mock
.parallel
= False
4596 args_mock
.config
= "config"
4597 args_mock
.user
= "user"
4598 parse_args
.return_value
= args_mock
4600 parse_config
.return_value
= ["pg_config", "report_path"]
4602 fetch_markets
.return_value
= [[3, "config1", 1], [1, "config2", 2]]
4604 main
.main(["Foo", "Bar"])
4606 parse_args
.assert_called_with(["Foo", "Bar"])
4607 parse_config
.assert_called_with("config")
4608 fetch_markets
.assert_called_with("pg_config", "user")
4610 self
.assertEqual(2, process
.call_count
)
4611 process
.assert_has_calls([
4612 mock
.call("config1", 3, 1, args_mock
, "report_path", "pg_config"),
4613 mock
.call("config2", 1, 2, args_mock
, "report_path", "pg_config"),
4615 with self
.subTest(parallel
=True):
4616 with mock
.patch("main.parse_args") as parse_args
,\
4617 mock
.patch("main.parse_config") as parse_config
,\
4618 mock
.patch("main.fetch_markets") as fetch_markets
,\
4619 mock
.patch("main.process") as process
,\
4620 mock
.patch("store.Portfolio.start_worker") as start
:
4622 args_mock
= mock
.Mock()
4623 args_mock
.parallel
= True
4624 args_mock
.config
= "config"
4625 args_mock
.user
= "user"
4626 parse_args
.return_value
= args_mock
4628 parse_config
.return_value
= ["pg_config", "report_path"]
4630 fetch_markets
.return_value
= [[3, "config1", 1], [1, "config2", 2]]
4632 main
.main(["Foo", "Bar"])
4634 parse_args
.assert_called_with(["Foo", "Bar"])
4635 parse_config
.assert_called_with("config")
4636 fetch_markets
.assert_called_with("pg_config", "user")
4638 start
.assert_called_once_with()
4639 self
.assertEqual(2, process
.call_count
)
4640 process
.assert_has_calls([
4641 mock
.call
.__bool
__(),
4642 mock
.call("config1", 3, 1, args_mock
, "report_path", "pg_config"),
4643 mock
.call
.__bool
__(),
4644 mock
.call("config2", 1, 2, args_mock
, "report_path", "pg_config"),
4647 @mock.patch.object(main
.sys
, "exit")
4648 @mock.patch("main.configparser")
4649 @mock.patch("main.os")
4650 def test_parse_config(self
, os
, configparser
, exit
):
4651 with self
.subTest(pg_config
=True, report_path
=None):
4652 config_mock
= mock
.MagicMock()
4653 configparser
.ConfigParser
.return_value
= config_mock
4654 def config(element
):
4655 return element
== "postgresql"
4657 config_mock
.__contains
__.side_effect
= config
4658 config_mock
.__getitem
__.return_value
= "pg_config"
4660 result
= main
.parse_config("configfile")
4662 config_mock
.read
.assert_called_with("configfile")
4664 self
.assertEqual(["pg_config", None], result
)
4666 with self
.subTest(pg_config
=True, report_path
="present"):
4667 config_mock
= mock
.MagicMock()
4668 configparser
.ConfigParser
.return_value
= config_mock
4670 config_mock
.__contains
__.return_value
= True
4671 config_mock
.__getitem
__.side_effect
= [
4672 {"report_path": "report_path"}
,
4673 {"report_path": "report_path"}
,
4677 os
.path
.exists
.return_value
= False
4678 result
= main
.parse_config("configfile")
4680 config_mock
.read
.assert_called_with("configfile")
4681 self
.assertEqual(["pg_config", "report_path"], result
)
4682 os
.path
.exists
.assert_called_once_with("report_path")
4683 os
.makedirs
.assert_called_once_with("report_path")
4685 with self
.subTest(pg_config
=False),\
4686 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4687 config_mock
= mock
.MagicMock()
4688 configparser
.ConfigParser
.return_value
= config_mock
4689 result
= main
.parse_config("configfile")
4691 config_mock
.read
.assert_called_with("configfile")
4692 exit
.assert_called_once_with(1)
4693 self
.assertEqual("no configuration for postgresql in config file\n", stdout_mock
.getvalue())
4695 @mock.patch.object(main
.sys
, "exit")
4696 def test_parse_args(self
, exit
):
4697 with self
.subTest(config
="config.ini"):
4698 args
= main
.parse_args([])
4699 self
.assertEqual("config.ini", args
.config
)
4700 self
.assertFalse(args
.before
)
4701 self
.assertFalse(args
.after
)
4702 self
.assertFalse(args
.debug
)
4704 args
= main
.parse_args(["--before", "--after", "--debug"])
4705 self
.assertTrue(args
.before
)
4706 self
.assertTrue(args
.after
)
4707 self
.assertTrue(args
.debug
)
4709 exit
.assert_not_called()
4711 with self
.subTest(config
="inexistant"),\
4712 mock
.patch('sys.stdout', new_callable
=StringIO
) as stdout_mock
:
4713 args
= main
.parse_args(["--config", "foo.bar"])
4714 exit
.assert_called_once_with(1)
4715 self
.assertEqual("no config file found, exiting\n", stdout_mock
.getvalue())
4717 @mock.patch.object(main
, "psycopg2")
4718 def test_fetch_markets(self
, psycopg2
):
4719 connect_mock
= mock
.Mock()
4720 cursor_mock
= mock
.MagicMock()
4721 cursor_mock
.__iter
__.return_value
= ["row_1", "row_2"]
4723 connect_mock
.cursor
.return_value
= cursor_mock
4724 psycopg2
.connect
.return_value
= connect_mock
4726 with self
.subTest(user
=None):
4727 rows
= list(main
.fetch_markets({"foo": "bar"}
, None))
4729 psycopg2
.connect
.assert_called_once_with(foo
="bar")
4730 cursor_mock
.execute
.assert_called_once_with("SELECT id,config,user_id FROM market_configs")
4732 self
.assertEqual(["row_1", "row_2"], rows
)
4734 psycopg2
.connect
.reset_mock()
4735 cursor_mock
.execute
.reset_mock()
4736 with self
.subTest(user
=1):
4737 rows
= list(main
.fetch_markets({"foo": "bar"}
, 1))
4739 psycopg2
.connect
.assert_called_once_with(foo
="bar")
4740 cursor_mock
.execute
.assert_called_once_with("SELECT id,config,user_id FROM market_configs WHERE user_id = %s", 1)
4742 self
.assertEqual(["row_1", "row_2"], rows
)
4745 @unittest.skipUnless("unit" in limits
, "Unit skipped")
4746 class ProcessorTest(WebMockTestCase
):
4747 def test_values(self
):
4748 processor
= market
.Processor(self
.m
)
4750 self
.assertEqual(self
.m
, processor
.market
)
4752 def test_run_action(self
):
4753 processor
= market
.Processor(self
.m
)
4755 with mock
.patch
.object(processor
, "parse_args") as parse_args
:
4756 method_mock
= mock
.Mock()
4757 parse_args
.return_value
= [method_mock
, { "foo": "bar" }
]
4759 processor
.run_action("foo", "bar", "baz")
4761 parse_args
.assert_called_with("foo", "bar", "baz")
4763 method_mock
.assert_called_with(foo
="bar")
4765 processor
.run_action("wait_for_recent", "bar", "baz")
4767 method_mock
.assert_called_with(foo
="bar")
4769 def test_select_step(self
):
4770 processor
= market
.Processor(self
.m
)
4772 scenario
= processor
.scenarios
["sell_all"]
4774 self
.assertEqual(scenario
, processor
.select_steps(scenario
, "all"))
4775 self
.assertEqual(["all_sell"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "before"))))
4776 self
.assertEqual(["wait", "all_buy"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "after"))))
4777 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, 2))))
4778 self
.assertEqual(["wait"], list(map(lambda x
: x
["name"], processor
.select_steps(scenario
, "wait"))))
4780 with self
.assertRaises(TypeError):
4781 processor
.select_steps(scenario
, ["wait"])
4783 @mock.patch("market.Processor.process_step")
4784 def test_process(self
, process_step
):
4785 processor
= market
.Processor(self
.m
)
4787 processor
.process("sell_all", foo
="bar")
4788 self
.assertEqual(3, process_step
.call_count
)
4790 steps
= list(map(lambda x
: x
[1][1]["name"], process_step
.mock_calls
))
4791 scenario_names
= list(map(lambda x
: x
[1][0], process_step
.mock_calls
))
4792 kwargs
= list(map(lambda x
: x
[1][2], process_step
.mock_calls
))
4793 self
.assertEqual(["all_sell", "wait", "all_buy"], steps
)
4794 self
.assertEqual(["sell_all", "sell_all", "sell_all"], scenario_names
)
4795 self
.assertEqual([{"foo":"bar"}
, {"foo":"bar"}
, {"foo":"bar"}
], kwargs
)
4797 process_step
.reset_mock()
4799 processor
.process("sell_needed", steps
=["before", "after"])
4800 self
.assertEqual(3, process_step
.call_count
)
4802 def test_method_arguments(self
):
4803 ccxt
= mock
.Mock(spec
=market
.ccxt
.poloniexE
)
4804 m
= market
.Market(ccxt
, self
.market_args())
4806 processor
= market
.Processor(m
)
4808 method
, arguments
= processor
.method_arguments("wait_for_recent")
4809 self
.assertEqual(market
.Portfolio
.wait_for_recent
, method
)
4810 self
.assertEqual(["delta", "poll"], arguments
)
4812 method
, arguments
= processor
.method_arguments("prepare_trades")
4813 self
.assertEqual(m
.prepare_trades
, method
)
4814 self
.assertEqual(['base_currency', 'liquidity', 'compute_value', 'repartition', 'only'], arguments
)
4816 method
, arguments
= processor
.method_arguments("prepare_orders")
4817 self
.assertEqual(m
.trades
.prepare_orders
, method
)
4819 method
, arguments
= processor
.method_arguments("move_balances")
4820 self
.assertEqual(m
.move_balances
, method
)
4822 method
, arguments
= processor
.method_arguments("run_orders")
4823 self
.assertEqual(m
.trades
.run_orders
, method
)
4825 method
, arguments
= processor
.method_arguments("follow_orders")
4826 self
.assertEqual(m
.follow_orders
, method
)
4828 method
, arguments
= processor
.method_arguments("close_trades")
4829 self
.assertEqual(m
.trades
.close_trades
, method
)
4831 def test_process_step(self
):
4832 processor
= market
.Processor(self
.m
)
4834 with mock
.patch
.object(processor
, "run_action") as run_action
:
4835 step
= processor
.scenarios
["sell_needed"][1]
4837 processor
.process_step("foo", step
, {"foo":"bar"}
)
4839 self
.m
.report
.log_stage
.assert_has_calls([
4840 mock
.call("process_foo__1_sell_begin"),
4841 mock
.call("process_foo__1_sell_end"),
4843 self
.m
.balances
.fetch_balances
.assert_has_calls([
4844 mock
.call(tag
="process_foo__1_sell_begin"),
4845 mock
.call(tag
="process_foo__1_sell_end"),
4848 self
.assertEqual(5, run_action
.call_count
)
4850 run_action
.assert_has_calls([
4851 mock
.call('prepare_trades', {}, {'foo': 'bar'}
),
4852 mock
.call('prepare_orders', {'only': 'dispose', 'compute_value': 'average'}
, {'foo': 'bar'}
),
4853 mock
.call('run_orders', {}, {'foo': 'bar'}
),
4854 mock
.call('follow_orders', {}, {'foo': 'bar'}
),
4855 mock
.call('close_trades', {}, {'foo': 'bar'}
),
4859 with mock
.patch
.object(processor
, "run_action") as run_action
:
4860 step
= processor
.scenarios
["sell_needed"][0]
4862 processor
.process_step("foo", step
, {"foo":"bar"}
)
4863 self
.m
.balances
.fetch_balances
.assert_not_called()
4865 def test_parse_args(self
):
4866 processor
= market
.Processor(self
.m
)
4868 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4869 method_mock
= mock
.Mock()
4870 method_arguments
.return_value
= [
4874 method
, args
= processor
.parse_args("action", {"foo": "bar", "foo2": "bar"}
, {"foo": "bar2", "bla": "bla"}
)
4876 self
.assertEqual(method_mock
, method
)
4877 self
.assertEqual({"foo": "bar2", "foo2": "bar"}
, args
)
4879 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4880 method_mock
= mock
.Mock()
4881 method_arguments
.return_value
= [
4885 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {})
4887 self
.assertEqual(1, len(args
["repartition"]))
4888 self
.assertIn("BTC", args
["repartition"])
4890 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4891 method_mock
= mock
.Mock()
4892 method_arguments
.return_value
= [
4894 ["repartition", "base_currency"]
4896 method
, args
= processor
.parse_args("action", {"repartition": { "base_currency": 1 }
}, {"base_currency": "USDT"}
)
4898 self
.assertEqual(1, len(args
["repartition"]))
4899 self
.assertIn("USDT", args
["repartition"])
4901 with mock
.patch
.object(processor
, "method_arguments") as method_arguments
:
4902 method_mock
= mock
.Mock()
4903 method_arguments
.return_value
= [
4905 ["repartition", "base_currency"]
4907 method
, args
= processor
.parse_args("action", {"repartition": { "ETH": 1 }
}, {"base_currency": "USDT"}
)
4909 self
.assertEqual(1, len(args
["repartition"]))
4910 self
.assertIn("ETH", args
["repartition"])
4913 @unittest.skipUnless("acceptance" in limits
, "Acceptance skipped")
4914 class AcceptanceTest(WebMockTestCase
):
4915 @unittest.expectedFailure
4916 def test_success_sell_only_necessary(self
):
4917 # FIXME: catch stdout
4918 self
.m
.report
.verbose_print
= False
4921 "exchange_free": D("1.0"),
4922 "exchange_used": D("0.0"),
4923 "exchange_total": D("1.0"),
4927 "exchange_free": D("4.0"),
4928 "exchange_used": D("0.0"),
4929 "exchange_total": D("4.0"),
4933 "exchange_free": D("1000.0"),
4934 "exchange_used": D("0.0"),
4935 "exchange_total": D("1000.0"),
4936 "total": D("1000.0"),
4940 "ETH": (D("0.25"), "long"),
4941 "ETC": (D("0.25"), "long"),
4942 "BTC": (D("0.4"), "long"),
4943 "BTD": (D("0.01"), "short"),
4944 "B2X": (D("0.04"), "long"),
4945 "USDT": (D("0.05"), "long"),
4948 def fetch_ticker(symbol
):
4949 if symbol
== "ETH/BTC":
4951 "symbol": "ETH/BTC",
4955 if symbol
== "ETC/BTC":
4957 "symbol": "ETC/BTC",
4961 if symbol
== "XVG/BTC":
4963 "symbol": "XVG/BTC",
4964 "bid": D("0.00003"),
4967 if symbol
== "BTD/BTC":
4969 "symbol": "BTD/BTC",
4973 if symbol
== "B2X/BTC":
4975 "symbol": "B2X/BTC",
4979 if symbol
== "USDT/BTC":
4980 raise helper
.ExchangeError
4981 if symbol
== "BTC/USDT":
4983 "symbol": "BTC/USDT",
4987 self
.fail("Shouldn't have been called with {}".format(symbol
))
4989 market
= mock
.Mock()
4990 market
.fetch_all_balances
.return_value
= fetch_balance
4991 market
.fetch_ticker
.side_effect
= fetch_ticker
4992 with mock
.patch
.object(market
.Portfolio
, "repartition", return_value
=repartition
):
4994 helper
.prepare_trades(market
)
4996 balances
= portfolio
.BalanceStore
.all
4997 self
.assertEqual(portfolio
.Amount("ETH", 1), balances
["ETH"].total
)
4998 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
4999 self
.assertEqual(portfolio
.Amount("XVG", 1000), balances
["XVG"].total
)
5002 trades
= portfolio
.TradeStore
.all
5003 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
5004 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
5005 self
.assertEqual("dispose", trades
[0].action
)
5007 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
5008 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
5009 self
.assertEqual("acquire", trades
[1].action
)
5011 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
5012 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
5013 self
.assertEqual("dispose", trades
[2].action
)
5015 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
5016 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
5017 self
.assertEqual("acquire", trades
[3].action
)
5019 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
5020 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
5021 self
.assertEqual("acquire", trades
[4].action
)
5023 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
5024 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
5025 self
.assertEqual("acquire", trades
[5].action
)
5028 portfolio
.TradeStore
.prepare_orders(only
="dispose", compute_value
=lambda x
, y
: x
["bid"] * D("1.001"))
5030 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
5031 self
.assertEqual(2, len(all_orders
))
5032 self
.assertEqual(2, 3*all_orders
[0].amount
.value
)
5033 self
.assertEqual(D("0.14014"), all_orders
[0].rate
)
5034 self
.assertEqual(1000, all_orders
[1].amount
.value
)
5035 self
.assertEqual(D("0.00003003"), all_orders
[1].rate
)
5038 def create_order(symbol
, type, action
, amount
, price
=None, account
="exchange"):
5039 self
.assertEqual("limit", type)
5040 if symbol
== "ETH/BTC":
5041 self
.assertEqual("sell", action
)
5042 self
.assertEqual(D('0.66666666'), amount
)
5043 self
.assertEqual(D("0.14014"), price
)
5044 elif symbol
== "XVG/BTC":
5045 self
.assertEqual("sell", action
)
5046 self
.assertEqual(1000, amount
)
5047 self
.assertEqual(D("0.00003003"), price
)
5049 self
.fail("I shouldn't have been called")
5054 market
.create_order
.side_effect
= create_order
5055 market
.order_precision
.return_value
= 8
5058 portfolio
.TradeStore
.run_orders()
5060 self
.assertEqual("open", all_orders
[0].status
)
5061 self
.assertEqual("open", all_orders
[1].status
)
5063 market
.fetch_order
.return_value
= { "status": "closed", "datetime": "2018-01-20 13:40:00" }
5064 market
.privatePostReturnOrderTrades
.return_value
= [
5066 "tradeID": 42, "type": "buy", "fee": "0.0015",
5067 "date": "2017-12-30 12:00:12", "rate": "0.1",
5068 "amount": "10", "total": "1"
5071 with mock
.patch
.object(market
.time
, "sleep") as sleep
:
5073 helper
.follow_orders(verbose
=False)
5075 sleep
.assert_called_with(30)
5077 for order
in all_orders
:
5078 self
.assertEqual("closed", order
.status
)
5082 "exchange_free": D("1.0") / 3,
5083 "exchange_used": D("0.0"),
5084 "exchange_total": D("1.0") / 3,
5086 "total": D("1.0") / 3,
5089 "exchange_free": D("0.134"),
5090 "exchange_used": D("0.0"),
5091 "exchange_total": D("0.134"),
5093 "total": D("0.134"),
5096 "exchange_free": D("4.0"),
5097 "exchange_used": D("0.0"),
5098 "exchange_total": D("4.0"),
5103 "exchange_free": D("0.0"),
5104 "exchange_used": D("0.0"),
5105 "exchange_total": D("0.0"),
5110 market
.fetch_all_balances
.return_value
= fetch_balance
5112 with mock
.patch
.object(market
.Portfolio
, "repartition", return_value
=repartition
):
5114 helper
.prepare_trades(market
, only
="acquire", compute_value
="average")
5116 balances
= portfolio
.BalanceStore
.all
5117 self
.assertEqual(portfolio
.Amount("ETH", 1 / D("3")), balances
["ETH"].total
)
5118 self
.assertEqual(portfolio
.Amount("ETC", 4), balances
["ETC"].total
)
5119 self
.assertEqual(portfolio
.Amount("BTC", D("0.134")), balances
["BTC"].total
)
5120 self
.assertEqual(portfolio
.Amount("XVG", 0), balances
["XVG"].total
)
5123 trades
= portfolio
.TradeStore
.all
5124 self
.assertEqual(portfolio
.Amount("BTC", D("0.15")), trades
[0].value_from
)
5125 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[0].value_to
)
5126 self
.assertEqual("dispose", trades
[0].action
)
5128 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[1].value_from
)
5129 self
.assertEqual(portfolio
.Amount("BTC", D("0.05")), trades
[1].value_to
)
5130 self
.assertEqual("acquire", trades
[1].action
)
5132 self
.assertNotIn("BTC", trades
)
5134 self
.assertEqual(portfolio
.Amount("BTC", D("0.04")), trades
[2].value_from
)
5135 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[2].value_to
)
5136 self
.assertEqual("dispose", trades
[2].action
)
5138 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[3].value_from
)
5139 self
.assertEqual(portfolio
.Amount("BTC", D("-0.002")), trades
[3].value_to
)
5140 self
.assertEqual("acquire", trades
[3].action
)
5142 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[4].value_from
)
5143 self
.assertEqual(portfolio
.Amount("BTC", D("0.008")), trades
[4].value_to
)
5144 self
.assertEqual("acquire", trades
[4].action
)
5146 self
.assertEqual(portfolio
.Amount("BTC", D("0.00")), trades
[5].value_from
)
5147 self
.assertEqual(portfolio
.Amount("BTC", D("0.01")), trades
[5].value_to
)
5148 self
.assertEqual("acquire", trades
[5].action
)
5151 portfolio
.TradeStore
.prepare_orders(only
="acquire", compute_value
=lambda x
, y
: x
["ask"])
5153 all_orders
= portfolio
.TradeStore
.all_orders(state
="pending")
5154 self
.assertEqual(4, len(all_orders
))
5155 self
.assertEqual(portfolio
.Amount("ETC", D("12.83333333")), round(all_orders
[0].amount
))
5156 self
.assertEqual(D("0.003"), all_orders
[0].rate
)
5157 self
.assertEqual("buy", all_orders
[0].action
)
5158 self
.assertEqual("long", all_orders
[0].trade_type
)
5160 self
.assertEqual(portfolio
.Amount("BTD", D("1.61666666")), round(all_orders
[1].amount
))
5161 self
.assertEqual(D("0.0012"), all_orders
[1].rate
)
5162 self
.assertEqual("sell", all_orders
[1].action
)
5163 self
.assertEqual("short", all_orders
[1].trade_type
)
5165 diff
= portfolio
.Amount("B2X", D("19.4")/3) - all_orders
[2].amount
5166 self
.assertAlmostEqual(0, diff
.value
)
5167 self
.assertEqual(D("0.0012"), all_orders
[2].rate
)
5168 self
.assertEqual("buy", all_orders
[2].action
)
5169 self
.assertEqual("long", all_orders
[2].trade_type
)
5171 self
.assertEqual(portfolio
.Amount("BTC", D("0.0097")), all_orders
[3].amount
)
5172 self
.assertEqual(D("16000"), all_orders
[3].rate
)
5173 self
.assertEqual("sell", all_orders
[3].action
)
5174 self
.assertEqual("long", all_orders
[3].trade_type
)
5178 # Move balances to margin
5182 # portfolio.TradeStore.run_orders()
5184 with mock
.patch
.object(market
.time
, "sleep") as sleep
:
5186 helper
.follow_orders(verbose
=False)
5188 sleep
.assert_called_with(30)
5190 if __name__
== '__main__':