Learn Algo Trading with Python | Codes | Youtube Series

Thanks @Tradehull_Imran, After fixing the code as suggested, I am able to fetch LTP

1 Like

DEAR SIR

as per your guideline i downloaded the new tradehull as u given,
i rum my code ,but it showing the error ,
BANKNIFTY 27 NOV 50400 CALL BANKNIFTY 27 NOV 50400 PUT 50400
Exception at calling ltp as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: None, ‘error_type’: None, ‘error_message’: None}, ‘data’: {‘data’: {‘805’: ‘Too many requests. Further requests may result in the user being blocked.’}, ‘status’: ‘failed’}}
LTP data fetch failed, retrying…
Exception at calling ltp as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: None, ‘error_type’: None, ‘error_message’: None}, ‘data’: {‘data’: {‘805’: ‘Too many requests. Further requests may result in the user being blocked.’}, ‘status’: ‘failed’}}
LTP data fetch failed, retrying…
Exception at calling ltp as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: None, ‘error_type’: None, ‘error_message’: None}, ‘data’: {‘data’: {‘805’: ‘Too many requests. Further requests may result in the user being blocked.’}, ‘status’: ‘failed’}}
LTP data fetch failed, retrying…
Exception at calling ltp as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: None, ‘error_type’: None, ‘error_message’: None}, ‘data’: {‘data’: {‘805’: ‘Too many requests. Further requests may result in the user being blocked.’}, ‘status’: ‘failed’}}
LTP data fetch failed, retrying…
LTP CALL: 462.9
LTP PUT: 416.8
EMA CALL: 475
EMA PUT: 410
Placing PUT order with limit price

here is my code if any improvement ,please correct it

import pdb
import time
import datetime
import traceback
import talib
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd

Initialize client details

client_code = “1103655452”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMyNTM3OTQxLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMzY1NTQ1MiJ9.fr_y6xjBJ8e6_Ey4xSFb8vbVfS8Bg3DOu2GQJ7NuEpiV0aKYAvKj7Bt8FxylYI4dYMUp1wBgTXe3MlsB3NKvkQ” # Replace with your actual token
tsl = Tradehull(client_code, token_id) # tradehull_support_library

Fetch balance and calculate risk limit

available_balance = tsl.get_balance()
max_risk_for_the_day = (available_balance * 1) / 100 * -1

print(“Available balance:”, available_balance)
print(“Max risk for the day:”, max_risk_for_the_day)

Select ATM Strike Price options for NIFTY

ce_name, pe_name, strike = tsl.ATM_Strike_Selection(‘BANKNIFTY’, ‘27-11-2024’)
print(ce_name, pe_name, strike)

Initialize variables

traded_watchlist =
target_profit = 50 # Set your desired profit target
trailing_sl = 10 # Set your trailing stop-loss

Define the function for updating stop-loss

def update_stop_loss(current_price, last_sl):
“”"
Update stop loss dynamically based on the trailing stop-loss value.
“”"
new_sl = max(last_sl, current_price - trailing_sl)
return new_sl

def calculate_limit_price(symbol, ltp, order_type):
“”"
Calculate the limit price based on the order type and current price (ltp).
For a CALL, set a limit slightly below the LTP. For a PUT, slightly above.
“”"
price_offset = 0.01 # 1% offset for limit price
if order_type == ‘buy_call’:
return ltp * (1 - price_offset) # 1% below LTP for CALL option

Main trading loop

