Hi @Zee2Zahid @Subhajitpanja
Server deployment is added in todo-videos list
Use below code
import pandas_ta as ta
indi = ta.supertrend(df['high'], df['low'], df['close'], 7, 3)
df = pd.concat([df, indi], axis=1, join='inner')
print(df)
# 'Column1 = this will give full supertrend line values' trend
# 'Column2 = this will show if st is red or green' direction
# 'Column3 = show values only for green nan for red' long
# 'Column4 = show values only for red nan for green' short
Hi @Zee2Zahid
This is because we can call ltp data only once in 1 second, so we need to use sleep
check below code
for distance_from_atm in range(1,20):
time.sleep(1)
otm_ce_name, otm_pe_name, ce_OTM_strike, pe_OTM_strike = tsl.OTM_Strike_Selection('NIFTY','14-11-2024',3)
ce_ltp = tsl.get_ltp_data(names = otm_ce_name)
time.sleep(1)
pe_ltp = tsl.get_ltp_data(names = otm_pe_name)
print(distance_from_atm, otm_ce_name, ce_ltp)
print(distance_from_atm, otm_pe_name, pe_ltp)
print()
or
for distance_from_atm in range(1,20):
time.sleep(1)
otm_ce_name, otm_pe_name, ce_OTM_strike, pe_OTM_strike = tsl.OTM_Strike_Selection('NIFTY','14-11-2024',3)
ltp_data = tsl.get_ltp_data(names = [otm_ce_name, otm_pe_name])
ce_ltp = ltp_data[otm_ce_name]
pe_ltp = ltp_data[otm_pe_name]
print(distance_from_atm, otm_ce_name, ce_ltp)
print(distance_from_atm, otm_pe_name, pe_ltp)
print()
Hi @Vijen_Singh
This error is due to version mismatch
See below video, for codebase upgrade
@rahulcse56
what is the error you are getting
Hi @CapTn_Mohit
This is okey, I have left my test account api keys, in code.
- If no order is being placed, maybe one of the condition from ema_slope_downtrend , touch_ema_downtrend , no_repeat_order , max_order_limit is False for the entire duration.
so need to check it manually,
see below code
import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib
import time
# Trading API client setup
client_code = ""
token_id = ""
tsl = Tradehull(client_code, token_id)
# Intraday strategy parameters
available_balance = tsl.get_balance()
leveraged_margin = available_balance * 5 # 5x leverage
max_trades = 1
per_trade_margin = leveraged_margin / max_trades # Amount for each trade
# Watchlist
watchlist = ['NBCC', 'RVNL', 'IFCI', 'HUDCO', 'MAZDOCK', 'INOXWIND', 'ZEEL', 'BSE', 'MMTC', 'ITI', 'BEML', 'SUZLON', 'HINDCOPPER', 'RELIANCE']
traded_watchlist = []
# Function to calculate 69 EMA and check for trend (uptrend/downtrend)
def check_trend_and_touch_ema(chart):
# Calculate 69 EMA for the chart
chart['69ema'] = talib.EMA(chart['close'], timeperiod=69)
# Get the last 4 EMA values for slope detection
ema_values = chart['69ema'].iloc[-4:].values # Last 4 EMA values
ema_slope_uptrend = all(ema_values[i] < ema_values[i+1] for i in range(3)) # Uptrend condition
ema_slope_downtrend = all(ema_values[i] > ema_values[i+1] for i in range(3)) # Downtrend condition
# Get the most recent candle (breakout candle)
bc = chart.iloc[-2] # Breakout candle
# Check if any part of the candle touches the 69 EMA (either body or wick)
touch_ema_uptrend = (bc['high'] >= bc['69ema'] >= bc['low']) or (bc['close'] >= bc['69ema'] >= bc['open'])
touch_ema_downtrend = (bc['high'] >= bc['69ema'] >= bc['low']) or (bc['close'] <= bc['69ema'] <= bc['open'])
return ema_slope_uptrend, ema_slope_downtrend, touch_ema_uptrend, touch_ema_downtrend, bc
# Main loop for the strategy
while True:
for stock_name in watchlist:
print(f"Processing {stock_name}…")
# Fetch intraday data for the stock (1-minute candles)
chart = tsl.get_intraday_data(stock_name, 'NSE', 15) # Fetch 1-minute candles
if chart is None or chart.empty:
print(f"No data retrieved for {stock_name}. Skipping...")
continue
# Check trend and EMA touch conditions
try:
ema_slope_uptrend, ema_slope_downtrend, touch_ema_uptrend, touch_ema_downtrend, bc = check_trend_and_touch_ema(chart)
print(f"{stock_name} - 69 EMA values: {chart['69ema'].iloc[-4:]}")
print(f"Uptrend: {ema_slope_uptrend}, Downtrend: {ema_slope_downtrend}")
print(f"Touch EMA Uptrend: {touch_ema_uptrend}, Touch EMA Downtrend: {touch_ema_downtrend}")
except Exception as e:
print(f"Error processing {stock_name}: {e}")
continue
# Ensure there is enough data for trend analysis
if len(chart) < 4:
print(f"Not enough data for {stock_name}. Skipping...")
continue
# Check for trade conditions
no_repeat_order = stock_name not in traded_watchlist
max_order_limit = len(traded_watchlist) < max_trades # Ensure we don't exceed max trades
# Calculate quantity to trade based on the available margin
qty = int(per_trade_margin / bc['close']) # Quantity based on the price of the stock
# Assuming you already have the correct logic in place for determining uptrend/downtrend
# and the other conditions for placing orders.
# Example when placing a sell order (if conditions for downtrend and touch EMA are met)
current_time = datetime.datetime.now()
print(current_time, ema_slope_downtrend , touch_ema_downtrend , no_repeat_order , max_order_limit)
if ema_slope_downtrend and touch_ema_downtrend and no_repeat_order and max_order_limit:
print(f"Placing sell order for {stock_name} - Quantity: {qty}")
trigger_price = 0 # For a market order, trigger price might not be needed
tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 'MARKET', 'BUY', 'MIS')
traded_watchlist.append(stock_name)
time.sleep(10) # Sleep to prevent hitting API rate limits
# Example when placing a buy order (if conditions for uptrend and touch EMA are met)
if ema_slope_uptrend and touch_ema_uptrend and no_repeat_order and max_order_limit:
print(f"Placing buy order for {stock_name} - Quantity: {qty}")
trigger_price = 0 # For a market order, trigger price might not be needed
tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 'MARKET', 'SELL', 'MIS')
traded_watchlist.append(stock_name)
time.sleep(10) # Sleep to prevent hitting API rate limits
time.sleep(10) # Sleep between each watchlist check
-
Dhanhq 1.3.2 gives data for today only, so maybe it did not had enough data to process for signals
use Dhan_Tradehull_V2 to solve it
see : Learn Algo Trading with Python | Codes | Youtube Series - #631 by Tradehull_Imran -
SL orders are covered in Session8 , multitimeframe algo
sl_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
@Tradehull_Imran mene upgrade kr liya hai
ijjus-MacBook-Air:8. Session8- 2nd Live Algo vijju$ /usr/local/bin/python3.10 “/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Multi timeframe Algo.py”
Mibian requires scipy to work properly
-----Logged into Dhan-----
This BOT Is Picking New File From Dhan
Got the instrument file
step Value DF is not generated due to Error from NSE India site: Missing optional dependency ‘xlrd’. Install xlrd >= 2.0.1 for xls Excel support Use pip or conda to install xlrd.
Collecting step values from program memory.
MOTHERSON
dhanhq.intraday_minute_data() takes 4 positional arguments but 7 were given
Traceback (most recent call last):
File “/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Dhan_Tradehull_V2.py”, line 257, in get_historical_data
ohlc = self.Dhan.intraday_minute_data(str(security_id),exchange_segment,instrument_type,self.start_date,self.end_date,int(interval))
TypeError: dhanhq.intraday_minute_data() takes 4 positional arguments but 7 were given
Traceback (most recent call last):
File “/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Multi timeframe Algo.py”, line 58, in
chart_1[‘rsi’] = talib.RSI(chart_1[‘close’], timeperiod=14) #pandas
TypeError: ‘NoneType’ object is not subscriptable
vijjus-MacBook-Air:8. Session8- 2nd Live Algo vijju$ pip3 show dhanhq
Name: dhanhq
Version: 2.0.1
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: /Users/vijju/Library/Python/3.9/lib/python/site-packages
Requires: pandas, pyOpenSSL, requests, websockets
Required-by:
vijjus-MacBook-Air:8. Session8- 2nd Live Algo vijju$
mera version 2.0.1 aa rha hai fir bhi error aa rhi hai
Hi @rahulcse56
2 min timeframe is not supported as of now, below are the supported timeframes
Timeframe:
1 - 1 minute
5 - 5 minutes
15 - 15 minutes
25 - 25 minutes
60 - 60 minutes
DAY - DAY
However you could resample 1 min data to get 2 min candles
https://pandas.pydata.org/docs/reference/api/pandas.Series.resample.html
Hi @Vijen_Singh
try below code, and run again
pip install dhanhq==2.0.0
if it still not works after that
-
Send me code in formatted way : see : Learn Algo Trading with Python | Codes | Youtube Series - #368 by Tradehull_Imran
-
Also resend me pip show dhanhq
-
and the error in formatted way
dhanhq has been updated to 2.0.1, maybe thats creating some issue
Great Sir, Its working now, God bless you…Thank You
Hi @Vijen_Singh
I got your formatted code and error on : Youtube session 8
I tried the same code on my end,
The issue is in client_code or token_id, check if token is not expired and is correct.
Also do let me know, if it works after that
Hi @Tradehull_Imran
Sir ,on entering my credentials in the file , I’m unable to fetch available balance.
@Tradehull_Imran still not working
below my pip3 show danhq
vijjus-MacBook-Air:1. Api Upgrade vijju$ pip3 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: /Users/vijju/Library/Python/3.9/lib/python/site-packages
Requires: pandas, pyOpenSSL, requests, websockets
Required-by:
vijjus-MacBook-Air:1. Api Upgrade vijju$
I am getting error
vijjus-MacBook-Air:8. Session8- 2nd Live Algo vijju$ /usr/local/bin/python3.10 "/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Multi timeframe Algo.py"
Mibian requires scipy to work properly
-----Logged into Dhan-----
This BOT Is Picking New File From Dhan
Got the instrument file
step Value DF is not generated due to Error from NSE India site: Missing optional dependency 'xlrd'. Install xlrd >= 2.0.1 for xls Excel support Use pip or conda to install xlrd.
Collecting step values from program memory.
MOTHERSON
dhanhq.intraday_minute_data() takes 4 positional arguments but 7 were given
Traceback (most recent call last):
File "/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Dhan_Tradehull_V2.py", line 296, in get_intraday_data
ohlc = self.Dhan.intraday_minute_data(str(security_id),exchange_segment,instrument_type,start_date,end_date,int(1))
TypeError: dhanhq.intraday_minute_data() takes 4 positional arguments but 7 were given
Traceback (most recent call last):
File "/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Multi timeframe Algo.py", line 58, in <module>
chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14) #pandas
TypeError: 'NoneType' object is not subscriptable
vijjus-MacBook-Air:8. Session8- 2nd Live Algo vijju$
And my code is
# https://ta-lib.github.io/ta-lib-python/
# https://www.notion.so/TradeHull-Dhan-Codebase-76b32fa814e64aea843e14a148854214#efa40986725341e6bfa9ad6fcfc10a6d
import pdb
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
import talib
import time
import datetime
client_code = "1101529493"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMxNzcxMDU4LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMTUyOTQ5MyJ9.Oo3_dwF1lGkiSenKu-XdpsMZIav5og-BK2CxzuTPyaAZGyUMDJEb_lCaTOLXwydfeeXbwzeKRs3pHXhlosKGGQ"
tsl = Tradehull(client_code,token_id) # tradehull_support_library
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', 'MANAPPURAM', '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', 'IDFCFIRSTB', 'ABFRL', 'ZYDUSLIFE', 'GLENMARK', 'TATAPOWER', 'PEL', 'IDFC', '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']
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(15, 15)) 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, 'NSE', 1) # 1 minute chart # this call has been updated to get_historical_data call,
# chart_1 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="1")
chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14) #pandas
cc_1 = chart_1.iloc[-2] #pandas completed candle of 1 min timeframe
uptrend = cc_1['rsi'] > 50
# downtrend = cc_1['rsi'] < 49
# Conditions that are on 5 minute timeframe
chart_5 = tsl.get_intraday_data(stock_name, 'NSE', 5) # 5 minute chart
# chart_5 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="5") # this call has been updated to get_historical_data call,
chart_5['upperband'], chart_5['middleband'], chart_5['lowerband'] = talib.BBANDS(chart_5['close'], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
cc_5 = chart_5.iloc[-1] # pandas
ub_breakout = cc_5['high'] > cc_5['upperband']
# lb_breakout = cc_5['low'] < cc_5['lowerband']
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)
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')
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,'NSE', 1, 0, 0, 'MARKET', 'SELL', 'MIS')
# sl_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, sl_price, 'STOPMARKET', 'BUY', 'MIS')
# traded_wathclist.append(stock_name)
I tried both ways
chart_1 = tsl.get_intraday_data(stock_name, 'NSE', 1) # 1 minute chart # this call has been updated to get_historical_data call,
And
# chart_1 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="1")
both are getting same error
not able to extract 2 min intraday historical data
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-08.csv
Got the instrument file
DataFrame constructor not properly called!
Traceback (most recent call last):
File “C:\Python\Dhan API Python\BUY_SELL ALGO\Dhan_Tradehull_V2.py”, line 259, in get_historical_data
df = pd.DataFrame(ohlc[‘data’])
File “C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 817, in init
raise ValueError(“DataFrame constructor not properly called!”)
ValueError: DataFrame constructor not properly called!
Sir, I have a few doubts about my Algo strategy.
1, How to know the Stock’s current month’s future in Long Build-up or Short build-up?
2, How to know the Stock’s most traded/liquid Call or Put option? (I think adding Volume + Open Interest from ITM 6 to OTM 6, an option with most Vol+OI is liquid enough to Buy.
Or any other Method to find the most liquid Option?)
3, How to know the option’s Volume and Open Interest?
4, If applying an indicator with 14 periods on Intraday data at 9:15, how can
the indicator calculates accurate data when data starts at 9:15 today.
5, How to get previous day data for stock in 5 minute time frame?
6, code for trailing Stop Loss.
Code for the above would be helpful
Thanks a lot for the people and their hard work behind this Algo trading series!!!
Hi, sir… Thank you for your support…
After downloding the websocket_v2 and Multi timeframe Algo, I am getting this Error , but orders got placed in my account…
Any big issue with this errors ?
I have screenshot only.
Please check and reply, sir…
Hi i have done this. I happend to download the certifi certifi-2024.8.30-py3-none-any.whl from one of links mentioned in one of the posts. I then went to that folder and did “pip install certifi” and also “pip install certifi --upgrade”
output is:
C:\Users\rando\Downloads>pip install certifi-2024.8.30-py3-none-any.whl
Defaulting to user installation because normal site-packages is not writeable
Processing c:\users\rando\downloads\certifi-2024.8.30-py3-none-any.whl
certifi is already installed with the same version as the provided wheel. Use --force-reinstall to force an installation of the wheel.
C:\Users\rando\Downloads>pip install certifi --upgrade
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: certifi in c:\users\rando\appdata\local\packages\pythonsoftwarefoundation.python.3.12_qbz5n2kfra8p0\localcache\local-packages\python312\site-packages (2024.8.30)
but it says requirement already satisfied but still i keep getting [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000) error when i try to use the marketfeed Apis. what is the issue plz? does the certifi have to installed in some particular folder? (windows machine btw)
Dear imran sir
Many problems are solved in V2
But still need deep dive session needed in V2
Thanks for the V2
means algo by dhan is not free