-
-
Save ttt733/26c92cd48de849eff73851632f8ddd7d to your computer and use it in GitHub Desktop.
Listening for Alpaca order updates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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