-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.py
More file actions
48 lines (41 loc) · 1.48 KB
/
executor.py
File metadata and controls
48 lines (41 loc) · 1.48 KB
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
# Execution Module: executor.py
# This module will use the Alpaca API to execute trades based on the signals generated by the trading strategy.
from alpaca_trade_api.rest import REST, TimeFrame
from config import API_KEY, SECRET_KEY, BASE_URL
import datetime
# Initialize Alpaca API
api = REST(API_KEY, SECRET_KEY, base_url=BASE_URL, api_version='v2')
def execute_trade(symbol, quantity, trade_action):
"""
Executes a trade (buy or sell) for the given symbol and quantity based on the trade action.
:param symbol: The stock symbol to trade.
:param quantity: The number of shares to buy/sell.
:param trade_action: The trade action, either 'buy' or 'sell'.
"""
if trade_action == 'buy':
api.submit_order(
symbol=symbol,
qty=quantity,
side='buy',
type='market',
time_in_force='gtc' # Good till cancel
)
elif trade_action == 'sell':
api.submit_order(
symbol=symbol,
qty=quantity,
side='sell',
type='market',
time_in_force='gtc'
)
def check_open_positions(symbol):
"""
Checks for open positions for the given symbol.
:param symbol: The stock symbol to check open positions for.
:return: The quantity of shares for open positions; 0 if no open positions.
"""
positions = api.list_positions()
for position in positions:
if position.symbol == symbol:
return int(position.qty)
return 0