Ejemplo n.º 1
0
    def load_history(self):
        es = etherscan.Client(api_key='AFJ976ENEMDXAFPQH237I3KPYJSB164Y45')
        transactions = es.get_transactions_by_address(self.sender)
        if not transactions:
            self.ids['history'].add_widget(Label(text = 'История транзакций пуста'))

        else:
            id_trn = 1
            for transaction in transactions:
                self.ids['history'].add_widget(Factory.ItemTranz(text = f'{id_trn} Дата: {datetime.datetime.utcfromtimestamp(transaction["timestamp"])}', on_release = self.changer))
                id_trn += 1
Ejemplo n.º 2
0
class EtherScan:
    es = etherscan.Client(api_key='AFJ976ENEMDXAFPQH237I3KPYJSB164Y45' )
    def get_balance(self, sender):
        balance = self.es.get_eth_balance(sender)
        return balance
    
    def get_price(self, balance):
        get_price = self.es.get_eth_price() 
        price = get_price['ethusd'] 
        USD = price * float (balance)
        USD = '%.2f USD' % USD      # Delete everything after 2 num
        return USD
Ejemplo n.º 3
0
 def changer(self,instance,*args):
     text = instance.text
     print(text[0])
     es = etherscan.Client(api_key='AFJ976ENEMDXAFPQH237I3KPYJSB164Y45')
     transactions = es.get_transactions_by_address(self.sender)
     print(transactions[int(text[0])-1])
     transaction = transactions[int(text[0])-1]
     Transaction.sender = transaction["from"]
     Transaction.getter = transaction["to"]
     Transaction.how_many = transaction["value"]
     Transaction.comission = transaction["gas_used"]
     self.manager.current = 'Transaction'
Ejemplo n.º 4
0
def get_spells():
    spell_list = []
    es = etherscan.Client(api_key=config['ETHERSCAN_API']['key'],
                          cache_expire_after=5)
    for k, v in list(config.items('DEPLOYER_ADDRESSES')):
        txs = es.get_transactions_by_address(v, limit=10000)
        spell_list = parse_spell(k, v, txs, spell_list)

    for i in spell_list:
        try:
            txs = es.get_transactions_by_address(i.address, limit=1000)
        except:
            continue
        cast_block = find_when_cast(txs)
        i.setCasted_on(cast_block)

    return spell_list
Ejemplo n.º 5
0
def hello_world():

    from coincurve import PublicKey
    from sha3 import keccak_256
    import os
    import time
    import etherscan
    import time
    start_time = time.time()
    es = etherscan.Client(api_key='HB88FQKBAIKSSVX1BQWDP1KJ9BKTUSJVT2', )
    addrss = []
    pvkeys = []
    bolfnd = 0
    x = 0
    y = 0
    while y < 50:
        y = y + 1
        x = 0
        while x < 20:
            x = x + 1
            private_key = keccak_256(os.urandom(32)).digest()
            public_key = PublicKey.from_valid_secret(private_key).format(
                compressed=False)[1:]
            addr = keccak_256(public_key).digest()[-20:]
            addr = addr.hex()
            private_key = private_key.hex()
            addrss.append("0x" + str(addr))
            pvkeys.append(str(private_key))
        eth_balance = es.get_eth_balances(addrss)
        aa = list(eth_balance.values())
        for bl in aa:
            if bl != 0:
                bolfnd = 1
        if bolfnd != 0:
            break
        time.sleep(500 / 1000)
        addrss = []
        pvkeys = []

    #return "<xmp>" +  "bl:"+str(bolfnd)+"\n" +str(addrss)+ "\n"+str(pvkeys)+"</xmp>"
    return html("<h1>bl:" + str(bolfnd) + "</h1> <br> " + str(addrss) +
                " <br> " + str(pvkeys) + "<br>" + str(addr))
Ejemplo n.º 6
0
def main_etherscan():
    import etherscan
    file_name_dict = get_filename()
    es = etherscan.Client(
    api_key=API_KEY,
    cache_expire_after=5,
    )
    rows = []
    with open(file_name_dict["filename"], "w") as of:
        csvw = csv.DictWriter(of, fieldnames=HEADERS)
        csvw.writeheader()
        for i in range(1000):
            blocknumber = es.get_block_number()
            blockhash = es.get_block_by_number(blocknumber).get("transactionsRoot")
            rows.append({
              "ts":time.time_ns(),
              "source":file_name_dict["provider_type"],
              "blocknumber":blocknumber,
              "blockhash":blockhash,
            })
            time.sleep(.215)
        csvw.writerows(rows)
Ejemplo n.º 7
0
def main():
    address0 = "0xf79cb3BEA83BD502737586A6E8B133c378FD1fF2"
    network_blk_instance = NetworkBlkInstance(address=address0)

    print(len(address0))

    address1 = '0x3c7bec02bd4fa73dce24413d2a13c02e1a91e858'

    print(len(address1))

    address2_safe = '0x522715235d66faeF072509697445A66B442faD88'

    import re
    # re.search('[aA-zZ,0-9]')
    # re.search('[A-Z,0-9]')

    ETHERSCAN_API_KEY = api_key_dict['API_KEY']['etherscan']['0']
    import etherscan
    es = etherscan.Client(
        api_key=ETHERSCAN_API_KEY,
        cache_expire_after=5,
    )
