forked from anilshanbhag/RobinhoodShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.py
executable file
·277 lines (233 loc) · 8.79 KB
/
shell.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python
import cmd, json
from Robinhood import Robinhood
from beautifultable import BeautifulTable
from config import USERNAME, PASSWORD
class RobinhoodShell(cmd.Cmd):
intro = 'Welcome to the Robinhood shell. Type help or ? to list commands.\n'
prompt = '> '
# API Object
trader = None
# Cache file used to store instrument cache
instruments_cache_file = 'instruments.data'
# Maps Symbol to Instrument URL
instruments_cache = {}
# Maps URL to Symbol
instruments_reverse_cache = {}
# Cache file used to store instrument cache
watchlist_file = 'watchlist.data'
# List of stocks in watchlist
watchlist = []
def __init__(self):
cmd.Cmd.__init__(self)
self.trader = Robinhood()
self.trader.login(username=USERNAME, password=PASSWORD)
try:
data = open(self.instruments_cache_file).read()
self.instruments_cache = json.loads(data)
for k in self.instruments_cache:
self.instruments_reverse_cache[self.instruments_cache[k]] = k
except:
pass
try:
data = open(self.watchlist_file).read()
self.watchlist = json.loads(data)
except:
pass
# ----- basic commands -----
def do_l(self, arg):
'Lists current portfolio'
portfolio = self.trader.portfolios()
print 'Equity Value:', portfolio['equity']
account_details = self.trader.get_account()
if 'margin_balances' in account_details:
print 'Buying Power:', account_details['margin_balances']['unallocated_margin_cash']
positions = self.trader.securities_owned()
symbols = []
buy_price_data = {}
for position in positions['results']:
symbol = self.get_symbol(position['instrument'])
buy_price_data[symbol] = position['average_buy_price']
symbols.append(symbol)
quotes_data = {}
if len(symbols) > 0:
raw_data = self.trader.quotes_data(symbols)
for quote in raw_data:
quotes_data[quote['symbol']] = quote['last_trade_price']
table = BeautifulTable()
table.column_headers = ["symbol", "current price", "quantity", "total equity", "cost basis", "p/l"]
for position in positions['results']:
quantity = int(float(position['quantity']))
symbol = self.get_symbol(position['instrument'])
price = quotes_data[symbol]
total_equity = float(price) * quantity
buy_price = float(buy_price_data[symbol])
p_l = total_equity - buy_price * quantity
table.append_row([symbol, price, quantity, total_equity, buy_price, p_l])
print(table)
def do_w(self, arg):
'Show watchlist w \nAdd to watchlist w a <symbol> \nRemove from watchlist w r <symbol>'
parts = arg.split()
if len(parts) == 2:
if parts[0] == 'a':
self.watchlist.append(parts[1].strip())
if parts[0] == 'r':
self.watchlist = [r for r in self.watchlist if not r == parts[1].strip()]
print "Done"
else:
table = BeautifulTable()
table.column_headers = ["symbol", "current price"]
if len(self.watchlist) > 0:
raw_data = self.trader.quotes_data(self.watchlist)
quotes_data = {}
for quote in raw_data:
table.append_row([quote['symbol'], quote['last_trade_price']])
print(table)
else:
print "Watchlist empty!"
def do_b(self, arg):
'Buy stock b <symbol> <quantity> <price>'
parts = arg.split()
if len(parts) >= 2 and len(parts) <= 3:
symbol = parts[0]
quantity = parts[1]
if len(parts) == 3:
price = float(parts[2])
else:
price = 0.0
stock_instrument = self.trader.instruments(symbol)[0]
res = self.trader.place_buy_order(stock_instrument, quantity, price)
if not (res.status_code == 200 or res.status_code == 201):
print "Error executing order"
try:
data = res.json()
if 'detail' in data:
print data['detail']
except:
pass
else:
print "Done"
else:
print "Bad Order"
def do_s(self, arg):
'Sell stock s <symbol> <quantity> <?price>'
parts = arg.split()
if len(parts) >= 2 and len(parts) <= 3:
symbol = parts[0]
quantity = parts[1]
if len(parts) == 3:
price = float(parts[2])
else:
price = 0.0
stock_instrument = self.trader.instruments(symbol)[0]
res = self.trader.place_sell_order(stock_instrument, quantity, price)
if not (res.status_code == 200 or res.status_code == 201):
print "Error executing order"
try:
data = res.json()
if 'detail' in data:
print data['detail']
except:
pass
else:
print "Done"
else:
print "Bad Order"
def do_sl(self, arg):
'Setup stop loss on stock sl <symbol> <quantity> <price>'
parts = arg.split()
if len(parts) == 3:
symbol = parts[0]
quantity = parts[1]
price = float(parts[2])
stock_instrument = self.trader.instruments(symbol)[0]
res = self.trader.place_stop_loss_order(stock_instrument, quantity, price)
if not (res.status_code == 200 or res.status_code == 201):
print "Error executing order"
try:
data = res.json()
if 'detail' in data:
print data['detail']
except:
pass
else:
print "Done"
else:
print "Bad Order"
def do_o(self, arg):
'List open orders'
open_orders = self.trader.get_open_orders()
if open_orders:
table = BeautifulTable()
table.column_headers = ["index", "symbol", "price", "quantity", "type", "id"]
index = 1
for order in open_orders:
table.append_row([
index,
self.get_symbol(order['instrument']),
order['price'],
int(float(order['quantity'])),
order['side'],
order['id'],
])
index += 1
print(table)
else:
print "No Open Orders"
def do_c(self, arg):
'Cancel open order c <index> or c <id>'
order_id = arg.strip()
order_index = -1
try:
order_index = int(order_id)
except:
pass
if order_index > 0:
order_index = order_index - 1
open_orders = self.trader.get_open_orders()
if order_index < len(open_orders):
order_id = open_orders[order_index]['id']
else:
print "Bad index"
return
try:
self.trader.cancel_order(order_id)
print "Done"
except Exception as e:
print "Error executing cancel"
print e
def do_ca(self, arg):
'Cancel all open orders'
open_orders = self.trader.get_open_orders()
for order in open_orders:
try:
self.trader.cancel_order(order['id'])
except Exception as e:
pass
print "Done"
def do_q(self, arg):
'Get quote for stock q <symbol>'
symbol = arg.strip()
try:
self.trader.print_quote(symbol)
except:
print "Error getting quote for:", symbol
def do_bye(self, arg):
open(self.instruments_cache_file, 'w').write(json.dumps(self.instruments_cache))
open(self.watchlist_file, 'w').write(json.dumps(self.watchlist))
return True
# ------ utils --------
def get_symbol(self, url):
if not url in self.instruments_reverse_cache:
self.add_instrument_from_url(url)
return self.instruments_reverse_cache[url]
def add_instrument_from_url(self, url):
data = self.trader.get_url(url)
symbol = data['symbol']
self.instruments_cache[symbol] = url
self.instruments_reverse_cache[url] = symbol
def parse(arg):
'Convert a series of zero or more numbers to an argument tuple'
return tuple(map(int, arg.split()))
if __name__ == '__main__':
RobinhoodShell().cmdloop()