try:
while True:
# Restrict trading hours to 9:16 AM to 2:55 PM
if not (datetime.time(9, 16) <= datetime.datetime.now().time() <= datetime.time(22, 55)):
time.sleep(60) # Sleep for 1 minute before checking again
continue

    # Fetch LTP for CALL and PUT options
    ltp1 = tsl.get_ltp_data(ce_name)
    ltp2 = tsl.get_ltp_data(pe_name)

    # Check if data is valid before proceeding
    if not ltp1 or not ltp2:
        print("LTP data fetch failed, retrying...")
        time.sleep(5)
        continue  # Skip to the next iteration if data is invalid

    ltp1_value = list(ltp1.values())[0] if ltp1 else None
    ltp2_value = list(ltp2.values())[0] if ltp2 else None

    if ltp1_value is None or ltp2_value is None:
        print("Received empty LTP data, retrying...")
        time.sleep(5)
        continue  # Skip if no valid LTP values are found


    # Fetch intraday data and calculate EMA for CALL and PUT options
    chart1 = tsl.get_historical_data(tradingsymbol= ce_name, exchange='NFO', timeframe="1")
    chart2 = tsl.get_historical_data(tradingsymbol= pe_name,  exchange='NFO', timeframe="1")

    chart1['ema'] = talib.EMA(chart1['close'], timeperiod=20)
    chart2['ema'] = talib.EMA(chart2['close'], timeperiod=20)

    # Get the last EMA values
    last_candle1 = chart1['ema'].iloc[-1]
    last_candle2 = chart2['ema'].iloc[-1]

    # Convert to integers if necessary
    last_candle_close1 = int(last_candle1 + 1)
    last_candle_close2 = int(last_candle2 + 1)

    print("LTP CALL:", ltp1_value)
    print("LTP PUT:", ltp2_value)
    print("EMA CALL:", last_candle_close1)
    print("EMA PUT:", last_candle_close2)

    # Check if CALL order condition is met and hasn't been placed yet
    if last_candle_close1 <= ltp1_value and ce_name not in traded_watchlist:
        print("Placing CALL order with limit price")
        limit_price_call = calculate_limit_price(ce_name, ltp1_value, 'buy_call')
        #entry_order_id1 = tsl.order_placement(ce_name, 'NFO', 25, limit_price_call, 0, 'LIMIT', 'BUY', 'MIS')
        traded_watchlist.append(ce_name)

        # Define initial target and stop-loss for CALL
        stop_loss_call = ltp1_value - trailing_sl
        last_sl_call = stop_loss_call  # Set last_sl as initial stop-loss for CALL
        target_call = ltp1_value + target_profit
        order_active_call = True

        # Monitor the CALL position
        while order_active_call:

            current_price_call = tsl.get_ltp_data(ce_name)
            current_price_call_1 = list(current_price_call.values())[0] 

            last_sl_call = update_stop_loss(current_price_call_1, last_sl_call)

            if current_price_call_1 <= last_sl_call:
                print("Trailing stop-loss hit for CALL, exiting position")
                #tsl.order_placement(ce_name, 'NFO', 25, limit_price_call, 0, 'LIMIT', 'SELL', 'MIS')
                order_active_call = False

            elif current_price_call_1 >= target_call:
                print("Target hit for CALL, exiting position")
                #tsl.order_placement(ce_name, 'NFO', 25, limit_price_call, 0, 'LIMIT', 'SELL', 'MIS')
                order_active_call = False

            # After exiting the trade, only remove from watchlist if EMA is above LTP
            if not order_active_call:
                # Recalculate the EMA for the next iteration check
                chart1 = tsl.get_historical_data(tradingsymbol= ce_name, exchange='NFO', timeframe="1")
                chart1['ema'] = talib.EMA(chart1['close'], timeperiod=20)
                last_candle_close1 = int(chart1['ema'].iloc[-1] + 1)
                ltp3 = tsl.get_ltp_data(ce_name)
                ltp3_value = list(ltp3.values())[0]
                
                # Check if EMA is now above LTP before allowing re-entry
                if last_candle_close1 > ltp3_value:
                    traded_watchlist.remove(ce_name)
                    print(f"{ce_name} removed from watchlist; EMA is now above LTP.")

            time.sleep(5)

    # Repeat similar logic for PUT options
    if last_candle_close2 <= ltp2_value and pe_name not in traded_watchlist:
        print("Placing PUT order with limit price")
        limit_price_put = calculate_limit_price(pe_name, ltp2_value, 'buy_put')
        #entry_order_id2 = tsl.order_placement(pe_name, 'NFO', 25, limit_price_put, 0, 'LIMIT', 'BUY', 'MIS')            
        traded_watchlist.append(pe_name)

        # Define initial target and stop-loss for PUT
        stop_loss_put = ltp2_value - trailing_sl
        last_sl_put = stop_loss_put  # Set last_sl as initial stop-loss for PUT
        target_put = ltp2_value + target_profit
        order_active_put = True

        # Monitor the PUT position
        while order_active_put:
            current_price_put = tsl.get_ltp_data(pe_name)
            current_price_put_1 = list(current_price_put.values())[0] 
            last_sl_put = update_stop_loss(current_price_put_1, last_sl_put)

            if current_price_put_1 <= last_sl_put:
                print("Trailing stop-loss hit for PUT, exiting position")
                #tsl.order_placement(pe_name, 'NFO', 25, limit_price_put, 0, 'LIMIT', 'SELL', 'MIS')
                order_active_put = False

            elif current_price_put_1 >= target_put:
                print("Target hit for PUT, exiting position")
                #tsl.order_placement(pe_name, 'NFO', 25, limit_price_put, 0, 'LIMIT', 'SELL', 'MIS')
                order_active_put = False

            # After exiting the trade, only remove from watchlist if EMA is above LTP
            if not order_active_put:
                chart2 = tsl.get_historical_data(tradingsymbol= pe_name,  exchange='NFO', timeframe="1")
                chart2['ema'] = talib.EMA(chart2['close'], timeperiod=20)
                last_candle_close2 = int(chart2['ema'].iloc[-1] + 1)
                ltp4 = tsl.get_ltp_data(pe_name)
                ltp4_value = list(ltp4.values())[0]
                
                # Check if EMA is now above LTP before allowing re-entry
                if last_candle_close2 > ltp4_value:
                    traded_watchlist.remove(pe_name)
                    print(f"{pe_name} removed from watchlist; EMA is now above LTP.")

            time.sleep(1)

    # Wait before the next iteration
    time.sleep(5)

