alpacahq / alpaca-py

The Official Python SDK for Alpaca API
https://alpaca.markets/sdks/python/getting_started.html
Apache License 2.0
537 stars 134 forks source link

[Bug]: Data WebSocket Error: Restarting Connection Due to Server Rejected WebSocket Connection (HTTP 404) #383

Closed CurtMRosenbladWheeler closed 9 months ago

CurtMRosenbladWheeler commented 9 months ago

Is there an existing issue for this?

Current Behavior

When executing the provided code snippet with the specified Alpaca API keys to stream live cryptocurrency quote data (BTCUSD), the following issue occurs: "data websocket error, restarting connection: server rejected WebSocket connection: HTTP 404."

from autotrader.configs.alpaca_settings import ALPACA_API_KEY, ALPACA_SECRET_KEY

from alpaca.data.live import CryptoDataStream

# keys are required for live data
crypto_stream = CryptoDataStream(ALPACA_API_KEY, ALPACA_SECRET_KEY)

async def quote_data_handler(data):
    # quote data will arrive here
    print(data)

crypto_stream.subscribe_quotes(quote_data_handler, "BTCUSD")

crypto_stream.run()

Expected Behavior

The code should successfully establish a WebSocket connection to Alpaca's API for live cryptocurrency quote data (BTCUSD). Upon successful connection, the program should subscribe to quote updates and print the received data to the console using the quote_data_handler function. There should be no WebSocket errors, and the program should run without encountering HTTP 404 rejection from the server.

SDK Version I encountered this issue in

alpaca-py version: 0.13.3

Steps To Reproduce

1. Ensure that the Alpaca API key (ALPACA_API_KEY) and secret key (ALPACA_SECRET_KEY) in the alpaca_settings.py file are valid and have the necessary permissions for accessing live cryptocurrency data.

2. Run the provided Python script containing the code snippet that initializes an instance of CryptoDataStream and subscribes to live cryptocurrency quote data for the pair "BTCUSD."

3. Observe the console output and look for any error messages. In particular, check for the presence of the following error: "data websocket error, restarting connection: server rejected WebSocket connection: HTTP 404."

4. Verify that the issue persists consistently, indicating that the WebSocket connection is consistently rejected with a 404 status.

Filled out the Steps to Reproduce section?

Anything else?

No response

hiohiohio commented 9 months ago

@CurtMRosenbladWheeler Thank you for the issue report. Can you please try to use BTC/USD instead of BTCUSD?

CurtMRosenbladWheeler commented 9 months ago

@hiohiohio, I tried following your suggestion, but unfortunately, I'm still encountering the same error.

hiohiohio commented 9 months ago

@CurtMRosenbladWheeler hmmm. the below code works for me (Sorry, I am currently hitting the rate limit, so cannot try with your code). May I please ask you to provide actual logs of the error if possible?

from alpaca.data.live import CryptoDataStream

stream = CryptoDataStream(
    api_key=API_KEY,
    secret_key=API_SECRET,
)
symbol = "BTC/USD"
async def handler(data):
    print(data)
stream.subscribe_quotes(handler, symbol)
stream.subscribe_trades(handler, symbol)

stream.run()
CurtMRosenbladWheeler commented 9 months ago

@hiohiohio I encountered the same error when I ran your code: data websocket error, restarting connection: server rejected WebSocket connection: HTTP 404.

To troubleshoot, I implemented my own code to make a request to wss://stream.data.alpaca.markets/v1beta3/crypto/us, and it worked seamlessly without encountering any issues. Below is the code for reference:

import asyncio
import websockets
import json
from autotrader.configs.alpaca_settings import ALPACA_API_KEY, ALPACA_SECRET_KEY

async def connect_to_websocket():
    uri = "wss://stream.data.alpaca.markets/v1beta3/crypto/us"
    async with websockets.connect(uri) as websocket:
        auth_data = {
            "action": "auth",
            "key": ALPACA_API_KEY,
            "secret": ALPACA_SECRET_KEY
        }
        await websocket.send(json.dumps(auth_data))

        subscribe_data = {
            "action": "subscribe",
            "trades": ["BTC/USD"],
            "quotes": ["LTC/USD", "ETH/USD"],
            "bars": ["BCH/USD"]
        }
        await websocket.send(json.dumps(subscribe_data))

        async for message in websocket:
            print(message)

asyncio.run(connect_to_websocket())

This code establishes a WebSocket connection without encountering the mentioned error. Please let me know if you have any insights into why the original code might be facing this issue.

hiohiohio commented 9 months ago

@CurtMRosenbladWheeler thank you for the update and detailed info. Appreciate. It helps me a lot. Unfortunately, I still cannot reproduce the error you mentioned in my env. May I please ask you to provide the version of below libraries and python? I think the issue could be coming from library compatibility issues.

python
msgpack
pydantic
pydantic_core
websockets
hiohiohio commented 9 months ago

Found a way to reproduce this and created a PR to fix. https://github.com/alpacahq/alpaca-py/pull/385

Gustavanovic commented 9 months ago

Hey everyone! I can't import alpaca.data.live. I've downloaded the alpaca-py. Please help me :)