def get_global_price(self):
        """Gets how much this currency is worth, in terms of 1 USD."""
        if self.symbol.upper() in STABLECOIN_SYMBOLS or self.symbol.upper(
        ) == 'USD':
            return 1

        if not _is_symbol_a_cryptocurrency(self.symbol.upper()):
            #  Cryptocompare and Google don't know what's the actual free market ARS exchange rate
            #  https://en.wikipedia.org/wiki/Argentine_currency_controls_(2011%E2%80%932015)#Return_of_the_controls
            if self.symbol.upper() == 'ARS':
                price = get_ars_criptoya()
            result = json.loads(google_currency.convert(self.symbol, 'usd', 1))
            if result['converted'] is True:
                price = float(result['amount'])
            else:
                price = cryptocompare.get_price(
                    self.symbol, currency='USD')[self.symbol.upper()]['USD']
        else:
            try:
                price = get_chainlink_price(self.symbol)
            except ValueError:
                try:
                    price = binance_oracle.fetch_ticker(
                        f"{self.symbol.upper()}/USDT")['bid']
                except ccxt.base.errors.BadSymbol:
                    # Cryptocompare is used as a last resort because it has shitty rate limits
                    price = cryptocompare.get_price(
                        self.symbol,
                        currency='USD')[self.symbol.upper()]['USD']

        return price
示例#2
0
def payment(request, pay_id):
    form = PaymentsInfoForm(request.POST)

    if request.method == "POST":
        women = People.objects.get(id=pay_id)
        money = int(request.POST['amount'])
        converted = convert('usd', 'kgs', money)
        json_acceptable_string = converted.replace("'", "\"")
        d = json.loads(json_acceptable_string)

        women.remaining_amount = str(
            float(women.money_for_collecting) - float(d['amount']))
        women.get_money = str(float(women.get_money) + float(d['amount']))
        women.save()
        save_form = PaymentsInfoForm(request.POST)

        if save_form.is_valid():
            women_w = save_form.save(commit=False)
            women_w.for_whom = women
            payment = save_form.save()

            return redirect('news:index')
    else:
        form = PaymentsInfoForm()
    return render(request, 'payment.html', {"form": form})
def conversion():
	reverse=(currency_value.get()[::-1])
	codes_=(reverse[1:4:])
	working_codes_from=codes_[::-1]
	reverse_1=(currencies_value_to.get()[::-1])
	codes_1=(reverse_1[1:4:])
	working_codes_to=codes_1[::-1]
	try:
		error_handling=int(Amount_value.get())
	except Exception:
		messagebox.showinfo('Info','Please Enter A Valid Number!')
	try:
		print('Converting... Amount Is Converting...')
		Va=convert(working_codes_from,working_codes_to,error_handling)
		reverse=(Va[::-1])
		check_1=(reverse[1:6])
		value11=(check_1[::-1])
		total_amount=(re.findall("\\d+\\.\\d+",Va))
		for value___ in total_amount:
			pass
		if currency_value.get()=='Select Currency':
			messagebox.showinfo('Info','Please Select A From Currency!')
		elif currencies_value_to.get()=='Select Currency':
			messagebox.showinfo('Info','Please Select A To Currency!')
		elif currency_value.get()=='Select Currency' and currencies_value_to.get()=='Select Currency':
			messagebox.showinfo('Info','Please Select A From,To Currency!')

		elif value11==' true':
			Amount_.set(f'{Amount_value.get()} {working_codes_from} = {value___} {working_codes_to}')
		else:
			messagebox.showinfo('Info','Not Converted! Currency Is Not Correct Or Check Your Network Connection Speed Is Slow Or Not If Slow Thats Why Currency Is Not Converted! If Your Connection Speed Is Fast MayBe Thats A Bug In My Programme You Are Free To Report Me At Mail:[email protected] Or Check Network Connectivity!')
	except UnboundLocalError:
		 ''
