-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcplclick.py
77 lines (62 loc) · 2.12 KB
/
cplclick.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import csv
import os
import typer
import requests
app = typer.Typer()
COIN_GECKO_SIMPLE_PRICE_URL = "https://api.coingecko.com/api/v3/simple/price?ids={}&vs_currencies={}"
def _read_portfolio_dict():
if os.path.exists("portfolio.csv"):
with open("portfolio.csv", "r") as csvfile:
reader = csv.reader(csvfile)
data = dict(
[(row[0], float(row[1])) for row in reader]
)
return data
return {}
def _write_portfolio_dict(data):
with open("portfolio.csv", "w") as csvfile:
writer = csv.writer(csvfile)
for (coin_id, quantity) in data.items():
if float(quantity) > 0:
writer.writerow([coin_id, quantity])
@app.command(short_help="search for a coin")
def search(
coin,
currency = typer.Option("usd")
):
coin_data = requests.get(COIN_GECKO_SIMPLE_PRICE_URL.format(coin, currency)).json()
print(f"The current price of {coin} is {coin_data[coin][currency]}")
@app.command(short_help="view your portfolio")
def portfolio(
coin_id = typer.Option(None),
currency = typer.Option("usd")
):
data = _read_portfolio_dict()
coin_data = requests.get(COIN_GECKO_SIMPLE_PRICE_URL.format(",".join(data.keys()), currency)).json()
if coin_id is None:
for (coin_id, quantity) in data.items():
print(f"{quantity} {coin_id} with {quantity * coin_data[coin_id][currency]}")
else:
print(f"{data[coin_id]} {coin_id} worth {data[coin_id] * coin_data[coin_id][currency]}")
@app.command(short_help="buy coins")
def buy(
coin_id = typer.Option(...),
quantity: float = typer.Option(...)
):
data = _read_portfolio_dict()
if coin_id in data:
data[coin_id] = float(data[coin_id]) + quantity
else:
data[coin_id] = quantity
_write_portfolio_dict(data)
@app.command(short_help="sell coins")
def sell(
coin_id = typer.Option(...),
quantity: float = typer.Option(...)
):
data = _read_portfolio_dict()
if coin_id in data:
data[coin_id] = float(data[coin_id]) - quantity
_write_portfolio_dict(data)
if __name__ == "__main__":
app()