示例#1
0
def get_bitr(coin):
    my_bittrex = Bittrex(None, None, api_version=API_V1_1)
    l = []
    p = []
    markets = my_bittrex.get_markets()
    tick = my_bittrex.get_ticker('NEO-USDT')
    i=0
    eth = get_eth()
    while i<289:
        l.append(markets['result'][i]['MarketName'])
        i=i+1
    for i in l:
        if i[:3]=='ETH':
            p.append(i)
    i=0
    tr=False    
    while i<len(p):
        if coin==p[i][4:]:
                tick = my_bittrex.get_ticker(p[i])
                tr=True
                try:
                    highlow = get_histor(p[i])
                except:
                        print('Cant')   
                break
        i=i+1
    if tr==True:
        try:
                tests = check_coin(coin)
                link = 'https://coinmarketcap.com/currencies/{}/'.format(tests[2])
                return('1 ' + coin +' = ' + str(round(tick['result']['Bid']*eth,2)) + " USD\nСамая высокая цена: {} USD,\nСамая низкая цена: {} USD".format(round(highlow[0]*eth,2),round(highlow[1]*eth,2))+'\nИзменение за 24 часа: {} USD'.format(str(tests[0]))+'\nИзменение за 7 дней: {} USD\nСсылка на токен: '.format(str(tests[1]))+link)
        except:
                return('1 ' + coin +' = ' + str(tick['result']['Bid']*eth) + ' USD')
    else:
        return('Информации не найдено')
示例#2
0
def getPredictions():
    f = open('predictor.txt', 'r+')
    x = f.read()
    y = ast.literal_eval(x)
    p = open('profits.txt', 'r+')
    profits = float(p.read())
    new_data = []
    for z in y:
        my_bittrex = Bittrex('******', '####')
        market = "BTC-" + z['coin']
        price_btc = my_bittrex.get_ticker(market)['result']['Ask']
        new_prices = z['data']['prices']
        new_prices.pop(0)
        new_prices.append(price_btc)

        if z['data']['tracing'] == True:
            if ((price_btc / new_prices[4]) +
                (new_prices[4] / new_prices[3])) / 2 >= 1:
                finace = finances.Finances()
                amount = finace.getBuyAmount()
                #trader = trader.Trader()
                # trader.buyCoin(z['coin'])
                print('BUY,', z['coin'])
                buyCoin(z['coin'])

        # for i in range(1,len(new_prices)-3):
        #   running_average = running_average + (new_prices[i]/new_prices[i-1]
        #print("% 5s   .......  % 4.3f" % (z['coin'],running_average))
        running_average = ((new_prices[1] / new_prices[0]) +
                           (new_prices[2] / new_prices[1]) +
                           (new_prices[1] / new_prices[0]) +
                           (new_prices[3] / new_prices[2])) / 4
        #print("% 5s   .......  % 4.3f" % (z['coin'], running_average))

        new_price_length = len(new_prices)
        if ((price_btc / new_prices[new_price_length - 2]) +
            (new_prices[new_price_length - 2] /
             new_prices[new_price_length - 3])) / 2 > 1:
            tracing_bool = False
        elif (running_average) < 0.995:
            print("STARTED TRACING", z['coin'])
            tracing_bool = True
        else:
            tracing_bool = False

        data = {
            'coin': z['coin'],
            'data': {
                'prices': new_prices,
                'slope': new_prices[1] / new_prices[0],
                'tracing': tracing_bool
            }
        }
        new_data.append(data)
    # print(new_data)
    f = open('predictor.txt', 'w+')
    f.write(str(new_data))
    f.close()
示例#3
0
class TestBittrexPublicAPI(unittest.TestCase):
    """
        Integration tests for Bittrex Public API
    """
    def setUp(self):
        self.bittrex = Bittrex()

    def test_get_markets(self):
        actual = self.bittrex.get_markets()
        test_basic_response(self, actual, 'get_markets')

    def test_get_currencies(self):
        actual = self.bittrex.get_currencies()
        test_basic_response(self, actual, 'get_currencies')

    def test_get_ticker(self):
        self.assertRaises(TypeError, self.bittrex.get_ticker)
        actual = self.bittrex.get_ticker('BTC-LTC')
        test_basic_response(self, actual, 'get_ticker')
        false_actual = self.bittrex.get_ticker('BTC')
        test_failed_response(self, false_actual, 'get_ticker')

    def test_get_market_summaries(self):
        actual = self.bittrex.get_market_summaries()
        test_basic_response(self, actual, 'get_market_summaries')

    def test_get_market_summary(self):
        self.assertRaises(TypeError, self.bittrex.get_market_summary)
        actual = self.bittrex.get_ticker('BTC-LTC')
        test_basic_response(self, actual, 'get_market_summar')
        false_actual = self.bittrex.get_ticker('BTC')
        test_failed_response(self, false_actual, 'get_market_summar')

    def test_get_order_book(self):
        self.assertRaises(TypeError, self.bittrex.get_order_book)
        self.assertRaises(TypeError, self.bittrex.get_order_book, 'BTC-LTC')
        actual = self.bittrex.get_order_book('BTC-LTC', 'buy')
        test_basic_response(self, actual, 'get_order_book')

    def test_get_market_history(self):
        self.assertRaises(TypeError, self.bittrex.get_market_history)
        actual = self.bittrex.get_market_history('BTC-LTC')
        test_basic_response(self, actual, 'get_market_history')
示例#4
0
class BittrexWrapper(object):

    def __init__(self, apiKey, apiSecret):
	self.apiKey = apiKey
	self.apiSecret = apiSecret
	self.api = Bittrex(self.apiKey, self.apiSecret)
	self.failure = (False, 0, 0)

    def get_price(self, market_code, base_code='BTC'):
	self.currency_code = '%s-%s' % (base_code, market_code)
	price_ticker = bittrex_api.get_ticker(currency_code)
	if price_ticker['success']:
		return price_ticker
	else:
		return {}

    def get_address(self):
        deposit_address_query = self.api.get_deposit_address(base_code)
        if deposit_address_query['success'] == False and deposit_address_query['message'] == 'ADDRESS_GENERATING':
                time.sleep(10)
                deposit_address_query = self.api.get_deposit_address(base_code)

    def buy_coins(self, market_code, price, base_code='BTC'):
	currency_code = '%s-%s' % (base_code, market_code)

	price_ticker = self.api.get_ticker(currency_code)
	if price_ticker['success']:
		ask_price = price_ticker['result']['Ask']
	else:
		return self.failure

	quantity = price / ask_price 
	sell_market_query = self.api.buy_limit(currency_code, quantity, ask_price)
	if sell_market_query['success']:
		order_uuid = sell_market_query['result']['uuid']
	elif not sell_market_query['success']:
		return self.Failure

	# Sleep for long enough for bittrex to process the order
	time.sleep(30)  # 4) Check the Order
	order_status_query = bittrex_api.get_order(order_uuid)
	if order_status_query['success']:
		aOrder = dict()
		aOrder['price'] = order_status_query['result']['Price']
		aOrder['Quantity'] = order_status_query['result']['Quantity']
		aOrder['Exchange'] = order_status_query['result']['Exchange']
		aOrder['completed'] = True
		return aOrder['completed'], aOrder['price'], aOrder['Quantity']
	else:
		return self.Failure
