Skip to content

Commit 400fca7

Browse files
Update and Add functionalities to the old CLI ver. of Cryptocurrency Converter (Fixed and Refactored.) (HarshCasper#845)
* Update the old CLI ver of crypto_converter.py and fix a few errors. * Updated the script with suggested refactors and fixes. * Added an EOF
1 parent c3de7af commit 400fca7

File tree

1 file changed

+111
-86
lines changed

1 file changed

+111
-86
lines changed
Lines changed: 111 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,135 @@
1-
"""we will be using coinbase API as it is public
2-
More info below
1+
"""We will be using coinbase API as it is public.
32
https://developers.coinbase.com/api/v2?python#get-exchange-rates"""
43

54
import requests
65

6+
def exchange_rates(exchange_type):
7+
"""This function gets exhange rates. The coinbase API returns the JSON for an input cryptocurrency
8+
with data or exhangerate of one coin to all known "normal" fiat currencies like BTC(input) to INR, USD etc."""
9+
exchange_type = exchange_type.upper()
10+
response_obj = requests.get(f"https://api.coinbase.com/v2/exchange-rates?currency={exchange_type}")
711

8-
def exchange_rates(cryptocurrency):
9-
"""
10-
This function gets exhange rates.
11-
The coinbase API returns the JSON for an input cryptocurrency with
12-
data or exhangerate of one coin to all known "normal" fiat currencies
13-
like BTC(input) to INR,USD,etc.
14-
"""
15-
16-
# capitalising the cryptocurrency values as the API accepts and returns
17-
cryptocurrency = cryptocurrency.upper()
18-
19-
# These are the cryptocurrency available currently by the API.
20-
# "BTC" is for Bitcoin,"ETH" is for Ethereum and so on
21-
available_cryptocurrencies = [
22-
'BTC', 'ETH', 'ETC', 'BCH', 'LTC', 'ZEC', 'ZRX']
23-
24-
if cryptocurrency not in available_cryptocurrencies:
25-
return None
26-
27-
# sending a request to the api and storing the response object in r variable
28-
response_obj = requests.get(
29-
'https://api.coinbase.com/v2/exchange-rates?currency='+cryptocurrency)
30-
31-
try:
32-
exchange_dict = response_obj.json()["data"]["rates"]
33-
except KeyError:
34-
return None
12+
try: exchange_dict = response_obj.json()["data"]["rates"]
13+
except: return None
3514
return exchange_dict
3615

37-
# This function converts currency amount to cryptocurrency amount
38-
3916

40-
def convert_currency_to_crypto(amount, currency, cryptocurrency):
41-
"""This function converts currency amount to cryptocurrency amount"""
42-
43-
# checking that the input is correct
44-
try:
45-
amount = float(amount)
46-
except ValueError:
47-
return "wrong input!"
17+
def convert_fiat_to_crypto(fvalue, ftype, ctype):
18+
"""This function converts Fiat Money to Cryptocurrency amount.
19+
Returns 1 if the input is found not valid, converted currency value if the input is found valid, else returns "None".
20+
"fvalue" corresponds to Fiat Money value, "ftype" to Fiat Money type and "ctype" to Cryptocurrency type --> all given by the user."""
21+
flag, statement = validity_of_currencytype(ctype, ftype)
22+
if flag == 1:
23+
print(statement)
24+
return 1
4825

4926
# get current_price for cryptocurrency using exhange_rates function
50-
current_price = exchange_rates(cryptocurrency)[currency]
51-
27+
try: current_price = exchange_rates(ftype)[ctype]
28+
except:
29+
print("nNo Information Available. We're Sorry!")
30+
return
5231
if current_price is None:
53-
return "No info available"
54-
55-
return amount/float(current_price)
32+
print("\nNo Information Available. We're Sorry!")
33+
return
34+
return float(current_price)*fvalue
5635

5736

58-
def convert_crypto_to_currency(amount, cryptocurrency, currency):
59-
"""This function converts currency amount to cryptocurrency amount"""
60-
61-
# Just checking the input
62-
try:
63-
amount = float(amount)
64-
except ValueError:
65-
return "wrong input!"
37+
def convert_crypto_to_fiat(cvalue, ctype, ftype):
38+
"""This function converts Cryptocurrency amount to Fiat Money.
39+
Returns 1 if the input is found not valid, converted currency value if the input is found valid, else returns "None".
40+
"cvalue" corresponds to Cryptocurrency value, "ctype" to Cryptocurrency type and "ftype" to Fiat Money type --> all given by the user."""
41+
flag, statement = validity_of_currencytype(ctype, ftype)
42+
if flag == 1:
43+
print(statement)
44+
return 1
6645

6746
# get current_price for cryptocurrency using exhange_rates function
68-
current_price = exchange_rates(cryptocurrency)[currency]
69-
47+
try: current_price = exchange_rates(ctype)[ftype]
48+
except:
49+
print("\nNo Information Available. We're Sorry!")
50+
return
7051
if current_price is None:
71-
return "No info available"
52+
print("\nNo Information Available. We're Sorry!")
53+
return
54+
return float(current_price)*cvalue
7255

73-
return float(current_price)*amount
7456

57+
def validity_of_currencytype(ctype, ftype):
58+
"""This function checks if the user input of Cryptocurrency type or Fiat Money type are truly the latter.
59+
Returns 1 if found an error in the input, else returns 0."""
60+
available_cryptocurrencies = ['BTC', 'ETH', 'ETC', 'BCH', 'LTC', 'ZEC', 'ZRX']
61+
if ctype not in available_cryptocurrencies:
62+
return 1, f"\n{ctype} is not a Cryptocurrency. Try Again!\n"
63+
elif ftype in available_cryptocurrencies:
64+
return 1, f"\n{ftype} is not a Fiat Money. Try Again!\n"
65+
else:
66+
return 0, "\nAll Good!"
7567

76-
if __name__ == "__main__":
77-
STRING = """
78-
################################################################
79-
80-
examples of fiat currencies :INR,USD,etc.
81-
examples of Cryptocurrencies :BTC,ETH,etc.
82-
83-
################################################################
84-
85-
Choose one of the below options:
86-
87-
Convert Cryptocurrency to fiat currency (Enter 1)
88-
Convert fiat currency to Cryptocurrency (Enter 2)
89-
Quit (Enter Q)
90-
"""
9168

69+
def main():
70+
"""This function loops through the input given by the user, until given a bad input or "Q/q". """
9271
while True:
93-
print(STRING)
94-
user_inp = input()
95-
currency = input("Enter fiat currency type:").upper()
96-
cryptocurrency = input("Enter Cryptocurrency type:").upper()
97-
amount = int(input("Enter Cryptocurrency amount:"))
98-
print("\n")
72+
user_inp = input("\n\tEnter Your Choice Here : ")
73+
9974
if user_inp == "1":
100-
result = convert_crypto_to_currency(
101-
amount, cryptocurrency, currency)
102-
print(f"{amount} {cryptocurrency} in {currency} is {result}")
75+
crypto_type = input("\nEnter the Cryptocurrency Type : ")
76+
fiat_type = input("Enter the Fiat Money Type : ")
77+
try: crypto_value = float(input("\nEnter the Cryptocurrency Value : "))
78+
except:
79+
print("Bad Input!\nPlease Enter \"y\" if you wish to continue, else \"n\".")
80+
choice = input()
81+
if choice == "y": continue
82+
elif choice == "n": return
83+
else:
84+
print("Bad Input Again!")
85+
return
86+
result = convert_crypto_to_fiat(crypto_value, crypto_type.upper(), fiat_type.upper())
87+
if result is None: return
88+
elif result == 1: continue
89+
print(f"{crypto_value} {crypto_type.upper()} in {fiat_type.upper()} is --> {result}")
90+
10391
elif user_inp == "2":
104-
result = convert_crypto_to_currency(
105-
amount, cryptocurrency, currency)
106-
print(f"{amount} {currency} in {cryptocurrency} is {result}")
107-
elif user_inp == "Q":
108-
break
92+
fiat_type = input("\nEnter the Fiat Money Type : ")
93+
crypto_type = input("Enter the Cryptocurrency Type : ")
94+
try: fiat_value = float(input("\nEnter the Fiat Money Value : "))
95+
except:
96+
print("You did not enter a number!\nPlease Enter \"y\" if you wish to continue, else \"n\".")
97+
choice = input()
98+
if choice == "y": continue
99+
elif choice == "n": return
100+
else:
101+
print("Bad Input Again!")
102+
return
103+
result = convert_fiat_to_crypto(fiat_value, fiat_type.upper(), crypto_type.upper())
104+
if result is None: return
105+
elif result == 1: continue
106+
print(f"{fiat_value} {fiat_type.upper()} in {crypto_type.upper()} is --> {result}")
107+
108+
elif user_inp == "Q" or user_inp == "q": return
109+
109110
else:
110-
print("Wrong Input! try again")
111+
print("\nYour Input was NOT in the choices. Try again later.\n")
112+
return
113+
114+
115+
if __name__ == "__main__":
116+
"""The driver code."""
117+
info_msg = """
118+
We convert currency -> Cryptocurrency to Fiat Money and vice-versa.\n\n
119+
Possible Cryptocurrencies available for conversion are :
120+
\t BTC : Bitcoin
121+
\t ETH : Ethereum.
122+
\t ETC : Ethereum Classic
123+
\t BCH : Bitcoin Cash
124+
\t LTC : Litecoin
125+
\t ZEC : Zcash
126+
\t ZRX : Ox\n\n
127+
Press (1) : To convert Cryptocurrency to Fiat Money.
128+
Press (2) : To convert Fiat Money to Cryptocurrency.
129+
Press (Q/q) : If you're wanting to Quit
130+
"""
131+
print(info_msg)
132+
stat = main()
133+
if stat is not None:
134+
print(stat)
135+

0 commit comments

Comments
 (0)