Learn Algo Trading with Python | Codes | Youtube Series

Hi, @Tradehull_Imran , Sir,

What is the Code for Range Candle Break Out, for example from 10.10 am to 10.40 am high/low break out. :slightly_smiling_face:

Hi Imran - how many codebase zip files you have made available so far out of 10 sessions? not able to locate where they all are.

@Tradehull_Imran Sir, I encountered this error. How can I resolve it?

Thanks it is working now.

2 Likes

Latest updated Code Base :- Learn Algo Trading with Python | Codes | Youtube Series - #1991 by Tradehull_Imran

1 Like

@Kanha_Meher , It is Rate Limit Issue, Run the Algo Tomorrow…

For more information :- Learn Algo Trading with Python | Codes | Youtube Series - #1557 by thakurmhn

1 Like

Hi, tradehall@imran,

chart_5 = tsl.get_historical_data(tradingsymbol = stock_name, exchange = ‘NSE’,timeframe=“5”) # Upgraded 5 minute chart according to Dhan_Tradehull_V2
cc_5 = chart_5.iloc[-1] # pandas
------ is [ -1] running candel or completed candel? pls. explain

@SUKANTA_MONDAL1 , [ -1] is running candle and [ -2] is completed candle…

2 Likes

traded_candle = ‘2025-1-2 10:10:00+05:30’
data_15 = tsl.get_historical_data(tradingsymbol=stock, exchange=‘NSE’, timeframe=“15”)
data_15 = data_15.set_index(data_15[‘timestamp’])
trade_candle = data_15.loc[traded_candle ] Use this code


plese slove this error

@Tradehull_Imran Getting

tsl.ITM_Strike_Selection(NIFTY, 0, 3)

Getting Error at OTM strike Selection as Unable to find the ITM strike for the NIFTY
Exception in Getting OHLC data as 'NoneType' object has no attribute 'upper'

Its was working yesterday :frowning_face:

Update: works for SENSEX

@Tradehull_Imran Is it possible to cache the instrument file locally after the initial download.

This BOT Is Picking New File From Dhan
Got the instrument file

Its taking around 20-30 seconds to process each time. Its kind a delaying the script development

Hi @Kishore007

Use this code for range breakout



chart = tsl.get_historical_data(tradingsymbol = 'NIFTY',exchange = 'INDEX',timeframe="5")
chart =  chart.set_index(chart['timestamp'])


# get todays date in this format 2025-01-01
today_date = datetime.datetime.now().strftime("%Y-%m-%d")
start_time = today_date + " 09:20:00"
end_time   = today_date + " 09:40:00"

range_chart = chart[start_time:end_time]
range_chart_high  = range_chart['high']
range_chart_low   = range_chart['low']




bc1 = ltp > range_chart_high
sc2 = ltp < range_chart_low




1 Like

Hi @Gaurav_Kumar2

It seems that you are using python 3.11.3.
we need to use python 3.8.0 …

so do uninstall python 3.11.3 and then retry the installation

we use older python versions, because they are supported by all the major libraries for algo trading.
Newer version may or may not support algo trading libraries, example : Ta-Lib

Hi @Rajashekhar_Rangappa

Instrument files gets a fresh download once per day,
so on the next run we just read it… which may still take 20-30 seconds as the file is of 20 MB.

but yes, it feels too slow… I will check on this.

1 Like

@Tradehull_Imran
error


import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings

warnings.filterwarnings(“ignore”)

---------------for dhan login ----------------

client_code = “”
token_id = “”

tsl = Tradehull(client_code,token_id)
available_balance = tsl.get_balance()
leveraged_margin = available_balance2
max_trades = 3
per_trade_margin = (leveraged_margin/max_trades)
max_loss = (available_balance
1)/100*-1

traded = “no”
trade_info = {“options_name”:None, “qty”:None, “sl”:None, “CE_PE”:None}

while True:
live_pnl = tsl.get_live_pnl()
# current_time = datetime.datetime.now()
current_time = datetime.datetime.now().time() #time only
# print(current_time)
if current_time < datetime.time(9, 45, 00):
print (“Wait market to open”, current_time)
continue
if current_time> datetime.time(15, 15, 30) or(live_pnl <max_loss):
i_want_to_trade_no_more = tsl.kill_switch(‘ON’)
order_details = tsl.cancel_all_orders()
print (“Market is over or MAX LOSS, Bye for Now”, current_time)
break
print(“Algo is working”, current_time)

index_chart  = tsl.get_historical_data(tradingsymbol='NIFTY JAN FUT', exchange='NFO', timeframe="5")
time.sleep(3)
index_ltp    = tsl.get_ltp_data(names = ['NIFTY JAN FUT'])['NIFTY JAN FUT']
try:
	index_chart = tsl.get_historical_data(tradingsymbol = 'NIFTY JAN FUT',exchange = 'NFO',timeframe="5")
except Exception as e:
	print(e)
	continue




# rsi    ------------------------ apply indicators
index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)

# vwap
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'])

# Supertrend
indi = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], 10, 2)
index_chart = pd.concat([index_chart, indi], axis=1, join='inner')


