Ejemplo n.º 1
0
    def index_remove_coin(self, coin):
        if (coin.upper() == "BTC"):
            logger.warn("You cannot remove BTC from your index.")
            return

        indexedCoin = DatabaseManager.get_index_coin_model(coin.upper())
        btcCoin = DatabaseManager.get_index_coin_model('BTC')
        percentageToAdd = indexedCoin.DesiredPercentage

        if self.coin_supported_check(coin.upper()):

            if DatabaseManager.delete_index_coin_model(coin.upper()):

                # Add percentage back to BTC model
                DatabaseManager.update_index_coin_model(
                    btcCoin.Ticker,
                    btcCoin.DesiredPercentage + percentageToAdd,
                    btcCoin.DistanceFromTarget, btcCoin.Locked)

                logger.info("Coin " + coin.upper() + " removed from index")
            else:
                # Already Exist
                logger.warn("Coin not in index")
        else:
            logger.warn("Coin not supported")
Ejemplo n.º 2
0
    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}
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    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)
Ejemplo n.º 6
0
    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")
Ejemplo n.º 7
0
 def index_stop_command(self):
     indexInfo = DatabaseManager.get_index_info_model()
     DatabaseManager.update_index_info_model(False, indexInfo.TotalBTCVal,
                                             indexInfo.TotalUSDVal,
                                             indexInfo.BalanceThreshold,
                                             indexInfo.OrderTimeout,
                                             indexInfo.OrderRetryAmount,
                                             indexInfo.RebalanceTickSetting)
     logger.info("Index Management Stopped.")
Ejemplo n.º 8
0
 def __init__(self):
     self._client = discord.Client(heartbeat_timeout=60, guild_subscriptions=False, fetch_offline_members=False)
     self._databaseManager = DatabaseManager(self)
     self._cacheManager = CacheManager(self)
     self._commandsManager = CommandsManager(self)
     self._statisticsManager = StatisticsManager(self)
     self._teamupManager = TeamupManager(self, config.bot["teamup_dev_token"])
     self._calendarsManager = CalendarsManager(self)
     print("✓ Bot initialized")
Ejemplo n.º 9
0
    def index_remove_coin(self, coin):

        if self.coin_supported_check(coin.upper()):
            if DatabaseManager.delete_index_coin_model(coin.upper()):
                DatabaseManager.delete_realized_gain_model(coin.upper())
                logger.info("Coin " + coin.upper() + " removed from index")
            else:
                # Already Exist
                logger.warn("Coin not in index")
        else:
            logger.warn("Coin not supported")
Ejemplo n.º 10
0
def increment_rebalance_tick_task():

    indexInfo = DatabaseManager.get_index_info_model()

    if indexInfo.Active == True:
        rebalanceTick = DatabaseManager.get_rebalance_tick_model()

        if rebalanceTick.TickCount >= indexInfo.RebalanceTickSetting:
            app.send_task('Tasks.perform_algo_task',args=[])
        else:
            DatabaseManager.update_rebalance_tick_model(rebalanceTick.TickCount + 1)
Ejemplo n.º 11
0
    def lock_unlock_coin(self, ticker, is_lock):
        coin = DatabaseManager.get_index_coin_model(ticker)
        if coin is None:
            logger.error(
                "%s is not currently in your index. Use index add functionality to add it.",
                ticker)
            return
        coin.Locked = is_lock

        DatabaseManager.update_index_coin_object(coin)
        logger.info("%s %s", ticker, "locked" if is_lock else "unlocked")
Ejemplo n.º 12
0
 def index_rebalance_tick_update(self, tickcount):
     if isinstance(int(tickcount), (float, int, complex, long)):
         DatabaseManager.update_index_info_model(
             indexInfo.Active, indexInfo.TotalBTCVal, indexInfo.TotalUSDVal,
             indexInfo.TotalRealizedGain, indexInfo.TotalUnrealizedGain,
             round(float(percentage),
                   2), indexInfo.OrderTimeout, indexInfo.OrderRetryAmount,
             int(tickcount))
         logger.info("Index rebalance time set to " + str(tickcount) +
                     " minutes.")
     else:
         logger.warn("Tick count isn't a number")
Ejemplo n.º 13
0
    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")
