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 _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 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 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 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 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 init_pairs_rates(self): ''' Returns list of tuples containing (pair <string>, rate <float>)''' try: pairs_rates = [] for pair in btceapi.all_pairs: rate = btceapi.getTicker(pair).avg pairs_rates.append((pair, rate)) return pairs_rates except Exception, e: print "Could not produce pairs rates: %s" % e raise
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 printTicker(self, pair, attrs): '''Modular print, prints all ticker values of one pair .. and saves them in a list of size 'listlength' ''' print "*****************************************************" connection = btceapi.BTCEConnection() ticker = btceapi.getTicker(pair, connection) #currently only checking 1 pair print pair #for a in attrs: currently disabled because only checking 1 pair atm value = ticker.last print "\t%s %s" % (attrs, value) #fill list with found last value of pair self.lastValuesltcbtc.append(value) #iteration count to show how many checks have been done(will be used later) self.iteration = self.iteration+1 connection.close()
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 collect_data(): while DATA_COLLECT: ticker = btceapi.getTicker("ppc_usd") data = { 'high': float(ticker.high), 'low' : float(ticker.low), 'avg' : float(ticker.avg), 'last': float(ticker.last), 'time' : str(ticker.server_time) } data = [float(ticker.high),float(ticker.low),float(ticker.avg),float(ticker.last),str(ticker.server_time)] print 'collect_data is writing to file' fd = open('tickers.csv', 'a') #fd.write("hello bye hello bye hello") writer = csv.writer(fd) writer.writerow(data) #writer.writerow("hello bye hello bye hello") fd.close() time.sleep(10)
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 calcAvgPrice(self, pair, buy_margin, sell_margin, alfa=0.994, beta=1, lastMinutes=60, count =150 ): if not(singleMode): print_trade_history(self, self.api, pair) buy_margin, sell_margin = (int(buy_margin), int(sell_margin)) avg_price, licznik, mianownik, volume=(0,0,0,0) ile=count dlugosc=0 nowStart= self._now() freshHistory = btceapi.getTradeHistory(pair, None, count) freshHistory = filter(lambda x: nowStart - x.__getstate__()["date"]<timedelta(minutes=lastMinutes), freshHistory) if freshHistory: lastFreshRecord = freshHistory[-1].__getstate__() self.history = filter(lambda x: nowStart - x.__getstate__()["date"]<timedelta(minutes=lastMinutes), self.history) self.history = filter(lambda x: lastFreshRecord["date"] - x.__getstate__()["date"] > timedelta(minutes=0), self.history) self.history = freshHistory+self.history if self.history: q=self.history[-1].__getstate__() ost_date=q["date"] else: print "no history available" self.live_trades=False range = truncate((nowStart - ost_date).total_seconds()/60,0) if (range < lastMinutes/8) or not(self.history) or self.fatalError: self.live_trades=False iPrint( "No trades! range: " , range ,"<", lastMinutes, "div 8!", "error:",self.fatalError) iPrint("%"*30) else: self.live_trades=True now= self._now() for h in self.history: q=h.__getstate__() if (now-q["date"])>=timedelta(minutes=0): wspolczynnik = self.alfas[alfa,int((now - q["date"]).total_seconds())] volume+=q["amount"] licznik+=q["price"]*q["amount"]*wspolczynnik mianownik+=q["amount"]*wspolczynnik avg_price = truncate(licznik/mianownik, 8) volume=truncate(volume, 2) VM_plus, VM_minus, size = vortex(10, 90, self.history, nowStart, alfa2) iPrint(VM_plus, VM_minus, size) if (VM_plus is not None) and (VM_minus is not None) and (size>5): future_factor = VM_plus - VM_minus else: future_factor=0 post_avg_prediction = predictAvg(avg_price, future_factor, 2) avg_price_backup = avg_price if abs(post_avg_prediction - avg_price)/avg_price < decimal.Decimal("0.02"): avg_price= post_avg_prediction else: print ("!"*50) print avg_price , post_avg_prediction, VM_plus, VM_minus, abs(post_avg_prediction - avg_price)/avg_price, decimal.Decimal("0.02") cancel_all_active_orders_of_pair(self.api, self.pair) self.fatalError=True self.live_trades=False print "fatalError" '''if abs(self.depthIndicator)<decimal.Decimal("0.004"): if self.depthIndicatorCount>0: bak=avg_price avg_price = avg_price*(1+ self.depthIndicator) print bak, "-->", avg_price else: print ("!"*50) cancel_all_active_orders_of_pair(self.api, self.pair) self.fatalError=True self.live_trades=False print "fatalError"''' iPrint( "alfa= ", alfa, len(self.history), "orders", range, "/", lastMinutes, "min. vol", volume, pair) iPrint( "AVG: ",avg_price_backup, "-->", avg_price ) iPrint(VM_plus, VM_minus, "-->" , future_factor) ###################### UWZGLEDNIA BETA CZYNNIK!!! ########################################### if (beta<1): ticker = btceapi.getTicker(pair, None) avg_price_ticker=truncate(getattr(ticker, 'avg'),8) avg_price= truncate(avg_price*beta + avg_price_ticker*(1-beta), 8) iPrint( "Beta" , beta) iPrint( "AVG:",avg_price) #avgVector+=[[avg_price, now]] buy_floor=truncate(avg_price*(100000-buy_margin)/100000, 6) sell_ceiling=truncate(avg_price*(100000+sell_margin)/100000, 6) iPrint( "low: ",buy_floor) iPrint( "AVG:",avg_price) iPrint( "high:", sell_ceiling) self.avg_price_calc_time = self._now() print "AVGbedzieRowne1", self.avg_price_calc_time self.depthIndicator, self.depthIndicatorCount = 0,0 return (buy_floor, avg_price, sell_ceiling)
#!/usr/bin/env python import btceapi attrs = ('high', 'low', 'avg', 'vol', 'vol_cur', 'last', 'buy', 'sell', 'updated') print("Tickers:") connection = btceapi.BTCEConnection() info = btceapi.APIInfo(connection) for pair in info.pair_names: ticker = btceapi.getTicker(pair, connection) print(pair) for a in attrs: print("\t%s %s" % (a, getattr(ticker, a)))
#!/usr/bin/python import btceapi attrs = ('high', 'low', 'avg', 'vol', 'vol_cur', 'last', 'buy', 'sell', 'updated', 'server_time') print "Tickers:" connection = btceapi.BTCEConnection() for pair in btceapi.all_pairs: ticker = btceapi.getTicker(pair, connection) print pair for a in attrs: print "\t%s %s" % (a, getattr(ticker, a))
def loadData(dataPath = '/media/Big Daddy/New_Documents/python_data/btc_usd_depth.pkl',num=None): i = 0 historical = open(dataPath,'rb') full_data = [] while True: try: if num != None and i > num: break current = pickle.load(historical) full_data.append(current) i = i+1 except EOFError: print 'Done Loading.' break except: print 'Problem loading.' break return full_data x = loadData() import btceapi from collections import deque connection = btceapi.BTCEConnection() ticker = btceapi.getTicker("btc_usd", connection)
def getTicker(pair): return btceapi.getTicker(pair, settings.connection)
#!/usr/bin/python import btceapi attrs = ('high', 'low', 'avg', 'vol', 'vol_cur', 'last', 'buy', 'sell', 'updated', 'server_time') #print "Tickers:" tickers = {} connection = btceapi.BTCEConnection() for pair in btceapi.all_pairs: tickers[pair] = btceapi.getTicker(pair, connection) #print pair #for a in attrs: # print "\t%s %s" % (a, getattr(tickers[pair], a)) print "Sell/Buy Ratios" for pair in btceapi.all_pairs: selfloop = tickers[pair].sell / tickers[pair].buy print "%s: %s" % (pair, str(selfloop) ) selfloop = ( tickers['btc_usd'].sell / tickers['ltc_usd'].buy ) * tickers['ltc_btc'].sell print "%s: %s" % ('btc->usd->ltc->btc', str(selfloop) ) selfloop = ( ( 1 / tickers['ltc_btc'].buy ) * tickers['ltc_usd'].sell ) / tickers['btc_usd'].buy print "%s: %s" % ('btc->ltc->usd->btc', str(selfloop) )
def calcAvgPrice(self, pair, buy_margin, sell_margin, alfa=0.994, beta=1, lastMinutes=60, count=150): if not (singleMode): print_trade_history(self, self.api, pair) buy_margin, sell_margin = (int(buy_margin), int(sell_margin)) avg_price, licznik, mianownik, volume = (0, 0, 0, 0) ile = count dlugosc = 0 nowStart = self._now() freshHistory = btceapi.getTradeHistory(pair, None, count) freshHistory = filter( lambda x: nowStart - x.__getstate__()["date"] < timedelta( minutes=lastMinutes), freshHistory) if freshHistory: lastFreshRecord = freshHistory[-1].__getstate__() self.history = filter( lambda x: nowStart - x.__getstate__()["date"] < timedelta( minutes=lastMinutes), self.history) self.history = filter( lambda x: lastFreshRecord["date"] - x.__getstate__()["date"] > timedelta(minutes=0), self.history) self.history = freshHistory + self.history if self.history: q = self.history[-1].__getstate__() ost_date = q["date"] else: print "no history available" self.live_trades = False range = truncate((nowStart - ost_date).total_seconds() / 60, 0) if (range < lastMinutes / 8) or not (self.history) or self.fatalError: self.live_trades = False iPrint("No trades! range: ", range, "<", lastMinutes, "div 8!", "error:", self.fatalError) iPrint("%" * 30) else: self.live_trades = True now = self._now() for h in self.history: q = h.__getstate__() if (now - q["date"]) >= timedelta(minutes=0): wspolczynnik = self.alfas[alfa, int((now - q["date"]).total_seconds())] volume += q["amount"] licznik += q["price"] * q["amount"] * wspolczynnik mianownik += q["amount"] * wspolczynnik avg_price = truncate(licznik / mianownik, 8) volume = truncate(volume, 2) VM_plus, VM_minus, size = vortex(10, 90, self.history, nowStart, alfa2) iPrint(VM_plus, VM_minus, size) if (VM_plus is not None) and (VM_minus is not None) and (size > 5): future_factor = VM_plus - VM_minus else: future_factor = 0 post_avg_prediction = predictAvg(avg_price, future_factor, 2) avg_price_backup = avg_price if abs(post_avg_prediction - avg_price) / avg_price < decimal.Decimal("0.02"): avg_price = post_avg_prediction else: print("!" * 50) print avg_price, post_avg_prediction, VM_plus, VM_minus, abs( post_avg_prediction - avg_price) / avg_price, decimal.Decimal("0.02") cancel_all_active_orders_of_pair(self.api, self.pair) self.fatalError = True self.live_trades = False print "fatalError" '''if abs(self.depthIndicator)<decimal.Decimal("0.004"): if self.depthIndicatorCount>0: bak=avg_price avg_price = avg_price*(1+ self.depthIndicator) print bak, "-->", avg_price else: print ("!"*50) cancel_all_active_orders_of_pair(self.api, self.pair) self.fatalError=True self.live_trades=False print "fatalError"''' iPrint("alfa= ", alfa, len(self.history), "orders", range, "/", lastMinutes, "min. vol", volume, pair) iPrint("AVG: ", avg_price_backup, "-->", avg_price) iPrint(VM_plus, VM_minus, "-->", future_factor) ###################### UWZGLEDNIA BETA CZYNNIK!!! ########################################### if (beta < 1): ticker = btceapi.getTicker(pair, None) avg_price_ticker = truncate(getattr(ticker, 'avg'), 8) avg_price = truncate(avg_price * beta + avg_price_ticker * (1 - beta), 8) iPrint("Beta", beta) iPrint("AVG:", avg_price) #avgVector+=[[avg_price, now]] buy_floor = truncate(avg_price * (100000 - buy_margin) / 100000, 6) sell_ceiling = truncate(avg_price * (100000 + sell_margin) / 100000, 6) iPrint("low: ", buy_floor) iPrint("AVG:", avg_price) iPrint("high:", sell_ceiling) self.avg_price_calc_time = self._now() print "AVGbedzieRowne1", self.avg_price_calc_time self.depthIndicator, self.depthIndicatorCount = 0, 0 return (buy_floor, avg_price, sell_ceiling)
def get_pair(curr1='btc',curr2='usd'): connection = btceapi.BTCEConnection() ticker = btceapi.getTicker(curr1+'_'+curr2, connection) return BTCePair(float(ticker.buy),float(ticker.sell))
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)