def onclose(message):
"""Handles WebSocket connection close events."""
print("Connection closed:", message)
def onopen():
"""
Callback function to subscribe to data type and symbols upon WebSocket connection.
"""
global subscribed_symbols
# Specify the data type and symbols you want to subscribe to
data_type = "SymbolUpdate"
# Subscribe to the specified symbols and data type
SYMBOLS=set(get_scripts())
print(SYMBOLS)
subscribed_symbols.update(SYMBOLS)
#SYMBOLS = ["MCX:CRUDEOILM25FEBFUT","MCX:SILVER25MARFUT"]
#fyers.subscribe(symbols=SYMBOLS, data_type=data_type)
fyers.subscribe(symbols=list(subscribed_symbols), data_type=data_type)
# Keep the socket running to receive real-time data
fyers.keep_running()
Replace with your actual Fyers access token
#access_token = “R0YJ55A6R4-100:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkuZnllcnMuaW4iLCJpYXQiOjE3NDA2MzY1NzEsImV4cCI6MTc0MDcwMjYzMSwibmJmIjoxNzQwNjM2NTcxLCJhdWQiOlsieDowIiwieDoxIiwieDoyIiwiZDoxIiwiZDoyIiwieDoxIiwieDowIl0sInN1YiI6ImFjY2Vzc190b2tlbiIsImF0X2hhc2giOiJnQUFBQUFCbndBR2JibGcxSmpBVkN4ZXpVS25nNWhSVUx5am1jMDlLbmJiU0h1V1JJREw5YWh0N1VoZXlUOU5HcXRrNFpNNHYxdXZrd0lqcHBMRmhNZDRNXzRTdVFONGFZYWFUQ1ZfYVYxeExrSWhhSUx5cDFkND0iLCJkaXNwbGF5X25hbWUiOiJNSVRVTCBNQU5HRVNIIFNIRUxBVEtBUiIsIm9tcyI6IksxIiwiaHNtX2tleSI6IjUzYWEzMjU4NTg0MWVlOTUzYjk1Mjc4MmJiNDY3ZjYwNzE5ZTgzZjdhZjM1MDJhNzc2YTNhYTEzIiwiaXNEZHBpRW5hYmxlZCI6Ik4iLCJpc010ZkVuYWJsZWQiOiJOIiwiZnlfaWQiOiJZTTE5NTI1IiwiYXBwVHlwZSI6MTAwLCJwb2FfZmxhZyI6Ik4ifQ.c9o2dG_Xa7Hleir3QQ9OJhlJxFtkY23NEDAUgBhZ4Bk”
access_token = os.getenv(“FYERS_ACCESS_TOKEN”, “Token Not Found”)
Initialize Fyers WebSocket
fyers = data_ws.FyersDataSocket(
access_token=access_token,
log_path="",
litemode=False,
write_to_file=False,
reconnect=True,
on_connect=onopen,
on_close=onclose,
on_error=onerror,
on_message=onmessage
)
Start FastAPI Server in a Separate Thread
def run_fastapi():
[uvicorn.run](http://uvicorn.run)(app, host="0.0.0.0", port=8000)
fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
fastapi_thread.start()
Connect to Fyers WebSocket
shutdown_event = threading.Event()
try:
fyers.connect()
shutdown_event.wait() # Wait indefinitely until shutdown signal
except KeyboardInterrupt:
print("CTRL + C detected. Closing connection...")
fyers.close_connection()
shutdown_event.set()
print("[INFO] Program terminated.")