kitetrader


Namekitetrader JSON
Version 3.0.0 PyPI version JSON
download
home_pageNone
SummaryUnofficial Python Client for Zerodha Kite
upload_time2024-04-22 15:24:38
maintainerNone
docs_urlNone
authorBenny Thadikaran
requires_python>=3.8
licenseNone
keywords algo-trading historical-data intraday-data kiteconnect stock-data stock-market zerodha zerodha-kite
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Kite-Trader

Unofficial Python library for Zerodha Kite with built-in throttling, so you never exceed Kite's API limits.

If you :heart: my work so far, please :star2: this repo.

## Installation

Supports Python version >= 3.8

`pip install kitetrader`

## Breaking changes in v3.0.0: 22nd April 2024

Methods return the entire JSON response unmodified. Previously only the `data` portion of the response was returned.

This allows the library user to code defensively. For example the trying to access `data` on the below response would result in a KeyError.

```
{
    "status": "error",
    "message": "Error message",
    "error_type": "GeneralException"
}
```

User can instead check if `response['status'] == 'success'` before accessing the `data` key. Otherwise log the error.

## Usage

```python
from kitetrader import Kite

# Using with statement (context manager)
with Kite() as kite:
  kite.profile() # user profile
  kite.holdings() # user portfolio

# or
kite = Kite()
kite.profile()
kite.holdings()

# close the requests session
kite.close()
```

## Login

**Update v2.2.0 - 19th April 2024** - Support both KiteConnect login and Web login

**For KiteConnect login:**

1. Pass the `api_key`, `api_secret` and `request_token` during initialization. Once authorized, the `access_token` can be accessed as `kite.access_token`

```python
kite = Kite(
    api_key=credentials['api_key'],
    api_secret=credentials['api_secret'],
    request_token=credentials['request_token'],
)

# On successful authentication, save the kite.access_token to database or file
# for future use
print(kite.access_token)
```

2. On subsequent attempts, simply pass the `access_token` and `api_key`

```python
kite = Kite(
    access_token=credentials["access_token"],
    api_key=credentials["api_key"],
)
```

**For Web Login:**

1. Web login is the default, if no arguments are passed. It will start an interactive prompt, requesting `user_id`, `password` and `twofa`.

```python
# Interactive prompt
kite = Kite()

# Once auth is completed, save the enctoken for later use
print(kite.enctoken)
```

2. You may pass some or all three arguments. Any missing info, will need to be entered, when prompted.

```python
kite = Kite(
    user_id: credentials['user_id'],
    password: credentials['password'],
    twofa: twofa,
)
```

3. On successful authorization, the enctoken is saved to a cookie file. On subsequent attempts, the `enctoken` is loaded from the cookie file.

4. Using the web login, will log you out of any Kite web browser sessions. You can reuse the browser `enctoken`, passing it to Kite. This way, you can use Kite Web, without getting logged out.

`kite = Kite(enctoken=credentials['enctoken'])`

To access the browser `enctoken`, login to kite.zerodha.com and press `SHIFT + F9` to open the Storage inspector (On Firefox). You will find the info under cookies.

## IMPORTANT NOTES and WARNINGs

- Hard coding password and credentials can be risky. Take appropriate measure to safeguard your credentials from accidental uploads or exposure on shared computers. Stick to defaults or use enctoken if unsure.

- Web login credentials are meant to be used on your PC (For personal use). Use of Web login credentials on a public facing server can put your account at high risk.

- Methods may raise the following errors:
  - A `RuntimeError` is raised if too many (>15) 429 reponse codes are returned.
  - A `TimeoutError` is raised if server takes too long to respond.
  - A `ConnectionError` is raised if:
    - Session expired
    - Bad request or invalid parameters
    - Internal server error

## Available Methods

