Esempio n. 1
0
def signal_task(self, ticker, interval, alt, source, action):
    logger.info('running signal task')
    try:
        ticker = ticker.replace('XBT', 'BTC')
        if action == "unset":
            l_s = pd.DataFrame(
                list(db.signal.find({"ticker": ticker}))).sort_values(
                by='time', ascending=False).reset_index()
            action = "buy" if l_s.iloc[0]['action'] == "sell" else "sell"
        db.signal.insert_one({
            "ticker": ticker,
            "action": action,
            "interval": interval,
            "alt": alt,
            "time": datetime.now(),
            "price": kraken.fetch_ticker(ticker)['close'],
            "stop": kraken.fetch_ticker(ticker)['close'] * 0.93,
            "source": source
        })
    except Exception as exc:
        logger.info(exc)
        telegram_bot("🔴 SIGNAL",
                     "FAILED inserting signal : " + ticker + " | " + action)
        telegram_bot("🔴 EXCEPTION", str(exc))
        self.retry(countdown=backoff(self.request.retries), exc=exc)
    telegram_bot("🟢 SIGNAL",
                 "Successfully inserted signal : " + ticker + " | " + action)
    allocate_btc_eth_task.apply_async()
    return True
Esempio n. 2
0
def test():
    try:
        test_task.delay()
    except Exception as exc:
        print(exc)
        telegram_bot("🔴 SIGNAL",
                     "GET /signal endpoint | failed starting signal_task")
        telegram_bot("🔴 EXCEPTION", str(exc))
    logger.info('core test route hit')
    telegram_bot("🟢 TEST", "GET /test endpoint core")
    return 'Congratulations! Your core-app test route is running!'
Esempio n. 3
0
def run():
    content = request.get_json()
    logger.info('trade allocate route hit: ' + json.dumps(content))
    telegram_bot("🟢 TRADE", "GET /trade endpoint: " + json.dumps(content))
    if 'USD' not in content or 'BTC' not in content or 'ETH' not in content:
        telegram_bot("🟠 TRADE", "INVALID BODY!")
        return "Invalid body"
    if content == {'USD': 0, 'BTC': 0, 'ETH': 0}:
        telegram_bot("🟠 TRADE", "No changes!")
        return "No changes!"
    for user in secrets:
        trade_btc_eth_task.apply_async(args=[user, content])
    return 'Trade started!'
Esempio n. 4
0
def signal():
    content = request.get_json()
    logger.info('core signal route hit')
    telegram_bot("🟢 SIGNAL", "GET /signal endpoint")
    if 'interval' not in content or 'ticker' not in content \
        or 'source' not in content or 'secret' not in content \
        or 'alt' not in content:
        telegram_bot("🟠 SIGNAL", "INVALID BODY!")
        return "Invalid body"
    if content['secret'] != BaseConfig.TV_KEY:
        telegram_bot("🟠 SIGNAL", "WRONG SECRET!")
        return "Unauthorized"
    if content['action'] != "buy" and content['action'] != "sell":
        telegram_bot("🟠 SIGNAL",
                     "NO VALID ACTION! Only buy or sell accepted!")
        return "No valid action : " + content['action']
    try:
        signal_task.apply_async(args=[
            content['ticker'], content['interval'], content['alt'],
            content['source'], content['action']
        ])
    except Exception as exc:
        print(exc)
        telegram_bot("🔴 SIGNAL",
                     "GET /signal endpoint | failed starting signal_task")
        telegram_bot("🔴 EXCEPTION", str(exc))
        return str(exc)
    return 'Received Signal!'
