Learn Algo Trading with Python | Codes | Youtube Series

Thanks for providing the direction… i will defiantly try to get 2 min data… could you please help me to get first 2 min candle data from the intraday… means how to address the candle because when i say data[-1]… it will give me last candle data… and when i say data[0]… it will give me 6 day’s prior candle data… Also, I am not able to get the first 2 min candle data as well.
Please advise and try to address the issue in the next video…

for your reference check the below screenshot of output… i need to get data of first 2 min candle low high open and close data i.e. combined data of 2024-11-11 09:15:00 and 2024-11-11 09:16:00

Hi @Tradehull_Imran

I am working on a code and I am facing strange issue, below code sometimes works properly and sometimes it doesn’t work. Like the same code was working fine from morning till 11:00 - 11:30am but later started giving errors:

-----Logged into Dhan-----
reading existing file all_instrument 2024-11-11.csv
Got the instrument file
2024-11-11 13:46:18.187409
If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "D:\Dhan\6. Session6- 1st Live Algo\6. Session6- 1st Live Algo\1st live Algo\Dhan_Tradehull_V2.py", line 259, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 709, in __init__
    mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 481, in dict_to_mgr
    return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 115, in arrays_to_mgr
    index = _extract_index(arrays)
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 645, in _extract_index
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "D:\Dhan\6. Session6- 1st Live Algo\6. Session6- 1st Live Algo\1st live Algo\Dhan_Tradehull_V2.py", line 259, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 709, in __init__
    mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 481, in dict_to_mgr
    return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 115, in arrays_to_mgr
    index = _extract_index(arrays)
  File "C:\Users\Aijaz\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 645, in _extract_index
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
Number of stocks above 50EMA: 0
Execution time: 0.18 seconds
2024-11-11 13:46:18.366175
import time
import datetime
import traceback
import concurrent.futures
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
import talib

client_code = "1104227243"
token_id = "xxxxxxxx"
tsl = Tradehull(client_code, token_id)

current_time_1 = datetime.datetime.now()
print(current_time_1)

# Read symbols
stock_name_df = pd.read_csv('Testsymbol1.csv')
watchlist = stock_name_df['Symbol'].tolist()

# Function to fetch and process historical data
def check_above_50ema(stock_name):
    try:
        # Fetch historical data
        previous_hist_data = tsl.get_historical_data(stock_name, 'NSE', timeframe="DAY")
        
        # Ensure data is not empty
        if previous_hist_data is not None and not previous_hist_data.empty:
            # Calculate 50-day EMA
            previous_hist_data['EMA50'] = talib.EMA(previous_hist_data['close'], timeperiod=50)
            
            # Check if the latest close price is above the 50-day EMA
            if previous_hist_data['close'].iloc[-1] > previous_hist_data['EMA50'].iloc[-1]:
                return stock_name
    except Exception as e:
        print(f"Error processing {stock_name}: {str(e)}")
    
    return None

# Optimized function to get stocks above 50 EMA using parallel processing
def get_stocks_above_50ema_parallel(watchlist):
    stocks_above_50ema = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        # Fetch data concurrently
        results = list(executor.map(check_above_50ema, watchlist))
    
    # Filter out None values
    stocks_above_50ema = [stock for stock in results if stock is not None]
    
    return stocks_above_50ema, len(stocks_above_50ema)

# Call the function and store the result
start_time = time.time()
stocks_above_50ema_list, number_of_stocks_above_50ema = get_stocks_above_50ema_parallel(watchlist)
end_time = time.time()

# Use the variables later in your code
print(f"Number of stocks above 50EMA: {number_of_stocks_above_50ema}")
print(f"Execution time: {end_time - start_time:.2f} seconds")

current_time_2 = datetime.datetime.now()
print(current_time_2)

Please help me understand why this issue is happening.

Hello @Tradehull_Imran

getting error

please help
thanks

Hi @rejithkoroth

I have checked it, there is some issue with the client_code and token_id.
for my credentials it’s working fine.

Also do check if you have again subscribed to Data api. This should also be renewed.

@Vijen_Singh @Manish_Goel Do let me know any if your issue was solved.

Hi @Kishore007