Almost all methods defined on the Kite Connect 3 api have been covered except Webhooks and Websocket streaming. You can refer to the [Kite Connect Docs](https://kite.trade/docs/connect/v3/) for more information

```python
# User
kite.profile()
kite.margins(segment=kite.MARGIN_EQUITY) # or kite.MARGIN_COMMODITY

# Portfolio
kite.holdings() # long-term holdings
kite.positions() # short-term positions
kite.auctions() # list all auctions

# Orders
kite.orders() # list all orders for the day
kite.order_history('171229000724687') # order_id
kite.trades() # list all executed trades
kite.order_trades('171229000724687') # order_id

kite.place_order(kite.VARIETY_REGULAR,
                 kite.EXCHANGE_NSE,
                 'INFY',
                 kite.TRANSACTION_TYPE_BUY,
                 1,
                 kite.PRODUCT_NRML,
                 kite.ORDER_TYPE_MARKET) # Buy INFY at market price from NSE with product type NRML

kite.modify_order(kite.VARIETY_REGULAR, '171229000724687', 5) # order_id with quantity 5

kite.cancel_order(kite.VARIETY_REGULAR, '171229000724687')
```

### Market Quotes

```python
# Get the full market quotes - ohlc, OI, bid/ask, etc

instruments = ['NSE:INFY', 'NSE:RELIANCE', 'NSE:HDFCBANK', 'NSE:TCS']

kite.quote(instruments) # accepts list or a single string

# or

kite.quote('NSE:INFY')

kite.ohlc(instruments) # Get OHLCV and last traded price

kite.ltp(instruments) # Last traded price of all instruments
```

### Historical Candle data

```python
from kitetrader import Kite
from pandas import DataFrame, to_datetime
from datetime import datetime

'''An example to load historical candle data in Pandas DataFrame'''

def to_dataframe(data, oi=False):
    '''Returns a pandas DataFrame with Date as Index'''

    columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']

    if oi:
        columns.append('OpenInterest')

    df = DataFrame(data, columns=columns)

    df['Date'] = to_datetime(df['Date'])
    return df.set_index('Date')


from_dt = datetime(2023, 10, 4, 9, 15)
to_dt = datetime(2023, 10, 4, 15, 30)
instrument_token = '8979970' # banknifty oct futures

with Kite() as kite:
    data = kite.historical_data(instrument_token,
                                from_dt,
                                to_dt,
                                interval='15minute', oi=True)

df = to_dataframe(data, oi=True)

print(df.head())

df.to_csv(kite.base_dir / 'BANKNIFTY_OCT_FUT.csv')
```

### Instruments

Instruments method will return a dump of all tradable instruments. This is a large file of 7MB with 10k+ records. Only download what is required by specifying the exchange.

```python
from kitetrader import Kite
from io import BytesIO
from pandas import read_csv

'''Example to load and save instruments to csv file. '''

with Kite() as kite:
    # returns data in binary format
    data = kite.instruments(kite.EXCHANGE_NSE)

# Save as csv file using pathlib.path
(kite.base_dir / 'instruments.csv').write_bytes(data)

# or using file open with write binary
with open('instruments.csv', 'wb') as f:
    f.write(data)

# To convert data to Pandas DataFrame
df = read_csv(BytesIO(data), index_col='tradingsymbol')

# or load the saved csv file as DataFrame
df = read_csv('instruments.csv', index_col='tradingsymbol')

# to query an instrument token
instrument_token = df.loc['INFY', 'instrument_token']
```

### Constants

The below contants have been defined on the Kite class. You can use them as arguments to the various methods.

```python
# Exchanges
EXCHANGE_NSE = "NSE"
EXCHANGE_BSE = "BSE"
EXCHANGE_NFO = "NFO"
EXCHANGE_CDS = "CDS"
EXCHANGE_BFO = "BFO"
EXCHANGE_MCX = "MCX"
EXCHANGE_BCD = "BCD"

# Products
PRODUCT_MIS = "MIS"
PRODUCT_CNC = "CNC"
PRODUCT_NRML = "NRML"
PRODUCT_CO = "CO"

# Order types
ORDER_TYPE_MARKET = "MARKET"
ORDER_TYPE_LIMIT = "LIMIT"
ORDER_TYPE_SLM = "SL-M"
ORDER_TYPE_SL = "SL"

# Varities
VARIETY_REGULAR = "regular"
VARIETY_CO = "co"
VARIETY_AMO = "amo"
VARIETY_ICEBERG = "iceberg"
VARIETY_AUCTION = "auction"

# Transaction type
TRANSACTION_TYPE_BUY = "BUY"
TRANSACTION_TYPE_SELL = "SELL"

# Validity
VALIDITY_DAY = "DAY"
VALIDITY_IOC = "IOC"
VALIDITY_TTL = "TTL"

# Position Type
POSITION_TYPE_DAY = "day"
POSITION_TYPE_OVERNIGHT = "overnight"

# Margins segments
MARGIN_EQUITY = "equity"
MARGIN_COMMODITY = "commodity"

# GTT order type
GTT_TYPE_OCO = "two-leg"
GTT_TYPE_SINGLE = "single"

# Status constants
STATUS_COMPLETE = "COMPLETE"
STATUS_REJECTED = "REJECTED"
STATUS_CANCELLED = "CANCELLED"

# GTT order status
GTT_STATUS_ACTIVE = "active"
GTT_STATUS_TRIGGERED = "triggered"
GTT_STATUS_DISABLED = "disabled"
GTT_STATUS_EXPIRED = "expired"
GTT_STATUS_CANCELLED = "cancelled"
GTT_STATUS_REJECTED = "rejected"
GTT_STATUS_DELETED = "deleted"
```

### API limits and Throttling

When making large number of requests its essential to respect the [API limits set by Zerodha](https://kite.trade/docs/connect/v3/exceptions/#api-rate-limit).

The Throttle class ensures you do not exceed these limits. Its takes two arguments - a dictionary configuration and an integer max_penalty_count.

The `max_penalty_count` is maximum number of 429 HTTP error code, allowed to be returned during a session. Exceeding this limit will result in a runtime error.

The configuration is a dictionary which defines the limits for each endpoint. Here, `RPS` stands for Requests Per Second and`RPM` stands for Requests Per Minute. Limits are set for each end point.

```python
throttle_config = {
    'quote': {
        'rps': 1,
    },
    'historical': {
        'rps': 3,
    },
    'order': {
        'rps': 8,
        'rpm': 180,
    },
    'default': {
        'rps': 8,
    }
}

max_penalty_count = 15

th = Throttle(throttle_config, max_penalty_count)
```

### Class and Method signature

```python
class Kite(builtins.object)
 |  Kite(enctoken: Optional[str] = None)
 |  
 |  Unofficial implementation of Zerodha Kite api
 |  
 |  Methods defined here:
 |  
 |  __init__(self, user_id: Optional[str] = None, password: Optional[str] = None, twofa: Optional[str] = None, enctoken: Optional[str] = None)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  auctions(self)
 |      Retrieve the list of auctions that are currently being held
 |  
 |  cancel_order(self, variety, order_id)
 |      Cancel an order.
 |  
 |  close(self)
 |      Close the Requests session
 |  
 |  historical_data(self, instrument_token: str, from_dt: Union[datetime.datetime, str], to_dt: Union[datetime.datetime, str], interval: str, continuous=False, oi=False)
 |      return historical candle records for a given instrument.
 |  
 |  holdings(self)
 |      Return the list of long term equity holdings
 |  
 |  instruments(self, exchange: Optional[str] = None)
 |      return a CSV dump of all tradable instruments
 |  
 |  ltp(self, instruments: Union[str, collections.abc.Collection])
 |      Returns the last traded price
 |  
 |  margins(self, segment: Optional[str] = None)
 |      Returns funds, cash, and margin information for the user
 |      for equity and commodity segments
 |  
 |  modify_order(self, variety, order_id, quantity=None, price=None, order_type=None, trigger_price=None, validity=None, disclosed_quantity=None)
 |      Modify an open order.
 |  
 |  ohlc(self, instruments: Union[str, collections.abc.Collection])
 |      Returns ohlc and last traded price
 |  
 |  order_history(self, order_id)
 |      Get history of individual orders
 |  
 |  order_trades(self, order_id)
 |      Get the the trades generated by an order
 |  
 |  orders(self)
 |      Get list of all orders for the day
 |  
 |  place_order(self, variety, exchange, tradingsymbol, transaction_type, quantity, product, order_type, price=None, validity=None, validity_ttl=None, disclosed_quantity=None, trigger_price=None, iceberg_legs=None, iceberg_quantity=None, auction_number=None, tag=None)
 |      Place an order of a particular variety
 |  
 |  positions(self)
 |      Retrieve the list of short term positions
 |  
 |  profile(self)
 |      Retrieve the user profile
 |  
 |  quote(self, instruments: Union[str, collections.abc.Collection])
 |      Return the full market quotes - ohlc, OI, bid/ask etc
 |  
 |  trades(self)
 |      Get the list of all executed trades for the day
 |  
 |  Data and other attributes defined here:
 |  
 |  EXCHANGE_BCD = 'BCD'
 |  
 |  EXCHANGE_BFO = 'BFO'
 |  
 |  EXCHANGE_BSE = 'BSE'
 |  
 |  EXCHANGE_CDS = 'CDS'
 |  
 |  EXCHANGE_MCX = 'MCX'
 |  
 |  EXCHANGE_NFO = 'NFO'
 |  
 |  EXCHANGE_NSE = 'NSE'
 |  
 |  GTT_TYPE_OCO = 'two-leg'
 |  
 |  GTT_TYPE_SINGLE = 'single'
 |  
 |  MARGIN_COMMODITY = 'commodity'
 |  
 |  MARGIN_EQUITY = 'equity'
 |  
 |  ORDER_TYPE_LIMIT = 'LIMIT'
 |  
 |  ORDER_TYPE_MARKET = 'MARKET'
 |  
 |  ORDER_TYPE_SL = 'SL'
 |  
 |  ORDER_TYPE_SLM = 'SL-M'
 |  
 |  POSITION_TYPE_DAY = 'day'
 |  
 |  POSITION_TYPE_OVERNIGHT = 'overnight'
 |  
 |  PRODUCT_CNC = 'CNC'
 |  
 |  PRODUCT_CO = 'CO'
 |  
 |  PRODUCT_MIS = 'MIS'
 |  
 |  PRODUCT_NRML = 'NRML'
 |  
 |  TRANSACTION_TYPE_BUY = 'BUY'
 |  
 |  TRANSACTION_TYPE_SELL = 'SELL'
 |  
 |  VALIDITY_DAY = 'DAY'
 |  
 |  VALIDITY_IOC = 'IOC'
 |  
 |  VALIDITY_TTL = 'TTL'
 |  
 |  VARIETY_AMO = 'amo'
 |  
 |  VARIETY_AUCTION = 'auction'
 |  
 |  VARIETY_CO = 'co'
 |  
 |  VARIETY_ICEBERG = 'iceberg'
 |  
 |  VARIETY_REGULAR = 'regular'
 |  
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "kitetrader",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "algo-trading, historical-data, intraday-data, kiteconnect, stock-data, stock-market, zerodha, zerodha-kite",
    "author": "Benny Thadikaran",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/dd/53/d50bb273d765f918a0e52426373ba3c3f6091a7e67d824c11a7f8b155916/kitetrader-3.0.0.tar.gz",
    "platform": null,
    "description": "# Kite-Trader\n\nUnofficial Python library for Zerodha Kite with built-in throttling, so you never exceed Kite's API limits.\n\nIf you :heart: my work so far, please :star2: this repo.\n\n## Installation\n\nSupports Python version >= 3.8\n\n`pip install kitetrader`\n\n## Breaking changes in v3.0.0: 22nd April 2024\n\nMethods return the entire JSON response unmodified. Previously only the `data` portion of the response was returned.\n\nThis allows the library user to code defensively. For example the trying to access `data` on the below response would result in a KeyError.\n\n```\n{\n    \"status\": \"error\",\n    \"message\": \"Error message\",\n    \"error_type\": \"GeneralException\"\n}\n```\n\nUser can instead check if `response['status'] == 'success'` before accessing the `data` key. Otherwise log the error.\n\n## Usage\n\n```python\nfrom kitetrader import Kite\n\n# Using with statement (context manager)\nwith Kite() as kite:\n  kite.profile() # user profile\n  kite.holdings() # user portfolio\n\n# or\nkite = Kite()\nkite.profile()\nkite.holdings()\n\n# close the requests session\nkite.close()\n```\n\n## Login\n\n**Update v2.2.0 - 19th April 2024** - Support both KiteConnect login and Web login\n\n**For KiteConnect login:**\n\n1. Pass the `api_key`, `api_secret` and `request_token` during initialization. Once authorized, the `access_token` can be accessed as `kite.access_token`\n\n```python\nkite = Kite(\n    api_key=credentials['api_key'],\n    api_secret=credentials['api_secret'],\n    request_token=credentials['request_token'],\n)\n\n# On successful authentication, save the kite.access_token to database or file\n# for future use\nprint(kite.access_token)\n```\n\n2. On subsequent attempts, simply pass the `access_token` and `api_key`\n\n```python\nkite = Kite(\n    access_token=credentials[\"access_token\"],\n    api_key=credentials[\"api_key\"],\n)\n```\n\n**For Web Login:**\n\n1. Web login is the default, if no arguments are passed. It will start an interactive prompt, requesting `user_id`, `password` and `twofa`.\n\n```python\n# Interactive prompt\nkite = Kite()\n\n# Once auth is completed, save the enctoken for later use\nprint(kite.enctoken)\n```\n\n2. You may pass some or all three arguments. Any missing info, will need to be entered, when prompted.\n\n```python\nkite = Kite(\n    user_id: credentials['user_id'],\n    password: credentials['password'],\n    twofa: twofa,\n)\n```\n\n3. On successful authorization, the enctoken is saved to a cookie file. On subsequent attempts, the `enctoken` is loaded from the cookie file.\n\n4. Using the web login, will log you out of any Kite web browser sessions. You can reuse the browser `enctoken`, passing it to Kite. This way, you can use Kite Web, without getting logged out.\n\n`kite = Kite(enctoken=credentials['enctoken'])`\n\nTo access the browser `enctoken`, login to kite.zerodha.com and press `SHIFT + F9` to open the Storage inspector (On Firefox). You will find the info under cookies.\n\n## IMPORTANT NOTES and WARNINGs\n\n- Hard coding password and credentials can be risky. Take appropriate measure to safeguard your credentials from accidental uploads or exposure on shared computers. Stick to defaults or use enctoken if unsure.\n\n- Web login credentials are meant to be used on your PC (For personal use). Use of Web login credentials on a public facing server can put your account at high risk.\n\n- Methods may raise the following errors:\n  - A `RuntimeError` is raised if too many (>15) 429 reponse codes are returned.\n  - A `TimeoutError` is raised if server takes too long to respond.\n  - A `ConnectionError` is raised if:\n    - Session expired\n    - Bad request or invalid parameters\n    - Internal server error\n\n## Available Methods\n\nAlmost all methods defined on the Kite Connect 3 api have been covered except Webhooks and Websocket streaming. You can refer to the [Kite Connect Docs](https://kite.trade/docs/connect/v3/) for more information\n\n```python\n# User\nkite.profile()\nkite.margins(segment=kite.MARGIN_EQUITY) # or kite.MARGIN_COMMODITY\n\n# Portfolio\nkite.holdings() # long-term holdings\nkite.positions() # short-term positions\nkite.auctions() # list all auctions\n\n# Orders\nkite.orders() # list all orders for the day\nkite.order_history('171229000724687') # order_id\nkite.trades() # list all executed trades\nkite.order_trades('171229000724687') # order_id\n\nkite.place_order(kite.VARIETY_REGULAR,\n                 kite.EXCHANGE_NSE,\n                 'INFY',\n                 kite.TRANSACTION_TYPE_BUY,\n                 1,\n                 kite.PRODUCT_NRML,\n                 kite.ORDER_TYPE_MARKET) # Buy INFY at market price from NSE with product type NRML\n\nkite.modify_order(kite.VARIETY_REGULAR, '171229000724687', 5) # order_id with quantity 5\n\nkite.cancel_order(kite.VARIETY_REGULAR, '171229000724687')\n```\n\n### Market Quotes\n\n```python\n# Get the full market quotes - ohlc, OI, bid/ask, etc\n\ninstruments = ['NSE:INFY', 'NSE:RELIANCE', 'NSE:HDFCBANK', 'NSE:TCS']\n\nkite.quote(instruments) # accepts list or a single string\n\n# or\n\nkite.quote('NSE:INFY')\n\nkite.ohlc(instruments) # Get OHLCV and last traded price\n\nkite.ltp(instruments) # Last traded price of all instruments\n```\n\n### Historical Candle data\n\n```python\nfrom kitetrader import Kite\nfrom pandas import DataFrame, to_datetime\nfrom datetime import datetime\n\n'''An example to load historical candle data in Pandas DataFrame'''\n\ndef to_dataframe(data, oi=False):\n    '''Returns a pandas DataFrame with Date as Index'''\n\n    columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']\n\n    if oi:\n        columns.append('OpenInterest')\n\n    df = DataFrame(data, columns=columns)\n\n    df['Date'] = to_datetime(df['Date'])\n    return df.set_index('Date')\n\n\nfrom_dt = datetime(2023, 10, 4, 9, 15)\nto_dt = datetime(2023, 10, 4, 15, 30)\ninstrument_token = '8979970' # banknifty oct futures\n\nwith Kite() as kite:\n    data = kite.historical_data(instrument_token,\n                                from_dt,\n                                to_dt,\n                                interval='15minute', oi=True)\n\ndf = to_dataframe(data, oi=True)\n\nprint(df.head())\n\ndf.to_csv(kite.base_dir / 'BANKNIFTY_OCT_FUT.csv')\n```\n\n### Instruments\n\nInstruments method will return a dump of all tradable instruments. This is a large file of 7MB with 10k+ records. Only download what is required by specifying the exchange.\n\n```python\nfrom kitetrader import Kite\nfrom io import BytesIO\nfrom pandas import read_csv\n\n'''Example to load and save instruments to csv file. '''\n\nwith Kite() as kite:\n    # returns data in binary format\n    data = kite.instruments(kite.EXCHANGE_NSE)\n\n# Save as csv file using pathlib.path\n(kite.base_dir / 'instruments.csv').write_bytes(data)\n\n# or using file open with write binary\nwith open('instruments.csv', 'wb') as f:\n    f.write(data)\n\n# To convert data to Pandas DataFrame\ndf = read_csv(BytesIO(data), index_col='tradingsymbol')\n\n# or load the saved csv file as DataFrame\ndf = read_csv('instruments.csv', index_col='tradingsymbol')\n\n# to query an instrument token\ninstrument_token = df.loc['INFY', 'instrument_token']\n```\n\n### Constants\n\nThe below contants have been defined on the Kite class. You can use them as arguments to the various methods.\n\n```python\n# Exchanges\nEXCHANGE_NSE = \"NSE\"\nEXCHANGE_BSE = \"BSE\"\nEXCHANGE_NFO = \"NFO\"\nEXCHANGE_CDS = \"CDS\"\nEXCHANGE_BFO = \"BFO\"\nEXCHANGE_MCX = \"MCX\"\nEXCHANGE_BCD = \"BCD\"\n\n# Products\nPRODUCT_MIS = \"MIS\"\nPRODUCT_CNC = \"CNC\"\nPRODUCT_NRML = \"NRML\"\nPRODUCT_CO = \"CO\"\n\n# Order types\nORDER_TYPE_MARKET = \"MARKET\"\nORDER_TYPE_LIMIT = \"LIMIT\"\nORDER_TYPE_SLM = \"SL-M\"\nORDER_TYPE_SL = \"SL\"\n\n# Varities\nVARIETY_REGULAR = \"regular\"\nVARIETY_CO = \"co\"\nVARIETY_AMO = \"amo\"\nVARIETY_ICEBERG = \"iceberg\"\nVARIETY_AUCTION = \"auction\"\n\n# Transaction type\nTRANSACTION_TYPE_BUY = \"BUY\"\nTRANSACTION_TYPE_SELL = \"SELL\"\n\n# Validity\nVALIDITY_DAY = \"DAY\"\nVALIDITY_IOC = \"IOC\"\nVALIDITY_TTL = \"TTL\"\n\n# Position Type\nPOSITION_TYPE_DAY = \"day\"\nPOSITION_TYPE_OVERNIGHT = \"overnight\"\n\n# Margins segments\nMARGIN_EQUITY = \"equity\"\nMARGIN_COMMODITY = \"commodity\"\n\n# GTT order type\nGTT_TYPE_OCO = \"two-leg\"\nGTT_TYPE_SINGLE = \"single\"\n\n# Status constants\nSTATUS_COMPLETE = \"COMPLETE\"\nSTATUS_REJECTED = \"REJECTED\"\nSTATUS_CANCELLED = \"CANCELLED\"\n\n# GTT order status\nGTT_STATUS_ACTIVE = \"active\"\nGTT_STATUS_TRIGGERED = \"triggered\"\nGTT_STATUS_DISABLED = \"disabled\"\nGTT_STATUS_EXPIRED = \"expired\"\nGTT_STATUS_CANCELLED = \"cancelled\"\nGTT_STATUS_REJECTED = \"rejected\"\nGTT_STATUS_DELETED = \"deleted\"\n```\n\n### API limits and Throttling\n\nWhen making large number of requests its essential to respect the [API limits set by Zerodha](https://kite.trade/docs/connect/v3/exceptions/#api-rate-limit).\n\nThe Throttle class ensures you do not exceed these limits. Its takes two arguments - a dictionary configuration and an integer max_penalty_count.\n\nThe `max_penalty_count` is maximum number of 429 HTTP error code, allowed to be returned during a session. Exceeding this limit will result in a runtime error.\n\nThe configuration is a dictionary which defines the limits for each endpoint. Here, `RPS` stands for Requests Per Second and`RPM` stands for Requests Per Minute. Limits are set for each end point.\n\n```python\nthrottle_config = {\n    'quote': {\n        'rps': 1,\n    },\n    'historical': {\n        'rps': 3,\n    },\n    'order': {\n        'rps': 8,\n        'rpm': 180,\n    },\n    'default': {\n        'rps': 8,\n    }\n}\n\nmax_penalty_count = 15\n\nth = Throttle(throttle_config, max_penalty_count)\n```\n\n### Class and Method signature\n\n```python\nclass Kite(builtins.object)\n |  Kite(enctoken: Optional[str] = None)\n |  \n |  Unofficial implementation of Zerodha Kite api\n |  \n |  Methods defined here:\n |  \n |  __init__(self, user_id: Optional[str] = None, password: Optional[str] = None, twofa: Optional[str] = None, enctoken: Optional[str] = None)\n |      Initialize self.  See help(type(self)) for accurate signature.\n |  \n |  auctions(self)\n |      Retrieve the list of auctions that are currently being held\n |  \n |  cancel_order(self, variety, order_id)\n |      Cancel an order.\n |  \n |  close(self)\n |      Close the Requests session\n |  \n |  historical_data(self, instrument_token: str, from_dt: Union[datetime.datetime, str], to_dt: Union[datetime.datetime, str], interval: str, continuous=False, oi=False)\n |      return historical candle records for a given instrument.\n |  \n |  holdings(self)\n |      Return the list of long term equity holdings\n |  \n |  instruments(self, exchange: Optional[str] = None)\n |      return a CSV dump of all tradable instruments\n |  \n |  ltp(self, instruments: Union[str, collections.abc.Collection])\n |      Returns the last traded price\n |  \n |  margins(self, segment: Optional[str] = None)\n |      Returns funds, cash, and margin information for the user\n |      for equity and commodity segments\n |  \n |  modify_order(self, variety, order_id, quantity=None, price=None, order_type=None, trigger_price=None, validity=None, disclosed_quantity=None)\n |      Modify an open order.\n |  \n |  ohlc(self, instruments: Union[str, collections.abc.Collection])\n |      Returns ohlc and last traded price\n |  \n |  order_history(self, order_id)\n |      Get history of individual orders\n |  \n |  order_trades(self, order_id)\n |      Get the the trades generated by an order\n |  \n |  orders(self)\n |      Get list of all orders for the day\n |  \n |  place_order(self, variety, exchange, tradingsymbol, transaction_type, quantity, product, order_type, price=None, validity=None, validity_ttl=None, disclosed_quantity=None, trigger_price=None, iceberg_legs=None, iceberg_quantity=None, auction_number=None, tag=None)\n |      Place an order of a particular variety\n |  \n |  positions(self)\n |      Retrieve the list of short term positions\n |  \n |  profile(self)\n |      Retrieve the user profile\n |  \n |  quote(self, instruments: Union[str, collections.abc.Collection])\n |      Return the full market quotes - ohlc, OI, bid/ask etc\n |  \n |  trades(self)\n |      Get the list of all executed trades for the day\n |  \n |  Data and other attributes defined here:\n |  \n |  EXCHANGE_BCD = 'BCD'\n |  \n |  EXCHANGE_BFO = 'BFO'\n |  \n |  EXCHANGE_BSE = 'BSE'\n |  \n |  EXCHANGE_CDS = 'CDS'\n |  \n |  EXCHANGE_MCX = 'MCX'\n |  \n |  EXCHANGE_NFO = 'NFO'\n |  \n |  EXCHANGE_NSE = 'NSE'\n |  \n |  GTT_TYPE_OCO = 'two-leg'\n |  \n |  GTT_TYPE_SINGLE = 'single'\n |  \n |  MARGIN_COMMODITY = 'commodity'\n |  \n |  MARGIN_EQUITY = 'equity'\n |  \n |  ORDER_TYPE_LIMIT = 'LIMIT'\n |  \n |  ORDER_TYPE_MARKET = 'MARKET'\n |  \n |  ORDER_TYPE_SL = 'SL'\n |  \n |  ORDER_TYPE_SLM = 'SL-M'\n |  \n |  POSITION_TYPE_DAY = 'day'\n |  \n |  POSITION_TYPE_OVERNIGHT = 'overnight'\n |  \n |  PRODUCT_CNC = 'CNC'\n |  \n |  PRODUCT_CO = 'CO'\n |  \n |  PRODUCT_MIS = 'MIS'\n |  \n |  PRODUCT_NRML = 'NRML'\n |  \n |  TRANSACTION_TYPE_BUY = 'BUY'\n |  \n |  TRANSACTION_TYPE_SELL = 'SELL'\n |  \n |  VALIDITY_DAY = 'DAY'\n |  \n |  VALIDITY_IOC = 'IOC'\n |  \n |  VALIDITY_TTL = 'TTL'\n |  \n |  VARIETY_AMO = 'amo'\n |  \n |  VARIETY_AUCTION = 'auction'\n |  \n |  VARIETY_CO = 'co'\n |  \n |  VARIETY_ICEBERG = 'iceberg'\n |  \n |  VARIETY_REGULAR = 'regular'\n |  \n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Unofficial Python Client for Zerodha Kite",
    "version": "3.0.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/BennyThadikaran/Kite-Trader/issues",
        "Homepage": "https://github.com/BennyThadikaran/Kite-Trader"
    },
    "split_keywords": [
        "algo-trading",
        " historical-data",
        " intraday-data",
        " kiteconnect",
        " stock-data",
        " stock-market",
        " zerodha",
        " zerodha-kite"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "83fb503804656b5ca1c716f9f03c49e2a5a533e1ad4483f3294b95b6b6af98e0",
                "md5": "ccc8f7e9308eefe1470cf6bd0df2568e",
                "sha256": "ea378b56b17858a8a431dc9f25726254ca9e8d833f46e34e5b5af49efbf891b5"
            },
            "downloads": -1,
            "filename": "kitetrader-3.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ccc8f7e9308eefe1470cf6bd0df2568e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 22503,
            "upload_time": "2024-04-22T15:24:37",
            "upload_time_iso_8601": "2024-04-22T15:24:37.162555Z",
            "url": "https://files.pythonhosted.org/packages/83/fb/503804656b5ca1c716f9f03c49e2a5a533e1ad4483f3294b95b6b6af98e0/kitetrader-3.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "dd53d50bb273d765f918a0e52426373ba3c3f6091a7e67d824c11a7f8b155916",
                "md5": "fa8be59c9868b496afcd0e91d6da1439",
                "sha256": "10f358e51b5fec6575976d03057faf7679c9333a755e18c9eee808f21ffa9682"
            },
            "downloads": -1,
            "filename": "kitetrader-3.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "fa8be59c9868b496afcd0e91d6da1439",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 24128,
            "upload_time": "2024-04-22T15:24:38",
            "upload_time_iso_8601": "2024-04-22T15:24:38.320038Z",
            "url": "https://files.pythonhosted.org/packages/dd/53/d50bb273d765f918a0e52426373ba3c3f6091a7e67d824c11a7f8b155916/kitetrader-3.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-22 15:24:38",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "BennyThadikaran",
    "github_project": "Kite-Trader",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "kitetrader"
}
        
Elapsed time: 0.25502s