A Zerodha Codebase from TradeHull
Project description
Zerodha TradeHull Codebase Project
This project is built to interact with the Zerodha API using the Tradehull
library. It provides a comprehensive suite of tools for trading, fetching market data, placing orders, and analyzing options.
Features
- Fetch Market Data: Get Live Trading Price (LTP), historical data.
- Order Placement: Place, modify, or cancel orders with various parameters.
- Option Greeks: Retrieve Greeks like Delta, Theta, Gamma, and Vega for options.
- Option Strike Selection: Automate ATM, ITM, and OTM strike price identification.
- Portfolio Management: Fetch holdings, positions, and balances.
Installation
To install the Tradehull package:
pip install Zerodha-Tradehull
Install required dependencies:
pip install -r requirements.txt
Upgrade Tradehull Package
To update the Tradehull package:
pip install --upgrade Zerodha-Tradehull
Usage
Zerodha API Authentication
Update the api_key
and api_secret
with your Zerodha API credentials:
from Zerodha_Tradehull import Tradehull
api_key = "your_api_key"
api_secret = "your_api_secret"
tsl = Tradehull(api_key, api_secret, "yes")
# get kite object
kite = tsl.kite
Key Functionalities
1. Fetch Live Market Data
Get LTP (Last Traded Price)
Function:
tsl.get_data_for_single_script(exchange: str, name: str, call_type: str)
Arguments:
exchange
(str): The exchange where the instrument is traded (e.g., 'NSE').name
(str): The name of the instrument (e.g., 'ACC').call_type
(str): Type of data to fetch ('ltp', 'ohlc', 'quote').
Sample Code:
ltp = tsl.get_data_for_single_script(exchange="NSE", name="ACC", call_type ="ltp")
print(ltp)
Get OHLC (Open, High, Low, Close)
Sample Code:
OHLC_data = tsl.get_data_for_single_script(exchange="NSE", name="ACC", call_type ="ohlc")
print(OHLC_data)
Get Quote Data
Sample Code:
quote = tsl.get_data_for_single_script(exchange="NSE", name="ACC", call_type ="quote")
print(quote)
2. Fetch Historical Data
Get Short-Term Historical Data
Function:
tsl.get_short_length_hist_data(name: str, exchange: str, interval: str, oi: bool = False)
- Arguments:
name
(str): The trading symbol of the instrument (e.g., "ACC").exchange
(str): The exchange where the instrument is traded (e.g., "NSE").interval
(str): The timeframe for the data. Possible values are:- "minute": 30 days
- "hour": 365 days
- "day": 2000 days
- "3minute": 90 days
- "5minute": 90 days
- "10minute": 90 days
- "15minute": 180 days
- "30minute": 180 days
- "60minute": 365 days
oi
(bool, optional): Whether to include Open Interest data. Default isFalse
.
Sample Code:
data = tsl.get_short_length_hist_data(name="ACC", exchange="NSE", interval="minute", oi=True)
print(data)
Get Long-Term Historical Data
Function:
tsl.get_long_length_hist_data(name: str, exchange: str, interval: str, length: int, oi: bool = False)
- Arguments:
name
(str): The trading symbol of the instrument (e.g., "ACC").exchange
(str): The exchange where the instrument is traded (e.g., "NSE").interval
(str): The timeframe for the data. Possible values are:- "minute": 60 days
- "3minute": 100 days
- "5minute": 100 days
- "10minute": 100 days
- "15minute": 200 days
- "30minute": 200 days
- "60minute": 400 days
- "day": 2000 days
from_date
(str): The start date for historical data retrieval (format: "YYYY-MM-DD").to_date
(str): The end date for historical data retrieval (format: "YYYY-MM-DD").oi
(bool, optional): Whether to include Open Interest data. Default isFalse
.
Sample Code:
data = tsl.get_long_length_hist_data(name="ACC", exchange="NSE", interval="5minute", length=1000, oi=True)
print(data)
3. Option Strike Selection
Get ATM (At The Money) Strike
Function:
tsl.get_atm(ltp: float, underlying: str, expiry: int, script_type: str)
- Arguments:
ltp
(float): Last traded price of the underlying.underlying
(str): The index name (e.g., "NIFTY", "BANKNIFTY").expiry
(int): The expiry to select.0
- Current expiry1
- Next expiry2
- Third expiry from now
script_type
(str): Option type ("CE"
for Call,"PE"
for Put).
Sample Code:
Nifty_ltp = tsl.get_data_for_single_script(exchange="NSE", name="NIFTY 50", call_type ="ltp")
atm = tsl.get_atm(ltp=Nifty_ltp, underlying="NIFTY 50", expiry=0, script_type="CE")
print(atm)
Get ITM (In The Money) Strike
Function:
tsl.get_itm(ltp: float, underlying: str, expiry: int, script_type: str, multiplier: int)
- Arguments:
ltp
(float): Last traded price of the underlying.underlying
(str): The index name (e.g., "NIFTY", "BANKNIFTY").expiry
(int): The expiry to select.0
- Current expiry1
- Next expiry2
- Third expiry from now
script_type
(str): Option type ("CE"
for Call,"PE"
for Put).multiplier
(int): Number of strikes away from ATM for ITM selection.
Sample Code:
Nifty_ltp = tsl.get_data_for_single_script(exchange="NSE", name="NIFTY 50", call_type ="ltp")
itm = tsl.get_itm(ltp=Nifty_ltp, underlying="NIFTY 50", expiry=0, multiplier=2, script_type="CE")
print(itm)
Get OTM (Out of The Money) Strike
Function:
tsl.get_otm(ltp: float, underlying: str, expiry: int, script_type: str, multiplier: int)
- Arguments:
ltp
(float): Last traded price of the underlying.underlying
(str): The index name (e.g., "NIFTY", "BANKNIFTY").expiry
(int): The expiry to select.0
- Current expiry1
- Next expiry2
- Third expiry from now
script_type
(str): Option type ("CE"
for Call,"PE"
for Put).multiplier
(int): Number of strikes away from ATM for OTM selection.
Sample Code:
Nifty_ltp = tsl.get_data_for_single_script(exchange="NSE", name="NIFTY 50", call_type ="ltp")
otm = tsl.get_otm(ltp=Nifty_ltp, underlying="NIFTY 50", expiry=0, multiplier=2, script_type="CE")
print(otm)
4. Option Greeks
Get Option Greeks
Function:
tsl.get_option_greek(strike: int, expiry_date: str, asset: str, interest_rate: float, flag: str, scrip_type: str)
Arguments:
strike
(int): Option strike price.expiry_date
(str): Expiry date ("YYYY-MM-DD"
).asset
(str): Underlying asset name.interest_rate
(float): Risk-free interest rate.flag
(str): Greek value to fetch ("delta"
,"theta"
,"theta"
,etc.).price
- Option price.delta
- Delta value.delta2
- Second-order delta.theta
- Theta value.rho
- Rho value.vega
- Vega value.gamma
- Gamma value.all_val
- All Greeks values in a dictionary.
scrip_type
(str): Option type ("CE"
or"PE"
).
Sample Code:
ce_delta = tsl.get_option_greek(strike=22250, expiry_date="2025-03-13", asset="NIFTY 50", interest_rate=10, flag="delta", scrip_type="CE")
print(ce_delta)
5. Order Placement and Management
Place Order
Function:
tsl.place_order(variety: str, exchange: str, tradingsymbol: str, transaction_type: str, quantity: int, product: str, order_type: str, price: float = None, validity: str = None, disclosed_quantity: int = None, trigger_price: float = None, validity_ttl: int = None, iceberg_legs: int = None, iceberg_quantity: int = None, auction_number : str = None , tag: str = None)
Arguments:
variety
(str): Order variety ("regular"
,"amo"
,"co"
,"iceberg"
,"auction"
).exchange
(str): Exchange ("NSE"
,"BSE"
,"NFO"
,"BFO"
,"CDS"
,"BCD"
,"MCX"
).tradingsymbol
(str): Tradingsymbol of the instrument.transaction_type
(str):"BUY"
or"SELL"
.quantity
(int): Number of shares or lots to trade.product
(str): Product type ("CNC"
,"NRML"
,"MIS"
,"MTF"
).order_type
(str): Order type ("MARKET"
,"LIMIT"
,"SL"
,"SL-M"
).price
(float, optional): Price for limit orders.trigger_price
(float, optional): Stop-loss trigger price.validity
(str, optional): Order validity ("DAY"
,"IOC"
,"TTL"
).disclosed_quantity
(int, optional): Disclosed order quantity.validity_ttl
(int, optional): TTL order life span in minutes.iceberg_legs
(int, optional): Total legs for iceberg order.iceberg_quantity
(int, optional): Quantity per iceberg leg.
Sample Code:
order_id = tsl.place_order(variety="regular", exchange='NSE', tradingsymbol='GAIL', transaction_type='SELL', quantity=5, product="MIS", order_type="MARKET")
print(order_id)
Modify Order
Function:
tsl.modify_order(variety: str, order_id: str, quantity: int = None, price: float = None, order_type: str = None, trigger_price: float = None, disclosed_quantity: int = None, validity: str = None)
Arguments:
variety
(str): Order variety ("regular"
,"co"
).order_id
(str): Unique order ID.quantity
(int, optional): Modified order quantity.price
(float, optional): Modified price for limit orders.order_type
(str, optional): Modified order type ("LIMIT"
,"SL"
, etc.).trigger_price
(float, optional): New stop-loss trigger price.disclosed_quantity
(int, optional): New disclosed quantity.validity
(str, optional): New order validity.
Sample Code:
modified_order_id = tsl.modify_order(variety=kite.VARIETY_REGULAR, order_id='220722001346805', quantity=5, trigger_price=54)
print(modified_order_id)
Cancel Order
Function:
tsl.market_over_close_all_order()
Sample Code:
tsl.market_over_close_all_order()
Get Executed Price
Retrieve the average executed price of any order.
Function:
tsl.get_executed_price(order_id: int)
Arguments:
order_id
(int): The unique order ID for which the executed price is needed.
Returns:
float
: The average executed price of the order.
Example:
# Get executed price of an order
price = tsl.get_executed_price(order_id = 220722001332188)
print(price)
Get Executed Time
Retrieve the execution time of any order.
Function:
tsl.get_executed_time(order_id: int)
Arguments:
order_id
(int): The unique order ID for which the execution time is needed.
Returns:
str
: The execution time of the order in string format.
Example:
# Get execution time of an order
time = tsl.get_executed_time(order_id = 220722001332188)
print(time)
6. Portfolio Management
Get Live PNL
Retrieve real-time Profit and Loss (PNL) calculation for all open positions.
Function:
tsl.get_live_pnl()
Returns:
float
: Total PNL across all positions- Positive value indicates profit
- Negative value indicates loss
0
: If no open positions existNone
: If there was an error
Example:
# Get live PNL
pnl = tsl.get_live_pnl()
print(pnl)
Get Order Status
Sample Code:
status = tsl.get_order_status('220722001346805')
print(status)
7. Get Lot Size
Retrieve the lot size for a given instrument.
Function:
tsl.get_lot_size(script_name: str)
Arguments:
script_name
(str): Trading symbol/Description (e.g., 'NIFTY25MAR22000PE', 'RELIANCE')
Example:
# Get lot size for NIFTY options
lot_size = tsl.get_lot_size("NIFTY25MAR22000PE")
8. Check Valid Instrument
Verify if a given instrument name exists in the exchange.
Function:
tsl.check_valid_instrument(name: str)
Arguments:
name
(str): Trading symbol/Description (e.g., 'NIFTY25MAR22300PE', 'ACC')
Returns:
str
: Message indicating if the instrument is valid or invalid"instrument {name} is valid"
if found"instrument {name} is invalid"
if not found
None
: If there was an error
Example:
# Check if NIFTY option exists
result = tsl.check_valid_instrument("NIFTY25MAR22750PE")
9. Telegram Alerts
Send real-time alerts and notifications via Telegram bot.
Function:
tsl.send_telegram_alert(message: str, receiver_chat_id: str, bot_token: str)
Arguments:
message
(str): The text message to send- Can include trade details, alerts, or any notification text
- Supports basic text formatting
receiver_chat_id
(str): Telegram chat ID for message delivery- For individual users: Personal chat ID
- For groups: Group chat ID (bot must be added to group)
bot_token
(str): Telegram bot authorization token- Obtained from BotFather when creating a bot
- Format: "123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Returns:
None
- Prints success/failure message to console
- Logs exceptions if any error occurs
Setup Steps:
- Create a Telegram bot via BotFather
- Get the bot token
- Add bot to the desired chat/group
- Get chat ID for the target recipient
Sample Code:
# Send trade execution alert
tsl.send_telegram_alert(
message="Order executed: BUY 50 shares of RELIANCE @ 2400",
receiver_chat_id="123456789",
bot_token="123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
# Send market alert
tsl.send_telegram_alert(
message="NIFTY crossed 19000!",
receiver_chat_id="987654321",
bot_token="123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
License
This project is licensed under the MIT License. See the LICENSE file for details.
Contact
For queries or issues, please contact: contact.tradehull@gmail.com
.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
File details
Details for the file Zerodha_Tradehull-1.0.1-py3-none-any.whl
.
File metadata
- Download URL: Zerodha_Tradehull-1.0.1-py3-none-any.whl
- Upload date:
- Size: 16.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.8.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2cdf4be2b6e00f091424c9e00f236f97e28d96d76b95ee945c9b08d46394ce3f |
|
MD5 | b9f55810ace25623acb5e91b7662ed1e |
|
BLAKE2b-256 | 625e500decb7cc20b0672d670fa887fac3f7884fbc0627a5a597f74d0e971c75 |