forked from joshfraser/robinhood-to-csv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Robinhood.py
204 lines (173 loc) · 7.7 KB
/
Robinhood.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import json
import requests
import urllib
try:
from urllib.request import urlretrieve #py3
except ImportError:
from urllib import urlretrieve # py2
class Robinhood:
endpoints = {
"accounts": "https://api.robinhood.com/accounts/",
"ach_iav_auth": "https://api.robinhood.com/ach/iav/auth/",
"ach_relationships": "https://api.robinhood.com/ach/relationships/",
"ach_transfers": "https://api.robinhood.com/ach/transfers/",
"applications": "https://api.robinhood.com/applications/",
"document_requests": "https://api.robinhood.com/upload/document_requests/",
"dividends": "https://api.robinhood.com/dividends/",
"edocuments": "https://api.robinhood.com/documents/",
"employment": "https://api.robinhood.com/user/employment",
"investment_profile": "https://api.robinhood.com/user/investment_profile/",
"instruments": "https://api.robinhood.com/instruments/",
"login": "https://api.robinhood.com/oauth2/token/",
"margin_upgrades": "https://api.robinhood.com/margin/upgrades/",
"markets": "https://api.robinhood.com/markets/",
"notification_settings": "https://api.robinhood.com/settings/notifications/",
"notifications": "https://api.robinhood.com/notifications/",
"orders": "https://api.robinhood.com/orders/",
"password_reset": "https://api.robinhood.com/password_reset/request/",
"portfolios": "https://api.robinhood.com/portfolios/",
"positions": "https://api.robinhood.com/positions/",
"quotes": "https://api.robinhood.com/quotes/",
"user": "https://api.robinhood.com/user/",
"watchlists": "https://api.robinhood.com/watchlists/",
"optionsOrders":"https://api.robinhood.com/options/orders/",
"optionsPositions":"https://api.robinhood.com/options/positions/"
}
session = None
username = None
password = None
headers = None
auth_token = None
positions = None
client_id = "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS"
##############################
#Logging in and initializing
##############################
def __init__(self):
self.session = requests.session()
try:
self.session.proxies = urllib.getproxies() #py2
except:
self.session.proxies = urllib.request.getproxies() #py3
self.headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"X-Robinhood-API-Version": "1.0.0",
"Connection": "keep-alive",
"User-Agent": "Robinhood/823 (iPhone; iOS 7.1.2; Scale/2.00)"
}
self.session.headers = self.headers
def login(self, username, password, mfa_code=None):
self.username = username
self.password = password
self.mfa_code = mfa_code
if mfa_code:
fields = {
'password' : self.password,
'username' : self.username,
'mfa_code': self.mfa_code,
'grant_type': 'password',
'client_id': self.client_id
}
else:
fields = {
'password' : self.password,
'username' : self.username,
'grant_type': 'password',
'client_id': self.client_id
}
try:
data = urllib.urlencode(fields) #py2
except:
data = urllib.parse.urlencode(fields) #py3
res = self.session.post(self.endpoints['login'], data=data)
res = res.json()
try:
self.auth_token = res['access_token']
except KeyError:
return res
self.headers['Authorization'] = 'Bearer ' + self.auth_token
return True
##############################
#GET DATA
##############################
def get_endpoint(self, endpoint=None):
res = self.session.get(self.endpoints[endpoint])
return json.loads(res.content.decode('utf-8'))
def get_custom_endpoint(self, endpoint=None):
res = self.session.get(endpoint)
return json.loads(res.content.decode('utf-8'))
def investment_profile(self):
self.session.get(self.endpoints['investment_profile'])
def instruments(self, stock=None):
if stock == None:
res = self.session.get(self.endpoints['instruments'])
else:
res = self.session.get(self.endpoints['instruments'], params={'query':stock.upper()})
res = res.json()
return res['results']
def quote_data(self, stock=None):
#Prompt for stock if not entered
if stock is None:
stock = raw_input("Symbol: ");
url = str(self.endpoints['quotes']) + str(stock) + "/"
#Check for validity of symbol
try:
res = json.loads((urllib.urlopen(url)).read());
if len(res) > 0:
return res;
else:
raise NameError("Invalid Symbol: " + stock);
except (ValueError):
raise NameError("Invalid Symbol: " + stock);
def get_quote(self, stock=None):
data = self.quote_data(stock)
return data["symbol"]
def print_quote(self, stock=None):
data = self.quote_data(stock)
print(data["symbol"] + ": $" + data["last_trade_price"]);
def print_quotes(self, stocks):
for i in range(len(stocks)):
self.print_quote(stocks[i]);
def ask_price(self, stock=None):
return self.quote_data(stock)['ask_price'];
def ask_size(self, stock=None):
return self.quote_data(stock)['ask_size'];
def bid_price(self, stock=None):
return self.quote_data(stock)['bid_price'];
def bid_size(self, stock=None):
return self.quote_data(stock)['bid_size'];
def last_trade_price(self, stock=None):
return self.quote_data(stock)['last_trade_price'];
def last_trade_price(self, stock=None):
return self.quote_data(stock)['last_trade_price'];
def previous_close(self, stock=None):
return self.quote_data(stock)['previous_close'];
def previous_close_date(self, stock=None):
return self.quote_data(stock)['previous_close_date'];
def adjusted_previous_close(self, stock=None):
return self.quote_data(stock)['adjusted_previous_close'];
def symbol(self, stock=None):
return self.quote_data(stock)['symbol'];
def last_updated_at(self, stock=None):
return self.quote_data(stock)['updated_at'];
##############################
#PLACE ORDER
##############################
def place_order(self, instrument, quantity=1, bid_price = None, transaction=None):
# cache the account ID that's needed for placing orders
if self.positions == None:
self.positions = self.get_endpoint("positions")['results']
if bid_price == None:
bid_price = self.quote_data(instrument['symbol'])[0]['bid_price']
data = 'account=%s&instrument=%s&price=%f&quantity=%d&side=buy&symbol=%s&time_in_force=gfd&trigger=immediate&type=market' % (urllib.quote(self.positions[0]['account']), urllib.unquote(instrument['url']), float(bid_price), quantity, instrument['symbol'])
res = self.session.post(self.endpoints['orders'], data=data)
return res
def place_buy_order(self, instrument, quantity, bid_price=None):
transaction = "buy"
return self.place_order(instrument, quantity, bid_price, transaction)
def place_sell_order(self, instrument, quantity, bid_price=None):
transaction = "sell"
return self.place_order(instrument, quantity, bid_price, transaction)