def handle_trade(self, coin, amount, is_over, celery_app): """Send the appropriate celery message based on buy/sell.""" string_ticker = coin if coin == "BTC": string_ticker += "/USDT" else: string_ticker += "/BTC" if self.em.check_min_buy(amount, string_ticker): ticker = self.em.get_ticker(string_ticker) single_coin_cost = ticker["last"] num_coins = round(amount / single_coin_cost, 8) DatabaseManager.create_coin_lock_model(coin) DatabaseManager.create_wallet_trade_lock_model(coin) if is_over is True: logger.debug("selling %s", coin) celery_app.send_task('Tasks.perform_sell_task', args=[coin.upper(), num_coins]) else: logger.debug("buying %s", coin) celery_app.send_task('Tasks.perform_buy_task', args=[coin.upper(), num_coins]) else: logger.debug("purchase %s does not meet market minimum")
def handle_coin(self, coin_above_threshold, coin_below_threshold, percentage_btc_amount, celery_app): """Handle buying and selling these coins.""" logger.debug("Handling sell/buy for %s and %s", coin_above_threshold, coin_below_threshold) coin_balance = DatabaseManager.get_coin_balance_model( coin_above_threshold) amounts = self.calculate_amounts(coin_above_threshold, coin_below_threshold, percentage_btc_amount) amount_to_sell = amounts["rebalance"] amount_to_buy = amounts["eligible"] if coin_balance.TotalCoins >= amount_to_sell: if self.check_markets(coin_above_threshold, coin_below_threshold): DatabaseManager.create_coin_lock_model(coin_above_threshold) DatabaseManager.create_coin_lock_model(coin_below_threshold) logger.info("Performing Rebalance %s %s - %s %s", coin_above_threshold.upper(), amount_to_sell, coin_below_threshold.upper(), amount_to_buy) celery_app.send_task('Tasks.perform_rebalance_task', args=[ coin_above_threshold.upper(), amount_to_sell, coin_below_threshold.upper(), amount_to_buy ]) else: logger.error("Failed to sell coins - we do not have enough of %s", coin_above_threshold)
def perform_buy_task(elgibleTicker, elgibleBuyAmount): coinBuyIncomplete = True coinBuyRetryCount = 0 buyOrderUUID = "" indexInfo = DatabaseManager.get_index_info_model() retryLimit = indexInfo.OrderRetryAmount elgibleCoinTicker = DatabaseManager.get_ticker_model(elgibleTicker + "/BTC") em = ExchangeManager() partial_fill_amount = 0 partial_filled = False DatabaseManager.create_coin_lock_model(elgibleTicker) while coinBuyIncomplete: if coinBuyRetryCount >= retryLimit: coinBuyIncomplete = False logger.info("Buying of coin " + rebalanceTicker + " failed after " + str(coinBuyRetryCount) + " attempts") break # Cancel Order else: if CondexConfig.DEBUG == True: logger.debug("Putting in buy order") else: logger.info("Buying " + str(elgibleBuyAmount) + " of " + elgibleTicker + " at " + str(elgibleCoinTicker.BTCVal)) buyOrderUUID = em.create_buy_order( elgibleTicker, elgibleBuyAmount, elgibleCoinTicker.BTCVal)['id'] time.sleep(60 * indexInfo.OrderTimeout) # Check order succeded through if CondexConfig.DEBUG == True: logger.debug("Fetching order") coinBuyIncomplete = False else: order_result = em.fetch_order(buyOrderUUID) order_filled_amount = order_result['filled'] if order_result['status'] == "closed": logger.info("Bought coin " + elgibleTicker + " for " + str(order_result['price'])) coinBuyIncomplete = False elif ( order_filled_amount * elgibleCoinTicker.BTCVal ) > CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT and order_result[ 'status'] == "open": em.cancel_order(buyOrderUUID) logger.debug("Bought partial of coin " + elgibleCoinTicker + " for " + str(order_result['price'])) coinBuyIncomplete = False else: coinBuyRetryCount = coinBuyRetryCount + 1 if CondexConfig.DEBUG == True: logger.debug("Canceling buy order") else: try: em.cancel_order(buyOrderUUID) except: coinBuyIncomplete = False pass # order failed to cancel got filled previously logger.debug("Buy Order Timeout Reached") time.sleep(10) #Magic Number # Delete the locks if CondexConfig.DEBUG != True: DatabaseManager.delete_coin_lock_model(elgibleTicker)
def perform_algo_task(): coinsAboveThreshold = {} coinsElgibleForIncrease = {} indexInfo = DatabaseManager.get_index_info_model() if indexInfo.Active == True: percentage_btc_amount = indexInfo.TotalBTCVal * ( indexInfo.BalanceThreshold / 100) logger.debug("Percentage_to_btc_amount: " + str(percentage_btc_amount)) if percentage_btc_amount <= CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT: logger.debug("Current BTC Threshold Value To Low - " + str(percentage_btc_amount)) else: # Generate our winners/lossers list for indexedCoin in DatabaseManager.get_all_index_coin_models(): if indexedCoin.UnrealizedGain >= indexInfo.BalanceThreshold: coinsAboveThreshold[ indexedCoin.Ticker] = indexedCoin.UnrealizedGain elif indexedCoin.UnrealizedGain <= indexInfo.BalanceThreshold: coinsElgibleForIncrease[ indexedCoin.Ticker] = indexedCoin.UnrealizedGain # Sort our tables coinsAboveThreshold = Util.tuple_list_to_dict( sorted(coinsAboveThreshold.iteritems(), key=lambda (k, v): (v, k), reverse=True)) coinsElgibleForIncrease = Util.tuple_list_to_dict( sorted(coinsElgibleForIncrease.iteritems(), key=lambda (k, v): (v, k), reverse=True)) if len(coinsAboveThreshold) >= 1: logger.debug("Currently " + str(len(coinsAboveThreshold)) + " avalible for rebalance") logger.debug(coinsAboveThreshold) if len(coinsElgibleForIncrease) >= 1: logger.debug("Currently " + str(len(coinsElgibleForIncrease)) + " elgible for increase") logger.debug(coinsElgibleForIncrease) for akey in coinsAboveThreshold: # Check to see if we still have coins to increase if len(coinsElgibleForIncrease) >= 1: elgibleCoinTicker = coinsElgibleForIncrease.keys( )[0] rebalanceCoinLocked = False elgibleCoinLocked = False if DatabaseManager.get_coin_lock_model(akey): rebalanceCoinLocked = True if DatabaseManager.get_coin_lock_model( elgibleCoinTicker): rebalanceCoinLocked = True if rebalanceCoinLocked == False and elgibleCoinLocked == False: indexCoinInfo = DatabaseManager.get_index_coin_model( akey) coinBalance = DatabaseManager.get_coin_balance_model( akey) rebalanceSpecialTicker = akey + "/BTC" if akey == "BTC": rebalanceSpecialTicker = "BTC/USDT" rebalanceCoinTickerModel = DatabaseManager.get_ticker_model( rebalanceSpecialTicker) elgibleCoinTickerModel = DatabaseManager.get_ticker_model( elgibleCoinTicker + "/BTC") amountOfRebalanceToSell = 0.0 if akey == "BTC": amountOfRebalanceToSell = percentage_btc_amount else: amountOfRebalanceToSell = percentage_btc_amount / rebalanceCoinTickerModel.BTCVal amountOfEligbleToBuy = percentage_btc_amount / elgibleCoinTickerModel.BTCVal if coinBalance.TotalCoins >= amountOfRebalanceToSell: DatabaseManager.create_coin_lock_model( akey) DatabaseManager.create_coin_lock_model( elgibleCoinTicker) logger.info("Performing Rebalance " + akey.upper() + " " + str(amountOfRebalanceToSell) + " - " + elgibleCoinTicker.upper() + " " + str(amountOfEligbleToBuy)) #perform_rebalance_task.s(akey.upper(), amountOfRebalanceToSell, elgibleCoinTicker.upper(), amountOfEligbleToBuy) app.send_task( 'Tasks.perform_rebalance_task', args=[ akey.upper(), amountOfRebalanceToSell, elgibleCoinTicker.upper(), amountOfEligbleToBuy ]) # Need to remove the eligbile coin from dictireonary del coinsElgibleForIncrease[ elgibleCoinTicker] else: logger.error( "Failed to sell coins - we do not have enough of " + str(akey)) else: logger.debug("One of the coins where locked") else: logger.debug("No coins eligible for increase") else: logger.debug("No coins above threshold")
def perform_sell_task(rebalanceTicker, rebalanceSellAmount): coinSellIncomplete = True coinSellRetryCount = 0 sellOrderUUID = "" indexInfo = DatabaseManager.get_index_info_model() retryLimit = indexInfo.OrderRetryAmount eligibleCoinTicker = DatabaseManager.get_ticker_model(rebalanceTicker + "/BTC") em = ExchangeManager() try: partial_fill_amount = 0 partial_filled = False DatabaseManager.create_coin_lock_model(rebalanceTicker) while coinSellIncomplete: if coinSellRetryCount >= retryLimit: coinSellFailed = True coinSellIncomplete = False break # Cancel Order else: rebalanceCoinTicker = DatabaseManager.get_ticker_model( rebalanceTicker + "/BTC") if CondexConfig.DEBUG == True: logger.info("Placing Sell Order For " + rebalanceTicker + "/BTC") else: logger.info("Selling " + str(rebalanceSellAmount) + " of " + rebalanceTicker + " at " + str(rebalanceCoinTicker.BTCVal)) sellOrderUUID = em.create_sell_order( rebalanceTicker, rebalanceSellAmount, rebalanceCoinTicker.BTCVal)['id'] time.sleep(60 * indexInfo.OrderTimeout) # Check order succeded through if CondexConfig.DEBUG == True: logger.debug("Fetching order") coinSellIncomplete = False else: order_result = em.fetch_order(sellOrderUUID) order_filled_amount = order_result['filled'] if order_result['status'] == "closed": logger.debug("Sold coin " + rebalanceTicker + " for " + str(order_result['price'])) coinSellIncomplete = False elif ( order_filled_amount * rebalanceCoinTicker.BTCVal ) > CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT and order_result[ 'status'] == "open": em.cancel_order(sellOrderUUID) logger.debug("Sold partial of coin " + rebalanceTicker + " for " + str(order_result['price'])) coinSellIncomplete = False partial_filled = True partial_fill_amount = order_filled_amount * rebalanceCoinTicker.BTCVal else: coinSellRetryCount = coinSellRetryCount + 1 if CondexConfig.DEBUG == True: logger.debug("Canceling sell order") else: em.cancel_order(sellOrderUUID) logger.debug("Sell Order Timeout Reached") time.sleep(10) #Magic Number except Exception as e: logger.exception(e) finally: if CondexConfig.DEBUG != True: DatabaseManager.delete_coin_lock_model(rebalanceTicker)