def perform_algo_task(): balanceManager = BalanceManager() coinsAboveThreshold = {} coinsEligibleForIncrease = {} em = ExchangeManager() indexInfo = DatabaseManager.get_index_info_model() try: 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/losers list for indexedCoin in DatabaseManager.get_all_index_coin_models(): if indexedCoin.DistanceFromTarget >= indexInfo.BalanceThreshold: coinsAboveThreshold[indexedCoin.Ticker] = indexedCoin.DistanceFromTarget elif abs(indexedCoin.DistanceFromTarget) >= indexInfo.BalanceThreshold: coinsEligibleForIncrease[indexedCoin.Ticker] = indexedCoin.DistanceFromTarget # Sort our tables coinsAboveThreshold = Util.tuple_list_to_dict(sorted(coinsAboveThreshold.items(), key=lambda pair: pair[1], reverse=True)) coinsEligibleForIncrease = Util.tuple_list_to_dict(sorted(coinsEligibleForIncrease.items(), key=lambda pair: pair[1], reverse=True)) balanceManager.rebalance_coins(coinsAboveThreshold, coinsEligibleForIncrease, percentage_btc_amount, app) except Exception as e: logger.exception(e)
def index_equal_weight(self): """Set portfolio to equal weight""" totalPercentage = 0 totalLockedPercentage = 0.0 totalUnlockedPercentage = 100 totalUnlockedCoinsCount = 0 averagePercentage = 0 indexedCoins = DatabaseManager.get_all_index_coin_models() for inCoins in indexedCoins: if inCoins.Locked == True: totalLockedPercentage = totalLockedPercentage + inCoins.DesiredPercentage else: totalUnlockedCoinsCount = totalUnlockedCoinsCount + 1 totalPercentage = totalPercentage + totalLockedPercentage totalUnlockedPercentage = totalUnlockedPercentage - totalLockedPercentage averagePercentage = round( totalUnlockedPercentage / totalUnlockedCoinsCount, 2) logger.info("Setting default allocation to " + str(averagePercentage)) for inCoins in indexedCoins: if inCoins.Locked == False: totalPercentage = totalPercentage + averagePercentage if totalPercentage + averagePercentage > 100: desiredPercentage = 100 - totalPercentage else: desiredPercentage = averagePercentage DatabaseManager.update_index_coin_model( inCoins.Ticker, float(desiredPercentage), 0.0, False)
def index_add_coin(self, coin, percentage=1.0, locked=False): lockCoin = False totalLockedPercentage = 0.0 totalUnlockedPercentage = 0.0 totalUnlockedCoinsCount = 0 indexInfo = DatabaseManager.get_index_info_model() indexedCoins = DatabaseManager.get_all_index_coin_models() if locked == "true" or locked == "True": lockCoin = True for inCoins in indexedCoins: if inCoins.Locked == True: totalLockedPercentage = totalLockedPercentage + inCoins.DesiredPercentage else: totalUnlockedPercentage = totalUnlockedPercentage + inCoins.DesiredPercentage totalUnlockedCoinsCount = totalUnlockedCoinsCount + 1 if totalUnlockedPercentage > float(percentage): if self.coin_supported_check(coin.upper()): percentageToRemove = float( percentage) / totalUnlockedCoinsCount for iCoin in indexedCoins: if iCoin.Locked != True: DatabaseManager.update_index_coin_model( iCoin.Ticker, iCoin.DesiredPercentage - percentageToRemove, iCoin.DistanceFromTarget, iCoin.Locked) if isinstance(float(percentage), (float, int, complex, int)): if DatabaseManager.create_index_coin_model( coin.upper(), float(percentage), 0.0, lockCoin): logger.info("Coin " + coin.upper() + " added to index") else: # Already Exist logger.warn("Coin already in index") else: logger.warn("Percentage isn't a number") else: logger.warn("Coin not supported") else: logger.warn("Not Enough Unlocked Percentage")
def export_index(self): """Export the index to a JSON file.""" indexInfo = DatabaseManager.get_all_index_coin_models() indexJson = "[" coins = [] for coin in indexInfo: coins.append(jsonpickle.encode(coin)) indexJson += ",".join(coins) indexJson += "]" with open("index.json", "w") as file_object: file_object.write(indexJson) logger.info("Index exported to index.json")
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 import_index(self): """Destructively create the index from a JSON file.""" coins = DatabaseManager.get_all_index_coin_models() for coin in coins: DatabaseManager.delete_index_coin_model(coin.Ticker) indexed_coins = "" with open("index.json", "r") as file_obj: indexed_coins = jsonpickle.decode(file_obj.read()) for coin in indexed_coins: coin.DesiredPercentage = coin.DesiredPercentage if coin.DesiredPercentage is not None else 1 coin.Locked = coin.Locked if coin.Locked is not None else False # logger.debug('adding %s with percentage %s', coin.Ticker, coin.DesiredPercentage) DatabaseManager.create_index_coin_model(coin.Ticker, coin.DesiredPercentage, 0, coin.Locked) logger.info("Index imported from index.json")
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 index_update_coin(self, coin, percentage, locked): lockCoin = False totalLockedPercentage = 0.0 totalUnlockedPercentage = 0.0 totalUnlockedCoinsCount = 0 indexInfo = DatabaseManager.get_index_info_model() indexedCoins = DatabaseManager.get_all_index_coin_models() indexedCoin = DatabaseManager.get_index_coin_model(coin.upper()) for inCoins in indexedCoins: if inCoins.Ticker != coin.upper(): if inCoins.Locked == True: totalLockedPercentage = totalLockedPercentage + inCoins.DesiredPercentage else: totalUnlockedPercentage = totalUnlockedPercentage + inCoins.DesiredPercentage totalUnlockedCoinsCount = totalUnlockedCoinsCount + 1 if len(indexedCoins) > 1: if totalUnlockedCoinsCount > 0: if locked == "true" or locked == "True": lockCoin = True percentage_btc_amount = indexInfo.TotalBTCVal * ( float(percentage) / 100) if percentage_btc_amount >= CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT: if float(percentage) > indexedCoin.DesiredPercentage: if totalUnlockedPercentage > float(percentage): if self.coin_supported_check(coin.upper()): percentageToAdd = 0.0 if totalUnlockedCoinsCount > 0: percentageToAdd = float( indexedCoin.DesiredPercentage - float(percentage) ) / totalUnlockedCoinsCount else: percentageToAdd = float( indexedCoin.DesiredPercentage - float(percentage)) for iCoin in indexedCoins: if iCoin.Ticker != coin.upper(): if iCoin.Locked != True: DatabaseManager.update_index_coin_model( iCoin.Ticker, iCoin.DesiredPercentage - percentageToAdd, iCoin.DistanceFromTarget, iCoin.Locked) if isinstance(float(percentage), (float, int, complex, long)): if DatabaseManager.update_index_coin_model( coin.upper(), float(percentage), 0.0, lockCoin): logger.info("Coin " + coin.upper() + " updated in index") else: # Already Exist logger.warn("Coin already in index") else: logger.warn("Percentage isn't a number") else: logger.warn("Coin not supported") else: logger.warn("Not Enough Unlocked Percentage") else: ## NEW BLOCK if self.coin_supported_check(coin.upper()): percentageToAdd = 0.0 if totalUnlockedCoinsCount > 0: percentageToAdd = float( indexedCoin.DesiredPercentage - float( percentage)) / totalUnlockedCoinsCount else: percentageToAdd = float( indexedCoin.DesiredPercentage - float(percentage)) for iCoin in indexedCoins: if iCoin.Ticker != coin.upper(): if iCoin.Locked != True: DatabaseManager.update_index_coin_model( iCoin.Ticker, iCoin.DesiredPercentage + percentageToAdd, iCoin.DistanceFromTarget, iCoin.Locked) if isinstance(float(percentage), (float, int, complex, int)): if DatabaseManager.update_index_coin_model( coin.upper(), float(percentage), 0.0, lockCoin): logger.info("Coin " + coin.upper() + " updated in index") else: # Already Exist logger.warn("Coin already in index") else: logger.warn("Percentage isn't a number") else: logger.warn("Coin not supported") else: logger.warn( "Specified percentage below current bittrex trade value" ) else: logger.warn( "Currently no unlocked coins to transfer free value") else: logger.warn( "Please add another coin to your index before updating a given coin" )
def index_add_coin(self, coin, percentage, locked): lockCoin = False totalLockedPercentage = 0.0 totalUnlockedPercentage = 0.0 totalUnlockedCoinsCount = 0 indexInfo = DatabaseManager.get_index_info_model() indexedCoins = DatabaseManager.get_all_index_coin_models() if locked == "true" or locked == "True": lockCoin = True percentage_btc_amount = indexInfo.TotalBTCVal * (float(percentage) / 100) if percentage_btc_amount >= CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT: for inCoins in indexedCoins: if inCoins.Locked == True: totalLockedPercentage = totalLockedPercentage + inCoins.DesiredPercentage else: totalUnlockedPercentage = totalUnlockedPercentage + inCoins.DesiredPercentage totalUnlockedCoinsCount = totalUnlockedCoinsCount + 1 if totalUnlockedPercentage > float(percentage): if self.coin_supported_check(coin.upper()): percentageToRemove = float( percentage) / totalUnlockedCoinsCount for iCoin in indexedCoins: if iCoin.Locked != True: DatabaseManager.update_index_coin_model( iCoin.Ticker, iCoin.DesiredPercentage - percentageToRemove, iCoin.CurrentPercentage, iCoin.UnrealizedGain, iCoin.Locked) if isinstance(float(percentage), (float, int, complex, long)): if DatabaseManager.create_index_coin_model( coin.upper(), float(percentage), 0.0, 0.0, lockCoin): DatabaseManager.create_realized_gain_model( coin.upper(), 0.0) logger.info("Coin " + coin.upper() + " added to index") else: # Already Exist logger.warn("Coin already in index") else: logger.warn("Percentage isn't a number") else: logger.warn("Coin not supported") else: logger.warn("Not Enough Unlocked Percentage") else: logger.warn( "Specified percentage below current bittrex trade value")
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")