Skip to main content

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")

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:

open_, high, low, close = tsl.get_data_for_single_script(exchange="NSE", name="ACC", call_type ="ohlc")
print(open_, high, low, close)

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 is False.

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 is False.

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 expiry
      • 1 - Next expiry
      • 2 - Third expiry from now
    • script_type (str): Option type ("CE" for Call, "PE" for Put).

Sample Code:

atm = tsl.get_atm(ltp=18000, 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 expiry
      • 1 - Next expiry
      • 2 - 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:

itm = tsl.get_itm(ltp=18000, 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 expiry
      • 1 - Next expiry
      • 2 - 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:

otm = tsl.get_otm(ltp=18000, 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", etc.).
  • scrip_type (str): Option type ("CE" or "PE").

Sample Code:

ce_delta = tsl.get_option_greek(strike=38400, expiry_date="2022-08-11", asset="NIFTY BANK", 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()

6. Portfolio Management

Get Live PNL

Retrieve real-time Profit and Loss (PNL) calculation for all open positions.

Function:

tsl.get_pnl()

Returns:

  • float: Total PNL across all positions
    • Positive value indicates profit
    • Negative value indicates loss
  • 0: If no open positions exist
  • None: If there was an error

Example:

# Get live PNL
pnl = tsl.get_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:

  1. Create a Telegram bot via BotFather
  2. Get the bot token
  3. Add bot to the desired chat/group
  4. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

Zerodha_Tradehull-1.0.0-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file Zerodha_Tradehull-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for Zerodha_Tradehull-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5f852e80b8409a6be1f7344d814a14ba7be46a2685cbb40106e1b76bbccb57bb
MD5 beec5056bf6ad61546d517a3b01fc884
BLAKE2b-256 fa4a0f493979cb58eb0f114c416f3f79628714b29a15aaf835aaf2432c29256b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page