Learn Algo Trading with Python | Codes | Youtube Series

Hi everyone,

  1. 8th session video is scheduled for today

  2. Also I have update 8th session code to match with dhanhq 2.0.0
    files link : https://drive.google.com/file/d/1GyOX0KSSYjrWHIR2tMJ7uB66D5L7Ehsf/view?usp=drive_link

  3. Update to dhanhq 2.0.0 before running files for session 8
    use

    pip install --upgrade dhanhq
2 Likes

@Tradehull_Imran Sir, I am unable to fetch previous historical data. Getting this error. Please guide.

Hi @TusharKB
See below steps for the fix
https://private-poc.madefortrade.in/t/learn-algo-trading-with-python-codes-youtube-series/32718/179

Error resolved. I’m able to place orders now. Thanks a lot!

Hope so @Tradehull_Imran Sir. I am keeping my fingers crossed

@Dhan

Hi Sir! On running the websocket file, I’m getting message that websocket is disconnected. Certificate verify failed. Please help

Getting this error on codebase file: unable to fetch available balance. Please help resolve @Tradehull_Imran

could you please let us know how to send signal to Telegram group whenever placed any order from the script???

Hi @Tradehull_Imran thanks for support, please give me access to this drive

import time
import datetime
import pandas as pd
from Dhan_Tradehull import Tradehull

client_code = “11”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMxNzcxMDU4LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMTUyOTQ5MyJ9.Oo3_dwF1lGkiSenKu-XdpsMZIav5og-BK2CxzuTPyaAZGyUMDJEb_lCaTOLXwydfeeXbwzeKRs3pHXhlosKGGQ”
tsl = Tradehull(client_code,token_id) # tradehull_support_library

def get_strike_price(symbol, exchange):
data = tsl.get_option_chain(symbol, exchange) # Assume an option chain API exists
valid_options = [opt for opt in data if opt[‘premium’] > 95]
selected_option = valid_options[0] if valid_options else None
return selected_option

def execute_trade(side, symbol, price, strike_price, qty=1):
# Execute buy/sell based on side and manage stop loss
entry_price = price
stop_loss = entry_price - 6 if side == “PE” else entry_price + 6
tsl.place_order(symbol, side, qty, strike_price) # Placeholder for trade execution
return {“entry_price”: entry_price, “stop_loss”: stop_loss, “strike_price”: strike_price}

def main():
trade_executions = {“CE”: 0, “PE”: 0}
max_executions = 4
initial_time = datetime.time(9, 20)
exit_time = datetime.time(12, 50)
max_loss = -1000
max_profit = 600
pnl = 0
open_positions = {“CE”: None, “PE”: None}

while True:
    current_time = datetime.datetime.now().time()
    if current_time < initial_time:
        time.sleep(60)
        continue
    elif current_time >= exit_time or pnl <= max_loss or pnl >= max_profit:
        tsl.exit_all_positions()
        break
    
    for side in ["CE", "PE"]:
        if open_positions[side] is None and trade_executions[side] < max_executions:
            selected_option = get_strike_price("NIFTY", "NSE")
            if selected_option:
                strike_price = selected_option['strike_price']
                premium_price = selected_option['premium']
                
                # Check for 10% increment condition
                while True:
                    new_premium = tsl.get_ltp(f"NIFTY {strike_price} {side}")
                    if new_premium >= premium_price * 1.10:
                        trade_data = execute_trade(side, "NIFTY", new_premium, strike_price)
                        open_positions[side] = trade_data
                        trade_executions[side] += 1
                        break
                    time.sleep(5)  # Re-check every 5 seconds
            
        elif open_positions[side]:
            # Check for stop loss
            ltp = tsl.get_ltp(f"NIFTY {open_positions[side]['strike_price']} {side}")
            if (side == "CE" and ltp <= open_positions[side]["stop_loss"]) or \
               (side == "PE" and ltp >= open_positions[side]["stop_loss"]):
                tsl.exit_position(open_positions[side]['strike_price'], side)
                pnl -= 6  # Assuming 6 points loss per stop loss hit
                open_positions[side] = None

    # Update PnL check and exit if criteria met
    pnl = tsl.calculate_pnl()  # Placeholder for calculating PnL from executed trades
    time.sleep(60)  # Run the loop every minute

if name == “main”:
main()

@Tradehull_Imran hi mene ye algo likhi hai isme mujhe kuch function likhna hai jo Dhan_Tradehull.py me nhi hai please help me

algo hai
9:20AM ko 95 see upr ka premium select krna hai PE and CE dono ka or jo premium 10% increase ho jaye usme trade le le 6 points ka sl ke sath
or exit condtion 12:50PM ya 1000 ka loss ho ya 600 ka profit ho
isme 4 bar PE side ka trade le skta hai 4 bar hi CE side ka trade le skta hai

please help me

@Tradehull_Imran Sir, I tried on original file Dhan_codebase usage.py with pdb and without pdb too, still getting error. I have not yet subscribed to Dhan Data API. Is it because of that i am getting error?

Hi @CapTn_Mohit
Try these steps
https://private-poc.madefortrade.in/t/learn-algo-trading-with-python-codes-youtube-series/32718/177?u=tradehull_imran

1 Like

today I’m excited & waiting for V2 :v: :boom:

1 Like

Hi @deepV
Dhanhq does not support last 2 months of historical data
Although data from last 6 days can be fetched now in dhanhq 2.0.0

Hi @Samis ,
the link is now open.

Hi @rahulcse56

For telegram integration use below code

bot_token = "place_your_bot_token_here"
receiver_chat_id = "your_receiver_chat_id" 
message = "This message from Algo"


send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + receiver_chat_id + '&text=' + message
response = requests.get(send_text)

Hi @TusharKB

Yes Dhan Data Api, needs to be subscribed.

Hi @Vijen_Singh

The code seems to be okey, what is the exact issue/function that you need help with.

@Tradehull_Imran
exit_all_positions() ka function nhi likha hai
tsl.get_option_chain(symbol, exchange)
ye bhi nhi hai
get_strike_price(“NIFTY”, “NSE”)

tsl.calculate_pnl()

ye sare function nhi mil rhe hai

@Tradehull_Imran

2 issues/queries.

  1. Facing below issue, plz guide.

    is the tradehull file got updated? if yes , plz provide new link.
  2. I am working guy not getting time to test my algo during markets hours is there any way to test my script outside of market hours with historical data (live data is not required) to do backtest of my strategy. Are you covering this point in upcoming videos?