aboutsummaryrefslogblamecommitdiff
path: root/test.py
blob: fde3a0684808c9afc2bf2dd05fa2ddb1b8a9aa96 (plain) (tree)
1
2
3
4
5
6
7
8
9

                
                                


                                    
                          

                                                 

                                                





                                                                 
                                                                               
                                           


                                                                         
                                                                               
                                        
                                        



                                                              
                                                              



                                                                   









                                                    

                                                 



                                                             
                                                






                                                    
                                                





                                            

                                                 
 
                                                             

                                                             
                                                





                                                    


                                            

                                                              






                                            

                                                              



                                            

                                                             



                                            

                                                             

















































                                                                                                                           



















































































                                                                                                                                                                 
























                                        
                                                                                














                                                                                                  
                                                     

                                            
                                                                        



                                                         


                                    



                                                              

                                                         

                                                                            

                                                         

                                                                                         
                                                         



                                                 
                                                                        
























                                                                                  
                                                                                    
                                                            

                                                        

                                                                         
                                                     






                                                                           

                                            



                                             


                                         

                        


                                         







                                                     


                                                              







                                                                                                      
























































































































                                                                                 

                          
import portfolio
import unittest
from decimal import Decimal as D
from unittest import mock

class AmountTest(unittest.TestCase):
    def test_values(self):
        amount = portfolio.Amount("BTC", "0.65")
        self.assertEqual(D("0.65"), amount.value)
        self.assertEqual("BTC", amount.currency)

    def test_in_currency(self):
        amount = portfolio.Amount("ETC", 10)

        self.assertEqual(amount, amount.in_currency("ETC", None))

        ticker_mock = unittest.mock.Mock()
        with mock.patch.object(portfolio.Trade, 'get_ticker', new=ticker_mock):
            ticker_mock.return_value = None

            self.assertRaises(Exception, amount.in_currency, "ETH", None)

        with mock.patch.object(portfolio.Trade, 'get_ticker', new=ticker_mock):
            ticker_mock.return_value = {
                    "average": D("0.3"),
                    "foo": "bar",
                    }
            converted_amount = amount.in_currency("ETH", None)

            self.assertEqual(D("3.0"), converted_amount.value)
            self.assertEqual("ETH", converted_amount.currency)
            self.assertEqual(amount, converted_amount.linked_to)
            self.assertEqual("bar", converted_amount.ticker["foo"])

    def test__abs(self):
        amount = portfolio.Amount("SC", -120)
        self.assertEqual(120, abs(amount).value)
        self.assertEqual("SC", abs(amount).currency)

        amount = portfolio.Amount("SC", 10)
        self.assertEqual(10, abs(amount).value)
        self.assertEqual("SC", abs(amount).currency)

    def test__add(self):
        amount1 = portfolio.Amount("XVG", "12.9")
        amount2 = portfolio.Amount("XVG", "13.1")

        self.assertEqual(26, (amount1 + amount2).value)
        self.assertEqual("XVG", (amount1 + amount2).currency)

        amount3 = portfolio.Amount("ETH", "1.6")
        with self.assertRaises(Exception):
            amount1 + amount3

        amount4 = portfolio.Amount("ETH", 0.0)
        self.assertEqual(amount1, amount1 + amount4)

    def test__radd(self):
        amount = portfolio.Amount("XVG", "12.9")

        self.assertEqual(amount, 0 + amount)
        with self.assertRaises(Exception):
            4 + amount

    def test__sub(self):
        amount1 = portfolio.Amount("XVG", "13.3")
        amount2 = portfolio.Amount("XVG", "13.1")

        self.assertEqual(D("0.2"), (amount1 - amount2).value)
        self.assertEqual("XVG", (amount1 - amount2).currency)

        amount3 = portfolio.Amount("ETH", "1.6")
        with self.assertRaises(Exception):
            amount1 - amount3

        amount4 = portfolio.Amount("ETH", 0.0)
        self.assertEqual(amount1, amount1 - amount4)

    def test__mul(self):
        amount = portfolio.Amount("XEM", 11)

        self.assertEqual(D("38.5"), (amount * D("3.5")).value)
        self.assertEqual(D("33"), (amount * 3).value)

        with self.assertRaises(Exception):
            amount * amount

    def test__rmul(self):
        amount = portfolio.Amount("XEM", 11)

        self.assertEqual(D("38.5"), (D("3.5") * amount).value)
        self.assertEqual(D("33"), (3 * amount).value)

    def test__floordiv(self):
        amount = portfolio.Amount("XEM", 11)

        self.assertEqual(D("5.5"), (amount / 2).value)
        self.assertEqual(D("4.4"), (amount / D("2.5")).value)

    def test__div(self):
        amount = portfolio.Amount("XEM", 11)

        self.assertEqual(D("5.5"), (amount / 2).value)
        self.assertEqual(D("4.4"), (amount / D("2.5")).value)

    def test__lt(self):
        amount1 = portfolio.Amount("BTD", 11.3)
        amount2 = portfolio.Amount("BTD", 13.1)

        self.assertTrue(amount1 < amount2)
        self.assertFalse(amount2 < amount1)
        self.assertFalse(amount1 < amount1)

        amount3 = portfolio.Amount("BTC", 1.6)
        with self.assertRaises(Exception):
            amount1 < amount3

    def test__eq(self):
        amount1 = portfolio.Amount("BTD", 11.3)
        amount2 = portfolio.Amount("BTD", 13.1)
        amount3 = portfolio.Amount("BTD", 11.3)

        self.assertFalse(amount1 == amount2)
        self.assertFalse(amount2 == amount1)
        self.assertTrue(amount1 == amount3)
        self.assertFalse(amount2 == 0)

        amount4 = portfolio.Amount("BTC", 1.6)
        with self.assertRaises(Exception):
            amount1 == amount4

        amount5 = portfolio.Amount("BTD", 0)
        self.assertTrue(amount5 == 0)

    def test__str(self):
        amount1 = portfolio.Amount("BTX", 32)
        self.assertEqual("32.00000000 BTX", str(amount1))

        amount2 = portfolio.Amount("USDT", 12000)
        amount1.linked_to = amount2
        self.assertEqual("32.00000000 BTX [12000.00000000 USDT]", str(amount1))

    def test__repr(self):
        amount1 = portfolio.Amount("BTX", 32)
        self.assertEqual("Amount(32.00000000 BTX)", repr(amount1))

        amount2 = portfolio.Amount("USDT", 12000)
        amount1.linked_to = amount2
        self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT))", repr(amount1))

        amount3 = portfolio.Amount("BTC", 0.1)
        amount2.linked_to = amount3
        self.assertEqual("Amount(32.00000000 BTX -> Amount(12000.00000000 USDT -> Amount(0.10000000 BTC)))", repr(amount1))

class PortfolioTest(unittest.TestCase):
    import urllib3
    def fill_data(self):
        if self.json_response is not None:
            portfolio.Portfolio.data = self.json_response

    def setUp(self):
        super(PortfolioTest, self).setUp()

        with open("test_portfolio.json") as example:
            import json
            self.json_response = json.load(example)

        self.patcher = mock.patch.multiple(portfolio.Portfolio, data=None, liquidities={})
        self.patcher.start()

    @mock.patch.object(urllib3, "disable_warnings")
    @mock.patch.object(urllib3.poolmanager.PoolManager, "request")
    @mock.patch.object(portfolio.Portfolio, "URL", new="foo://bar")
    def test_get_cryptoportfolio(self, request, disable_warnings):
        request.side_effect = [
                type('', (), { "data": '{ "foo": "bar" }' }),
                type('', (), { "data": 'System Error' }),
                Exception("Connection error"),
                ]

        portfolio.Portfolio.get_cryptoportfolio()
        self.assertIn("foo", portfolio.Portfolio.data)
        self.assertEqual("bar", portfolio.Portfolio.data["foo"])
        request.assert_called_with("GET", "foo://bar")

        request.reset_mock()
        portfolio.Portfolio.get_cryptoportfolio()
        self.assertIsNone(portfolio.Portfolio.data)
        request.assert_called_with("GET", "foo://bar")

        request.reset_mock()
        portfolio.Portfolio.data = "foo"
        portfolio.Portfolio.get_cryptoportfolio()
        request.assert_called_with("GET", "foo://bar")
        self.assertEqual("foo", portfolio.Portfolio.data)
        disable_warnings.assert_called_with()

    @mock.patch.object(portfolio.Portfolio, "get_cryptoportfolio")
    def test_parse_cryptoportfolio(self, mock_get):
        mock_get.side_effect = self.fill_data

        portfolio.Portfolio.parse_cryptoportfolio()

        self.assertListEqual(
                ["medium", "high"],
                list(portfolio.Portfolio.liquidities.keys()))

        liquidities = portfolio.Portfolio.liquidities
        self.assertEqual(10, len(liquidities["medium"].keys()))
        self.assertEqual(10, len(liquidities["high"].keys()))

        expected = {'BTC': 2857, 'DGB': 1015, 'DOGE': 1805, 'SC': 623, 'ZEC': 3701}
        self.assertDictEqual(expected, liquidities["high"]['2018-01-08'])

        expected = {'ETC': 1000, 'FCT': 1000, 'GAS': 1000, 'NAV': 1000, 'OMG': 1000, 'OMNI': 1000, 'PPC': 1000, 'RIC': 1000, 'VIA': 1000, 'XCP': 1000}
        self.assertDictEqual(expected, liquidities["medium"]['2018-01-08'])

        # It doesn't refetch the data when available
        portfolio.Portfolio.parse_cryptoportfolio()
        mock_get.assert_called_once_with()

        portfolio.Portfolio.data["portfolio_1"]["holding"]["direction"][3] = "short"
        self.assertRaises(AssertionError, portfolio.Portfolio.parse_cryptoportfolio)

    @mock.patch.object(portfolio.Portfolio, "get_cryptoportfolio")
    def test_repartition_pertenthousand(self, mock_get):
        mock_get.side_effect = self.fill_data

        expected_medium = {'USDT': 1000, 'ETC': 1000, 'FCT': 1000, 'OMG': 1000, 'STEEM': 1000, 'STRAT': 1000, 'XEM': 1000, 'XMR': 1000, 'XVC': 1000, 'ZRX': 1000}
        expected_high = {'USDT': 1226, 'BTC': 1429, 'ETC': 1127, 'ETH': 1569, 'FCT': 3341, 'GAS': 1308}

        self.assertEqual(expected_medium, portfolio.Portfolio.repartition_pertenthousand())
        self.assertEqual(expected_medium, portfolio.Portfolio.repartition_pertenthousand(liquidity="medium"))
        self.assertEqual(expected_high, portfolio.Portfolio.repartition_pertenthousand(liquidity="high"))

    def tearDown(self):
        self.patcher.stop()