# vwma
index_chart['pv'] = index_chart['close'] * index_chart['volume']
index_chart['vwma'] = index_chart['pv'].rolling(20).mean() / index_chart['volume'].rolling(20).mean()

# volume
volume = 50000

first_candle   = index_chart.iloc[-3]
second_candle  = index_chart.iloc[-2]
running_candle = index_chart.iloc[-1]


# ---------------------------- BUY ENTRY CONDITIONS ----------------------------
bc1 = first_candle['close'] > first_candle['vwap']                # First Candle close is above VWAP
bc2 = first_candle['close'] > first_candle['SUPERT_10_2.0']       # First Candle close is above Supertrend 
bc3 = first_candle['close'] > first_candle['vwma']                # First Candle close is above VWMA
bc4 = first_candle['rsi'] < 80                                    # First candle RSI < 80	
bc5 = second_candle['volume'] > 50000                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
bc6 = traded == "no"
bc7 = index_ltp > first_candle['low']
print(f"BUY \t {current_time} \t {bc1} \t {bc2} \t {bc3} \t {bc4} \t {bc5} \t {bc7} \t first_candle {str(first_candle['timestamp'].time())}")


# ---------------------------- SELL ENTRY CONDITIONS ----------------------------
sc1 = first_candle['close'] < first_candle['vwap']                # First Candle close is below VWAP
sc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']       # First Candle close is below Supertrend 
sc3 = first_candle['close'] < first_candle['vwma']                # First Candle close is below VWMA
sc4 = first_candle['rsi'] > 20                                    # First candle RSI < 80	
sc5 = second_candle['volume'] > 50000                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
sc6 = traded == "no"
sc7 = index_ltp < first_candle['high']
print(f"SELL \t {current_time} \t {sc1} \t {sc2} \t {sc3} \t {sc4} \t {sc5} \t {sc7} \t first_candle {str(first_candle['timestamp'].time())} \n")


