Socket returning streaming data while market is closed

Gjain75
am running the sample code, it keeps returning ticks data while market is closed. Have not compared if its the identical data thats being repeated..during closed market, on_ticks shouldnt return anything.. or at best the last data once only? could someone clarify pls..
  • RED
    Try reading about After Market trades.

    Yes, trades are done during this period. you might be getting data intermittently but not continuous during this period.
  • rakeshr
    Have not compared if its the identical data thats being repeated..during closed market, on_ticks shouldn't return anything.. or at best the last data once only?
    Yes, as @RED said these are post-market orders(from 3:40 PM to 4:00 PM). You can know more about this here.
    You can have a condition to close WebSocket connection aftermarket timing for required exchange using the close method if you don't want to receive ticks post-market.
  • Gjain75
    @rakeshr Hi... today I am not able to get any data..though kws shows connected as True, and console shows streaming activity, tick_data is blank.. could you help please?
  • rakeshr
    console shows streaming activity, tick_data is blank
    Where you subscribed to correct instrument_token?
    You can fetch detail of the required tokens from the complete instrument list.
    You can check the WebSocket example here for the python clients.
  • Gjain75
    i collected the correct tokens from the instrument list, the same tokens worked yesterday.. today no data is returned for same tokens, I collected token data from kite.instruments method , same as in dump..
  • Gjain75
    @rakeshr i am using the same ws example that I used yesterday and got all ticks data.. today the same code is neither returning anything nor throwing any error !#@?
  • rakeshr
    Please paste your complete WebSocket code, along with instrument_token used. We will try to debug this at our end.
  • Gjain75
    tokens:
    59392 59393 25073666 25075714 25079810 25083906 25088002 25092098 25100290 24199170 24215554 24231938 26345474 59396 59397 59398 59399 59400 59401 59402 59403 59404 59405 59406 59407 59408 59409 59410 59411 59412 59413 59414 59415 59416 59417 59418 59419 59420 59421 59422 59423 59424 59425 59426 59427 59428 59429 59430 59431 59432 59433 59434 59435 59436 59437 59438 59439 59440 59441 26363394 59442 59444 59445 59446 59447 59443 59449 59450 59451 59452 59453 59454 59455 59456 59457 25102338 26347522 59460 59461 59462 59463 59464 59465 59466 59467 59468 59469 59470 59471 59472 59448 59474 59475 59476 59477 59478 59479 59480 59481 26356482 59483 59484 59485 59486 59487 59488 59489 24218626 59491 59492 59493 59494 59495 59496 59497 59498 59499 59500 59501 59502 59503 59504 59505 24202754 26365442 59508 59509 59510 59511 59512 59513 59514 59515 59516 59517 59518 59519 59520 59521 26349570 59523 59458 59525 59526 59527 59528 59459 24211714 59531 59532 59533 59534 59535 59536 59537 25088514 26333698 59540 59541 59542 59543 59544 59545 26358530 59547 59548 59549 59550 59551 59552 59553 24220674 59555 59556 59557 59558 59559 59560 59561 25097474 26342658 59564 59565 59566 59567 59568 59569 24204802 59571 59572 59573 59574 59575 59576 59577 25081602 59579 59580 59581 59582 59583 59584 59585 26351618 59587 59588 59589 59590 59591 59592 59593 24213762 59595 59596 59597 59598 59473 59600 59601 25090562 26335746 59604 59605 59606 59607 59608 59609 26360578 59611 59612 59613 59614 59615 59616 59617 24222722 59619 59620 59621 59622 59623 59624 59625 25099522 26344706 59628 59629 59630 59631 59632 59633 24206850 59635 59636 59637 59638 59639 59640 25092354 24207618 24224002 26337538 25078018 25094402 24209666 24226050 26339586 25096450 25083650 59482 59653 59654 59655 59656 59657 24215810 59659 59660 59661 59662 59663 59664 59665 25092610 26337794 24199938 26362626 25076738 24224770 59490 25101570 26346754 24208898 25085698 26355714 24217858 84311 25094658 26339842 26364674 25078786 24226818 25103618 26348802 24210946 59506 24231682 25087746 26332930 59507 26357762 24219906 25096706 26341890 24204034 25080834 26350850 24212994 25089794 26334978 26359810 59522 25073922 24221954 59524 25098754 26343938 24206082 25082882 24230914 59529 59530 25074178 25084418 25100802 24199682 24216066 24232450 26345986 25086466 25102850 24218114 26337026 26361858 25075970 59538 59539 26354946 59546 24201218 26363906 13256706 26348034 59554 26356994 24219138 26341122 25080066 59562 26350082 59563 24212226 25089026 26334210 26359042 24221186 59570 25097986 26343170 24205314 25082114 24230146 26352130 24214274 59578 25091074 26336258 24198402 26361090 24223234 25076482 25092866 24208130 24224514 26338050 25078530 25094914 24210178 24226562 26340098 25100034 24207362 59586 25084162 24232194 24216322 25093122 26338306 24200450 26363138 59594 25077250 24225282 25102082 26347266 24209410 59599 25086210 26356226 59602 24218370 59603 25095170 26340354 24202498 26365186 25079298 26349314 59610 24211458 26345218 25088258 26333442 26358274 24220418 25097218 26342402 59618 24204546 25081346 26351362 24213506 25090306 26335490 59626 26360322 59627 25074434 24222466 25099266 26344450 24206594 24231426 25083394 424961 25074690 25084930 25101314 24200194 24216578 24232962 26346498 25086978 25103362 24202242 26362370 59641 59642 59643 59644 59645 59646 26355458 59647 59634 59648 24217602 59649 59650 59651 26364418 59652 26348546 25087490 26332674 59658 26357506 24219650 26341634 24203778 25080578 59666 26350594 24212738 25089538 26334722 26359554 24221698 25098498 26343682 24205826 25082626 24230658 26352642 24214786 25091586 26336770 25076994 25093378 24208642 24225026 26338562 25079042 25095426 24210690 26340610 25081090 24223746 25100546 26345730 24207874 25084674 24232706 24216834 25093634 26338818 24200962 26363650 25077762 24225794 25102594 26347778 24209922 24198914 25086722 26356738 24218882 25095682 26340866 24203010 26349826 24211970 26361602 25088770 26333954 26358786 25072898 24220930 25097730 26342914 24205058 25081858 26351874 24214018 25090818 26336002 26360834 25074946 24222978 26344962 25099778 25073154 25075202 24198658 25085442 25101826 24200706 24217090 24233474 26347010 24215042 26362882 59338 25085954 26355970 59346 59347 26364930 25103874 26349058 59354 24211202 26333186 26358018 24220162 25096962 26342146 59362 24204290 12538882 26351106 24213250 25090050 26335234 59370 26360066 81622 59371 81623 81624 24222210 25099010 26344194 24206338 25083138 24231170 59378 25091842 25077506 25093890 24209154 24225538 26339074 24207106 24223490 25079554 25095938 26337282 24199426 26362114 59383 59384 25076226 24224258 59385 59386 25101058 26346242 59387 24208386 59388 59389 25085186 24233218 13747458 59390 26355202 59391 24217346 25094146 26339330 59394 59395 26364162 25078274 24226306 25103106 26348290 24210434 24215298 25087234 26332418 26357250 24219394 25096194 26341378 24203522 25080322 26350338 59301 59302 59303 59304 59305 59306 24212482 59307 59308 59309 59310 59311 59312 59313 25089282 26334466 59314 59315 25075458 59316 59317 59318 26359298 59319 59320 59321 59322 59323 59324 59325 25073410 24221442 59326 59327 59328 59329 59330 59331 25098242 26343426 59332 59333 59334 59335 59336 59337 24205570 59339 59340 59341 59342 59343 59344 59345 25082370 24230402 59348 59349 59350 59351 59352 59353 26352386 59355 59356 59357 59358 59359 59360 59361 24214530 59363 59364 59365 59366 59367 59368 59369 25091330 26336514 59372 59373 59374 59375 59376 59377 26361346 59379 59380 59381 59382
  • Gjain75
    Gjain75 edited August 2021
    # Callback for tick reception.
    def on_ticks(ws, ticks):
    if len(ticks) > 0:
    logging.info("Current mode: {}".format(ticks[0]["mode"]))

    # Callback for successful connection.
    def on_connect(ws, response):
    logging.info("Successfully connected. Response: {}".format(response))
    ws.subscribe(tokens)
    ws.set_mode(ws.MODE_FULL, tokens)
    logging.info("Subscribe to tokens in Full mode: {}".format(tokens))
    # result = ws.recv()
    # print(result)

    # Callback when current connection is closed.
    def on_close(ws, code, reason):
    logging.info("Connection closed: {code} - {reason}".format(code=code, reason=reason))
    # ws.stop()

    # Callback when connection closed with error.
    def on_error(ws, code, reason):
    logging.info("Connection error: {code} - {reason}".format(code=code, reason=reason))

    # Callback when reconnect is on progress
    def on_reconnect(ws, attempts_count):
    logging.info("Reconnecting: {}".format(attempts_count))
    ws.subscribe(tokens)

    # Callback when all reconnect failed (exhausted max retries)
    def on_noreconnect(ws):
    logging.info("Reconnect failed.")


    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_close = on_close
    kws.on_error = on_error
    kws.on_connect = on_connect
    kws.on_reconnect = on_reconnect
    kws.on_noreconnect = on_noreconnect

    try:
    kws.connect(threaded=True)
    except Exception as e:
    print("Connection failed : {e}")

    while True:
    def on_ticks(ws, ticks):
    logging.info("inside while loop, Current mode: {}".format(ticks[0]["mode"]))
    TickProcess(ticks)

    def TickProcess(ticks):
    print(ticks)
    tick_data.append(ticks)
    kws._on_ticks = on_ticks
  • Gjain75
    I had trimmed the code above for your ease, following is the actual full code, in case you can spare time for longer code..

    Note : code before kws.connect(threaded=True) is same as standard documentation above..
    =====================================
    df = pd.DataFrame()
    tick_data = []
    last = time.time()
    dt = datetime.now().strftime("%Y_%m_%d_%H_%M")
    dfile = os.path.join("C:\Zerodha", "tickfile_" + dt + ".csv")

    # Infinite loop on the main thread. Nothing after this will run.
    # You have to use the pre-defined callbacks to manage subscriptions.
    try:
    kws.connect(threaded=True)
    except Exception as e:
    print("Connection failed : {e}")

    while True:
    def on_ticks(ws, ticks):
    logging.info("inside while loop, Current mode: {}".format(ticks[0]["mode"]))
    TickProcess(ticks)

    # close the socket after market hours
    # if datetime.now().hour > 15 & (datetime.now().minute > 30):
    # ws.close()

    # Do all processing and computation on ticks in below func
    def TickProcess(ticks):
    global df, last, file, dfile
    print(ticks)
    tick_data.append(ticks)

    if time.time() - last >= 0: # write to file every [10] minute(s)
    for inst in ticks:

    tdf = pd.DataFrame.from_dict(inst, orient='index').T
    tdf['open'] = inst['ohlc']['open']
    tdf['high'] = inst['ohlc']['high']
    tdf['low'] = inst['ohlc']['low']
    tdf['close'] = inst['ohlc']['close']
    cols = ['tradingsymbol', 'name', 'expiry', 'strike', 'instrument_type',
    'lot_size']
    try:
    for col in cols:
    if col not in tdf.columns:
    tdf.insert(4, col, value='')
    tdf[col] = tdf.apply(lambda x: instruments_fno.at[x.name, col] if x.name in instruments_fno.index else instruments_cash.at[x.name, col] if x.name in instruments_cash.index else instruments_all.at[x.name, col] if x.name in instruments_all.index else "Not Found", axis=1)

    tdf.set_index('instrument_token', inplace=True)
    order_param_single_sell = [{
    "exchange": "NSE",
    "tradingsymbol": tdf.iloc[0]['tradingsymbol'],
    "transaction_type": "SELL",
    "variety": "regular",
    "product": "MIS",
    "order_type": "MARKET",
    "quantity": 1
    }]

    logging.info("Required margin for single order: {}".format(order_param_single_sell))

    order_param_single_buy = [{
    "exchange": "NSE",
    "tradingsymbol": tdf.iloc[0]['tradingsymbol'],
    "transaction_type": "BUY",
    "variety": "regular",
    "product": "MIS",
    "order_type": "MARKET",
    "quantity": 1
    }]
    logging.info("Required margin for single order: {}".format(order_param_single_buy))

    margin_detail_sell = kite.order_margins(order_param_single_sell)
    margin_detail_buy = kite.order_margins(order_param_single_buy)
    tdf['margin_sell'] = margin_detail_sell
    tdf['margin_buy'] = margin_detail_buy
    except:
    print("error in applying function")

    # @app.route("/")
    # def results():
    # return f"

    {tdf}

    "

    df = df.append(tdf)
    df.to_csv(dfile)
    dfg = df.groupby(by=['name', 'expiry'])
    # yield dfg
    # from hereon call the modules to do calculations for strategies
    kws._on_ticks = on_ticks


  • Gjain75
    @rakeshr kindly bear with the quality of coding, am not a tech guy and have learned very elementary coding, just trying to make do things somehow...thanks anyways in advance for your help... appreciate your spirit..
  • Gjain75
    @rakeshr.. hi could you pls help.. its third day in row am not able to get any data...
  • Gjain75
    solved.. kindly close the ticket..
This discussion has been closed.