-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlpaca_buy_sell.py
279 lines (234 loc) · 8.96 KB
/
Alpaca_buy_sell.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
278
279
import alpaca_trade_api as tradeapi
import config
class AlpacaBuySell:
def __init__(self, symbol=None, qty=10, order_type='market', time_in_force='gtc'):
self.base_url = config.BASE_URL
self.api_key_id = '' # put your api key of the account you want to trade on
self.api_secret = '' # put your secret key of the account you want
# to trade on
self.symbol = symbol # Ticker symbol of the stock
self.qty = qty # number of shares
self.order_type = order_type # Order type
self.time_in_force = time_in_force # Time in force
def api_call(self): # This function uses api call to get to the endpoint from which user can buy/sell stocks
api = tradeapi.REST(
base_url=self.base_url,
key_id=self.api_key_id,
secret_key=self.api_secret
)
return api
def naked_buy_order(self):
"""
place a naked buy order i.e. place a market buy order without any limit or stop sell order
"""
naked_buy_order = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='buy',
type=self.order_type,
time_in_force=self.time_in_force,
order_class='simple',
)
return naked_buy_order
def buy(self, limit, stop):
"""
Place market buy order with limit and stop (OCO) orders
i.e. place market order along with take profit and stop limit order
"""
api_buy = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='buy',
type=self.order_type,
time_in_force=self.time_in_force,
order_class='bracket',
take_profit=dict(limit_price=limit),
stop_loss=dict(stop_price=stop)
)
return api_buy
def buy_and_stop_order(self, stop):
"""
Place buy with stop loss order
"""
api_buy = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='buy',
type=self.order_type,
time_in_force=self.time_in_force,
order_class='oto',
stop_loss=dict(stop_price=stop)
)
return api_buy
def stop_limit_buy_order(self, limit_price, stop_price):
"""
place market buy order along with take profit and stop limit order
"""
api_buy = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='buy',
type=self.order_type,
time_in_force=self.time_in_force,
order_class='oto',
stop_loss=dict(stop_price=stop_price, limit_price=limit_price)
)
return api_buy
def stop_limit_sell_order(self, limit, stop):
"""
place market sell order take profit and stop limit order
"""
api_stop_limit_sell = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='sell',
type='limit',
time_in_force=self.time_in_force,
order_class='oco',
take_profit=dict(limit_price=limit),
stop_loss=dict(stop_price=stop)
)
return api_stop_limit_sell
def stop_limit_buy_order_without_making_a_market_buy(self, limit, stop):
"""
Place stop and limit (OCO) orders
without placing a buy order for this to work one must have a open naked buy order
"""
api = tradeapi.REST(
base_url=self.base_url,
key_id=self.api_key_id,
secret_key=self.api_secret
)
api_buy = api.submit_order(
symbol=self.symbol,
qty=self.qty,
side='buy',
type='limit',
time_in_force=self.time_in_force,
order_class='oco',
take_profit=dict(limit_price=limit),
stop_loss=dict(stop_price=stop)
)
return api_buy
def market_sell(self):
"""
Place market sell order - to close out the long position in particular stock
"""
api_sell = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='sell',
type='market',
time_in_force=self.time_in_force,
)
return api_sell
def short_sell(self):
"""
Place short sell order on the given stock
Caution: If the broken does not allow shorting on the given stock you will not be able to short that stock.
"""
api_sell = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='sell',
type='market',
time_in_force=self.time_in_force,
)
return api_sell
def limit_sell(self, limit):
"""
place market order along with take profit and stop limit order
"""
api_sell = AlpacaBuySell(self.symbol).api_call().submit_order(
symbol=self.symbol,
qty=self.qty,
side='sell',
type='limit',
time_in_force=self.time_in_force,
limit_price=limit
)
return api_sell
def current_positions(self):
"""
Get current open positions of the portfolio
"""
positions = AlpacaBuySell(self.symbol).api_call().list_positions()
for idx, p in enumerate(positions):
if positions[idx].symbol != self.symbol:
return False
else:
return True
def liqidate_positions(self):
"""
This function liquidates all the open positions in the given current portfolio
got from the reference from internet and modified the function a bit
"""
api = AlpacaBuySell(self.symbol).api_call()
orders = api.list_orders(status='open')
positions = api.list_positions()
if orders or positions:
if positions:
print(positions)
if orders:
print("Canceling open orders:")
print([o.id for o in orders])
result = [api.cancel_order(o.id) for o in orders]
print(result)
closed = []
for p in positions:
side = 'sell'
if int(p.qty) < 0:
p.qty = abs(int(p.qty))
side = 'buy'
closed.append(
api.submit_order(p.symbol, qty=p.qty, side=side, type="market", time_in_force="day")
)
if closed:
print("Submitted Orders", closed)
for o in closed:
status = api.get_order(o.id)
if status.status == 'rejected':
print("ORDER FAILED: Your Order was Rejected!!!")
def liqidate_position_of_a_stock(self):
"""
Unlike above given function this function has capability to liquidate anyone stock at a time rather than
liquidating all the positions in the portfolio
"""
pos = AlpacaBuySell(self.symbol).api_call().list_positions()
# print(pos[0].symbol)
for idx, p in enumerate(pos):
if pos[idx].symbol == self.symbol:
print("Element Exists")
print(pos[idx].symbol)
print(pos[idx].side)
print(pos[idx].qty)
if pos[idx].side == "long":
print("I am here")
AlpacaBuySell(pos[idx].symbol, qty=pos[idx].qty).market_sell()
elif pos[idx].side == "short":
AlpacaBuySell(pos[idx].symbol, qty=self.qty).naked_buy_order()
def cancel_orders_and_liquidate_the_given_stock(self):
"""
This function cancels open positions attached with the particular share and than liquidate the position
"""
api = AlpacaBuySell(self.symbol).api_call()
order_list_for_the_give_stock = list()
list_orders_ = api.list_orders()
for i in list_orders_:
if i.symbol == self.symbol:
order_list_for_the_give_stock.append(i.id)
# print(i.id[-1])
print(order_list_for_the_give_stock)
api.cancel_order(order_list_for_the_give_stock[-1])
# AlpacaBuySell(self.symbol).liqidate_position_of_a_stock()
pos = api.list_positions()
for idx, p in enumerate(pos):
if pos[idx].symbol == self.symbol:
print("Element Exists")
print(pos[idx].symbol)
print(pos[idx].side)
# print(pos[idx].qty)
if pos[idx].side == "long":
print("I am here")
AlpacaBuySell(pos[idx].symbol, qty=self.qty).market_sell()
# AlpacaBuySell("ROKU").naked_buy_order()