How to stopLive data Websocket program ?

How to stop Live data Websocket program ? after i unsubscribe too the python program executing and its not closing by itself , how to stop the program execting after 3:30 pm ? @Z4PBvkQGyF @chirag

This issue was fixed in 3.04 for Data socket and Order socket was fixed in 3.05

So upgrade to Fyers py 3.05 module and BOTH order and Data sockets Threads return properly

unsubscribe() will not explicitly disconnect the websocket, for that you need to call close_connection()

So if you are running program from terminal, i use simple keyboard interrupt as one of the EXIT Gracefully options.

Here is an outline of the code

class DataSocket():    # similar class for OrderSocket
   # other funcs here
   # init fyersDS var in class pvt

   def disconnect(self):
        try:
            ## import to disconnect
            if self.fyersDS:  self.fyersDS.close_connection()
        except Exception as e:
            print(f'DS disconnect(): {repr(e)}')
   
    #other class stuff

## in main thread or Main running func ##
try:
    # init DataSocket and OrderSocket objects here
     while True:
         # here I have queue.Queue
         # all stuff to process Q tasks
         ## WRITE all Termination Condition here
         # like time > XX or only Weekdays or many other, then raise KB interrupt if any is True

except KeyboardInterrupt:
    # code to perform clean up
    fyers_obj_os.disconnect()
    fyers_obj_ws.disconnect()
    # wait for other threads to join etc

# handle other Exceptions

@sathishmurugan450-phl my post is pending review so wait until someone approves it

Hi @chirag im already used close_connection()

in my code but still program not get out of it .

Did you check the Package version?

package version mean? Chirag can you please provide your mail id i’ll reachout you

fyers-apiv3 · PyPI

Yes im using latest Fyers Api 3.05 only , Dont know why its happening like this

Check your code. After last patch there is no issue in py module.

Do it peacefully, or write small test script and verify in that instead.

Yes @sathishmurugan450-phl
Chirag is right

This issue has been fixed
By using close_connection you can close the connection

         def onmessage(msg):

               # print(msg)

                scriptt = msg['symbol']
                script = scriptt[4:]
                open_price = msg['open_price']
                high = msg['high_price']
                low = msg['low_price']
                close = msg['prev_close_price']
                ltp = msg['ltp']

                if (script == 'NIFTY50-INDEX'):

                    last_traded_time = msg['exch_feed_time']

                    volume = 0

                else :

                    last_traded_time = msg['last_traded_time']

                    volume = msg['vol_traded_today']

                ltt_naive = dt.datetime.fromtimestamp(last_traded_time)
                ltt = timezone.make_aware(ltt_naive, timezone.get_current_timezone())

                Live_Data.objects.create(
                    Symbol=script,
                    Open=open_price,
                    High=high,
                    Low=low,
                    Ltp=ltp,
                    Close=close,
                    Ltt=ltt,
                    Volume=volume
                )

                now = dt.datetime.now()
                hour = now.hour
                minute = now.minute

                if (hour >= 15) and (minute >= 30):

                    fyers.unsubscribe(symbols=Strikes, data_type='SymbolUpdate')

                    print('Market Closed...')
                    fyers.close_connection()

            def onerror(message):

                print("Error:", message)
                with open('D:\Trading Projects\Django\Logs\Live_Data_Log.txt', 'a') as error_file:
                    error_file.write(f'{now} Error occurred: {str(message)}\n')

            def onclose(message):

                print("Connection closed:", message)
                with open('D:\Trading Projects\Django\Logs\Live_Data_Log.txt', 'a') as error_file:
                    error_file.write(f'{now} Error occurred: {str(message)}\n')
                sys.exit()

            def onopen():

                data_type = "SymbolUpdate"

                fyers.subscribe(symbols=Strikes, data_type=data_type,channel=15)

                fyers.keep_running()

            log_path = 'D:\\Trading Projects\\Django\\Logs\\'

            fyers = data_ws.FyersDataSocket(
                access_token=access_token,
                log_path=log_path,
                litemode=False,
                write_to_file=False,
                reconnect=True,
                on_connect=onopen,
                on_close=onclose,
                on_error=onerror,
                on_message=onmessage
            )

            fyers.connect()

Here you can see during onmessage() im checking whether the time is greater than 15 : 30 if condition satisfied then im unsubscribing and using fyers.close_connection() but its closing the connection

with the below logs

2023-11-22 15:35:16.188554 Error occurred: cannot join current thread

2023-11-22 15:35:16.188554 Error occurred: {‘code’: 200, ‘message’: ‘Connection Closed’, ‘s’: ‘ok’}

but after that its get out from the onmessage() so that program execution is not getting stopped and the python program continuously , this is the issue @Z4PBvkQGyF @chirag

Before you posted code itself i told you, and i gave outline of my code.

On_Message() is a callback function that runs in websocket thread space.

That is why you do all that in MAIN Thread, not in CB func. So let the Main thread run as an infinite loop and keep couple of exit conditions like TIME > CloseTime, Some Exceptions, Reconnect count and Raise KB Interupt to break it.

Thats how all appl work, Main thread processes all events and all tasks ideally should be run in their own threads.

@sathishmurugan450-phl again my post is pending review, sometimes it takes whole day/night for them to approve. in short, you should do all that in main thread not cb func.

@Z4PBvkQGyF bhai, someone should approve posts more frequently and also get rid of SPAM posts that pile up from 5PM to 8AM next day :grinning_face_with_smiling_eyes:

Yr I have also moderate access but I can not see your post.

Hi @sathishmurugan450-phl

I have also tried for same he is correct,
You have to call outside this side.

Check once outside then update us.
It is working I checked for you just now.

@sathishmurugan450-phl

this is what i wrote

def onmessage(msg):

    #rest of my code

# Now outside of my CB function

if (hour >= 15) and (minute >= 30):

    fyers.unsubscribe(symbols=Strikes, data_type='SymbolUpdate')

    print('Market Closed...')

    fyers.close_connection()

I think this is what both of you trying to tell . is the above code correct ? @chirag @Z4PBvkQGyF

This small piece of code does not make sense, but may not work so you test. Ideally this is crude code, not well structured. In main thread, execution will pass over it and wait at the end for websocket thread to join.

I have given you full outline in my example which is actually working unit test, so I expect you to work from there and I can’t dedicate excess time to minor issue. (I am not from support)

@chirag @Z4PBvkQGyF Now i fixed and its working well . Thankyou so much both of you . :innocent:

Hi @chirag

I approved your post , Can you check now it is published or not.

However I got to know, it comes after 1 day for approval. As I can not see your post yesterday but it is visible and I published it.

And No need to worry if it comes under approval, sometimes mine also goes.