Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 65cebf9

Browse files
Initial commit
0 parents commit 65cebf9

File tree

6 files changed

+434
-0
lines changed

6 files changed

+434
-0
lines changed

‎.gitignore

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
pip-wheel-metadata/
24+
share/python-wheels/
25+
*.egg-info/
26+
.installed.cfg
27+
*.egg
28+
MANIFEST
29+
30+
# PyInstaller
31+
# Usually these files are written by a python script from a template
32+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
33+
*.manifest
34+
*.spec
35+
36+
# Installer logs
37+
pip-log.txt
38+
pip-delete-this-directory.txt
39+
40+
# Unit test / coverage reports
41+
htmlcov/
42+
.tox/
43+
.nox/
44+
.coverage
45+
.coverage.*
46+
.cache
47+
nosetests.xml
48+
coverage.xml
49+
*.cover
50+
*.py,cover
51+
.hypothesis/
52+
.pytest_cache/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
target/
76+
77+
# Jupyter Notebook
78+
.ipynb_checkpoints
79+
80+
# IPython
81+
profile_default/
82+
ipython_config.py
83+
84+
# pyenv
85+
.python-version
86+
87+
# pipenv
88+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
90+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
91+
# install all needed dependencies.
92+
#Pipfile.lock
93+
94+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
95+
__pypackages__/
96+
97+
# Celery stuff
98+
celerybeat-schedule
99+
celerybeat.pid
100+
101+
# SageMath parsed files
102+
*.sage.py
103+
104+
# Environments
105+
.env
106+
.venv
107+
env/
108+
venv/
109+
ENV/
110+
env.bak/
111+
venv.bak/
112+
113+
# Spyder project settings
114+
.spyderproject
115+
.spyproject
116+
117+
# Rope project settings
118+
.ropeproject
119+
120+
# mkdocs documentation
121+
/site
122+
123+
# mypy
124+
.mypy_cache/
125+
.dmypy.json
126+
dmypy.json
127+
128+
# Pyre type checker
129+
.pyre/

‎Alpaca_examples.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import alpaca_trade_api as tradeapi
2+
import threading
3+
4+
api_key = 'Insert_your_api_key_here'
5+
api_secret = 'Insert_your_api_secret_here'
6+
base_url = 'https://paper-api.alpaca.markets'
7+
8+
#instantiate REST API
9+
api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')
10+
11+
#obtain account information
12+
account = api.get_account()
13+
print(account)
14+
15+
16+
#init websocket - How do I use WebSockets to stream data with the Alpaca API?
17+
conn = tradeapi.stream2.StreamConn(api_key, api_secret, base_url)
18+
19+
@conn.on(r'^account_updates$')
20+
async def on_account_updates(conn, channel, account):
21+
print('account', account)
22+
23+
@conn.on(r'^trade_updates$')
24+
async def on_trade_updates(conn, channel, trade):
25+
print('trade', trade)
26+
27+
def ws_start():
28+
conn.run(['account_updates', 'trade_updates'])
29+
30+
#start WebSocket in a thread
31+
ws_thread = threading.Thread(target=ws_start, daemon=True)
32+
ws_thread.start()
33+
34+
'''Data Examples - How do I get historical data from the Alpaca API?
35+
36+
aapl = api.polygon.historic_agg_v2('AAPL', 1, 'day', _from='2019年01月01日', to='2019年02月01日').df
37+
aapl = api.alpha_vantage.historic_quotes('AAPL', adjusted=True, output_format='pandas')
38+
tsla = api.alpha_vantage.historic_quotes('TSLA', adjusted=True, output_format='json', cadence='weekly')
39+
tsla = api.alpha_vantage.intraday_quotes ('TSLA', interval='5min', output_format='csv')
40+
'''
41+
42+
43+
''' How can I use indicators with the Alpaca API?
44+
45+
#sma = api.alpha_vantage.techindicators(symbol='AAPL', interval='weekly', time_period='10', series_type='close')
46+
47+
#rsi = api.alpha_vantage.techindicators(techindicator='RSI', symbol='AAPL', interval='weekly', time_period='14', series_type='close')
48+
49+
print(sma)
50+
print(rsi)
51+
'''
52+
53+
''' How can I fire order in the Alpaca API?
54+
55+
api.submit_order(symbol='TSLA',
56+
qty=1,
57+
side='buy',
58+
time_in_force='gtc',
59+
type='limit',
60+
limit_price=400.00,
61+
client_order_id='001'
62+
)
63+
'''
64+
65+
''' How do I set a stop loss or take profit?
66+
api.submit_order(symbol='TSLA',
67+
qty=1,
68+
side='buy',
69+
time_in_force='gtc',
70+
type='limit',
71+
limit_price=400.00,
72+
client_order_id=001,
73+
order_class='bracket',
74+
stop_loss=dict(stop_price='360.00'),
75+
take_profit=dict(limit_price='440.00')
76+
)
77+
'''
78+
79+
''' Which stocks can you trade with Alpaca?
80+
active_assets = api.list_assets(status='active')
81+
for a in active_assets:
82+
print(a)
83+
print()
84+
print(type(a))
85+
86+
87+
aapl_asset = api.get_asset('AAPL')
88+
print(aapl_asset)
89+
'''
90+
91+
#How do I find out what time the market closes?
92+
93+
print(api.get_clock())
94+
95+
96+
''' Get additional documentation for the REST API
97+
help(tradeapi.REST)
98+
'''