Ejemplo n.º 14
0
def get_ticker(key):
    fullTicker = key.Ticker + "/BTC"

    if key.Ticker == 'BTC':
        fullTicker = 'BTC/USDT'

    return DatabaseManager.get_ticker_model(fullTicker)
Ejemplo n.º 15
0
    def index_rebalance_tick_update(self, tickcount):

        indexInfo = DatabaseManager.get_index_info_model()

        if isinstance(int(tickcount), (float, int, complex, int)):
            DatabaseManager.update_index_info_model(True,
                                                    indexInfo.TotalBTCVal,
                                                    indexInfo.TotalUSDVal,
                                                    indexInfo.BalanceThreshold,
                                                    indexInfo.OrderTimeout,
                                                    indexInfo.OrderRetryAmount,
                                                    int(tickcount))
            logger.info("Index rebalance time set to " + str(tickcount) +
                        " minutes.")
        else:
            logger.warn("Tick count isn't a number")
Ejemplo n.º 16
0
def supported_coins_task():
    em = ExchangeManager()
    marketData = em.get_tickers()
    btcUsdValue = em.get_btc_usd_value()
    supportedCoins = em.get_supported_pairs(marketData)

    logger.debug("Starting Coins Update Task")

    # First We Update our Supported Market List

    for key in supportedCoins:

        sliced_pair = ''
        if key != 'BTC/USDT':
            sliced_pair = key[:-4]
        else:
            sliced_pair = 'BTC'

        DatabaseManager.create_supported_coin_model(sliced_pair)

        btcTickerVal = 0.0
        usdTickerVal = 0.0

        if key != 'BTC/USDT':
            btcTickerVal = marketData[key]['info']['Ask']
            usdTickerVal = btcUsdValue * btcTickerVal
        else:
            btcTickerVal = 0.0
            usdTickerVal = marketData[key]['info']['Ask']

        if DatabaseManager.create_ticker_model(key, round(btcTickerVal, 8),
                                               round(usdTickerVal, 8),
                                               datetime.datetime.now()):

            #logger.debug("Created Ticker Model - " + key)
            pass
        else:

            if DatabaseManager.update_ticker_model(key, round(btcTickerVal, 8),
                                                   round(usdTickerVal, 8),
                                                   datetime.datetime.now()):
                #logger.debug("Updated Ticker Model - " + key)
                pass
            else:
                logger.error("Failed To Update Ticker Model - " + key)

    logger.info("Coins Update Task Completed")
    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")
Ejemplo n.º 18
0
    def check_locks(self, coin_above_threshold, coin_below_threshold):
        """Check the coins to make sure neither are currently locked."""
        logger.debug("Checking locks for %s and %s", coin_above_threshold,
                     coin_below_threshold)
        if DatabaseManager.get_coin_lock_model(
                coin_above_threshold) is not None:
            logger.debug("Current Avalible Coin Is Locked - %s",
                         coin_above_threshold)
            return False

        if DatabaseManager.get_coin_lock_model(
                coin_below_threshold) is not None:
            logger.debug("Current Eligible Coin Is Locked - %s",
                         coin_below_threshold)
            return False

        return True
Ejemplo n.º 19
0
    def handle_coin(self, coin, is_over, celery_app):
        """Handle re-balancing an individual coin."""
        if DatabaseManager.get_coin_lock_model(
                coin) is None and DatabaseManager.get_wallet_trade_lock_model(
                    coin) is None:
            if not coin == "BTC":
                if not self.em.market_active(coin, "BTC"):
                    logger.error("Market for %s/BTC offline", coin)
                    return

            amount = self.calculate_amount(coin, is_over)

            if amount is None:
                return

            if not coin == "BTC":
                self.handle_trade(coin, amount, is_over, celery_app)

        else:
            logger.warning("Coin %s is locked and cannot be traded", coin)
Ejemplo n.º 20
0
    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")
Ejemplo n.º 21
0
    def index_threshold_update(self, percentage):

        if isinstance(float(percentage), (float, int, complex, int)):

            indexInfo = DatabaseManager.get_index_info_model()

            percentage_btc_amount = indexInfo.TotalBTCVal * (
                float(percentage) / 100)

            if percentage_btc_amount <= CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT:
                logger.error("Desired BTC Threshold Value Too Low - " +
                             str(percentage))
            else:
                DatabaseManager.update_index_info_model(
                    True, indexInfo.TotalBTCVal, indexInfo.TotalUSDVal,
                    round(float(percentage), 2), indexInfo.OrderTimeout,
                    indexInfo.OrderRetryAmount, indexInfo.RebalanceTickSetting)
                logger.info("Index threshold set to " +
                            str(round(float(percentage), 2)))
        else:
            logger.warn("Percentage isn't a number")