Esempio n. 5
0
def allocate_btc_eth_task(self):
    logger.info('running allocate')
    changes = {"USD": 0, "BTC": 0, "ETH": 0}
    try:
        s_db = pd.DataFrame(list(db.signal.find({}))) \
            .sort_values(by='time', ascending=False).reset_index(drop=True)

        s = {"ETH/BTC": 0, "BTC/USD": 0, "ETH/USD": 0}
        for index, row in s_db.iterrows():
            if row['ticker'] == "ETH/BTC" and s["ETH/BTC"] == 0:
                logger.info("HERE : " + row['action'])
                s["ETH/BTC"] = "buy" if row['action'] == "buy" else "sell"
            elif row['ticker'] == "BTC/USD" and s["BTC/USD"] == 0:
                s["BTC/USD"] = "buy" if row['action'] == "buy" else "sell"
            elif row['ticker'] == "ETH/USD" and s["ETH/USD"] == 0:
                s["ETH/USD"] = "buy" if row['action'] == "buy" else "sell"

        a = {
            "USD": 0,
            "BTC": 0,
            "ETH": 0,
            "btc_price": kraken.fetch_ticker("BTC/USD")['close'],
            "eth_price": kraken.fetch_ticker("ETH/USD")['close'],
            "eth_btc_price": kraken.fetch_ticker("ETH/BTC")['close'],
            "time": datetime.now()
        }
        if s["ETH/BTC"] == "buy" and s["ETH/USD"] == "buy":
            a["ETH"] = 100
        elif s["ETH/BTC"] == "sell" and s["BTC/USD"] == "buy":
            a["BTC"] = 100
        else:
            a["USD"] = 100

        c_a = pd.DataFrame(list(db.allocation_btc_eth.find({}))) \
            .sort_values(by='time', ascending=False).reset_index(drop=True)

        changes = {
            "USD": a["USD"] - c_a.iloc[0]["USD"],
            "BTC": a["BTC"] - c_a.iloc[0]["BTC"],
            "ETH": a["ETH"] - c_a.iloc[0]["ETH"]
        }

        if changes["USD"] == 0 and changes["BTC"] == 0 and changes["ETH"] == 0:
            telegram_bot("🟢 ALLOCATE", "No changes")
            return True
        elif changes["USD"] == 100 and changes["BTC"] == -100:
            telegram_bot("🟢 ALLOCATE", "Sell BTC to USD")
        elif changes["USD"] == 100 and changes["ETH"] == -100:
            telegram_bot("🟢 ALLOCATE", "Sell ETH to USD")
        elif changes["BTC"] == 100 and changes["ETH"] == -100:
            telegram_bot("🟢 ALLOCATE", "Sell ETH to BTC")
        elif changes["ETH"] == 100 and changes["BTC"] == -100:
            telegram_bot("🟢 ALLOCATE", "Sell BTC to ETH")
        elif changes["USD"] == -100 and changes["BTC"] == 100:
            telegram_bot("🟢 ALLOCATE", "Buy BTC with USD")
        elif changes["USD"] == -100 and changes["ETH"] == 100:
            telegram_bot("🟢 ALLOCATE", "Buy ETH with USD")
        else:
            telegram_bot("🔴 ALLOCATE", "Invalid allocation result!")
            telegram_bot("🔴 EXCEPTION", json.dumps(changes))
            return False

        db.allocation_btc_eth.insert_one(a)

    except Exception as exc:
        logger.info(exc)
        telegram_bot("🔴 ALLOCATE",
                     "FAILED running allocate_btc_eth_task task")
        telegram_bot("🔴 EXCEPTION", str(exc))
        self.retry(countdown=backoff(self.request.retries), exc=exc)

    changes = {
        "USD": str(changes['USD']),
        "BTC": str(changes['BTC']),
        "ETH": str(changes['ETH']),
    }

    for user in secrets:
        trade_btc_eth_task.apply_async(args=[user, changes])

    telegram_bot("🟢 ALLOCATE", "Successfully allocated btc_eth portfolio")
    telegram_bot("🟢 ALLOCATE", str(a))
    return True
Esempio n. 6
0
def test():
    logger.info('allocate test route hit')
    telegram_bot("TEST", "GET /test endpoint allocate")
    return 'Congratulations! Your core-app test route is running!'
