Basic websocket python script copied from the github not working.


  • I don't see any messages or ticks on running the below script. I expect at least it should print the message inside the on connect method, but it just hangs and don't print any thing

    Below is the script.

    from smartapi import SmartConnect #or from smartapi.smartConnect import SmartConnect
    #import smartapi.smartExceptions(for smartExceptions)
    from smartapi import SmartWebSocket
    import multiprocessing
    import sys

    #create object of call
    obj=SmartConnect(api_key="API key")

    #login api call

    data = obj.generateSession("Client code","password")
    refreshToken= data['data']['refreshToken']

    #fetch the feedtoken
    feedToken=obj.getfeedToken()

    #fetch User Profile
    userProfile= obj.getProfile(refreshToken)

    print(userProfile)
    CLIENT_CODE = "<client code>"

    token="mcx_fo|224395"

    token = "EXCHANGE|TOKEN_SYMBOL" # SAMPLE: nse_cm|2885&nse_cm|1594&nse_cm|11536&nse_cm|3045

    token="mcx_fo|226745&mcx_fo|220822&mcx_fo|227182&mcx_fo|221599"

    token="nse_cm|2885&nse_cm|1594&nse_cm|11536&nse_cm|3045"
    task = "mw" # mw|sfi|dp

    ss = SmartWebSocket(feedToken, CLIENT_CODE)

    def on_tick(ws, tick):
    print("Ticks: {}".format(tick))

    def on_connect(ws, response):
    print("Inside connect")
    ws.websocket_connection()
    ws.send_request(token,task)

    def on_message(ws, message):
    print("Ticks: {}".format(message))

    def on_open(ws):
    print("on open")
    ss.subscribe(task, token)

    def on_error(ws, error):
    print(error)

    def on_close(ws):
    print("Close")

    Assign the callbacks.

    #ss.on_open = on_open
    #ss.on_message = on_message
    ss.on_ticks = on_tick
    ss.on_error = on_error
    ss.on_close = on_close
    ss.on_connect = on_connect

    ss.connect()
    #p1 = multiprocessing.Process(target = ss.connect())
    #sys.exit()
    #p1.start()

    When i print the user profile, i am getting a valid success response:

    {'status': True, 'message': 'SUCCESS', 'errorcode': '', 'data': {'clientcode': '<Code>', 'name': '<Name>', 'email': '', 'mobileno': '', 'exchanges': ['bse_cm', 'nse_cm', 'nse_fo', 'ncx
    _fo', 'mcx_fo', 'cde_fo'], 'products': ['CNC', 'NRML', 'MARGIN', 'MIS', 'BO', 'CO'], 'lastlogintime': '', 'broker': ''}}

    Can you please tell wht is wrong with the code?


  • Hi @issacj Have you passed the valid feed token to get the feed.