class bittrex_public: def __init__(self): self.bittrex_public = Bittrex(None, None) # 公開情報を扱うBittrexオブジェクト # 取引可能通貨サマリ一覧をList型で返す def get_coin_summery_list(self): coin_summery_list = [] response = self.bittrex_public.get_markets() for item in response['result']: coin_summery = str(item['MarketCurrencyLong']) coin_summery_list.append(coin_summery) return coin_summery_list # 通貨の最小取引単位取得 def get_min_trade_size(self, market): response = self.bittrex_public.get_markets() for item in response['result']: if item['MarketCurrency'] == market: return item['MinTradeSize'] return False # 通貨の終値取得 def get_last_price(self, market): response = self.bittrex_public.get_marketsummary(market) return response['result'][0]['Last']
class BittrexClient: def __init__(self, config: BittrexConfig) -> None: self.config = config.value self.bitrex_client = Bittrex(api_key="XXXXXXXXXXXXXX", api_secret="XXXXXXXXXXXXX") def get_available_coin_volume(self) -> None: coins = self.config['available_coins'] for coin in coins: btc_volume_dict = self.bitrex_client.get_balance(coin) # data = json.load(btc_volume_json) btc_volume_dict = self._parse_result(btc_volume_dict) # for header, value in btc_volume_dict.items(): # print("{x} {y}".format(x=header, y=value)) # if btc_volume_dict.get('Available'): # print('Available {0:} in your account is {1:0.10f}'.format(coin, btc_volume_dict.get('Available'))) # else: # print('Available {0:} in your account is {1:}'.format(coin, btc_volume_dict.get('Available'))) def get_current_market(self) -> dict: markets = self.config['monitor_markets'] result = dict() for market in markets: market_name = None while market != market_name: market_name, ask_value = self.get_market(market) result.update({market_name: ask_value}) return result def get_market(self, market: str) -> tuple: result = dict() market_value = self.bitrex_client.get_marketsummary(market=market) market_value = self._parse_result(market_value) ask_value = market_value[0].get('Last') market_name = market_value[0].get('MarketName') print("Last Traded value of {0:} : {1:0.10f} BTC".format( market_name, ask_value)) result[market_name] = ask_value return market_name, ask_value @staticmethod def _parse_result(raw_response: dict) -> dict: # Todo: check response status to be success response = raw_response['result'] return response
class TradeBot(): def __init__(self, key=None, secret=None, **kwargs): self.exchange = Bittrex(key, secret) self.orders = [] # Default config config = { 'base_currency': 'ETH', 'min_order': 0.001, 'max_order': 0.05, 'sleep_time': 60, 'profit': 2, 'min_volume': 75, 'max_units': 100 } # Update config from object constructor config.update(kwargs) # Set attributes based on config for attr in config.keys(): setattr(self, attr, config[attr]) def get_markets(self): logging.info(f'Getting markets for {self.base_currency}') all_markets = self.exchange.get_markets()['result'] markets = set() for mkt in all_markets: if mkt['BaseCurrency'] == self.base_currency: markets.add(mkt['MarketName']) return markets def get_coins_with_open_orders(self): open_orders = self.exchange.get_open_orders()['result'] if len(open_orders) == 0: return [] else: return [x['Exchange'] for x in open_orders] def get_market_data(self): mkt_data = [] for mkt in self.markets: logging.info(f'Getting market data for {mkt}') data = self.exchange.get_marketsummary(mkt)['result'][0] data['Change'] = calculate_change(data['Last'], data['Low']) mkt_data.append(data) return mkt_data def has_balance_to_buy(self): logging.info('checking if we have some balance to buy') q = self.exchange.get_balance(self.base_currency) # balance_adjustment to avoid INSUFFICIENT FUNDS MESSAGE balance_adjustment = 0.0005 self.balance = q['result']['Available'] - balance_adjustment logging.debug(f'{self.balance}{self.base_currency} available') if self.balance >= self.min_order: return True else: return False def get_market_to_buy(self): self.update() mkt = [ m for m in self.market_data if m['BaseVolume'] >= self.min_volume ] sorted_mkt = sorted(mkt, key=lambda x: x['BaseVolume'], reverse=True) while sorted_mkt[0]['MarketName'] in self.coins_with_open_orders: sorted_mkt.pop(0) return sorted_mkt[0] def buy(self, mkt): coin = mkt['MarketName'] # get a price between ask and bid price = (mkt['Ask'] + mkt['Bid']) / 2 if self.balance > self.max_order: qnt = self.max_order / price else: qnt = self.balance / price if qnt > self.max_units: qnt = self.max_units if (qnt * price) < self.min_order: qnt = self.min_order / price logging.info(f'BUY {qnt} {coin} - price {price}, total {price * qnt}') order = self.exchange.buy_limit(coin, qnt, price) if order['success']: self.orders.append(order['result']['uuid']) else: logging.error(f'BUY FAIL - {order}') return (order) def sell(self): for order in self.orders: order_info = self.exchange.get_order(order)['result'] if order_info['Closed']: coin = order_info['Exchange'] qnt = order_info['Quantity'] price = profit(order_info['PricePerUnit'], self.profit) sell_order = self.exchange.sell_limit(coin, qnt, price) self.orders.remove(order) logging.info(f'SELL {order} {sell_order}') def update(self): logging.info('Updating data') self.markets = self.get_markets() self.market_data = self.get_market_data() self.coins_with_open_orders = self.get_coins_with_open_orders() def do_trade(self): if self.has_balance_to_buy(): self.buy(self.get_market_to_buy()) if len(self.orders) > 0: self.sell() logging.info(f'Sleeping for {self.sleep_time} seconds') sleep(self.sleep_time) def run(self): logging.info('Starting Bot') while True: self.do_trade()
def get_summary(message): my_bittrex = Bittrex(None, None) return (my_bittrex.get_marketsummary('BTC-' + str(message)))
class BittrexBuysellWorker(object): def __init__(self, key=None, secret=None, token=None): self.EXCHANGE_RATE = 0.9975 # 0.25% for each trading transaction self.api = Bittrex(key, secret) self.token = token try: m = self.api.get_market_summaries() #print m market_list = [] for market in m.get("result"): market_list.append(market.get("MarketName")) #print marketlist except: print "Error: Cannot get market summaries" exit(1) self.market_list = market_list def w_get_api(self): """ Get balance of a coin :return: api Bittrex.py :rtype : Bittrex class """ return self.api def w_get_balance(self, coin): """ Get balance of a coin :return: current balance value :rtype : float """ try: m = self.api.get_balance(coin) print m if (m.get("success")): v = m.get("result").get("Balance") return v if v else 0 else: print("Cannot get {} balance".format(coin)) return ERROR.CMD_UNSUCCESS except: print("Error Account/Connection issue. Get {} balance failed". format(coin)) return ERROR.CONNECTION_FAIL def w_get_market_name(self, coin1, coin2): """ Get marketname for pair of coins :param coin1: String literal for coin 1 (ex: USDT) :param coin2: String literal for coin 2 (ex: XMR) :return: (MarketName, "Buy"/"Sell") :rtype : str """ market = coin1 + "-" + coin2 if market in self.market_list: return (market, "Buy") else: market = coin2 + "-" + coin1 if market in self.market_list: return (market, "Sell") else: print "Error: Invalid coin pair" return (None, None) def w_get_price(self, market, type, unit=0, depth=20): """ Get price Ask Last Bid :param market: String literal for coin1-coin2 (ex: USDT-XMR) :param type: Ask/Last/Bid :param unit: if unit != 0, get price with respect to order book :return: price :rtype : float """ if type is "Last" or "Bid" or "Ask": try: price = self.api.get_marketsummary(market).get( "result")[0].get(type) if type == "Ask": ordertype = "sell" elif type == "Bid": ordertype = "buy" else: #Dont need to check order book for Last return price m = self.api.get_orderbook(market, ordertype, depth) #print m if (m.get("message") != ""): print "Fail to get order book of {}: {}".format( market, m.get("message")) return ERROR.CMD_UNSUCCESS else: order_price_list = m.get("result") #print order_price_list sum_quantity = 0 for o in order_price_list: #print o quantity = o.get("Quantity") price = o.get("Rate") sum_quantity += quantity if (sum_quantity >= unit): return price except: print("Error in get {} price".format(market)) return ERROR.CONNECTION_FAIL else: print("Invalid type of market (Ask/Bid/Last)") return ERROR.PARAMETERS_INVALID '''To do: unit != 0''' def w_get_open_order(self, market=None): """ Get list of uuid of open orders :param market: String literal for coin1-coin2 (ex: USDT-XMR) :return: uuid list :rtype : str """ return self.api.get_open_orders(market) def w_order_buy_sell(self, coin1, coin2, value1, price, timeout, cancel_on_timeout=True): """ Buy/Sell from coin c1 to coin coin2 at price :param coin1: String literal for coin 1 (ex: USDT) :param coin2: String literal for coin 2 (ex: XMR) :param value1: The value of coin1 which is used to buy/sell :param price: buy/sell price, can be Ask, Last or Bid :return: uuid order :rtype : str """ value2_before = self.w_get_balance(coin2) #get current coin2 balance market, type = self.w_get_market_name(coin1, coin2) #print market, type #Buy and sell are seperated from market point of view. if (type == "Buy"): order_buy_sell = self.api.buy_limit quantity = value1 / price * self.EXCHANGE_RATE value2 = quantity * self.EXCHANGE_RATE elif (type) == "Sell": order_buy_sell = self.api.sell_limit quantity = value1 value2 = quantity * price * self.EXCHANGE_RATE else: print "Buy/Sell Error: Invalid market {}-{}".format(coin1, coin2) return ERROR.CMD_INVALID print("@@@ From {} {} buy {} {} at price {}.".format( value1, coin1, value2, coin2, price)) #Process buy/sell within timeout #Several posible cases: # 1. The price is too high/low, no one wants to buy/sell # 2. The connection drops while waiting the result # 3. The quantity is too low -> "INSUFFICIENT_FUNDS" response from server try: m = order_buy_sell(market, quantity, price) if (m.get("success") == True): uuid = m.get("result").get("uuid") process_time = time.time() + timeout while 1: value2_after = self.w_get_balance(coin2) if time.time() > process_time: if cancel_on_timeout: #Cancel order because of timeout self.w_cancel_order(uuid) print "Cancel order!" else: print "Order is still open!" return uuid print "{} transaction was timeout".format(type) return ERROR.TIME_OUT if (value2_after < 0): #Error print "Error: in balance code {}".format(value2_after) return ERROR.CMD_UNSUCCESS if (value2_after - value2_before >= value2 * 0.9): #offset 10% for safety #buy success return uuid elif m.get("message") == "INSUFFICIENT_FUNDS": print("INSUFFICIENT_FUNDS issue") print m return ERROR.PARAMETERS_INVALID else: print m return ERROR.CMD_UNSUCCESS except: print "Error buy/sell. Conection failed." return ERROR.CONNECTION_FAIL def w_cancel_order(self, uuid): """ Cancel an order via uuid :param uuid: order uuid :return: error code :rtype : ERROR """ try: #todo: need check timeout self.api.cancel(uuid) while uuid in self.api.get_open_orders(): print "Wait for cancel order {}".format(uuid) return ERROR.CMD_SUCCESS except: print "Cannot cancel order {}".format(uuid) return ERROR.CONNECTION_FAIL def w_get_price_by_order_book(self, market, ordertype, value, depth=20): """ Get the corresponding price for a given value -> Avoid stuck in buy/sell order :param market: Ex: USDT-XMR :param ordertype: "buy" or "sell" :param value: The value of coin1 which is used to buy/sell :return: uuid order :rtype : str """ return 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 history = my_bittrex.get_market_history('BTC-LTC') historydf = pd.DataFrame.from_dict(history['result']) print historydf.head()
class MultiExchangeClient(object): def __init__(self, exchanges): '''exchanges = comma separated list of exchanges you want to monitor''' self.exchanges = [e.lower() for e in exchanges] # Depending on which exchanges got included, connect to APIs if 'kraken' in self.exchanges: self.kraken_api = krakenex.API() self.kraken = KrakenAPI(self.kraken_api) if 'gdax' in self.exchanges: self.gdax = gdax_api.PublicClient() if 'bittrex' in self.exchanges: self.bittrex = Bittrex(None, None) if 'coinmarketcap' in self.exchanges: self.coinmarketcap = Market() def get_latest_price(self, pair, show_arbitrage=True): '''Gief keypair & exchanges, get prices''' responses = dict() if 'bittrex' in self.exchanges: formatted_pair = self._pair_formatter(pair, 'bittrex') pair_bittrex = self.bittrex.get_marketsummary(formatted_pair)['result'][0]['Last'] responses['bittrex'] = pair_bittrex if 'gdax' in self.exchanges: formatted_pair = self._pair_formatter(pair, 'gdax') pair_gdax = parse(self.gdax.get_product_ticker(formatted_pair)['price']) responses['gdax'] = pair_gdax if 'kraken' in self.exchanges: formatted_pair = self._pair_formatter(pair, 'kraken') # eth_kraken = parse(kraken_api.query_public('Ticker?pair=ETHXBT')['result']['XETHXXBT']['a'][0]) # responses['kraken'] = pair_kraken if 'coinmarketcap' in self.exchanges: formatted_pair = self._pair_formatter(pair, 'coinmarketcap') pair_cmcap = parse(self.coinmarketcap.ticker(formatted_pair)[0]['price_btc']) responses['coinmarketcap'] = pair_cmcap if show_arbitrage: self.arbitrage(responses) return responses def arbitrage(self, combination_dict): result_list = list(map(dict, itertools.combinations( # get all combinations combination_dict.items(), 2))) max_arbitrage = 0 for pair in result_list: a,b = pair.values() diff = a-b # find differences between each pair e1, e2 = list(pair.keys()) print ('{} has {} BTC arbitrage over {}'.format(e1, diff, e2)) def _pair_formatter(self, pair, exchange): '''Normalizes the pair to match the expected format by the selected exchange API''' ETH_BTC = ['BTCETH', 'ETHBTC', 'XBT-ETH', 'BTC-ETH', 'ETH-BTC'] if pair in ETH_BTC: if exchange.lower() == 'bittrex': return 'BTC-ETH' elif exchange.lower() == 'gdax': return 'ETH-BTC' elif exchange.lower() == 'kraken': return 'ETHXBT' elif exchange.lower() == 'coinmarketcap': return 'Ethereum' else: raise ValueError('Exchange not supported') else: raise ValueError('Pair not supported')
import time from bittrex import Bittrex import pandas as pd apikey = 'fd25ef6daf6c4d5cb8507878781df312' secret = '5f00769f175141be861bf199f089f9fd' my_bittrex = Bittrex(apikey, secret) my_bittrex.get_currencies() my_bittrex.get_marketsummary('BTC-LTC') coinList = [{ 'CoinName': x['MarketCurrency'], 'CoinName_Full': x['MarketCurrencyLong'], 'MarketName': x['MarketName'], 'BaseCurrency': x['BaseCurrency'] } for x in my_bittrex.get_markets()['result']] coinList = pd.DataFrame(coinList) coinList BTC - LTC, col = [ 'MarketName', 'High', 'Low', 'Volume', 'Last', 'BaseVolume', 'TimeStamp', 'Bid', 'Ask', 'OpenBuyOrders', 'OpenSellOrders', 'PrevDay', 'Created' ] market_price = pd.DataFrame(columns=col) i = 0 while 1: market_price = pd.DataFrame(columns=col) time = time.asctime()
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)
from bittrex import Bittrex import ast import traceback import time import datetime try: import user key = user.key secret = user.secret except: key = None secret = None print key, secret api = Bittrex(key, secret) while 1: start = datetime.datetime.now() n = api.get_marketsummary("BTC-SEQ").get("result")[0].get("Bid") m = api.get_market_summaries().get("result") [p] = [d.get("Bid") for d in m if d['MarketName'] == 'BTC-SEQ'] finish = datetime.datetime.now() print start, finish, finish - start, n, p