示例#5
0
def buyCoin(coin):
    my_bittrex = Bittrex('******', '####')
    market = 'BTC-' + coin
    price_btc = my_bittrex.get_ticker(market)['result']['Ask']
    finance = finances.Finances()
    size = (finance.getBuyAmount() / price_btc)
    #size = ((profits*0.92)/(price_btc))
    my_bittrex.buy_limit(market, size, price_btc)
    print('BOUGHT', coin)
    ledger_list.append({'coin': coin, 'price': price_btc, 'size': size})
    print(ledger_list)
    f = open('ledger.txt', 'w+')
    f.write(str(ledger_list))
    # updateProfitsSpent(profits*0.92)
    f.close()
示例#6
0
def get_kurs():
    my_bittrex = Bittrex(None, None)
    coins = ['TRIG', 'NEO', 'ADX']
    sumbuy = [0.00008899, 0.00346663, 0.00012222]
    col = [50, 0.33, 15, 7, 200]
    #col = [0.01,0.01,0.01,0.01,0.01]
    val = []
    resp = ""
    for item in coins:
        tmp = my_bittrex.get_ticker('BTC-' + item)
        try:
            val.append(tmp['result']['Last'])
        except:
            val.append(0)
    resp = ""
    for i in range(len(coins)):
        resp = resp + coins[i] + ' Tek: %.8f : %.8f (%.3f)\n' % (
            val[i], sumbuy[i], (val[i] - sumbuy[i]) * col[i] * 58 * 13500)
    return resp
示例#7
0
def checkCoin(coin, price, size):
    my_bittrex = Bittrex('******', '#####')

    market = 'BTC-' + coin
    price_btc = my_bittrex.get_ticker(market)['result']['Ask']
    change = float(price_btc) / float(price)
    print("% 5s   .......  % 4.2f" % (coin, ((change - 1) * 100)), '%')
    # changes.append(change)
    # changes_times.append(int(time.time()))
    #data = pd.DataFrame({'changes': changes ,'changes_times':changes_times})
    #sns.lmplot(x="changes_times", y="changes", hue="changes", data=data)
    if change >= 1.0125:
        my_bittrex.sell_limit(market, size, price_btc)
        # updateTracer(coin,price_btc,size)
        #print("STARTED TRACING ", market)
        removeFromLedger(price)
        print("SOLD ", coin)
    elif change <= 0.99:
        my_bittrex.sell_limit(market, size, price_btc)
        print("SOLD AT STOPLOSS ", market)
        removeFromLedger(price)
示例#8
0
def updateBuyingScore():
    my_bittrex = Bittrex('******', '#####')

    my_markets = [
        'BTC-ETH',
        'BTC-XRP',
        'BTC-RVN',
        'BTC-BSV',
        'BTC-ADA',
        'BTC-LTC',
        'BTC-BCH',
        'BTC-TRX',
        'BTC-XMR',
        'BTC-SPND',
        'BTC-XLM',
        'BTC-TUSD',
        'BTC-ZEC',
        'BTC-NEO',
        'BTC-XEM',
        'BTC-SOLVE',
        'BTC-BAT',
        'BTC-DGB',
        'BTC-XVG',
    ]
    prev_day_dict = {}
    volatity_dict = {}
    volume_dict = {}

    for market in my_markets:
        ask = price_btc = my_bittrex.get_ticker(market)['result']['Ask']
        prev_day_dict.update({
            market:
            (ask /
             my_bittrex.get_market_summary(market)['result'][0]['PrevDay'])
        })
        prev_day_ascending = sorted(prev_day_dict,
                                    key=prev_day_dict.get,
                                    reverse=False)

        volume_dict.update({
            market:
            (my_bittrex.get_market_summary(market)['result'][0]['Volume'])
        })
        volume_ascending = sorted(volume_dict,
                                  key=volume_dict.get,
                                  reverse=True)

        volatity_dict.update({
            market:
            (my_bittrex.get_market_summary(market)['result'][0]['High']) /
            (my_bittrex.get_market_summary(market)['result'][0]['Low'])
        })
        volatility_ascending = sorted(volatity_dict,
                                      key=volatity_dict.get,
                                      reverse=True)

    #print('PrevDay ', {key: rank for rank, key in enumerate(prev_day_ascending, key=prev_day_ascending.get, reverse=False)})
    #print('Volume ', sorted(volume_ascending, key=volume_ascending.get, reverse=True))
    i = 0
    new_prev_dict = {}
    for key in prev_day_ascending:
        new_prev_dict.update({key: i})
        i = i + 1
    #print("New Previous",new_prev_dict)

    i = 0
    new_volume_dict = {}
    for key in volume_ascending:
        new_volume_dict.update({key: i})
        i = i + 1
    #print("New Volume",new_volume_dict)

    i = 0
    new_volatility_dict = {}
    #print('Volatility ', sorted(volatility_ascending, key=volatility_ascending.get, reverse=True))
    for key in volatility_ascending:
        new_volatility_dict.update({key: i})
        i = i + 1
    #print("New Volatility", new_volatility_dict)

    score_dict = {}
    for market in my_markets:
        score_dict.update({
            market: (new_prev_dict.get(market) + new_volume_dict.get(market) +
                     new_volatility_dict.get(market))
        })
    sorted_score = sorted(score_dict, key=score_dict.get, reverse=False)
    print("THE SCORE DICT", sorted_score)
    for x in list(sorted_score)[0:1]:
        print("Buy", x)
        return x