if bc1 and bc2 and bc3 and bc4 and bc5 and bc6 and bc7:
	print("Buy Signal Formed")

	CE_symbol_name, PE_symbol_name, strike   = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='09-01-2024')
	lot_size                   				 = tsl.get_lot_size(CE_symbol_name)*1
	entry_orderid              				 = tsl.order_placement(CE_symbol_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
	traded                     				 = "yes"
	trade_info['options_name'] 				 = CE_symbol_name
	trade_info['qty']                        = lot_size
	trade_info['sl']           				 = first_candle['low']
	trade_info['CE_PE']        				 = "CE"



if sc1 and sc2 and sc3 and sc4 and sc5 and sc6 and sc7:
	print("Sell Signal Formed")

	CE_symbol_name, PE_symbol_name, strike   = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='09-01-2024')
	lot_size                   				 = tsl.get_lot_size(PE_symbol_name)*1
	entry_orderid              				 = tsl.order_placement(PE_symbol_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
	traded                     				 = "yes"
	trade_info['options_name'] 				 = PE_symbol_name
	trade_info['qty']                     	 = lot_size
	trade_info['sl']            			 = first_candle['high']
	trade_info['CE_PE']                      = "PE"



# ---------------------------- check for exit SL/TG

if traded == "yes":

	long_position  = trade_info['CE_PE'] == "CE"
	short_position = trade_info['CE_PE'] == "PE"


	if long_position:
		sl_hit = index_ltp < trade_info['sl']
		tg_hit = index_ltp < running_candle['SUPERT_10_2.0']

		if sl_hit or tg_hit:
			print("Order Exited", trade_info)
			exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
			# pdb.set_trace()





	if short_position:
		sl_hit = index_ltp > trade_info['sl']
		tg_hit = index_ltp > running_candle['SUPERT_10_2.0']

		if sl_hit or tg_hit:
			print("Order Exited", trade_info)
			exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
			# pdb.set_trace()

Hi @Tradehull_Imran ,
I’m facing following issue,
I checked for all the dependencies and version of local python, all they are in good shape,
even though facing the following issue,

Can we have all the updated new code in one place”,
I seen many of the times updates in the new files or version,
Due to which local code may not work sometimes,
So they are confusing to us.

TIA, :slightly_smiling_face:

Hi @Arun_Rawat

Its a managed error in atm_strike_selection

use below code

import pdb
import time
import datetime
import traceback
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings
from Dhan_Tradehull_V2 import Tradehull

warnings.filterwarnings("ignore")

# ---------------- For Dhan Login ----------------
client_code = ""
token_id = ""

tsl = Tradehull(client_code, token_id)
available_balance = tsl.get_balance()
leveraged_margin = available_balance * 2
max_trades = 3
per_trade_margin = leveraged_margin / max_trades
max_loss = available_balance / 100 * -1

traded = "no"
trade_info = {"options_name": None, "qty": None, "sl": None, "CE_PE": None}

while True:
    live_pnl = tsl.get_live_pnl()
    current_time = datetime.datetime.now().time()  # time only

    if current_time < datetime.time(9, 45, 0):
        print("Wait for the market to open", current_time)
        continue

    if current_time > datetime.time(15, 15, 30) or (live_pnl < max_loss):
        tsl.kill_switch('ON')
        tsl.cancel_all_orders()
        print("Market is over or MAX LOSS reached, Bye for Now", current_time)
        break

    print("Algo is working", current_time)

    try:
        index_chart = tsl.get_historical_data(tradingsymbol='NIFTY JAN FUT', exchange='NFO', timeframe="5")
        time.sleep(3)
        index_ltp = tsl.get_ltp_data(names=['NIFTY JAN FUT'])['NIFTY JAN FUT']
    except Exception as e:
        print(e)
        continue

    # Apply Indicators
    index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)

    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'])

    indi = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], 10, 2)
    index_chart = pd.concat([index_chart, indi], axis=1, join='inner')

    index_chart['pv'] = index_chart['close'] * index_chart['volume']
    index_chart['vwma'] = index_chart['pv'].rolling(20).mean() / index_chart['volume'].rolling(20).mean()

    first_candle = index_chart.iloc[-3]
    second_candle = index_chart.iloc[-2]
    running_candle = index_chart.iloc[-1]

    # Buy Entry Conditions
    bc1 = first_candle['close'] > first_candle['vwap']
    bc2 = first_candle['close'] > first_candle['SUPERT_10_2.0']
    bc3 = first_candle['close'] > first_candle['vwma']
    bc4 = first_candle['rsi'] < 80
    bc5 = second_candle['volume'] > 50000
    bc6 = traded == "no"
    bc7 = index_ltp > first_candle['low']

    print(f"BUY \t {current_time} \t {bc1} \t {bc2} \t {bc3} \t {bc4} \t {bc5} \t {bc7} \t first_candle {str(first_candle['timestamp'].time())}")

    # Sell Entry Conditions
    sc1 = first_candle['close'] < first_candle['vwap']
    sc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']
    sc3 = first_candle['close'] < first_candle['vwma']
    sc4 = first_candle['rsi'] > 20
    sc5 = second_candle['volume'] > 50000
    sc6 = traded == "no"
    sc7 = index_ltp < first_candle['high']

    print(f"SELL \t {current_time} \t {sc1} \t {sc2} \t {sc3} \t {sc4} \t {sc5} \t {sc7} \t first_candle {str(first_candle['timestamp'].time())} \n")

    if bc1 and bc2 and bc3 and bc4 and bc5 and bc6 and bc7:
        print("Buy Signal Formed")

        CE_symbol_name, PE_symbol_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='09-01-2024')
        if (CE_symbol_name is None) or (PE_symbol_name is None):
            continue



        lot_size = tsl.get_lot_size(CE_symbol_name) * 1
        entry_orderid = tsl.order_placement(CE_symbol_name, 'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
        traded = "yes"
        trade_info.update({"options_name": CE_symbol_name, "qty": lot_size, "sl": first_candle['low'], "CE_PE": "CE"})

    if sc1 and sc2 and sc3 and sc4 and sc5 and sc6 and sc7:
        print("Sell Signal Formed")

        CE_symbol_name, PE_symbol_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='09-01-2024')
        if (CE_symbol_name is None) or (PE_symbol_name is None):
            continue


        lot_size = tsl.get_lot_size(PE_symbol_name) * 1
        entry_orderid = tsl.order_placement(PE_symbol_name, 'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
        traded = "yes"
        trade_info.update({"options_name": PE_symbol_name, "qty": lot_size, "sl": first_candle['high'], "CE_PE": "PE"})

    # Check for exit SL/TG
    if traded == "yes":
        long_position = trade_info['CE_PE'] == "CE"
        short_position = trade_info['CE_PE'] == "PE"

        if long_position:
            sl_hit = index_ltp < trade_info['sl']
            tg_hit = index_ltp < running_candle['SUPERT_10_2.0']

            if sl_hit or tg_hit:
                print("Order Exited", trade_info)
                tsl.order_placement(trade_info['options_name'], 'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')

        if short_position:
            sl_hit = index_ltp > trade_info['sl']
            tg_hit = index_ltp > running_candle['SUPERT_10_2.0']

            if sl_hit or tg_hit:
                print("Order Exited", trade_info)
                tsl.order_placement(trade_info['options_name'], 'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')

1 Like

Hi @Akshay_Bawane

No module named talib, means the installation was not successful

do install libraries see : https://www.youtube.com/watch?v=YAyIoDJYorA&list=PLnuHyqUCoJsPA4l9KRLrNpWLIfZ9ucLxx&index=8

Also use the sequence : Learn Algo Trading with Python | Codes | Youtube Series - #1065 by Tradehull_Imran

code files : Learn Algo Trading with Python | Codes | Youtube Series

1 Like

i am getting error in modify_order and cancel_order. Please help

Traceback (most recent call last):
File “/Users/vinodbhardwaj/Downloads/test/Trading/DhanTrading/Dhan_Tradehull_V2.py”, line 1431, in modify_order
p_orders = pd.DataFrame(self.xts1.get_order_book()[‘result’])
AttributeError: ‘Tradehull’ object has no attribute ‘xts1’