Running code into Google cloude VM

saurabh123

class ZerodhakiteConn(threading.Thread):

def __init__(self):
threading.Thread.__init__(self)

def run(self):


kite, access_token = zerodha_connect() # this is my code it is run perfectly fine in local

# Initialise kite object
kws = KiteTicker(os.environ.get('api_key'), access_token)
logging.debug(f"kws obj. - {kws}")
#getting trading instrument for which we need to generate candle
trd_portfolio = trade_portfolio()
logging.debug(f"for {len(trd_portfolio)} instruments we are creating candle!")


def on_ticks(ws, ticks):
# Callback to receive ticks.
logging.info(f"tickers data - {ticks}")

def on_connect(ws, response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
ws.subscribe(ids_of_instrument)

# Set RELIANCE to tick in `full` mode.
ws.set_mode(ws.MODE_QUOTE, ids_of_instrument)

def on_close(ws, code, reason):
# On connection close stop the event loop.
# Reconnection will not happen after executing `ws.stop()`
ws.stop()

# Assign the callbacks.
logging.info(" calling on ticker...")
kws.on_ticks = on_ticks
logging.info(" calling on_connect...")
kws.on_connect = on_connect
logging.info(" calling on_close...")
kws.on_close = on_close

# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
logging.info(" kws connect done...")
kws.connect(threaded=True)

while True:





--- I have this code. which is perfectly working in local but as soon as i deployed it into google cloude VM instance it failed and give me error like this.

INFO:root: calling on ticker...
INFO:root: calling on_connect...
INFO:root: calling on_close...
INFO:root: kws connect done...
[27/Mar/2023 12:24:04] "GET /api/strategy/daily-candle-create-start/ HTTP/1.1" 200 5541
ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))
ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))


any solution ?
  • rakeshr
    WebSocket connection upgrade failed (400 - BadRequest)
    Go through the python websocket FAQs here.
  • saurabh123
    my issue didn't resolve yet.

    my code is something like this...
    ---------------

    import logging
    from kiteconnect import KiteTicker, KiteConnect
    logging.basicConfig(level=logging.DEBUG)

    kite = KiteConnect(api_key="###my_api_key") #api key , access token and secret key is in string..!!
    data = kite.generate_session("###my_daily_request_token_here", api_secret="###my_secret_key")
    access_token = data['access_token']
    kite.set_access_token(access_token)

    # Initialise kite object
    kws = KiteTicker("###my_api_key", access_token)
    trd_portfolio = [738561 , 5633] #data in int list..


    def on_ticks(ws, ticks):
    # Callback to receive ticks.
    logging.info(f"tickers data - {ticks}")

    def on_connect(ws, response):
    # Callback on successful connect.
    # Subscribe to a list of instrument_tokens (RELIANCE and ACC here).

    logging.info(f"tickers data - {trd_portfolio}")
    ws.subscribe(trd_portfolio)

    ws.set_mode(ws.MODE_QUOTE, trd_portfolio)

    def on_close(ws, code, reason):
    # On connection close stop the event loop.
    # Reconnection will not happen after executing `ws.stop()`
    logging.info(f"adding code- {code}")
    logging.info(f"adding reason- {reason}")
    ws.stop()

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

    # Infinite loop on the main thread. Nothing after this will run.
    # You have to use the pre-defined callbacks to manage subscriptions.
    kws.connect(threaded=True)

    while True:
    ''' my logic runs here'''


    -----------------
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

    still i'm getting this error. this code works perfectly fine in my local machine. but when i run it in google cloude vm it is giving me this error.

    web socket anything to do with SSL certificate ?
    or anything related to cloude deployment ?


  • sujith
    It looks like an input exception.
  • sujith
    Check if you are sending correct api_key and access token
  • tahseen
    @saurabh123

    This is clearly a case of access_token issue.
    Because of access_token issue, the application fails and as the thread with web socket is also killed, what you see is the unclean websocket disconnection error

    The diverts the attention of developers towards web socket but the issue is related to no / incorrect access_token passed to the code. So sort that out. Check if you application has access_token by logging / printing to visually confirm it
  • saurabh123
    saurabh123 edited March 2023

    still i'm getting this error. this code works perfectly fine in my local machine. but when i run it in google cloude vm it is giving me this error.


    i have check access token and api key are in string and access token and api key are valid in my local machine. ( i'm able to place order with same in local machine)

    @sujith @tahseen

  • tahseen
    @saurabh123 then it further confirms that this is not Kite API issue and probably something to do with Google. Maybe Google Firewall is closing / dropping the web socket connects
  • saurabh123
    @tahseen can you tell me which port i should allow ?
    and it has anything to do with SSL certificate. ?
  • tahseen
    80 and 443 the very least to be open. Then close 80 as that in my option is not required. Only 443 port
  • saurabh123
    my vm's apache tomcat running on 443 port. so i tried to stop that port and run my application but it woudn't work. so is there any way to change zerodha socket port?
  • tahseen
    Service port and outgoing client requests are different thing. You don't have to stop Apache

    Web Socket protocol is ws, check if Google has blocked socket protocol
  • saurabh123
    saurabh123 edited March 2023
    @tahseen @sujith
    issue is resolved. !

    thanks for help. issue was we are fetching api_key from environment but it was okay in local but in devlopment environment file it was wrong.
    thanks for help! :)
  • tahseen
    @saurabh123 I wrote it on 28th March as the first thing but you countered my point stating you are fetching it all correctly

    Most of the developers make this mistake thinking there is a web socket issue just because they see the "connection was closed uncleanly" error

    But they failed to realize that their code threw error and broke the program and also the web socket connection. Just because they see web socket error, they end up thinking it is web socket error whereas the actually issue is always developers' own code
  • saurabh123
    you are correct.
Sign In or Register to comment.