예제 #1
0
def data_tor(tor=None):
    from node_warden import load_config
    config = load_config(quiet=True)
    if not tor:
        tor = test_tor()

    import socket
    try:
        local_ip = socket.gethostbyname(socket.gethostname())
    except Exception:
        local_ip = 'Error getting local IP'

    if not config['MAIN'].getboolean('hide_private_info'):
        tor_string = f""" ✅ {success('TOR Connected')}
    Running on port {info(bold(tor['port']))}
    Tor IP Address {warning(tor['post_proxy']['origin'])}
    Ping Time {tor['post_proxy_ping']}
    Global IP Address {warning(tor['pre_proxy']['origin'])}
    Ping Time {muted(tor['pre_proxy_ping'])}
    Local IP Address {warning(local_ip)}
    """
    else:
        tor_string = f""" ✅ {success('TOR Connected')}
    Running on port {info(bold(tor['port']))}
    Tor IP Address {yellow('** HIDDEN **')}
    Ping Time {tor['post_proxy_ping']}
    Global IP Address {yellow('** HIDDEN **')}
    Ping Time {muted(tor['pre_proxy_ping'])}
    Local IP Address {yellow('** HIDDEN **')}
    """
    return (tor_string)
예제 #2
0
def data_large_price():
    from node_warden import load_config
    config = load_config(quiet=True)
    ft_config = config['MAIN']
    font = ft_config.get('large_text_font')
    btc = btc_price_data()
    try:
        btc_price = cleanfloat(btc['DISPLAY']['BTC']['USD']['PRICE'])
    except Exception:
        return (error(' >> Error getting price data. Retrying...'))
    custom_fig = pyfiglet.Figlet(font=font)
    return_fig = custom_fig.renderText('$  ' + jformat(btc_price, 0))
    return_fig = yellow(return_fig)

    chg_str = btc['DISPLAY']['BTC']['USD']['CHANGEPCTDAY']
    chg = cleanfloat(chg_str)
    msg = '\n'

    if chg >= 0:
        msg += success(f'24hr Change: +{chg_str}%\n')
    if chg > 5:
        msg += (info("[NgU] ") + muted(f"Looks like Bitcoin is pumping ") +
                emoji.emojize(":rocket:"))

    if chg < 0:
        msg += error(f'24hr Change: {chg_str}%\n')
    if chg < -5:
        msg += muted(
            f"Bitcoin dropping? Buy the dip!\nTime to stack some sats. ")

    return_fig = muted(return_fig)
    return_fig += msg

    return (return_fig)
예제 #3
0
def toggle(config_var):
    from node_warden import load_config
    from node_warden import basedir
    config = load_config(quiet=True)
    getter = config['MAIN'].getboolean(config_var)
    getter = not getter
    config['MAIN'][config_var] = str(getter)
    config_file = os.path.join(basedir, 'config.ini')
    with open(config_file, 'w') as configfile:
        config.write(configfile)
예제 #4
0
def data_random_satoshi():
    from node_warden import load_config
    config = load_config(quiet=True)
    url = config['QUOTES'].get('url')
    try:
        quotes = tor_request(url).json()
    except Exception:
        return (error(' >> Error contacting server. Retrying... '))
    quote = quotes[randrange(len(quotes))]
    return_str = info(f"Satoshi Quotes | Subject: {quote['category']}\n")
    return_str += muted(f"{quote['date']} on {quote['medium']}\n")
    return_str += yellow(f"{quote['text']} \n\n")
    return_str += muted("Source: Nakamoto Institute")
    return (return_str)
예제 #5
0
def multiple_price_grab(tickers, fx):
    from node_warden import load_config
    config = load_config(quiet=True)
    api_key = config['API'].get('cryptocompare')
    # tickers should be in comma sep string format like "BTC,ETH,LTC" and "USD,EUR"
    baseURL = \
        "https://min-api.cryptocompare.com/data/pricemultifull?fsyms="\
        + tickers + "&tsyms=" + fx + "&&api_key=" + api_key
    try:
        request = tor_request(baseURL)
    except requests.exceptions.ConnectionError:
        return ("ConnectionError")
    try:
        data = request.json()
    except AttributeError:
        data = "ConnectionError"
    return (data)
예제 #6
0
def data_btc_price():
    from node_warden import launch_logger
    launch_logger()

    from node_warden import load_config
    config = load_config(quiet=True)
    fx_config = config['CURRENCIES']
    currencies = ast.literal_eval(fx_config.get('fx_list'))
    primary_fx = ast.literal_eval(fx_config.get('primary_fx'))
    price_data = multiple_price_grab('BTC', ','.join(currencies))
    # Get prices in different currencies
    tabs = []
    btc_usd_price = 0
    for fx in currencies:
        try:
            price_str = price_data['DISPLAY']['BTC'][fx]['PRICE']
            chg_str = price_data['DISPLAY']['BTC'][fx]['CHANGEPCTDAY']
            high = price_data['DISPLAY']['BTC'][fx]['HIGHDAY']
            low = price_data['DISPLAY']['BTC'][fx]['LOWDAY']
            market = muted(price_data['DISPLAY']['BTC'][fx]['LASTMARKET'])
            try:
                chg = float(chg_str)
                if chg >= 0:
                    chg_str = success('+' + chg_str + '%')
                elif chg < 0:
                    chg_str = error(chg_str + '%')
            except Exception:
                chg_str = muted(chg_str + '%')

            if fx == 'USD':
                btc_usd_price = cleanfloat(price_str)

            if fx == primary_fx:
                fx = info(fx)
            tabs.append(
                [u'  ' + fx, price_str, chg_str, low + ' - ' + high, market])

        except Exception as e:
            tabs.append(['error: ' + str(e)])

    tabs = tabulate(
        tabs,
        headers=['Fiat', 'Price', '% change', '24h Range', 'Source'],
        colalign=["center", "right", "right", "center", "right"])

    # GBTC
    gbtc_config = config['STOCKS']
    try:
        if gbtc_config.getboolean('GBTC_enabled'):
            tabs += '\n\n'
            gbtc_url = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=GBTC&apikey=DDC232JDH'
            gbtc_data = tor_request(gbtc_url).json()['Global Quote']
            gbtc_tabs = []
            GBTC_shares = gbtc_config.getfloat('gbtc_shares')
            fairvalue, premium = (GBTC_premium(float(gbtc_data['05. price']),
                                               btc_usd_price, GBTC_shares))

            if premium * 1 > 0:
                premium = success('+' + jformat(premium, 2, 0.01) + '%')
            elif premium * 1 < 0:
                premium = error(jformat(premium, 2, 0.01) + '%')

            fairvalue = jformat(fairvalue, 2)

            chg_str = gbtc_data['10. change percent']
            try:
                chg = cleanfloat(chg_str)
                if chg > 0:
                    chg_str = success('+' + jformat(chg, 2) + ' %')
                elif chg < 0:
                    chg_str = error(jformat(chg, 2) + ' %')
            except Exception:
                chg_str = muted(chg_str)

            gbtc_tabs.append([
                'GBTC', gbtc_data['05. price'], chg_str,
                gbtc_data['04. low'] + ' - ' + gbtc_data['03. high'], premium,
                fairvalue, gbtc_data['07. latest trading day']
            ])
            gbtc_tabs = tabulate(gbtc_tabs,
                                 headers=[
                                     'Ticker', 'Price', '% change',
                                     '24h Range', 'Premium', 'Fair Value',
                                     'Last Update'
                                 ],
                                 colalign=[
                                     "center", "right", "right", "center",
                                     "right", "right", "right"
                                 ])
            tabs += gbtc_tabs

    except Exception as e:
        er_st = error(f' Error getting GBTC data: {e}')
        tabs += er_st

    tabs += (
        f"\n\n Last Refresh on: {info(datetime.now().strftime('%H:%M:%S'))}")
    return tabs
예제 #7
0
def data_mempool():
    from node_warden import load_config
    from node_warden import launch_logger
    launch_logger()

    config = load_config(quiet=True)
    mp_config = config['MEMPOOL']
    url = mp_config.get('url')
    tabs = []

    # Get recommended fees

    mp_fee = tor_request(url + '/api/v1/fees/recommended').json()
    tabs = list(mp_fee.values())
    tabs = [[str(x) + ' sats/Vb' for x in tabs]]
    tabs = tabulate(tabs,
                    headers=["Fastest Fee", "30 min fee", "1 hour fee"],
                    colalign=["center", "center", "center"])
    try:
        block_height = tor_request(url + '/api/blocks/tip/height').json()
    except Exception:
        return (error(f' >> Error getting data from {url}. Retrying...'))
    # Save the latest block height
    saved_block = pickle_it(action='load', filename='block.pkl')
    if (saved_block != block_height) and (
            config['MEMPOOL'].getboolean('block_found_sound')):
        # Block found play sound
        try:
            engine = pyttsx3.init()
            engine.setProperty('rate', 270)
            engine.say(config['MEMPOOL'].get('block_found_txt'))
            engine.runAndWait()
        except Exception:
            pass
        logging.info(
            info('[MEMPOOL] ') +
            success("A new Bitcoin Block was just found. ") +
            yellow("'Tick. Tock. Next block.'"))

    pickle_it(action='save', filename='block.pkl', data=block_height)

    block_txt = success(f' Block Height: {jformat(block_height, 0)}\n\n')
    tabs = block_txt + info(' Mempool Fee Estimates: \n') + tabs

    try:
        mp_blocks = tor_request(url + '/api/blocks').json()
    except Exception:
        return (error(" >> Error getting Mempool data. Retrying..."))

    mp_tabs = []
    gradient_color = 0
    for block in mp_blocks:
        mp_tabs.append([
            time_ago(block['timestamp']),
            jformat(block['height'], 0),
            jformat(block['tx_count'], 0),
            jformat(block['size'], 2, 1000000) + ' MB'
        ])
        gradient_color += 1

    mp_tabs = tabulate(mp_tabs,
                       headers=[" Time", "Height", "Tx Count", "Size"],
                       colalign=["right", "center", "center", "right"])
    tabs += info('\n\n Latest Blocks: \n') + mp_tabs
    tabs += muted(f"\n\n Source: {url}  {success('[Tor Request]')}\n")
    return tabs
