Hi :) I have few Questions on WebSocket, RSI & LTP. Please help me out

Question 1:

Is this the right way to establish the WebSocket connection? have I missed anything here ?

def on_open(ws):
    print("WebSocket connection opened")
    auth_data = {
        "client_id": client_id,
        "access_token": access_token
    }
    ws.send(json.dumps(auth_data))

def on_close(ws):
    print("WebSocket connection closed")

def on_error(ws, error):
    print(f"WebSocket error: {error}")

ws_url = "wss://api-feed.dhan.co"
ws = websocket.WebSocketApp(ws_url, on_message=on_message, on_open=on_open, on_close=on_close, on_error=on_error)

Question 2:

Can I open the WebSocket in a thread?

import threading
ws_thread = threading.Thread(target=ws.run_forever)
ws_thread.start()

Question 3:

In on_message of websocket event, do we receive the ltp in the message attribute (data['ltp'])?

def on_message(ws, message):
    data = json.loads(message)
    ltp = data['ltp']  # Assuming the message contains the latest price as 'ltp'

Question 4:

In holdings[holdings['symbol'] == script]['buy_price'].iloc[0] and positions[positions['symbol'] == script]['buy_price'].iloc[0], do we get buy_price?

Python

def get_buy_price():
    if not holdings.empty and script in holdings['symbol'].values:
        return holdings[holdings['symbol'] == script]['buy_price'].iloc[0]
    if not positions.empty:
        position = positions[positions['symbol'] == script]
        if not position.empty and position['transaction_type'].iloc[0] == 'BUY':
            return position['buy_price'].iloc[0]
    return None

Question 5:

On my Windows server, Ta-lib is not working, so I have written the RSI calculation function. Is this correct?

Python

def calculate_rsi(data, window=14):
    delta = data.diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
    
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    
    return rsi

Hello @Bhaskar_S

Welcome to MadeForTrade community!

Sorry I missed this earlier. Adding replies where I can help:

No, you will have to use DhanFeed function. You can checkout the Quickstart code for the same.

Yes, you can. You will have to try and check the same although. Threading is not yet maintained by default in the library.

Data is currently not added in this format.

On 4 & 5, you will have to run this and check if you are getting the correct data or not yourself.