-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrobin_stocks_functions.py
227 lines (162 loc) · 13 KB
/
robin_stocks_functions.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
#requires robin_stocks
import robin_stocks
import robin_stocks.robinhood as r
import matplotlib.pyplot as plt
from time import sleep
def login(email, password):
'''login to robinhood account'''
r.login(email, password)
def logout():
r.logout()
def get_quote(ticker):
'''get quote (misc info) for a given company'''
print(robin_stocks.robinhood.stocks.get_quotes(ticker))
def plot_hourly_historical(ticker):
'''plot historical hourly price for the last day'''
data = robin_stocks.robinhood.stocks.get_stock_historicals(ticker, interval='hour', span='day')
prices = []
times = []
for datum in data:
prices.append(float(datum['close_price']))
times.append(datum['begins_at']) # needs better formatting
plt.plot(range(len(prices)), prices)
# may need to save the figure instead?
plt.show()
def get_spot_price(ticker):
'''get current price of a stock'''
return r.get_latest_price(ticker)
def get_buying_power():
'''returns buying power as proxy for account balance'''
return r.load_phoenix_account(info='account_buying_power')
"""
Order (Buy/Sell) Functions
Several functions below are redundant. I've put them in place in advance to be later culled depending on which of two styles of function call we decide to use.
"""
#Cancels all stock orders
def cancel_all_stock_orders():
return r.orders.cancel_all_stock_orders()
#Returns the list of orders that were cancelled.
#Cancels a specific order.
def cancel_stock_order(orderID):
return r.orders.cancel_stock_order(orderID)
#Returns the order information for the order that was cancelled.
#Returns a list of all the orders that are currently open.
def get_all_open_stock_orders():
return r.orders.get_all_open_stock_orders(info = None)
#Returns a list of dictionaries of key/value pairs for each order. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info.
#Returns a list of all the orders that have been processed for the account.
def get_all_stock_orders():
return r.orders.get_all_stock_orders(info = None)
#Returns a list of dictionaries of key/value pairs for each order. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info.
#Returns the information for a single order.
def get_stock_order_info(orderID):
return r.orders.get_stock_order_info(orderID)
#Returns a list of dictionaries of key/value pairs for the order.
#A generic order function.
def order(symbol, quantity, side):
return r.orders.order(symbol, quantity, side, limitPrice = None, stopPrice = None, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#symbol (str) – The stock ticker of the stock to sell.
#quantity (int) – The number of stocks to sell.
#side (str) – Either ‘buy’ or ‘sell’
#limitPrice (float) – The price to trigger the market order.
#stopPrice (float) – The price to trigger the limit or market order.
#timeInForce (str) – Changes how long the order will be in effect for. ‘gtc’ = good until cancelled. ‘gfd’ = good for the day.
#extendedHours (Optional[str]) – Premium users only. Allows trading during extended hours. Should be true or false.
#jsonify (Optional[str]) – If set to False, function will return the request object which contains status code and headers.
#Returns: Dictionary that contains information regarding the purchase or selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a market order to be executed immediately for fractional shares by specifying the amount in dollars that you want to trade. Good for share fractions up to 6 decimal places. Robinhood does not currently support placing limit, stop, or stop loss orders for fractional trades.
def order_buy_fractional_by_price(symbol, amountInDollars):
return r.orders.order_buy_fractional_by_price(symbol, amountInDollars, timeInForce = 'gfd', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a market order to be executed immediately for fractional shares by specifying the amount that you want to trade. Good for share fractions up to 6 decimal places. Robinhood does not currently support placing limit, stop, or stop loss orders for fractional trades.
def order_buy_fractional_by_quantity(symbol, quantity):
return r.orders.order_buy_fractional_by_quantity(symbol, quantity, timeInForce = 'gfd', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a limit order to be executed once a certain price is reached.
def order_buy_limit(symbol, quantity, limitPrice):
return r.orders.order_buy_limit(symbol, quantity, limitPrice, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a market order to be executed immediately.
def order_buy_market(symbol, quantity):
return r.orders.order_buy_market(symbol, quantity, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a stop order to be turned into a limit order once a certain stop price is reached.
def order_buy_stop_limit(symbol, quantity, limitPrice, stopPrice):
return r.orders.order_buy_stop_limit(symbol, quantity, limitPrice, stopPrice, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a stop order to be turned into a market order once a certain stop price is reached.
def order_buy_stop_loss(symbol, quantity, stopPrice):
return r.orders.order_buy_stop_loss(symbol, quantity, stopPrice, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a trailing stop buy order to be turned into a market order when traling stop price reached.
def order_buy_trailing_stop(symbol, quantity, trailAmount):
return r.orders.order_buy_trailing_stop(symbol, quantity, trailAmount, trailType = 'percentage', timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a market order to be executed immediately for fractional shares by specifying the amount in dollars that you want to trade. Good for share fractions up to 6 decimal places. Robinhood does not currently support placing limit, stop, or stop loss orders for fractional trades.
def order_sell_fractional_by_price(symbol, amountInDollars):
return r.orders.order_sell_fractional_by_price(symbol, amountInDollars, timeInForce = 'gfd', extendedHours = False, jsonify = True)
#Returns Dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a market order to be executed immediately for fractional shares by specifying the amount that you want to trade. Good for share fractions up to 6 decimal places. Robinhood does not currently support placing limit, stop, or stop loss orders for fractional trades.
def order_sell_fractional_by_quantity(symbol, quantity):
return r.orders.order_sell_fractional_by_quantity(symbol, quantity, timeInForce = 'gfd', priceType = 'bid_price', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a limit order to be executed once a certain price is reached.
def order_sell_limit(symbol, quantity, limitPrice):
return r.orders.order_sell_limit(symbol, quantity, limitPrice, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a market order to be executed immediately.
def order_sell_market(symbol, quantity):
return r.orders.order_sell_market(symbol, quantity, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns Dictionary that contains information regarding the selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a stop order to be turned into a limit order once a certain stop price is reached.
def order_sell_stop_limit(symbol, quantity, limitPrice, stopPrice):
return r.orders.order_sell_stop_limit(symbol, quantity, limitPrice, stopPrice, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a stop order to be turned into a market order once a certain stop price is reached.
def order_sell_stop_loss(symbol, quantity, stopPrice):
return r.orders.order_sell_stop_loss(symbol, quantity, stopPrice, timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a trailing stop sell order to be turned into a market order when traling stop price reached.
def order_sell_trailing_stop(symbol, quantity, trailAmount):
return r.orders.order_sell_trailing_stop(symbol, quantity, trailAmount, trailType = 'percentage', timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns dictionary that contains information regarding the selling of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Returns dictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
#Submits a trailing stop order to be turned into a market order when traling stop price reached.
def order_trailing_stop(symbol, quantity, side, trailAmount):
return r.orders.order_trailing_stop(symbol, quantity, side, trailAmount, trailType = 'percentage', timeInForce = 'gtc', extendedHours = False, jsonify = True)
#Returns ictionary that contains information regarding the purchase of stocks, such as the order id, the state of order (queued, confired, filled, failed, canceled, etc.), the price, and the quantity.
"""
Exporting Functions
"""
#Creates a filepath given a directory and file name.
def create_absolute_csv(dir_path, file_name, order_type):
return r.export.create_absolute_csv(dir_path, file_name, order_type)
#Returns an absolute file path as a string.
#Write all completed orders to a csv file
def export_completed_stock_orders(dir_path):
#file_name (Optional[str]) – An optional argument for the name of the file. If not defined, filename will be stock_orders_{current date}
r.export.export_completed_stock_orders(dir_path, file_name = None)
"""
Plot for top panel
"""
def top_panel(ticker):
# get historical data, default is hourly for the past week
data = robin_stocks.robinhood.stocks.get_stock_historicals(ticker, interval='hour', span='month')
prices = []
times = []
for datum in data:
prices.append(float(datum['close_price']))
times.append(datum['begins_at']) # needs better formatting
# plot it
#plt.plot(times, prices)
#plt.xlabel('Past Month')
#plt.ylabel('Price $')
#plt.tick_params(
# axis='x', # changes apply to the x-axis
# which='both', # both major and minor ticks are affected
# bottom=False, # ticks along the bottom edge are off
# top=False, # ticks along the top edge are off
# labelbottom=False) # labels along the bottom edge are off
#plt.show()
return range(len(times)), prices