Websocket end to end code or best resource

Kamalv
@sujith @rakeshr and all,

I am looking for end to end good practice Websocket code/examples, I can handle routine tasks (connect, register, place order, register order, upon complete close the connection) but facing challenges (connection related activities) while developing robust framework such as restore connection with same state upon onReconnect, handling if force abort from zerodha side, etc).

Official document is good but having definition & syntax but I'm looking for one level down, end to end good practice code. I spent 3 days to build complete framework but could not, failing upon reconnect (not able to bring back to exact state). Most of the blogs & videos has part of it but not full. Could you suggest some good resource/code.
  • sujith
    @Kamalv,
    You don't need to handle reconnect, it is done by the client libraries.
  • Kamalv
    @sujith my intention is to maintain exact state after new/re connection (connection closes if max reconnection attempts reached).

    Since i'm new to websocket concept and if i make any mistake will impact badly, so looking for reference code/project.
  • Kamalv
    @sujith @rakeshr i tried to save 'TATAMOTOTS' on_tick but it is getting disconnect. This is one of the scenarios. Here is my code. Can you help me if any issue with code or websocket.

    kws = KiteTicker(api_key, acc_code)
    mapInsdf = pd.read_csv('mapInsdf.csv')
    conn_prod = config.aws_connect('prod')
    cur = conn_prod.cursor()

    def on_ticks(ws, brokerTicks):

    tick = {}
    for bTick in brokerTicks:
    global mapInsdf
    tradingSymbol1 = mapInsdf.loc[mapInsdf['instrument_token']==bTick['instrument_token'], ['tradingsymbol']]
    tick['tradingSymbol'] = tradingSymbol1.iloc[0][0]
    tick['last_price'] = bTick['last_price']
    tick['change'] = round(bTick['change'],2)
    print(tick)

    sql = """ UPDATE current_stock_values SET ltp = %s, ltp_variance = %s WHERE stock_symbol = %s"""
    try:
    global conn_prod
    cur = conn_prod.cursor()
    cur.execute(sql, (tick['last_price'], tick['change'], tick['tradingSymbol']))
    conn_prod.commit()
    except (Exception, psycopg2.DatabaseError) as error:
    print(error)

    def on_connect(ws, response):
    ws.subscribe([884737])
    ws.set_mode(ws.MODE_FULL, [884737])

    def on_close(ws, code, reason):
    ws.stop()

    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.connect()
  • rakeshr
    Avoid doing any computation inside on_tick thread. This thread explains more regarding the above query.
  • Kamalv
    @rakeshr @sujith I followed the suggestions but still it is stopping after few ticks. Could you suggest if i miss anything.

    update_flg = True
    conn_prod = config.aws_connect('prod')

    def update_ltp(tick):

    global conn_prod, update_flg, ltp_prev
    update_flg = False

    if ltp_prev != tick['last_price']:
    ltp_prev = tick['last_price']
    cur = conn_prod.cursor()
    sql = """UPDATE current_stock_values SET ltp = %s, ltp_variance = %s WHERE stock_symbol = %s"""
    cur.execute(sql, (tick['last_price'], tick['change'], tick['tradingSymbol']))
    conn_prod.commit()
    update_flg = True

    except Exception as e:
    conn_prod.rollback()
    print("Error while updating ltp")
    print(e)


    def on_ticks(ws, brokerTicks):

    try:
    tick = {}
    for bTick in brokerTicks:
    global mapInsdf, update_flg, conn_prod
    tick['instrument_token'] = bTick['instrument_token']
    tick['last_price'] = bTick['last_price']
    tick['change'] = round(bTick['change'], 2)
    print(tick)

    if update_flg:
    update_ltp(tick)
    except Exception as e:
    print(e)
  • rakeshr
    Use method 1 mentioned in the above thread. This answer explains more on this.
Sign In or Register to comment.