Пример #1
0
def convert(c1, c2, amount):
    try:
        if amount == "":
            messagebox.showerror("Error", "Amount not specified")
        elif c1 == "Select" or c2 == "Select":
            messagebox.showinfo("Error", "Currency not selected")
        else:
            try:
                amount = float(amount)
                b = BtcConverter()
                c = CurrencyRates()
                if c1 == c2:
                    result = amount
                elif c1 == "BTC":
                    result = b.convert_btc_to_cur(amount, c2)
                elif c2 == "BTC":
                    result = b.convert_to_btc(amount, c1)
                else:
                    result = c.convert(c1, c2, int(amount))
                print(result)
                label_down[
                    "text"] = f"Conversion Result: {amount} {c2}\n{amount} {c1} = {result} {c2}"
            except ValueError:
                messagebox.showerror("Error", "Invalid amount")
                clear()
    except Exception:
        messagebox.showerror("Error", "Please try again")
Пример #2
0
def arcturus_cal(money, arcturus_rate, c_type, bonus=0):
    c = CurrencyRates()
    b = BtcConverter()
    print(c_type)
    if c_type == "USD":
        if int(money) >= 100:
            usd = float(money)
            no_of_btc = b.convert_to_btc(usd, 'USD')
            return {"no_of_arcturus": float(usd) / float(arcturus_rate)}
        else:
            return {
                "no_of_arcturus":
                "Error... Minimum transaction should be more then 100 usd"
            }
    elif c_type.upper() == "BTC":
        usd = b.convert_btc_to_cur(float(money), 'USD')
        if int(usd) >= 100:
            usd = float(usd)
            return {"no_of_arcturus": float(usd) / float(arcturus_rate)}
        else:
            return {
                "no_of_arcturus":
                "Minimum transaction should be more then 100 usd"
            }
    else:
        return {"no_of_arcturus": "Usupported cryptotype.... "}
Пример #3
0
 async def execute(self, args, msg):
     amount, origin, destination = args
     try:
         amount = Decimal(amount)
     except Exception as _:
         raise ValueError(f'Cannot parse decimal: {amount}')
     try:
         o_code, o_symbol = self.currency_code_and_symbol(origin)
     except TypeError:
         raise ValueError(f'Unknown currency: {origin}')
     try:
         d_code, d_symbol = self.currency_code_and_symbol(destination)
     except TypeError:
         raise ValueError(f'Unknown currency: {destination}')
     c = CurrencyRates()
     if o_code == 'BTC':
         b = BtcConverter()
         res = b.convert_btc_to_cur(amount, 'USD')
         if d_code != 'USD':
             res = c.convert('USD', d_code, res)
     elif d_code == 'BTC':
         b = BtcConverter()
         if o_code != 'USD':
             amount = c.convert(o_code, 'USD', amount)
         res = b.convert_to_btc(amount, o_code)
     else:
         res = c.convert(o_code, d_code, amount)
     res = self.format_number(res, 4, 2)
     await msg.channel.send(f'{amount: f} {o_code} = {res or 0} {d_code}')
def convert(amount, input_currency, output_currency):
    input_currency_code = get_currency_code(input_currency)
    if input_currency_code is None:  # Input currency code was not found - unknown currency
        raise UnknownCurrencyError

    if output_currency is not None:
        output_currency_code = get_currency_code(output_currency)
        if output_currency_code is None:  # Output currency code was not found - unknown currency
            raise UnknownCurrencyError
        currency_data = [{'cc': output_currency_code}]
    else:
        # Getting currency data from file
        currency_data = get_currency_data()

    c = CurrencyRates()
    b = BtcConverter()
    output_currencies = dict(
    )  # Dictionary to store converted amounts for each currency

    # Converting currency
    for item in currency_data:
        if item['cc'] == input_currency_code:  # Out currency == in currency
            if output_currency is None:
                continue
            else:
                raise SameCurrencyError

        try:
            if input_currency_code == "BTC":  # Bitcoin is input currency
                output_currencies[item['cc']] = round(
                    b.convert_btc_to_cur(amount, item['cc']), 2)

            elif item['cc'] == "BTC":  # Bitcoin is output currency
                output_currencies[item['cc']] = round(
                    b.convert_to_btc(amount, input_currency_code), 5)

            else:  # Other currencies than bitcoin
                output_currencies[item['cc']] = round(
                    c.convert(input_currency_code, item['cc'], amount), 2)

        except RatesNotAvailableError:
            if output_currency is None:  # Output currency not entered, currencies without available rates are skipped
                pass
            else:  # Output currency entered => not available currency rate yields error
                raise RatesNotAvailableError

    output_data = dict()
    output_data['input'] = {'amount': amount, 'currency': input_currency_code}
    output_data['output'] = output_currencies

    return json.dumps(output_data, indent='\t')
