[Python] twisted.internet.error.ReactorNotRestartable Error in AWS Lambda when using Kite...

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to run a AWS Lambda function which acheives the following :

    1. Run the code every 10 minutes, which will subscribe to tick data for one or more stocks
    2. Call the function if the tick_datetime.second is between 1 and 20
    3. Close the websocket and exit the code after 20 seconds or as defined by variable ttl

    Below is the code :

    from kiteconnect import KiteTicker
    kws = KiteTicker(api_key, access_token)
    tick_data = []
    unique_tk = []
    start_time = datetime.now(timezone("Asia/Kolkata"))

    instrument_token = i_token_list
    print("Tick Stock Instrument Token: ", instrument_token)

    def on_ticks(ws, ticks):
    tk = {}
    tk['t_stamp'] = ticks[0].get("last_trade_time")
    tk['last_price'] = ticks[0].get("last_price")
    # print("Ticks: ",tk['t_stamp'],tk['last_price'])
    return None

    def on_connect(ws, response):
    ws.subscribe(instrument_token)
    ws.set_mode(ws.MODE_FULL, instrument_token)

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

    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close

    kws.connect(threaded=True)
    # kws.connect()

    while True:
    def on_ticks(ws, ticks):
    feed_data(ticks)

    def feed_data(ticks):
    for tick in ticks:
    # print(tick)

    tk = {}
    tk['instrument_token'] = tick['instrument_token']
    tk['t_stamp'] = tick["last_trade_time"].astimezone(timezone('Asia/Kolkata')).strftime("%Y-%m-%d %H:%M:%S")
    tk['last_price'] = tick["last_price"]

    if 0 < tick["last_trade_time"].second < 20:
    tick_data.append(tk)

    kws.on_ticks=on_ticks

    def update_item(l_tick) :
    print(json.dumps(l_ticks, indent = 2))

    if (datetime.now(timezone("Asia/Kolkata")) -start_time).total_seconds() % 2 == 0:
    update_dynamo_item(tick_data)
    ttl_seconds = 20
    if (datetime.now(timezone("Asia/Kolkata")) -start_time).total_seconds() > ttl_seconds:
    update_dynamo_item(tick_data)
    print(str(ttl_seconds) + " seconds passed, closing connection...")
    kws.unsubscribe(instrument_token)
    kws.close()
    kws.stop()
    print("Tick Data: ", json.dumps(tick_data, indent=2))
    break


    In AWS Lambda, the code is running for the first invocation of Lambda function. From the second invocation onwards, the below error is thrown :

    >2025-06-26T09:19:50.536+05:30
    Exception in thread Thread-2 (run):
    >2025-06-26T09:19:51.356+05:30
    Traceback (most recent call last):
    >2025-06-26T09:19:51.416+05:30
    File "/var/lang/lib/python3.13/threading.py", line 1041, in _bootstrap_inner
    >2025-06-26T09:19:51.416+05:30
    self.run()
    >2025-06-26T09:19:51.416+05:30
    ~~~~~~~~^^
    >2025-06-26T09:19:51.456+05:30
    File "/var/lang/lib/python3.13/threading.py", line 992, in run
    >2025-06-26T09:19:51.456+05:30
    self._target(*self._args, **self._kwargs)
    >2025-06-26T09:19:51.456+05:30
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    >2025-06-26T09:19:51.476+05:30
    File "/opt/python/twisted/internet/base.py", line 695, in run
    >2025-06-26T09:19:51.476+05:30
    self.startRunning(installSignalHandlers=installSignalHandlers)
    >2025-06-26T09:19:51.476+05:30
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    >2025-06-26T09:19:51.516+05:30
    File "/opt/python/twisted/internet/base.py", line 926, in startRunning
    >2025-06-26T09:19:51.516+05:30
    raise error.ReactorNotRestartable()
    >2025-06-26T09:19:51.536+05:30
    twisted.internet.error.ReactorNotRestartable

    Continue reading...

Compartilhe esta Página