-
Notifications
You must be signed in to change notification settings - Fork 16
/
robinhoodAPI.py
110 lines (106 loc) · 3.97 KB
/
robinhoodAPI.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# Nelson Dane
# Robinhood API
import os
import robin_stocks.robinhood as rh
from time import sleep
import pyotp
from dotenv import load_dotenv
def robinhood_init():
# Initialize .env file
load_dotenv()
# Import Robinhood account
if not os.getenv("ROBINHOOD_USERNAME") or not os.getenv("ROBINHOOD_PASSWORD"):
print("Robinhood not found, skipping...")
return None
RH_USERNAME = os.environ["ROBINHOOD_USERNAME"]
RH_PASSWORD = os.environ["ROBINHOOD_PASSWORD"]
if os.environ["ROBINHOOD_TOTP"]:
RH_TOTP = os.environ["ROBINHOOD_TOTP"]
totp = pyotp.TOTP(RH_TOTP).now()
else:
totp = None
# Log in to Robinhood account
print("Logging in to Robinhood...")
try:
if not totp:
rh.login(RH_USERNAME, RH_PASSWORD)
else:
print("Using Robinhood TOTP")
rh.login(RH_USERNAME, RH_PASSWORD, mfa_code=totp)
except Exception as e:
print(f"Error: Unable to log in to Robinhood: {e}")
return None
print("Logged in to Robinhood!")
return rh
async def robinhood_holdings(rh, ctx=None):
print()
print("==============================")
print("Robinhood Holdings")
print("==============================")
print()
# Make sure init didn't return None
if rh is None:
print("Error: No Robinhood account")
return None
try:
# Get account holdings
positions = rh.get_open_stock_positions()
if positions == []:
print("No holdings in Robinhood")
if ctx:
await ctx.send("No holdings in Robinhood")
else:
print("Holdings in Robinhood:")
if ctx:
await ctx.send("Holdings in Robinhood:")
for item in positions:
# Get symbol, quantity, price, and total value
sym = item['symbol'] = rh.get_symbol_by_url(item['instrument'])
qty = float(item['quantity'])
current_price = round(float(rh.stocks.get_latest_price(sym)[0]), 2)
total_value = round(qty * current_price, 2)
print(f"{sym}: {qty} @ ${(current_price)} = ${total_value}")
if ctx:
await ctx.send(f"{sym}: {qty} @ ${(current_price)} = ${total_value}")
except Exception as e:
print(f'Robinhood: Error getting account holdings: {e}')
if ctx:
await ctx.send(f'Robinhood: Error getting account holdings: {e}')
async def robinhood_transaction(rh, action, stock, amount, price, time, DRY=True, ctx=None):
print()
print("==============================")
print("Robinhood")
print("==============================")
print()
action = action.lower()
stock = stock.upper()
amount = int(amount)
# Make sure init didn't return None
if rh is None:
print("Error: No Robinhood account")
return None
if not DRY:
try:
# Buy Market order
if action == "buy":
rh.order_buy_market(stock, amount)
print(f"Robinhood: Bought {amount} of {stock}")
if ctx:
await ctx.send(f"Robinhood: Bought {amount} of {stock}")
# Sell Market order
elif action == "sell":
rh.order_sell_market(stock, amount)
print(f"Robinhood: Sold {amount} of {stock}")
if ctx:
await ctx.send(f"Robinhood: Sold {amount} of {stock}")
else:
print("Error: Invalid action")
return None
except Exception as e:
print(f'Robinhood: Error submitting order: {e}')
if ctx:
await ctx.send(f'Robinhood: Error submitting order: {e}')
else:
print(f"Robinhood: Running in DRY mode. Trasaction would've been: {action} {amount} of {stock}")
if ctx:
await ctx.send(f"Robinhood: Running in DRY mode. Trasaction would've been: {action} {amount} of {stock}")