Пример #5
0
    def currencyconv(self, jarvis, amount, fr, to):
        """
        currencyconv converts the given amount to another currency
        using fore-python
        """

        b = BtcConverter(force_decimal=True)
        c = CurrencyRates(force_decimal=True)

        if (to == "BTC"):
            result = b.convert_to_btc(Decimal(amount), fr)
        elif (fr == "BTC"):
            result = b.convert_btc_to_cur(Decimal(amount), to)
        else:
            result = c.convert(fr, to, Decimal(amount))

        jarvis.say(str(result))
Пример #6
0
    def currencyconv(self, jarvis, amount, fr, to):
        """
        currencyconv converts the given amount to another currency
        using fore-python
        """

        b = BtcConverter(force_decimal=True)
        c = CurrencyRates(force_decimal=True)

        if (to == "BTC"):
            result = b.convert_to_btc(Decimal(amount), fr)
        elif (fr == "BTC"):
            result = b.convert_btc_to_cur(Decimal(amount), to)
        else:
            result = c.convert(fr, to, Decimal(amount))
        outputText = str(amount) + " " + fr + \
            " are equal to " + str(result) + " " + to
        jarvis.say(outputText)
Пример #7
0
class TestBitCoinForceDecimal(TestCase):
    def setUp(self):
        self.b = BtcConverter(force_decimal=True)

    def test_latest_price_valid_currency(self):
        price = self.b.get_latest_price('USD')
        self.assertEqual(type(price), Decimal)

    def test_latest_price_invalid_currency(self):
        price = self.b.get_latest_price('XYZ')
        self.assertFalse(price)

    def test_previous_price_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        price = self.b.get_previous_price('USD', date_obj)
        self.assertEqual(type(price), Decimal)

    def test_previous_price_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.get_previous_price,
                          'XYZ', date_obj)

    def test_previous_price_list_with_valid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('USD', start_date,
                                                    end_date)
        self.assertTrue(price_list)
        self.assertEqual(type(price_list), dict)

    def test_previous_price_list_with_invalid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('XYZ', start_date,
                                                    end_date)
        self.assertFalse(price_list)
        self.assertEqual(type(price_list), dict)

    def test_convet_to_btc_with_valid_currency(self):
        coins = self.b.convert_to_btc(Decimal('250'), 'USD')
        self.assertEqual(type(coins), Decimal)

    def test_convet_to_btc_with_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc,
                          Decimal('250'), 'XYZ')

    def test_convert_btc_to_cur_valid_currency(self):
        amount = self.b.convert_btc_to_cur(Decimal('2'), 'USD')
        self.assertEqual(type(amount), Decimal)

    def test_convert_btc_to_cur_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur,
                          Decimal('250'), 'XYZ')

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        coins = self.b.convert_to_btc_on(Decimal('300'), 'USD', date_obj)
        self.assertEqual(type(coins), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc_on,
                          Decimal('250'), 'XYZ', date_obj)

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        amount = self.b.convert_btc_to_cur_on(Decimal('250'), 'USD', date_obj)
        self.assertEqual(type(amount), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur_on,
                          Decimal('3'), 'XYZ', date_obj)
Пример #8
0
pozadovana_mena = input('Zadej pozadovanou menu')
pozadovane_mnozstvi = int(input('Zadej pozadovane mnozstvi'))

from forex_python.converter import CurrencyRates
prevodnik = CurrencyRates()
pozadovano_v_cilove_mene = pozadovane_mnozstvi
cena_v_korunach = prevodnik.convert(pozadovana_mena, 'CZK',
                                    pozadovano_v_cilove_mene)
print(cena_v_korunach)

mena = input('Zadej menu')
pozadovane_mnozstvi_bitcoinu = int(input('Zadej pozadovane mnozstvi bitcoinu'))

