Will I need a consumers.py, asgi,py and routing.py using Tradier's websocket API?

32 views Asked by At

So I'm trying to stream market data via the tradier API with websockets. Here are 2 links to the docs: https://documentation.tradier.com/brokerage-api/streaming/websocket-streaming https://documentation.tradier.com/brokerage-api/streaming/wss-market-websocket

I'm not too familiar with websockets, so I'm wondering if I need to use django channels and add a consumers.py, asgi.py, and routing.py to stream this market data live to a front end? If the answer is yes, what would I need to add in each of these files?

I've tried just having a consumers.py and having the streaming endpoint in urls.py

consumers.py:

import json
import logging
import websockets
from channels.generic.websocket import WebsocketConsumer
from .tradingAPI.tradier import tradierFunctions

logger = logging.getLogger(__name__)

class TradierStreamConsumer(WebsocketConsumer):
    async def connect(self):
        await self.accept()

        logger.info("WebSocket connection established")

        uri = "wss://ws.tradier.com/v1/markets/events"
        async with websockets.connect(uri, ssl=True, compression=None) as websocket:
            payload = {
                "symbols": ["SPY", "NVDA"], 
                "sessionid": tradierFunctions.createStreamingSession(), 
                "filter": ["quote"],
                "linebreak": "true"
                }
            await websocket.send(json.dumps(payload))
            
            logger.info(f"Sent payload: {payload}")

            async for message in websocket:
                logger.info(f"Received message: {message}")
                await self.send(text_data=json.dumps({"message": message}))

urls.py:

urlpatterns = [
    ...
    path('api/tradier/stream', TradierStreamConsumer.as_asgi()),
]

I expected continuous JSON data being streamed to the web page, but in reality I get this: enter image description here

Also, this is my console output when I log the info: enter image description here

0

There are 0 answers