Kite Reference¶
- class aio_trader.kite.Kite(enctoken: str | None = None, access_token: str | None = None)¶
Bases:
AbstractBroker
Unofficial implementation of Zerodha Kite API using aiohttp for async requests
Implements
AbstractBroker
- Parameters:
enctoken (Optional[str]) – Optional Web or browser token from a previous login
access_token (Optional[str]) – Api login token from a previous login
All arguments are Optional
enctoken
oraccess_token
if available can be reused to login.# Successful request HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": {} } # Failed request HTTP/1.1 500 Server error Content-Type: application/json { "status": "error", "message": "Error message", "error_type": "GeneralException" }
- async auctions() dict ¶
Retrieve the list of auctions that are currently being held
- async authorize(**kwargs) None ¶
Authorize the User
- Parameters:
user_id (Optional[str]) – Kite Web user-id
password (Optional[str]) – Kite Web password
twofa (str | Callable | None) – An optional OTP string or Callable that returns OTP
request_token (Optional[str]) – KiteConnect request_token
api_key (Optional[str]) – KiteConnect api key. Required if access_token is passed
secret (Optional[str]) – KiteConnect secret
- Raises:
ValueError – if one of request_token or secret or api_key is provided but others are missing.
WEB login - requires
user_id
,password
andtwofa
KiteConnect login - requires
request_token
,secret
oraccess_token
.enctoken
from web login is stored in a cookie file and reused.
If no arguments passed, defaults to web login using interactive prompt
If
enctoken
oraccess_token
was provided, update the headers and returnIf
request_token
andsecret
are provided, proceed to KiteConnect loginElse proceed with WEB login.
Check if cookie file exists and not expired. Load the enctoken, update the headers and return
If no cookie file exists or has expired, prompt for missing arguments, request the enctoken, update the headers and return.
- async cancel_order(variety: str, order_id: str) dict ¶
Cancel an order.
- Parameters:
variety (str) – One of regular, co, amo, iceberg, auction
order_id (str)
- async historical_data(instrument_token: str, from_dt: datetime | str, to_dt: datetime | str, interval: str, continuous=False, oi=False) dict ¶
Return historical candle records for a given instrument.
- Parameters:
instrument_token (str)
from_dt (datetime.datetime | str) – ISO format datetime string or datetime
to_dt (datetime.datetime | str) – ISO format datetime string or datetime
interval (str) – minute, day, 3minute, 5minute, 10minute, 15minute, 30minute, 60minute
continuous (bool) – Pass True to get continuous data (F & O)
oi (bool) – Pass True to get OI data (F & O)
- async holdings() dict ¶
Return the list of long term equity holdings
- async instruments(exchange: str | None = None) bytes ¶
Return a CSV dump of all tradable instruments in binary format
Example:
with Kite() as kite: data = await kite.instruments(kite.EXCHANGE_NSE) with open('instruments.csv', 'wb') as f: f.write(data)
import pandas as pd import io # Load data into pandas Dataframe df = pd.read_csv(io.BytesIO(data), index_col='tradingsymbol')
- async ltp(instruments: str | Collection[str]) dict ¶
Returns the last traded price
instrument identified by exchange:tradingsymbol example. NSE:INFY
- Parameters:
instruments – A str or collection of instruments
- Raises:
ValueError – If length of instruments collection exceeds 1000
Example:
await kite.ltp('NSE:INFY') await kite.ltp(['NSE:INFY', 'NSE:RELIANCE', 'NSE:HDFCBANK'])
- async margins(segment: str | None = None) dict ¶
Returns funds, cash, and margin information for the user for equity and commodity segments
- Parameters:
segment (Optional[str]) – One of equity or commodity
- async modify_order(variety: str, order_id: str, quantity: int | None = None, price: float | None = None, order_type: str | None = None, trigger_price: float | None = None, validity: str | None = None, disclosed_quantity: int | None = None) dict ¶
Modify an open order.
- Parameters:
variety (str) – One of regular, co, amo, iceberg, auction
order_id (str)
quantity (Optional[int] = None)
price (Optional[float] = None)
order_type (Optional[str] = None)
trigger_price (Optional[float] = None)
validity (Optional[str] = None)
disclosed_quantity (Optional[int] = None)
- async ohlc(instruments: str | Collection[str]) dict ¶
Returns ohlc and last traded price
instrument identified by exchange:tradingsymbol example. NSE:INFY
- Parameters:
instruments – A str or collection of instruments
- Raises:
ValueError – If length of instruments collection exceeds 1000
Example:
await kite.ohlc('NSE:INFY') await kite.ohlc(['NSE:INFY', 'NSE:RELIANCE', 'NSE:HDFCBANK'])
- async order_history(order_id: str) dict ¶
Get history of individual orders
- Parameters:
order_id (str)
- async order_trades(order_id: str) dict ¶
Get the the trades generated by an order
- Parameters:
order_id (str)
- async orders() dict ¶
Get list of all orders for the day
- async place_order(variety: str, exchange: str, tradingsymbol: str, transaction_type: str, quantity: int, product: str, order_type: str, price: float | None = None, validity: str | None = None, validity_ttl: int | None = None, disclosed_quantity: int | None = None, trigger_price: float | None = None, iceberg_legs: int | None = None, iceberg_quantity: int | None = None, auction_number: str | None = None, tag: str | None = None) dict ¶
Place an order of a particular variety
- Parameters:
variety (str) – One of regular, co, amo, iceberg, auction
exchange (str,) – One of NSE, BSE, NFO, CDS, BFO, MCX, BCD
tradingsymbol (str) – Stock symbol name
transaction_type (str) – One of BUY or SELL
quantity (int) – Quantity to transact
product (str) – One of MIS, CNC, NRML, CO
order_type – One of MARKET, LIMIT, SL-M, SL
price (Optional[float] = None,) – The price to execute the order at (for LIMIT orders)
validity (Optional[str] = None) – One of DAY, IOC, TTL
validity_ttl (Optional[int] = None,) – Order life span in minutes for TTL validity orders
disclosed_quantity (Optional[int] = None) – Disclosed quantity (for equity trades)
trigger_price (Optional[float] = None) – Price at which an order should trigger (SL, SL-M)
iceberg_legs (Optional[int] = None) – Total number of legs for iceberg order type (Between 2 and 10)
iceberg_quantity (Optional[int] = None) – Split quantity for each iceberg leg order (qty/iceberg_legs)
auction_number (Optional[str] = None) – A unique identifier for a particular auction
tag (Optional[str] = None) – An optional tag to identify an order (alphanumeric, max 20 chars)
Parameters are not validated
- async positions() dict ¶
Retrieve the list of short term positions
- async profile() dict ¶
Retrieve the user profile
- async quote(instruments: str | Collection[str]) dict ¶
Return the full market quotes - ohlc, OI, bid/ask etc
instrument identified by exchange:tradingsymbol example. NSE:INFY
- Parameters:
instruments – A str or collection of instruments
- Raises:
ValueError – If length of instruments collection exceeds 500
Example:
await kite.quote('NSE:INFY') await kite.quote(['NSE:INFY', 'NSE:RELIANCE', 'NSE:HDFCBANK'])
- async trades() dict ¶
Get the list of all executed trades for the day
- class aio_trader.kite.KiteFeed(api_key: str = 'kitefront', user_id: str | None = None, enctoken: str | None = None, access_token: str | None = None, parse_data: bool = True, session: ClientSession | None = None)¶
Bases:
AbstractFeeder
Websocket class for Zerodha Kite
Implements the
AbstractFeeder
base class- Parameters:
api_key (str) – KiteConnect api_key. Default is “kitefront” for Web login.
user_id (Optional[str]) – Optional user_id for Kite Web login.
enctoken (Optional[str]) – Optional enctoken for Kite Web login.
access_token (Optional[str]) – Optional KiteConnect access_token.
parse_data (bool) – If true, on_tick handler receives raw binary/text data. Default True.
session (Optional[aiohttp.ClientSession].) – Client Session for making HTTP requests.
- Raises:
ValueError – If enctoken or access_token is not provided
ValueError – If enctoken is provided, but user_id is missing
ValueError – If access_token is provided, but api_key is the default value
- async close()¶
Perform clean up operations to gracefully exit
- async connect(**kwargs) None ¶
Connect and start the Websocket connection
Use the retry decorator @retry(max_retries=50, base_wait=2, max_wait=60)
- Parameters:
kwargs – Any keyword arguments to pass to aiohttp.ClientSession.ws_connect
- Type:
kwargs: Any
- async set_mode(mode: str, instrument_tokens: List[int] | Tuple[int])¶
Set streaming mode for the given list of tokens.
- Parameters:
mode (str) – Mode to set. It can be one of ltp, quote, or full
instrument_tokens (List[int] | Tuple[int]) – A collection of instrument tokens
- async subscribe(instrument_tokens: List[int] | Tuple[int])¶
Subscribe to a list of instrument_tokens.
- Parameters:
instrument_tokens (List[int] | Tuple[int]) – A collection of instrument tokens
- async unsubscribe(instrument_tokens: List[int] | Tuple[int])¶
Unsubscribe the given list of instrument_tokens.
- Parameters:
instrument_tokens (List[int] | Tuple[int]) – A collection of instrument tokens