This is a codebase error, which is being encountered
while fetching LTP in Dhan_Tradehull_V2 in get_live_pnl fucntion.

I will mark this a bug to be solved for Dhan_Tradehull_V3.py

:+1: for pointing the bug out. Less bugs relaxed coding.

1 Like

Super Sir. Very happy

@Tradehull_Imran Can you plz check this

Hi @pratik_patil2

  1. Do check below thread, and check if data api has been renewed
    Learn Algo Trading with Python | Codes | Youtube Series - #688 by Tradehull_Imran

  2. Also if it has been renewed and still the same issue
    a. Do send me main code file and Dhan_Tradehull_V2.py that you are using, on forum
    Do format code correctly see : Learn Algo Trading with Python | Codes | Youtube Series - #368 by Tradehull_Imran

    b. Also send the output of the command on CMD pip show dhanhq

@ddeogharkar
check if the data api are re-subscribed

@Tradehull_Imran After Subscribe Data API it’s working?

mene Data API ko subscribe nhi kiya tha

Hi @Vijen_Singh
Yes, Data Api needs to be subscribed to get historical data.

Yes, it is active. Can I switch to dhan api 2.0 and check

@Tradehull_Imran Ok thanks sir

Thank you, sir…

I have written a code for Take profit… Please check it whether it is correct or not, sir…

 if uptrend and ub_breakout and no_repeat_order and max_order_limit:
            print(stock_name, "is in uptrend, Buy this script")

            sl_price = round((cc_1['close'] * 0.98), 1)
            tp_price = round((cc_1['close'] * 1.003), 1)  # Take Profit price (0.3% above buy price)
            qty = int(per_trade_margin / cc_1['close'])

            buy_entry_orderid = tsl.order_placement(stock_name, 'NSE', 1, 0, 0, 'MARKET', 'BUY', 'MIS')
            sl_orderid = tsl.order_placement(stock_name, 'NSE', 1, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
            tp_orderid = tsl.order_placement(stock_name, 'NSE', 1, qty, tp_price, 'LIMIT', 'SELL', 'MIS')  # Take Profit Limit Order
            traded_wathclist.append(stock_name)

Hi Sir, @Tradehull_Imran
I have activated the Data API service today, as I had not subscribed to it till yesterday. However, I have encountered some issues with my account today. Unfortunately, I am unable to place a manual order at this time.

I have raised this issue with customer care, and they have assured me that they are looking into the matter and will work to resolve it as soon as possible.

Once my account is back online, I plan to retry the algo and will keep you updated on my progress.

Thank you for your support. :pray: :pray:

1 Like

@ddeogharkar
yes, try it once

Hi @Kishore007

tp_orderid = tsl.order_placement(stock_name, ‘NSE’, 1, qty, tp_price, ‘LIMIT’, ‘SELL’, ‘MIS’) # Take Profit Limit Order
seems to be wrong, the sequence of parameters in order placement function is as stated below

    tradingsymbol
    exchange
    quantity
    price
    trigger_price
    order_type
    transaction_type
    trade_type

1 Like

Hi
@Tradehull_Imran
I am trying to learn with your given file
Also purchase data API
But I am facing the error
I have tried both Trading API and data API simultaneously
But can’t understand the error
Code is running well till line 46 but there after give error

I got it, sir…

Thank you, sir…

Sir , I have written a super trend algo by using super trend indicator code. while testing it is showing lot of errors, please check, sir…





# i am using mcx markets for testing the below code in live markets

# buy trade:
# my stragegy is in 5 mins chart supertrend should be in green  and in 1 min chart adx should be above 20





import pdb
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
import pandas_ta as ta
import talib
import time
import datetime

client_code = "11"
token_id = "11"
tsl = Tradehull(client_code,token_id)


available_balance = tsl.get_balance()
leveraged_margin  = available_balance*5
max_trades = 3
per_trade_margin = (leveraged_margin/max_trades)
max_loss = (available_balance*1)/100*-1

# watchlist = ['MOTHERSON', 'OFSS', 'BSOFT', 'CHAMBLFERT', 'DIXON', 'NATIONALUM', 'DLF', 'IDEA', 'ADANIPORTS', 'SAIL', 'HINDCOPPER', 'INDIGO', 'RECLTD', 'PNB', 'HINDALCO', 'RBLBANK', 'GNFC', 'ALKEM', 'CONCOR', 'PFC', 'GODREJPROP', 'MARUTI', 'ADANIENT', 'ONGC', 'CANBK', 'OBEROIRLTY', 'BANDHANBNK', 'SBIN', 'HINDPETRO', 'CANFINHOME', 'TATAMOTORS', 'LALPATHLAB', 'MCX', 'TATACHEM', 'BHARTIARTL', 'INDIAMART', 'LUPIN', 'INDUSTOWER', 'VEDL', 'SHRIRAMFIN', 'POLYCAB', 'WIPRO', 'UBL', 'SRF', 'BHARATFORG', 'GRASIM', 'IEX', 'BATAINDIA', 'AARTIIND', 'TATASTEEL', 'UPL', 'HDFCBANK', 'LTF', 'TVSMOTOR', 'GMRINFRA', 'IOC', 'ABCAPITAL', 'ACC', 'ZYDUSLIFE', 'GLENMARK', 'TATAPOWER', 'PEL', 'LAURUSLABS', 'BANKBARODA', 'KOTAKBANK', 'CUB', 'GAIL', 'DABUR', 'TECHM', 'CHOLAFIN', 'BEL', 'SYNGENE', 'FEDERALBNK', 'NAVINFLUOR', 'AXISBANK', 'LT', 'ICICIGI', 'EXIDEIND', 'TATACOMM', 'RELIANCE', 'ICICIPRULI', 'IPCALAB', 'AUBANK', 'INDIACEM', 'GRANULES', 'HDFCAMC', 'COFORGE', 'LICHSGFIN', 'BAJAJFINSV', 'INFY', 'BRITANNIA', 'M&MFIN', 'BAJFINANCE', 'PIIND', 'DEEPAKNTR', 'SHREECEM', 'INDUSINDBK', 'DRREDDY', 'TCS', 'BPCL', 'PETRONET', 'NAUKRI', 'JSWSTEEL', 'MUTHOOTFIN', 'CUMMINSIND', 'CROMPTON', 'M&M', 'GODREJCP', 'IGL', 'BAJAJ-AUTO', 'HEROMOTOCO', 'AMBUJACEM', 'BIOCON', 'ULTRACEMCO', 'VOLTAS', 'BALRAMCHIN', 'SUNPHARMA', 'ASIANPAINT', 'COALINDIA', 'SUNTV', 'EICHERMOT', 'ESCORTS', 'HAL', 'ASTRAL', 'NMDC', 'ICICIBANK', 'TORNTPHARM', 'JUBLFOOD', 'METROPOLIS', 'RAMCOCEM', 'INDHOTEL', 'HINDUNILVR', 'TRENT', 'TITAN', 'JKCEMENT', 'ASHOKLEY', 'SBICARD', 'BERGEPAINT', 'JINDALSTEL', 'MFSL', 'BHEL', 'NESTLEIND', 'HDFCLIFE', 'COROMANDEL', 'DIVISLAB', 'ITC', 'TATACONSUM', 'APOLLOTYRE', 'AUROPHARMA', 'HCLTECH', 'LTTS', 'BALKRISIND', 'DALBHARAT', 'APOLLOHOSP', 'ABBOTINDIA', 'ATUL', 'UNITDSPR', 'PVRINOX', 'SIEMENS', 'SBILIFE', 'IRCTC', 'GUJGASLTD', 'BOSCHLTD', 'NTPC', 'POWERGRID', 'MARICO', 'HAVELLS', 'MPHASIS', 'COLPAL', 'CIPLA', 'MGL', 'ABB', 'PIDILITIND', 'MRF', 'LTIM', 'PAGEIND', 'PERSISTENT']

watchlist = ['CRUDEOIL NOV FUT', 'NATURALGAS NOV FUT', 'SILVERM NOV FUT']

traded_wathclist = []


while True:

	live_pnl = tsl.get_live_pnl()
	current_time = datetime.datetime.now().time()

	if current_time < datetime.time(9, 30):
		print("wait for market to start", current_time)
		continue


	if (current_time > datetime.time(23, 00)) 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, Bye Bye see you tomorrow", current_time)
		break



	for stock_name in watchlist:
		time.sleep(0.2)
		print(stock_name)



		# Conditions that are on 1 minute timeframe
		# chart_1        = tsl.get_intraday_data(stock_name, 'MCX', 1)       # 1 minute chart   # this call has been updated to get_historical_data call, 
		chart_1          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'MCX',timeframe="1")


		chart_1['adx'] = talib.ADX(chart_1['high'], chart_1['low'], chart_1['close'], timeperiod=14)								
		cc_1           = chart_1.iloc[-1]  #pandas  completed candle of 1 min timeframe
		uptrend 	   = cc_1['adx'] >= 20.0
		downtrend      = cc_1['adx'] <= 19.9

		# Conditions that are on 5 minute timeframe
		chart_5        = tsl.get_intraday_data(stock_name, 'MCX', 5)       # 5 minute chart
		chart_5          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'MCX',timeframe="5") # this call has been updated to get_historical_data call, 

		chart_5 ['supertrend'] 	= ta.supertrend(chart_5['high'], chart_5['low'], chart_5['close'],7,3)
		chart_5 	= pd.concat([chart_5, supertrend], axis=1, join='inner')
		cc_5 		= chart_1.iloc[-1]

		ub_breakout    = cc_5['close'] > cc_5['supertrend']
		lb_breakout    = cc_5['close'] < cc_5['supertrend']


		no_repeat_order = stock_name not in traded_wathclist
		max_order_limit = len(traded_wathclist) <= max_trades


		if uptrend and ub_breakout and no_repeat_order and max_order_limit:
			print(stock_name, "is in uptrend, Buy this script")

			sl_price          = round((cc_1['close']*0.98),1)
			tp_price 			= round((cc_1['close'] * 1.003), 1)  # Take Profit price (0.3% above buy price)
			qty               = int(per_trade_margin/cc_1['close'])

			buy_entry_orderid = tsl.order_placement(stock_name,'MCX', 1, 0, 0, 'MARKET', 'BUY', 'MIS')
			sl_orderid        = tsl.order_placement(stock_name,'MCX', 1, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
			tp_orderid 		  = tsl.order_placement(stock_name,'MCX', 1, 0, tp_price, 'LIMIT', 'SELL', 'MIS')  # Take Profit Limit Order
			traded_wathclist.append(stock_name)

		if downtrend and lb_breakout and no_repeat_order and max_order_limit:
			print(stock_name, "is in downtrend, Sell this script")

			sl_price          = round((cc_1['close']*1.02),1)
			qty               = int(per_trade_margin/cc_1['close'])

			buy_entry_orderid = tsl.order_placement(stock_name,'MCX', 1, 0, 0, 'MARKET', 'SELL', 'MIS')
			sl_orderid        = tsl.order_placement(stock_name,'MCX', 1, 0, sl_price, 'STOPMARKET', 'BUY', 'MIS')
			traded_wathclist.append(stock_name)

Error Messages

reading existing file all_instrument 2024-11-11.csv
Got the instrument file
Error at Gettting balance as 'availabelBalance'
Traceback (most recent call last):
  File "C:\Users\Admin\Documents\Dhan\8. Session8- 2nd Live Algo\8. Session8- 2nd Live Algo\2nd live Algo\Dhan_Tradehull_V2.py", line 168, in get_live_pnl
    pos_book = pd.DataFrame(pos_book_dict)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 709, in __init__
    mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 481, in dict_to_mgr
    return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 115, in arrays_to_mgr
    index = _extract_index(arrays)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 645, in _extract_index
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
CRUDEOIL NOV FUT
If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "C:\Users\Admin\Documents\Dhan\8. Session8- 2nd Live Algo\8. Session8- 2nd Live Algo\2nd live Algo\Dhan_Tradehull_V2.py", line 259, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 709, in __init__
    mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 481, in dict_to_mgr
    return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 115, in arrays_to_mgr
    index = _extract_index(arrays)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 645, in _extract_index
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "Super trend.py", line 62, in <module>
    chart_1['adx'] = talib.ADX(chart_1['high'], chart_1['low'], chart_1['close'], timeperiod=14)
TypeError: 'NoneType' object is not subscriptable