Fyers Websocket is not working

Running websocket throws following error.

Error: {‘code’: 12001, ‘message’: ‘Mode change failed’, ‘s’: ‘error’}

Error: {‘type’: ‘sub’, ‘code’: 11011, ‘message’: ‘subscription failed’, ‘s’: ‘error’}

Websocket Code

from fyers_apiv3.FyersWebsocket import data_ws

def onmessage(message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.

    """
    print("Response:", message)

def onerror(message):
    """
    Callback function to handle WebSocket errors.

    Parameters:
        message (dict): The error message received from the WebSocket.

    """
    print("Error:", message)

def onclose(message):
    """
    Callback function to handle WebSocket connection close events.
    """
    print("Connection closed:", message)

def onopen():
    """
    Callback function to subscribe to data type and symbols upon WebSocket connection.

    """
    # Specify the data type and symbols you want to subscribe to
    data_type = "SymbolUpdate"

    # Subscribe to the specified symbols and data type
    symbols = ['NSE:YESBANK-EQ']
    fyers.subscribe(symbols=symbols, data_type=data_type)

    # Keep the socket running to receive real-time data
    fyers.keep_running()

# Replace the sample access token with your actual access token obtained from Fyers
access_token = "app_id:access_token"
# account = get_first_account()
# access_token = f"{account.app_id}:{account.access_token}"
# Create a FyersDataSocket instance with the provided parameters
fyers = data_ws.FyersDataSocket(
    access_token=access_token,       # Access token in the format "appid:accesstoken"
    log_path="",                     # Path to save logs. Leave empty to auto-create logs in the current directory.
    litemode=False,                  # Lite mode disabled. Set to True if you want a lite response.
    write_to_file=False,              # Save response in a log file instead of printing it.
    reconnect=True,                  # Enable auto-reconnection to WebSocket on disconnection.
    on_connect=onopen,               # Callback function to subscribe to data upon connection.
    on_close=onclose,                # Callback function to handle WebSocket connection close events.
    on_error=onerror,                # Callback function to handle WebSocket errors.
    on_message=onmessage             # Callback function to handle incoming messages from the WebSocket.
)

# Establish a connection to the Fyers WebSocket
fyers.connect()

Hey @kb0eGzTj77

The current SDK version is 3.0.8 , if you’re using any version below please upgrade it to 3.0.8 to avoid this .

is this working ? or there some other code? i am using fyers_apiv3 3.1.4. i am geting error Error: Handshake status 403 Forbidden -±± {‘date’: ‘Mon, 17 Mar 2025 16:35:36 GMT’, ‘content-length’: ‘0’, ‘connection’: ‘keep-alive’, ‘cf-cache-status’: ‘DYNAMIC’, ‘set-cookie’: ‘_cf_bm=nntKygq3yZdkna6fBjjh3iKToI1vzc9CqCtKsQvRg5A-1742229336-1.0.1.1-ixC8r9nYSZb.K5HupmBQ.C4b8d7.ufZb.1403S4buBSOIMlAN5EmFZlpbTXHrp.tuDVbqvqmascQNMbDxuAQZoruu0.Hu2BnnIgDTXQCSQ; path=/; expires=Mon, 17-Mar-25 17:05:36 GMT; domain=.fyers.in; HttpOnly; Secure; _cfuvid=tX0FJoArIF2y5cnCq60apvgxsnW00BqcKxdl07neQ70-1742229336366-0.0.1.1-604800000; path=/; domain=.fyers.in; HttpOnly; Secure; SameSite=None’, ‘strict-transport-security’: ‘max-age=31536000; includeSubDomains; preload’, ‘x-content-type-options’: ‘nosniff’, ‘server’: ‘cloudflare’, ‘cf-ray’: ‘921de78579068fb6-KNU’} -±± b’’

ERROR:FyersDataSocket:Handshake status 403 Forbidden -±± {‘date’: ‘Mon, 17 Mar 2025 16:35:36 GMT’, ‘content-length’: ‘0’, ‘connection’: ‘keep-alive’, ‘cf-cache-status’: ‘DYNAMIC’, ‘set-cookie’: ‘_cf_bm=nntKygq3yZdkna6fBjjh3iKToI1vzc9CqCtKsQvRg5A-1742229336-1.0.1.1-ixC8r9nYSZb.K5HupmBQ.C4b8d7.ufZb.1403S4buBSOIMlAN5EmFZlpbTXHrp.tuDVbqvqmascQNMbDxuAQZoruu0.Hu2BnnIgDTXQCSQ; path=/; expires=Mon, 17-Mar-25 17:05:36 GMT; domain=.fyers.in; HttpOnly; Secure; _cfuvid=tX0FJoArIF2y5cnCq60apvgxsnW00BqcKxdl07neQ70-1742229336366-0.0.1.1-604800000; path=/; domain=.fyers.in; HttpOnly; Secure; SameSite=None’, ‘strict-transport-security’: ‘max-age=31536000; includeSubDomains; preload’, ‘x-content-type-options’: ‘nosniff’, ‘server’: ‘cloudflare’, ‘cf-ray’: ‘921de78579068fb6-KNU’} -±± b’’

ERROR:websocket:Handshake status 403 Forbidden -±± {‘date’: ‘Mon, 17 Mar 2025 16:35:36 GMT’, ‘content-length’: ‘0’, ‘connection’: ‘keep-alive’, ‘cf-cache-status’: ‘DYNAMIC’, ‘set-cookie’: ‘_cf_bm=nntKygq3yZdkna6fBjjh3iKToI1vzc9CqCtKsQvRg5A-1742229336-1.0.1.1-ixC8r9nYSZb.K5HupmBQ.C4b8d7.ufZb.1403S4buBSOIMlAN5EmFZlpbTXHrp.tuDVbqvqmascQNMbDxuAQZoruu0.Hu2BnnIgDTXQCSQ; path=/; expires=Mon, 17-Mar-25 17:05:36 GMT; domain=.fyers.in; HttpOnly; Secure; _cfuvid=tX0FJoArIF2y5cnCq60apvgxsnW00BqcKxdl07neQ70-1742229336366-0.0.1.1-604800000; path=/; domain=.fyers.in; HttpOnly; Secure; SameSite=None’, ‘strict-transport-security’: ‘max-age=31536000; includeSubDomains; preload’, ‘x-content-type-options’: ‘nosniff’, ‘server’: ‘cloudflare’, ‘cf-ray’: ‘921de78579068fb6-KNU’} -±± b’’ - goodbye

my code

from fyers_apiv3 import fyersModel
from fyers_apiv3.FyersWebsocket import order_ws
import sqlite3
import pandas as pd
import os
import sys
from pathlib import Path

# Ensure the project root is in sys.path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(project_root)
from app.doc import db_path, symbols, access_token, client_id,log_path
from datetime import datetime
import os
import time
import logging

# # Check if the directory exists, if not, create it
# if not os.path.exists(log_path):
#     os.makedirs(log_path)

fyers = fyersModel.FyersModel(client_id=client_id, is_async=False, token=access_token, log_path=log_path)
def onTrade(message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.

    """
    print("Trade Response:", message)

def onOrder(message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.

    """
    print("Order Response:", message)

def onPosition(message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.

    """
    print("Position Response:", message)

def onGeneral(message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.

    """
    print("General Response:", message)
def onerror(message):
    """
    Callback function to handle WebSocket errors.

    Parameters:
        message (dict): The error message received from the WebSocket.

    """
    print("Error:", message)

def onclose(message):
    """
    Callback function to handle WebSocket connection close events.
    """
    print("Connection closed:", message)

# WebSocket Callbacks
def onopen():
    """
    Callback function to subscribe to data type and symbols upon WebSocket connection.
    """
    # data_type = "SymbolUpdate","OnOrders", "OnTrades","OnGeneral","OnPositions"
    # data_type = "OnOrders, OnTrades, OnGeneral, OnPositions"
    data_type = "OnOrders,OnTrades,OnPositions,OnGeneral"
    fyers.subscribe(data_type=data_type)
    fyers.keep_running()
# WebSocket Initialization
fyers = order_ws.FyersOrderSocket(
    access_token=access_token,  # Your access token for authenticating with the Fyers API.
    write_to_file=False,        # A boolean flag indicating whether to write data to a log file or not.
    log_path="",                # The path to the log file if write_to_file is set to True (empty string means current directory).
    on_connect=onopen,          # Callback function to be executed upon successful WebSocket connection.
    on_close=onclose,           # Callback function to be executed when the WebSocket connection is closed.
    on_error=onerror,           # Callback function to handle any WebSocket errors that may occur.
    on_general=onGeneral,       # Callback function to handle general events from the WebSocket.
    on_orders=onOrder,          # Callback function to handle order-related events from the WebSocket.
    on_positions=onPosition,    # Callback function to handle position-related events from the WebSocket.
    on_trades=onTrade           # Callback function to handle trade-related events from the WebSocket.
)

def start_websocket():
    logging.info("[INFO] Starting WebSocket...")
    fyers.connect()
    logging.info("[INFO] Fyers WebSocket connected...")

def main():
    start_websocket()

if __name__ == "__main__":
    main()