class BalanceTest(unittest.TestCase):
    def setUp(self):
        super(BalanceTest, self).setUp()

        self.fetch_balance = {
                "free": "foo",
                "info": "bar",
                "used": "baz",
                "total": "bazz",
                "USDT": {
                    "free": 6.0,
                    "used": 1.2,
                    "total": 7.2
                    },
                "XVG": {
                    "free": 16,
                    "used": 0.0,
                    "total": 16
                    },
                "XMR": {
                    "free": 0.0,
                    "used": 0.0,
                    "total": 0.0
                    },
                }
        self.patcher = mock.patch.multiple(portfolio.Balance, known_balances={})
        self.patcher.start()

    def test_values(self):
        balance = portfolio.Balance("BTC", 0.65, 0.35, 0.30)
        self.assertEqual(0.65, balance.total.value)
        self.assertEqual(0.35, balance.free.value)
        self.assertEqual(0.30, balance.used.value)
        self.assertEqual("BTC", balance.currency)

        balance = portfolio.Balance.from_hash("BTC", { "total": 0.65, "free": 0.35, "used": 0.30})
        self.assertEqual(0.65, balance.total.value)
        self.assertEqual(0.35, balance.free.value)
        self.assertEqual(0.30, balance.used.value)
        self.assertEqual("BTC", balance.currency)

    @mock.patch.object(portfolio.Trade, "get_ticker")
    def test_in_currency(self, get_ticker):
        portfolio.Balance.known_balances = {
                "BTC": portfolio.Balance("BTC", "0.65", "0.35", "0.30"),
                "ETH": portfolio.Balance("ETH", 3, 3, 0),
                }
        market = mock.Mock()
        get_ticker.return_value = {
                "bid": D("0.09"),
                "ask": D("0.11"),
                "average": D("0.1"),
                }

        amounts = portfolio.Balance.in_currency("BTC", market)
        self.assertEqual("BTC", amounts["ETH"].currency)
        self.assertEqual(D("0.65"), amounts["BTC"].value)
        self.assertEqual(D("0.30"), amounts["ETH"].value)

        amounts = portfolio.Balance.in_currency("BTC", market, action="bid")
        self.assertEqual(D("0.65"), amounts["BTC"].value)
        self.assertEqual(D("0.27"), amounts["ETH"].value)

        amounts = portfolio.Balance.in_currency("BTC", market, action="bid", type="used")
        self.assertEqual(D("0.30"), amounts["BTC"].value)
        self.assertEqual(0, amounts["ETH"].value)

    def test_currencies(self):
        portfolio.Balance.known_balances = {
                "BTC": portfolio.Balance("BTC", "0.65", "0.35", "0.30"),
                "ETH": portfolio.Balance("ETH", 3, 3, 0),
                }
        self.assertListEqual(["BTC", "ETH"], list(portfolio.Balance.currencies()))

    @mock.patch.object(portfolio.market, "fetch_balance")
    def test_fetch_balances(self, fetch_balance):
        fetch_balance.return_value = self.fetch_balance

        portfolio.Balance.fetch_balances(portfolio.market)
        self.assertNotIn("XMR", portfolio.Balance.currencies())
        self.assertEqual(["USDT", "XVG"], list(portfolio.Balance.currencies()))

    @mock.patch.object(portfolio.Portfolio, "repartition_pertenthousand")
    @mock.patch.object(portfolio.market, "fetch_balance")
    def test_dispatch_assets(self, fetch_balance, repartition):
        fetch_balance.return_value = self.fetch_balance
        portfolio.Balance.fetch_balances(portfolio.market)

        self.assertNotIn("XEM", portfolio.Balance.currencies())

        repartition.return_value = {
                "XEM": 7500,
                "BTC": 2600,
                }

        amounts = portfolio.Balance.dispatch_assets(portfolio.Amount("BTC", "10.1"))
        self.assertIn("XEM", portfolio.Balance.currencies())
        self.assertEqual(D("2.6"), amounts["BTC"].value)
        self.assertEqual(D("7.5"), amounts["XEM"].value)

    @mock.patch.object(portfolio.Portfolio, "repartition_pertenthousand")
    @mock.patch.object(portfolio.Trade, "get_ticker")
    @mock.patch.object(portfolio.Trade, "compute_trades")
    def test_prepare_trades(self, compute_trades, get_ticker, repartition):
        repartition.return_value = {
                "XEM": 7500,
                "BTC": 2500,
                }
        get_ticker.side_effect = [
                { "average": D("0.0001") },
                { "average": D("0.000001") }
                ]
        market = mock.Mock()
        market.fetch_balance.return_value = {
                "USDT": {
                    "free": D("10000.0"),
                    "used": D("0.0"),
                    "total": D("10000.0")
                    },
                "XVG": {
                    "free": D("10000.0"),
                    "used": D("0.0"),
                    "total": D("10000.0")
                    },
                }
        portfolio.Balance.prepare_trades(market)
        compute_trades.assert_called()

        call = compute_trades.call_args
        self.assertEqual(market, call[1]["market"])
        self.assertEqual(1, call[0][0]["USDT"].value)
        self.assertEqual(D("0.01"), call[0][0]["XVG"].value)
        self.assertEqual(D("0.2525"), call[0][1]["BTC"].value)
        self.assertEqual(D("0.7575"), call[0][1]["XEM"].value)

    def test__repr(self):
        balance = portfolio.Balance("BTX", 3, 1, 2)
        self.assertEqual("Balance(BTX [1.00000000 BTX/2.00000000 BTX/3.00000000 BTX])", repr(balance))

    def tearDown(self):
        self.patcher.stop()

