def get_depth(self, base, alt): order_book = {'bids': [], 'asks': []} pair, swapped = self.get_validated_pair((base, alt)) if pair is None: return pairstr = pair[0].lower() + "_" + pair[1].lower() if swapped: bids, asks = btceapi.getDepth(pairstr) else: asks, bids = btceapi.getDepth(pairstr) order_book['bids'] = [Order(float(b[0]), float(b[1])) for b in bids] order_book['asks'] = [Order(float(a[0]), float(a[1])) for a in asks] return order_book
def test_getDepth(self): connection = btceapi.BTCEConnection() info = btceapi.APIInfo(connection) for pair in info.pair_names: btceapi.getDepth(pair, connection, info) btceapi.getDepth(pair, connection) btceapi.getDepth(pair, info=info) btceapi.getDepth(pair)
def getPrice(connection, f, tmp_f, pair="btc_usd"): #get ticker ticker = btceapi.getTicker(pair, connection) #print ticker.high #get asks/bids asks, bids = btceapi.getDepth(pair) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) #start list with all of the ticker info curTrades = trades(coin='ltc', updated=ticker.updated, server_time=ticker.server_time, buy=ticker.buy, sell=ticker.sell) #print out_list #now we have a huge list with all the info, write to a single line in the csv file line = ','.join( (pair, str(time.mktime(time.localtime())), str(curTrades.buy))) + '\n' #print line f.write(line) tmp_f.write(line)
def main(): attrs = ('high', 'low', 'avg', 'vol', 'vol_cur', 'last', 'buy', 'sell', 'updated', 'server_time') #initialize connection connection = btceapi.BTCEConnection() f = open('/media/Big Daddy/New_Documents/python_data/ltc_btc_depth.pkl', 'ab') while 1: #sleep for .5 seconds, i.e. collect at 2Hz time.sleep(1) try: #get ticker ticker = btceapi.getTicker("ltc_btc", connection) #get asks/bids asks, bids = btceapi.getDepth("ltc_btc") ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) #start list with all of the ticker info curTrades = trades(coin='ltc',updated=ticker.updated,server_time=ticker.server_time,ask_prices=ask_prices,ask_volumes=ask_volumes,bid_prices=bid_prices,bid_volumes=bid_volumes,buy=ticker.buy,sell=ticker.sell) #print out_list #now we have a huge list with all the info, write to a single line in the csv file # Pickle class using protocol 0. pickle.dump(curTrades,f) #if connection is lost, just try to reconnect (this does seem to happen, so this line is actually pretty important for long data collects) except: connection = btceapi.BTCEConnection() pass
def get_depth(self, base, alt): book = {'bids': [], 'asks': []} pair, swapped = self.get_validated_pair((base, alt)) if pair is None: return pairstr = pair[0].lower() + "_" + pair[1].lower() if swapped: bids, asks = btceapi.getDepth(pairstr) else: asks, bids = btceapi.getDepth(pairstr) book['bids'] = [Order(float(b[0]), float(b[1])) for b in bids] book['asks'] = [Order(float(a[0]), float(a[1])) for a in asks] return book
def checkMarketDepth(self, pair): ''' Keeps track of current market depth ''' connection = btceapi.BTCEConnection() asks, bids = btceapi.getDepth(pair, connection) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) a = np.array(bid_prices) b = np.array(bid_volumes) c = a*b #calc values and put them in list d = np.array(ask_prices) e = np.array(ask_volumes) f = d*e #calc valyes and put them in list suma = sum(ask_volumes) sumb = sum(bid_volumes) askspread = abs(max(bid_prices)-min(ask_prices)) #gap between buy and sell price print "Total askvolume:", suma, "with value:", f.sum() #print sum of lists print "Total bidvolume:", sumb, "with value:", c.sum() print "Lowest askprice:", min(ask_prices) print "Highest bidprice:", max(bid_prices) print "Ask-spread:", askspread connection.close()
def getAsks(): prices = [] for c in pairs: depth = ba.getDepth(c) price = depth[0][0][0] print c[:3] + " ask: " + str(price) prices.append((c[:3], price)) return prices
def sellCoinBTCE(coin, tradeapi): r = tradeapi.getInfo() try: balance = getattr(r, 'balance_' + coin) except: #probably a coin that BTCE doesn't have an exchange for, so just return return if balance > 0.1: #i.e. if we're selling and we have some to sell that's larger than the minimum order... asks, bids = btceapi.getDepth(coin + '_btc') tr = tradeapi.trade(coin + '_btc', 'sell', bids[0][0], balance)
def sellCoinBTCE(coin, tradeapi): r = tradeapi.getInfo() try: balance = getattr(r, 'balance_'+coin) except: # probably a coin that BTCE doesn't have an exchange for, so just return return if balance > 0.1: # i.e. if we're selling and we have some to sell that's larger than the minimum order... asks, bids = btceapi.getDepth(coin + '_btc') tr = tradeapi.trade(coin + '_btc', 'sell',bids[0][0]*tradeMultiplier,balance)
def GetDepth(self, pair, askLimit = 50, bidLimit = 50): if(not pair in self.btcePairs): return {} asks, bids = btceapi.getDepth(self.btcePairs[pair]) result = { \ 'ask' : [{ 'price' : price, 'amount' : amount } for price, amount in asks[:askLimit]], \ 'bid' : [{ 'price' : price, 'amount' : amount } for price, amount in bids[:bidLimit]] \ } return result
def get_pair_depth(self, pair): ''' Returns asks and bids ''' asks, bids = btceapi.getDepth(pair) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) pair_depth = {pair: {'ask_prices': ask_prices, 'ask_volumes': ask_volumes, 'bid_prices': bid_prices, 'bid_volumes' : bid_volumes } } return pair_depth
def graphDepth(self, pair): ''' Build a graph to show depth of given pair ''' asks, bids = btceapi.getDepth(pair) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) pylab.plot(ask_prices, np.cumsum(ask_volumes), 'r-') pylab.plot(bid_prices, np.cumsum(bid_volumes), 'g-') pylab.grid() pylab.title("%s depth" % pair) pylab.show() pylab.close()
def sellCoinBTCE(coin, tradeapi): r = tradeapi.getInfo() try: balance = getattr(r, "balance_" + coin) except: # probably a coin that BTCE doesn't have an exchange for, so just return return if balance > 0.1: # i.e. if we're selling and we have some to sell that's larger than the minimum order... asks, bids = btceapi.getDepth(coin + "_btc") price = bids[0][0] * tradeMultiplier if price > asks[0][0] and tradeMultiplierCheck == True: price = asks[0][0] - 0.00000001 tr = tradeapi.trade(coin + "_btc", "sell", price, balance)
def getTopOfTheBookMinAmount(symbol, minAskAmount, minBidAmount): asks, bids = btceapi.getDepth(symbol) askDepth = 0 bidDepth = 0 ask, askAmount, bid, bidAmount = float(asks[0][0]), float(asks[0][1]), float(bids[0][0]), float(bids[0][1]) while(askAmount < minAskAmount): askDepth = askDepth + 1 ask = float(asks[askDepth][0]) askAmount = askAmount + float(asks[askDepth][1]) while(bidAmount < minBidAmount): bidDepth = bidDepth + 1 bid = float(bids[bidDepth][0]) bidAmount = bidAmount + float(bids[bidDepth][1]) return ask, askAmount, bid, bidAmount
def sellCoinBTCE(coin, tradeapi): r = tradeapi.getInfo() try: balance = getattr(r, 'balance_' + coin) except: # probably a coin that BTCE doesn't have an exchange for, so just return return if balance > 0.1: # i.e. if we're selling and we have some to sell that's larger than the minimum order... asks, bids = btceapi.getDepth(coin + '_btc') price = bids[0][0] * tradeMultiplier if price > asks[0][0] and tradeMultiplierCheck == True: price = asks[0][0] - 0.00000001 tr = tradeapi.trade(coin + '_btc', 'sell', price, balance)
def sellCoin(coin, tradeapi): try: r = tradeapi.getInfo() balance = getattr(r, 'balance_'+coin) #TODO - check for BTCE mins instead of 0 if balance > 0.0001: #i.e. if we're selling and we have some to sell... asks, bids = btceapi.getDepth(coin + '_btc') print "Selling", balance, coin, "at the rate of", bids[0][0], "..." tr = tradeapi.trade(coin + '_btc', 'sell',bids[0][0],balance) print "Sold!" #This sells at the highest price someone currently has a bid lodged for. #It's possible that this won't totally deplete our reserves, but any #unsold immediately will be left on the book, and will probably sell shortly. except: print "Something is wrong with Trade API"
def get_prices_and_volumes(pairs): prices = {"bid": {}, "ask": {}} volumes ={"bid": {}, "ask": {}} for pair in pairs: asks, bids = btceapi.getDepth(pair) a_p, a_v = zip(*asks) b_p, b_v = zip(*bids) prices["ask"][pair] = a_p[0] volumes["ask"][pair] = a_v[0] prices["bid"][pair] = b_p[0] volumes["bid"][pair] = b_v[0] return prices, volumes
def get_prices_and_volumes(pairs): prices = {"bid": {}, "ask": {}} volumes = {"bid": {}, "ask": {}} for pair in pairs: asks, bids = btceapi.getDepth(pair) a_p, a_v = zip(*asks) b_p, b_v = zip(*bids) prices["ask"][pair] = a_p[0] volumes["ask"][pair] = a_v[0] prices["bid"][pair] = b_p[0] volumes["bid"][pair] = b_v[0] return prices, volumes
def getTopOfTheBookMinSum(symbol, s): asks, bids = btceapi.getDepth(symbol) askDepth = 0 bidDepth = 0 ask, askAmount, bid, bidAmount = float(asks[0][0]), float(asks[0][1]), float(bids[0][0]), float(bids[0][1]) askSum = ask * askAmount bidSum = bid * bidAmount while(askSum < s): askDepth = askDepth + 1 askSum = askSum + float(asks[askDepth][0]) * float(asks[askDepth][1]) ask = float(asks[askDepth][0]) askAmount = askAmount + float(asks[askDepth][1]) while(bidSum < s): bidDepth = bidDepth + 1 bidSum = bidSum + float(bids[bidDepth][0]) * float(bids[bidDepth][1]) bid = float(bids[bidDepth][0]) bidAmount = bidAmount + float(bids[bidDepth][1]) return ask, askAmount, bid, bidAmount
def getPrice(connection,f,pair="btc_usd"): #get ticker ticker = btceapi.getTicker(pair, connection) #print ticker.high #get asks/bids asks, bids = btceapi.getDepth(pair) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) #start list with all of the ticker info curTrades = trades(coin='ltc',updated=ticker.updated,server_time=ticker.server_time,buy=ticker.buy,sell=ticker.sell) #print out_list #now we have a huge list with all the info, write to a single line in the csv file line = ','.join((pair,str(time.mktime(time.localtime())),str(curTrades.buy)))+'\n' #print line f.write(line)
def getPrice(connection,f,pair="btc_usd"): #get ticker ticker = btceapi.getTicker(pair, connection) #print ticker.high #get asks/bids asks, bids = btceapi.getDepth(pair) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) #start list with all of the ticker info curTrades = trades(coin='ltc',updated=ticker.updated,server_time=ticker.server_time,buy=ticker.buy,sell=ticker.sell) #print out_list #now we have a huge list with all the info, write to a single line in the csv file print pair print curTrades.buy # Pickle class using protocol 0. pickle.dump(curTrades,f)
def GetDepth(self, pair, askLimit = 50, bidLimit = 50): if(not pair in self.btcePairs): return {} asks, bids = btceapi.getDepth(self.btcePairs[pair]) r = randint(0, 1) if r == 0: result = { \ 'ask' : [{ 'price' : (price / Decimal('2')), 'amount' : amount } for price, amount in asks[:askLimit]], \ 'bid' : [{ 'price' : price, 'amount' : amount } for price, amount in bids[:bidLimit]] \ } else: result = { \ 'ask' : [{ 'price' : price, 'amount' : amount } for price, amount in asks[:askLimit]], \ 'bid' : [{ 'price' : (price * Decimal('2')), 'amount' : amount } for price, amount in bids[:bidLimit]] \ } return result
def _runHandler(trade_handler): last_tid = False while trade_handler.running: conn = btceapi.BTCEConnection() loop_start = time.time() interval = trade_handler.collectionInterval p = trade_handler.type try: trade_handler.asks, trade_handler.bids = btceapi.getDepth(p, conn) except: print "getDepth Error" # Collect the set of handlers for which we should get trade history. try: tradeHistory = btceapi.getTradeHistory(p, conn) if tradeHistory[0].tid != last_tid: trade_handler.tradeHistory = tradeHistory last_tid = trade_handler.arrangePriceHistory(tradeHistory) except: print "getTradeHistory Error" conn.close() while trade_handler.running and time.time() - loop_start < interval: time.sleep(0.5)
def prices(self): """ Returns tuple of closest ask/bid prices (ask, bid) """ asks, bids = btceapi.getDepth(pair) return (asks[0][0], bids[0][0])
def getTopOfTheBook3(symbol): asks, bids = btceapi.getDepth(symbol) return (float(asks[2][0]), float(asks[0][1] + asks[1][1] + asks[2][1]), float(bids[2][0]), float(bids[0][1] + bids[1][1] + bids[2][1]))
key_file = sys.argv[1] handler = btceapi.KeyHandler(key_file, resaveOnDeletion=True) for key in handler.getKeys(): print "Computing value for key %s" % key # NOTE: In future versions, the handler argument will be required. conn = btceapi.BTCEConnection() t = btceapi.TradeAPI(key, handler=handler) try: r = t.getInfo(connection = conn) exchange_rates = {} for pair in btceapi.all_pairs: asks, bids = btceapi.getDepth(pair) exchange_rates[pair] = bids[0][0] btc_total = 0 for currency in btceapi.all_currencies: balance = getattr(r, "balance_" + currency) if currency is "btc": print "\t%s balance: %s" % (currency.upper(), balance) btc_total += balance else: pair = "%s_btc" % currency if pair in btceapi.all_pairs: btc_equiv = balance * exchange_rates[pair] else: pair = "btc_%s" % currency btc_equiv = balance / exchange_rates[pair]
def getDepth(pair): return btceapi.getDepth(pair, settings.connection)
def _runBot(bot): while bot.running: loop_start = time.time() # Collect the set of pairs for which we should get depth. depth_pairs = set() for handler, pairs in bot.depthHandlers: depth_pairs.update(pairs) # Get current depth depths = {} conn = btceapi.BTCEConnection() for p in depth_pairs: try: asks, bids = btceapi.getDepth(p, conn) depths[p] = (datetime.datetime.now(), asks, bids) except: bot.onDepthRetrievalError(p, traceback.format_exc()) # Collect the set of pairs for which we should get trade history. trade_history_pairs = set() for handler, pairs in bot.tradeHistoryHandlers: trade_history_pairs.update(pairs) trade_histories = {} for p in trade_history_pairs: try: trades = btceapi.getTradeHistory(p, conn) trade_histories[p] = (datetime.datetime.now(), trades) except: bot.onTradeHistoryRetrievalError(p, traceback.format_exc()) conn.close() for p, (t, asks, bids) in depths.items(): for handler, pairs in bot.depthHandlers: if p in pairs: try: handler(t, p, asks, bids) except: bot.onDepthHandlingError(p, handler, traceback.format_exc()) for p, (t, trades) in trade_histories.items(): # Merge new trades into the bot's history. bot.mergeTradeHistory(p, trades) # Provide full history to traders for handler, pairs in bot.tradeHistoryHandlers: if p in pairs: try: handler(t, p, bot.tradeHistoryItems[p]) except: bot.onTradeHistoryHandlingError( p, handler, traceback.format_exc()) # Tell all bots that have requested it that we're at the end # of an update loop. for handler in bot.loopEndHandlers: try: handler(datetime.datetime.now()) except: # TODO: refactor this somewhere t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("%s Error while calling loop end handler (%r): %s" % (t, handler, traceback.format_exc())) while bot.running and time.time() - loop_start < bot.collectionInterval: time.sleep(0.5) # Give traders and opportunity to do thread-specific cleanup. for t in bot.traders: t.onExit()
def _runBot(bot): while bot.running: sys.stdout.flush() loop_start = time.time() # Collect the set of pairs for which we should get depth. depthPairs = set() for handler, pairs in bot.depthHandlers: depthPairs.update(pairs) # Get current depth depths = {} conn = btceapi.BTCEConnection() for p in depthPairs: try: asks, bids = btceapi.getDepth(p, conn) depths[p] = (datetime.datetime.now(), asks, bids) except: bot.onDepthRetrievalError(p, traceback.format_exc()) # Collect the set of pairs for which we should get trade history. tradeHistoryPairs = set() for handler, pairs in bot.tradeHistoryHandlers: tradeHistoryPairs.update(pairs) tradeHistories = {} for p in tradeHistoryPairs: try: trades = btceapi.getTradeHistory(p, conn) tradeHistories[p] = (datetime.datetime.now(), trades) except: bot.onTradeHistoryRetrievalError(p, traceback.format_exc()) conn.close() for p, (t, asks, bids) in depths.items(): for handler, pairs in bot.depthHandlers: if p in pairs: try: handler(t, p, asks, bids) except: bot.onDepthHandlingError(p, handler, traceback.format_exc()) for p, (t, trades) in tradeHistories.items(): # Merge new trades into the bot's history. bot.mergeTradeHistory(p, trades) # Provide full history to traders for handler, pairs in bot.tradeHistoryHandlers: if p in pairs: try: handler(t, p, bot.tradeHistoryItems[p]) except: bot.onTradeHistoryHandlingError(p, handler, traceback.format_exc()) # Tell all bots that have requested it that we're at the end # of an update loop. for handler in bot.loopEndHandlers: try: handler(datetime.datetime.now()) except: # TODO: refactor this somewhere t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) logging.debug("%s Error while calling loop end handler (%r): %s" % (t, handler, traceback.format_exc())) while bot.running and time.time() - loop_start < bot.collectionInterval: time.sleep(0.5) # Give traders and opportunity to do thread-specific cleanup. for t in bot.traders: t.onExit()
#!/usr/bin/python import sys import pylab import numpy as np import btceapi # If an argument is provided to this script, it will be interpreted # as a currency pair for which depth should be displayed. Otherwise # the BTC/USD depth will be displayed. if len(sys.argv) >= 2: pair = sys.argv[1] print("Showing depth for %s" % pair) else: print("No currency pair provided, defaulting to btc_usd") pair = "btc_usd" asks, bids = btceapi.getDepth(pair) print(len(asks), len(bids)) ask_prices, ask_volumes = zip(*asks) bid_prices, bid_volumes = zip(*bids) pylab.plot(ask_prices, np.cumsum(ask_volumes), 'r-') pylab.plot(bid_prices, np.cumsum(bid_volumes), 'g-') pylab.grid() pylab.title("%s depth" % pair) pylab.show()
def showAccountInfo(self, keyfile): ''' Show account info such as balance and total value of wallet ''' handler = btceapi.KeyHandler(keyfile, resaveOnDeletion=True) for key in handler.getKeys(): # print "Printing info for key %s" % key conn = btceapi.BTCEConnection() t = btceapi.TradeAPI(key, handler=handler) try: r = t.getInfo(connection = conn) print "\t*************" for currency in btceapi.all_currencies: balance = getattr(r, "balance_" + currency) if balance != 0: print "\t%s balance: %s" % (currency.upper(), balance) # print "\tInformation rights: %r" % r.info_rights # print "\tTrading rights: %r" % r.trade_rights # print "\tWithrawal rights: %r" % r.withdraw_rights print "\tServer time: %r" % str(r.server_time) #compute estimated account value too exchange_rates = {} for pair in btceapi.all_pairs: asks, bids = btceapi.getDepth(pair) exchange_rates[pair] = bids[0][0] btc_total = 0 for currency in btceapi.all_currencies: balance = getattr(r, "balance_" + currency) if currency == "btc": # print "\t%s balance: %s" % (currency.upper(), balance) btc_total += balance else: pair = "%s_btc" % currency if pair in btceapi.all_pairs: btc_equiv = balance * exchange_rates[pair] else: pair = "btc_%s" % currency btc_equiv = balance / exchange_rates[pair] bal_str = btceapi.formatCurrency(balance, pair) btc_str = btceapi.formatCurrency(btc_equiv, "btc_usd") #print "\t%s balance: %s (~%s BTC)" % (currency.upper(), bal_str, btc_str) btc_total += btc_equiv #print "\tCurrent value of open orders:" orders = t.activeOrders(connection = conn) if orders: for o in orders: btc_equiv = o.amount * exchange_rates[o.pair] btc_str = btceapi.formatCurrency(btc_equiv, pair) print "\t\t%s %s %s @ %s (~%s BTC)" % (o.type, o.amount, o.pair, o.rate, btc_str) btc_total += btc_equiv else: print "\t\tThere are no open orders." btc_str = btceapi.formatCurrency(btc_total, "btc_eur") print "\tTotal estimated value: %s BTC" % btc_str # for fiat in ("eur"): fiat_pair = "btc_%s" % "eur" fiat_total = btc_total * exchange_rates[fiat_pair] fiat_str = btceapi.formatCurrencyDigits(fiat_total, 2) print "\t %s EUR" % fiat_str print "\t*************" #print "\tItems in transaction history: %r" % r.transaction_count except: print " An error occurred: kakzooi" raise
buy_flag = False delta = 0 adjust = 0.99999 conn.close() while True: ask_list = [] price_list = [] if counter == sample_rate: counter = 0 print "counter has zeroed" print "delta list is: %s" % DeltaList try: conn = btceapi.BTCEConnection() tradeHistory = btceapi.getTradeHistory(pair, conn) available = getattr(api.getInfo(conn), "balance_usd") asks, bids = btceapi.getDepth("btc_usd", conn) for ask in asks: ask_list.append(ask[0]) for i in range(int(1.5 * sample_rate)): price_list.append(tradeHistory[i].price) last_mean = mean mean = numpy.mean(ask_list) except: print "error getDepth" pass conn.close() try: DeltaList[counter] = float(mean - last_mean) filtered_delta = filter(lambda x: x != 0, DeltaList) delta = numpy.mean(filtered_delta) except: