-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtradebot.py
68 lines (50 loc) · 1.83 KB
/
tradebot.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
# -*- coding: utf-8 -*-
"""TradeBot
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1n7Ub6b1_xTelr33phRI1cpjT6u1ckU5h
"""
!pip install pipenv
!pip install alpaca-trade-api
import alpaca_trade_api as tradeapi
sec_key = '7sAJ142sPJQnVJizA29fbSAxjUM10i6raWRcoLai'
api_id = 'PKHYOP5V6NH3YRCZF10O'
baseurl = 'https://paper-api.alpaca.markets'
import numpy as np
import time
api = tradeapi.REST(key_id = api_id, secret_key = sec_key, base_url = baseurl)
symb = "SPY"
pos_held = False
while True:
print("")
print("Checking Price")
market_data = api.get_barset(symb, 'minute', limit=5) # Get one bar object for each of the past 5 minutes
close_list = [] # This array will store all the closing prices from the last 5 minutes
for bar in market_data[symb]:
close_list.append(bar.c) # bar.c is the closing price of that bar's time interval
close_list = np.array(close_list, dtype=np.float64) # Convert to numpy array
ma = np.mean(close_list)
last_price = close_list[4] # Most recent closing price
print("Moving Average: " + str(ma))
print("Last Price: " + str(last_price))
if ma + 0.1 < last_price and not pos_held: # If MA is more than 10cents under price, and we haven't already bought
print("Buy")
api.submit_order(
symbol=symb,
qty=1,
side='buy',
type='market',
time_in_force='gtc'
)
pos_held = True
elif ma - 0.1 > last_price and pos_held: # If MA is more than 10cents above price, and we already bought
print("Sell")
api.submit_order(
symbol=symb,
qty=1,
side='sell',
type='market',
time_in_force='gtc'
)
pos_held = False
time.sleep(60)