示例#4
0
async def currency_convert_cmd(client, message):
    """convert various currencies
	
	Currency price checker and conversion tool. Accept many currency tickers, like `.currency btc` \
	or `.currency btc 20 eur`.
	Will use Google Currency for values, and if currency is not found there, cryptocompare.
	Add flag `-crypto` to directly search cryptocompare.
	"""
    if len(message.command) < 1:
        return await edit_or_reply(message, "`[!] → ` Not enough arguments")
    await client.send_chat_action(message.chat.id, "choose_contact")
    val = float(message.command[1] or 1.0)
    from_ticker = message.command[0]
    to_ticker = message.command[2] or "USD"
    converted_val = 0.0
    res = {"converted": False}
    if not bool(message.command["-crypto"]):
        res = json.loads(convert(from_ticker, to_ticker, val))
    if res["converted"]:
        to_ticker = res["to"]
        converted_val = float(res["amount"])
    else:
        res = cryptocompare.get_price(from_ticker, currency=to_ticker)
        if not res:
            return await edit_or_reply(message,
                                       "`[!] → ` Invalid currency ticker")
        from_ticker = list(res.keys())[0]
        to_ticker = list(res[from_ticker].keys())[0]
        converted_val = val * float(res[from_ticker][to_ticker])
    await edit_or_reply(message, f"` → ` **{sep(converted_val)}** {to_ticker}")
示例#5
0
 async def currency(self, ctx, amount, frm, to):
     x = convert(frm, to, float(amount))
     y = json.loads(x)
     frm1 = y['from']
     to1 = y['to']
     amount1 = y['amount']
     cnvrtd1 = y['converted']
     embed = discord.Embed(colour=0x520081, title="Currency Converter")
     embed.set_thumbnail(url="https://w7.pnging.com/pngs/712/357/png-transparent-exchange-rate-currency-computer-icons-foreign-exchange-market-coin-coin-text-logo-exchange.png")
     embed.add_field(name="Original:", value=f"{amount} {frm1}")
     embed.add_field(name="Converted:", value=f"{amount1} {to1}")
     await ctx.send(embed=embed)
def functionbutton():
    try:
        lightbox = Combobox1.get()
        heavybox = Combobox2.get()
        lapto = dictop[lightbox]
        lapti = dictop[heavybox]
        serial = var1.get() 
        opol = convert(lapto, lapti, serial)
        lope = json.loads(opol)
        jsonfix = lope["amount"]
        var2.set(jsonfix)
    except:
        rr = messagebox.askretrycancel("A Problem Has Been Occured", "Please Check your Internet Connection or Check the Amount You Have Entered.")
示例#7
0
async def currency_convert_cmd(client, message):
    if len(message.command) < 4:
        return await edit_or_reply(message, "`[!] → ` Not enough arguments")
    try:
        logger.info("Converting currency")
        await client.send_chat_action(message.chat.id, "choose_contact")
        res = json.loads(
            convert(message.command[2], message.command[3],
                    float(message.command[1])))
        await edit_or_reply(message, f"` → ` {res['amount']} {res['to']}")
    except Exception as e:
        traceback.print_exc()
        await edit_or_reply(message, "`[!] → ` " + str(e))
    await client.send_chat_action(message.chat.id, "cancel")
    await client.set_offline()
示例#8
0
def get_forex_goog(from_cur, to_cur):
    from google_currency import convert
    for _ in range(5):
        try:
            res = json.loads(convert(from_cur, to_cur, 1))
            print(res)
            print(type(res))
            if res['converted']:
                a = get_float_or_none_from_string(res['amount'])
                if a:
                    return a
        except Exception as ex:
            print(
                f'goog exception while getting forex rate for: {from_cur} to {to_cur} {ex}'
            )
            time.sleep(5)
    return None
示例#9
0
def convert_money(origin_currency: str, target_currency: str,
                  amount: float) -> float:
    """
    Convert a certain amount of money from one currency to another.

    :param origin_currency: Origin currency
    :param target_currency: Target currency
    :param amount: Amount of money to convert
    :return: Converted amount
    """
    result = convert(origin_currency.upper(), target_currency.upper(), amount)
    result = json.loads(result)
    succeed = result.get('converted', False)

    # Check if the conversion completed successfully and return the converted
    # amount, otherwise return zero.
    if not succeed:
        return 0

    converted_amount = float(result.get('amount', 0))

    return converted_amount
示例#10
0
def eur_to_zar():
    return convert('eur', 'zar', 1)
