Skip to content

Instantly share code, notes, and snippets.

@ttt733
Created August 6, 2019 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttt733/26c92cd48de849eff73851632f8ddd7d to your computer and use it in GitHub Desktop.
Save ttt733/26c92cd48de849eff73851632f8ddd7d to your computer and use it in GitHub Desktop.
Listening for Alpaca order updates
conn = tradeapi.StreamConn(
self.key_id,
self.secret_key,
self.base_url
)
# Listen for updates to our orders
@conn.on(r'trade_updates')
async def handle_trade(conn, channel, data):
symbol = data.order['symbol']
if symbol != self.symbol:
# The order was for a position unrelated to this script
return
event_type = data.event
qty = int(data.order['filled_qty'])
side = data.order['side']
oid = data.order['id']
if event_type == 'fill' or event_type == 'partial_fill':
# Our position size has changed
self.position = int(data.position_qty)
print(f'New position size due to order fill: {self.position}')
if (event_type == 'fill' and self.current_order
and self.current_order.id == oid):
self.current_order = None
elif event_type == 'rejected' or event_type == 'canceled':
if self.current_order and self.current_order.id == oid:
# Our last order should be removed
self.current_order = None
elif event_type != 'new':
print(f'Unexpected order event type {event_type} received')
conn.run(['trade_updates'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment