-
Notifications
You must be signed in to change notification settings - Fork 539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1006 error still happening #265
Comments
Hi, |
Hi, loop = self.loop
should_renew = True # should renew connection if it disconnects
while should_renew:
try:
if loop.is_closed():
self.loop = asyncio.new_event_loop()
loop = self.loop
loop.run_until_complete(self.subscribe(initial_channels))
loop.run_until_complete(self.consume())
except KeyboardInterrupt:
logging.info("Exiting on Interrupt")
should_renew = False
except Exception as e:
logging.error(f"error while consuming ws messages: {e}")
loop.run_until_complete(self.close(should_renew))
if loop.is_running():
loop.close() |
I'm having a very similar issue using the same latest push |
I will need some more information in order to try and reproduce the issue.
|
And then the log messages I receive are as follows:
Thanks for the help! |
Last error: Sample code: *** In main call setup, then call ws_start, then loop forever doing a sleep(10)
|
hi @rizzomichaelg tried to work with your code example..
|
Is there a place I can upload the code to? Easier than cut/paste. Jim
On 7/15/2020 11:02:00 AM, Shlomi Kushchi <[email protected]> wrote:
hi @rizzomichaelg [https://github.com/rizzomichaelg] tried to work with your code example..
* it's a part of your example so it doesn't work.
* I fixed the errors to make it execute, but even after that.. it does nothing
so there's nothing I could debug with this.
if you could provide a better example code I will run it
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub [#265 (comment)], or unsubscribe [https://github.com/notifications/unsubscribe-auth/APH72TYHCABT5Y4XMCYKHNLR3XHHNANCNFSM4OVWMO6A].
|
@dandwfdm I was referring to rizzomichaelg's code and you will get a result like this: async def on_minute(self, conn, channel, bar):
print(bar) # dummy to show routine that is called |
The following is a version of my code that should run. I ran it earlier and it failed after 6 minutes. Here is the output: C:\Projects\test\venv\Scripts\python.exe C:/Projects/test/main.py Process finished with exit code 1 **** the code *** *** main.py: import time def main():
if name == "main": **** trading.py import json class Trading:
|
@dandwfdm Apologies, here is my complete example. from datetime import datetime
from pytz import timezone
from websockets.exceptions import ConnectionClosedError
from time import sleep
import asyncio
import alpaca_trade_api
eastern = timezone('US/Eastern')
ALPACA_API_KEY = ''
ALPACA_SECRET_KEY = ''
ALPACA_API_ENDPOINT = 'https://paper-api.alpaca.markets'
class DisconnectedException(Exception):
pass
class Quit(Exception):
pass
class Trader(object):
def __init__(self, symbols):
self.key_id = ALPACA_API_KEY
self.secret_key = ALPACA_SECRET_KEY
self.api_endpoint = ALPACA_API_ENDPOINT
self.api = alpaca_trade_api.REST(
self.key_id,
self.secret_key,
base_url=self.api_endpoint
)
self.disconnected = False
self.symbols = symbols
def start_trading(self):
conn = alpaca_trade_api.StreamConn(
self.key_id,
self.secret_key,
base_url=self.api_endpoint,
data_stream="polygon"
)
now = datetime.now()
today = now.strftime('%Y-%m-%d')
break_time = datetime.strptime(f'{today} 16:00:00', '%Y-%m-%d %H:%M:%S')
break_time = eastern.localize(break_time)
@conn.on(r'^status$')
async def on_status(conn, channel, data):
print('polygon status update', data)
if data.status == 'disconnected':
print('Disconnected. Going to try to reconnect...')
self.disconnected = True
await conn.close()
print('awaited conn close')
raise DisconnectedException('Disconnected')
@conn.on(r'^AM$', self.symbols)
async def handle_agg(conn, channel, data):
print(data)
async def periodic():
while True:
# if not self.api.get_clock().is_open:
if not self.api.get_clock().is_open or self.api.get_clock().timestamp >= break_time:
print('done for today')
raise Quit('Quit')
if self.disconnected:
print('raise from periodic')
raise DisconnectedException('Disconnected')
await asyncio.sleep(30)
should_continue = True
def exception_handler(loop, context):
global should_continue
loop.default_exception_handler(context)
loop.stop()
print('exception handler')
print(context)
if 'exception' in context and context['exception'] == DisconnectedException:
should_continue = True
print('Now streaming...')
channels = ['trade_updates'] + ['AM.{}'.format(s) for s in self.symbols]
while should_continue:
should_continue = False
try:
loop = conn.loop
loop.set_exception_handler(exception_handler)
self.disconnected = False
loop.run_until_complete(asyncio.gather(
conn.subscribe(channels),
periodic(),
))
loop.close()
except Quit:
print('Quit Exception')
except DisconnectedException:
print('Disconnected')
try:
pass
except Exception as e:
print('second try just in case', e)
should_continue = True
except ConnectionClosedError as e:
print('ConnectionClosedError', e)
should_continue = True
sleep(5)
except Exception as e:
print('Caught exception', e)
def main():
symbols = ['AAPL', 'SBUX']
trader = Trader(symbols)
trader.start_trading()
if __name__ == '__main__':
main() |
@dandwfdm I ran your sample code for over 3 hours yesterday. there was no issue I encountered. |
Ran for 4 1/2 hours today before gettting the error. |
Error after 30 min. today, but as I said, it could run a day or 2 before getting one. |
Failed again after 5 min. after restart |
Ok for 3 1/2 hours till stopped |
Still experiencing this issue daily. Any updates? |
Still getting it as follows:
7/27 1006 error at 10:36 ET
7/28 OK
7/29 OK
7/30 at 11:25
7/31 OK
8/3 at 9:46 and 14:12
On 8/3/2020 1:45:47 PM, rizzomichaelg <[email protected]> wrote:
Still experiencing this issue daily. Any updates?
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub [#265 (comment)], or unsubscribe [https://github.com/notifications/unsubscribe-auth/APH72T2MN7J45A5JVYVDHITR64AVHANCNFSM4OVWMO6A].
|
is it still the same sample code? |
Still the same code. Have installed the most recent code base 0.49.
Will try again tommorow
On 8/3/2020 4:37:13 PM, Shlomi Kushchi <[email protected]> wrote:
is it still the same sample code?
are you using the most recent code base?
try installing directly from github: pip install git+https://github.com/alpacahq/alpaca-trade-api-python
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub [#265 (comment)], or unsubscribe [https://github.com/notifications/unsubscribe-auth/APH72T3OMHSG4C363B6KWP3R64UYJANCNFSM4OVWMO6A].
|
I'm still seeing this error popping up occasionally when subscribed to the AM stream, though the library is reconnecting fairly quickly. It looks like there's something going on with PONG responses from the websocket server. Here's some logs I captured:
|
Hi, this sounds like normal behavior. especially from the SDK side. |
I'm running into a similar issue where the websocket connection is lost and never reconnected. It happens at varying intervals, anywhere from minutes to hours. I'm running the I'm also starting the stream by scheduling a call to I saved the test script and logs as gists to avoid cluttering this issue with more code. Environment details: Thanks for any help! |
Hi, second, the stream data is not streamed outside market hours (it differs between polygon and the alpaca data stream a bit) third point, this is a bit tricky, asyncio thing - based on my experience, the thread that opens a websocket is the only thread that could send messages to that websocket connection (it relies on the eventloop being the same) in this project I have 1 ws connection to the api servers, and other websockets that use this one connection to get multiple data streams for different strategies. |
I have a similar approach like the one mentioned by @JSTHoffman and I did try the proxy functionality but I still have this disconnect error of 1006. Although the frequency of the disconnects have dropped substantially. Have anyone done extensive tests on this? |
Adding my voice to the choir that the latest version of the api (0.51) still does not connect for me, on two separate computers; the older version (0.46) does reconnect correctly. I've not had a chance to look at the source yet, but thought I'd mention it here. Here's the traceback that happens at least daily. Yesterday:
Today:
|
Error is persisting for me as well |
Still getting the 1006 error with v1.5.0 and no news streamed. Also, have tested it in golang afterwards and streamed news working fine.. |
Hey closing this one out due to inactivity. Also please see #588 for a more recent issue on this happening. With recent changes to both the SDK and the API itself we believe this issue should be mostly mitigated |
Got the most recent code which I thought had a solution to this problem, but still getting it. Have had 2 today.
Here is the Traceback. Any help would be appreciated.
WARNING:root:code = 1006 (connection closed abnormally [internal]), no reason
Traceback (most recent call last):
File "C:/Projects/stocks/src/main.py", line 272, in
main()
File "C:/Projects/stocks/src/main.py", line 156, in main
trading.ws_start()
File "C:\Projects\stocks\src\trading.py", line 381, in ws_start
self.conn.run(['AM.SPY', 'trade_updates'])
File "C:\Projects\stocks\src\alpaca_trade_api\stream2.py", line 287, in run
loop.run_until_complete(self.consume())
File "C:\Users\jimpc4\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
asyncio.exceptions.CancelledError
The text was updated successfully, but these errors were encountered: