An existing connection was forcibly closed by the remote host

rsandanshiv
Hi,

I've started getting below error on the python code, it was working fine till yesterday. Please help.

File "C:\Users\rsandanshiv\Anaconda3\lib\site-packages\requests\adapters.py", line 498, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
  • sujith
    Can you give us more details about this? Which API is throwing this error and let us know more about your setup and network details.
  • rsandanshiv
    rsandanshiv edited November 2021
    I am fetching realtime banknifty last_price using below code to check against my target/stoploss, it runs for some time and gives connection Error. I am running this on spyder.

    def get_bn_price():
    global bn_price
    try:
    bn_price = (kite.ltp(Exch_symbol)).get(Exch_symbol,{}).get('last_price')
    except ReadTimeout:
    pass
    except exceptions.NetworkException:
    pass
    return bn_price

    Here is the result of pip show kiteconnect:

    Name: kiteconnect
    Version: 3.9.4
    Summary: The official Python client for the Kite Connect trading API
    Home-page: https://kite.trade
    Author: Zerodha Technology Pvt ltd. (India)
    Author-email: [email protected]
    License: MIT
    Location: c:\users\rsandanshiv\anaconda3\lib\site-packages
    Requires: autobahn, python-dateutil, pyOpenSSL, enum34, service-identity, pywin32, requests, six
    Required-by:
    Note: you may need to restart the kernel to use updated packages.

    Note --- I have already tried restarting Kernal multiple times but error still occurs
  • rsandanshiv


    Attached code which gives error, also copied below:

    while get_bn_price() >= Stoploss15:
    if int(str(datetime.datetime.now().hour) + str(datetime.datetime.now().minute)) >= squareoff_time:
    pos_df = get_position()
    Place_Exit_orders(OPT_NAME_CE, pos_df[pos_df["tradingsymbol"]==OPT_NAME_CE]["quantity"].values[0], "Exiting all CALL positions, Market Closing : ")
    print("market closing")
    notification("Remaining positions exited as Market Closing, system exit")
    sys.exit()
    else:
    print(OPT_NAME_CE, "Running, LTP :", get_bn_price(), "Target: ", round(First_Target15,1), " STOPLOSS :", Stoploss15)
    pos_df = get_position()
    if get_bn_price() >= First_Target15 and pos_df[pos_df["tradingsymbol"]==OPT_NAME_CE]["quantity"].values[0] == qty:
    pos_df = get_position()
    if pos_df.empty:
    print("No active position")
    elif pos_df[pos_df["tradingsymbol"]==OPT_NAME_CE]["quantity"].values[0] == qty:
    Place_Exit_orders(OPT_NAME_CE, round(qty/2), "50% Target CALL profit booked : ")
    print("50% Target achieved!!")
    notification("50% Target booked")
    else:
    pos_df = get_position()
    if pos_df.empty:
    print("No active position")
    else:
    Place_Exit_orders(OPT_NAME_CE, pos_df[pos_df["tradingsymbol"]==OPT_NAME_CE]["quantity"].values[0], "Exiting all CALL positions : ")
    ltp_tick = get_bn_price()
    print("LTP :", get_bn_price())
    notification("Remaining positions exited as Market Closing, system exit")

  • rakeshr
    pos_df = get_position()
    You should avoid pooling positions with each call. This thread explains more.
  • rsandanshiv
    Thanks Rakeshr, get_position is called only before existing or entering the trade. It is important to avoid unnecessary buy or short selling. Do you think get_position is causing me connection error? I haven't received any error on the same code until a day before.
  • rakeshr
    ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host')
    This means, your code tries to reuse the connection just as the server is closing it because it has been idle for too long or the local session is timed out. You can check if there is any higher value of sleep kept in between or frequent get_position can also cause connection close error.
    I haven't received any error on the same code until a day before.
    We haven't done any changes from our side. Maybe inspect your local connection.
  • rsandanshiv
    Sure, Thanks Rakesh for your response. I will have to recode to minimize the use of get_position. On "forcibly closed" error, once I entered in a trade, I stay in a loop to wait for target or stoploss which might have caused this error during waiting loop. Is there any code to stay active on server/connection ?
    Connection error occurred only on 10 Nov, didnt get that error yesterday and today.
  • rakeshr
    Is there any code to stay active on server/connection ?
    You are in an active session until you log out. You can keep using the same access_token.
  • rsandanshiv
    "your code tries to reuse the connection just as the server is closing it because it has been idle for too long or the local session is timed out" - referring to this, session is getting timed out, is there any way to avoid timeout?
  • rakeshr
    is there any way to avoid timeout?
    These time-outs are mostly because of local network disconnection. You need to maintain an undisruptive internet connection.
  • rsandanshiv
    Thanks Rakesh for your help. Appreciate your timely response and Zerodha for providing best service.
Sign In or Register to comment.