Any freelancer here for websocket implementation, troubleshooting

nicetochatting
i have some code files that i have written myself. But i am facing a problem of fetching tick data from websocket and also closing the websockets (closing handshakes). Need troubleshooting. In python language
  • vaibhavsharma13
    Please share the code where you need help.
  • nicetochatting

    while True:
    for api_info in api_data.get('api_keys', []):
    time.sleep(5)
    api_key = api_info.get('api_key', '')
    with open('access tokens list.txt', 'r') as fp: # to read a json file
    hya = json.load(fp)
    ref_name = api_info.get('ref_name', '')
    access_token = hya[ref_name]['act']
    if not api_key or not access_token:
    print("Invalid API key or access token in the JSON file.")
    continue
    kite = KiteConnect(api_key=api_key)
    kite.set_access_token(access_token)
    kws = KiteTicker(api_key, access_token)
    abc = {}
    tick_queue = queue.Queue()
    # Function to process tick data
    def process_ticks():
    while True:
    tick = tick_queue.get()
    inst_token = tick['instrument_token']
    last_price = tick['last_price']
    abc[inst_token]['last_price'] = last_price

    # Start the tick processing thread
    tick_thread = threading.Thread(target=process_ticks, daemon=True)
    tick_thread.start()

    # Define on_ticks callback
    def on_ticks(ws, ticks):
    for tick in ticks:
    tick_queue.put(tick)

    # Define on_connect callback
    def on_connect(ws, response):
    ws.subscribe(list(stock.keys()))
    ws.set_mode(ws.MODE_LTP, list(stock.keys()))

    data = kite.positions()
    stock = {}
    for entry in data['net']:
    instrument_token = entry['instrument_token']
    trading_symbol = entry['tradingsymbol']
    abc[instrument_token] = {} # Initialize the nested dictionary if not present
    qty = entry['quantity']
    # delayed_pnl = entry['pnl']
    sell_value = entry['sell_value']
    buy_value = entry['buy_value']
    abc[instrument_token]['trading_symbol'] = trading_symbol
    abc[instrument_token]['qty'] = qty
    abc[instrument_token]['sell_value'] = sell_value
    abc[instrument_token]['buy_value'] = buy_value
    # abc[instrument_token]['delayed_pnl'] = delayed_pnl
    stock[instrument_token] = trading_symbol

    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.connect(threaded=True)
    time.sleep(5)
    # print(abc)
    m2m_calc = 0
    for entry in abc.values():
    m2m_calc = m2m_calc + entry['sell_value'] - entry['buy_value'] + (entry['qty'] * entry['last_price'])

    print("final m2m of " +ref_name + " is "+ str(round(m2m_calc)))
    kws.close()
Sign In or Register to comment.