Python client 3.0 is out with WebSocket class for live streams

  • muke5hy
    I am running example code but getting an error.

    ERROR:websocket:error from callback >: _on_close() takes exactly 1 argument (2 given)

  • Vivek
    @muke5hy We have released a patch for Python client - 3.1. Please check it out.
  • muke5hy
    Thanks @vivek tried it still not getting any response in this hour, Will it give any result when running after closing time ?

    Also pip is still on 3.0
  • pybull
    I am having problems with the SSL certificates when I try to use the websocket API. The openssl s_client shows "unable to get local issuer certificate". Am I missing some intermediate certificate files? I have disabled certificate verification for the time being, for my testing, but will need to fix this when I push my code to production. Any workarounds for this?
  • Kailash
    @pybull hm, you shoudn't have to do that. We use a Geotrust cert and the intermediary/root CAs should be in your local trust store.
  • sunnypatel
    can I use WebSocket on my local machine or I have to purchase some web server, if yes can you guide me on this?
  • tonystark
    @sunnypatel, Of course, you can use WebSocket on your local machine. You can follow the example code in the documentation.
  • pybull
    pybull edited February 2018
    Hi @Kailash,

    I have migrated my app to kite connect 3.0. However, I can't seem to get the ticker up, with the new websocket library. The following is the twisted log

    2018-02-10 13:08:51+0530 [-] Starting factory
    2018-02-10 13:08:52+0530 [-] failing WebSocket opening handshake ('WebSocket connection upgrade failed (403 - Forbidden)')
    2018-02-10 13:08:52+0530 [-] dropping connection to peer tcp4:35.154.180.164:443 with abort=True: WebSocket connection upgrade failed (403 - Forbidden)
    2018-02-10 13:08:52+0530 [-] will retry in 6 seconds
    2018-02-10 13:08:52+0530 [-] Stopping factory

    The corresponding log from the kite connect client is

    [2018-02-10 13:08:52,081] {kiteconnect/ticker.py:191} ERROR websocket - Try reconnecting. Retry attempt count: 1
    [2018-02-10 13:08:58,889] {myapp.py} ERROR - Websocket error code: 1006, reason: connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    [2018-02-10 13:08:58,890] {myapp.py} ERROR - Websocket closed code: 1006, reason: connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    [2018-02-10 13:08:58,890] {kiteconnect/ticker.py:188} ERROR pybull.websocket - WebSocket connection lost: [Failure instance: Traceback (failure with no frames): : Connection was aborted locally, using.
    ].

    I had been trying to debug this over the last weekend, but to no avail. The last resort for me would be to switch back to the older websocket client, which used to work fine, but I would love to try the current autobahn websocket, before giving up.

    Any suggestions on what I should be trying to fix this?

    EDIT: Found a discussion on the same in an old thread. Seems like it is an issue with my access token. Will fix that
  • archulysses
    archulysses edited February 2018
    I am just starting with kite connect API's, so which version of python should I work with 2 or 3.
    i.e pykiteconnect is implemented in python 2 or 3?
  • sujith
    sujith edited February 2018
    @pybull,
    You need to send a valid access token to use new websockets API. Make sure your access token is valid.

    @archulysses,
    You need to use Kite Connect 3 (kite3 branch).
    pykiteconnect is compatible with both python 2 and 3.
  • pybull
    @sujith, thanks, I was using the public token from the previous API instead of the changed API.

    On a side note, I get a notification that kite 2.0 will be phased out soon. But the login through my kite connect app, happens through kite 2.0 instead of 3.0. I am already using the kite3 branch. Do I need any additional configuration (I suppose the python client automatically sends a header containing kite 3.0 in the request)? Or will the app continue to authenticate using kite 2.0?
  • sujith
    @pybull,
    There is a new login URL, wherein you need to append query param v=3, now authorization tokens have to be sent in the header and X-Kite-Version has to be sent via header.
    You can check out documentation for more details and cURL example requests
  • sriram73405
    I was not getting the ticks in the event callbacks for the whole day, today. onconnect and close callbacks were working fine but not the onticks callback. Extremely dissatisfied, since we are losing out on time and also money. Please resolve the issue as soon as possible.
  • sujith
    @sriram73405,
    It was a trading holiday yesterday. Hence there were no ticks.
  • SWAPNILMEHTA
    Anyone please guide me how can I code a strategy & use it to trade through Zerodha . I want to do it but I have no idea .
  • sujith
    @SWAPNILMEHTA,
    Please don't hijack threads.
    Kite Connect is purely an execution platform. We don't provide any kind of solution or support for writing strategies.
    You can check out this thread to look at some of the examples written by community members.
  • RajeshSivadasan
    My program runs infinitely and I have to press Ctrl+C to stop. How do I exit the program gracefully after market hours? What happens to the websocket callbacks post market hours?
  • sujith
    You can call unsubscribe and then call close method. You can check out python documentation here.
  • nikhil154
    What is the call rate as per the new websocket ?
  • sujith
    @nikhil154,
    You can open up to 3 websocket connections per app and you can subscribe for up to 3000 instruments with one websocket connection.
  • AutoTrade
    AutoTrade edited May 2019
    Hi Kailash,
    I am facing an issue with python client installation(win7), i installed Anaconda and tried to install kiteconnect("pip install kiteconnect") but i am not successful for all the time when tried. its been throwing the same error(pls see the below error). i have been following all the documentation and this forum posts but not helpful. its frustrating me a lot.

    Please help me out by providing detailed info if you can pls. why i am addressing is, it looks you are prompt in responding to the issues and providing the solutions for the people being an active member in this forum. Thanks

    running build_ext
    building 'twisted.test.raiser' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
    C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
    ERROR: Command "'c:\programdata\anaconda3\python.exe' -u -c 'import setuptools,
    tokenize;__file__='"'"'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-install-qs
    c_7wua\\Twisted\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file_
    _);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(co
    de, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\ADMINI~1\AppData\Loca
    l\Temp\pip-record-ow197umt\install-record.txt' --single-version-externally-manag
    ed --compile" failed with error code 1 in C:\Users\ADMINI~1\AppData\Local\Temp\p
    ip-install-qsc_7wua\Twisted\

    I have intalled Mirosfot Visual C++ 14.0 and build tools too....but no help.
  • rakeshr
    @AutoTrade
    Can you try this thread?
    If still facing issue,can you uninstall kiteconnect completely and try pip install kiteconnect --no-cache? And paste the stacktrace if you are getting any error.
  • AutoTrade
    now, i am not able to uninstall kiteconnect...when i tired 'pip uninstall kiteconnect'. the following is thrown,

    (base) C:\Users\Administrator>pip uninstall kiteconnect
    WARNING: Skipping kiteconnect as it is not installed.
  • AutoTrade
    it looks very tedious process installing kiteconnect, Could you please help me to have a smoth install ....your prompt help would be greatly appreciated
  • rakeshr
    @AutoTrade
    Was asking about the error thrown post pip install kiteconnect --no-cache? Can you do this and post error traceback if any.
  • sovan_nit
    I have installed Twisted from the below
    https://github.com/zerodhatech/python-wheels/blob/master/Twisted-18.7.0-cp27-cp27m-win_amd64.whl

    Then installed kiteconnect

    But when i m trying to use Kiteticker via websocket im getting below error.
    Any clue what is wrong here?

    Python\Python37\site-packages\twisted\internet\_win32stdio.py", line 9, in
    import win32api
    ImportError: DLL load failed: The specified module could not be found.
  • sujith
    You seem to have python 3.7 and installed python 2.7 twisted library.
  • sovan_nit
    that was a typo , i installed Twisted-18.7.0-cp37-cp37m-win_amd64.whl this which is for python 3.7. and this is giving me the above error.
  • harshtock
    harshtock edited November 2019
    @sujith
    i have tried to run the example code on my machine which has python 3.7 but getting errors.. kindly advise

    ————————————————————————————————
    ————————————————————————————————
    ——— TRY TO PIP INSTALL KITECONNECT HERE—————-———-
    ————————————————————————————————
    ————————————————————————————————


    Building wheel for kiteconnect (setup.py) ... done
    WARNING: Legacy build of wheel for 'kiteconnect' created no files.
    Command arguments: /usr/local/opt/python/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/fy/nxdh_z0d2mn805sjv4016ck40000gn/T/pip-install-zdf3bpg1/kiteconnect/setup.py'"'"'; __file__='"'"'/private/var/folders/fy/nxdh_z0d2mn805sjv4016ck40000gn/T/pip-install-zdf3bpg1/kiteconnect/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/fy/nxdh_z0d2mn805sjv4016ck40000gn/T/pip-wheel-ledu_tsk --python-tag cp37
    Command output: [use --verbose to show]
    Running setup.py clean for kiteconnect
    Building wheel for Twisted (setup.py) ... done
    Created wheel for Twisted: filename=Twisted-19.10.0-cp37-cp37m-macosx_10_14_x86_64.whl size=3043199 sha256=376fedcae15c7066cfe922525a47654c38c1c120a1299f006de32c2e905e3cad
    Stored in directory: /Users/homedir/Library/Caches/pip/wheels/59/31/54/d03a61017b6f2c09942b09c20035007bb64c6f69c9e6be4a6e
    Building wheel for pycparser (setup.py) ... done
    Created wheel for pycparser: filename=pycparser-2.19-py2.py3-none-any.whl size=111029 sha256=0cb89b0a1a5234933f1452059513f9cf46231373d1859e222935e37a4c927f62
    Stored in directory: /Users/homedir/Library/Caches/pip/wheels/f2/9a/90/de94f8556265ddc9d9c8b271b0f63e57b26fb1d67a45564511
    Successfully built Twisted pycparser
    Failed to build kiteconnect
    Installing collected packages: certifi, chardet, urllib3, idna, requests, pycparser, cffi, cryptography, pyOpenSSL, enum34, python-dateutil, txaio, zope.interface, constantly, incremental, attrs, Automat, hyperlink, PyHamcrest, Twisted, autobahn, kiteconnect
    Running setup.py install for kiteconnect ... done
    WARNING: Could not find .egg-info directory in install record for kiteconnect from https://files.pythonhosted.org/packages/d6/d7/e6d25d77ea89d6f8c039c44facbd7c913a5b6ee651e46438a23a3f1940c5/kiteconnect-3.7.7.tar.gz#sha256=27836367e7bb0d30ad08dd7b9f05e9d4ca872d5bc0600aeed6f08ef166a5aa4b
    Successfully installed Automat-0.8.0 PyHamcrest-1.9.0 Twisted-19.10.0 attrs-19.3.0 autobahn-19.11.1 certifi-2019.9.11 cffi-1.13.2 chardet-3.0.4 constantly-15.1.0 cryptography-2.8 enum34-1.1.6 hyperlink-19.0.0 idna-2.8 incremental-17.5.0 kiteconnect pyOpenSSL-19.0.0 pycparser-2.19 python-dateutil-2.8.1 requests-2.22.0 txaio-18.8.1 urllib3-1.25.7 zope.interface-4.7.1


    ————————————————————————————————
    ————————————————————————————————
    ——— HERE I TRY RUNNING THE EXAMPLE CODE simple.py———-
    ————————————————————————————————
    ————————————————————————————————

    mycomp:py homedir$ /usr/local/opt/python/bin/python3.7 /Users/homedir/Documents/TNE/CODE/Lab/py/tryOrder.py
    :0: UserWarning: You do not have a working installation of the service_identity module: 'No module named 'service_identity''. Please install it from and make sure all of its dependencies are satisfied. Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification. Many valid certificate/hostname mappings may be rejected.
    Traceback (most recent call last):
    File "/Users/homedir/Documents/TNE/CODE/Lab/py/tryOrder.py", line 3, in
    from kiteconnect import kiteconnect
    ImportError: cannot import name 'kiteconnect' from 'kiteconnect' (/usr/local/lib/python3.7/site-packages/kiteconnect-3.7.7-py3.7.egg/kiteconnect/__init__.py)
  • hemangjoshi37a
    ???? hjAlgos ????
    AlgoTrading using python notebook and excel using Zerodha's kite connect API
    https://github.com/hemangjoshi37a/hjAlgos
  • Kamalv
    Kamalv edited December 2021
    I am trying to get and save LTP in AWS with Python. But facing challenges while importing kiteconnect package ( https://kite.trade/forum/discussion/10788/import-kiteconnect-in-aws-lambda#latest ). as a result not able to use Websockets.

    Any way i can implement Websockets without Python package and get LTP (like curl commands) or any other way (LTP API call may be final option but looking for best solution).
  • sanjayatzerodha
    Using Google colab and running python. Following WORKS and I get results so I assume api_key and access token are set correctly.
    instrument_dump = kite.instruments("NFO")

    I get error (TokenException: Incorrect `api_key` or `access_token`.) When I run
    kite.quote(['NSE:INFY'])

    What could possibly go wrong? Any suggestions? thanks
  • SRIJAN
    No,your access token is incorrect. The instruments dump can be fetched with just the api_key.
  • Naveensingh
    ImportError: cannot import name 'KiteConnect' from partially initialized module 'kiteconnect' (most likely due to a circular import) (C:\Users\admin\PycharmProjects\pythonProject\venv\lib\site-packages\kiteconnect\__init__.py)

    why is this error create. when i have installed kiteconnect inside my python then just import then it is given error
  • Naveensingh
    please help me quickely
  • SRIJAN
    SRIJAN edited April 2022
    .
  • rakeshr
    most likely due to a circular import
    You need to change file_name and it's shouldn't be the same name as the package i.e kiteconnect here.
  • SRIJAN
    Thanks for the solution @rakeshr Sir.
  • Naveensingh
    ImportError: cannot import name 'KiteConnect' from partially initialized module 'kiteconnect' (most likely due to a circular import) (C:\Users\admin\PycharmProjects\pythonProject\venv\lib\site-packages\kiteconnect\__init__.py)

    why is this error create. when i have installed kiteconnect inside my python then just import then it is given error
  • SRIJAN
    @Naveensingh ,
    Rakesh Sir has already given the solution. The name of your file would be kiteconnect.py and then you are trying to import from the kiteconnect module . That's why it's showing error. Change your file name and it will work fine.
  • seenuchennai
    hi
    " My program runs infinitely and I have to press Ctrl+C to stop. How do I exit the program gracefully after market hours? What happens to the WebSocket callbacks post-market hours? "
    I am also facing this issue aftermarket also running the last ticks how to stop the market close how to fix it anyone please help me
  • rakeshr
    How do I exit the program gracefully after market hours?
    Go through this thread.
    What happens to the WebSocket callbacks post-market hours?
    It remains active until disconnected from the user end.
  • seenuchennai
    I am testing now yesterday's last traded
    market value shows

    I attached the code also anyone please help I need to start at 9:15 am and stop at 3:30 please fix it

    ##from kiteconnect import KiteConnect
    import time
    from kiteconnect import KiteTicker
    import sys
    import pandas as pd


    api_key=open('api_key.txt','r').read().strip()
    access_token=open('access_token.txt','r').read().strip()


    kws = KiteTicker(api_key,access_token)
    print(kws)

    instruments=pd.read_csv('tokens.csv',names=['instrument_token','tradingsymbol'])
    tokens=[i for i in instruments['instrument_token']]
    tokens= list(map(int, tokens))

    dict={}

    symbol=pd.read_csv('tokens.csv',names=['instrument_token','tradingsymbol'])
    for x,y in zip(symbol['instrument_token'],symbol['tradingsymbol']):
    dict.update({x:y})

    #tokens=[60292359,59549447,59658503,]
    #dict={60292359:'CRUDEOIL22JULFUT',59549447 : 'GOLD22AUGFUT',59658503 : 'SILVER22SEPFUT',}

    def on_ticks(ws, ticks):

    print(dict[ticks[0]['instrument_token']],ticks[0]['depth']['buy'][0]['price'],ticks[0]['depth']['sell'][0]['price'],ticks[0]['last_price'],ticks[0]['last_traded_quantity'],ticks[0]['last_trade_time'])

    # print(ticks[0]['instrument_token'],ticks[0]['depth']['buy'][0]['price'],ticks[0]['depth']['sell'][0]['price'],ticks[0]['last_price'],ticks[0]['last_traded_quantity'],ticks[0]['exchange_timestamp'],)
    ## sys.exit()

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


    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    #kws.connect(threaded=False)
    kws.connect(threaded=True)
    count=0
    while True:

    # count+=1
    # if(count%2==0):

    if kws.is_connected():
    kws.set_mode(kws.MODE_FULL,tokens)
    else:
    if kws.is_connected():
    kws.set_mode(kws.MODE_FULL,tokens)
    time.sleep(0.350)

  • kishanninja
    while datetime.time(9, 20) < datetime.datetime.now().time() < datetime.time(15, 15):
    # Call on_ticks() inside here...........
Sign In or Register to comment.