‎Alpaca_trading_example.py

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import alpaca_trade_api as tradeapi
2+
import threading
3+
from time import *
4+
import json
5+
import logging
6+
7+
#init
8+
logging.basicConfig(filename='errlog.log',level=logging.WARNING, format='%(asctime)s:%(levelname)s:%(message)s')
9+
10+
api_key = 'insert_api_key'
11+
api_secret = 'insert_api_secret'
12+
base_url = 'https://paper-api.alpaca.markets'
13+
14+
api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')
15+
16+
trade_msg = []
17+
order_msg = []
18+
past_trades = []
19+
20+
searching_for_trade = False
21+
order_sent = False
22+
order_submitted = False
23+
active_trade = False
24+
done_for_the_day = False
25+
26+
#check if market is open
27+
api.cancel_all_orders()
28+
clock = api.get_clock()
29+
30+
if clock.is_open:
31+
pass
32+
else:
33+
time_to_open = clock.next_open - clock.timestamp
34+
sleep(time_to_open.total_seconds())
35+
36+
if len(api.list_positions()) == 0:
37+
searching_for_trade = True
38+
else:
39+
active_trade = True
40+
41+
#init WebSocket
42+
conn = tradeapi.stream2.StreamConn(api_key, api_secret, base_url)
43+
44+
@conn.on(r'^account_updates$')
45+
async def on_account_updates(conn, channel, account):
46+
order_msg.append(account)
47+
48+
@conn.on(r'^trade_updates$')
49+
async def on_trade_updates(conn, channel, trade):
50+
trade_msg.append(trade)
51+
if 'fill' in trade.event:
52+
past_trades.append([trade.order['updated_at'], trade.order['symbol'], trade.order['side'],
53+
trade.order['filled_qty'], trade.order['filled_avg_price']])
54+
with open('past_trades.csv', 'w') as f:
55+
json.dump(past_trades, f, indent=4)
56+
print(past_trades[-1])
57+
58+
def ws_start():
59+
conn.run(['account_updates', 'trade_updates'])
60+
61+
#start WebSocket in a thread
62+
ws_thread = threading.Thread(target=ws_start, daemon=True)
63+
ws_thread.start()
64+
sleep(10)
65+
66+
67+
#functions
68+
def time_to_market_close():
69+
clock = api.get_clock()
70+
closing = clock.next_close - clock.timestamp
71+
return round(closing.seconds/60)
72+
73+
def send_order(direction):
74+
if time_to_market_close() > 20:
75+
if direction == 'buy':
76+
sl = high-range_size
77+
tp = high+range_size
78+
elif direction == 'sell':
79+
sl = low+range_size
80+
tp = low-range_size
81+
82+
api.submit_order(symbol='AAPL', qty=100, side=direction, type='market', time_in_force='day', order_class='bracket', stop_loss=dict(stop_price=str(sl)), take_profit=dict(limit_price=str(tp)))
83+
return True, False
84+
85+
else:
86+
return False, True
87+
88+
89+
#main loop
90+
while True:
91+
92+
try:
93+
94+
candlesticks = api.get_barset('AAPL', 'minute', limit=10)
95+
high = candlesticks['AAPL'][0].h
96+
low = candlesticks['AAPL'][0].l
97+
range_size = high - low
98+
if range_size / candlesticks['AAPL'][0].c < 0.003:
99+
range_size = candlesticks['AAPL'][0].c * 0.003
100+
for candle in candlesticks['AAPL']:
101+
if candle.h > high:
102+
high = candle.h
103+
elif candle.l < low:
104+
low = candle.l
105+
range_size = high - low
106+
107+
while searching_for_trade:
108+
clock = api.get_clock()
109+
sleep(60-clock.timestamp.second)
110+
candlesticks = api.get_barset('AAPL', 'minute', limit=1)
111+
if candlesticks['AAPL'][0].c > high:
112+
searching_for_trade = False
113+
order_sent, done_for_the_day = send_order('buy')
114+
115+
elif candlesticks['AAPL'][0].c < low:
116+
searching_for_trade = False
117+
order_sent, done_for_the_day = send_order('sell')
118+
119+
while order_sent:
120+
sleep(1)
121+
for item in trade_msg:
122+
if item.event == 'new':
123+
order_submitted = True
124+
order_sent = False
125+
126+
while order_submitted:
127+
sleep(1)
128+
for item in trade_msg:
129+
if item.order['filled_qty'] == '100':
130+
order_submitted = False
131+
active_trade = True
132+
trade_msg = []
133+
134+
135+
while active_trade:
136+
for i in range(time_to_market_close()-5):
137+
sleep(60)
138+
if len(api.list_positions()) == 0:
139+
active_trade = False
140+
searching_for_trade = True
141+
break
142+
if active_trade:
143+
done_for_the_day = True
144+
active_trade = False
145+
146+
while done_for_the_day:
147+
api.close_all_positions()
148+
clock = api.get_clock()
149+
next_market_open = clock.next_open - clock.timestamp
150+
sleep(next_market_open.total_seconds())
151+
searching_for_trade = True
152+
153+
except Exception as e:
154+
logging.exception(e)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /