def collect_data(wait=60): #initialize connection connection = btceapi.BTCEConnection() while 1: btc_usd_f = open('/media/Big Daddy/New_Documents/python/python_projects/trading/data/btc_usd_depth.pkl', 'ab') ltc_btc_f = open('/media/Big Daddy/New_Documents/python/python_projects/trading/data/ltc_btc_depth.pkl', 'ab') ltc_usd_f = open('/media/Big Daddy/New_Documents/python/python_projects/trading/data/ltc_usd_depth.pkl', 'ab') try: getPrice(connection,btc_usd_f,'btc_usd') #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() try: getPrice(connection,ltc_btc_f,'ltc_btc') #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() try: getPrice(connection,ltc_usd_f,'ltc_usd') #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() print 'done loop' btc_usd_f.close() ltc_btc_f.close() ltc_usd_f.close() #sleep for .5 seconds, i.e. collect at 2Hz time.sleep(wait)
def collect_data(wait=60): # infinite loop while 1: # Keep a running list of everything btc_usd_f = open('data/btc_usd_btce.txt', 'a') ltc_btc_f = open('data/ltc_usd_btce.txt', 'a') ltc_usd_f = open('data/ltc_btc_btce.txt', 'a') # Temporary files for loading into observers btc_usd_tmp = open('data/btc_usd_btce.tmp', 'w') ltc_btc_tmp = open('data/ltc_usd_btce.tmp', 'w') ltc_usd_tmp = open('data/ltc_btc_btce.tmp', 'w') #initialize connection connection = btceapi.BTCEConnection() try: getPrice(connection, btc_usd_f, btc_usd_tmp, 'btc_usd') #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: print 'BTC problemo' connection = btceapi.BTCEConnection() try: getPrice(connection, ltc_btc_f, ltc_btc_tmp, 'ltc_btc') #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: print 'ltc-btc problem' connection = btceapi.BTCEConnection() try: getPrice(connection, ltc_usd_f, ltc_usd_tmp, 'ltc_usd') #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: print 'ltc-usd problem' connection = btceapi.BTCEConnection() #print 'done loop' # Close everything in between runs so that there are # no issues with simultaneous read/write btc_usd_f.close() ltc_btc_f.close() ltc_usd_f.close() btc_usd_tmp.close() ltc_usd_tmp.close() ltc_btc_tmp.close() #sleep for X seconds time.sleep(wait)
def run(database_path): conn = btceapi.BTCEConnection() api = btceapi.APIInfo(conn) #logger = MarketDataLogger(api.pair_names, database_path) logger = MarketDataLogger(api, ("btc_usd", "ltc_usd"), database_path) # Create a bot and add the logger to it. bot = btcebot.Bot(api) bot.addTrader(logger) # Add an error handler so we can print info about any failures bot.addErrorHandler(onBotError) # The bot will provide the logger with updated information every # 60 seconds. bot.setCollectionInterval(60) bot.start() print "Running; press Ctrl-C to stop" try: while 1: # you can do anything else you prefer in this loop while # the bot is running in the background time.sleep(3600) except KeyboardInterrupt: print "Stopping..." finally: bot.stop()
def call_active_orders(self, req): res = active_orders_allResponse() for key in self.handler.getKeys(): t = btceapi.TradeAPI(key, self.handler) try: orders = t.activeOrders(connection=self.conn) if orders: for o in orders: msg = active_orders() msg.order_id = int(o.order_id) msg.type = o.type.encode('ascii') msg.pair = o.pair.encode('ascii') msg.rate = float(o.rate) msg.amount = float(o.amount) msg.timestamp_created = o.timestamp_created.strftime( "%Y-%m-%d %H:%M:%S") msg.status = int(o.status) res.orders.append(msg) else: print "\t\tno orders" except Exception as e: print " An error occurred: %s" % e rospy.sleep(5.0) self.conn = btceapi.BTCEConnection() pass return res
def __init__(self): #get params #TODO: make this a param self.key_file = "/home/bob/Documents/btce_bot/trade_api.key" self.handler = btceapi.KeyHandler(self.key_file, resaveOnDeletion=True) self.conn = btceapi.BTCEConnection() self.topic_names_init = False self.topics = deque([]) # self.msg = get_info() #intiate a bunch of services get_info_service = rospy.Service('get_info_service', get_info_all, self.call_get_info) trans_history_service = rospy.Service('trans_history_service', trans_history_all, self.call_trans_history) active_orders_service = rospy.Service('active_orders_service', active_orders_all, self.call_active_orders) cancel_order_service = rospy.Service('cancel_order_service', cancel_order, self.call_cancel_order) make_trade_service = rospy.Service('make_trade_service', make_trade, self.call_make_trade) #trade_history_service = rospy.Service('trade_history_service', trade_history_all, self.call_trade_history) rospy.spin()
def _ticker_loop(bot): while bot.running: loop_start = time.time() conn = btceapi.BTCEConnection() ticker_pairs = set() for handler, pairs in bot.tickerHandlers: ticker_pairs.update(pairs) ticks = {} for p in ticker_pairs: try: response = btceapi.getTicker(p, conn) ticks[p] = (datetime.datetime.now(), response) except: bot.onTickerRetrievalError(p, traceback.format_exc()) for p, (t, ticker) in ticks.items(): for handler, pairs in bot.tickerHandlers: if p in pairs: try: handler(t, p, ticker) except: bot.onTickerHandlingError(p, handler, traceback.format_exc()) while bot.running and time.time() - loop_start < bot.tickerInterval: time.sleep(0.1)
def test_getTicker(self): connection = btceapi.BTCEConnection() info = btceapi.APIInfo(connection) for pair in info.pair_names: btceapi.getTicker(pair, connection, info) btceapi.getTicker(pair, connection) btceapi.getTicker(pair, info=info) btceapi.getTicker(pair)
def calc(bot, trigger): # price import btceapi try: connection = btceapi.BTCEConnection() ticker = btceapi.getTicker("ltc_usd", connection) last = getattr(ticker, "last") avg = getattr(ticker, "avg") # diff and block count content = urllib2.urlopen( "http://litecoinscout.com/chain/Litecoin/q/nethash/1/-1") data = content.readlines()[-1].split(",") diff = float(data[4]) blockscount = float(data[0]) except: say_string = "Either litecoinscount.com or BTC-e is ignoring my requests. Wait a few and try again." bot.say(say_string) return # grab intended hash rate parms = trigger.group(2) parms = parms.split("@") try: hashrate = int(parms[0]) * 1000 except: hashrate = 1000 * 1000 # 1000KH/s try: diff = int(parms[1]) except: pass # do the math target = 0x00000000ffff0000000000000000000000000000000000000000000000000000 / diff time_per_block = math.pow(2, 256) / (target * hashrate) secsinyear = 86400 * 365 time_per_block = math.pow(2, 256) / (target * hashrate) coinsperblock = 50.0 / (2**int((blockscount + 1) / 840000)) revenue = secsinyear / time_per_block * coinsperblock # clean up and convert yrrevenue = revenue yrinusdollars = int(revenue) * last # print say_string = "Calculating return with %sKH/s with %s difficulty using last trade of LTC: US$%s | US$%s/yr (%s LTC) | US$%s/month (%s LTC) | US$%s/week (%s LTC) | US$%s/day (%s LTC) | This calculation brought to you by kordless: BF4 promo codes for 2 LTC: http://goo.gl/zRrmTT" % ( hashrate / 1000, diff, round(last, 2), round( yrinusdollars, 2), round(yrrevenue, 4), round( yrinusdollars / 12, 2), round(yrrevenue / 12, 4), round(yrinusdollars / 52, 2), round(yrrevenue / 52, 4), round(yrinusdollars / 365, 2), round(yrrevenue / 365, 4)) if hashrate / 1000 > 100000: say_string = "Mules gives %s a blank stare." % trigger.nick bot.say(say_string)
def __init__(self, keyfile): keyfile = os.path.abspath(keyfile) self.keyhandler = btceapi.KeyHandler(keyfile) key = self.keyhandler.getKeys()[0] self.conn = btceapi.BTCEConnection() self.api = btceapi.TradeAPI(key, self.keyhandler) super(BTCE, self).__init__() self.name = 'BTCE' self.trading_fee = 0.002
def _log(self, price, amount): conn = btceapi.BTCEConnection() info = self.api.getInfo(conn) curr1, curr2 = self.pair.split("_") # Limit order to what we can afford to buy. available = getattr(info, "balance_" + curr2) max_buy = available / price logging.debug("available=%s, max_buy=%s\n" % (available, max_buy))
def ticker(bot, trigger): import btceapi connection = btceapi.BTCEConnection() ticker = btceapi.getTicker("ltc_usd", connection) avg = getattr(ticker, "avg") last = getattr(ticker, "last") vol = getattr(ticker, "vol_cur") say_string = "LTC/USD Average: $%s | LTC/USD Last Trade: $%s | Current LTC/USD Volume: %s | via http://btc-e.com" % ( avg, last, vol) bot.say(say_string)
def pub_ticker(): rospy.init_node('ticker_publisher_node') trade_pair = rospy.get_param('~trade_pair', 'btc_usd') topic_name = 'ticker_' + trade_pair pub = rospy.Publisher(topic_name, ticker) #attrs = ('high', 'low', 'avg', 'vol', 'vol_cur', 'last', # 'buy', 'sell', 'updated', 'server_time') #make persistent connection so it doesn't have to every request connection = btceapi.BTCEConnection() #create empty ticker message msg = ticker() #while ROs is still running, publish ticker data while not rospy.is_shutdown(): try: ticker_ = btceapi.getTicker(trade_pair, connection) except: rospy.sleep(1.0) connection = btceapi.BTCEConnection() pass msg.header.stamp = rospy.Time.now() msg.trade_pair = trade_pair msg.high = ticker_.high msg.low = ticker_.low msg.avg = ticker_.avg msg.vol = ticker_.vol msg.vol_cur = ticker_.vol_cur msg.last = ticker_.last msg.buy = ticker_.buy msg.sell = ticker_.sell msg.updated = "%s" % ticker_.updated msg.server_time = "%s" % ticker_.server_time pub.publish(msg) rospy.sleep(1.0)
def call_cancel_order(self, req): res = cancel_orderResponse() for key in self.handler.getKeys(): t = btceapi.TradeAPI(key, self.handler) try: t.cancelOrder(req.order_id) res.completed = True except Exception as e: res.completed = False print " An error occurred: %s" % e rospy.sleep(5.0) self.conn = btceapi.BTCEConnection() pass return res
def __init__(self, keypath): keyfile = os.path.abspath(keypath) self.keyhandler = btceapi.KeyHandler(keyfile) key = self.keyhandler.getKeys()[0] self.conn = btceapi.BTCEConnection() self.api = btceapi.TradeAPI(key, self.keyhandler) self.name = 'BTCE' self.trading_fee = 0.002 # The fee is 0.2% for all pairs, maker and taker self.bid_fee = self.trading_fee self.ask_fee = self.trading_fee self.tradeable_pairs = self.get_tradeable_pairs() self.minimum_amount = {} self.decimal_places = {} self.get_info()
def call_make_trade(self, req): res = make_tradeResponse() for key in self.handler.getKeys(): t = btceapi.TradeAPI(key, self.handler) try: r = t.trade(req.pair, req.buy_or_sell, req.price, req.amount, self.conn) res.order_id = r.order_id res.received = r.received except Exception as e: print " An error occurred: %s" % e rospy.sleep(5.0) self.conn = btceapi.BTCEConnection() pass return res
def _attemptBuy(self, price, amount): conn = btceapi.BTCEConnection() info = self.api.getInfo(conn) curr1, curr2 = self.type.split("_") # Limit order to what we can afford to buy. available = float(getattr(info, "balance_" + curr2)) max_buy = available / price buy_amount = min(max_buy, amount) * self.fee_adjustment print "attempting to buy %s %s at %s for %s %s" % ( buy_amount, curr1.upper(), price, buy_amount * price, curr2.upper()) r = self.api.trade(self.type, "buy", price, str(buy_amount), conn) print "\tReceived %s %s" % (r.received, curr1.upper()) # If the order didn't fill completely, cancel the remaining order if r.order_id != 0: print "\tCanceling unfilled portion of order" self.api.cancelOrder(r.order_id, conn) conn.close()
def _attemptSell(self, price, amount): conn = btceapi.BTCEConnection() info = self.api.getInfo(conn) curr1, curr2 = self.pair.split("_") # Limit order to what we have available to sell. available = getattr(info, "balance_" + curr1) sell_amount = min(available, amount) * self.fee_adjustment if sell_amount >= btceapi.min_orders[self.pair]: logging.debug("attempting to sell %s %s at %s for %s %s" % (sell_amount, curr1.upper(), price, sell_amount*price, curr2.upper())) if self.live_trades: r = self.api.trade(self.pair, "sell", price, sell_amount, conn) logging.debug("\tReceived %s %s" % (r.received, curr2.upper())) # If the order didn't fill completely, cancel the remaining order if r.order_id != 0: logging.debug("\tCanceling unfilled portion of order") self.api.cancelOrder(r.order_id, conn)
def test_scrape_main_page(self): with btceapi.BTCEConnection() as connection: info = btceapi.APIInfo(connection) mainPage = info.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str)
def _attemptSell(price): conn = btceapi.BTCEConnection() try: info = api.getInfo(conn) # Limit order to what we have available to sell. available = float(getattr(info, "balance_btc")) r = api.trade(pair, "sell", price, available, conn) # If the order didn't fill completely, cancel the remaining order if r.order_id != 0: print "\tCanceling unfilled portion of order" api.cancelOrder(r.order_id, conn) conn.close() raise Exception('sell failure') except: "print sell failed" conn.close() raise Exception('sell failure') print "\tSold %s at %s" % (r.received, price) conn.close()
def call_get_info(self, req): res = get_info_allResponse() for key in self.handler.getKeys(): # NOTE: In future versions, the handler argument will be required. t = btceapi.TradeAPI(key, handler=self.handler) try: r = t.getInfo(connection=self.conn) res.transaction_count = r.transaction_count res.open_orders = r.open_orders res.server_time = r.server_time.strftime("%Y-%m-%d %H:%M:%S") counter = 0 for currency in btceapi.all_currencies: msg = get_info() if (self.topic_names_init == False): topic_name = 'trade_interface/get_info/' + currency self.topics.append( rospy.Publisher(topic_name, get_info)) balance = getattr(r, "balance_" + currency) msg.coin = currency msg.balance = balance #msg.server_time = r.server_time.strftime("%Y-%m-%d %H:%M:%S") res.info.append(msg) counter = counter + 1 self.topic_names_init = True except Exception as e: print " An error occurred: %s" % e rospy.sleep(5.0) self.conn = btceapi.BTCEConnection() pass return res
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 _attemptBuy(price): conn = btceapi.BTCEConnection() try: info = api.getInfo(conn) # Limit order to what we can afford to buy. available = float(getattr(info, "balance_usd")) buy_amount = available / price print "attempting to buy %s bitcoin at %s for %s" % ( buy_amount, price, buy_amount * price) r = api.trade(pair, "buy", price, buy_amount, conn) # If the order didn't fill completely, cancel the remaining order if r.order_id != 0: print "\tCanceling unfilled portion of order" api.cancelOrder(r.order_id, conn) conn.close() raise Exception('buy failure') except: print "error buying" conn.close() raise Exception('buy failure') pass print "\tReceived %s bits" % (r.received) conn.close()
#!/usr/bin/python import sys import btceapi if len(sys.argv) < 2: print "Usage: compute-account-value.py <key file>" print " key file - Path to a file containing key/secret/nonce data" sys.exit(1) key_file = sys.argv[1] with btceapi.KeyHandler(key_file, resaveOnDeletion=True) as handler: 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) 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 == "btc": print "\t%s balance: %s" % (currency.upper(), balance)
def setUp(self): self.connection = btceapi.BTCEConnection()
def setUp(self): self.key_handler = btceapi.KeyHandler(TEST_KEY_FILE) self.connection = btceapi.BTCEConnection()
#!/usr/bin/env python import btceapi with btceapi.BTCEConnection() as connection: info = btceapi.APIInfo(connection) print("Server time: %s" % info.server_time) print("Active currencies:") for curr in info.currencies: print(" %s" % curr) print("Active trading pairs:") for name in info.pair_names: data = info.pairs[name] print(" %s" % name) print(" decimal places: %s" % data.decimal_places) print(" min price: %s" % data.min_price) print(" max price: %s" % data.max_price) print(" min amount: %s" % data.min_amount) print(" hidden: %s" % data.hidden) print(" fee: %s" % data.fee)
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()