except Exception as e:
print(“An error occurred:”, e)
print(traceback.format_exc())
pdb.set_trace()

@Tradehull_Imran,

Please help.

Hello @Tradehull_Imran sir,
Sorry very delay practice

last time it was working fine for

Dhan_Tradehull_V2 Algo || Learn Algo Trading

but I when I am trying with below files

I am getting

Hope already answer is somewhere here. I will try to find it out from my side also.

1 Like

@Tradehull_Imran sir
I think for this also I need to replace the Dhan_Tradehull_V2.py file as per below solution right ?

Hi @Tradehull_Imran,

Day before yesterday it was working fine.
When i was running today getting below error.
VWAP CODE:

	index_chart = tsl.get_historical_data(tradingsymbol='BANKNIFTY 27 NOV 50400 PUT', exchange='NFO', timeframe="1")
	print(index_chart)
	index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
	index_chart['vwap'] = pta.vwap(index_chart['high'], index_chart['low'], index_chart['close'], index_chart['volume'])

Copied latest Dhan_Tradehull_V2.py
Error:

Traceback (most recent call last):
  File "C:/Dhan/8. Session8- 2nd Live Algo/8. Session 8 Dhan_Tradehull_V2/vwap strategy.py", line 43, in <module>
    index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
AttributeError: 'NoneType' object has no attribute 'set_index'
None
C:\Dhan\8. Session8- 2nd Live Algo>pip show dhanhq
Name: dhanhq
Version: 2.0.0
Summary: The official Python client for communicating with the DhanHQ API
Home-page: https://dhanhq.co/
Author: Dhan
Author-email: dhan-oss@dhan.co
License: MIT LICENSE
Location: c:\python3.8\lib\site-packages
Requires: pandas, pyOpenSSL, requests, websockets

Hi
@Tradehull_Imran

I am trying today
But still it shows error
So How and when I will get the data and error will remove
And How Does it works

C:\Algo Practice\Api Upgrade>py RSI.py
Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-21.csv
Got the instrument file
available_balance 129364.75
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-905’, ‘error_type’: ‘Input_Exception’, ‘error_message’: ‘Missing required fields, bad values for parameters etc.’}, ‘data’: {‘errorType’: ‘Input_Exception’, ‘errorCode’: ‘DH-905’, ‘errorMessage’: ‘Missing required fields, bad values for parameters etc.’}}
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-905’, ‘error_type’: ‘Input_Exception’, ‘error_message’: ‘Missing required fields, bad values for parameters etc.’}, ‘data’: {‘errorType’: ‘Input_Exception’, ‘errorCode’: ‘DH-905’, ‘errorMessage’: ‘Missing required fields, bad values for parameters etc.’}}
Traceback (most recent call last):
File “RSI.py”, line 46, in
chart_15[‘rsi’] = talib.RSI(chart_15[‘close’], timeperiod=14) #pandas
TypeError: ‘NoneType’ object is not subscriptable

Hi @Deodas_kumar

The issue is of rate limit
Too many requests. Further requests may result in the user being blocked.

for solution check : Learn Algo Trading with Python | Codes | Youtube Series - #860 by Tradehull_Imran

Hi @Aijaz_Ahmad

This is related to order cancellation
I will check your question in live market tomorrow

Hye Sir @Tradehull_Imran

Suppose I enter a trade when the condition is met, e.g., Close > EMA, and my take profit is set to 10 points.
After booking the profit, the code enters a new trade again because the condition is still true.

