from flask import Flask, jsonify
from flask_sock import Sock
import websocket
import json
import threading
import time
app = Flask(name)
sock = Sock(app)
Replace with your valid access token
FYERS_ACCESS_TOKEN = “FYERS_ACCESS_TOKEN”
FYERS_WEBSOCKET_URL = f"ws://socket.fyers.in/quotes/v2?access_token={FYERS_ACCESS_TOKEN}"
Store real-time stock data
live_stock_data = {}
def on_message(ws, message):
global live_stock_data
try:
data = json.loads(message)
if "d" in data:
for stock in data["d"]:
symbol = stock["s"]
live_stock_data[symbol] = {
"ltp": stock["lp"],
"open": stock["open_price"],
"high": stock["high_price"],
"low": stock["low_price"]
}
except Exception as e:
print("Error processing message:", e)
def on_error(ws, error):
print("WebSocket Error:", error)
reconnect_websocket(ws)
def on_close(ws, close_status_code, close_msg):
print("WebSocket Closed:", close_status_code, close_msg)
reconnect_websocket(ws)
def on_open(ws):
print("WebSocket Connected!")
payload = {
"T": "SUB_LTP",
"SL": ["NSE:RELIANCE", "NSE:TCS", "NSE:HDFCBANK", "NSE:INFY"]
}
ws.send(json.dumps(payload))
def reconnect_websocket(ws):
""" Auto-reconnect if the WebSocket fails """
print("Reconnecting in 5 seconds...")
time.sleep(5)
start_websocket()
Start WebSocket in a separate thread
def start_websocket():
ws = websocket.WebSocketApp(FYERS_WEBSOCKET_URL,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
[ws.run](http://ws.run)_forever()
Run WebSocket in background
threading.Thread(target=start_websocket, daemon=True).start()
WebSocket route for frontend
@sock.route(‘/ws’)
def send_live_data(ws):
while True:
ws.send(json.dumps(live_stock_data))
time.sleep(1) # Send data every second
if name == ‘main’:
[app.run](http://app.run)(debug=True)