Ejemplo n.º 8
0
class discord_bot:
    # api instance
    cg = CoinGeckoAPI()
    es = etherscan.Client(
        api_key='Y9KQMISGCXVNMJJXA2TBFMENF1JM2D4HAP',
        cache_expire_after=5,
    )

    # functions to gather btc, eth, and any coins price
    def btc_status(self):
        price_data = self.cg.get_price(ids= 'bitcoin', vs_currencies='usd')
        price = price_data['bitcoin']['usd']
        price = round(price,2)
        response = "Bitcoin - $" + str(price)
        return response

    def eth_status(self):
        price_data = self.cg.get_price(ids= 'Ethereum', vs_currencies='usd')
        price = price_data['ethereum']['usd']
        price = round(price,2)
        response = "Ethereum: $" + str(price)
        return response

    def get_coin_price(self, coin_name):
        coin_label = ""
        coin_name = coin_name.lower()
        coin_label = self.check_coin(coin_name)
        if self.check_coin(coin_name) != "":
            price_data = self.cg.get_price(ids= coin_label, vs_currencies='usd', include_24hr_change='true', include_market_cap = 'true')
            price = price_data[coin_label]['usd']
            price = round(price,3)
            price = "{:,}".format(price)
            percent_change = price_data[coin_label]['usd_24h_change']
            percent_change = round(percent_change, 2)
            market_cap = price_data[coin_label]['usd_market_cap']
            market_cap = round(market_cap, 2)
            market_cap = self.check_large(market_cap)
            mc = market_cap
            # market_cap = "{:,}".format(market_cap)
            coin_name = self.change_cap(coin_name)
            # embedResponse = discord.Embed(title=coin_name + " Info", color=0xFF8C00)
            embedResponse = discord.Embed(color=0xFF8C00)
            embedResponse.add_field(name= coin_name + " Price", value= "$" + str(price), inline=False)
            embedResponse.add_field(name= coin_name + " Percent Change (24hr)", value= str(percent_change) + "%", inline=False)
            embedResponse.add_field(name= coin_name + " Market Cap", value= "$" + mc, inline=False)
            response1 = "```" + coin_name + "'s price: $" + str(price) + "\n" + "Percent Change (24h): " + str(percent_change) + "%" + "\n" + "Market Cap: $" + str(market_cap) + "```"
            # response2 = "```" + coin_name + "'s price: $" + str(price) + ", " + "Percent Change (24h): " + str(percent_change) + "%" + "\n" + "Market Cap: $" + str(market_cap) + "```"
            return embedResponse
        return ""

    # retreive data and create candle chart of any coin
    def get_line_chart(self, coin_name, num_days):
        #coin label work
        coin_label = ""
        coin_name = coin_name.lower()
        coin_label = self.check_coin(coin_name)
        #checking if num days is valid
        temp = str(num_days)
        if not temp.isdigit():
            temp = temp.lower()
            if temp != "max":
                return False

        if self.check_coin(coin_name) != "":
            charts = self.cg.get_coin_market_chart_by_id(id = coin_label, vs_currency='usd', days = num_days)
            plt.clf()
            x_vals = []
            y_vals = []
            count = 0
            open, close, high, low, volume = [], [], [], [], []
            for point in charts['prices']:
                if count == 0:
                    time_conv = datetime.utcfromtimestamp(point[0] / 1000).strftime('%Y-%m-%d')
                x_vals.append(time_conv)
                y_vals.append(point[1])
                volume.append(1)
                count += 1
            # create the date and dataframe
            open = y_vals
            close = y_vals
            high = y_vals
            low = y_vals
            period = len(open)
            frequency = ""
            if num_days == "1":
                frequency = "5min"
            elif num_days != "max" and (int(num_days) <= 90 and int(num_days) > 1):
                frequency = "1H"
            else:
                frequency = "4D"
            dti = pd.date_range(time_conv, periods=period, freq=frequency)
            ohlc = {"opens":open, "highs":high, "lows":low, "closes":close, "volumes":volume}
            ohlc = pd.DataFrame(data = ohlc, index = dti)
            ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume'] #these two lines solved the dataframe problem
            ohlc.index.name = "Date"
            # plot and make it look good
            percent_change = ((close[len(close) - 1] - close[0]) / close[0]) * 100
            percent_change = round(percent_change, 2)
            changed, days = "", ""
            # change title based on days
            if num_days == "1":
                days = "the past 24 hours"
            elif num_days == "MAX" or num_days == "max":
                days = "Within Lifetime"
            else:
                days = "Past " + num_days + " Days"
            # change title based on percent
            if percent_change > 0:
                changed = "+"
            else:
                changed = ""

            percent_change = "{:,}".format(percent_change) # had to do it here because this converts it to a string, need it as a int above
            # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days
            coin_label = self.change_cap(coin_label)
            title1 = "\n" + "\n" + coin_label + " " + changed + percent_change + "% - " + days
            mc = mpf.make_marketcolors(
                                up='tab:blue',down='tab:red',
                                wick={'up':'blue','down':'red'},
                                volume='tab:green',
                               )

            edited_style  = mpf.make_mpf_style(gridstyle = '-', facecolor = "lightgray", gridcolor = "white", edgecolor = "black", base_mpl_style = "classic", marketcolors=mc)
            mpf.plot(ohlc, type='line', title = title1, figratio = (16,10), ylabel = 'Price - USD', style = edited_style, savefig = "chart.png")
            return ""
        else:
            return "error"

    # chart of two coins for instance link/btc
    def get_line_chart_two(self, coin_name, coin_name2, num_days):
        #coin label work
        coin_label = ""
        coin_label2 = ""
        coin_name = coin_name.lower()
        coin_label2 = coin_name2.lower()
        coin_label = self.check_coin(coin_name)
        coin_label2 = self.check_coin(coin_name2)
        #checking if num days is valid
        temp = str(num_days)
        if not temp.isdigit():
            temp = temp.lower()
            if temp != "max":
                return False

        if self.check_coin(coin_name) != "":
            charts = self.cg.get_coin_market_chart_by_id(id = coin_label, vs_currency='usd', days = num_days)
            charts2 = self.cg.get_coin_market_chart_by_id(id = coin_label2, vs_currency = 'usd', days = num_days)
            plt.clf()
            x_vals = []
            y_vals = []
            count = 0
            open, close, high, low, volume = [], [], [], [], []
            min = len(charts["prices"])
            if min > len(charts2["prices"]):
                min = len(charts2["prices"])
            for point in charts['prices']:
                if count == min:
                    break
                if count == 0:
                    time_conv = datetime.utcfromtimestamp(point[0] / 1000).strftime('%Y-%m-%d')
                x_vals.append(time_conv)
                y_vals.append(point[1])
                volume.append(1)
                count += 1
            count = 0
            for point in charts2['prices']:
                if count == min:
                    break
                y_vals[count] = y_vals[count] / point[1]
                count += 1
            # create the date and dataframe
            open = y_vals
            close = y_vals
            high = y_vals
            low = y_vals
            period = len(open)
            frequency = ""
            if num_days == "1":
                frequency = "5min"
            elif num_days != "max" and (int(num_days) <= 90 and int(num_days) > 1):
                frequency = "1H"
            else:
                frequency = "4D"
            dti = pd.date_range(time_conv, periods=period, freq=frequency)
            ohlc = {"opens":open, "highs":high, "lows":low, "closes":close, "volumes":volume}
            ohlc = pd.DataFrame(data = ohlc, index = dti)
            ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume'] #these two lines solved the dataframe problem
            ohlc.index.name = "Date"
            # plot and make it look good
            percent_change = ((close[len(close) - 1] - close[0]) / close[0]) * 100
            percent_change = round(percent_change, 2)
            changed, days = "", ""
            # change title based on days
            if num_days == "1":
                days = "the past 24 hours"
            elif num_days == "MAX" or num_days == "max":
                days = "Within Lifetime"
            else:
                days = "Past " + num_days + " Days"
            # change title based on percent
            if percent_change > 0:
                changed = "+"
            else:
                changed = ""

            percent_change = "{:,}".format(percent_change) # had to do it here because this converts it to a string, need it as a int above
            # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days
            coin_label = self.change_cap(coin_name.lower())
            coin_label2 = self.change_cap(coin_name2.lower())
            title1 = "\n" + "\n" + coin_label + "/" + coin_label2 + " " + changed + percent_change + "% - " + days
            mc = mpf.make_marketcolors(
                                up='tab:blue',down='tab:red',
                                wick={'up':'blue','down':'red'},
                                volume='tab:green',
                               )

            edited_style  = mpf.make_mpf_style(gridstyle = '-', facecolor = "lightgray", gridcolor = "white", edgecolor = "black", base_mpl_style = "classic", marketcolors=mc)
            mpf.plot(ohlc, type='line', title = title1, figratio = (16,10), ylabel = coin_label + "/" + coin_label2, style = edited_style, savefig = "chart.png")
            return ""
        else:
            return "error"


    # retreive data and create candle chart of any coin
    def get_candle_chart(self, coin_name, num_days):

        # used the below links for the mpf libraries
        # https://github.com/matplotlib/mplfinance#usage
        # https://github.com/matplotlib/mplfinance/blob/master/examples/styles.ipynb

        #coin label work
        coin_label = ""
        coin_name = coin_name.lower()
        coin_label = self.check_coin(coin_name)
        #checking if num days is valid
        valid_days = ["1","7","14","30","90","180","365", "MAX", "max"]
        check = False
        error_days = "```Command Error: Wrong number of days: Only can input '1','7','14','30','90','180','365','MAX'```"
        for day in valid_days:
            if num_days == day:
                check = True
        if check == False:
            return error_days

        if self.check_coin(coin_name) != "":
            candles = self.cg.get_coin_ohlc_by_id(id = coin_label, vs_currency='usd', days = num_days)
            plt.clf()
            date_arr, year, month, day, hour, open, high, low, close, volume = [], [], [], [], [], [], [], [], [], []
            dohlcv = [[]]
            count = 0
            time_conv = ""
            for point in candles:
                # convert to standard date and time, parse and add them into arrays
                if count == 0:
                    time_conv = datetime.utcfromtimestamp(point[0] / 1000).strftime('%Y-%m-%d')
                # parse and add in the OHLC vectors
                open.append(point[1])
                high.append(point[2])
                low.append(point[3])
                close.append(point[4])
                volume.append(1)
                count += 1
            # create the date and dataframe
            period = len(open)
            frequency = ""
            if num_days == "1":
                frequency = "30min"
            elif num_days == "7" or num_days == "14" or num_days == "30":
                frequency = "4H"
            else:
                frequency = "4D"
            dti = pd.date_range(time_conv, periods=period, freq=frequency)
            ohlc = {"opens":open, "highs":high, "lows":low, "closes":close, "volumes":volume}
            ohlc = pd.DataFrame(data = ohlc, index = dti)
            ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume'] #these two lines solved the dataframe problem
            ohlc.index.name = "Date"
            # plot and make it look good
            percent_change = ((close[len(close) - 1] - close[0]) / close[0]) * 100
            percent_change = round(percent_change, 2)
            changed, days = "", ""
            # change title based on days
            if num_days == "1":
                days = "the past 24 hours"
            elif num_days == "MAX" or num_days == "max":
                days = "Within Lifetime"
            else:
                days = "Past " + num_days + " Days"
            # change title based on percent
            if percent_change > 0:
                changed = "+"
            else:
                changed = ""

            percent_change = "{:,}".format(percent_change) # had to do it here because this converts it to a string, need it as a int above
            # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days
            coin_label = self.change_cap(coin_label)
            title1 = "\n" + "\n" + coin_label + " " + changed + percent_change + "% - " + days
            mc = mpf.make_marketcolors(
                                up='tab:blue',down='tab:red',
                                wick={'up':'blue','down':'red'},
                                volume='tab:green',
                               )

            edited_style  = mpf.make_mpf_style(gridstyle = '-', facecolor = "lightgray", gridcolor = "white", edgecolor = "black", base_mpl_style = "classic", marketcolors=mc)
            mpf.plot(ohlc, type='candle', title = title1, figratio = (16,10), ylabel = 'Price - USD', style = edited_style, savefig = "candle.png")
            return ""
        else:
            return "error"

    def get_conversion(self, num, first, second):
        first_coin = ""
        second_coin = ""
        first_coin = self.check_coin(first)
        second_coin = self.check_coin(second)
        # check if the coin names are valid
        if first_coin == "" or second_coin == "":
            return "e"
        # retreive price data about the coins
        first_data = self.cg.get_price(ids= first_coin, vs_currencies='usd')
        first_price = first_data[first_coin]['usd']
        second_data = self.cg.get_price(ids= second_coin, vs_currencies='usd')
        second_price = second_data[second_coin]['usd']
        # convert to proper cap.
        first = self.change_cap(first)
        second = self.change_cap(second)
        conv_num = float(num) * (first_price / second_price)
        conversion = self.round_num(conv_num)
        conversion = self.check_large(conversion)
        num = self.check_large(int(num))
        embedResponse = discord.Embed(color=0x7A2F8F)
        embedResponse.add_field(name= first + " to " + second + " Conversion", value= str(num) + " " + first + " = " + str(conversion) + " " + second, inline=False)
        return embedResponse

    # functions to check coins, names, and size

    # round numbers correctly, sig figs for <1, rounding for >1
    def round_num(self, num):
        if num < 1:
            num = round(num, -int(floor(log10(abs(num)))))
            temp = num
            count = 0
            while temp < 1:
                temp *= 10
                count += 1
            format_string = "{:." + str(count) + "f}"
            num = format_string.format(float(str(num)))
            return num
        else:
            return round(num, 2)

    def check_coin(self, coin_name):
        coin_label = ""
        coin_name = coin_name.lower()
        for coin in self.cg.get_coins_list():
            if coin['id'] == coin_name or coin['symbol'] == coin_name:
                if coin['symbol'] == coin_name:
                    coin_label = coin['id']
                else:
                    coin_label = coin_name
                return coin_label
        return coin_label

    #find a better way of doing this instead of recopying the function
    def change_cap(self, coin_name):
        coin_label = ""
        coin_name = coin_name.lower()
        for coin in self.cg.get_coins_list():
            if coin['id'] == coin_name or coin['symbol'] == coin_name:
                if coin['symbol'] == coin_name:
                    coin_label = coin_name.upper()
                else:
                    coin_label = coin_name.lower()
                    coin_label = coin_label.capitalize()
                return coin_label
        return coin_label

    def check_large(self, num): #there are better ways but atm, its not important
        letter = ""
        num = float(num)
        if num == 0:
            return "Not Found"
        if num >= 1000000:
            letter = " M"
            num /= 1000000
            if (num >= 1000):
                letter = " B"
                num /= 1000
                if (num >= 1000):
                    letter = " T"
                    num /= 1000
        num = round(num, 2)
        if letter == "":
            num = "{:,}".format(num)
        return str(num) + letter

    def get_events(self):
        news = self.cg.get_events(country_code = 'US', type = "Eventf", page = 10, upcoming_events_only = False, from_date = "2019-01-01", to_date = "2020-10-02")
        return news['data']

    def get_list_exchanges(self):
        ex = self.cg.get_exchanges_list()
        response = "```List of Exchanges: " + "\n"
        for i in range(len(ex)):
            response += ex[i]['id'] + ", "
        response += "```"
        return response

    def get_global_data(self):
        print(self.cg.get_coins_markets(vs_currency = 'USD'))

    def get_global_defi_data(self):
        coin_label = ""
        news = self.cg.get_global_decentralized_finance_defi()
        def_mc = news['defi_market_cap']
        def_mc = float(def_mc)
        def_mc = round(def_mc,2)
        def_mc = "{:,}".format(def_mc)
        response = "```Defi Market Cap: $" + str(def_mc) + "\n"
        der = news['defi_to_eth_ratio']
        der = float(der)
        der = round(der,2)
        response += "Defi To Eth Ratio: " + str(der) + "\n"
        defi_dom = news['defi_dominance']
        defi_dom = float(defi_dom)
        defi_dom = round(defi_dom,2)
        response += "Defi Dominance: " + str(defi_dom) + "%" + "\n"
        tdc = news['top_coin_name']
        tdcmc = news['top_coin_defi_dominance']
        tdcmc = float(tdcmc)
        tdcmc = round(tdcmc,2)
        response += "Top Defi Coin: " + tdc + "\n" + "Top Defi Coin Dominance: " + str(tdcmc) + "%"+ "\n```"
        return response

    def gas(self):
        wei = self.es.get_gas_price()
        gwei = wei / 1000000000
        gwei = round(gwei, 2)
        avg_gas = 21000
        price_data = self.cg.get_price(ids= "ethereum", vs_currencies='usd')
        eth_price = price_data["ethereum"]['usd']
        eth_price = round(eth_price,3)
        usd_amount = (avg_gas * gwei / 1000000000) * eth_price
        usd_amount = round(usd_amount, 2)
        embedResponse = discord.Embed(title="Gas Price", color=0x0000ff)
        embedResponse.add_field(name="Gwei Price", value = str(gwei), inline=False)
        embedResponse.add_field(name="USD Price (avg trxn)", value= "$" + str(usd_amount), inline=False)
        return embedResponse

    def future(self):
        response = "BAND is a shitcoin [I'm not changing this Shi]"
        return response

    def error(self):
        response = "Not a valid command/coin"
        return response

    def find_member(self, bot, gld, mem_id):
        found_mem = None
        for guild in bot.guilds:
            if guild.name == gld:
                break
        members = '\n - '.join([member.name for member in guild.members])
        ids = [member.id for member in guild.members]
        for member in guild.members:
            if member.id == mem_id:
                return member
Ejemplo n.º 9
0
class discord_bot:
    # api instance
    cg = CoinGeckoAPI()
    es = etherscan.Client(
        api_key=bot_ids.etherscan_api_key,
        cache_expire_after=5,
    )

    # logging.basicConfig(filename="log.log", level=logging.INFO)

    global the_coin_list
    the_coin_list = copy.deepcopy(cg.get_coins_list())

    # functions to gather btc, eth, and any coins price
    def btc_status(self):
        price_data = self.cg.get_price(ids='bitcoin', vs_currencies='usd')
        price = price_data['bitcoin']['usd']
        if price != None:
            price = round(price, 2)
            price = "{:,}".format(price)
            response = "Bitcoin - $" + str(price)
            # logging.info("Logged BTC price at " + str(datetime.now()))
            return response
        else:
            # logging.warning("Error from CoinGecko at: " + str(datetime.now()))
            return "CoinGecko Error"

    def eth_status(self):
        price_data = self.cg.get_price(ids='Ethereum', vs_currencies='usd')
        price = price_data['ethereum']['usd']
        if price != None:
            price = round(price, 2)
            price = "{:,}".format(price)
            response = "Ethereum: $" + str(price)
            # logging.info("Logged ETH price at " + str(datetime.now()))
            return response
        else:
            # logging.warning("Error from CoinGecko at: " + str(datetime.now()))
            return "Coingecko Errors"

    def get_coin_price(self, coin_name):
        coin_label = ""
        coin_name = coin_name.lower()
        coin_label = self.check_coin(coin_name)
        if self.check_coin(coin_name) != "":
            price_data = self.cg.get_price(ids=coin_label,
                                           vs_currencies='usd',
                                           include_24hr_change='true',
                                           include_market_cap='true')
            price = price_data[coin_label]['usd']
            if price != None:
                if float(price) < 0.001:
                    price = round(price, 5)
                elif float(price) < 0.01:
                    price = round(price, 4)
                else:
                    price = round(price, 3)
                price = "{:,}".format(price)
                percent_change = price_data[coin_label]['usd_24h_change']
                if percent_change != None:
                    percent_change = str(round(percent_change, 2)) + "%"
                else:
                    percent_change = None
                market_cap = price_data[coin_label]['usd_market_cap']
                market_cap = round(market_cap, 2)
                market_cap = self.check_large(market_cap)
                if market_cap != "Not Found":
                    mc = "$" + market_cap
                else:
                    mc = market_cap
                # market_cap = "{:,}".format(market_cap)
                coin_name = self.change_cap(coin_name)
                # embedResponse = discord.Embed(title=coin_name + " Info", color=0xFF8C00)
                embedResponse = discord.Embed(title=coin_name + "'s" +
                                              " Stats",
                                              color=0xFF8C00)
                embedResponse.add_field(
                    name="Price",
                    value="[" + "$" + str(price) +
                    "](https://www.coingecko.com/en/coins/" + coin_label + ")",
                    inline=False)
                embedResponse.add_field(name="Percent Change (24hr)",
                                        value=str(percent_change),
                                        inline=False)
                embedResponse.add_field(name="Market Cap",
                                        value=mc,
                                        inline=False)
                embedResponse.set_footer(text="Powered by cryptobot.info")
                response1 = "```" + coin_name + "'s price: $" + str(
                    price) + "\n" + "Percent Change (24h): " + str(
                        percent_change) + "%" + "\n" + "Market Cap: $" + str(
                            market_cap) + "```"
                # response2 = "```" + coin_name + "'s price: $" + str(price) + ", " + "Percent Change (24h): " + str(percent_change) + "%" + "\n" + "Market Cap: $" + str(market_cap) + "```"
                return embedResponse
        return ""

    # retreive data and create candle chart of any coin
    def get_line_chart(self, coin_name, coin_name2, num_days, type):
        #all code that includes type 2 is for chart one currency against another

        #coin label work
        coin_label = ""
        coin_name = coin_name.lower()
        coin_label = self.check_coin(coin_name)
        #coin label 2 work
        if type == 2:
            coin_label2 = ""
            coin_name2 = coin_name2.lower()
            coin_label2 = self.check_coin(coin_name2)

        #checking if num days is valid
        temp = str(num_days)
        if not temp.isdigit():
            temp = temp.lower()
            if temp != "max":
                return False

        if self.check_coin(coin_name) != "":
            charts = self.cg.get_coin_market_chart_by_id(id=coin_label,
                                                         vs_currency='usd',
                                                         days=num_days)
            if type == 2:
                charts2 = self.cg.get_coin_market_chart_by_id(
                    id=coin_label2, vs_currency='usd', days=num_days)
            plt.close()
            x_vals = []
            y_vals = []
            count = 0
            open, close, high, low, volume = [], [], [], [], []
            min = len(charts["prices"])
            if type == 2:
                if min > len(charts2["prices"]):
                    min = len(charts2["prices"])
            for point in charts['prices']:
                if count == 0:
                    time_conv = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d')
                    time1 = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
                if count == 1:
                    time2 = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
                if count == min - 1:
                    time_end = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d')
                x_vals.append(time_conv)
                y_vals.append(point[1])
                volume.append(1)
                count += 1
                if count == min:
                    break
            if type == 2:
                count = 0
                for point in charts2['prices']:
                    if count == min:
                        break
                    y_vals[count] = y_vals[count] / point[1]
                    count += 1
            open = y_vals
            close = y_vals
            high = y_vals
            low = y_vals
            period = len(open)
            frequency = ""
            if num_days == "1":
                frequency = "5min"
            elif num_days != "max" and (int(num_days) <= 90
                                        and int(num_days) > 1):
                frequency = "1H"
            else:
                frequency = "4D"
            dti = pd.date_range(start=time_conv, end=time_end, periods=period)
            # print(dti2)
            # dti = pd.date_range(time_conv, periods=period, freq=frequency)
            ohlc = {
                "opens": open,
                "highs": high,
                "lows": low,
                "closes": close,
                "volumes": volume
            }
            ohlc = pd.DataFrame(data=ohlc, index=dti)
            ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume'
                            ]  #these two lines solved the dataframe problem
            ohlc.index.name = "Date"
            # plot and make it look good
            percent_change = (
                (close[len(close) - 1] - close[0]) / close[0]) * 100
            percent_change = round(percent_change, 2)
            changed, days = "", ""
            # change title based on days
            if num_days == "1":
                days = "the past 24 hours"
            elif num_days == "MAX" or num_days == "max":
                days = "Within Lifetime"
            else:
                days = "Past " + num_days + " Days"
            # change title based on percent
            if percent_change > 0:
                changed = "+"
            else:
                changed = ""

            percent_change = "{:,}".format(
                percent_change
            )  # had to do it here because this converts it to a string, need it as a int above
            # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days
            coin_label = self.change_cap(coin_label)
            title1 = "\n" + "\n" + coin_label + " " + changed + percent_change + "% - " + days
            if type == 2:
                coin_label2 = self.change_cap(coin_name2.lower())
                title1 = "\n" + "\n" + coin_label + "/" + coin_label2 + " " + changed + percent_change + "% - " + days
            mc = mpf.make_marketcolors(
                up='tab:blue',
                down='tab:red',
                wick={
                    'up': 'blue',
                    'down': 'red'
                },
                volume='tab:green',
            )
            edited_style = mpf.make_mpf_style(gridstyle='-',
                                              facecolor="lightgray",
                                              gridcolor="white",
                                              edgecolor="black",
                                              base_mpl_style="classic",
                                              marketcolors=mc)
            if type == 1:
                fig, axlist = mpf.plot(ohlc,
                                       type='line',
                                       title=title1,
                                       figratio=(30, 20),
                                       ylabel='Price - USD',
                                       style=edited_style,
                                       returnfig=True)
                ax1 = axlist[0]
                # ax1.yaxis.set_major_formatter(tick.FormatStrFormatter('%.8f'))
                ax1.yaxis.set_major_formatter(
                    tick.FuncFormatter(reformat_large_tick_values))
                fig.savefig('chart.png')
            else:
                fig, axlist = mpf.plot(ohlc,
                                       type='line',
                                       title=title1,
                                       figratio=(16, 10),
                                       ylabel=coin_label + "/" + coin_label2,
                                       style=edited_style,
                                       returnfig=True)
                ax1 = axlist[0]
                # ax1.yaxis.set_major_formatter(tick.FormatStrFormatter('%.8f'))
                ax1.yaxis.set_major_formatter(
                    tick.FuncFormatter(reformat_large_tick_values))
                fig.savefig('chart.png')
            return ""
        else:
            return "error"

    def get_tvl_chart(self, coin_name, coin_name2, num_days, type):
        #coin label work
        coin_label = ""
        coin_name = coin_name.lower()
        coin_label = self.check_coin(coin_name)
        #coin label 2 work

        valid_intervals = ["1w", "1m", "3m", "1y", "all", "max"]
        check_int = False
        num_days = num_days.lower()
        for interval in valid_intervals:
            if num_days == interval:
                check_int = True
        if not check_int:
            error_days = "```Command Error: Wrong number of days: Only can input '1w','1m','3m','1y','all','max'```"
            return error_days

        if type == 2:
            coin_label2 = ""
            coin_name2 = coin_name2.lower()
            coin_label2 = self.check_coin(coin_name2)

        if self.check_coin(coin_name) != "":
            link = "https://data-api.defipulse.com/api/v1/defipulse/api/GetHistory?api-key=" + bot_ids.defipulse_api_key + "&project=" + coin_name + "&period=" + num_days
            response = requests.get(link)
            output = response.json()
            y_vals = []
            x_vals = []
            count = 0
            min = len(output)
            volume = []
            for one_int in output:
                time_conv = time.strftime('%Y-%m-%d %H:%M:%S',
                                          time.localtime(one_int["timestamp"]))

                x_vals.append(time_conv)
                y_vals.append(one_int["tvlUSD"])
                volume.append(1)
                count += 1
            # check to see if the data is reversed
            if x_vals[0] > x_vals[1]:
                # reverse lists
                x_vals = x_vals[::-1]
                y_vals = y_vals[::-1]
            plt.close()
            open, close, high, low = y_vals, y_vals, y_vals, y_vals
            period = len(open)
            frequency = ""
            # if num_days == "1":
            #     frequency = "5min"
            # elif num_days != "max" and (int(num_days) <= 90 and int(num_days) > 1):
            #     frequency = "1H"
            # else:
            #     frequency = "4D"
            dti = pd.date_range(start=x_vals[0],
                                end=x_vals[len(x_vals) - 1],
                                periods=period)
            # print(dti2)
            # dti = pd.date_range(time_conv, periods=period, freq=frequency)
            ohlc = {
                "opens": open,
                "highs": high,
                "lows": low,
                "closes": close,
                "volumes": volume
            }
            ohlc = pd.DataFrame(data=ohlc, index=dti)
            ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume'
                            ]  #these two lines solved the dataframe problem
            ohlc.index.name = "Date"
            # plot and make it look good
            percent_change = (
                (close[len(close) - 1] - close[0]) / close[0]) * 100
            percent_change = round(percent_change, 2)
            changed, days = "", ""
            # change title based on days
            # if num_days == "1":
            #     days = "the past 24 hours"
            # elif num_days == "MAX" or num_days == "max":
            #     days = "Within Lifetime"
            # else:
            #     days = "Past " + num_days + " Days"
            # # change title based on percent
            # if percent_change > 0:
            #     changed = "+"
            # else:
            #     changed = ""

            percent_change = "{:,}".format(
                percent_change
            )  # had to do it here because this converts it to a string, need it as a int above
            # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days
            coin_label = self.change_cap(coin_label)
            title1 = "\n" + "\n" + coin_label + " " + "Historcal TVL: " + percent_change + "% - " + "Past " + num_days
            if type == 2:
                coin_label2 = self.change_cap(coin_name2.lower())
                title1 = "\n" + "\n" + coin_label + "/" + coin_label2 + " " + changed + percent_change + "% - " + days
            mc = mpf.make_marketcolors(
                up='tab:blue',
                down='tab:red',
                wick={
                    'up': 'blue',
                    'down': 'red'
                },
                volume='tab:green',
            )
            edited_style = mpf.make_mpf_style(gridstyle='-',
                                              gridcolor="white",
                                              edgecolor="black",
                                              base_mpl_style="nightclouds",
                                              marketcolors=mc)
            # edited_style  = mpf.make_mpf_style(gridstyle = '-', facecolor = "black", gridcolor = "white", edgecolor = "black", base_mpl_style = "classic", marketcolors=mc)
            if type == 1:
                fig, axlist = mpf.plot(ohlc,
                                       type='line',
                                       title=title1,
                                       figratio=(16, 10),
                                       ylabel='Price - USD ($)',
                                       style="nightclouds",
                                       returnfig=True)
                ax1 = axlist[0]
                # ax1.yaxis.set_major_formatter(tick.FormatStrFormatter('%.8f'))
                ax1.yaxis.set_major_formatter(
                    tick.FuncFormatter(reformat_large_tick_values))
                fig.savefig('ctvl.png')
            else:
                mpf.plot(ohlc,
                         type='line',
                         title=title1,
                         figratio=(16, 10),
                         ylabel=coin_label + "/" + coin_label2,
                         style=edited_style,
                         savefig="ctvl.png")
            return ""
        else:
            return "error"

    # retreive data and create candle chart of any coin
    def get_candle_chart(self, coin_name, num_days):

        # used the below links for the mpf libraries
        # https://github.com/matplotlib/mplfinance#usage
        # https://github.com/matplotlib/mplfinance/blob/master/examples/styles.ipynb

        #coin label work
        coin_label = ""
        coin_label = self.check_coin(coin_name)
        #checking if num days is valid
        valid_days = ["1", "7", "14", "30", "90", "180", "365", "MAX", "max"]
        check = False
        error_days = "```Command Error: Wrong number of days: Only can input '1','7','14','30','90','180','365','MAX'```"
        for day in valid_days:
            if num_days == day:
                check = True
        if check == False:
            return error_days

        if self.check_coin(coin_name) != "":
            candles = self.cg.get_coin_ohlc_by_id(id=coin_label,
                                                  vs_currency='usd',
                                                  days=num_days)
            plt.close()
            date_arr, year, month, day, hour, open, high, low, close, volume = [], [], [], [], [], [], [], [], [], []
            count = 0
            time_conv = ""
            for point in candles:
                # convert to standard date and time, parse and add them into arrays
                if count == 0:
                    time_conv = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d')
                if count == 0:
                    time1 = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
                if count == 1:
                    time2 = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
                if count == len(candles) - 1:
                    time_end = datetime.utcfromtimestamp(
                        point[0] / 1000).strftime('%Y-%m-%d')
                # parse and add in the OHLC vectors
                open.append(point[1])
                high.append(point[2])
                low.append(point[3])
                close.append(point[4])
                volume.append(1)
                count += 1
            # create the date and dataframe
            period = len(open)
            frequency = ""
            if num_days == "1":
                frequency = "30min"
            elif num_days == "7" or num_days == "14" or num_days == "30":
                frequency = "4H"
            else:
                frequency = "4D"
            dti = pd.date_range(start=time_conv, end=time_end, periods=period)
            # dti = pd.date_range(time_conv, periods=period, freq=frequency)
            ohlc = {
                "opens": open,
                "highs": high,
                "lows": low,
                "closes": close,
                "volumes": volume
            }
            ohlc = pd.DataFrame(data=ohlc, index=dti)
            ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume'
                            ]  #these two lines solved the dataframe problem
            ohlc.index.name = "Date"
            # plot and make it look good
            percent_change = (
                (close[len(close) - 1] - close[0]) / close[0]) * 100
            percent_change = round(percent_change, 2)
            changed, days = "", ""
            # change title based on days
            if num_days == "1":
                days = "the past 24 hours"
            elif num_days == "MAX" or num_days == "max":
                days = "Within Lifetime"
            else:
                days = "Past " + num_days + " Days"
            # change title based on percent
            if percent_change > 0:
                changed = "+"
            else:
                changed = ""

            percent_change = "{:,}".format(
                percent_change
            )  # had to do it here because this converts it to a string, need it as a int above
            # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days
            coin_label = self.change_cap(coin_label)
            title1 = "\n" + "\n" + coin_label + " " + changed + percent_change + "% - " + days
            mc = mpf.make_marketcolors(
                up='tab:blue',
                down='tab:red',
                wick={
                    'up': 'blue',
                    'down': 'red'
                },
                volume='tab:green',
            )

            edited_style = mpf.make_mpf_style(gridstyle='-',
                                              facecolor="lightgray",
                                              gridcolor="white",
                                              edgecolor="black",
                                              base_mpl_style="classic",
                                              marketcolors=mc)
            mpf.plot(ohlc,
                     type='candle',
                     title=title1,
                     figratio=(16, 10),
                     ylabel='Price - USD',
                     style=edited_style,
                     savefig="candle.png")
            return ""
        else:
            return "error"

    # function to get the ath, atl, and/or the range of the coin
    def get_all_time(self, symbol, coin_name):
        coin = ""
        coin = self.check_coin(coin_name)
        if coin == "":
            return "e"
        # get market data
        market_data = self.cg.get_coin_by_id(id=coin)
        ath = market_data["market_data"]["ath"]["usd"]
        atl = market_data["market_data"]["atl"]["usd"]
        # change the coin name capitalization
        coin_final = self.change_cap(coin)
        # then deduce based on type of prompt
        if symbol == "H":
            if ath != None and ath != "":
                ath = "{:,}".format(ath)
                embedResponse = discord.Embed(color=0xFF8C00)
                embedResponse.add_field(name=coin_final + " ATH",
                                        value="$" + str(ath),
                                        inline=False)
                return embedResponse
            else:
                return "e"
        elif symbol == "L":
            if atl != None and atl != "":
                atl = "{:,}".format(atl)
                embedResponse = discord.Embed(color=0xFF8C00)
                embedResponse.add_field(name=coin_final + " ATL",
                                        value="$" + str(atl),
                                        inline=False)
                return embedResponse
            else:
                return "e"
        elif symbol == "R":
            if ath != None and atl != None and ath != "" and atl != "":
                # get ath and atl prices
                ath = "{:,}".format(ath)
                atl = "{:,}".format(atl)
                # get current price
                price_data = self.cg.get_price(ids=coin,
                                               vs_currencies='usd',
                                               include_24hr_change='true',
                                               include_market_cap='true')
                price = price_data[coin]['usd']
                if price != None:
                    if float(price) < 0.001:
                        price = round(price, 5)
                    elif float(price) < 0.01:
                        price = round(price, 4)
                    else:
                        price = round(price, 3)
                    # format price for commas
                    price = "{:,}".format(price)
                    embedResponse = discord.Embed(title=coin_final + " Range",
                                                  color=0x0000ff)
                    embedResponse.add_field(name="All Time Low",
                                            value="$" + str(atl),
                                            inline=True)
                    embedResponse.add_field(name="Current Price",
                                            value="$" + str(price),
                                            inline=True)
                    embedResponse.add_field(name="All Time High",
                                            value="$" + str(ath),
                                            inline=True)
                    embedResponse.set_footer(text="Powered by cryptobot.info")
                    return embedResponse
                else:
                    return "e"
            else:
                return "e"

    # get an image of a coin
    def get_image(self, coin_name):
        coin = ""
        coin = self.check_coin(coin_name)
        if coin == "":
            return "e"
        # get coin image data
        output = self.cg.get_coin_by_id(id=coin)
        image_url = image_cg = output["image"]["small"]
        # change the coin name capitalization
        coin_final = self.change_cap(coin)

        # take image and save as png
        req = requests.get(image_url, headers={'User-Agent': 'Mozilla/5.0'})
        # webpage = urlopen(req).read()
        file = open("image.png", "wb")
        file.write(req.content)
        file.close()
        return coin_final

    def get_conversion(self, num, first, second):
        first_coin = ""
        second_coin = ""
        first_coin = self.check_coin(first)
        second_coin = self.check_coin(second)
        # check if the coin names are valid
        if first_coin == "" or second_coin == "":
            return "e"
        # retreive price data about the coins
        first_data = self.cg.get_price(ids=first_coin, vs_currencies='usd')
        first_price = first_data[first_coin]['usd']
        if first_data != None:
            second_data = self.cg.get_price(ids=second_coin,
                                            vs_currencies='usd')
            second_price = second_data[second_coin]['usd']
            if second_data != None:
                # convert to proper cap.
                first = self.change_cap(first)
                second = self.change_cap(second)
                conv_num = float(num) * (first_price / second_price)
                conversion = self.round_num(conv_num)
                conversion = self.check_large(conversion)
                num = self.check_large(int(num))
                embedResponse = discord.Embed(color=0x7A2F8F)
                embedResponse.add_field(
                    name=first + " to " + second + " Conversion",
                    value=str(num) + " " + first + " = " + str(conversion) +
                    " " + second,
                    inline=False)
                embedResponse.set_footer(text="Powered by cryptobot.info")
                return embedResponse
        else:
            embedResponse = discord.Embed(color=0x7A2F8F)
            embedResponse.add_field(name="Error",
                                    value="No data from CoinGecko",
                                    inline=False)
            return embedResponse
        return embedResponse

    def get_supply(self, coin):
        coin_name = ""
        coin_name = self.check_coin(coin)
        # check if the coin names are valid
        if coin_name == "":
            return "e"

        data = self.cg.get_coin_by_id(id=coin_name)
        csupply = data["market_data"]["circulating_supply"]
        tsupply = data["market_data"]["total_supply"]
        msupply = data["market_data"]["max_supply"]

        coin_name = self.change_cap(coin_name)
        csupply = self.check_large(csupply)
        tsupply = self.check_large(tsupply)
        msupply = self.check_large(msupply)

        embedResponse = discord.Embed(title=coin_name + "'s" + " Supply",
                                      color=0x00C09A)
        embedResponse.add_field(name="Circulating",
                                value=csupply,
                                inline=False)
        embedResponse.add_field(name="Total", value=tsupply, inline=False)
        embedResponse.add_field(name="Max", value=msupply, inline=False)
        embedResponse.set_footer(text="Powered by cryptobot.info")
        return embedResponse

    # find trending coins on coingecko
    def get_trending(self):
        numbering = range(1, 8)
        output = ""
        trendy = self.cg.get_search_trending()
        count = 0
        for x in trendy["coins"]:
            output += str(numbering[count]) + ") " + x['item']['name'] + "\n"
            count += 1
        embedResponse = discord.Embed(color=0x0099E1)
        embedResponse.add_field(name="Top Trending Coins on CoinGecko",
                                value=output)
        embedResponse.set_footer(text="Powered by cryptobot.info")
        return embedResponse

    # find trending coins on coingecko
    def get_rekt(self):
        count = 0
        # link = "https://data-api.defipulse.com/api/v1/rekto/api/top10?api-key=" + bot_ids.defipulse_api_key
        # link = "https://api.rek.to/api/top10?api-key=" + bot_ids.defipulse_api_key
        # response = requests.get(link)
        # output = response.json()
        # ids, amounts = "", ""
        # for idiot in output["top10"]:
        #     if count < 5:
        #         ids += str(idiot["id"]) + "\n"
        #         amounts += "$" + str(self.check_large(idiot["value_usd"])) + "\n"
        #         # amounts += str(self.check_large(int(idiot["value_usd"]))) +  "\n"
        #         count += 1
        # embedResponse = discord.Embed(title="Top 5 Rekts (Past 24hrs)", color=0x6d37da)
        # embedResponse.add_field(name = "Rekted Amount (USD)", value = amounts)
        # embedResponse.add_field(name = "The Rekt-ed", value = ids)
        embedResponse = discord.Embed(title="Error with API", color=0x6d37da)
        embedResponse.add_field(
            name="Depreciated",
            value="Defipulse deprecated the Rekt API endpoints")
        return embedResponse

    def get_mcap_to_tvl_ratio(self, coin):
        coin_name = ""
        coin_name = self.check_coin(coin)
        # check if the coin names are valid
        if coin_name == "":
            return "e"
        data = self.cg.get_coin_by_id(id=coin_name)
        ratio = data["market_data"]["mcap_to_tvl_ratio"]
        coin_name = self.change_cap(coin_name)
        embedResponse = discord.Embed(color=0xF8C300)
        embedResponse.add_field(name=coin_name + " Mcap to TVL Ratio",
                                value=str(ratio),
                                inline=False)
        embedResponse.set_footer(text="Powered by cryptobot.info")
        return embedResponse

    def get_tvl(self, coin):
        coin_name = ""
        coin_name = self.check_coin(coin)
        # check if the coin names are valid
        if coin_name == "":
            return "e"
        data = self.cg.get_coin_by_id(id=coin_name)
        try:
            tvl = data["market_data"]["total_value_locked"]["usd"]
            tvl = self.check_large(tvl)
        except:
            tvl = "None"
        coin_name = self.change_cap(coin_name)
        embedResponse = discord.Embed(color=0xF8C300)
        embedResponse.add_field(name=coin_name + " TVL",
                                value=str(tvl),
                                inline=False)
        embedResponse.set_footer(text="Powered by cryptobot.info")
        return embedResponse

    def get_gmr(self):
        options = webdriver.ChromeOptions()
        options.headless = True
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        options.add_argument("window-size=1024,768")
        options.add_argument("--no-sandbox")
        driver = webdriver.Chrome(
            executable_path="/root/cryptobot/chromedriver", options=options)
        driver.get(
            "https://www.lookintobitcoin.com/charts/golden-ratio-multiplier/")
        driver.execute_script("window.scrollTo(0, 260)")
        sleep(5)
        screenshot = driver.save_screenshot("grm.png")
        img = Image.open("grm.png")
        width, height = img.size
        img = img.crop((50, 0, width - 10, height - 200))
        img = img.save("grm.png", format="png")
        driver.quit()

    def get_mvrv(self):
        options = webdriver.ChromeOptions()
        options.headless = True
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        options.add_argument("window-size=1024,768")
        options.add_argument("--no-sandbox")
        driver = webdriver.Chrome(
            executable_path="/root/cryptobot/chromedriver", options=options)
        driver.get("https://www.lookintobitcoin.com/charts/mvrv-zscore/")
        driver.execute_script("window.scrollTo(0, 290)")
        sleep(5)
        screenshot = driver.save_screenshot("mvrv.png")
        img = Image.open("mvrv.png")
        width, height = img.size
        img = img.crop((0, 0, width - 10, height - 205))
        img = img.save("mvrv.png", format="png")
        driver.quit()

    # The Puell Multiple Chart
    def get_puell(self):
        options = webdriver.ChromeOptions()
        options.headless = True
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        options.add_argument("window-size=1024,768")
        options.add_argument("--no-sandbox")
        driver = webdriver.Chrome(
            executable_path="/root/cryptobot/chromedriver", options=options)
        driver.get("https://www.lookintobitcoin.com/charts/puell-multiple/")
        driver.execute_script("window.scrollTo(0, 300)")
        sleep(5)
        screenshot = driver.save_screenshot("puell.png")
        img = Image.open("puell.png")
        width, height = img.size
        img = img.crop((10, 0, width - 10, height - 220))
        img = img.save("puell.png", format="png")
        driver.quit()

    # The Pi Cycle Top Indicator
    def get_pi(self):
        options = webdriver.ChromeOptions()
        options.headless = True
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        options.add_argument("window-size=1024,768")
        options.add_argument("--no-sandbox")
        driver = webdriver.Chrome(
            executable_path="/root/cryptobot/chromedriver", options=options)
        driver.get(
            "https://www.lookintobitcoin.com/charts/pi-cycle-top-indicator/")
        driver.execute_script("window.scrollTo(0, 270)")
        sleep(5)
        screenshot = driver.save_screenshot("picycle.png")
        img = Image.open("picycle.png")
        width, height = img.size
        img = img.crop((10, 0, width - 10, height - 205))
        img = img.save("picycle.png", format="png")
        driver.quit()

    def get_ds(self):
        options = webdriver.ChromeOptions()
        options.headless = True
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        options.add_argument("window-size=1024,768")
        options.add_argument("--no-sandbox")
        driver = webdriver.Chrome(
            executable_path="/root/cryptobot/chromedriver", options=options)
        driver.get("https://www.defisocks.com/#/")
        last_height = driver.execute_script(
            "return document.body.scrollHeight")
        for i in range(0, 2):
            # Scroll down to bottom
            if i == 1:
                driver.execute_script("window.scrollTo(0, 3350);")
            # Wait to load page
            sleep(4)
            # Calculate new scroll height and compare with last scroll height
            new_height = driver.execute_script(
                "return document.body.scrollHeight")
            if new_height == last_height:
                break
            last_height = new_height
        screenshot = driver.save_screenshot("ds.png")
        img = Image.open("ds.png")
        width, height = img.size
        img = img.crop((320, 125, width - 340, height - 100))
        img = img.save("ds.png", format="png")
        driver.quit()

    def get_defisocks(self):
        results = self.es.get_token_transactions(
            contract_address="0x9d942bd31169ed25a1ca78c776dab92de104e50e")
        return results

    # functions to check coins, names, and size

    # round numbers correctly, sig figs for <1, rounding for >1
    def round_num(self, num):
        if num < 1:
            temp = num
            count = 1
            while temp < 1:
                temp *= 10
                count += 1
            return round(num, count)
        else:
            return round(num, 2)

    def check_coin(self, coin_name):
        coin_label = ""
        coin_name = coin_name.lower()
        if coin_name == "uni":
            coin_name = "uniswap"
        elif coin_name == "rbc":
            coin_name = "rubic"
        elif coin_name == "comp" or coin_name == "compound":
            coin_name = "compound-governance-token"
        elif coin_name == "graph" or coin_name == "thegraph":
            coin_name = "the-graph"
        for coin in the_coin_list:
            if coin['id'] == coin_name or coin['symbol'] == coin_name:
                if coin['symbol'] == coin_name:
                    coin_label = coin['id']
                else:
                    coin_label = coin_name
                return coin_label
        return coin_label

    #find a better way of doing this instead of recopying the function
    def change_cap(self, coin_name):
        coin_label = ""
        coin_name = coin_name.lower()
        for coin in the_coin_list:
            if coin['id'] == coin_name or coin['symbol'] == coin_name:
                if coin['symbol'] == coin_name:
                    coin_label = coin_name.upper()
                else:
                    coin_label = coin_name.lower()
                    coin_label = coin_label.capitalize()
                return coin_label
        return coin_label

    def check_large(self,
                    num):  #there are better ways but atm, its not important
        num = float(num)
        # check to see if num exists or less than 999, if so no need to compress
        if num == None:
            return "None"
        if num < 999:
            print("in here")
            return num
        if num == 0:
            return "Not Found"
        #start compressing
        letter = ""
        if num >= 1000000:
            letter = " M"
            num /= 1000000
            if (num >= 1000):
                letter = " B"
                num /= 1000
                if (num >= 1000):
                    letter = " T"
                    num /= 1000
        num = round(num, 2)
        if letter == "":
            num = "{:,}".format(num)
        return str(num) + letter

    def get_events(self):
        news = self.cg.get_events(country_code='US',
                                  type="Eventf",
                                  page=10,
                                  upcoming_events_only=False,
                                  from_date="2019-01-01",
                                  to_date="2020-10-02")
        return news['data']

    def get_list_exchanges(self):
        ex = self.cg.get_exchanges_list()
        response = "```List of Exchanges: " + "\n"
        for i in range(len(ex)):
            response += ex[i]['id'] + ", "
        response += "```"
        return response

    def get_global_data(self):
        print(self.cg.get_coins_markets(vs_currency='USD'))

    def get_global_defi_data(self):
        coin_label = ""
        news = self.cg.get_global_decentralized_finance_defi()
        def_mc = news['defi_market_cap']
        def_mc = float(def_mc)
        def_mc = round(def_mc, 2)
        def_mc = "{:,}".format(def_mc)
        response = "```Defi Market Cap: $" + str(def_mc) + "\n"
        der = news['defi_to_eth_ratio']
        der = float(der)
        der = round(der, 2)
        response += "Defi To Eth Ratio: " + str(der) + "\n"
        defi_dom = news['defi_dominance']
        defi_dom = float(defi_dom)
        defi_dom = round(defi_dom, 2)
        response += "Defi Dominance: " + str(defi_dom) + "%" + "\n"
        tdc = news['top_coin_name']
        tdcmc = news['top_coin_defi_dominance']
        tdcmc = float(tdcmc)
        tdcmc = round(tdcmc, 2)
        response += "Top Defi Coin: " + tdc + "\n" + "Top Defi Coin Dominance: " + str(
            tdcmc) + "%" + "\n```"
        return response

    def gas(self):
        wei = self.es.get_gas_price()
        gwei = wei / 1000000000
        gwei = round(gwei, 2)
        avg_gas = 21000
        price_data = self.cg.get_price(ids="ethereum", vs_currencies='usd')
        eth_price = price_data["ethereum"]['usd']
        eth_price = round(eth_price, 3)
        usd_amount = (avg_gas * gwei / 1000000000) * eth_price
        usd_amount = round(usd_amount, 2)
        embedResponse = discord.Embed(title="Gas Price", color=0x0000ff)
        embedResponse.add_field(name="Gwei Price",
                                value=str(gwei),
                                inline=False)
        embedResponse.add_field(name="USD Price (avg trxn)",
                                value="$" + str(usd_amount),
                                inline=False)
        return embedResponse

    def future(self):
        response = "BAND is a shitcoin [I'm not changing this Shi]"
        return response

    def error(self):
        embedResponse = discord.Embed(color=0xF93A2F)
        embedResponse.add_field(name="Error",
                                value="Not a valid command/coin",
                                inline=False)
        return embedResponse

    def find_member(self, bot, gld, mem_id):
        found_mem = None
        for guild in bot.guilds:
            if guild.name == gld:
                break
        members = '\n - '.join([member.name for member in guild.members])
        ids = [member.id for member in guild.members]
        for member in guild.members:
            if member.id == mem_id:
                return member

    def get_servers(self, bot):
        all = ""
        counter = 1
        for guild in bot.guilds:
            mem_count = guild.member_count
            all += "Server " + str(counter) + ": " + str(
                guild.name) + " (Size: " + str(mem_count) + ")" + "\n"
            counter += 1
        return all

    def help(self):
        help_info =  "```CryptoBot gives you sends live updates of " + \
        "any cryptocurrency!" + "\n" + "\n" + \
        "Commands:" + "\n" + "\n" + \
        "   Price Command: ![coin symbol/name], '!btc' or '!bitcoin' - retreive price information about a coin" + "\n" + "\n" + \
        "   Chart Command: '!chart btc 5' <chart> <coin> <num days> - retreive the line chart of a coin, only support USD as of now (ex: !chart link 30)" + "\n" + "\n" + \
        "   Chart Command: '!chart btc 5' <chart> <coin1> <coin2> <num days> - retreive the line chart of two coins coupled (ex: !chart link btc 30)" + "\n" + "\n" + \
        "   Candle Command: '!candle btc 5' <chart> <coin_name/symbol> <num days>, "\
        "days has to be one of these:" + "\n" + "   '1','7','14','30','90','180','365','MAX' - retreive the candle chart of a coin" + "\n" + "\n" + \
        "   Suggestion Command: !suggestion or !suggestions do this' <suggestion> <message> - send a suggestion for the bot" + "\n" + "\n" + \
        "   Gas Command: '!gas' - get information about gwei prices" + "\n" + "\n" + \
        "   Convert Command: '!convert <num> <coin1> <coin2>' - get conversion rate of num of coin1 in number of coin2 (ex: !convert 1000 usdc btc)" + "\n" + "\n" + \
        "   Global Defi Stats Command: '!global-defi' - get global information about defi" + "\n" + "\n" + \
        "   Top Trending Coins Command: '!trendy - get the top trending coins on CoinGecko" + "\n" + "\n" + \
        "   Supply Command: '!supply <coin> - get the circulating and maximum supply of a coin" + "\n" + "\n" + \
        "   Golden Ratio Multiple Indicator (BTC) (Unavailable): '!grm-chart" + "\n" + "\n" + \
        "   Puell Multiple Indicator (BTC) (Unavailable): '!puell-chart" + "\n" + "\n" + \
        "   MVRV Z-Score Indicator (BTC) (Unavailable): '!mvrv-chart" + "\n" + "\n" + \
        "   PI Cycle Top Indicator (BTC) (Unavailable): '!pi-chart" + "\n" + "\n" + \
        "   ATH, ATL, Range Commands: '!ath [coin], !atl [coin], !range [coin]" + "\n" + "\n" + \
        "   Image Command: '!image [coin]" + "\n" + "\n" + \
        "   TVL Command: '!tvl [coin]" + "\n" + "\n" + \
        "   Mcap to TVL Ratio Command: '!tvl-ratio [coin]" + "\n" + "\n" + \
        "   Defisocks (Unavailable): '!defisocks" + "\n" + "\n" + \
        "   ATH, ATL, Range: '!ath [coin], !atl [coin], !range [coin]" + "\n" + "\n" + \
        "Credits to CoinGecko® and Etherscan® for their free APIs!```"

        return help_info
