Connection error: 1006

Yogarajan
Hi

Am new to API trading just started few months ago. On friday I have by mistake close the terminal without properly terminating the python script. I am getting the below error. Didn't find any proper answer anywhere online. could somebody help. Am using a static API. None of my trading script which which has websocket is going through.

Connection error: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
  • rakeshr
    Am using a static API. None of my trading script which which has websocket is going through.
    Connection error: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
    This websocket error seems to be unrelated to forced closure of the program. Can you paste here the complete websocket code? Are you placing order or doing heavy computing inside ws stream?
  • Yogarajan
    Hi @rakeshr

    I am just doing virtual trading by fetching live prices from zerodha API. The code was working perfectly without any issue till friday. Just by mistake closed the terminal before closing the script.
    thank you for your response.

    Below is the code.

    class PerfectTrader:
    def __init__(self):
    # Stock data
    atexit.register(self.clean_shutdown)
    self.stock_prices = {stock: {'current': 0, 'open': 0} for stock in STOCKS}

    # Options data
    self.option_data = {
    stock: {
    'atm_strike': 0,
    'ce_price': 0,
    'pe_price': 0
    } for stock in STOCKS
    }

    self.active_trades = []
    self.total_pnl = 0
    self.ticker = KiteTicker(API_KEY, ACCESS_TOKEN)

    # WebSocket callbacks
    self.ticker.on_connect = self.on_connect
    self.ticker.on_ticks = self.on_ticks

    def reset_connection():
    try:
    self.ticker.close()
    except:
    pass
    time.sleep(2)
    self.ticker.connect(threaded=True)

    def clean_shutdown(self):
    """Handle unexpected closures gracefully"""
    print("\nPerforming emergency cleanup...")
    if self.ticker:
    try:
    self.ticker.close()
    except:
    pass
    print(f"Final PnL: ₹{self.total_pnl:.2f}")


    def on_close(self, ws, code, reason):
    """Auto-reconnect on unexpected closures"""
    print(f"\nConnection lost ({code} - {reason}). Reconnecting...")
    time.sleep(5)
    self.ticker.connect(threaded=True)
    self.reset_connection()

    def on_ticks(self, ws, ticks):
    now = datetime.now().time()

    # Update stock prices
    for tick in ticks:
    for stock in STOCKS:
    if tick['instrument_token'] == self.token_map[stock]:
    self.stock_prices[stock]['current'] = tick['last_price']

    # Set opening prices
    if all(p['open'] == 0 for p in self.stock_prices.values()):
    if all(p['current'] > 0 for p in self.stock_prices.values()):
    for stock in STOCKS:
    self.stock_prices[stock]['open'] = self.stock_prices[stock]['current']
    print("Opening prices set")

    # Update option data
    self.update_option_data()

    # Trading logic - ONLY when we have capacity
    if START_TIME <= now <= END_TIME:
    self.check_exits()

    if len(self.active_trades) < MAX_CONCURRENT_TRADES:
    signals = self.generate_signals()
    if signals:
    best_signal = max(signals, key=lambda x: x['divergence'])
    self.execute_trade(best_signal)

    self.update_dashboard()

    def run(self):
    self.ticker.connect(threaded=True)
    try:
    while True:
    time.sleep(1)
    except KeyboardInterrupt:
    print(f"\nFinal Total PnL: ₹{self.total_pnl:.2f}")
    sys.exit(0)
    print(f"Error: {str(e)}")
    self.clean_shutdown() # Ensure cleanup is performed

    if __name__ == "__main__":
    retry_count = 0
    try:
    trader = PerfectPairTrader()
    trader.run()
    except Exception as e:
    print(f"Error: {str(e)}")
    self.clean_shutdown()
    sys.exit(0)
    except Exception as e:
    print(f"Error: {str(e)}")
    self.clean_shutdown() # Ensure cleanup is performed
  • sujith
    You seem to be blocking the thread that is receiving ticks. You need to offload your calculation or writing to DB to the secondary thread.
  • Yogarajan
    @rakeshr

    I checked with my ISP to see if there is any issue from their side. they clearly said I am being blocked from the server side. I did run the script with different network. Issue remains. Only work around is I change the name of the script, it works for a couple of time. from 3rd or 4th time if i run the same script, i get the same error and again I have to change the name of the script. doing the same since saturday.
  • Yogarajan
    @sujith

    thanks for the sugession I'll modify and run the script again. but this issue didn't happen so far
  • Yogarajan
    @sujith @rakeshr

    after modifying the code am getting this error

    requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
  • Yogarajan
    @sujith @rakeshr

    so I have modified the script entirely without using websocket and completely to REST still i get the error.

    Zerodha says no problem from their end, My ISP says no problem from their end. offcourse I have tried in 3 different networks. Dont know whom to ask

    2025-04-28 23:35:24,929 - API error: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
  • Yogarajan
    even for REST API version. If i use the exisiting name of the script where I get the error. If I change the name to something else it doesn't throw the error.
Sign In or Register to comment.