The official Python client library for the Kite Connect trading APIs

Overview

The Kite Connect API Python client - v3

PyPI Build Status Windows Build Status codecov.io

The official Python client for communicating with the Kite Connect API.

Kite Connect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection.

Zerodha Technology (c) 2018. Licensed under the MIT License.

Documentation

Installing the client

You can install the pre release via pip

pip install --upgrade kiteconnect

Its recommended to update setuptools to latest if you are facing any issue while installing

pip install -U pip setuptools

Since some of the dependencies uses C extensions it has to compiled before installing the package.

Linux, BSD and macOS

  • On Linux, and BSDs, you will need a C compiler (such as GCC).

Debian/Ubuntu

apt-get install libffi-dev python-dev python3-dev

Centos/RHEL/Fedora

yum install libffi-devel python3-devel python-devel

macOS/OSx

xcode-select --install

Microsoft Windows

Each Python version uses a specific compiler version (e.g. CPython 2.7 uses Visual C++ 9.0, CPython 3.3 uses Visual C++ 10.0, etc). So, you need to install the compiler version that corresponds to your Python version

For more details check official Python documentation.

API usage

import logging
from kiteconnect import KiteConnect

logging.basicConfig(level=logging.DEBUG)

kite = KiteConnect(api_key="your_api_key")

# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.

data = kite.generate_session("request_token_here", api_secret="your_secret")
kite.set_access_token(data["access_token"])

# Place an order
try:
    order_id = kite.place_order(tradingsymbol="INFY",
                                exchange=kite.EXCHANGE_NSE,
                                transaction_type=kite.TRANSACTION_TYPE_BUY,
                                quantity=1,
                                order_type=kite.ORDER_TYPE_MARKET,
                                product=kite.PRODUCT_NRML)

    logging.info("Order placed. ID is: {}".format(order_id))
except Exception as e:
    logging.info("Order placement failed: {}".format(e.message))

# Fetch all orders
kite.orders()

# Get instruments
kite.instruments()

# Place an mutual fund order
kite.place_mf_order(
    tradingsymbol="INF090I01239",
    transaction_type=kite.TRANSACTION_TYPE_BUY,
    amount=5000,
    tag="mytag"
)

# Cancel a mutual fund order
kite.cancel_mf_order(order_id="order_id")

# Get mutual fund instruments
kite.mf_instruments()

Refer to the Python client documentation for the complete list of supported methods.

WebSocket usage

import logging
from kiteconnect import KiteTicker

logging.basicConfig(level=logging.DEBUG)

# Initialise
kws = KiteTicker("your_api_key", "your_access_token")

def on_ticks(ws, ticks):
    # Callback to receive ticks.
    logging.debug("Ticks: {}".format(ticks))

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

    # Set RELIANCE to tick in `full` mode.
    ws.set_mode(ws.MODE_FULL, [738561])

def on_close(ws, code, reason):
    # On connection close stop the main loop
    # Reconnection will not happen after executing `ws.stop()`
    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()

Run unit tests

python setup.py test

or

pytest -s tests/unit --cov-report html:cov_html --cov=./

Run integration tests

pytest -s tests/integration/ --cov-report html:cov_html --cov=./  --api-key api_key --access-token access_token

Generate documentation

pip install pdoc

pdoc --html --html-dir docs kiteconnect

Changelog

Check CHANGELOG.md

