Ejemplo n.º 1
0
    def handle(self, *args, **options):
        email = options.get('email')
        exchange = options.get('exchange')
        if not email:
            raise CommandError(
                "Please provide --account_email. See details --help"
            )
        accounts = Account.objects.filter(
            user__email=email,
            exchange__name=exchange
        )
        if not accounts.exists():
            raise CommandError(
                f"Could not find account for {exchange} with {email} email"
            )
        for account in accounts:
            if not all([account.api_key, account.api_secret]):
                raise CommandError(
                    "Wrong account, check that API_KEY and API_SECRET were provided for this account, and they correct."
                )

            bittrex = Bittrex(
                account.api_key, account.api_secret,
                # api_version=API_V2_0
                api_version=API_V1_1
            )
            response = bittrex.get_order_history()
            orders = response.get('result')
            if orders is None:
                self.stdout.write(f'There no new orders: API response - {response}')
            self.save_orders(account, orders)
            self.stdout.write('Done')
Ejemplo n.º 2
0
class TestBittrexAccountAPI(unittest.TestCase):
    def setUp(self):
        self.bittrex = Bittrex()

    def test_get_balances(self):
        actual = self.bittrex.get_balances()
        test_basic_response(self, actual, 'get_balances')

    def test_get_balance(self):
        self.assertRaises(TypeError, self.bittrex.get_balance)
        actual = self.bittrex.get_balance('BTC')
        test_basic_response(self, actual, 'get_balance')
        invalid_actual = self.bittrex.get_balance('Invalid currency')
        test_failed_response(self, invalid_actual, 'get_balance')

    def test_get_deposit_address(self):
        self.assertRaises(TypeError, self.bittrex.get_deposit_address)
        actual = self.bittrex.get_deposit_address('BTC')
        test_basic_response(self, actual, 'get_deposit_address')
        invalid_actual = self.bittrex.get_deposit_address('Invalid currency')
        test_failed_response(self, invalid_actual, 'get_deposit_address')

    def test_withdraw(self):
        self.assertRaises(TypeError, self.bittrex.withdraw)

    def test_get_order(self):
        self.assertRaises(TypeError, self.bittrex.get_order)
        actual = self.bittrex.get_order('test')
        test_response_structure(self, actual, 'get_order')

    def test_get_order_history(self):
        actual = self.bittrex.get_order_history()
        test_basic_response(self, actual, 'get_order_history')
        actual = self.bittrex.get_order_history('BTC-LTC')
        test_basic_response(self, actual, 'get_order_history')

    def test_get_withdrawal_historyself(self):
        actual = self.bittrex.get_withdrawal_history()
        test_basic_response(self, actual, 'get_withdrawal_history')
        actual = self.bittrex.get_withdrawal_history('BTC')
        test_basic_response(self, actual, 'get_withdrawal_history')

    def test_get_deposit_history(self):
        actual = self.bittrex.get_deposit_history()
        test_basic_response(self, actual, 'get_deposit_history')
        actual = self.bittrex.get_deposit_history('BTC')
        test_basic_response(self, actual, 'get_deposit_history')
