Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions algo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import numpy as np
from datetime import datetime, timedelta
from pytz import timezone
import os

# Replace these with your API connection info from the dashboard
base_url = 'Your API URL'
api_key_id = 'Your API Key'
api_secret = 'Your API Secret'
base_url = os.environ.get('APCA_API_BASE_URL', 'https://paper-api.alpaca.markets')
api_key_id = os.environ.get('APCA_API_KEY_ID')
api_secret = os.environ.get('APCA_API_SECRET_KEY')

api = tradeapi.REST(
base_url=base_url,
Expand Down Expand Up @@ -48,7 +49,9 @@ def get_tickers():
print('Getting current ticker data...')
tickers = api.polygon.all_tickers()
print('Success.')
print('Getting list of assets...')
assets = api.list_assets()
print('Success.')
symbols = [asset.symbol for asset in assets if asset.tradable]
return [ticker for ticker in tickers if (
ticker.ticker in symbols and
Expand Down Expand Up @@ -146,7 +149,7 @@ async def handle_trade_update(conn, channel, data):
partial_fills[symbol] = 0
open_orders[symbol] = None

@conn.on(r'A\..*')
@conn.on(r'A')
async def handle_second_bar(conn, channel, data):
symbol = data.symbol

Expand Down Expand Up @@ -190,8 +193,8 @@ async def handle_second_bar(conn, channel, data):
return

# Now we check to see if it might be time to buy or sell
since_market_open = ts - market_open_dt
until_market_close = market_close_dt - ts
since_market_open = ts.astimezone(nyc) - market_open_dt
until_market_close = market_close_dt - ts.astimezone(nyc)
if (
since_market_open.seconds // 60 > 15 and
since_market_open.seconds // 60 < 60
Expand Down Expand Up @@ -336,7 +339,7 @@ async def handle_second_bar(conn, channel, data):
])

# Replace aggregated 1s bars with incoming 1m bars
@conn.on(r'AM\..*')
@conn.on(r'AM')
async def handle_minute_bar(conn, channel, data):
ts = data.start
ts -= timedelta(microseconds=ts.microsecond)
Expand Down Expand Up @@ -391,6 +394,7 @@ def run_ws(conn, channels):
since_market_open = current_dt - market_open
while since_market_open.seconds // 60 <= 14:
time.sleep(1)
current_dt = datetime.today().astimezone(nyc)
since_market_open = current_dt - market_open

run(get_tickers(), market_open, market_close)