예제 #8
0
def data_btc_price():
    from node_warden import launch_logger
    launch_logger()

    from node_warden import load_config
    config = load_config(quiet=True)
    fx_config = config['CURRENCIES']
    currencies = ast.literal_eval(fx_config.get('fx_list'))
    primary_fx = ast.literal_eval(fx_config.get('primary_fx'))
    price_data = multiple_price_grab('BTC', ','.join(currencies))
    # Get prices in different currencies
    tabs = []
    btc_usd_price = 0
    for fx in currencies:
        try:
            price_str = price_data['DISPLAY']['BTC'][fx]['PRICE']
            chg_str = price_data['DISPLAY']['BTC'][fx]['CHANGEPCTDAY']
            high = price_data['DISPLAY']['BTC'][fx]['HIGHDAY']
            low = price_data['DISPLAY']['BTC'][fx]['LOWDAY']
            market = muted(price_data['DISPLAY']['BTC'][fx]['LASTMARKET'])
            try:
                chg = float(chg_str)
                if chg >= 0:
                    chg_str = success('+' + chg_str + '%')
                elif chg < 0:
                    chg_str = error(chg_str + '%')
            except Exception:
                chg_str = muted(chg_str + '%')

            if fx == 'USD':
                btc_usd_price = cleanfloat(price_str)

            if fx == primary_fx:
                fx = info(fx)
            tabs.append(
                [u'  ' + fx, price_str, chg_str, low + ' - ' + high, market])

        except Exception as e:
            tabs.append(['error: ' + str(e)])

    if tabs == []:
        return (
            error(f' >> Error getting data from CryptoCompare. Retrying...'))

    try:
        tabs = tabulate(
            tabs,
            headers=['Fiat', 'Price', '% change', '24h Range', 'Source'],
            colalign=["center", "right", "right", "center", "right"])
    except Exception:
        return (
            error(f' >> Error getting data from CryptoCompare. Retrying...'))

    # GBTC
    gbtc_config = config['STOCKS']
    try:
        if gbtc_config.getboolean('GBTC_enabled'):
            tabs += '\n\n'
            gbtc_url = 'https://finnhub.io/api/v1/quote?symbol=GBTC&token=bvfhuqv48v6rhdtvnks0'
            gbtc_data = tor_request(gbtc_url).json()
            gbtc_tabs = []
            GBTC_shares = gbtc_config.getfloat('gbtc_shares')
            fairvalue, premium = (GBTC_premium((gbtc_data['c']), btc_usd_price,
                                               GBTC_shares))

            if premium * 1 > 0:
                premium = success('+' + jformat(premium, 2, 0.01) + '%')
            elif premium * 1 < 0:
                premium = error(jformat(premium, 2, 0.01) + '%')

            fairvalue = jformat(fairvalue, 2)

            chg_str = gbtc_data['c'] / gbtc_data['pc']
            try:
                chg = (chg_str)
                if chg > 0:
                    chg_str = success('+' + jformat(chg, 2) + ' %')
                elif chg < 0:
                    chg_str = error(jformat(chg, 2) + ' %')
            except Exception:
                chg_str = muted(chg_str)

            gbtc_tabs.append([
                'GBTC',
                jformat(gbtc_data['c'], 2), chg_str,
                jformat(gbtc_data['l'], 2) + ' - ' +
                jformat(gbtc_data['h'], 2), premium, fairvalue,
                time_ago(gbtc_data['t'])
            ])
            gbtc_tabs = tabulate(gbtc_tabs,
                                 headers=[
                                     'Ticker', 'Price', '% change',
                                     '24h Range', 'Premium', 'Fair Value',
                                     'Last Update'
                                 ],
                                 colalign=[
                                     "center", "right", "right", "center",
                                     "right", "right", "right"
                                 ])
            tabs += gbtc_tabs

    except Exception as e:
        er_st = error(f' Error getting GBTC data: {e}')
        tabs += er_st

    tabs += (
        f"\n\n Last Refresh on: {info(datetime.now().strftime('%H:%M:%S'))}")
    return tabs