示例#9
0
# Repeats every minute... if coin is in Tracer, see if sell, if coin is not in Tracer, send to check
#
#*******************************************************************************************#
#*******************************************************************************************#
changes = []
changes_times = []
tracer_coins = []
finace = finances.Finances()
p = 0
# print(finace.getTotalAmount())
for i in range(600):
    updateProfitsSpent(finace.getTotalAmount())
    for value in ledger_list:
        # print(value['coin'])
        market = 'BTC-' + value['coin']
        price_btc = my_bittrex.get_ticker(market)['result']['Ask']
        #t = open('tracer.txt','r+')
        #tracer_text = t.read()
        #tracer = ast.literal_eval(tracer_text)
        # for value in tracer:
        #    tracer_coins.append(value['coin'])
        #    print(tracer_coins)
        # print(value['coin'])
        # if value['coin'] in tracer_coins:
        #    print("CHECKING TRACE")
        #    trace(value['coin'],value['size'],value['price'])
        # else:
        checkCoin(value['coin'], value['price'], value['size'])
        if p == 5:
            print("--------------------")
            getPredictions()
示例#10
0
class BrainDataGen(threading.Thread):
    def __init__(self, stores, settings):
        self.stores = stores
        self.settings = settings
        self.my_bittrex = Bittrex(None, None)
        threading.Thread.__init__(self)

    def run(self):
        print("Thread 2 started")
        try:
            time.sleep(60 * 60)
            for element in self.stores:
                element.lock.acquire()
                element.flag = False
                element.lock.release()
        except:
            with open("log.txt", "a") as log:
                log.write("Fehler vor Start des Output Generators")
        while True:
            print("I am working")
            for store in self.stores:
                try:
                    if store.flag:  #true if history goes back 30 minutes
                        print("Output steht bevor: " + store.market)
                        coin_count, transactions, changesm, changemd, changelg = 0, 0, 0, 0, 0  #Variablen initialisieren
                        akt_value = self.my_bittrex.get_ticker(
                            store.market)['result'][
                                'Last']  #History-Daten von Bittrex holen.
                        offset_value = 0  #Offset-Preis t=0
                        store.lock.acquire()
                        for element in store.history:  #start: t-30
                            if (
                                    datetime.utcnow().timestamp() -
                                    element.ts.timestamp()
                            ) < self.OFFSET:  #Wenn Zeitpunkt näher als t=0 (also z.B: t+1)
                                offset_value = element.price
                        akt_time = datetime.utcnow(
                        ).hour * 60 + datetime.utcnow(
                        ).minute  #aktuelle Zeit in Minuten
                        changelg = (
                            offset_value - store.history[0].price
                        ) / store.history[
                            0].price  #Prozentuale Änderung von OFFSET(t=0)+CHANGE_LG(t-30) => Wert der am weitesten in der Vergangenheit liegt.
                        for element in store.history:  #start: t-30
                            time_diff = datetime.utcnow().timestamp(
                            ) - element.ts.timestamp(
                            )  #Zeitunterschied zwischen ELement und jetzt
                            if time_diff < self.OFFSET:  #Wenn Wert näher an Gegenwart als t=0
                                break
                            if time_diff < (
                                    self.CHANGE_SM + self.OFFSET
                            ):  #Wenn Element zwischen t=0 und t-5 liegt
                                transactions += 1  #Zahl der Transaktionen zwischen t=0 und t-5
                                coin_count += element.amount  #Zahl der gehandelten Coins zwischen t=0 und t-5
                                if changesm == 0:  #Wenn Element das erste mal zwischen t=0 und t-5 liegt
                                    changesm = (
                                        offset_value - element.price
                                    ) / element.price  #Prozentuale Änderung von OFFSET(t=0)+CHANGE_SM(t-5)
                                    print("SM gesetzt")
                            else:
                                if time_diff < (
                                        self.CHANGE_MD + self.OFFSET
                                ) and changemd == 0:  #Wenn Element das erste mal zwischen
                                    changemd = (offset_value -
                                                element.price) / element.price
                                    print("MD gesetzt")
                        store.lock.release()
                        out = Out_element1(akt_time, offset_value,
                                           transactions, coin_count, changesm,
                                           changemd, changelg, akt_value)
                        with open("brain_out.csv", "a") as brain_out:
                            csv_writer = csv.writer(brain_out,
                                                    delimiter=';',
                                                    lineterminator='\n',
                                                    quotechar='"',
                                                    quoting=csv.QUOTE_MINIMAL)
                            csv_writer.writerow(out.getIterable())
                            print("New Output")
                        #for element in store.history:
                        #with open("debug.txt", "a") as log:
                        #log.write(str(element)+"\n")

                        #with open("debug.txt", "a") as log:
                        #log.write("=========================================\n")
                except Exception as e:
                    with open("log.txt", "a") as log:
                        log.write(
                            "==============================================================================\n"
                        )
                        log.write(str(datetime.timestamp()))
                        log.write("Fehler beim Erstellen von Output: " +
                                  store.market + "\n")
                        log.write(str(e) + "\n")
                        log.write(
                            "==============================================================================\n"
                        )
            time.sleep(5 * 60)
示例#11
0
class Market(object):
    """
    Used to provide analysis of a market on Bittrex.
    """
    def __init__(self, name, bittrex=None):
        """
        :param name: String literal for the market (e.g. BTC-LTC)
        :type name: str
        :param bittrex: Instance of Bittrex, potentially with API_KEY and SECRET
        :type bittrex: Bittrex
        """
        self.name = name
        self.basis, self.coin = self.name.split("-")
        if bittrex:
            self.bittrex = bittrex
        else:
            self.bittrex = Bittrex(None, None)

    @property
    def summary(self):
        response = self.bittrex.get_market_summary(self.name)
        if response['success']:
            return response['result'][0]
        raise Exception("Could not retrieve data from Bittrex: {:s}".format(
            response['message']))

    @property
    def history(self):
        response = self.bittrex.get_market_history(self.name)
        if response['success']:
            df = pd.DataFrame(response['result'])
            df["TimeStamp"] = pd.to_datetime(df["TimeStamp"])
            return df
        raise Exception("Could not retrieve data from Bittrex: {:s}".format(
            response['message']))

    def _get_orderbook(self, depth_type, depth=20):
        response = self.bittrex.get_orderbook(self.name, depth_type, depth)
        if response['success']:
            return pd.DataFrame(response['result'])
        raise Exception("Could not retrieve data from Bittrex: {:s}".format(
            response['message']))

    def get_buy_orderbook(self, depth=20):
        return self._get_orderbook(BUY_ORDERBOOK, depth)

    def get_sell_orderbook(self, depth=20):
        return self._get_orderbook(SELL_ORDERBOOK, depth)

    def get_both_orderbooks(self, depth=20):
        response = self.bittrex.get_orderbook(self.name, BOTH_ORDERBOOK, depth)
        if response['success']:
            return (pd.DataFrame(response['result']['buy']),
                    pd.DataFrame(response['result']['sell']))
        raise Exception("Could not retrieve data from Bittrex: {:s}".format(
            response['message']))

    @property
    def ticker(self):
        response = self.bittrex.get_ticker(self.name)
        if response['success']:
            return response['result']
        raise Exception("Could not retrieve data from Bittrex: {:s}".format(
            response['message']))

    def get_price_time_series(self):
        return self.history[["TimeStamp", "Price"]]

    def __str__(self):
        return "{:s}\t{:s}".format(self.name, str(self.ticker))