Ejemplo n.º 10
0
from django.conf import settings

if not hasattr(settings, 'ETHERSCAN_API_KEY'):
    raise ValueError("ETHERSCAN_API_KEY not found in local_settings")

ETHERSCAN_API_KEY = settings.ETHERSCAN_API_KEY

if not hasattr(settings, 'ETH_ADDRESS_LIST'):
    raise ValueError("ETH_ADDRESS_LIST not found in local_settings")

ETH_ADDRESS_LIST = settings.ETH_ADDRESS_LIST

import etherscan

es = etherscan.Client(
    api_key=ETHERSCAN_API_KEY,
    cache_expire_after=5,
)

eth_price = es.get_eth_price()
print("----- eth_price -----\n", eth_price)

eth_supply = es.get_eth_supply()
print("----- eth_supply -----\n", eth_supply)

eth_balance = es.get_eth_balance(ETH_ADDRESS_LIST[0])
print("----- eth_balance -----\n", eth_balance)

eth_balances = es.get_eth_balances(ETH_ADDRESS_LIST)
print("----- eth_balances -----\n", eth_balances)

gas_price = es.get_gas_price()
import os
import etherscan
from web3 import Web3
from datetime import date
import plotly.graph_objects as go
import plotly as py

py.offline.init_notebook_mode(connected=True)
import pandas as pd
import datetime
'''
Gets Eth price and adds it to the EtherPrice CSV
'''
#for etherscan API
es = etherscan.Client(
    api_key='XHT1QMF1HM8QM1JQJA68WNPTJF2WP1JM84',
    cache_expire_after=5,
)

