def run(key_file, buy_floor, sell_ceiling, live_trades): # Load the keys and create an API object from the first one. handler = btceapi.KeyHandler(key_file) key = handler.getKeys()[0] print "Trading with key %s" % key api = btceapi.TradeAPI(key, handler) # Create a trader that handles LTC/USD trades in the given range. trader = RangeTrader(api, "ltc_usd", buy_floor, sell_ceiling, live_trades) # Create a bot and add the trader to it. bot = btcebot.Bot() bot.addTrader(trader) # Add an error handler so we can print info about any failures bot.addErrorHandler(onBotError) # The bot will provide the traders with updated information every # 15 seconds. bot.setCollectionInterval(15) 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 run(key_file, pair, buy_margin, sell_margin, logging, loggingTime, printing, live_trades, gamma, eraSec, alfa, beta, buyChunk, sellChunk, buyBudget, sellBudget, interval, lastMinutes, epsilonSize, singleMode): #Load the keys and create an API object from the first one. handler = btceapi.KeyHandler(key_file, resaveOnDeletion=True) key = handler.getKeys()[0] print "Trading with key %s" % key api = btceapi.TradeAPI(key, handler=handler) # Create a trader trader = RangeTrader(api, pair, buy_margin, sell_margin, logging, loggingTime, printing, live_trades, gamma, eraSec, alfa, beta, buyChunk, sellChunk, buyBudget, sellBudget, lastMinutes, epsilonSize, singleMode) # Create a bot and add the trader to it. bot = btcebot.Bot() bot.addTrader(trader) # Add an error handler so we can iPrint( info about any failures bot.addErrorHandler(onBotError) # The bot will provide the traders with updated information every # 15 seconds. bot.setCollectionInterval(interval) 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(96000) except KeyboardInterrupt: print "Stopping..." finally: bot.stop() cancel_all_active_orders_of_pair(api, pair)
def call_trans_history(self, req): res = trans_history_allResponse() for key in self.handler.getKeys(): t = btceapi.TradeAPI(key, handler=self.handler) try: th = t.transHistory() for h in th: msg = trans_history() msg.transaction_id = int(h.transaction_id) msg.type = int(h.type) msg.amount = float(h.amount) msg.currency = h.currency.encode('ascii') msg.desc = h.desc.encode('ascii', 'ignore') msg.status = int(h.status) msg.timestamp = h.timestamp.strftime("%Y-%m-%d %H:%M:%S") res.trans_hist_array.append(msg) except Exception as e: print " An error occurred: %s" % e print h.currency print h.desc rospy.sleep(5.0) #self.conn = btceapi.BTCEConnection() pass return res
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, keyfile, shared_data): self.handler = btceapi.KeyHandler(keyfile) try: self.key = self.handler.getKeys()[0] except IndexError: print( "Error: something's wrong with keyfile. Looks like it's empty") exit(1) self.api = btceapi.TradeAPI(self.key, self.handler) self.update_balance(prnt=True) # Trade all available money on the following condition if shared_data.trading_sum >= self.usd or shared_data.trading_sum <= 0: print("Trading all available money") self.trade_all = True else: self.trade_all = False # Check if we are able to trade at all with current sums if self.usd < shared_data.trading_sum \ and self.btc < self.min_amount("sell", shared_data.price): print("Not enough funds for real trading. Activating simulation") shared_data.real_trading = False else: # Define initial action. Buy has priority. # If enough USD if self.usd >= shared_data.trading_sum \ and self.usd >= self.min_amount("buy", shared_data.price): print("Looking to buy") self.next_action = "buy" # Else, if enough BTC - sell elif self.btc >= self.min_amount("sell", shared_data.price): print("Looking to sell") self.next_action = "sell"
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 __init__(self, pair, key, collectionInterval=1, bufferSpanMinutes=10): self.bufferSpanMinutes = bufferSpanMinutes handler = btceapi.KeyHandler(key) key = handler.getKeys()[0] print "Trading with key %s" % key self.api = btceapi.TradeAPI(key, handler) self.type = pair self.fee_adjustment = 1 - float(btceapi.getTradeFee(self.type)) / 10 self.collectionInterval = collectionInterval self.running = False self.bidHistory = {} self.askHistory = {} self.asks = [] self.bids = []
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 trade(opportunity, max_volume, key_file, prices, volumes, tax): handler = btceapi.KeyHandler(key_file, resaveOnDeletion=True) volume = max_volume keys = handler.getKeys() key = keys[0] t = btceapi.TradeAPI(key, handler=handler) for operation in opportunity: pair = operation[1] price = float(prices[operation[0]][operation[1]]) if operation[0] == "bid": results = t.trade(pair, "sell", price, volume) volume *= price * tax if operation[0] == "ask": volume /= price results = t.trade(pair, "buy", price, volume) volume *= tax
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 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
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) btc_total += balance
key_file = sys.argv[1] pair = sys.argv[2] order_type = sys.argv[3] amount = decimal.Decimal(sys.argv[4]) price = decimal.Decimal(sys.argv[5]) with btceapi.KeyHandler(key_file) as handler: if not handler.keys: print("No keys in key file.") else: for key in handler.keys: print("Placing order for key {}".format(key)) with btceapi.BTCEConnection() as connection: t = btceapi.TradeAPI(key, handler, connection) try: result = t.trade(pair, order_type, price, amount) print("Trade result:") print(" received: {0}".format(result.received)) print(" remains: {0}".format(result.remains)) print(" order_id: {0}".format(result.order_id)) print(" funds:") for c, v in result.funds.items(): print(" {} {}".format(c, v)) except Exception as e: print(" An error occurred: {}".format(e))
def test_key_info(self): for key in self.key_handler.keys: t = btceapi.TradeAPI(key, self.key_handler, self.connection) r = t.getInfo()
def test_construction(self): keys = list(self.key_handler.keys) t = btceapi.TradeAPI(keys[0], self.key_handler, self.connection)
#NOTE: This is the original version of this script; it still runs with #version 0.2 of the API, but will produce lots of warnings. Please #see print-account-info-0.2.py to see recommended usage for that version. if len(sys.argv) < 2: print "Usage: print_account_info.py <key file>" print " key file - Path to a file containing key/secret/nonce data" sys.exit(1) key_file = sys.argv[1] handler = btceapi.KeyHandler(key_file) for key, (secret, nonce) in handler.keys.items(): print "Printing info for key %s" % key t = btceapi.TradeAPI(key, secret, nonce) try: r = t.getInfo() for d in dir(r): if d[:2] == '__': continue print " %s: %r" % (d, getattr(r, d)) except Exception as e: print " An error occurred: %s" % e # Give the next nonce to the handler so it can update the key file. handler.setNextNonce(key, t.next_nonce()) handler.save(key_file)
bal = acct.GetAvailableBalance(coin) price = acct.GetBuyPrice(coin, "BTC") * tradeMultiplier sell = acct.GetSellPrice(coin, "BTC") if price > sell and tradeMultiplierCheck == True: price = sell - 0.00000001 if price > 0: acct.CreateSellOrder(coin, "BTC", bal, price) return if enableBTCE: key_file = './key' handler = btceapi.KeyHandler(key_file) key = handler.keys.keys()[0] secret, nonce = handler.keys[handler.keys.keys()[0]] authedAPI = btceapi.TradeAPI(key, secret, nonce) # create http handler opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'CryptoSwitcher')] # disable extended status output (=> coin price and difficulty) by default. only # enable it, if at least one coins profitability is calculated by cryptoswitcher extout = False # main loop cnt_all = 0 while True: # print header print "\n\n\n<<< Round %d >>>" % (cnt_all + 1) print "time:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())