示例#11
0
                'hkd ( hong kong )', 'huf ( hungary )', 'isk ( iceland )',
                'idr ( indonesia )', 'irr ( iran )', 'xcd ( grenada )',
                'iqd ( iraq )', 'ils ( israel )', 'jmd ( jamaica )',
                'jpy ( japan )', 'jod ( jordan )', 'kzt ( kazakhstan )',
                'kes ( kenya )', 'kwd ( kuwait )', 'lbp ( lebanon )',
                'lyd ( libya )', 'myr ( malaysia )', 'mxn ( mexico )',
                'npr ( nepal )', 'omr ( oman )', 'pkr ( pakistan )',
                'php ( philippines )', 'pln ( poland )', 'lrd ( liberia )',
                'mvr ( maldives )', 'qar ( qatar )', 'sgd ( singapore)',
                'lkr ( sri lanka )', 'sek ( sweden )', 'chf ( switzerland )',
                'tjs ( tajikistan )', 'thb ( thailand )', 'try ( turkey )',
                'ugx ( uganda )', 'yer ( yemen )', 'mad ( western sahara )'
            ])

            # The output comes in a string , so making it proper by using string slice and a for loop
            currency_cnt = convert(input_from[0:3], input_to[0:3], num1)

            # Getting the symbol of the entered currency
            symbol = curr.get_symbol(input_to[0:3].upper())

            list1 = []
            length = currency_cnt[40:100]
            for i in currency_cnt:
                if i.isdigit():
                    list1.append(i)

            # Both selection same
            if input_from == input_to:
                num11.markdown('  1.00')

            # Selection different
示例#12
0
def index():

    #Url's for weather and country info API

    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=393c1b4f02ee0aa5afe38fa55e0160e3'
    url2 = 'https://restcountries.eu/rest/v2/alpha/{}'

    #Arrays to store information about cities

    all_info = []

    cities = []

    #Getting data from the database

    city = db.execute("SELECT name FROM city")

    user_city = db.execute("SELECT city FROM users WHERE id = :userid",
                           userid=session["user_id"])

    preferences = db.execute(
        "SELECT * FROM preferences WHERE user_id = :userid",
        userid=session["user_id"])

    #Setting preferences to display

    currency_type = preferences[0]["currency"]

    distance_type = preferences[0]["distance"]

    degree_type = preferences[0]["degree"]

    #Adding cities on the database to an array

    for i in range(len(city)):

        cities.append(city[i]["name"])

    #Getting information about all cities on the array

    for city in cities:

        weather = requests.get(url.format(city)).json()
        country = weather["sys"]["country"]
        info = requests.get(url2.format(country)).json()
        data = convert(currency_type, info["currencies"][0]["code"], 1)
        currency = json.loads(data)

        temp = round(((float(weather["main"]["temp"]) - 32) * 5) / 9)

        #Checking the preferences

        if degree_type == "F":

            temp = round(float(weather["main"]["temp"]))

        distancee = distance(user_city[0]["city"], city)

        if distance_type == "miles":

            distancee = round((distance(user_city[0]["city"], city) * 5) / 8)

        #Adding all informationa about a city to a dictionary

        new_city = {
            "name": city,
            "temp": temp,
            "description": weather["weather"][0]["description"].capitalize(),
            "icon": weather["weather"][0]["icon"],
            "degree_type": degree_type,
            "currency_price": currency["amount"],
            "currency_name": currency["to"],
            "currency_type": currency_type,
            "flag": info["flag"],
            "distance": distancee,
            "distance_type": distance_type,
            "time_zone": info["timezones"][0]
        }

        #Adding city with details in a array

        all_info.append(new_city)

    return render_template("index.html", all_info=all_info)
示例#13
0
from google_currency import convert

Money = convert("RUB", "USD", 20)

print(Money)













from google_currency import convert

# Converte de acordo com a moeda desejada
data = convert('usd', 'inr', 100)

print(data)
示例#15
0
# pip install google_currency

from google_currency import convert

# Converter dolar(USD) para Reais(BRL)
data = convert('usd', 'brl', 1)

print(data)
# {"from": "USD", "to": "BRL", "amount": "4.80", "converted": true}

# Converter Euro(EUR) para Reais(BRL)
data = convert('eur', 'brl', 1)

print(data)
# {"from": "EUR", "to": "BRL", "amount": "5.19", "converted": true}