eth_price = es.get_eth_price()
eth_price_str = str(eth_price['ethusd'])

today = date.today()
day = today.strftime("%m/%d/%y")
row_contents = str(day + ',' + '-' + ',' + eth_price_str)
with open('EtherPrice.csv', 'a') as fd:
    fd.write('\n' + row_contents)

print('Updated ETH Value for today')
'''
Takes the last 30 rows from full EtherPrice CSV
Places them into their own CSV files to be used to
Ejemplo n.º 12
0
#
# MODIFICATIONS:
#
# Initial mod. version: --------
# Final mod. version:   --------
#
# TODO_dd_mmm_yyyy - TODO_describe_appropriate_changes - TODO_name
#--------------------------------------------------------------------------
import etherscan
import transferValue as transfer
import os

#Public key to test: 0x140427a7D27144A4cDa83bD6b9052a63b0c5B589

es = etherscan.Client(
    api_key='https://ropsten.infura.io/v3/963aa3c429b5444cb0e007241f8bf0fd',
    cache_expire_after=5,
)
"""
Function: login
Input: account (a public address)
Returns: --
Description: It presents the balance of an account as well as allowing users to
explore transactions associated within the account or to make transactions of
Ether or Tokens
"""


def login(account):
    print("\n ---------------- Account login ----------------")
    print("Account: " + account)
    balance = es.get_eth_balance(account)
Ejemplo n.º 13
0
import pandas as pd
import etherscan

omniscope_api = OmniscopeApi()

# read the records associated to the first block input
input_data = omniscope_api.read_input_records(input_number=0)

# read the value of the option called "my_option"
apikey = omniscope_api.get_option("apikey")

address = omniscope_api.get_option("address")
addresses = input_data[address].tolist()

es = etherscan.Client(
    api_key=apikey,
    cache_expire_after=5,
)

method = omniscope_api.get_option("method")
output_data = None

if method == "get_eth_balance":
    eth_balance = es.get_eth_balance(addresses[0])
    output_data = pd.DataFrame({'ETH Balance': [eth_balance]})
elif method == "get_eth_balances":
    for i in range(0, len(addresses), 20):
        chunk = addresses[i:i + 20]
        eth_balance = es.get_eth_balances(chunk)
        df = pd.DataFrame(list(eth_balance.items()),
                          columns=['Account', 'Balance'])
        if output_data is None:
Ejemplo n.º 14
0
'''
Python script that generates random ethereum addresseses and checks
for an existing balance. Mathematically you are more likely to win the lottery every day
of your life than to ever find one but everyone enjoys a good treasure hunt
'''

from secrets import token_bytes
from coincurve import PublicKey
from sha3 import keccak_256
import etherscan
import time
import asyncio
es = etherscan.Client(

    # Get an API key from Etherscan.io
    api_key='ENTER YOUR ETHERSCAN API KEY HERE',
    cache_expire_after=5,
    )


f = open('keys.txt', 'w')

###########################
# Checks if transactions have ocurred on the address
# @param address -> an Ethereum compatible hex address 0x...
# @return the transactions list object
###########################
def transaction_check(address):
    print(address)
    transactions = es.get_transactions_by_address(address)
    # Uncomment sleep or change the paramater to slow down or speed up API calls
Ejemplo n.º 15
0
def get_interactions(fname):
    chief_contract = web3.eth.contract(address=CHIEF, abi=CHIEF_ABI)
    #LOCK = 'dd467064'
    VOTE = 'ed081329'
    #FREE = 'd8ccd0f3'
    #MINT_TOPIC = '0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885'
    #BURN_TOPIC = '0xcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca5'
    VOTE_TOPIC = '0xed08132900000000000000000000000000000000000000000000000000000000'

    spells = []
    list = list_spells()
    list.sort(key=lambda x: x.created)
    for s in list:
        spells.append(s.address)

    voters = []
    with open(fname) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            voters.append(row[0])

    interactions = []
    es = etherscan.Client(api_key=config['ETHERSCAN_API']['key'],
                          cache_expire_after=5)
    for i in voters:
        txs = es.get_transactions_by_address(i, limit=5000)
        print('\ntxs for {0}'.format(i))
        time.sleep(1)

        votes_locked = 0
        for k in txs:
            input_chars = str(k['input'][2:10])
            if ((k['tx_receipt_status'] == False)
                    or (k['block_number'] > END_BLOCK)
                    or (k['block_number'] < START_BLOCK)):
                continue

            if (input_chars == VOTE):
                tx_rec = web3.eth.getTransactionReceipt(k['hash'])
                #print('hash: {0}'.format(k['hash']))
                #print('length k input: {0}'.format(len(k['input'])))
                for j in range(0, len(tx_rec['logs'])):
                    if ((web3.toHex(bytes(tx_rec['logs'][j]['topics'][0]))
                         == VOTE_TOPIC) and (len(k['input']) == 202)):
                        slate_voted_for = '0x' + str(
                            tx_rec['logs'][j]['data'][354:394])
                        if (slate_voted_for in spells):
                            amt_mkr = chief_contract.functions.deposits(
                                i).call(block_identifier=tx_rec['blockNumber']
                                        ) / ETH_SCALE
                            if (amt_mkr != 0):
                                interactions.append(
                                    Interaction(i, slate_voted_for, amt_mkr,
                                                tx_rec['blockNumber'],
                                                k['hash']))
                                print(
                                    'spell voted for: {0} with {1} MKR in block {2}'
                                    .format(slate_voted_for, amt_mkr,
                                            tx_rec['blockNumber']))
                        break

    return interactions
Ejemplo n.º 16
0
with open(eligible_tokens_path) as json_file:
    eligible = json.load(json_file)

for network in eligible.keys():
	
	# mainnet/testnet tokens
	network_name = network;

	# etherscan API expects mainnet specifier to be None
	if network_name=="homestead":
		network_name=None;
	
	# connect to etherscan API for specific network
	es = etherscan.Client(
		network=network_name,
		api_key=api_key,
		cache_expire_after=max_queries_per_sec,
	)

	# get all whitelisted token addresses for current network
	token_addresses = (eligible[network].keys())

	# if file already exists, don't bother looking up all the symbols again
	# we'll still check for updated caps though
	network_dict = {};
	network_dict_in = {};
	tokens = [];
	if performing_update:
		network_dict_in = out_dict[network];
		tokens = list(network_dict_in.keys());
Ejemplo n.º 17
0
import pandas as pd
from web3 import Web3
import etherscan
from datetime import datetime
import schedule
import time
from os import getenv
from dotenv import load_dotenv

load_dotenv()

es = etherscan.Client(api_key=getenv('ETHERSCAN'))
w3 = Web3(Web3.HTTPProvider(getenv('INFURA')))

rarible_contract = '0xcd4EC7b66fbc029C116BA9Ffb3e59351c20B5B06'
rarible = pd.read_csv('../rarible.csv', index_col=0)

def mp_transactions(address):
    columns = ['timestamp', 'block_number', 'from', 'to', 'input', 'hash', 'value', 'gas', 
                'gas_price', 'gas_used', 'nonce', 'confirmations', 'is_error', 'tx_receipt_status', 
                'transaction_index', 'cumulative_gas_used', 'block_hash']

    transactions = []

    start_block = rarible['block_number'].iloc[-1]

    for l in es.get_transactions_by_address(address, start_block=start_block, limit=9999):
        time.sleep(.2)
        transactions.append(l)

    df = pd.DataFrame(transactions, columns=columns)
Ejemplo n.º 18
0
import etherscan
import tinydb


__VERSION__ = (6, 2, 1)
ETHERSCAN_KEY = "T772QZEA6VGYD2UMTW5ZT4JJ98AVM6KVME"
ETHEREUM_NETWORK = "ropsten"


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
coloredlogs.install(fmt="%(asctime)-15s %(message)s", datefmt="%m/%d %H:%M:%S", logger=logger)
app = flask.Flask(__name__)
rpc = flask_jsonrpc.JSONRPC(app, "/", enable_web_browsable_api=True)
cache = tinydb.TinyDB("./cache.json")
etherscan_client = lambda: etherscan.Client(ETHERSCAN_KEY, network=ETHEREUM_NETWORK)
brainwallet = lambda data, security = 2000: web3.Web3.sha3(text=str(data) * security)
address = lambda account: eth_account.Account.privateKeyToAccount(brainwallet(account)).address
balances = {}


@rpc.method("getinfo")
def getinfo():
    return {
        "name": "RPC Masq v{}.{}.{}".format(*__VERSION__),
        "plugins": ["ethereum", "web3", "etherscan", "ropsten"],
    }


@rpc.method("listtransactions")
def listtransactions(account, limit):