def calculate_amounts(self, coin_above_threshold, coin_below_threshold, percentage_btc_amount): """Calculate the amounts necessary to buy and sell.""" rebalance_special_ticker = coin_above_threshold + "/BTC" if coin_above_threshold == "BTC": rebalance_special_ticker = "BTC/USDT" rebalance_coin_ticker_model = DatabaseManager.get_ticker_model( rebalance_special_ticker) eligible_coin_ticker_model = DatabaseManager.get_ticker_model( coin_below_threshold + "/BTC") amount_to_sell = 0.0 amount_to_buy = 0.0 if coin_above_threshold == "BTC": amount_to_sell = percentage_btc_amount else: btc_val = rebalance_coin_ticker_model.BTCVal if btc_val is not None and btc_val > 0: amount_to_sell = percentage_btc_amount / btc_val if coin_below_threshold == "BTC": amount_to_buy = percentage_btc_amount else: btc_val = eligible_coin_ticker_model.BTCVal if btc_val is not None and btc_val > 0: amount_to_buy = percentage_btc_amount / btc_val return {"rebalance": amount_to_sell, "eligible": amount_to_buy}
def get_ticker(key): fullTicker = key.Ticker + "/BTC" if key.Ticker == 'BTC': fullTicker = 'BTC/USDT' return DatabaseManager.get_ticker_model(fullTicker)
def index_start_command(self): totalIndexPercentage = 0.0 indexInfo = DatabaseManager.get_index_info_model() indexCoins = DatabaseManager.get_all_index_coin_models() for coin in indexCoins: totalIndexPercentage = totalIndexPercentage + coin.DesiredPercentage if totalIndexPercentage == 100: for iCoin in indexCoins: if iCoin.Ticker != "BTC": coinTicker = DatabaseManager.get_ticker_model( iCoin.Ticker.upper() + "/BTC") sys.stdout.write(coinTicker) sys.stdout.write(iCoin.Ticker) sys.stdout.write('\n') percentage_btc_amount = (indexInfo.TotalBTCVal / 100) * iCoin.DesiredPercentage amountToBuy = percentage_btc_amount / coinTicker.BTCVal 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: #buy app.send_task('Tasks.perform_buy_task', args=[iCoin.Ticker.upper(), amountToBuy]) DatabaseManager.update_index_info_model( True, indexInfo.TotalBTCVal, indexInfo.TotalUSDVal, indexInfo.TotalRealizedGain, indexInfo.TotalUnrealizedGain, indexInfo.BalanceThreshold, indexInfo.OrderTimeout, indexInfo.OrderRetryAmount, indexInfo.RebalanceTickSetting) else: logger.warn("Index is currently unbalanced please rebuild")
def index_gen_command(self): totalIndexPercentage = 0.0 indexInfo = DatabaseManager.get_index_info_model() indexCoins = DatabaseManager.get_all_index_coin_models() for iCoin in indexCoins: if iCoin.Ticker != "BTC": coinTicker = DatabaseManager.get_ticker_model( iCoin.Ticker.upper() + "/BTC") percentage_btc_amount = (indexInfo.TotalBTCVal / 100) * iCoin.DesiredPercentage amountToBuy = percentage_btc_amount / coinTicker.BTCVal 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: #buy app.send_task('Tasks.perform_buy_task', args=[iCoin.Ticker.upper(), amountToBuy]) DatabaseManager.update_index_info_model(True, indexInfo.TotalBTCVal, indexInfo.TotalUSDVal, indexInfo.BalanceThreshold, indexInfo.OrderTimeout, indexInfo.OrderRetryAmount, indexInfo.RebalanceTickSetting)
def wallet_update_task(): em = ExchangeManager() walletData = em.get_balance() btcUsdValue = em.get_btc_usd_value() totalBtcValue = 0.0 logger.info("Starting Wallet Update Task") for key in DatabaseManager.get_all_supported_coin_models(): btcbalance = 0.0 usdBalance = 0.0 totalCoins = None fullTicker = key.Ticker + "/BTC" if key.Ticker == 'BTC': fullTicker = 'BTC/USDT' tickerModel = DatabaseManager.get_ticker_model(fullTicker) try: btcbalance = walletData[key.Ticker]['total'] * tickerModel.BTCVal totalCoins = walletData[key.Ticker]['total'] usdBalance = btcUsdValue * btcbalance except: btcbalance = 0.0 totalCoins = 0.0 if key.Ticker == 'BTC': btcbalance = walletData[key.Ticker]['total'] usdBalance = btcUsdValue * btcbalance indexedCoin = DatabaseManager.get_index_coin_model(key.Ticker) if indexedCoin is not None: totalBtcValue = totalBtcValue + btcbalance if DatabaseManager.create_coin_balance_model(key.Ticker, btcbalance, usdBalance, totalCoins, datetime.datetime.now()): #logger.debug("Created Coin Balance Model - " + key.Ticker) pass else: if DatabaseManager.update_coin_balance_model( key.Ticker, btcbalance, btcUsdValue * btcbalance, totalCoins, datetime.datetime.now()): #logger.debug("Updated Coin Balance Model - " + key.Ticker) pass else: logger.error("Failed Update Coin Balance Model - " + key.Ticker) totalUnrealizeGain = 0.0 totalRealizedGain = 0.0 for key in DatabaseManager.get_all_supported_coin_models(): coinBalance = DatabaseManager.get_coin_balance_model(key.Ticker) indexedCoin = DatabaseManager.get_index_coin_model(key.Ticker) realizedGainModel = DatabaseManager.get_realized_gain_model(key.Ticker) if indexedCoin is not None: if DatabaseManager.update_index_coin_model( indexedCoin.Ticker, indexedCoin.DesiredPercentage, (coinBalance.BTCBalance / totalBtcValue) * 100, ((coinBalance.BTCBalance / totalBtcValue) * 100) - indexedCoin.DesiredPercentage, indexedCoin.Locked): totalUnrealizeGain = totalUnrealizeGain + ( ((coinBalance.BTCBalance / totalBtcValue) * 100) - indexedCoin.DesiredPercentage) totalRealizedGain = totalRealizedGain + realizedGainModel.RealizedGain logger.debug("Total unrealized gain - " + str(totalUnrealizeGain)) logger.debug("Updated Indexed Coin Model - " + indexedCoin.Ticker) else: logger.error("Failed To Update Indexed Coin Model - " + indexedCoin.Ticker) indexInfo = DatabaseManager.get_index_info_model() totalUnrealizeGain = totalUnrealizeGain if DatabaseManager.update_index_info_model( indexInfo.Active, totalBtcValue, btcUsdValue * totalBtcValue, totalRealizedGain, totalUnrealizeGain, indexInfo.BalanceThreshold, indexInfo.OrderTimeout, indexInfo.OrderRetryAmount, indexInfo.RebalanceTickSetting): logger.debug("Updated Index Info Model") else: logger.error("Failed To Update Index Info Model") logger.info("Wallet Update Task Completed")
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_rebalance_task(rebalanceTicker, rebalanceSellAmount, elgibleTicker, elgibleBuyAmount): coinSellIncomplete = True coinBuyIncomplete = True coinSellRetryCount = 0 coinBuyRetryCount = 0 coinSellFailed = False sellOrderUUID = "" buyOrderUUID = "" indexInfo = DatabaseManager.get_index_info_model() retryLimit = indexInfo.OrderRetryAmount rebalanceTickerGainModel = DatabaseManager.get_realized_gain_model( rebalanceTicker) elgibleCoinTicker = DatabaseManager.get_ticker_model(elgibleTicker + "/BTC") em = ExchangeManager() partial_fill_amount = 0 partial_filled = False if rebalanceTicker != "BTC" and rebalanceTicker != "btc": 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 DatabaseManager.update_realized_gain_model( rebalanceTicker, rebalanceTickerGainModel.RealizedGain + ((order_filled_amount * rebalanceCoinTicker.BTCVal) / indexInfo.TotalBTCVal) * 100) 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 DatabaseManager.update_realized_gain_model( rebalanceTicker, rebalanceTickerGainModel.RealizedGain + ((order_filled_amount * rebalanceCoinTicker.BTCVal) / indexInfo.TotalBTCVal) * 100) 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 if coinSellFailed: logger.info("Sell of coin " + rebalanceTicker + " failed after " + str(coinSellRetryCount) + " attempts") else: 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)) if partial_filled == True: buyOrderUUID = em.create_buy_order( elgibleTicker, partial_fill_amount / elgibleCoinTicker.BTCVal, elgibleCoinTicker.BTCVal)['id'] else: 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 if rebalanceTicker == "BTC" or rebalanceTicker == "btc": DatabaseManager.update_realized_gain_model( rebalanceTicker, rebalanceTickerGainModel.RealizedGain + ((order_filled_amount * elgibleCoinTicker.BTCVal) / indexInfo.TotalBTCVal) * 100) 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 if rebalanceTicker == "BTC" or rebalanceTicker == "btc": DatabaseManager.update_realized_gain_model( rebalanceTicker, rebalanceTickerGainModel.RealizedGain + ((order_filled_amount * elgibleCoinTicker.BTCVal) / indexInfo.TotalBTCVal) * 100) 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(rebalanceTicker) 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)