Ejemplo n.º 22
0
    def __call__(self, *args, **kwargs):
        """Init main loop for the application."""

        self.database_manager = DatabaseManager()

        while True:
            clean_terminal()
            cprint(' Menu ', 'red')
            print("==================")
            cprint(' 1) Quel aliment souhaitez-vous remplacer ?', 'red')
            cprint(' 2) Retrouver mes aliments substitués.', 'red')

            reply_1 = self.ask_with_input(
                'Choisir un numéro '
                '(tapez "quit" pour quitter)'
                ' : ', 2, ('quit', ))

            if reply_1 == 'quit':
                break
            elif reply_1 == '1':
                while True:
                    clean_terminal()
                    cprint(' 1) Parcourir le rayon. ', 'red')
                    cprint(' 2) Effectuer une recherche. ', 'red')

                    reply_2 = self.ask_with_input(
                        'Choisir un numéro '
                        '(tapez "quit" pour quitter)'
                        ' : ', 2, ('quit', ))

                    if reply_2 == 'quit':
                        break
                    elif reply_2 == "1":
                        self.get_store_department()
                    elif reply_2 == "2":
                        self.do_research()
            else:
                self.get_substitutable_products()

        self.database_manager.close()
Ejemplo n.º 23
0
    def show_stats(self):
        indexInfo = IndexInfoModel.get(id=1)

        # Create the Index Table
        cointTableData = [[
            'Coin', 'Amount', 'BTC Val', 'USD Val', 'Desired %', 'Locked',
            'Active %', 'U Gain %', 'R Gain %'
        ]]

        for coin in IndexedCoinModel.select():

            coinBalance = CoinBalanceModel.get(
                CoinBalanceModel.Coin == coin.Ticker)
            realizedGainModel = DatabaseManager.get_realized_gain_model(
                coin.Ticker)

            newArray = [
                coin.Ticker,
                coinBalance.TotalCoins,
                coinBalance.BTCBalance,
                round(coinBalance.USDBalance, 2),
                coin.DesiredPercentage,
                coin.Locked,
                coin.CurrentPercentage,
                coin.UnrealizedGain,
                realizedGainModel.RealizedGain,
            ]
            cointTableData.append(newArray)

        # Create the summary table
        summary_table_data = [[
            'Active', 'Index Count', 'BTC Val', 'USD Val', 'Unrealized Gain %',
            'Realized Gain %'
        ]]
        summary_table_data.append([
            True,
            len(IndexedCoinModel.select()), indexInfo.TotalBTCVal,
            indexInfo.TotalUSDVal,
            round(indexInfo.TotalUnrealizedGain, 2),
            round(indexInfo.TotalRealizedGain, 2)
        ])

        coin_table = AsciiTable(cointTableData)
        summary_table = AsciiTable(summary_table_data)

        sys.stdout.write("\nCurrent Index Summary\n")
        sys.stdout.write(summary_table.table)

        sys.stdout.write("\nCurrent Index Table\n")
        sys.stdout.write(coin_table.table)
        sys.stdout.write('\n')
Ejemplo n.º 24
0
    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)
Ejemplo n.º 25
0
    def show_threshold(self):
        indexInfo = DatabaseManager.get_index_info_model()
        sys.stdout.write("\nCurrent Rebalance Threshold\n")

        summary_table_data = [[
            "Active", "Balance Threshold", "Order Timeout",
            "Rebalance Tick Setting"
        ]]
        summary_table_data.append([
            indexInfo.Active, indexInfo.BalanceThreshold,
            indexInfo.OrderTimeout, indexInfo.RebalanceTickSetting
        ])

        summary_table = AsciiTable(summary_table_data)
        sys.stdout.write(summary_table.table)
        sys.stdout.write("\n")
Ejemplo n.º 26
0
    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")
Ejemplo n.º 27
0
from flask.blueprints import Blueprint
from flask import render_template
from flask import request
from managers.DatabaseManager import DatabaseManager
from extensions import db