However, I don’t want it to re-enter immediately. I want to trade only when the next signal comes. Please help

Hi @Deodas_kumar
Also modify your code to use less calls

New code


while True:

	time.sleep(2)


	try:
		ltp_ce_pe = tsl.get_ltp_data([ce_name, pe_name])
		ltp1 = ltp_ce_pe[ce_name]
		ltp2 = ltp_ce_pe[pe_name]
	except Exception as e:
	    print("Received empty LTP data, retrying...", e)
		continue

New code is a replacement for


while True:


	# Fetch LTP for CALL and PUT options
	ltp1 = tsl.get_ltp_data(ce_name)
	ltp2 = tsl.get_ltp_data(pe_name)

	# Check if data is valid before proceeding
	if not ltp1 or not ltp2:
	    print("LTP data fetch failed, retrying...")
	    time.sleep(5)
	    continue  # Skip to the next iteration if data is invalid

	ltp1_value = list(ltp1.values())[0] if ltp1 else None
	ltp2_value = list(ltp2.values())[0] if ltp2 else None

	if ltp1_value is None or ltp2_value is None:
	    print("Received empty LTP data, retrying...")
	    time.sleep(5)
	    continue  # Skip if no valid LTP values are found

Hi @Kalpeshh_Patel
see : Learn Algo Trading with Python | Codes | Youtube Series - #942 by Tradehull_Imran

Hi @Subhajitpanja
yes its correct
use : Dhan_Tradehull_V2.py - Google Drive

1 Like

Hi @Minakshi_Kuila

Error says it cannot get data for index_chart, so its not able to plot vwap

use this file : Dhan_Tradehull_V2.py - Google Drive

Hi @Zee2Zahid

How to manage re-entry and trade details, This concept I have not covered till now. will add the same in upcoming videos.

Hi
@Tradehull_Imran

As per chart
If my one strategy requires following parameters

tsl = Tradehull(client_code,token_id)

chart_1 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = ‘NSE’,timeframe=“5”)

chart_1[‘rsi’] = talib.RSI(chart_1[‘close’], timeperiod=14) #pandas

chart_15 = tsl.get_intraday_data(stock_name, ‘NSE’, 15) # 15 minute chart

chart_15 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = ‘NSE’,timeframe=“15”) # this call has been updated to get_historical_data call,

buy_entry_orderid = tsl.order_placement(stock_name,‘NSE’, 1, 0, 0, ‘MARKET’, ‘BUY’, ‘MIS’)

live_pnl = tsl.get_live_pnl()

I_want_to_trade_no_more = tsl.kill_switch(‘ON’)

order_details = tsl.cancel_all_orders()

sl_orderid = tsl.order_placement(stock_name,‘NSE’, 1, 0, sl_price, ‘STOPMARKET’, ‘SELL’, ‘MIS’)


As per above parameter which I demand
Means I requested 10 DATA API

Is that right???

Hi @Kalpeshh_Patel

Yes it is correct

note:
chart_1[‘rsi’] = talib.RSI(chart_1[‘close’], timeperiod=14) …
is not a api call… its just a calculation.

Hi
@Tradehull_Imran

Understand

But what 10 stocks in watchlist and one parameter of given as follows

watchlist = [‘MOTHERSON’, ‘OFSS’, ‘MANAPPURAM’, ‘BSOFT’, ‘CHAMBLFERT’, ‘DIXON’, ‘NATIONALUM’, ‘DLF’, ‘IDEA’, ‘ADANIPORTS’]

chart_15 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = ‘NSE’,timeframe=“15”)


It means 10 DATA API requested

Is it right?

wanted to share this…
found accurate Nifty expiries for last 3 years,

Actually this is a difficult data to get because expiry dates may be influenced by NSE holidays.

