User Feedback - WebSocket 2.0 Beta Rollout – Python Language


  • We are excited to announce that WebSocket 2.0 functionality is now available on Python in public beta.

    Endpoint URL: ws://smartapisocket.angelone.in/smart-stream

    Features:

    1. Simplified and consistent request (JSON) and response (binary) structure.
    2. Simplified heartbeat message and response.
    3. Each client code (Angel One trading account id) can have up to three concurrent WebSocket connection
    4. No need to kill the connection and reconnect for subscribing and unsubscribing. The existing open connection can be used to subs and
    5. unsubs in real-time.
    6. Any failure in subscription requests will not impact existing subscriptions and the client will continue to get the feed.
    7. If the client sends an unsubs request for the tokens which are not subscribed then the system will gracefully ignore the request without impacting the feed for currently subscribed tokens.
    8. The total limit/quota of token subscriptions is 1000 per WebSocket session.
      a. For example: If the client subscribes to Infosys NSE with LTP, Quote, and SnapQuote mode then this will be counted as 3 subscriptions.
      b. Duplicate subscriptions to the same token and mode will be gracefully ignored and will not be counted towards the quota.
    9. The client will receive one tick per token_mode combination.
      a. For example: If the client subscribes to Infosys NSE with LTP, Quote, and SnapQuote mode then 1 tick will be published for each mode, containing respective fields.
      b. The recommendation is to subscribe to one mode as a time of a token.

    Thanks everyone for patiently waiting for this.

    Steps to use Python Library for WebSocket Feed:

    1. Clone the following repository -> https://github.com/angel-one/smartapi-python/tree/AMX-3393-Smart-Api-Python-Library
    2. Open the project in your favourite Terminal
    3. git checkout AMX-3393-Smart-Api-Python-Library
    4. Create a virtual environment
    5. Activate the virtual environment
    6. pip install -r requirements.txt
    7. Open the example/smartWebSocketv2Example.py file and change the value of AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN
    8. Subscribe to tokens by changing the value of token_list variable
    9. Run the file example/smartWebSocketv2Example.py
    10. You will get the ticks

    Data fields include OHLC, LTP, Volume, Open interest, 52 week high/low, Upper circuit/Lower circuit, Best 5 bid / ask etc

    last_traded_price
    last_traded_quantity
    average_traded_price
    volume_trade_for_the_day
    total_buy_quantity
    total_sell_quantity
    open_price_of_the_day
    high_price_of_the_day
    low_price_of_the_day
    closed_price
    last_traded_timestamp
    open_interest
    open_interest_change_percentage
    upper_circuit_limit
    lower_circuit_limit
    52_week_high_price
    52_week_low_price
    best_5_buy_data (quantity, price, no of orders)
    best_5_sell_data (quantity, price, no of orders)

    Websocket 2.0 Documentation https://smartapi.angelbroking.com/docs/WebSocket2

    Note: This is still in beta and our goal is to gather any feedback you have on the feature. We’ll be iterating based on your feedback to ensure that we’re heading the right way as we move towards the next steps in supporting WebSockets in other programming languages. With the launch of Websocket 2.0 we have officially withdrawn the support for Websocket 1.0 and any future updates to SmartAPI will not be rolled out for websocket 1.0.


  • @jaideep-siddula @DIYD57519, I'm also getting "attempting to resubscibe/reconnect", is there any solution, as I've drilled a bit and got Handshake status 404 not found.


  • Hi @jaideep-siddula , I'm also having the same issue, have you found the solution?


  • @DIYD57519 Im no getting on open. Instead, I'm getting "attempting to resubscibe/reconnect". Any help is appreciated.
    Thanks in advance


  • @sathyaraj
    We can fix this error by updating _on_close method with additional arguments in SmartWebSocketV2.py file.

    def _on_close(self, wsapp**, close_status_code, close_msg**):

    <Error: SmartWebSocketV2._on_close() takes 2 positional arguments but 4 were given>
    This error is thrown because on_close method of websocket class takes multiple arguments which are missing in SmartWebSocket library. Example code:
    https://websocket-client.readthedocs.io/en/latest/examples.html


  • nvm, I gather that this is the amount of pending buy and sell orders at the Exchange.


  • What is total_buy_quantity and total_sell_quantity?
    When are they different? I mean whatever is bought is sold as well. Thanks.


  • @dharm change the function as following

    @staticmethod
    def _parse_token_value(binary_packet):
        token = ""
        binary_packet = binary_packet.decode("UTF-8")
        for i in range(len(binary_packet)):
            if binary_packet[i] == '\x00':
                return token
            token += str(binary_packet[i])
        return token

  • @Ankita do you get any solution on this issue?
    If Yes so help me



  • @vrkhyd how can you get the live data?
    I am facing the same issue


  • Hi @Javajp @vishant @whemant @Kiran @Narendra_Javvadi @vrkhyd @zubuco @N399438

    We are excited to announce the release of updated SmartAPI libraries that now fully support WebSocket 2.0, further enhancing your trading experience. The latest versions of the SmartAPI Python SDK (1.3.4), SmartAPI Java SDK (2.1.0) and the SmartAPI Node.js Library (1.0.15) incorporate WebSocket 2.0 implementation, ensuring faster market data updates, reduced latency, and improved overall performance.

    https://smartapi.angelbroking.com/topic/3660/upgraded-smartapi-libraries-to-support-websocket-2-0-python-java-sdk-and-node-js-library


  • @J88913 dont install SmartApi. download and keep it in the same folder as program


  • @admin
    This script i not working. No error, nothing happens, It times out. Why ?
    I have tried many a times today.

    Code below:

    from SmartApi.smartWebSocketV2 import SmartWebSocketV2
    from smartapi import SmartConnect
    import pyotp

    obj=SmartConnect(api_key="") # feed app API key.
    #optional
    #access_token = "your access token",
    #refresh_token = "your refresh_token")
    #login api call
    token='
    '

    Login needs to be done through MPIN now.

    data = obj.generateSession("","",pyotp.TOTP(token).now())
    print(data)
    refreshToken= data['data']['refreshToken']
    jwt_token = data['data']['jwtToken']

    	#fetch the feedtoken
    

    feedToken=obj.getfeedToken()

    AUTH_TOKEN = jwt_token
    API_KEY = ******* #feed app API key
    CLIENT_CODE = '*******'
    FEED_TOKEN = feedToken

    correlation_id = "Testing"
    action = 1
    mode = 3

    token_list = [{"exchangeType": 1, "tokens": ["26009","11536","1594","2885"]}]

    sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)

    def on_data(wsapp, message):
    print("Ticks: {}".format(message))

    def on_open(wsapp):
    print("on open")

    sws.subscribe(correlation_id, mode, token_list)
    

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

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

    Assign the callbacks.

    sws.on_open = on_open
    sws.on_data = on_data
    sws.on_error = on_error
    sws.on_close = on_close

    sws.connect()


    Rsult:

    on open


  • How to handle ws disconnection?
    Do we need to Initialize ws again or it handles reconnection?
    I am getting the following error sometimes

    ERROR - Handshake status 429 Too Many Requests - goodbye
    ERROR - error from callback <bound method SmartWebSocketV2._on_close of <SmartWebsocketv2.SmartWebSocketV2 object at 0x000001D5D1637750>>: SmartWebSocketV2._on_close() takes 2 positional arguments but 4 were given
    ERROR - [WinError 10054] An existing connection was forcibly closed by the remote host - goodbye
    ERROR - error from callback <bound method SmartWebSocketV2._on_close of <SmartWebsocketv2.SmartWebSocketV2 object at 0x000001D5D1637750>>: SmartWebSocketV2._on_close() takes 2 positional arguments but 4 were given


  • @admin and team and forum members

    Request you to post a final working working Websocket 2.0 code as i am still not able to get any ticks even after doing all the changes discussed above.

    Thank you.


  • Is websocket 2.0 working? As i am getting only ping data(subscribing to Options). @admin @rajanprabu @StocksDeveloper @rjbanna


  • @admin, the instructions for websocket2.0 seems to be too lengthy, Kindly consider to simplify & add sample like we have it in https://github.com/angel-one/smartapi-python🙏


  • @vrkhyd https://github.com/markov404/AngelOneOptionChainSmartApi
    You can user this script it is getting data about OPTIDX every 3 min then saving and updating. You can change the way of saving , it describes in readme.


  • Hi @asho and @vrkhyd if anyone of you can provide any help on this? Thanks.