class TradeTest(unittest.TestCase):
    import time

    def setUp(self):
        super(TradeTest, self).setUp()

        self.patcher = mock.patch.multiple(portfolio.Trade,
                ticker_cache={},
                ticker_cache_timestamp=self.time.time(),
                fees_cache={},
                trades={})
        self.patcher.start()

    def test_get_ticker(self):
        market = mock.Mock()
        market.fetch_ticker.side_effect = [
                { "bid": 1, "ask": 3 },
                portfolio.ccxt.ExchangeError("foo"),
                { "bid": 10, "ask": 40 },
                portfolio.ccxt.ExchangeError("foo"),
                portfolio.ccxt.ExchangeError("foo"),
                ]

        ticker = portfolio.Trade.get_ticker("ETH", "ETC", market)
        market.fetch_ticker.assert_called_with("ETH/ETC")
        self.assertEqual(1, ticker["bid"])
        self.assertEqual(3, ticker["ask"])
        self.assertEqual(2, ticker["average"])
        self.assertFalse(ticker["inverted"])

        ticker = portfolio.Trade.get_ticker("ETH", "XVG", market)
        self.assertEqual(0.0625, ticker["average"])
        self.assertTrue(ticker["inverted"])
        self.assertIn("original", ticker)
        self.assertEqual(10, ticker["original"]["bid"])

        ticker = portfolio.Trade.get_ticker("XVG", "XMR", market)
        self.assertIsNone(ticker)

        market.fetch_ticker.assert_has_calls([
            mock.call("ETH/ETC"),
            mock.call("ETH/XVG"),
            mock.call("XVG/ETH"),
            mock.call("XVG/XMR"),
            mock.call("XMR/XVG"),
            ])

        market2 = mock.Mock()
        market2.fetch_ticker.side_effect = [
                { "bid": 1, "ask": 3 },
                { "bid": 1.2, "ask": 3.5 },
                ]
        ticker1 = portfolio.Trade.get_ticker("ETH", "ETC", market2)
        ticker2 = portfolio.Trade.get_ticker("ETH", "ETC", market2)
        ticker3 = portfolio.Trade.get_ticker("ETC", "ETH", market2)
        market2.fetch_ticker.assert_called_once_with("ETH/ETC")
        self.assertEqual(1, ticker1["bid"])
        self.assertDictEqual(ticker1, ticker2)
        self.assertDictEqual(ticker1, ticker3["original"])

        ticker4 = portfolio.Trade.get_ticker("ETH", "ETC", market2, refresh=True)
        ticker5 = portfolio.Trade.get_ticker("ETH", "ETC", market2)
        self.assertEqual(1.2, ticker4["bid"])
        self.assertDictEqual(ticker4, ticker5)

        market3 = mock.Mock()
        market3.fetch_ticker.side_effect = [
                { "bid": 1, "ask": 3 },
                { "bid": 1.2, "ask": 3.5 },
                ]
        ticker6 = portfolio.Trade.get_ticker("ETH", "ETC", market3)
        portfolio.Trade.ticker_cache_timestamp -= 4
        ticker7 = portfolio.Trade.get_ticker("ETH", "ETC", market3)
        portfolio.Trade.ticker_cache_timestamp -= 2
        ticker8 = portfolio.Trade.get_ticker("ETH", "ETC", market3)
        self.assertDictEqual(ticker6, ticker7)
        self.assertEqual(1.2, ticker8["bid"])

    @unittest.skip("TODO")
    def test_values_assertion(self):
        pass

    @unittest.skip("TODO")
    def test_fetch_fees(self):
        pass

    @unittest.skip("TODO")
    def test_compute_trades(self):
        pass

    @unittest.skip("TODO")
    def test_action(self):
        pass

    @unittest.skip("TODO")
    def test_action(self):
        pass

    @unittest.skip("TODO")
    def test_order_action(self):
        pass

    @unittest.skip("TODO")
    def test_prepare_order(self):
        pass

    @unittest.skip("TODO")
    def test_all_orders(self):
        pass

    @unittest.skip("TODO")
    def test_follow_orders(self):
        pass

    @unittest.skip("TODO")
    def test__repr(self):
        pass

    def tearDown(self):
        self.patcher.stop()

if __name__ == '__main__':
    unittest.main()