07-Jan-2021, 14-Jan-2021, 21-Jan-2021, 28-Jan-2021, 04-Feb-2021, 11-Feb-2021, 18-Feb-2021, 25-Feb-2021, 04-Mar-2021, 10-Mar-2021, 18-Mar-2021, 25-Mar-2021, 01-Apr-2021, 08-Apr-2021, 15-Apr-2021, 22-Apr-2021, 29-Apr-2021, 06-May-2021, 12-May-2021, 20-May-2021, 27-May-2021, 03-Jun-2021, 10-Jun-2021, 17-Jun-2021, 24-Jun-2021, 01-Jul-2021, 08-Jul-2021, 15-Jul-2021, 22-Jul-2021, 29-Jul-2021, 05-Aug-2021, 12-Aug-2021, 18-Aug-2021, 26-Aug-2021, 02-Sep-2021, 09-Sep-2021, 16-Sep-2021, 23-Sep-2021, 30-Sep-2021, 07-Oct-2021, 14-Oct-2021, 21-Oct-2021, 28-Oct-2021, 03-Nov-2021, 11-Nov-2021, 18-Nov-2021, 25-Nov-2021, 02-Dec-2021, 09-Dec-2021, 16-Dec-2021, 23-Dec-2021, 30-Dec-2021, 06-Jan-2022, 13-Jan-2022, 20-Jan-2022, 27-Jan-2022, 03-Feb-2022, 10-Feb-2022, 17-Feb-2022, 24-Feb-2022, 03-Mar-2022, 10-Mar-2022, 17-Mar-2022, 24-Mar-2022, 31-Mar-2022, 07-Apr-2022, 13-Apr-2022, 21-Apr-2022, 28-Apr-2022, 05-May-2022, 12-May-2022, 19-May-2022, 26-May-2022, 02-Jun-2022, 09-Jun-2022, 16-Jun-2022, 23-Jun-2022, 30-Jun-2022, 07-Jul-2022, 14-Jul-2022, 21-Jul-2022, 28-Jul-2022, 04-Aug-2022, 11-Aug-2022, 18-Aug-2022, 25-Aug-2022, 01-Sep-2022, 08-Sep-2022, 15-Sep-2022, 22-Sep-2022, 29-Sep-2022, 06-Oct-2022, 13-Oct-2022, 20-Oct-2022, 27-Oct-2022, 03-Nov-2022, 10-Nov-2022, 17-Nov-2022, 24-Nov-2022, 01-Dec-2022, 08-Dec-2022, 15-Dec-2022, 22-Dec-2022, 29-Dec-2022, 05-Jan-2023, 12-Jan-2023, 19-Jan-2023, 25-Jan-2023, 02-Feb-2023, 09-Feb-2023, 16-Feb-2023, 23-Feb-2023, 02-Mar-2023, 09-Mar-2023, 16-Mar-2023, 23-Mar-2023, 29-Mar-2023, 06-Apr-2023, 13-Apr-2023, 20-Apr-2023, 27-Apr-2023, 04-May-2023, 11-May-2023, 18-May-2023, 25-May-2023, 01-Jun-2023, 08-Jun-2023, 15-Jun-2023, 22-Jun-2023, 28-Jun-2023, 29-Jun-2023, 06-Jul-2023, 13-Jul-2023, 20-Jul-2023, 27-Jul-2023, 03-Aug-2023, 10-Aug-2023, 17-Aug-2023, 24-Aug-2023, 31-Aug-2023, 07-Sep-2023, 14-Sep-2023, 21-Sep-2023, 28-Sep-2023, 05-Oct-2023, 12-Oct-2023, 19-Oct-2023, 26-Oct-2023, 02-Nov-2023, 09-Nov-2023, 16-Nov-2023, 23-Nov-2023, 30-Nov-2023, 07-Dec-2023, 14-Dec-2023, 21-Dec-2023, 28-Dec-2023, 04-Jan-2024, 11-Jan-2024, 18-Jan-2024, 25-Jan-2024, 01-Feb-2024, 08-Feb-2024, 15-Feb-2024, 22-Feb-2024, 29-Feb-2024, 07-Mar-2024, 14-Mar-2024, 21-Mar-2024, 28-Mar-2024, 04-Apr-2024, 10-Apr-2024, 18-Apr-2024, 25-Apr-2024, 02-May-2024, 09-May-2024, 16-May-2024, 23-May-2024, 30-May-2024, 06-Jun-2024, 13-Jun-2024, 20-Jun-2024, 27-Jun-2024, 04-Jul-2024, 11-Jul-2024, 18-Jul-2024, 25-Jul-2024, 01-Aug-2024, 08-Aug-2024, 14-Aug-2024, 22-Aug-2024, 29-Aug-2024, 05-Sep-2024, 12-Sep-2024, 19-Sep-2024, 26-Sep-2024, 03-Oct-2024, 10-Oct-2024, 17-Oct-2024, 24-Oct-2024, 31-Oct-2024, 07-Nov-2024, 14-Nov-2024, 21-Nov-2024, 28-Nov-2024, 05-Dec-2024, 12-Dec-2024, 19-Dec-2024, 26-Dec-2024, 
1 Like

@Tradehull_Imran sir it’s working

1 Like