Ejemplo n.º 3
0
class TestBittrexV20AccountAPI(unittest.TestCase):
    """
    Integration tests for the Bittrex Account API.
      * These will fail in the absence of an internet connection or if bittrex API goes down.
      * They require a valid API key and secret issued by Bittrex.
      * They also require the presence of a JSON file called secrets.json.
      It is structured as such:
    {
      "key": "12341253456345",
      "secret": "3345745634234534"
    }
    """
    def setUp(self):
        with open("secrets.json") as secrets_file:
            self.secrets = json.load(secrets_file)
            secrets_file.close()
        self.bittrex = Bittrex(self.secrets['key'],
                               self.secrets['secret'],
                               api_version=API_V2_0)

    def test_handles_invalid_key_or_secret(self):
        self.bittrex = Bittrex('invalidkey',
                               self.secrets['secret'],
                               api_version=API_V2_0)
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'Invalid key, valid secret')

        self.bittrex = Bittrex(None,
                               self.secrets['secret'],
                               api_version=API_V2_0)
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'None key, valid secret')

        self.bittrex = Bittrex(self.secrets['key'],
                               'invalidsecret',
                               api_version=API_V2_0)
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'valid key, invalid secret')

        self.bittrex = Bittrex(self.secrets['key'], None, api_version=API_V2_0)
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'valid key, None secret')

        self.bittrex = Bittrex('invalidkey',
                               'invalidsecret',
                               api_version=API_V2_0)
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'invalid key, invalid secret')

    def test_get_openorders(self):
        actual = self.bittrex.get_open_orders('BTC-LTC')
        test_basic_response(self, actual, "get_openorders")
        self.assertTrue(isinstance(actual['result'], list),
                        "result is not a list")

    def test_get_balances(self):
        actual = self.bittrex.get_balances()
        test_basic_response(self, actual, "get_balances")
        self.assertTrue(isinstance(actual['result'], list),
                        "result is not a list")

    @unittest.skip(
        "the return result is an empty dict.  API bug?  the 2.0 get_balances works as expected"
    )
    def test_get_balance(self):
        actual = self.bittrex.get_balance('BTC')
        test_basic_response(self, actual, "get_balance")
        self.assertTrue(isinstance(actual['result'], dict),
                        "result is not a dict")
        self.assertEqual(
            actual['result']['Currency'], "BTC",
            "requested currency {0:s} does not match returned currency {1:s}".
            format("BTC", actual['result']['Currency']))

    @unittest.skip("my testing account is acting funny this should work")
    def test_get_depositaddress(self):
        actual = self.bittrex.get_deposit_address('BTC')
        test_basic_response(self, actual, "get_deposit_address")

    def test_get_order_history_all_markets(self):
        actual = self.bittrex.get_order_history()
        test_basic_response(self, actual, "get_order_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_order_history_one_market(self):
        actual = self.bittrex.get_order_history(market='BTC-LTC')
        test_basic_response(self, actual, "get_order_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_withdrawlhistory_all_currencies(self):
        actual = self.bittrex.get_withdrawal_history()
        test_basic_response(self, actual, "get_withdrawal_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_withdrawlhistory_one_currency(self):
        actual = self.bittrex.get_withdrawal_history('BTC')
        test_basic_response(self, actual, "get_withdrawal_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_deposithistory_all_currencies(self):
        actual = self.bittrex.get_deposit_history()
        test_basic_response(self, actual, "get_deposit_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_deposithistory_one_currency(self):
        actual = self.bittrex.get_deposit_history('BTC')
        test_basic_response(self, actual, "get_deposit_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_pending_withdrawals_all_currencies(self):
        actual = self.bittrex.get_pending_withdrawals()
        test_basic_response(self, actual, "get_pending_withdrawals")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_pending_withdrawals_one_currency(self):
        actual = self.bittrex.get_pending_withdrawals('BTC')
        test_basic_response(self, actual, "get_pending_withdrawals")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_pending_deposits_all_currencies(self):
        actual = self.bittrex.get_pending_deposits()
        test_basic_response(self, actual, "get_pending_deposits")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_pending_deposits_one_currency(self):
        actual = self.bittrex.get_pending_deposits('BTC')
        test_basic_response(self, actual, "get_pending_deposits")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_generate_deposit_address(self):
        actual = self.bittrex.generate_deposit_address(currency='BTC')
        test_basic_response(self, actual, "generate_deposit_address")
        self.assertIsInstance(actual['result'], list, "result is not a list")
Ejemplo n.º 4
0
class TestBittrexV11AccountAPI(unittest.TestCase):
    """
    Integration tests for the Bittrex Account API.
      * These will fail in the absence of an internet connection or if bittrex API goes down.
      * They require a valid API key and secret issued by Bittrex.
      * They also require the presence of a JSON file called secrets.json.
      It is structured as such:
    {
      "key": "12341253456345",
      "secret": "3345745634234534"
    }
    """
    def setUp(self):
        with open("secrets.json") as secrets_file:
            self.secrets = json.load(secrets_file)
            secrets_file.close()
        self.bittrex = Bittrex(self.secrets['key'], self.secrets['secret'])

    def test_handles_invalid_key_or_secret(self):
        self.bittrex = Bittrex('invalidkey', self.secrets['secret'])
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'Invalid key, valid secret')

        self.bittrex = Bittrex(None, self.secrets['secret'])
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'None key, valid secret')

        self.bittrex = Bittrex(self.secrets['key'], 'invalidsecret')
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'valid key, invalid secret')

        self.bittrex = Bittrex(self.secrets['key'], None)
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'valid key, None secret')

        self.bittrex = Bittrex('invalidkey', 'invalidsecret')
        actual = self.bittrex.get_balance('BTC')
        test_auth_basic_failures(self, actual, 'invalid key, invalid secret')

    def test_get_openorders(self):
        actual = self.bittrex.get_open_orders('BTC-LTC')
        test_basic_response(self, actual, "get_openorders")
        self.assertTrue(isinstance(actual['result'], list),
                        "result is not a list")

    def test_get_balances(self):
        actual = self.bittrex.get_balances()
        test_basic_response(self, actual, "get_balances")
        self.assertTrue(isinstance(actual['result'], list),
                        "result is not a list")

    def test_get_balance(self):
        actual = self.bittrex.get_balance('BTC')
        test_basic_response(self, actual, "get_balance")
        self.assertTrue(isinstance(actual['result'], dict),
                        "result is not a dict")
        self.assertEqual(
            actual['result']['Currency'], "BTC",
            "requested currency {0:s} does not match returned currency {1:s}".
            format("BTC", actual['result']['Currency']))

    def test_get_depositaddress(self):
        actual = self.bittrex.get_deposit_address('BTC')
        if not actual['success']:
            self.assertTrue(actual['message'], 'ADDRESS_GENERATING')
        else:
            test_basic_response(self, actual, "get_deposit_address")

    def test_get_order_history_all_markets(self):
        actual = self.bittrex.get_order_history()
        test_basic_response(self, actual, "get_order_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_order_history_one_market(self):
        actual = self.bittrex.get_order_history(market='BTC-LTC')
        test_basic_response(self, actual, "get_order_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_withdrawlhistory_all_currencies(self):
        actual = self.bittrex.get_withdrawal_history()
        test_basic_response(self, actual, "get_withdrawal_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_withdrawlhistory_one_currency(self):
        actual = self.bittrex.get_withdrawal_history('BTC')
        test_basic_response(self, actual, "get_withdrawal_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_deposithistory_all_currencies(self):
        actual = self.bittrex.get_deposit_history()
        test_basic_response(self, actual, "get_deposit_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_deposithistory_one_currency(self):
        actual = self.bittrex.get_deposit_history('BTC')
        test_basic_response(self, actual, "get_deposit_history")
        self.assertIsInstance(actual['result'], list, "result is not a list")

    def test_get_pending_withdrawals(self):
        self.assertRaisesRegexp(Exception, 'method call not available',
                                self.bittrex.get_pending_withdrawals)

    def test_get_pending_deposits(self):
        self.assertRaisesRegexp(Exception, 'method call not available',
                                self.bittrex.get_pending_deposits)

    def test_generate_deposit_address(self):
        self.assertRaisesRegexp(Exception,
                                'method call not available',
                                self.bittrex.generate_deposit_address,
                                currency='BTC')
Ejemplo n.º 5
0
class CryptoArb(object):
    """
    Integration tests for the Bittrex Account API.
      * These will fail in the absence of an internet connection or if bittrex API goes down.
      * They require a valid API key and secret issued by Bittrex.
      * They also require the presence of a JSON file called secrets.json.
      It is structured as such:
    {
      "key": "12341253456345",
      "secret": "3345745634234534"
    }
    """
    def setUp(self):
        with open("secrets.json") as secrets_file:
            self.secrets = json.load(secrets_file)
            secrets_file.close()
        self.bittrex = Bittrex(self.secrets['key'], self.secrets['secret'])

    def test(self):

        desiredResult = .95

        ## ETHEREUM

        btcResult = 0
        LoopNumber = 1

        while btcResult < desiredResult:

            markets = self.bittrex.get_market_summaries()

            marketCount = len(markets["result"])

            print("Start - " + str(LoopNumber))
            btcCount = 0
            ethCount = 0

            ### ~~ Filling the BTC-ALT Matrix ~~ ###

            # Counting the number of BTC Currency Pairs
            btcLoopCount = 0
            while btcLoopCount < marketCount:
                if "BTC-" in markets["result"][btcLoopCount]["MarketName"]:
                    btcCount = btcCount + 1
                btcLoopCount = btcLoopCount + 1

            # Creating the BTC pair-exchange matrix
            btcCol, btcRow = 2, btcCount
            BTCMatrix = [[0 for x in range(btcCol)] for y in range(btcRow)]

            # Filling the BTC Matrix
            btcLoopCount = 0
            btcMatrixRowCount = 0

            while btcLoopCount < marketCount:
                if "BTC-" in markets["result"][btcLoopCount]["MarketName"]:

                    BTCMatrix[btcMatrixRowCount][0] = markets["result"][
                        btcLoopCount]["MarketName"]
                    BTCMatrix[btcMatrixRowCount][1] = markets["result"][
                        btcLoopCount]["Ask"]

                    btcMatrixRowCount = btcMatrixRowCount + 1

                btcLoopCount = btcLoopCount + 1

            ### ~~ Filling the ETH-ALT Matrix ~~ ###

            # Counting the number of ETH Currency Pairs
            ethLoopCount = 0
            while ethLoopCount < marketCount:
                if "ETH-" in markets["result"][ethLoopCount]["MarketName"]:
                    ethCount = ethCount + 1
                ethLoopCount = ethLoopCount + 1

            # Creating the ETH pair-exchange matrix
            ethCol, ethRow = 2, ethCount
            ETHMatrix = [[0 for x in range(ethCol)] for y in range(ethRow)]

            # Filling the ETH Matrix
            ethLoopCount = 0
            ethMatrixRowCount = 0

            while ethLoopCount < marketCount:
                if "ETH-" in markets["result"][ethLoopCount]["MarketName"]:

                    ETHMatrix[ethMatrixRowCount][0] = markets["result"][
                        ethLoopCount]["MarketName"]
                    ETHMatrix[ethMatrixRowCount][1] = markets["result"][
                        ethLoopCount]["Bid"]

                    ethMatrixRowCount = ethMatrixRowCount + 1

                ethLoopCount = ethLoopCount + 1

            btc_ethTick = self.bittrex.get_ticker("BTC-ETH")
            btc_eth_BTC = btc_ethTick["result"]["Bid"]

            # ~~~ Comparing Bitcoin Arbitrage Returns ~~~ #

            arbBTCPairs = []
            arbBTCReturn = []
            arbBTCTestReturn = []
            arbBTCRow = 0

            for btcAlt in BTCMatrix:

                for ethAlt in ETHMatrix:

                    if ethAlt[0][4:] == btcAlt[0][4:]:

                        btcResult = 0

                        #arbBTCPairs.append(str(btcAlt[0]) + " > " + str(ethAlt[0]) + " > BTC_ETH")
                        arbPath = str(btcAlt[0]) + " > " + str(
                            ethAlt[0]) + " > BTC_ETH"

                        btcAltDiff = 0.0000007
                        altEthDiff = -0.0000002
                        ethBtcDiff = -0.000001

                        # Forumla to check returns
                        print("BTC -> Alt: " + str(btcAlt[1]))
                        btc_altX = float(btcAlt[1] + btcAltDiff)
                        print("Alt -> ETH: " + str(ethAlt[1]))
                        eth_altX = float(ethAlt[1] + altEthDiff)
                        print("ETH -> BTC: " + str(btc_eth_BTC))
                        btc_ethX = float(btc_eth_BTC + ethBtcDiff)

                        #test1 = float(btcAlt[1] - 0.00000001)
                        #test2 = float(ethAlt[1] - 0.00000001)
                        #test3 = float(btc_eth_BTC - 0.0000004)

                        print(
                            str(btcAlt[0]) + " > " + str(ethAlt[0]) +
                            " > BTC_ETH")

                        btcUnits = 1
                        print("BTC = " + str(btcUnits))

                        altUnits = round(((btcUnits / 1.0025) / btc_altX), 8)
                        #testaltUnits = round(((btcUnits / 1.0025) / test1), 8)

                        print("Alt Units = " + str(altUnits) + " (" +
                              str(btc_altX) + ")")
                        #print("Test Alt Units = " + str(testaltUnits) + " (" + str(test1) + ")")

                        ethUnits = round(
                            ((altUnits - (altUnits * 0.0025)) * eth_altX), 8)
                        #testethUnits = round(((testaltUnits - (testaltUnits * 0.0025)) * test2), 8)

                        print("ETH Units = " + str(ethUnits) + " (" +
                              str(eth_altX) + ")")
                        #print("Test ETH Units = " + str(testethUnits) + " (" + str(test2) + ")")

                        btcResult = round(
                            ((ethUnits - (ethUnits * 0.0025)) * btc_ethX), 8)
                        #testbtcResult = round(((testethUnits - (testethUnits * 0.0025)) * test3), 8)

                        print("BTC Result = " + str(btcResult) + " (" +
                              str(btc_ethX) + ")")
                        #print("Test BTC Result = " + str(testbtcResult) + " (" + str(test3) + ")")

                        print("")

                        #arbBTCReturn.append(btcResult)
                        #arbBTCTestReturn.append(testbtcResult)
                        print(btcAlt[0])
                        if (btcResult
                            ) >= desiredResult and btcAlt[0] != "BTC-SALT":
                            print("!! Desired Result Reached !!")
                            break

                        arbBTCRow = arbBTCRow + 1

                if (btcResult) >= desiredResult and btcAlt[0] != "BTC-SALT":
                    break

            print("")

            # If desired result is not reached empty the lists to start again
            if btcResult <= desiredResult:
                BTCMatrix[:] = []
                ETHMatrix[:] = []
                arbBTCPairs[:] = []
                arbBTCReturn[:] = []

            LoopNumber = LoopNumber + 1

            # Loops if return isn't good enough i.e. > 1.005

        # Loop has been exited because return is good enough
        # If statement is final check to make sure return is good enough
        if float(btcResult) > desiredResult and btcAlt[0] != "BTC-SALT":

            print("Arb Return = " + str(btcResult))

            print("begin timer")

            startTime = time.time()

            # Path of the arb which yiels return i.e. BTC -> ALT -> ETH -> BTC
            #print(arbPath)

            # Getting name of Alt
            if len(arbPath) == 25:
                alt = arbPath[4:6]
                print("Alt = " + alt)

            elif len(arbPath) == 27:
                alt = arbPath[4:7]
                print("Alt = " + alt)

            elif len(arbPath) == 29:
                alt = arbPath[4:8]
                print("Alt = " + alt)

            elif len(arbPath) == 31:
                alt = arbPath[4:9]
                print("Alt = " + alt)

            else:
                print("Wrong Number Letters " + len(arbPath))

            print("Time elapsed " + str(time.time() - startTime))

            # Begin Buy Process

            orderBTCALTBook = self.bittrex.get_orderbook(
                "BTC-" + str(alt), "sell")

            print("")

            #BTCBal = self.bittrex.get_balance("BTC")

            #if str(BTCBal["result"]["Balance"]) == "None":
            #    principle = 0
            #else:
            #    principle = float(BTCBal["result"]["Balance"])

            principle = 0.00065
            print("Principle = " + str(principle))

            AltQuantity = 0
            ETHQuantity = 0
            BTCQuantity = 0
            market = "BTC-" + alt
            print("Market = " + market)
            print("")

            actBtcAltRate = 0
            actAltEthRate = 0
            actEthBtcRate = 0

            btcOrderCount = 0
            while principle > 0:

                print("BTC -> " + str(alt) + " Order " +
                      str(btcOrderCount + 1) + ": Principle = " +
                      str(principle))

                askQuantity = orderBTCALTBook["result"][btcOrderCount][
                    "Quantity"]
                askRate = orderBTCALTBook["result"][btcOrderCount]["Rate"]
                askTotal = askQuantity * askRate

                print("-- Order Details: --")
                print("---- Ask Quantity = " + str(askQuantity))
                print("---- Ask Rate = " + str(askRate))
                print("---- Ask Total = " + str(askTotal))
                print("---- Principle = " + str(principle))
                print("")

                if askTotal > principle:
                    print("---- Executing full final trade...")
                    tradeQuantity = math.floor(
                        ((principle / 1.0025) / askRate) *
                        100000000) / 100000000
                    print("---- Trade Quantity = " + str(tradeQuantity) +
                          " (" + str(principle / 1.0025) + " / " +
                          str(askRate) + ")")
                    # Execute full or remainder of trade
                    AltQuantity = AltQuantity + tradeQuantity
                    print("---- BUY " + str(AltQuantity) + " " + str(alt) +
                          " @ " + str(askRate) + "BTC = " +
                          str(round((AltQuantity * askRate), 8)))

                    altBuy = self.bittrex.buy_limit(market, AltQuantity,
                                                    askRate)
                    print("---- " + str(altBuy))
                    actBtcAltRate = askRate  # I can delete this because I have a more accurate below from get_order_history
                    altBuy = True
                    break
                else:
                    # Execute a portion of the trade
                    print("---- Partial Trade - CANCEL ... ")
                    print("---- BUY " + str(askQuantity) + str(alt) + " @ " +
                          str(askRate) + " BTC = " +
                          str(round((askQuantity * askRate), 8)))
                    AltQuantity = AltQuantity + askQuantity
                    principle = principle - askTotal
                    break
                    #buy = self.bittrex.buy_limit(market, askQuantity, askRate)
                    #print(buy)
                    #principle = (principle * 0.9975) - askTotal
                    # execute trade

                btcOrderCount = btcOrderCount + 1

            print("")
            print(str(alt) + " Quantity = " + str(AltQuantity))
            firstTrade = time.time() - startTime
            secondTrade = 0
            finalTrade = 0
            print("Time since arb calc = " + str(firstTrade))

            print("")

            if altBuy == True:

                orderETHALTBook = self.bittrex.get_orderbook(
                    "ETH-" + str(alt), "buy")

                market = "ETH-" + alt

                ogAltQuantity = AltQuantity

                altOrderCount = 0
                while AltQuantity > 0:

                    print(
                        str(alt) + " -> ETH Order " + str(altOrderCount + 1) +
                        ": Principle = " + str(AltQuantity))
                    bidQuantity = orderETHALTBook["result"][altOrderCount][
                        "Quantity"]
                    bidRate = orderETHALTBook["result"][altOrderCount]["Rate"]
                    bidTotal = bidQuantity * bidRate

                    print("-- Order Details: --")
                    print("---- Bid Quantity = " + str(bidQuantity))
                    print("---- Bid Rate = " + str(bidRate))
                    print("---- Bid Total = " + str(bidTotal))
                    print("---- Alt Quantity = " + str(AltQuantity))
                    print("")

                    if bidQuantity > AltQuantity:
                        print("Executing full final trade...")
                        tradeQuantity = math.floor(
                            ((AltQuantity * 0.9975) * bidRate) *
                            100000000) / 100000000
                        print("---- Trade Quantity = " + str(tradeQuantity) +
                              " (" + str(AltQuantity) + " * " + str(bidRate) +
                              ")")
                        # Execute full or remainder of trade
                        print("---- SELL " + str(ogAltQuantity) + " " +
                              str(alt) + " @ " + str(bidRate) + "ETH = " +
                              str(tradeQuantity))
                        ETHQuantity = ETHQuantity + tradeQuantity

                        altSell = self.bittrex.sell_limit(
                            market, ogAltQuantity, bidRate)
                        print("---- " + str(altSell))
                        actAltEthRate = bidRate  # I can delete this because I have a more accurate below from get_order_history
                        altSell = True
                        break
                    else:
                        # Execute a portion of the trade
                        print("---- Executing partial trade... " +
                              str(bidQuantity) + str(alt) + " @ " +
                              str(bidRate) + "ETH = " +
                              str(bidQuantity * bidRate))
                        ETHQuantity = (ETHQuantity + bidTotal) * 0.9975
                        sell = self.bittrex.sell_limit(market, bidQuantity,
                                                       bidRate)
                        print(sell)
                        AltQuantity = AltQuantity - bidQuantity
                        # execute trade

                    print("")
                    altOrderCount = altOrderCount + 1

                if altSell == True:

                    print("")
                    print("ETH Quantity = " + str(ETHQuantity))
                    secondTrade = time.time() - startTime
                    print("Time since arb calc = " + str(secondTrade))
                    print("")

                    orderBTCETHBook = self.bittrex.get_orderbook(
                        "BTC-ETH", "buy")

                    ogETHQuantity = ETHQuantity

                    market = "BTC-ETH"

                    ethOrderCount = 0
                    while ETHQuantity > 0:
                        print("ETH -> BTC Order " + str(ethOrderCount + 1) +
                              ": Principle = " + str(ETHQuantity))
                        bidQuantity = orderBTCETHBook["result"][ethOrderCount][
                            "Quantity"]
                        bidRate = orderBTCETHBook["result"][ethOrderCount][
                            "Rate"]
                        bidTotal = bidQuantity * bidRate

                        print("-- Order Details: --")
                        print("---- Bid Quantity = " + str(bidQuantity))
                        print("---- Bid Rate = " + str(bidRate))
                        print("---- Bid Total = " + str(bidTotal))
                        print("---- ETH Quantity = " + str(ETHQuantity))
                        print("")

                        if bidQuantity > ETHQuantity:
                            print("---- Executing full final trade...")
                            tradeQuantity = math.floor(
                                ((ETHQuantity * 0.9975) * bidRate) *
                                100000000) / 100000000
                            print("---- Trade Quantity = " +
                                  str(tradeQuantity) + " (" +
                                  str(ETHQuantity) + " * " + str(bidRate) +
                                  ")")
                            # Execute full or remainder of trade
                            print("---- SELL " + str(ogETHQuantity) +
                                  " ETH @ " + str(bidRate) + "BTC = " +
                                  str(tradeQuantity))
                            BTCQuantity = BTCQuantity + tradeQuantity

                            sell = self.bittrex.sell_limit(
                                market, ogETHQuantity, bidRate)
                            print("---- " + str(sell))
                            actEthBtcRate = bidRate  # I can delete this because I have a more accurate below from get_order_history
                            break
                        else:
                            # Execute a portion of the trade
                            print("---- Executing partial trade... " +
                                  str(bidQuantity) + "ETH @ " + str(bidRate) +
                                  "BTC = " + str(bidQuantity * bidRate))
                            BTCQuantity = BTCQuantity + bidTotal
                            sell = self.bittrex.sell_limit(
                                market, bidQuantity, bidRate)
                            print(sell)

                            ETHQuantity = ETHQuantity - bidQuantity
                            # execute trade

                        ethOrderCount = ethOrderCount + 1

                    print(BTCQuantity)

                    finalTrade = time.time() - startTime
                    print("Time since arb calc = " + str(finalTrade))

                    btcAltMarket = self.bittrex.get_market_summary("BTC-" +
                                                                   str(alt))
                    btcAltVolume = btcAltMarket["result"][0]["Volume"]

                    altEthMarket = self.bittrex.get_market_summary("ETH-" +
                                                                   str(alt))
                    altEthVolume = altEthMarket["result"][0]["Volume"]

                    ethBtcMarket = self.bittrex.get_market_summary("BTC-ETH")
                    ethBtcVolume = ethBtcMarket["result"][0]["Volume"]

                    #  Grab bittrex Trade Details
                    #  1 - BTC-ALT
                    #tradeDetails = self.bittrex.get_order_history()

                    tradeDetails = self.bittrex.get_order_history()
                    tradeOne = tradeDetails["result"][2]
                    tradeTwo = tradeDetails["result"][1]
                    tradeThree = tradeDetails["result"][0]

                    #  Actual Arb Return
                    tradeOneActualValue = tradeOne["Price"] + tradeOne[
                        "Commission"]
                    tradeThreeActualValue = tradeThree["Price"] + tradeThree[
                        "Commission"]
                    actualArbReturn = tradeThreeActualValue / tradeOneActualValue

                    # Actual Rates
                    tradeOneActualRate = tradeOne["PricePerUnit"]
                    tradeTwoActualRate = tradeTwo["PricePerUnit"]
                    tradeThreeActualRate = tradeThree["PricePerUnit"]

                    with open('Trade Tracker.csv', 'a', newline='') as csvfile:
                        tracker = csv.writer(csvfile,
                                             delimiter=',',
                                             quotechar='|',
                                             quoting=csv.QUOTE_MINIMAL)
                        tracker.writerow([
                            arbPath,
                            datetime.datetime.now().strftime(
                                "%Y-%m-%d %H:%M:%S.%f")[:-3], btcResult,
                            actualArbReturn,
                            str(btcAlt[1]),
                            str(btcAltDiff), btcAlt[1] + btcAltDiff,
                            tradeOneActualRate,
                            str(btcAlt[1] - tradeOneActualRate),
                            str((
                                (btcAlt[1] - tradeOneActualRate) / btcAlt[1]) *
                                100),
                            str(firstTrade),
                            str(btcAltVolume),
                            str(ethAlt[1]),
                            str(altEthDiff),
                            str(ethAlt[1] + altEthDiff), tradeTwoActualRate,
                            str(ethAlt[1] - tradeTwoActualRate),
                            str((
                                (ethAlt[1] - tradeTwoActualRate) / ethAlt[1]) *
                                100),
                            str(secondTrade),
                            str(altEthVolume),
                            str(btc_eth_BTC),
                            str(ethBtcDiff),
                            str(btc_eth_BTC + ethBtcDiff),
                            tradeThreeActualRate,
                            str(btc_eth_BTC - tradeThreeActualRate),
                            str(((btc_eth_BTC - tradeThreeActualRate) /
                                 btc_eth_BTC) * 100),
                            str(finalTrade),
                            str(ethBtcVolume)
                        ])

                    print("Excel Save Successful")

                    db = firebase.database()

                    data = {
                        "Arb Path":
                        arbPath,
                        "Date Time":
                        datetime.datetime.now().strftime(
                            "%Y-%m-%d %H:%M:%S.%f")[:-3],
                        "Principle":
                        principle,
                        "Actual Return":
                        BTCQuantity,
                        "Expected Arb Return":
                        btcResult,
                        "Actual Arb Return":
                        actualArbReturn,
                        "Trade 1 Quoted Rate":
                        str(btcAlt[1]),
                        "Trade 1 Adjustment":
                        str(btcAltDiff),
                        "Trade 1 Adjusted Quote":
                        btcAlt[1] + btcAltDiff,
                        "Trade 1 Actual Rate":
                        tradeOneActualRate,
                        "Trade 1 Actual-Quote Diff":
                        str(btcAlt[1] - tradeOneActualRate),
                        "Trade 1 Actual-Quote % Diff":
                        str(((btcAlt[1] - tradeOneActualRate) / btcAlt[1]) *
                            100),
                        "Trade 1 Time From Quote":
                        str(firstTrade),
                        "Trade 1 Market Volume":
                        str(btcAltVolume),
                        "Trade 2 Quoted Rate":
                        str(ethAlt[1]),
                        "Trade 2 Adjustment":
                        str(altEthDiff),
                        "Trade 2 Adjusted Quote":
                        str(ethAlt[1] + altEthDiff),
                        "Trade 2 Actual Rate":
                        tradeTwoActualRate,
                        "Trade 2 Actual-Quote Diff":
                        str(ethAlt[1] - tradeTwoActualRate),
                        "Trade 2 Actual-Quote % Diff":
                        str(((ethAlt[1] - tradeTwoActualRate) / ethAlt[1]) *
                            100),
                        "Trade 2 Time From Quote":
                        str(secondTrade),
                        "Trade 2 Market Volume":
                        str(altEthVolume),
                        "Trade 3 Quoted Rate":
                        str(btc_eth_BTC),
                        "Trade 3 Adjustment":
                        str(ethBtcDiff),
                        "Trade 3 Adjusted Quote":
                        str(btc_eth_BTC + ethBtcDiff),
                        "Trade 3 Actual Rate":
                        tradeThreeActualRate,
                        "Trade 3 Actual-Quote Diff":
                        str(btc_eth_BTC - tradeThreeActualRate),
                        "Trade 3 Actual-Quote % Diff Rate":
                        str(((btc_eth_BTC - tradeThreeActualRate) /
                             btc_eth_BTC) * 100),
                        "Trade 3 Time From Quote":
                        str(finalTrade),
                        "Trade 3 Market Volume":
                        str(ethBtcVolume)
                    }

                    db.child("Successful Transactions").push(data)

                else:
                    print("ALT -> ETH Fail")

            else:
                print("BTC -> ALT Fail")
Ejemplo n.º 6
0
class bittrex_private:
    def __init__(self):
        # self.bittrex_public = Bittrex(None, None)  # 公開情報を扱うBittrexオブジェクト
        self.bittrex_private = Bittrex(KEY, SECRET)  # 個人の情報を扱うBittrexオブジェクト

    # トレード履歴を取得
    def get_order_history(self):
        response = self.bittrex_private.get_order_history()
        pprint(response)
        return response

    # 買い注文を出す
    # marketに通貨ペア、quantityに注文する量、rateに価格を指定
    def buy_alt_coin(self, market, quantity, rate):
        response = self.bittrex_private.buy_limit(market=market,
                                                  quantity=quantity,
                                                  rate=rate)
        # 成功なら注文id、失敗ならfalseを返す
        if response['success'] is False:
            print(response)
            return False
        else:
            return response['result']['uuid']

    # 売り注文を出す
    # marketに通貨ペア、quantityに注文する量、rateに価格を指定
    def sell_alt_coin(self, market, quantity, rate):
        response = self.bittrex_private.sell_limit(market=market,
                                                   quantity=quantity,
                                                   rate=rate)
        # 成功なら注文id、失敗ならfalseを返す
        if response['success'] is False:
            print(response)
            return False
        else:
            return response['result']['uuid']

    # 注文をキャンセルする
    def order_cancel(self, uuid):
        response = self.bittrex_private.cancel(uuid=uuid)
        # 成功ならtrue、失敗ならfalseを返す
        print(response)
        return response['success']

    # 注文一覧を取得する
    def get_orders(self):
        order_list = []
        response = self.bittrex_private.get_open_orders()
        if response['success'] is False:
            print(response)
            return False
        else:
            # 注文が1件もない場合
            if len(response['result']) == 0:
                return None

            for item in response['result']:
                # 通貨の種類と量、注文IDを抜き出す
                balance = {}
                balance['market'] = item['Exchange']
                balance['quantity'] = item['Quantity']
                balance['uuid'] = item['OrderUuid']
                order_list.append(balance)

        return order_list

    # 所有している通貨をList型で返す
    def get_balances(self):
        balance_list = []
        response = self.bittrex_private.get_balances()
        if response['success'] is False:
            print(response)
            return False
        else:
            for item in response['result']:
                # 利用可能な通貨量が0の場合はスキップする
                if item['Available'] == 0:
                    continue
                # 通貨の種類と量を抜き出す
                balance = {}
                balance['currency'] = item['Currency']
                balance['available'] = item['Available']
                balance_list.append(balance)

        return balance_list
Ejemplo n.º 7
0
class CapitVitaCrypto(CapitVita):
    def __init__(self,
                 home_path='',
                 num_coins=25,
                 mailing_list=[],
                 debug=False):

        self.num_coins = num_coins
        self.mailing_list = mailing_list
        self.coin_list = []
        self.df = []
        self.debug = debug
        self.home_path = home_path
        self.file_path = home_path + 'crypto-data/'
        self.volume_sum = []

        # bittrex
        self.B = Bittrex(key, secret)
        self.b_currencies = [
            x['Currency'] for x in self.B.get_currencies()['result']
        ]  # currencies available to trade in bittrex
        self.market_summaries = self.B.get_market_summaries()['result']
        self.markets = [x['MarketName']
                        for x in self.market_summaries]  # market names
        self.BTC_markets = [
            x for x in self.markets if 'BTC' in x and 'USDT' not in x
        ]
        self.ETH_markets = [
            x for x in self.markets if 'ETH' in x and 'USDT' not in x
        ]
        self.USDT_markets = [x for x in self.markets if 'USDT' in x]
        self.USDT_BTC = [
            x for x in self.market_summaries if x['MarketName'] == 'USDT-BTC'
        ][-1]['Last']
        self.USDT_ETH = [
            x for x in self.market_summaries if x['MarketName'] == 'USDT-ETH'
        ][-1]['Last']

    def get_coin_list(self):
        # get coin list (all coins, some are not tradeable on bittrex)

        url = 'https://www.cryptocompare.com/api/data/coinlist/'
        response = urllib2.urlopen(url)
        data = json.loads(response.read())
        self.coin_list = [
            x.encode('ascii', 'ignore') for x in data['Data'].keys()
        ]
        #print(len(self.coin_list))   # 1507 as of 2017-09-14

    def grab_data(self, coin):
        # get historical OHLC for one cryptocurrency

        url = 'https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym=USD&limit={}&aggregate=1&e=CCCAGG'.format(
            coin, 80)
        response = urllib2.urlopen(url)
        data = json.loads(response.read())

        try:
            self.df = pd.DataFrame(data['Data'])
            self.df['date'] = self.df['time'].apply(
                lambda x: datetime.datetime.fromtimestamp(x))
            #self.df.drop(['time', 'volumefrom'], axis = 1)
            #self.df.columns = ['Adj. Close', 'Adj. High', 'Adj. Low', 'Adj. Open', 'time', 'volumefrom', 'volumeto', 'date']
        except KeyError:
            return False

        self.volume_sum.append(self.df['volumeto'].iloc[-20:].median())

        # generate signals
        self.df['rsi'] = self.RSI(self.df['close'], 14)
        self.df['26 ema'] = self.df['close'].ewm(ignore_na=False,
                                                 min_periods=0,
                                                 adjust=True,
                                                 com=26).mean()
        self.df['12 ema'] = self.df['close'].ewm(ignore_na=False,
                                                 min_periods=0,
                                                 adjust=True,
                                                 com=12).mean()
        self.df['MACD'] = self.df['12 ema'] - self.df['26 ema']
        self.df['MACD signal'] = self.df['MACD'] - self.df['MACD'].ewm(
            ignore_na=False, min_periods=0, adjust=True, com=9).mean()
        self.df['MACD_norm'] = self.normalize(self.df['MACD signal'])
        self.df['MACD_der'] = self.derivative(self.df['MACD_norm'])

    def get_points(self, coin):

        try:

            self.grab_data(coin)  ## get the data and store it in self.df

            if len(self.df) < 20 or self.df['volumeto'].iloc[-20:].median(
            ) < 850000 * 0.8:  # if grab is unsuccessful or below average volume * 0.7, end
                points = {'admin': -500}

            else:
                points = {}

                mb, tb, bb, = self.bbands(self.df['close'])
                if self.df['close'].iloc[-1] < (mb.iloc[-1] + bb.iloc[-1]) / 2:
                    points['admin'] = -500

                # RSI points (max 50)
                points['rsi'] = 50 - round(
                    1.2 * abs(30 - self.df['rsi'].iloc[-1]))

                # MACD points (max 50)
                points['macd1'] = round(
                    25 * self.df['MACD_norm'].iloc[-1] /
                    max([abs(x) for x in self.df['MACD_norm']]))
                points['macd2'] = round(
                    25 * self.df['MACD_der'].iloc[-1] /
                    max([abs(x) for x in self.df['MACD_der']]))

                # candlestick points (max 10)
                candlestickFactor = 1

                patterns = self.detectCandlestickPatterns(
                    self.df['open'][-7:], self.df['close'][-7:],
                    self.df['low'][-7:], self.df['high'][-7:],
                    candlestickFactor)
                points['candlesticks'] = self.rangeLimit(
                    round(sum([x[2] for x in patterns])), -20, 20)

        except BufferError as e:
            #except Exception as e:
            print('problem: {}'.format(e))

        return points

    def find_coins(self, graph=False, bittrex_currencies_only=True):
        # start counting duration of script
        start_time = time.time()

        print('Initiating log...')
        # create log
        ff = open(self.file_path + 'readme.txt', 'w')
        ff.write(str(datetime.datetime.now()))
        ff.write('\n')

        print('Deleting old plots...')
        # delete old files
        os.chdir(self.file_path)
        filelist = glob.glob('*.png')
        for f in filelist:
            os.remove(f)
        os.chdir(self.home_path)

        print('Fetching coin list...')
        if bittrex_currencies_only:
            self.update_B()
            self.coin_list = self.b_currencies
        else:
            self.get_coin_list()
            if self.debug:
                self.coin_list = self.coin_list[:30]

        len_coin_list = len(self.coin_list)
        print('  {} coins.'.format(len_coin_list))
        #print('  Expect script to take approximately {} minutes'.format(round(len_coin_list*1.0613 - 14)/60, 2))

        # grab data in batches
        print('Getting points for {} coins...'.format(len_coin_list))
        coin_points = {}
        for i, coin in enumerate(self.coin_list):
            if i % (len(self.coin_list) / 25) == 0:
                print('{}% done'.format(
                    round(100 * float(i) / len(self.coin_list), 1)))
            try:
                points = self.get_points(coin)
                coin_points[coin] = [sum([points[x] for x in points]), points]
            #except BufferError:
            except Exception as e:
                print('failed {} because {}'.format(coin, e))
        original_len_coin_list = len(coin_points)

        print('Sorting coins...')
        # sort stocks by point system
        sorted_coins = sorted(coin_points.items(),
                              key=itemgetter(1),
                              reverse=True)[:self.num_coins]

        print(sorted_coins)

        if graph:
            print('Graphing coins...')
            for coin in [x[0] for x in sorted_coins]:
                try:
                    self.graph_data(coin, saveLocation=self.file_path)
                except BufferError:
                    #except Exception as e:
                    print('failed {} because {}'.format(coin, e))

        # write into log
        ff.write('Cheap coins to invest in for 2 days ~ 1 week: \n\n')

        ff.write('#\n')
        for i in sorted_coins:
            ff.write(i[0] + ': ' + str(round(i[1][0], 1)) + '  ' +
                     str(i[1][1]) + '\n')
        ff.write('#\n')

        ff.write('\n\n  ' + str(original_len_coin_list) +
                 ' stocks shortened by point system to ' +
                 str(len(sorted_coins)) + ' stocks')

        ff.write("\n\n--- %s seconds ---" %
                 (round(time.time() - start_time, 2)))

        ff.write('\n\n\n  Capit-Vita Crypto Version 1.1  (2017-09-22)\n\n')
        ff.write('  - Buying is confirmed to work\n')
        ff.close()

        #print(self.volume_sum[-20:])
        #print('average volume', sum(self.volume_sum)/len(self.volume_sum))
        # median volumeto: 850k

        # send email
        if len(self.mailing_list) > 0:
            send_email(self.file_path,
                       'Top ' + str(self.num_coins) + ' Coin Prospects',
                       self.mailing_list)

        ###### remove coin types I currently own
        my_coins = [x['Currency'] for x in self.B.get_balances()['result']]
        print('my coins: {}'.format(my_coins))
        print('before: {}'.format([x[0] for x in sorted_coins]))
        sorted_coins = [x for x in sorted_coins if x[0] not in my_coins]
        print('after: {}'.format([x[0] for x in sorted_coins]))

        # save wanted coins
        with open(self.file_path + 'wanted_coins.txt', 'w') as f:
            f.write('{}, '.format([str(x[0]) for x in sorted_coins]))

        return sorted_coins

    def buy_next_coin(self):

        # save wanted_coins
        if os.path.isfile(self.file_path + 'wanted_coins.txt'):
            with open(self.file_path + 'wanted_coins.txt', 'r') as f:
                data = eval(f.readlines()[0][:-2])
        else:
            return False

        print(data)

    def update_B(self):

        self.b_currencies = [
            x['Currency'] for x in self.B.get_currencies()['result']
        ]  # currencies available to trade in bittrex
        self.market_summaries = self.B.get_market_summaries()['result']
        self.markets = [x['MarketName']
                        for x in self.market_summaries]  # market names
        self.BTC_markets = [
            x for x in self.markets if 'BTC' in x and 'USDT' not in x
        ]
        self.ETH_markets = [
            x for x in self.markets if 'ETH' in x and 'USDT' not in x
        ]
        self.USDT_markets = [x for x in self.markets if 'USDT' in x]
        self.USDT_BTC = [
            x for x in self.market_summaries if x['MarketName'] == 'USDT-BTC'
        ][-1]['Last']
        self.USDT_ETH = [
            x for x in self.market_summaries if x['MarketName'] == 'USDT-ETH'
        ][-1]['Last']
        #print len(self.b_currencies) # 277 as of 2017-09-21

    def thing(self):

        BTC_market_prices = []
        ETH_market_prices = []
        ### create value exchange rate
        for currency in self.b_currencies:
            if any(currency in x for x in BTC_markets):
                last_price = [
                    x['Last'] for x in self.market_summaries
                    if x['MarketName'] == 'BTC-{}'.format(currency)
                ]
                if len(last_price) > 0:
                    BTC_market_prices.append('Last price for {} is ${}'.format(
                        currency, round(last_price[0] * USDT_BTC, 2)))
            elif any(currency in x for x in ETH_markets):
                last_price = [
                    x['Last'] for x in self.market_summaries
                    if x['MarketName'] == 'ETH-{}'.format(currency)
                ]
                if len(last_price) > 0:
                    ETH_market_prices.append('Last price for {} is ${}'.format(
                        currency, round(last_price[0] * USDT_ETH, 2)))

        cnt_in = 0
        cnt_not_in = 0
        for currency in self.b_currencies:
            if all(currency not in x
                   for x in self.BTC_markets + self.ETH_markets):
                cnt_not_in += 1
                #print('{} not in any market'.format(currency))
            else:
                cnt_in += 1

        #print(cnt_in, cnt_not_in) #203 in market, 74 out of market as of 2017-09-21

        ### can only buy and sell on existing markets

    def my_coins(self):

        my_coins = [x for x in self.B.get_balances()['result']]
        print(my_coins)
        total = 0
        print('\n\n-----------  My Wallet -----------\n')
        for coin in my_coins:
            if coin['Currency'] == 'BTC':
                print('{} available for {} (${})'.format(
                    coin['Available'], coin['Currency'],
                    round(coin['Available'] * self.USDT_BTC, 2)))
                total += coin['Available'] * self.USDT_BTC
            elif any(coin['Currency'] in x for x in self.BTC_markets):
                BTC_coin_rate = [
                    x['Last'] for x in self.market_summaries
                    if x['MarketName'] == 'BTC-{}'.format(coin['Currency'])
                ][0]
                print('{} available for {} (${})'.format(
                    coin['Available'], coin['Currency'],
                    round(coin['Available'] * self.USDT_BTC * BTC_coin_rate,
                          2)))
                total += coin['Available'] * self.USDT_BTC * BTC_coin_rate
            else:
                print('{} available for {} (${})'.format(
                    coin['Available'], coin['Currency'],
                    'hold'))  ## add ethereum
        #return summary
        return my_coins

    def total_available_USD(self, BTC_ETH_only=True):

        balances = self.B.get_balances()['result']
        total_USD = 0

        for balance in balances:
            if balance['Balance'] > 0:
                if balance['Currency'] == 'BTC':
                    total_USD += balance['Balance'] * self.USDT_BTC
                    print('BTC: {}'.format(balance['Balance'] * self.USDT_BTC))
                elif balance['Currency'] == 'ETH':
                    total_USD += balance['Balance'] * self.USDT_ETH
                    print('ETH: {}'.format(balance['Balance'] * self.USDT_ETH))
                elif not BTC_ETH_only:
                    if any(balance['Currency'] in x for x in self.BTC_markets):
                        to_add = balance['Balance'] * [
                            x['Last']
                            for x in self.market_summaries if x['MarketName']
                            == 'BTC-{}'.format(balance['Currency'])
                        ][0] * self.USDT_BTC
                        total_USD += to_add
                        print('{}: {}'.format(balance['Currency'], to_add))
                    elif any(balance['Currency'] in x
                             for x in self.ETH_markets):
                        to_add = balance['Balance'] * [
                            x['Last']
                            for x in self.market_summaries if x['MarketName']
                            == 'ETH-{}'.format(balance['Currency'])
                        ][0] * self.USDT_ETH
                        total_USD += to_add
                        print('{}: {}'.format(balance['Currency'], to_add))
                # consider only BTC and ETH liquid?

        print('Total available: {}'.format(total_USD))

        return total_USD

    def buy_altcoin(self, coin):

        if any(coin in x['Currency'] for x in self.B.get_balances()['result']):
            print('not buying, already have')
            return False

        if any(coin in x for x in self.BTC_markets):

            market = [x for x in self.BTC_markets if coin in x][0]
            print(market)

            available_USD = self.total_available_USD()
            print('available USD', available_USD)

            increment_USD = available_USD / 20
            print('5% available USD: {}'.format(increment_USD))

            BTC_coin_rate = self.B.get_marketsummary(
                market)['result'][0]['Last']
            print('BTC - {} conversion: {}'.format(coin, BTC_coin_rate))

            print('BTC - USD conversion: {}'.format(self.USDT_BTC))

            print('want to buy {} {} coins'.format(
                increment_USD / self.USDT_BTC / BTC_coin_rate, coin))

            print('buying {}: {}'.format(
                coin,
                self.B.buy_limit(market,
                                 increment_USD / self.USDT_BTC / BTC_coin_rate,
                                 BTC_coin_rate)))  # market, quantity, rate

    def sell_altcoin(self, order):
        # takes a buy order and reverses it (sell)

        coin = order['Exchange'][4:]
        if any(coin in x for x in self.BTC_markets):
            market = [x for x in self.BTC_markets if coin in x][0]
        elif any(coin in x for x in self.ETH_markets):
            market = [x for x in self.ETH_markets if coin in x][0]
        coin_rate = self.B.get_marketsummary(market)['result'][0]['Last']
        quantity = order['Quantity']

        if all(coin not in x['Currency']
               for x in self.B.get_balances()['result']):
            print('cannot sell, do not have')
            return False

        #print('selling {}: {}'.format(market, self.B.sell_limit(market, quantity, coin_rate)))    # market, quantity, rate

    def coin_to_USD(self, order):

        coin = order['Exchange'][4:]

        market = [x for x in self.BTC_markets if coin in x][0]
        BTC_coin_rate = self.B.get_marketsummary(market)['result'][0]['Last']

        if coin == 'BTC':
            return order['Quantity'] * self.USDT_BTC
        elif coin == 'ETH':
            pass
        elif any([coin in x for x in self.BTC_markets]):
            last_price = [
                x['Last'] for x in self.market_summaries
                if coin in x['MarketName']
            ]
            return order['Quantity'] * self.USDT_BTC * BTC_coin_rate
        elif any(coin in x for x in self.ETH_markets):
            pass
        else:
            pass

    def my_coin_price_change(self):

        orders = self.B.get_order_history()['result']

        ## remove orders that I don't own
        orders = [x for x in orders]

        print(orders)

        self.update_B()

        for order in orders:
            bought_at = round(
                order['Quantity'] * order['PricePerUnit'] * self.USDT_BTC, 2)
            currently = round(self.coin_to_USD(order), 2)
            perc_change = round((currently / bought_at - 1) * 100, 1)
            timestamp = datetime.datetime.now() - datetime.datetime.strptime(
                order['TimeStamp'], '%Y-%m-%dT%H:%M:%S.%f')
            print(
                '   bought {} ({} ago) for relative BTC value of ${}, currently ${}: {}% change'
                .format(order['Exchange'][4:], timestamp, bought_at, currently,
                        perc_change))

            ### formula for selling:
            # cost of trade = 0.35% x 2 = 0.7%
            # have an open sell order at 10% -> 9.3% up
            # if simulataneous orders are possible, have an open sell order at -10% -> 10.7% down
            # if the coin is older than 5 days, lower the upper sell limit by 2% to 8% -> 7.3% up
            # every 3 days after that lower by 2% until @ 2%

            lower_limit = -10
            if timestamp < datetime.timedelta(days=5):
                upper_limit = 10
            elif timestamp < datetime.timedelta(days=8):  # approx one week
                upper_limit = 8
            elif timestamp < datetime.timedelta(days=11):
                upper_limit = 6
            elif timestamp < datetime.timedelta(days=14):  # two weeks
                upper_limit = 4
            elif timestamp < datetime.timedelta(days=17):
                upper_limit = 2
            elif timestamp > datetime.timedelta(
                    days=21):  # sell no matter what after 3 weeks
                upper_limit = -10

            if perc_change < lower_limit or perc_change > upper_limit:
                self.sell_altcoin(order)
Ejemplo n.º 8
0
    count += 1
master_bittrex = Bittrex(api_key=master_api_key, api_secret=master_api_secret)
print('Opening Master Account...')
master_open_orders = master_bittrex.get_open_orders()
if master_open_orders['success']:
    print('Master Open Orders = ', len(master_open_orders['result']))
else:
    print(
        'Error....', master_open_orders['message'],
        'Application cannot run...please correct errors and restart application'
    )
    print('Application will terminate after 10 seconds...')
    sleep(10)
    exit()

master_order_history = master_bittrex.get_order_history()
print('Master History Orders = ', len(master_order_history['result']))
print('Opening Slave Accounts...')
slave_number = 0
for i in slave_api:
    slave_bittrex = Bittrex(api_key=i[0], api_secret=i[1])
    slave_open_orders = slave_bittrex.get_open_orders()
    slave_number += 1
    if slave_open_orders['success']:
        print('Slave', slave_number, 'Success')
    else:
        print(
            'Error....Slave', slave_number, slave_open_orders['message'],
            'Application cannot run...please correct errors and restart application'
        )
        print('Application will terminate after 10 seconds...')