from forex_python.bitcoin import BtcConverter
b = BtcConverter()
b.convert_btc_to_cur(pozadovane_mnozstvi_bitcoinu, mena)
print(b.convert_btc_to_cur(pozadovane_mnozstvi_bitcoinu, mena))
Пример #9
0
to_currency = input('To : ').upper()

print('\n' + from_currency + " To " + to_currency, amount)
print('The current conversion rate for {} to {} is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency)))    #Get conversion rate from USD to INR
result = c.convert(from_currency, to_currency, amount)   #Convert the amount
print('Latest Conversion: ',result)

#Get conversion rate as of 2021-01-01
print('\nThe conversion rate from {} to {} as per 1st Jan 2021 is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency, date_obj)))
print('The conversion as per 1st Jan 2021: ', c.convert(from_currency, to_currency, amount, date_obj))

b = BtcConverter()
print('\n\nBitcoin Symbol: ', b.get_symbol())  # get_btc_symbol()
print('Bitcoin Latest Price in USD : ', b.get_latest_price('USD'))     #Get latest Bitcoin price.
print('Convert 10 Million USD to Bitcoin', b.convert_to_btc(10000000, 'USD'))     #Convert Amount to Bitcoins based on latest exchange price.
print('The Equivalent of 10.99 Bitcoin in USD: ',b.convert_btc_to_cur(10.99, 'USD'))         #Convert Bitcoins to valid currency amount based on lates price

print('\nBitcoin price as per 1st Jan 2021: ',b.get_previous_price('USD', date_obj)) #Get price of Bitcoin based on prevois date
print('The conversion of 10 Million Dollars to Bitcoin as of 1st Jan 2021',b.convert_to_btc_on(10000000, 'USD', date_obj))      #Convert Amount to bitcoins based on previous date prices
print('The conversion of 10.99 Bitcoin in USD as of 1st Jan 2021: ',b.convert_btc_to_cur_on(10.99, 'USD', date_obj))       #Convert Bitcoins to valid currency amount based on previous date price

start_date = datetime.datetime(2021, 2, 1, 19, 39, 36, 815417)
end_date = datetime.datetime(2021, 2, 7, 19, 39, 36, 815417)
print('\nBitcoin rates over the week in USD: ',b.get_previous_price_list('USD', start_date, end_date))         #Get list of prices list for given date range

d = CurrencyCodes()
print('\nUS Dollar Symbol:', d.get_symbol('USD'))          #Get currency symbol using currency code
print(d.get_currency_name('USD'))          #Get Currency Name using currency code

print('\nThe latest rate of USD for various currencies\n', c.get_rates('USD'))          #list all latest currency rates for "USD"
print('\nThe rate of USD for various currencies as per 1st Jan 2021\n',c.get_rates('USD', date_obj))             #List all Currency rates for “USD” on 2021-01-01
Пример #10
0
class BitcoinBackend:
    UNCONFIRMED_ADDRESS_BALANCE = 0
    CONFIRMED_ADDRESS_BALANCE = 1
    UNDERPAID_ADDRESS_BALANCE = -1
    NO_HASH_ADDRESS_BALANCE = -2

    def __init__(self, public_key):
        self.public_key = public_key
        self.converter = BtcConverter()

    def get_address_output_value(self, address, outputs):
        for output in outputs:
            if address in output["addresses"]:
                return output["value"]

    def generate_new_address(self, index):
        """
        Generate new bitcoin address from a hd public master key based on a particlar index
        Address can be generated sequentially like in the case of electrum
        :param index: Index to use to generate address
        :return: Generated address
        """
        address = btc.pubkey_to_address(
            btc.bip32_descend(self.public_key, [0, index]))
        return address

    def convert_from_fiat(self, amount, currency="USD"):
        """
        Convert a fiat amount to bitcoin
        :param amount: Fiat amount to convert
        :param currency: Fiat currency
        :return: Rounded btc amount
        """
        res = self.converter.convert_to_btc(amount, currency)
        return round(res, 8)

    def convert_to_fiat(self, amount, currency):
        """
        Convert a btc amount to fiat amount
        :param amount: BTC amount to convert
        :param currency: Fiat currency to convert
        :return: Amount in specified currency
        """
        res = self.converter.convert_btc_to_cur(amount, currency)
        return round(res, 2)

    def confirm_address_payment(
        self,
        address,
        total_crypto_amount,
        confirmation_number=1,
        accept_confirmed_bal_without_hash_mins=20,
        tx_hash=None,
    ):
        """
        Confirm if a payment was made to a specified address.
        A payment that was already confirmed on the blockchain before running
        this tool can still be seen as paid by specifying a time
        frame such payment was confirmed and the time this tool is used on accept_confirmed_bal_without_hash_mins.
        :param address: Address to check for payment
        :param total_crypto_amount: Amount to check
        :param accept_confirmed_bal_without_hash_mins : You can accept already confirmed payment within this minute
         if there is no previous hash provided
        :param tx_hash: Transaction hash if any can be gotten from this method if payment is unconfirmed
        :param confirmation_number: Block chain confirmations below this are returned as unconfirmed
        :return: UNCONFIRMED_ADDRESS_BALANCE, traansaction hash | CONFIRMED_ADDRESS_BALANCE, payment_amount |
                    UNDERPAID_ADDRESS_BALANCE, remaining_crypto_amount |  NO_HASH_ADDRESS_BALANCE, None
        """
        if tx_hash:
            transaction = get_transaction_details(transaction_hash=tx_hash)
            value = self.get_address_output_value(address,
                                                  transaction["outputs"])
            if value is None:
                return self.NO_HASH_ADDRESS_BALANCE, None
            return self._check_balance_confirmations(
                transaction["confirmations"],
                transaction["hash"],
                confirmation_number,
                value,
                total_crypto_amount,
            )
        data = get_address_details(address)
        if data["unconfirmed_balance"] != 0 and data["unconfirmed_n_tx"] > 0:
            return (
                self.UNCONFIRMED_ADDRESS_BALANCE,
                extract_latest_transaction(
                    data["unconfirmed_txrefs"])["tx_hash"],
            )

        elif (data["unconfirmed_balance"] == 0
              and data["unconfirmed_n_tx"] == 0 and data["total_received"] > 0
              and data["n_tx"] > 0):

            transaction = extract_latest_transaction(data["txrefs"],
                                                     key="confirmed")
            if tx_hash == transaction["tx_hash"]:
                value = transaction["value"]
            elif tx_hash:

                transaction = get_transaction_details(transaction_hash=tx_hash)
                value = self.get_address_output_value(address,
                                                      transaction["outputs"])
                if value is None:
                    return self.NO_HASH_ADDRESS_BALANCE, None
            else:
                # There is a confirmed balance and we dont have any old  hash to track it
                transaction = confirm_transaction_date_without_previous_hash(
                    transaction,
                    accept_confirmed_bal_without_hash_mins,
                    key="confirmed")
                if transaction is None:
                    return self.NO_HASH_ADDRESS_BALANCE, None
                value = transaction["value"]

            return self._check_balance_confirmations(
                transaction["confirmations"],
                transaction["tx_hash"],
                confirmation_number,
                value,
                total_crypto_amount,
            )
        else:
            return NO_HASH_ADDRESS_BALANCE, None

    def _check_balance_confirmations(
        self,
        transaction_confirmations,
        tx_hash,
        confirmation_number,
        sent_value,
        total_crypto_amount,
    ):
        if transaction_confirmations < confirmation_number:
            return self.UNCONFIRMED_ADDRESS_BALANCE, tx_hash
        sent_btc_amount = convert_from_satoshi(sent_value)
        if sent_btc_amount < total_crypto_amount:
            remaining_crypto_amount = total_crypto_amount - sent_btc_amount
            return self.UNDERPAID_ADDRESS_BALANCE, remaining_crypto_amount
        return self.CONFIRMED_ADDRESS_BALANCE, sent_value
Пример #11
0
from forex_python.bitcoin import BtcConverter
from forex_python.converter import CurrencyCodes

b = BtcConverter()
c = CurrencyCodes()

# print(b.get_latest_price("INR"))

#quantity,currency  (input)   --> output price 

quantity = float(input("Enter the quantity of Bitcoin you wanna Buy : "))
currency = input("Currency you wanna pay : ")
currency_symbol = c.get_symbol(currency)

bitcoin_symbol = b.get_symbol()

price = b.convert_btc_to_cur(quantity,currency)

print(f"{quantity}{bitcoin_symbol}  : {currency_symbol}{price}")