示例#12
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")
示例#13
0
# read config
print("reading config...")
c = open("marketmusic.conf", "r").readlines()
currency = []
for i in range(0, len(c)):
    t = c[i].replace("\n", "")
    currency.append(t)
    print(" - currency added: " + t)
print(" - done")

# get current market values
i = 1
s = ""
print("\nchoose a coin:")
for coinpair in currency:
    currentTick = api.get_ticker(coinpair)["result"]
    c = colors.ENDC
    unit = "BTC"
    if coinpair == "USDT-BTC":
        unit = "USD"
    if coinpair in RED_COINS:
        c = colors.RED
    if coinpair in YELLOW_COINS:
        c = colors.YELLOW
    if coinpair in GREEN_COINS:
        c = colors.GREEN
    if coinpair in BLUE_COINS:
        c = colors.BLUE
    if coinpair in WHITE_COINS:
        c = colors.BOLD
    print(s + c + str(i) + ". " + coinpair + " (" + str(currentTick["Last"]) +
示例#14
0
key = "yourkey"
secret = "yoursecret"
from bittrex import Bittrex
from bittrex import API_V2_0
my_bittrex = Bittrex(key, secret)

# Get Markets
markets = my_bittrex.get_markets()
marketsdf = pd.DataFrame.from_dict(markets['result'])
# Get Currencies
currencies = pd.DataFrame.from_dict(my_bittrex.get_currencies()['result'])
currencies_list = currencies[currencies['IsActive'] ==
                             True]['Currency'].unique()
# Get Ticker
ticker = my_bittrex.get_ticker('BTC-LTC')
print ticker['result'].head()
# Get Market Summaries
summaries = my_bittrex.get_market_summaries()
summariesdf = pd.DataFrame.from_dict(summaries['result'])
print summariesdf.head()
# Get Market Summary
summary = my_bittrex.get_marketsummary('BTC-LTC')
summarydf = pd.DataFrame.from_dict(summary['result'])
print summarydf.head()
# Get Orderbook
orderbook = my_bittrex.get_orderbook('BTC-LTC')
orderbookbuydf = pd.DataFrame.from_dict(orderbook['result']['buy'])
orderbookselldf = pd.DataFrame.from_dict(orderbook['result']['sell'])
print orderbookbuydf.head()
print orderbookselldf.head()
# Get Market History
示例#15
0
class CryptoCommander:
    def __init__(self, poloapicreds=['', ''], bittrexapicreds=['', '']):
        print(
            "Initializing Crypto Commander, Intelligent and Responsive Crypto-Currency Platform..."
        )
        print(
            "Disclaimer!! You have launched this via command line, great caution is advised and the developers are NOT responsible for proper usage or lost coins!"
        )
        print(
            "Notice - :: :: Bitcoin & Crypto-Currencies are largely untested and come with no assurances! Trade with care. :: ::"
        )
        if poloapicreds == ['', '']:
            print(
                "No poloniex credentials found, skipping initialization. This may cause instability!"
            )
        else:
            try:
                self.poloniexBot = poloniex(poloapicreds[0], poloapicreds[1])
                self.btcBalance, self.btsBalance, self.clamBalance, self.dashBalance, self.dogeBalance, self.ethBalance, self.fctBalance, self.ltcBalance, self.maidBalance, self.strBalance, self.xmrBalance, self.xrpBalance, = Decimal(
                    0.0), Decimal(0.0), Decimal(0.0), Decimal(0.0), Decimal(
                        0.0), Decimal(0.0), Decimal(0.0), Decimal(
                            0.0), Decimal(0.0), Decimal(0.0), Decimal(
                                0.0), Decimal(0.0)
            except AttributeError:
                print(
                    "An error occurred trying to initialize Poloniex functionality."
                )
        if bittrexapicreds == ['', '']:
            print(
                "No bittrex credentials detected, skipping initialization. This may cause instability!"
            )
        else:
            try:
                self.bittrexBot = Bittrex(bittrexapicreds[0],
                                          bittrexapicreds[1])
            except AttributeError:
                print(
                    "An error occurred trying to initialized Bittrex functionality."
                )

    def convert_coinpair_poloniex(self, coinpair):
        return coinpair.replace('-', '_')

    def get_tickers_raw(self, market):
        # A clone of the bittrex get_markets() & poloniex returnTicker commands, in a unified stream.
        if market == 'poloniex':
            return self.poloniexBot.returnTicker()
        elif market == 'bittrex':
            return self.bittrexBot.get_markets()

    def get_coinpair_ticker_raw(self, market, coinpair):
        # Returns raw market information on coin pair  on market
        if market == 'poloniex':
            coinpair = self.convert_coinpair_poloniex(coinpair)
            rawtickerdata = self.get_tickers_raw(market)
            for coinpairdata in rawtickerdata:
                if coinpairdata == coinpair:
                    return rawtickerdata[coinpairdata]
        if market == 'bittrex':
            return self.bittrexBot.get_ticker(coinpair.capitalize())

    def getTickerData(self,
                      market,
                      bitcoinMarketsOnly=True,
                      activeOnly=True,
                      printFriendly=False,
                      decimalTypes=True):
        #if market == 'poloniex:

        if market == 'bittrex':
            cryptoCommandTickers = {'BTC': [], 'Other': []}
            btcMarketsList = cryptoCommandTickers['BTC']
            otherMarketsList = cryptoCommandTickers['Other']
            stagingList = []
            if printFriendly == True:
                decimalTypes = False
            for ticker in self.bittrexBot.get_markets()['result']:
                if ticker != None:
                    stagingList.append([
                        str(ticker['MarketName']),
                        str(ticker['BaseCurrency']),
                        bool(str(ticker['IsActive']))
                    ])
            for ticker in self.bittrexBot.get_market_summaries()['result']:
                if ticker != None:
                    for list in stagingList:
                        if list[0] == str(ticker['MarketName']):
                            list.extend([
                                ticker['High'], ticker['Low'], ticker['Ask'],
                                ticker['Bid'], ticker['Last'],
                                ticker['PrevDay'], ticker['Volume'],
                                ticker['BaseVolume'],
                                (ticker['High'] + ticker['Low'] / 2.0)
                            ])
            for list in stagingList:
                if list[1] == 'BTC':
                    btcMarketsList.append(list)
                else:
                    otherMarketsList.append(list)
            if printFriendly == True:
                for dictobject in cryptoCommandTickers:
                    for list in cryptoCommandTickers[dictobject]:
                        for n, listobject in enumerate(list):
                            if type(listobject) == float:
                                list[n] = format(listobject, '.8f')
            elif decimalTypes == True:
                for dictobject in cryptoCommandTickers:
                    for list in cryptoCommandTickers[dictobject]:
                        for n, listobject in enumerate(list):
                            if type(listobject) == float:
                                list[n] = Decimal(format(listobject, '.8f'))
            return cryptoCommandTickers

    def getActiveMarketCurrencies(self, market, appendString=''):
        currentMarketList = []
        if market == 'poloniex':
            rawCoinPairData = self.poloniexBot.api_query('returnTicker')
            for coinPairData in rawCoinPairData:
                if str(rawCoinPairData[coinPairData]['isFrozen']) == '0':
                    currentMarketList.append(
                        str(coinPairData).split('_', 1)[1])
        if market == 'bittrex':
            for coinData in self.bittrexBot.get_currencies()['result']:
                if coinData['IsActive'] == True:
                    currentMarketList.append(appendString +
                                             str(coinData['Currency']))
        return set(currentMarketList)

    def getCurrentBalance(self, market, coin):
        if market == 'poloniex':
            return self.poloniexBot.returnBalances()[coin.upper()]
        elif market == 'bittrex':
            return self.bittrexBot.get_balance(coin)['result']['Balance']

    def getTopOrder(self, market, coinPair, buyOrders):
        if buyOrders == True:
            if market == 'poloniex':
                for i in self.poloniexBot.returnOrderBook(
                        coinPair.replace('-', '_'))['bids']:
                    return i
            elif market == 'bittrex':
                for i in self.bittrexBot.get_orderbook(coinPair,
                                                       'buy')['result']:
                    return i
            else:
                print('Not a valid market: ' + str(market))
        else:
            if market == 'poloniex':
                for i in self.poloniexBot.returnOrderBook(
                        coinPair.replace('-', '_'))['asks']:
                    return i
            elif market == 'bittrex':
                for i in self.bittrexBot.get_orderbook(coinPair,
                                                       'sell')['results']:
                    return i
            else:
                print('Not a valid market: ' + str(market))

    def getWalletAddress(self, market, coin):
        if market == "poloniex" or market == "Poloniex":
            return self.poloniexBot.api_query('returnDepositAddresses')[coin]
        elif market == "bittrex" or market == "Bittrex":
            return self.bittrexBot.get_balance(coin)['result']['CryptoAddress']

    def compareMarkets(self, market1, market2):
        currentActiveMarketsLists = [
            self.getActiveMarketCurrencies(market1),
            self.getActiveMarketCurrencies(market2)
        ]
        comparisonList = []
        for i in currentActiveMarketsLists[0]:
            for y in currentActiveMarketsLists[1]:
                if i == y: comparisonList.append(i)
                else: continue
        return comparisonList

    def getCoinPairPriceDifferencePercent(self, buyPrice, sellPrice):
        return (((float(buyPrice) - float(sellPrice)) / float(buyPrice)) *
                100.00)

    def arbitrageScan(self, market1, market2, minPercent=0.45):
        try:
            arbOpportunitiesList = []
            for coinpair in self.doMarketComparison(market1, market2):
                print("Scanning Coin Pair : " + str(coinpair))
                differenceBetweenMarket1and2 = format(
                    self.getCoinPairPriceDifferencePercent(
                        float(self.getTopOrder(market1, coinpair, False, 1)),
                        float(self.getTopOrder(market2, coinpair, True, 1))))
                differenceBetweenMarket2and1 = format(
                    self.getCoinPairPriceDifferencePercent(
                        float(self.getTopOrder(market2, coinpair, False, 1)),
                        float(self.getTopOrder(market1, coinpair, True, 1))))
                if float(differenceBetweenMarket2and1) < (-.525 - minPercent):
                    if (float(self.getTopOrder(market1, coinpair, True)[0]) *
                            float(
                                self.getTopOrder(market1, coinpair, True)[1])
                        ) >= float(self.getCurrentBalance(market1, "BTC")):
                        print("Arb Op: " + str(differenceBetweenMarket2and1) +
                              " for coin pair ")
                        print("Info: Bittrex: Buy:: ")
                        print(self.getTopOrder('bittrex', coinpair, True))
                        print("- Sell:: ")
                        print(self.getTopOrder('bittrex', coinpair, False))
                        arbOpportunity = (coinpair, "Market2to1",
                                          differenceBetweenMarket2and1, 1)
                        arbOpportunitiesList.append(arbOpportunity)
                    else:
                        continue
                elif float(differenceBetweenMarket1and2) < (-.525 -
                                                            minPercent):
                    if float(
                            self.getTopOrder('bittrex', coinpair, True, 3)[0]
                    ) * float(self.getTopOrder(
                            'bittrex', coinpair, True)[1]) >= float(
                                self.getCurrentBalance(market2, "BTC")):
                        print("Arb Op: ")
                        print(str(differenceBetweenMarket1and2))
                        print("Info: Bittrex: Buy:: ")
                        print(self.getTopOrder('poloniex', coinpair, True))
                        print("- Sell:: ")
                        print(self.getTopOrder('poloniex', coinpair, False))
                        print("Info: Poloniex: Buy:: ")
                        print(self.getTopOrder('bittrex', coinpair, True))
                        print("- Sell:: ")
                        print(self.getTopOrder('bittrex', coinpair, False))
                        arbOpportunity = (coinpair, "Market1to2",
                                          differenceBetweenMarket1and2, 1)
                        arbOpportunitiesList.append(arbOpportunity)
                    else:
                        continue
                else:
                    print(differenceBetweenMarket1and2 + " or " +
                          differenceBetweenMarket2and1 + " is more than -.7")
                    continue
            return arbOpportunitiesList
        except AttributeError:
            print("Attribute Error")

    def selectBestOpportunity(self, market1, market2, minPercent=0.45):
        opportunitiesList = []
        while opportunitiesList == []:
            opportunitiesList = self.arbitrageScan(market1, market2,
                                                   minPercent)
        if len(opportunitiesList) != 0:
            bestOpportunity = opportunitiesList[0]
            for opportunity in opportunitiesList:
                if bestOpportunity[2] < opportunity[2]:
                    bestOpportunity = opportunity
        else:
            print("No Opportunities Found")
            bestOpportunity = ("", "", 0.0, 0)
        return bestOpportunity

    def activateArbitrage(self, market1, market2, minPercent=0.45):
        bestArbitrageOpportunity = self.selectBestOpportunity(
            market1, market2, minPercent)
        coinName = str(bestArbitrageOpportunity[0]).replace("BTC-", "")
        if bestArbitrageOpportunity[1] == 'Market1to2':
            fullTopBuyOrder = self.getTopOrder(market1,
                                               bestArbitrageOpportunity[0],
                                               False)
            btcBuyOrderAvailable = (float(fullTopBuyOrder[0]) *
                                    float(fullTopBuyOrder[1]))
            btcBalanceOnMarket = float(
                self.getCurrentBalance('poloniex', "BTC"))
            if float(btcBuyOrderAvailable) > float(btcBalanceOnMarket):
                btcBuyOrderAvailable = float(btcBalanceOnMarket)
            coinAvailable = float(btcBuyOrderAvailable) / float(
                fullTopBuyOrder[0])
            if market1 == "poloniex" or market1 == "Poloniex":
                try:
                    if float(
                            self.getTopOrder(
                                market1, bestArbitrageOpportunity[0], False,
                                0)[0]) * float(
                                    self.getTopOrder(
                                        market1, bestArbitrageOpportunity[0],
                                        False, 0)[1]) < float(
                                            self.getBalance('poloniex',
                                                            'BTC')):
                        self.poloniexBot.buy(
                            bestArbitrageOpportunity[0].replace("-", "_"),
                            fullTopBuyOrder[0], coinAvailable)
                        print(
                            "Successfully Bought on Poloniex, Attempting to Send to Bittrex Now..."
                        )
                        time.sleep(3)
                        self.poloniexBot.withdraw(
                            coinName,
                            (self.getCurrentBalance('poloniex', coinName)),
                            self.getWalletAddress('bittrex', coinName))
                        tempCounter = 0
                        print(self.getCurrentBalance('bittrex', coinName))
                        while float(self.getCurrentBalance(
                                'bittrex', coinName)) < 0.0005:
                            time.sleep(5)
                            tempCounter = tempCounter + 1
                            if tempCounter > 15:
                                print("Still Awaiting Deposit...")
                                tempCounter = 0
                        print(
                            "Deposit Confirmed & Active! Preparing to Dump in 5 Seconds"
                        )
                        time.sleep(5)
                        while float(self.getCurrentBalance(market2, coinName)
                                    ) > 0.00050055 or self.getCurrentBalance(
                                        market2, coinName) == None:
                            time.sleep(3)
                            self.bittrexBot.sell_limit(
                                bestArbitrageOpportunity[0],
                                self.getCurrentBalance('bittrex', coinName),
                                self.getTopOrder(market2,
                                                 bestArbitrageOpportunity[0],
                                                 True, 1))
                        print(
                            "Finished Selling All the Coins that Could be Sold. Cycle Complete."
                        )
                    else:
                        print(
                            "The order didnt stay high enough, starting over")
                        self.activateArbitrage(market1, market2, minPercent)
                except MemoryError:
                    print("Error")
        if bestArbitrageOpportunity[1] == 'Market2to1':
            fullTopBuyOrder = self.getTopOrder(market2,
                                               bestArbitrageOpportunity[0],
                                               False, 0)
            btcBuyOrderAvailable = (float(fullTopBuyOrder[0]) *
                                    float(fullTopBuyOrder[1]))
            btcBalanceOnMarket = float(self.getCurrentBalance(market2, "BTC"))
            if btcBuyOrderAvailable > btcBalanceOnMarket:
                btcBuyOrderAvailable = btcBalanceOnMarket
            coinAvailable = float(btcBuyOrderAvailable) / float(
                fullTopBuyOrder[0])
            if market2 == "bittrex" or market2 == "Bittrex":
                try:
                    if float(
                            self.getTopOrder(
                                market1, bestArbitrageOpportunity[0], False,
                                0)[0]) * float(
                                    self.getTopOrder(
                                        market1, bestArbitrageOpportunity[0],
                                        False, 0)[1]) < float(
                                            self.getCurrentBalance(
                                                'bittrex', 'BTC')):
                        print("Buying " + str(bestArbitrageOpportunity[0]) +
                              " " + str(coinAvailable))
                        buy = self.bittrexBot.buy_limit(
                            bestArbitrageOpportunity[0], coinAvailable,
                            fullTopBuyOrder[0])
                        print(buy)
                        time.sleep(5)
                        if buy['success'] == True:
                            print(
                                "Successfully Bought on Bittrex, Attempting to Send to Poloniex Now..."
                            )
                            time.sleep(5)
                            self.bittrexBot.withdraw(
                                coinName,
                                self.getCurrentBalance(market2, coinName),
                                self.getWalletAddress(market1, coinName))
                            tempCounter = 0
                            print(self.getCurrentBalance(market1, coinName))
                            while float(
                                    self.getCurrentBalance(market1, coinName)
                            ) < 0.00050055 or self.getCurrentBalance(
                                    market1, coinName) == None:
                                time.sleep(5)
                                tempCounter = tempCounter + 1
                                if tempCounter > 15:
                                    print("Still Awaiting Deposit...")
                                    tempCounter = 0
                            print(
                                "Deposit Confirmed and Active! Preparing to Dump in 5 Seconds"
                            )
                            time.sleep(5)
                            while float(
                                    self.getCurrentBalance(
                                        market1, coinName)) > 0.00010055:
                                time.sleep(5)
                                self.poloniexBot.sell(
                                    str(bestArbitrageOpportunity[0]).replace(
                                        "-", "_"),
                                    float(
                                        self.getTopOrder(
                                            market1,
                                            bestArbitrageOpportunity[0].
                                            replace("-", "_"), True, 1)),
                                    self.getCurrentBalance(market1, coinName))
                                print(
                                    "Attempting to Sell Maximum Amount of Coins that Could be Sold."
                                )
                            print("Finished Selling all coins. Cycle Complete")
                        else:
                            print("Failed to Buy")
                            return "Failed to Buy"
                    else:
                        print(
                            "The order didn't stay high enough, starting over")
                        self.activateArbitrage(market1, market2, minPercent)
                except AttributeError:
                    print("Attribute Error, sorry")

    def getLendingBalances(self):
        #Only works with Poloniex
        try:
            return cryptoCommander.poloniexBot.api_query(
                'returnAvailableAccountBalances')['lending']
        except KeyError:
            return []

    def getCurrentLoanOffers(self, coin):
        #Only works with Poloniex
        ret = urllib2.request.urlopen('http://poloniex.com/public?command=' +
                                      'returnLoanOrders' + '&currency=' +
                                      str(coin))
        return json.loads(ret.read())

    def getPrimeLendingRate(self, coin, minWeight=Decimal('25.0')):
        #Only works with Poloniex
        accumulatedWeight, bestRate = Decimal('0.0'), Decimal('0.0')
        print(accumulatedWeight)
        for offer in self.getCurrentLoanOffers(coin)['offers']:
            if accumulatedWeight < minWeight:
                print('Accumulated weight is less than 25: ' +
                      str(accumulatedWeight))
                accumulatedWeight = accumulatedWeight + Decimal(
                    str(offer['amount']))
            else:
                print('Best rate is: ' + str(offer['rate']))
                bestRate = Decimal(str(offer['rate'])) - Decimal('0.000001')
                break
        if bestRate < Decimal('0.000001'): bestRate = Decimal('0.000001')
        return bestRate

    def getActiveLoans(self):
        #Only works with Poloniex
        return self.poloniexBot.api_query('returnActiveLoans')

    def getOpenLoanOffers(self):
        #Only works with Poloniex
        try:
            return self.poloniexBot.api_query('returnOpenLoanOffers')
        except KeyError:
            return []

    def cancelLoanOffer(self, currency, orderNumber):
        #Only works with Poloniex
        return self.poloniexBot.api_query('cancelLoanOffer', {
            "currency": currency,
            "orderNumber": orderNumber
        })

    def cancelAllLoanOffers(self):
        openLoansDict = self.getOpenLoanOffers()
        for openLoanCoin in openLoansDict:
            for dataObject in openLoansDict[openLoanCoin]:
                self.cancelLoanOffer(openLoanCoin, dataObject[id])

    def createLoanOffer(self, currency, amount, duration, autoRenew,
                        lendingRate):
        return self.poloniexBot.api_query(
            'createLoanOffer', {
                "currency": currency,
                "amount": amount,
                "duration": duration,
                "autoRenew": autoRenew,
                "lendingRate": lendingRate,
            })

    def checkLendingStagnation(self):
        openLoansDict = self.getOpenLoanOffers()
        for openLoanCoin in openLoansDict:
            for data in openLoansDict[openLoanCoin]:
                if (datetime.datetime.utcnow() - datetime.datetime.strptime(
                        str(data['date']), '%Y-%m-%d %X') >
                        datetime.timedelta(minutes=2)):
                    print('Cancelling Loan Orders that are stagnant.')
                    self.cancelLoanOffer(openLoanCoin, data['id'])

    def placeAllLoans(self):
        balances = self.getLendingBalances()
        for coin in balances:
            try:
                print(balances[coin])
                if type(balances[coin]
                        ) != Decimal and balances[coin] > Decimal('0.0'):
                    balances[coin] = Decimal(str(balances[coin]))
                if type(balances[coin]
                        ) == Decimal and balances[coin] >= Decimal('0.01'):
                    #print "Print currency available is: " + str(balances[coin]) + str(coin) + ", Lending Now."
                    while Decimal(str(balances[coin])) >= Decimal('0.01'):
                        if Decimal(str(balances[coin])) <= Decimal(
                                '0.02') and Decimal(str(
                                    balances[coin])) >= Decimal('0.01'):
                            print('lending between 0.01 and 0.02')
                            print(
                                self.createLoanOffer(
                                    coin, float(balances[coin]), 2, 0,
                                    self.getPrimeLendingRate(coin)))
                        else:
                            primeRate = self.getPrimeLendingRate(coin)
                            print("Prime Rate is: " + str(primeRate))
                            if primeRate <= Decimal('0.000025') or Decimal(
                                    balances[coin]) > Decimal('0.1'):
                                if Decimal(balances[coin]) >= Decimal('10.0'):
                                    if Decimal(
                                            balances[coin]
                                    ) < Decimal('20.0') and Decimal(
                                            balances[coin]) > Decimal('10.0'):
                                        print('lending between 10 and 20')
                                        print(
                                            self.createLoanOffer(
                                                coin, float(balances[coin]), 2,
                                                0, primeRate))
                                    else:
                                        print('lending 10')
                                        print(
                                            self.createLoanOffer(
                                                coin, 10.0, 2, 0, primeRate))
                                else:
                                    if Decimal(
                                            balances[coin]) > Decimal('0.1'):
                                        if Decimal(balances[coin]) < Decimal(
                                                '0.2') and Decimal(
                                                    balances[coin]) > Decimal(
                                                        '0.1'):
                                            print(
                                                'lending between 0.1 and 0.2')
                                            print(
                                                self.createLoanOffer(
                                                    coin,
                                                    float(balances[coin]), 2,
                                                    0, primeRate))
                                        else:
                                            print('lending 0.1')
                                            print(
                                                self.createLoanOffer(
                                                    coin, 0.1, 2, 0,
                                                    primeRate))
                                    else:
                                        print('lending 0.01')
                                        print(
                                            self.createLoanOffer(
                                                coin, 0.01, 2, 0, primeRate))
                            else:
                                print('lending 0.01')
                                print(
                                    self.createLoanOffer(
                                        coin, 0.01, 2, 0, primeRate))
                        time.sleep(.2)
                        balances = self.getLendingBalances()
                else:
                    print('No coins available to lend, sorry!')
            except KeyError:
                print('All loans for ' + str(coin) + ' actively being lent.')

    def startLendingAutomation(self):
        while True:
            try:
                while self.getLendingBalances(
                ) != None and self.getOpenLoanOffers() != None:
                    while any(self.getLendingBalances()) > Decimal(
                            '0.001') or any(self.getOpenLoanOffers()):
                        self.placeAllLoans()
                        time.sleep(150)
                        self.checkLendingStagnation()
                print('All Done.')
            except TypeError:
                print("NOT done")
示例#16
0
        list_balance.append(data["result"][i]["Balance"])
        list_available.append(data["result"][i]["Available"])
        list_pending.append(data["result"][i]["Pending"])
        i+=1
        
amount=len(list_currency)

#Getting currency price
while n<=amount-1:
    if list_market[n]=="BTC-BTC":
        list_last.append(btceuro+ " eur | "+btcusd+ " usd")
        list_btcvalue.append(list_balance[n])
        list_percent.append(btcpercent)
        n+=1
    else:
        ticker=wallet1.get_ticker(list_market[n])
        summary=requests.get("https://bittrex.com/api/v1.1/public/getmarketsummary?market="+list_market[n])
        summary=summary.json()
        summary=summary["result"][0]["PrevDay"]
        summary=float(summary)
        percent=(1-(summary/ticker["result"]["Last"]))*100
        percent=float(percent)
        ticker=ticker["result"]["Last"]
        ticker=float(ticker)
        list_last.append(ticker)
        list_btcvalue.append(list_last[n]*list_balance[n])
        list_percent.append(percent)
        n+=1
        
#Printing wallet details
while k<=amount-1:
示例#17
0
def get_pair(message):
    my_bittrex = Bittrex(None, None)
    return (my_bittrex.get_ticker('BTC-' + str(message)))
class TestBittrexV11PublicAPI(unittest.TestCase):
    """
    Integration tests for the Bittrex public API.
    These will fail in the absence of an internet connection or if bittrex API goes down
    """
    def setUp(self):
        self.bittrex = Bittrex(None, None, api_version=API_V1_1)

    def test_handles_none_key_or_secret(self):
        self.bittrex = Bittrex(None, None)
        # could call any public method here
        actual = self.bittrex.get_markets()
        self.assertTrue(actual['success'],
                        "failed with None key and None secret")

        self.bittrex = Bittrex("123", None)
        actual = self.bittrex.get_markets()
        self.assertTrue(actual['success'], "failed with None secret")

        self.bittrex = Bittrex(None, "123")
        actual = self.bittrex.get_markets()
        self.assertTrue(actual['success'], "failed with None key")

    def test_get_markets(self):
        actual = self.bittrex.get_markets()
        test_basic_response(self, actual, "get_markets")
        self.assertTrue(isinstance(actual['result'], list),
                        "result is not a list")
        self.assertTrue(len(actual['result']) > 0, "result list is 0-length")

    def test_get_currencies(self):
        actual = self.bittrex.get_currencies()
        test_basic_response(self, actual, "get_currencies")

    def test_get_ticker(self):
        actual = self.bittrex.get_ticker(market='BTC-LTC')
        test_basic_response(self, actual, "get_ticker")

    def test_get_market_summaries(self):
        actual = self.bittrex.get_market_summaries()
        test_basic_response(self, actual, "get_market_summaries")

    def test_get_orderbook(self):
        actual = self.bittrex.get_orderbook('BTC-LTC',
                                            depth_type=BUY_ORDERBOOK)
        test_basic_response(self, actual, "get_orderbook")

    def test_get_market_history(self):
        actual = self.bittrex.get_market_history('BTC-LTC')
        test_basic_response(self, actual, "get_market_history")

    def test_list_markets_by_currency(self):
        actual = self.bittrex.list_markets_by_currency('LTC')
        self.assertListEqual(['BTC-LTC', 'ETH-LTC', 'USDT-LTC'], actual)

    def test_get_wallet_health(self):
        self.assertRaisesRegexp(Exception, 'method call not available',
                                self.bittrex.get_wallet_health)

    def test_get_balance_distribution(self):
        self.assertRaisesRegexp(Exception, 'method call not available',
                                self.bittrex.get_balance_distribution)

    def test_get_candles(self):
        self.assertRaisesRegexp(Exception,
                                'method call not available',
                                self.bittrex.get_candles,
                                market='BTC-LTC',
                                tick_interval=TICKINTERVAL_ONEMIN)

    def test_get_latest_candle(self):
        self.assertRaisesRegexp(Exception,
                                'method call not available',
                                self.bittrex.get_latest_candle,
                                market='BTC-LTC',
                                tick_interval=TICKINTERVAL_ONEMIN)
            cfg['Data']['deposit'] = last_message['text'].split(' ')[1]
            bot.sendMessage(chat_id=str(last_message['from']['id']),
                            text="\u2757\ufe0f Депозит установлен на : " +
                            last_message['text'].split(' ')[1] + "%")
            # сохраняем настройки в файл
            with open('TeleTradingBittrex_bot.ini', 'w') as configfile:
                cfg.write(configfile)
            continue
        else:
            bot.sendMessage(chat_id=str(last_message['from']['id']),
                            text="\u274c Депозит не установлен")
            continue

    # ответ бота на команду о покупке
    # Существует ли такая монета ?
    if my_bittrex.get_ticker('BTC-' +
                             last_message['text'])['success'] == False:
        bot.sendMessage(chat_id=str(last_message['from']['id']),
                        text="\u274c Mонета '" + last_message['text'] +
                        "' не найдена ")
        continue

    # Подтверждение операции
    bot.sendMessage(
        chat_id=str(last_message['from']['id']),
        text=
        "\u2757\ufe0f 1. Купить '{0}' по текущей цене.\n\n\u2757\ufe0f 2. Поставить лимитный ордер на продажу '{0}' на {1}%  выше текуще стоимости. \n\nПодтверждаете ('Да'/'Нет') \u2753"
        .format(last_message['text'], cfg.getfloat('Data', 'sellPercent')))
    print("Waiting for confim (30 sek) ...")
    y = 0
    while y in range(0, 60):
        time.sleep(0.5)