Esempio n. 7
0
def run():
    logger.info('allocate allocate route hit')
    telegram_bot("🟢 ALLOCATE", "GET /allocate endpoint")
    allocate_btc_eth_task.apply_async()
    return 'Allocation started!'
Esempio n. 8
0
def trade_btc_eth_task(self, user, changes):
    logger.info('running trade btc_eth for ' + user['name'])
    try:
        changes = {
            "USD": int(changes['USD']),
            "BTC": int(changes['BTC']),
            "ETH": int(changes['ETH'])
        }

        kraken = ccxt.kraken({
            'apiKey': user['key'],
            'secret': user['secret'],
            'enableRateLimit': True,
            "timeout": 100000,
            # 'verbose': True,
            'options': {
                'fetchMinOrderAmounts': False
            }
        })

        kraken.check_required_credentials()
        kraken.load_markets()
        balance_usd = update_balance_usd(kraken)
        balance_btc = update_balance_btc(kraken)
        balance_eth = update_balance_eth(kraken)

        output = {}

        telegram_bot("🟢 TRADE", json.dumps(changes))
        telegram_bot("🟢 TRADE", "Current balance for " + user['name']
                     + " | USD: " + str(balance_usd) + " | BTC: "
                     + str(balance_btc) + " | ETH: " + str(balance_eth))

        if balance_btc > 0:
            output['sell_order_btc'] = kraken.create_order(
                'BTC/USD', 'market', 'sell', balance_btc)['info']['descr'][
                'order']
            telegram_bot("🟢 TRADE", "Sold BTC: " + output['sell_order_btc'])

        if balance_eth > 0:
            output['sell_order_eth'] = kraken.create_order(
                'ETH/USD', 'market', 'sell', balance_eth)['info']['descr'][
                'order']
            telegram_bot("🟢 TRADE", "Sold ETH: " + output['sell_order_eth'])

        balance_usd = update_balance_usd(kraken)
        btc_price = kraken.fetch_ticker('BTC/USD')['close']
        eth_price = kraken.fetch_ticker('ETH/USD')['close']

        if balance_usd > 0 and changes["BTC"] == 100:
            output['buy_order_btc'] = kraken.create_order(
                'BTC/USD', 'market', 'buy', (balance_usd / btc_price) * 0.97)[
                'info']['descr']['order']
            telegram_bot("🟢 TRADE", "Buy BTC: " + output['buy_order_btc'])

        if balance_usd > 0 and changes["ETH"] == 100:
            output['buy_order_eth'] = kraken.create_order(
                'ETH/USD', 'market', 'buy', (balance_usd / eth_price) * 0.97)[
                'info']['descr']['order']
            telegram_bot("🟢 TRADE", "Buy ETH: " + output['buy_order_eth'])

        balance_usd = update_balance_usd(kraken)
        balance_btc = update_balance_btc(kraken)
        balance_eth = update_balance_eth(kraken)

        telegram_bot("🟢 TRADE", "Balance for " + user['name']
                     + " | USD: " + str(balance_usd) + " | BTC: "
                     + str(balance_btc) + " | ETH: " + str(balance_eth))

        if output == {}:
            telegram_bot("🟠 TRADE", "No trades for: " + user['name'])

    except Exception as exc:
        logger.info(exc)
        telegram_bot("🔴 TRADE",
                     "FAILED running trade_btc_eth_task task for "
                     + user['name'])
        telegram_bot("🔴 EXCEPTION", str(exc))
        self.retry(countdown=backoff(self.request.retries), exc=exc)

    telegram_bot("🟢 TRADE",
                 "Successfully executed btc_eth trades for " + user['name'])
    return True
Esempio n. 9
0
def test():
    logger.info('trade test route hit')
    telegram_bot("TEST", "GET /test endpoint trade")
    return 'Congratulations! Your trade-app test route is running!'