Skip to content

Commit 14d6c9c

Browse files
authored
Send subscription requests in parts (#586)
* Send sub messages in smaller chunks * Fix inline comment * Address comments * Format line * Fix formatting * Set frame size
1 parent 1aba0f0 commit 14d6c9c

File tree

2 files changed

+13
-12
lines changed

2 files changed

+13
-12
lines changed

alpaca_trade_api/stream.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
from collections import defaultdict
23
import logging
34
import json
45
from typing import List, Optional
@@ -58,6 +59,7 @@ def __init__(self,
5859
}
5960
self._name = 'data'
6061
self._should_run = True
62+
self._max_frame_size = 32768
6163

6264
async def _connect(self):
6365
self._ws = await websockets.connect(
@@ -186,17 +188,16 @@ def _subscribe(self, handler, symbols, handlers):
186188
).result()
187189

188190
async def _subscribe_all(self):
189-
if any(
190-
v for k, v in self._handlers.items()
191-
if k not in ("cancelErrors", "corrections")
192-
):
193-
msg = {
194-
k: tuple(v.keys())
195-
for k, v in self._handlers.items()
196-
if v
197-
}
198-
msg['action'] = 'subscribe'
199-
await self._ws.send(msgpack.packb(msg))
191+
msg = defaultdict(list)
192+
for k, v in self._handlers.items():
193+
if k not in ("cancelErrors", "corrections") and v:
194+
for s in v.keys():
195+
msg[k].append(s)
196+
msg['action'] = 'subscribe'
197+
bs = msgpack.packb(msg)
198+
frames = (bs[i:i+self._max_frame_size]
199+
for i in range(0, len(bs), self._max_frame_size))
200+
await self._ws.send(frames)
200201

201202
async def _unsubscribe(self,
202203
trades=(),

requirements/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ numpy>=1.11.1 # pyup: ignore - allow all versions above this
33
requests>2,<3
44
urllib3>1.24,<2
55
websocket-client>=0.56.0,<2
6-
websockets>=8.0,<11
6+
websockets>=9.0,<11
77
msgpack==1.0.2
88
aiohttp==3.7.4
99
PyYAML==6.0

0 commit comments

Comments
 (0)