db_manager = DatabaseManager(db)

addLecturer = Blueprint('addLecturer', __name__,
                template_folder='templates',
                static_folder='static')


@addLecturer.route('/addLecturer')
def index3():
	return render_template('addLecturer.html')


@addLecturer.route('/addLecturer', methods=['post', 'get'])
def addLec():
    if request.method == 'POST':
        last_name = request.form.get('last_name')
        name = request.form.get('name')
        surname = request.form.get('surname')

    if last_name and name and surname:
        message = ""
        db_manager.add_lecturer(name=name, last_name=last_name, surname=surname)
    else:
        message = "error!"
Ejemplo n.º 28
0
    def calculate_amount(self, coin, is_over):
        """Figure out how much to buy/sell.
        Method should look up current value of each coin as trades fired previously could modify the balance.

        Includes minimum trade check.

        Returns None if amount doesn't meet trade threshold.
        """

        index_info = DatabaseManager.get_index_info_model()
        coin_balance = DatabaseManager.get_coin_balance_model(coin)
        indexed_coin = DatabaseManager.get_index_coin_model(coin)
        amount = None
        off = indexed_coin.get_percent_from_coin_target(
            coin_balance, index_info.TotalBTCVal)
        logger.info(
            "coin off percentage is %s with current coin balance of %s", off,
            coin_balance.BTCBalance)

        if coin_balance.BTCBalance > 0:
            if is_over is True:
                logger.info(
                    "Coin %s over threshold, calculating off percentage", coin)
                if off > 100:
                    amount = round(coin_balance.BTCBalance * (1 / (off / 100)),
                                   8)
                else:
                    amount = round(coin_balance.BTCBalance * off / 100, 8)
            else:
                logger.info(
                    "Coin %s under threshold, calculating off percentage",
                    coin)
                amount = round(
                    (coin_balance.BTCBalance /
                     (1 - (abs(off) / 100))) - coin_balance.BTCBalance, 8)

            logger.info("Amount calculated as %s", amount)

        if amount == None or amount == 0:
            logger.info(
                "Zero amount detected for %s. Attemping to buy 2x the minimum order.",
                coin)
            pair_string = coin
            if pair_string == "BTC":
                pair_string += "/USDT"
            else:
                pair_string += "/BTC"

            min_buy = self.em.get_min_buy_btc(pair_string)

            if min_buy is not None:
                amount = round(min_buy * 2, 8)
            else:
                logger.info(
                    "Zero amount of coin %s and market info cannot be found")
                amount = None

        if amount is not None:
            logger.info(
                "checking to see if amount %s is greater than trade threshold %s",
                amount, CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT)

            over_threshold = float(amount) >= float(
                CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT)

            if over_threshold is True:
                if is_over is False:
                    logger.info("checking to see if %s is available in BTC",
                                amount)
                    balance_available = 0.0
                    btc_balance = DatabaseManager.get_coin_balance_model("BTC")
                    btc_indexed_coin = DatabaseManager.get_index_coin_model(
                        "BTC")

                    btc_off = btc_indexed_coin.get_percent_from_coin_target(
                        btc_balance, index_info.TotalBTCVal)
                    if btc_off <= 0:
                        return None

                    balance_available = round(
                        btc_balance.BTCBalance * (btc_off / 100), 8)
                    logger.info("Available BTC balance %s", balance_available)
                    if balance_available >= amount:
                        return amount

                    #See if 1x the threshold is available
                    single_threshold_amount = round(
                        amount / (index_info.BalanceThreshold / 100), 8)

                    if not single_threshold_amount >= em.get_min_buy_btc(
                            pair_string):
                        single_threshold_amount = em.get_min_buy_btc(
                            pair_string) * 2

                    if balance_available >= single_threshold_amount and float(
                            single_threshold_amount) >= float(
                                CondexConfig.BITTREX_MIN_BTC_TRADE_AMOUNT):
                        return single_threshold_amount
                    else:
                        amount = None
                    logger.warning(
                        "The amount to trade %s not available currently",
                        amount)
                else:
                    logger.info("selling %s %s to BTC/USDT", amount, coin)
            else:
                logger.warning("Coin %s amount %s not over trade threshold",
                               coin, amount)
                amount = None

        return amount
Ejemplo n.º 29
0
    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"
            )
Ejemplo n.º 30
0
    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")