Comments
  • connecting position with order_id/tag

    connecting position with order_id/tag

    Is there anyway for me to link order_id/ or tag passed during placing the order with the position. So lets say I place a sell order for Nifty 17000 PE from one strategy and then another order for the same security through another strategy, I would like to track the two positions independently and right now the only way to do so is through maintaining an extensive log of the traded price, current price, etc for each of the orders in each of the strategy. The problem with the logging system is that it doesn't allow a manual intervention or modification of some position (from outside the algo) which then throws the entire tracking & logging at the algo level into a tizzy.

    opened by akshaythakker 9
  • feat: change data structure for subscribed_tokens

    feat: change data structure for subscribed_tokens

    Have made subscribed_tokens as a list instead of the dict, so users can un-subscribe the list of current tokens in a single go using ws.unsubscribe(ws.subscribe_tokens). Have removed redundant code around subscribed_tokens. This is in response to this raised issue.

    opened by ranjanrak 6
  • Every two minute i got this error - Connection error: 1006 - connection was closed uncleanly (None)

    Every two minute i got this error - Connection error: 1006 - connection was closed uncleanly (None)

    I read previous discussions about this error but am not resolve this issue am also not using any computation inside on_ticks(). kindly help me

    susbcription_list = [int(x) for x in trd_portfolio]
    def getticks(ticks):
    for tick in ticks:
    ticks_token = tick['instrument_token']
    push_tick_values_to_trd_portfolio(tick, ticks_token)
    
    push_value_to_excel()
    def on_ticks(ws, ticks):
    # Todo: "On_ticks"
    getticks(ticks)
    
    def on_connect(ws, response):
    ws.subscribe(susbcription_list)
    ws.set_mode(ws.MODE_FULL, susbcription_list)
    
    
    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    
    
    kws.connect(threaded=True)
    
    count = 0
    while True:
    count += 1
    if count % 2 == 0:
    if kws.is_connected():
    kws.set_mode(kws.MODE_FULL, susbcription_list)
    else:
    if kws.is_connected():
    kws.set_mode(kws.MODE_FULL, susbcription_list)
    
    time.sleep(5)
    

    image

    opened by karthickbala123 5
  • How get tick data again

    How get tick data again

    In my code first i get current ltp of subscribed stock then i place buy order when my strategy applied, then i need tick data again for check current ltp for placing sell order. but when i call on_ticks(ws, ticks) function am getting below error. so kindly help me how get current ltp from outside of on_tick function.

    on_ticks(ws, ticks) builtins.NameError: name 'ws' is not defined

    opened by karthickbala123 5
  • ImportError: cannot import name 'KiteConnect'

    ImportError: cannot import name 'KiteConnect'

    Hi,

    I recently purchased Kiteconnect API and trying to install kiteconnect in python. I am getting the following error -

    ImportError: cannot import name 'KiteConnect'

    Here is what I did -

    1. First command pip install --upgrade kiteconnect - successfully installed
    2. Second command python.exe -m pip install -U pip setuptools - successfully updated
    3. Third command pip show kiteconnect and here is the output I got -

    Name: kiteconnect Version: 3.8.1 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\user.conda\envs\tensorflowgpu1\lib\site-packages\kiteconnect-3.8.1-py3.6.egg Requires: requests, six, pyOpenSSL, enum34, python-dateutil, autobahn, pywin32 Required-by:

    Please help.

    Thanks

    opened by rajeshdua123 5
  • option chain volume for live data

    option chain volume for live data

    hi, i enrolled for kite connect api. when i write a code for live option chain feed. i'm not getting volume in my excel. but i'm getting remaining all oi, last price, change but why i'm not getting volume data. could you please help me through this issue. here i'm attaching the volume code.

    def stream(dict):

    oi = dict.get('oi')
    ltp = dict.get('last_price')
    change = dict.get('change')
    vol = dict.get('volume')
    inst_token = dict.get('instrument_token')
    strike = strike_list[inst_token]
    row = row_list[strike]
    

    in this code i'm getting all data except volume. if i run a code on a particular strike there i'm getting volume. but here i'm not getting it...

    opened by Lakshmi9787 4
  • While placing basket Order margin request,Input exception error was shown

    While placing basket Order margin request,Input exception error was shown

    Data Provided json_data = [ { 'exchange': 'NFO', 'tradingsymbol': 'NIFTY22DEC18800CE', 'transaction_type': 'BUY', 'variety': 'regular', 'product': 'NRML', 'order_type': 'LIMIT', 'quantity': 50, 'price': 0.05, 'trigger_price': 0, 'squareoff': 0, 'stoploss': 0, }, { 'exchange': 'NFO', 'tradingsymbol': 'NIFTY22DEC18400CE', 'transaction_type': 'SELL', 'variety': 'regular', 'product': 'NRML', 'order_type': 'LIMIT', 'quantity': 50, 'price': 298, 'trigger_price': 0, 'squareoff': 0, 'stoploss': 0, }, ]

    Exception:

    {'status': 'error', 'message': 'invalid json', 'data': {}, 'error_type': 'InputException'}

    opened by arul67800 3
  • Error with token generation

    Error with token generation

    My script used to work perfectly well till Nov 5. From today showing the error.

    line 21, in kite_trade
    self.kite_loginer.update_access_token()
    line 39, in update_access_token
    request_token = self._get_request_token()
    line 65, in _get_request_token
    return json.loads(resp.text)['token']
    KeyError: 'token'
    
    opened by augmen 3
  • How to get historical data of indices?

    How to get historical data of indices?

    Dear sir,

    There is absolute no documentation on how to read indices like NIFTY from historical_data() function or by any other way.

    Please help me. Thank you in advance sir.

    bug 
    opened by hemangjoshi37a 3
  • Unable to install on python 3.7

    Unable to install on python 3.7

    I am getting the following error:

    λ pip install kiteconnect
    Collecting kiteconnect
      Using cached https://files.pythonhosted.org/packages/5a/dc/482cb13486946889b6a26abeb4036f5b8af19978251cc61f0ee45de4d833/kiteconnect-3.7.6.tar.gz
        Complete output from command python setup.py egg_info:
        Download error on https://pypi.org/simple/pytest-runner/: [WinError 10054] An existing connection was forcibly closed by the remote host -- Some packages may not be found!
        Couldn't find index page for 'pytest-runner' (maybe misspelled?)
        No local packages or working download links found for pytest-runner
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "C:\Users\Shrey\AppData\Local\Temp\pip-install-2mx7jwys\kiteconnect\setup.py", line 126, in <module>
            cmdclass={"install": install, "bdist_wheel": FakeBdist}
          File "d:\current_work\macd-auto\venv\lib\site-packages\setuptools\__init__.py", line 142, in setup
            _install_setup_requires(attrs)
          File "d:\current_work\macd-auto\venv\lib\site-packages\setuptools\__init__.py", line 137, in _install_setup_requires
            dist.fetch_build_eggs(dist.setup_requires)
          File "d:\current_work\macd-auto\venv\lib\site-packages\setuptools\dist.py", line 586, in fetch_build_eggs
            replace_conflicting=True,
          File "d:\current_work\macd-auto\venv\lib\site-packages\pkg_resources\__init__.py", line 780, in resolve
            replace_conflicting=replace_conflicting
          File "d:\current_work\macd-auto\venv\lib\site-packages\pkg_resources\__init__.py", line 1063, in best_match
            return self.obtain(req, installer)
          File "d:\current_work\macd-auto\venv\lib\site-packages\pkg_resources\__init__.py", line 1075, in obtain
            return installer(requirement)
          File "d:\current_work\macd-auto\venv\lib\site-packages\setuptools\dist.py", line 653, in fetch_build_egg
            return cmd.easy_install(req)
          File "d:\current_work\macd-auto\venv\lib\site-packages\setuptools\command\easy_install.py", line 673, in easy_install
            raise DistutilsError(msg)
        distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('pytest-runner')
    
        ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in C:\Users\Shrey\AppData\Local\Temp\pip-install-2mx7jwys\kiteconnect\
    

    This error looks similar to pytest-dev/pytest-runner #41.

    When I separately install pytest-runner first and then install kiteconnect I am facing the following issue:

    Collecting zope.interface>=3.6.0; extra == "twisted" (from autobahn[twisted]>=17.10.1->kiteconnect->-r requirements.txt (line 4))                                                       
      Downloading https://files.pythonhosted.org/packages/da/08/726e3b0e3bd9912fb530f9864bf9a3af9f9f6a1dfd4cc7854ca14fdab441/zope.interface-4.6.0-cp36-cp36m-win_amd64.whl (133kB)          
        100% |████████████████████████████████| 143kB 212kB/s                                                                                                                               
    Collecting Twisted>=12.1.0; extra == "twisted" (from autobahn[twisted]>=17.10.1->kiteconnect->-r requirements.txt (line 4))                                                             
      Downloading https://files.pythonhosted.org/packages/5d/0e/a72d85a55761c2c3ff1cb968143a2fd5f360220779ed90e0fadf4106d4f2/Twisted-18.9.0.tar.bz2 (3.1MB)                                 
        100% |████████████████████████████████| 3.1MB 180kB/s                                                                                                                               
        Complete output from command python setup.py egg_info:                                                                                                                              
        Download error on https://pypi.org/simple/incremental/: [WinError 10054] An existing connection was forcibly closed by the remote host -- Some packages may not be found!           
        Couldn't find index page for 'incremental' (maybe misspelled?)                                                                                                                      
        Download error on https://pypi.org/simple/: [WinError 10054] An existing connection was forcibly closed by the remote host -- Some packages may not be found!                       
        No local packages or working download links found for incremental>=16.10.1                                                                                                          
        Traceback (most recent call last):                                                                                                                                                  
          File "<string>", line 1, in <module>                                                                                                                                              
          File "C:\Users\Shrey\AppData\Local\Temp\pip-install-xtwuif77\Twisted\setup.py", line 20, in <module>                                                                              
            setuptools.setup(**_setup["getSetupArgs"]())                                                                                                                                    
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\setuptools\__init__.py", line 144, in setup                                                                           
            _install_setup_requires(attrs)                                                                                                                                                  
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\setuptools\__init__.py", line 139, in _install_setup_requires                                                         
            dist.fetch_build_eggs(dist.setup_requires)                                                                                                                                      
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\setuptools\dist.py", line 724, in fetch_build_eggs                                                                    
            replace_conflicting=True,                                                                                                                                                       
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\pkg_resources\__init__.py", line 782, in resolve                                                                      
            replace_conflicting=replace_conflicting                                                                                                                                         
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\pkg_resources\__init__.py", line 1065, in best_match                                                                  
            return self.obtain(req, installer)                                                                                                                                              
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\pkg_resources\__init__.py", line 1077, in obtain                                                                      
            return installer(requirement)                                                                                                                                                   
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\setuptools\dist.py", line 791, in fetch_build_egg                                                                     
            return cmd.easy_install(req)                                                                                                                                                    
          File "d:\current_work\macd-auto\macd-auto\lib\site-packages\setuptools\command\easy_install.py", line 673, in easy_install                                                        
            raise DistutilsError(msg)                                                                                                                                                       
        distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('incremental>=16.10.1')                                                                 
                                                                                                                                                                                            
        ----------------------------------------                                                                                                                                            
    Command "python setup.py egg_info" failed with error code 1 in C:\Users\Shrey\AppData\Local\Temp\pip-install-xtwuif77\Twisted\                                                          
    
    opened by sdabhi23 3
  • Cant install Kiteconnect in python 2.7.

    Cant install Kiteconnect in python 2.7.

    sudo pip install --upgrade kiteconnect Password: The directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has beendisabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/User/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has beendisabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting kiteconnect Downloading https://files.pythonhosted.org/packages/5a/dc/482cb13486946889b6a26abeb4036f5b8af19978251cc61f0ee45de4d833/kiteconnect-3.7.6.tar.gz Requirement already satisfied, skipping upgrade: requests>=2.18.4 in /Users/User/Library/Python/2.7/lib/python/site-packages (from kiteconnect) (2.20.1) Requirement already satisfied, skipping upgrade: six>=1.11.0 in /Library/Python/2.7/site-packages (from kiteconnect) (1.11.0) Requirement already satisfied, skipping upgrade: pyOpenSSL>=17.5.0 in /Users/User/Library/Python/2.7/lib/python/site-packages (fromkiteconnect) (18.0.0) Requirement already satisfied, skipping upgrade: enum34>=1.1.6 in /Library/Python/2.7/site-packages (from kiteconnect) (1.1.6) Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in /Library/Python/2.7/site-packages (from kiteconnect) (2.7.0) Requirement already satisfied, skipping upgrade: autobahn[twisted]>=17.10.1 in /Users/User/Library/Python/2.7/lib/python/site-packages (from kiteconnect) (18.9.2) Requirement already satisfied, skipping upgrade: idna<2.8,>=2.5 in /Users/User/Library/Python/2.7/lib/python/site-packages (from requests>=2.18.4->kiteconnect) (2.7) Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /Library/Python/2.7/site-packages (from requests>=2.18.4->kiteconnect) (1.22) Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /Library/Python/2.7/site-packages (from requests>=2.18.4->kiteconnect) (2018.8.24) Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /Users/User/Library/Python/2.7/lib/python/site-packages (from requests>=2.18.4->kiteconnect) (3.0.4) Requirement already satisfied, skipping upgrade: cryptography>=2.2.1 in /Users/User/Library/Python/2.7/lib/python/site-packages (from pyOpenSSL>=17.5.0->kiteconnect) (2.3.1) Requirement already satisfied, skipping upgrade: txaio>=18.8.1 in /Users/User/Library/Python/2.7/lib/python/site-packages (from autobahn[twisted]>=17.10.1->kiteconnect) (18.8.1) Requirement already satisfied, skipping upgrade: zope.interface>=3.6.0; extra == "twisted" in /Users/User/Library/Python/2.7/lib/python/site-packages (from autobahn[twisted]>=17.10.1->kiteconnect) (4.5.0) Requirement already satisfied, skipping upgrade: Twisted>=12.1.0; extra == "twisted" in /Users/User/Library/Python/2.7/lib/python/site-packages (from autobahn[twisted]>=17.10.1->kiteconnect) (18.7.0) Requirement already satisfied, skipping upgrade: cffi!=1.11.3,>=1.7 in /Users/User/Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL>=17.5.0->kiteconnect) (1.11.5) Requirement already satisfied, skipping upgrade: asn1crypto>=0.21.0 in /Users/User/Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL>=17.5.0->kiteconnect) (0.24.0) Requirement already satisfied, skipping upgrade: ipaddress; python_version < "3" in /Users/User/Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL>=17.5.0->kiteconnect) (1.0.22) Requirement already satisfied, skipping upgrade: setuptools in /Library/Python/2.7/site-packages (from zope.interface>=3.6.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (38.5.2) Requirement already satisfied, skipping upgrade: constantly>=15.1 in /Users/User/Library/Python/2.7/lib/python/site-packages (from Twisted>=12.1.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (15.1.0) Requirement already satisfied, skipping upgrade: incremental>=16.10.1 in /Users/User/Library/Python/2.7/lib/python/site-packages (from Twisted>=12.1.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (17.5.0) Requirement already satisfied, skipping upgrade: Automat>=0.3.0 in /Users/User/Library/Python/2.7/lib/python/site-packages (from Twisted>=12.1.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (0.7.0) Requirement already satisfied, skipping upgrade: hyperlink>=17.1.1 in /Users/User/Library/Python/2.7/lib/python/site-packages (fromTwisted>=12.1.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (18.0.0) Requirement already satisfied, skipping upgrade: PyHamcrest>=1.9.0 in /Users/User/Library/Python/2.7/lib/python/site-packages (fromTwisted>=12.1.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (1.9.0) Requirement already satisfied, skipping upgrade: attrs>=17.4.0 in /Users/User/Library/Python/2.7/lib/python/site-packages (from Twisted>=12.1.0; extra == "twisted"->autobahn[twisted]>=17.10.1->kiteconnect) (18.2.0) Requirement already satisfied, skipping upgrade: pycparser in /Users/User/Library/Python/2.7/lib/python/site-packages (from cffi!=1.11.3,>=1.7->cryptography>=2.2.1->pyOpenSSL>=17.5.0->kiteconnect) (2.19) Installing collected packages: kiteconnect Found existing installation: kiteconnect 3.7.4 Uninstalling kiteconnect-3.7.4: Successfully uninstalled kiteconnect-3.7.4 Running setup.py install for kiteconnect ... done Could not find .egg-info directory in install record for kiteconnect from https://files.pythonhosted.org/packages/5a/dc/482cb13486946889b6a26abeb4036f5b8af19978251cc61f0ee45de4d833/kiteconnect-3.7.6.tar.gz#sha256=fdd55316bd66a6772e6ec71cea1ace2aa779b31b4e8ae5edff83c017aa94bb81 in /Users/User/Library/Python/2.7/lib/python/site-packages/kiteconnect-3.7.4-py2.7.egg Successfully installed kiteconnect Traceback (most recent call last): File "/usr/local/bin/pip", line 11, in sys.exit(main()) File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_internal/init.py", line 78, in main return command.main(cmd_args) File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_internal/cli/base_command.py", line 184, in main timeout=min(5, options.timeout) File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_internal/cli/base_command.py", line 79, in _build_session insecure_hosts=options.trusted_hosts, File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_internal/download.py", line 337, in init self.headers["User-Agent"] = user_agent() File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_internal/download.py", line 126, in user_agent setuptools_version = get_installed_version("setuptools") File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_internal/utils/misc.py", line 836, in get_installed_version working_set = pkg_resources.WorkingSet() File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 562, in init self.add_entry(entry) File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 618, in add_entry for dist in find_distributions(entry, True): File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 1883, in find_eggs_in_zip if metadata.has_metadata('PKG-INFO'): File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 1402, in has_metadata return self.egg_info and self._has(self._fn(self.egg_info, name)) File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 1757, in _has return zip_path in self.zipinfo or zip_path in self._index() File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 1634, in zipinfo return self._zip_manifests.load(self.loader.archive) File "/Users/User/Library/Python/2.7/lib/python/site-packages/pip/_vendor/pkg_resources/init.py", line 1591, in load mtime = os.stat(path).st_mtime OSError: [Errno 2] No such file or directory: '/Users/User/Library/Python/2.7/lib/python/site-packages/kiteconnect-3.7.4-py2.7.egg'

    opened by muthuselvamlms 3
  • minor documentation sync up issues

    minor documentation sync up issues

    1. Python Client documentation (https://kite.trade/docs/pykiteconnect/v4): a. When trying to look at Python client documentation, it seems the documentation was not updated for some new parameters in v4 e.g. place_order() accepts validity_ttl, iceberg_legs, iceberg_quantity as additional parameters, but these do not show up in the python client documentation page (though it's updated in http api documentation): https://kite.trade/docs/pykiteconnect/v4/#kiteconnect.KiteConnect.place_order . May be the python client documentation is not updated for v4.

    2. Kite Connect HTTP API documentation(https://kite.trade/docs/connect/v3): a. The http api documentation, while updated for v4, seems to have older version breadcrumb (Kite Connect 3 / API documentation) & the path also has v3 in it: https://kite.trade/docs/connect/v3/orders/#placing-orders

    b. Some parameters are not seen in http api documentation e.g. for /orders/:variety (https://kite.trade/docs/connect/v3/orders/#placing-orders), couldn't find squareoff, stoploss & trailing_stoploss parameters. It's not clear from python client documentation what values can be provided for these parameters & for which specific order_type.

    c. Are squareoff & trailing_stoploss implemented? The Kite interface does not seem to provide squareoff & trailing stoploss options.

    opened by avnishbm 0
  • Can the kite API be made faster?

    Can the kite API be made faster?

    The following images show the comparison between pykiteconnect and Kiteconnect REST-API for 15000 F&O instruments.

    Current python client:

    Capture1

    Creating requests session object:

    Capture2

    Asynchronous execution:

    Capture3

    Let me know if it can be improved further.

    opened by tkanhe 2
  • feat: add tz info to all naive datetime object

    feat: add tz info to all naive datetime object

    1> Add IST timezone info to all naive DateTime objects. Eg: 'order_timestamp': datetime.datetime(2021, 7, 1, 16, 45, 36, tzinfo=tzoffset('Asia/Kolkata', 19800)), 'exchange_timestamp': datetime.datetime(2021, 7, 1, 16, 45, 36, tzinfo=tzoffset('Asia/Kolkata', 19800) 2> Introduce proper logic(is_timestamp) to check if the response string is a timestamp field. Give away with an earlier string length comparison. 3> Add optional mode field for order_margins. 4> Add example with mode param for order_margins. 5> Change the way to handle exceptions for error responses, which don't have the error_type field(MF APIs). Ex: Kite error response is: {'status': 'error', 'message': "Couldn't find thatorder_id.", 'data': None, 'error_type': 'GeneralException'} Where MF error response is: {'status': 'error', 'message': 'Order not found', 'data': {}}. Don't have error_type field in response.

    opened by ranjanrak 0
  • AttributeError: module 'enum' has no attribute 'IntFlag' while installing AWS EBS Python 3.6

    AttributeError: module 'enum' has no attribute 'IntFlag' while installing AWS EBS Python 3.6

    Getting below error while installing kiteconnect==3.8.2 in AWS Elastic Beanstalk in python 3.6.


    Building wheels for collected packages: kiteconnect, retrying Building wheel for kiteconnect (setup.py): started Building wheel for kiteconnect (setup.py): finished with status 'done' WARNING: Legacy build of wheel for 'kiteconnect' created no files. Command arguments: /opt/python/run/venv/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xxzkrm1h/kiteconnect/setup.py'"'"'; file='"'"'/tmp/pip-install-xxzkrm1h/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 /tmp/pip-wheel-41ix1k84 Command output: [use --verbose to show] Running setup.py clean for kiteconnect Building wheel for retrying (setup.py): started Building wheel for retrying (setup.py): finished with status 'done' Created wheel for retrying: filename=retrying-1.3.3-py3-none-any.whl size=9532 sha256=6c3392994eb699dc99d81e801b0d28ba498b145a267b70028f0780130756ff5c Stored in directory: /root/.cache/pip/wheels/ac/cb/8a/b27bf6323e2f4c462dcbf77d70b7c5e7868a7fbe12871770cf Successfully built retrying Failed to build kiteconnect

    Running setup.py install for kiteconnect: started Running setup.py install for kiteconnect: finished with status 'error' ERROR: Command errored out with exit status 1: command: /opt/python/run/venv/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xxzkrm1h/kiteconnect/setup.py'"'"'; file='"'"'/tmp/pip-install-xxzkrm1h/kiteconnect/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-pziu6m7_/install-record.txt --single-version-externally-managed --compile --install-headers /opt/python/run/venv/include/site/python3.6/kiteconnect cwd: /tmp/pip-install-xxzkrm1h/kiteconnect/ Complete output (9 lines): Traceback (most recent call last): File "", line 1, in File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/init.py", line 3, in from fnmatch import fnmatchcase File "/opt/python/run/venv/lib64/python3.6/fnmatch.py", line 14, in import re File "/opt/python/run/venv/lib64/python3.6/re.py", line 142, in class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' ---------------------------------------- ERROR: Command errored out with exit status 1: /opt/python/run/venv/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xxzkrm1h/kiteconnect/setup.py'"'"'; file='"'"'/tmp/pip-install-xxzkrm1h/kiteconnect/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-pziu6m7_/install-record.txt --single-version-externally-managed --compile --install-headers /opt/python/run/venv/include/site/python3.6/kiteconnect Check the logs for full command output. 2020-09-19 10:05:10,776 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last):


    opened by raunaksingh321 6
Releases(v4.1.0)
  • v4.1.0(May 24, 2022)

  • v4.0.2(Mar 17, 2022)

  • v4.0.0(Nov 23, 2021)

    Breaking changes

    • Renamed ticker fields as per kite connect doc
    • Renamed bsecds to bcd in ticker.EXCHANGE_MAP

    The latest API doc for v4.x will be available here.

    What's Changed

    • fix: update API usage order placement example
    • fix: update getting started example for order placement
    • chore: remove docs, fix copyright year + ztech
    • fix: update bsecds to bcd to be consistency with segment naming
    • feat: update bcd price divisor for ticker
    • fix: timestamp ticker response attributes
    • fix: ticker_attributes naming as per doc

    Full Changelog: https://github.com/zerodha/pykiteconnect/compare/v3.9.4...v4.0.0

    Source code(tar.gz)
    Source code(zip)
  • v3.9.5(Nov 13, 2021)

  • v3.9.4(Jun 18, 2021)

  • v3.9.1(Jan 14, 2021)

  • v3.9.0rc1(Dec 3, 2020)

    • New order margins API
    • Refactored base requests handler to accommodate JSON POST/PUT content types
    • Refactored setup.py to remove FakeDist and other obscure ways of installing Twisted wheels since official wheels were not available
    • Migrated Travis and Appveyor CI tests and builds to Github actions
    Source code(tar.gz)
    Source code(zip)
  • v3.9.0(Dec 3, 2020)

    • New order margins API
    • Refactored base requests handler to accommodate JSON POST/PUT content types
    • Refactored setup.py to remove FakeDist and other obscure ways of installing Twisted wheels since official wheels were not available
    • Migrated Travis and Appveyor CI tests and builds to Github actions
    Source code(tar.gz)
    Source code(zip)
  • v3.8.2(Feb 7, 2020)

  • v3.8.1(Jan 6, 2020)

  • v3.8.1-dev3(Jan 6, 2020)

  • v3.8.1-dev2(Jan 6, 2020)

  • v3.8.1-dev1(Jan 6, 2020)

  • v3.7.7(Feb 14, 2019)

  • v3.7.3(Jun 12, 2018)

  • v3.7.2(Jun 5, 2018)

    • Disable connection pooling by default (Fix: request.ReadTimeout issue)
    • Fix: Reconnection should trigger resubscribe in spite of on_open cb
    Source code(tar.gz)
    Source code(zip)
  • v3.7.0-beta11(May 9, 2018)

  • v3.7.0-beta8(Feb 27, 2018)

  • v3.7.0-beta4(Feb 5, 2018)

    Changelog

    • trigger_range method to fetch CO trigger range
    • quote, ltp, ohlc and trigger_range takes instruments as args

    Trigger range example

    kite.trigger_range("BUY", "NSE:INFY", "NSE:RELIANCE")
    

    Quote calls example

    kite.ltp("NSE:INFY", "NSE:RELIANCE")
    kite.quote("NSE:INFY", "NSE:RELIANCE")
    kite.ohlc("NSE:INFY", "NSE:RELIANCE")
    

    Kiteconnect v3 changelog

    Source code(tar.gz)
    Source code(zip)
  • v3.7.0-beta1(Jan 18, 2018)

    Documentation

    Install

    pip install kiteconnect --upgrade --pre
    

    New features

    • method: profile
    • method: ohlc
    • method: ltp
    • method: renew_access_token
    • method: invalidate_refresh_token
    • constants for products, order type, transaction type, variety, validity, exchanges and margin segments
    • Param disable_ssl to KiteConnect initializer
    • quote call supports multiple instruments call
    • exit_order alias for cancel_order
    • All datetime string fields has been converted to datetime object.
      • orders, order_history, trades, order_trades, mf_orders responses fields order_timestamp, exchange_timestamp, fill_timestamp
      • mf_sips fields created, last_instalment
      • generate_session field login_time
      • quote fields timestamp, last_trade_time
      • instruments field expiry
      • mf_instruments field last_price_date
    • Requests thread pooling is enabled by default with defaults requests library settings Read more

    API method name changes

    | v2 | v3 | | ----------------- | ------------------------- | | request_access_token | generate_session | | invalidate_token | invalidate_access_token | | historical | historical_data | | order_place | place_order | | order_modify | modify_order | | order_cancel | cancel_order | | product_modify | convert_position | | mf_order_place | place_mf_order | | mf_order_cancel | cancel_mf_order | | mf_sip_place | place_mf_sip | | mf_sip_modify | modify_mf_sip | | mf_sip_cancel | cancel_mf_sip | | set_session_hook | set_session_expiry_hook | | orders(order_id) | order_history(order_id) | | trades(order_id) | order_trades(order_id) |

    Param and other changes

    Deprecated from v2

    • exceptions.UserException
    • exceptions.ClientNetworkException
    • exceptions.TwoFAException
    • Param micro_cache from KiteConnect initializer
    • Param order_id from orders call (Renamed to order_history)
    • Param order_id from trades call (Renamed to order_trades)

    KiteTicker changes

    • Rename class WebSocket to KiteTicker
    • KiteTicker initializer param public_token is replaced with access_token
    • Added KiteTicker param reconnect to enable/disable auto re-connection.
    • Auto re-connection is enabled by default (reconnect is True by default)
    • reconnect_interval is deprecated and replaced with reconnect_max_delay
    • Rename: reconnect_tries to reconnect_max_tries
    • Auto reconnect uses exponential back-off algorithm instead of fixed reconnect interval (https://en.wikipedia.org/wiki/Exponential_backoff)
    • Underlying WebSocket library is replaced with Autohbahn Python client (Supports 2,7+, 3.3+) for more stability.
    • Added param connect_timeout to KiteTicker initializer
    • Added method stop_retry to stop auto reconnect while auto re-connection in progress.

    KiteTicker callback changes

    • on_ticks(ws, ticks) - Triggered when ticks are received.
      • ticks - List of tick object. Check below for sample structure.
    • on_close(ws, code, reason) - Triggered when connection is closed.
      • code - WebSocket standard close event code (https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent)
      • reason - DOMString indicating the reason the server closed the connection
    • on_error(ws, code, reason) - Triggered when connection is closed with an error.
      • code - WebSocket standard close event code (https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent)
      • reason - DOMString indicating the reason the server closed the connection
    • on_connect - Triggered when connection is established successfully.
      • response - Response received from server on successful connection.
    • on_message(ws, payload, is_binary) - Triggered when message is received from the server.
      • payload - Raw response from the server (either text or binary).
      • is_binary - Bool to check if response is binary type.
    • on_reconnect(ws, attempts_count) - Triggered when auto re-connection is attempted.
      • attempts_count - Current reconnect attempt number.
    • on_noreconnect(ws) - Triggered when number of auto re-connection attempts exceeds reconnect_tries.

    KiteTicker deprecated methods

    • enable_reconnect
    • disable_reconnect
    • reconnect - reconnect can be set while initializing KiteTicker

    KiteTicker response changes

    • Full mode has following new fields
      • last_trade_time - Last trade time (Python datetime object or None)
      • oi - Open interest
      • oi_high - Day's open interest high
      • oi_low - Day's open interest low
      • timestamp - Tick timestamp (Python datetime object or None)
    Source code(tar.gz)
    Source code(zip)
  • v3.6.2(Dec 12, 2017)

    ohlc - Retrieve OHLC and market depth for list of instruments ltp - Retrieve last price for list of instruments

    Both methods accepts params: instruments which is a list of instruments. Instrument are in the format of tradingsymbol:exchange. For example NSE:INFY

    Source code(tar.gz)
    Source code(zip)
  • v3.6.1(Sep 14, 2017)

  • v3.6.0(Aug 16, 2017)

  • 3.5(Jul 17, 2017)

    Added features

    Auto reconnect WebSocket connection in case of network failure. Refer README for usage details - https://github.com/rainmattertech/pykiteconnect#websocket-usage

    Bug fixes

    1. Fixed mode was sent incorrectly as quote while subscribed for full mode (3d78dfcc74b3af15af1726ad925d619a3e16c770)
    2. Send empty buy and sell lists instead of empty depth if depths are not available. (1c2e0cdcec0e370c1070cf9877f5f2c7cd4b0cfa)
    Source code(tar.gz)
    Source code(zip)
  • v3.3(Oct 25, 2016)

    Released version 3.3 with following fixes and features

    • Added tag support to order APIs
    • Added proxy support for api and websocket streaming
    • Fixed market depth orders integer overflow issue.
    Source code(tar.gz)
    Source code(zip)
Owner
Zerodha Technology
Zerodha Technology
🐍 The official Python client library for Google's discovery based APIs.

Google API Client This is the Python client library for Google's discovery based APIs. To get started, please see the docs folder. These client librar

Google APIs 6.2k Jan 8, 2023
🐍 The official Python client library for Google's discovery based APIs.

Google API Client This is the Python client library for Google's discovery based APIs. To get started, please see the docs folder. These client librar

Google APIs 6.2k Dec 31, 2022
Trading bot - A Trading bot With Python

Trading_bot Trading bot intended for 1) Tracking current prices of tokens 2) Set

Tymur Kotkov 29 Dec 1, 2022
Crypto-trading-simulator - Cryptocurrency trading simulator using Python, Streamlit

Crypto Trading Simulator Run streamlit run main.py Dependency Python 3 streamli

Brad 12 Jul 2, 2022
Utilizing the freqtrade high-frequency cryptocurrency trading framework to build and optimize trading strategies. The bot runs nonstop on a Rasberry Pi.

Freqtrade Strategy Repository Please test all scripts and dry run them before using them in live mode Contact me on discord if you have any questions!

Michael Fourie 90 Jan 1, 2023
This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners and alerts system.

Python Trading Bot w/ Thinkorswim Description This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners

Trey Thomas 201 Jan 3, 2023
Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Alexandr Savinov 326 Jan 3, 2023
Python client for the iNaturalist APIs

pyinaturalist Introduction iNaturalist is a community science platform that helps people get involved in the natural world by observing and identifyin

Nicolas Noé 79 Dec 22, 2022
An API Client package to access the APIs for NBA.com

nba_api An API Client package to access the APIs for NBA.com Development Version: v1.1.9 nba_api is an API Client for www.nba.com. This package is mea

Swar Patel 1.4k Jan 1, 2023
A Pancakeswap v2 trading client (and bot) with limit orders, stop-loss, custom gas strategies, a GUI and much more.

Pancakeswap v2 trading client A Pancakeswap trading client (and bot) with limit orders, stop-loss, custom gas strategies, a GUI and much more. If you

null 571 Mar 15, 2022
A Pancakeswap and Uniswap trading client (and bot) with limit orders, marker orders, stop-loss, custom gas strategies, a GUI and much more.

Pancakeswap and Uniswap trading client Adam A A Pancakeswap and Uniswap trading client (and bot) with market orders, limit orders, stop-loss, custom g

null 570 Mar 9, 2022
GUI Pancakeswap2 and Uniswap3 trading client (and bot)

GUI Pancakeswap2 and Uniswap3 trading client (and bot) (MOST ADVANCE TRADING BOT SUPPORT WINDOWS LINUX MAC) (AUTO BUY TOKEN ON LUNCH AFTER ADD LIQUIDI

null 16 Dec 23, 2021
Unofficial GoPro API Library for Python - connect to GoPro via WiFi.

GoPro API for Python Unofficial GoPro API Library for Python - connect to GoPro cameras via WiFi. Compatibility: HERO3 HERO3+ HERO4 (including HERO Se

Konrad Iturbe 1.3k Jan 1, 2023
twitter bot tha uses tweepy library class to connect to TWITTER API

TWITTER-BOT-tweepy- twitter bot that uses tweepy library class to connect to TWITTER API replies to mentions automatically and follows the tweet.autho

Muziwandile Nkomo 2 Jan 8, 2022
alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API.

alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API. It allows rapid trading algo development easily, with support for both REST and streaming data interfaces

Alpaca 1.5k Jan 9, 2023
Dns-Client-Server - Dns Client Server For Python

Dns-client-server DNS Server: supporting all types of queries and replies. Shoul

Nishant Badgujar 1 Feb 15, 2022
Raphtory-client - The python client for the Raphtory project

Raphtory Client This is the python client for the Raphtory project Install via p

Raphtory 5 Apr 28, 2022
AuthGG is a Python library for dealing with Auth.gg apis

AuthGG AuthGG is a Python library for dealing with Auth.gg apis Installation Use the package manager pip to install requests Add the auth.py file in y

ExtremeDev 1 Dec 20, 2021