Entry
1 condtition - stock selection good Q results stocks
2 condition - apply SMC on 1hr and wait till idm
3 condition - after idm when 1hr super trend turns green buy and turns red exit no short only for long
```for short swing
Hi, @Tradehull_Imran
In the chart super trend turns green but in the code saying sell.
import pandas as pd
import talib
import time
from Dhan_Tradehull_V2 import Tradehull
# Initialize client
client_code = "11111111111"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFyG5lcklkIjoiIiwiZXhwIjoxNzM5MjY5OTEyLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMjk1NTI5MCJ9.5aG1-NOtFA3Bhsta9LZAdFsvljkz7sI_mXMDJ82QtumR67DLvUrFyJM8zUN3QO9_VpXaJK-leRqmMQIfxN6qCA"
tsl = Tradehull(client_code, token_id)
# Watchlist
pre_market_watchlist = ['INFY', 'M&M', 'HINDALCO', 'TATASTEEL', 'NTPC', 'MARUTI', 'TATAMOTORS',
'ONGC', 'BPCL', 'CIPLA', 'ASIANPAINT', 'TATACONSUM']
# Function to calculate Supertrend
def calculate_supertrend(df, period=10, multiplier=3):
"""
Calculate Supertrend indicator.
:param df: DataFrame with OHLC data
:param period: Lookback period for ATR
:param multiplier: ATR multiplier for upper and lower bands
:return: DataFrame with Supertrend values
"""
high = df['high']
low = df['low']
close = df['close']
atr = talib.ATR(high, low, close, timeperiod=period)
# Calculate Basic Upper Band and Lower Band
basic_upper_band = ((high + low) / 2) + (multiplier * atr)
basic_lower_band = ((high + low) / 2) - (multiplier * atr)
# Initialize Final Bands
final_upper_band = basic_upper_band.copy()
final_lower_band = basic_lower_band.copy()
# Supertrend calculation
supertrend = pd.Series(index=df.index, dtype='float64')
for i in range(1, len(df)):
final_upper_band[i] = (basic_upper_band[i]
if basic_upper_band[i] < final_upper_band[i - 1] or close[i - 1] > final_upper_band[i - 1]
else final_upper_band[i - 1])
final_lower_band[i] = (basic_lower_band[i]
if basic_lower_band[i] > final_lower_band[i - 1] or close[i - 1] < final_lower_band[i - 1]
else final_lower_band[i - 1])
supertrend[i] = (final_upper_band[i] if close[i] <= final_upper_band[i] else final_lower_band[i])
# Add columns to DataFrame
df['supertrend'] = supertrend
df['supertrend_direction'] = (close > supertrend).astype(int) # 1: Buy, 0: Sell
df['supertrend_direction'] = df['supertrend_direction'].replace(0, -1) # 1: Buy, -1: Sell
return df
# Pre-market scan with Supertrend
trade_info = {}
for name in pre_market_watchlist:
time.sleep(0.5)
print(f"Pre market scanning {name}")
# Fetch historical data
daily_data = tsl.get_historical_data(tradingsymbol=name, exchange='NSE', timeframe="60")
if daily_data.empty:
print(f"No data for {name}")
continue
# Calculate Supertrend
daily_data = calculate_supertrend(daily_data)
last_row = daily_data.iloc[-1]
# Check Supertrend signal
direction = "buy" if last_row['supertrend_direction'] == 1 else "sell"
level = last_row['supertrend']
trade_info[name] = {"Direction": direction, "Level": round(level, 2)}
print("Trade Info:")
for script, info in trade_info.items():
print(f"{script}: {info}")
Output
C:\Dhan\9. Session9- 3rd Live Algo Version 2\3rd live Algo>py "Supertrend practice.py"
Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-20.csv
Got the instrument file
Pre market scanning INFY
Pre market scanning M&M
Pre market scanning HINDALCO
Pre market scanning TATASTEEL
Pre market scanning NTPC
Pre market scanning MARUTI
Pre market scanning TATAMOTORS
Pre market scanning ONGC
Pre market scanning BPCL
Pre market scanning CIPLA
Pre market scanning ASIANPAINT
Pre market scanning TATACONSUM
Trade Info:
INFY: {'Direction': 'sell', 'Level': nan}
M&M: {'Direction': 'sell', 'Level': nan}
HINDALCO: {'Direction': 'sell', 'Level': nan}
TATASTEEL: {'Direction': 'sell', 'Level': nan}
NTPC: {'Direction': 'sell', 'Level': nan}
MARUTI: {'Direction': 'sell', 'Level': nan}
TATAMOTORS: {'Direction': 'sell', 'Level': nan}
ONGC: {'Direction': 'sell', 'Level': nan}
BPCL: {'Direction': 'sell', 'Level': nan}
CIPLA: {'Direction': 'sell', 'Level': nan}
ASIANPAINT: {'Direction': 'sell', 'Level': nan}
TATACONSUM: {'Direction': 'sell', 'Level': nan}
C:\Dhan\9. Session9- 3rd Live Algo Version 2\3rd live Algo>
Hi @Tradehull_Imran sir,
ye error aa raha hai baar baar. Please explain.
Hi @Nagi_Reddy_Vanga ,
It is not necessary to call the orderbook always for max trades purpose. It can be done even using the order status. This will be covered in the upcoming advanced sessions.
Hi @Sameer_Shaikh ,
- The code seems to be working fine.
- Status has not been shown because orders have not been placed through the code.
- Both trading and data api are required to get historical data using data api and to place orders using trading api.
Hello @Tradehull_Imran , Please have a look at the above query. Thanks.
Hi @Jagrut_Nemade ,
- Currently we get the OHLC data using get_historical_data(), so avoid the usage of get_intraday_data().
- Do refer and follow the below:
Retrieve historical or intraday data:
Get Historical Data
- tsl.get_historical_data(tradingsymbol: str, exchange: str, timeframe: str, debug: str = “NO”)
- Arguments:
- tradingsymbol (str): The trading symbol for the instrument you want to fetch data for (e.g., ‘NIFTY’, ‘ACC’).
- exchange (str): The exchange where the instrument is traded (e.g., ‘NSE’, ‘INDEX’).
- timeframe (str): The timeframe for the data. It can be:
- ‘1’ for 1-minute candles
- ‘5’ for 5-minute candles
- ‘15’ for 15-minute candles
- ‘25’ for 25-minute candles
- ‘60’ for 60-minute candles
- ‘DAY’ for daily candles
- debug (optional, str): Set to “YES” to enable detailed API response logging. Default is “NO”.
- Sample Code:
- Arguments:
data = tsl.get_historical_data(tradingsymbol='NIFTY', exchange='INDEX', timeframe="DAY")
data = tsl.get_historical_data(tradingsymbol='ACC', exchange='NSE', timeframe="1")
- If still there are errors do send your whole code.
I have already subscribed. now in the live market, I can see the order getting placed. but it is showing intraday when I’m changing to NRML It’s showing Tradhull v2 doesn’t have
I want to buy for delivery can you give me code for placing delivery order
and my orders are getting rejected also
C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2>py "Multi timeframe Algo.py"
Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-20.csv
Got the instrument file
TRENT
TRENT is in uptrend, Buy this script
Traceback (most recent call last):
File "C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2\Dhan_Tradehull_V2.py", line 128, in order_placement
product_Type = product[trade_type.upper()]
KeyError: 'NRML'
Traceback (most recent call last):
File "C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2\Dhan_Tradehull_V2.py", line 128, in order_placement
product_Type = product[trade_type.upper()]
KeyError: 'NRML'
MOTHERSON
BEL
HAVELLS
HAVELLS is in uptrend, Buy this script
Traceback (most recent call last):
File "C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2\Dhan_Tradehull_V2.py", line 128, in order_placement
product_Type = product[trade_type.upper()]
KeyError: 'NRML'
Traceback (most recent call last):
File "C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2\Dhan_Tradehull_V2.py", line 128, in order_placement
product_Type = product[trade_type.upper()]
KeyError: 'NRML'
APOLLOHOSP
SUNPHARMA
SUNPHARMA is in uptrend, Buy this script
Traceback (most recent call last):
File "C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2\Dhan_Tradehull_V2.py", line 128, in order_placement
product_Type = product[trade_typ
Hi @Sameer_Shaikh ,
- Yes, you have to change the import to Dhan_Tradehull_V2
from Dhan_Tradehull_V2 import Tradehull
and replace the file in the same folder.
Hi @rohit2312 ,
Currently 3min timeframe data is not available. tagging @Hardik for the same
Hi @Himansshu_Joshi ,
We have selected your idea for open source backtesting version 1 and currently thr development is in progress.
Hi @Sandeep_Vats ,
Do refer this URL:
Hello @Tradehull_Imran , thanks for clarification, it is working now. My mistake was that I was considering the variable timeframe in Integer, but it is required in String.
thank you so much sir, is there any to connect with you on call , so i can explain more about it.
Hi, @Tradehull_Imran
- For MIS orders it’s working but most of the orders are getting rejected only 1 or 2 orders are are getting placed
Code :
C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2>py "Multi timeframe Algo.py"
Codebase Version 2.4 : Solved - Option Chain
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-20.csv
Got the instrument file
Exception for instrument name TATA STEEL as Check the Tradingsymbol
got exception in pnl as 'Tata Steel'
TRENT
TRENT is in downtrend, Sell this script
MOTHERSON
BEL
TATASTEEL
BAJAJFINSV
RELIANCE
ONGC
Exception for instrument name TATA STEEL as Check the Tradingsymbol
got exception in pnl as 'Tata Steel'
TRENT
MOTHERSON
BEL
TATASTEEL
BAJAJFINSV
RELIANCE
ONGC
Exception for instrument name TATA STEEL as Check the Tradingsymbol
got exception in pnl as 'Tata Steel'
TRENT
MOTHERSON
MOTHERSON is in uptrend, Buy this script
BEL
TATASTEEL
BAJAJFINSV
RELIANCE
ONGC
ONGC is in uptrend, Buy this script
Exception for instrument name TATA STEEL as Check the Tradingsymbol
Exception for instrument name SAMVARDHANA MOTHERSON INTERNATIONAL as Check the Tradingsymbol
got exception in pnl as 'Tata Steel'
TRENT
MOTHERSON
BEL
TATASTEEL
BAJAJFINSV
RELIANCE
ONGC
I am stuck with NRML delivery order give me solution for this
Yes that will be very useful and not sure why it’s 25 mins candle, 30 Mins might be more useful, please
use below code for It has supertrend reference.
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 = "client_code"
token_id = "token_id"
tsl = Tradehull(client_code,token_id)
traded = "no"
trade_info = {"options_name":None, "qty":None, "sl":None, "CE_PE":None, "entry_price":None , "Trailed":None}
while True:
current_time = datetime.datetime.now()
index_chart = tsl.get_historical_data(tradingsymbol='NIFTY NOV FUT', exchange='NFO', timeframe="1")
time.sleep(3)
index_ltp = tsl.get_ltp_data(names = ['NIFTY NOV FUT'])['NIFTY NOV FUT']
if (index_chart == None):
time.sleep(60)
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("Sell Signal Formed")
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='28-11-2024')
lot_size = tsl.get_lot_size(ce_name)*1
entry_orderid = tsl.order_placement(ce_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
traded = "yes"
trade_info['options_name'] = ce_name
trade_info['qty'] = lot_size
trade_info['sl'] = first_candle['low']
trade_info['CE_PE'] = "CE"
time.sleep(1)
trade_info['entry_price'] = tsl.get_executed_price(orderid=trade_info['entry_orderid'])
if sc1 and sc2 and sc3 and sc4 and sc5 and sc6 and sc7:
print("Sell Signal Formed")
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='28-11-2024')
lot_size = tsl.get_lot_size(pe_name)*1
entry_orderid = tsl.order_placement(pe_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
traded = "yes"
trade_info['options_name'] = pe_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:
price_has_moved_20_pct = ltp > (trade_info['entry_price'])*1.2
position_has_not_been_trailed = trade_info['Trailed'] is None
if price_has_moved_20_pct and position_has_not_been_trailed:
trade_info['sl'] = trade_info['entry_price']
trade_info['Trailed'] = "yes_I_have_trailed"
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()
# trade_info = {
# 'CE_PE': 'PE',
# 'options_name': 'NIFTY 21 NOV 23350 PUT',
# 'qty': 25,
# 'sl': 23357.95
# }
hi @rohit2312 ,
Do send the complete code.
Hi @Sameer_Shaikh ,
Here’s how you can place orders:
Get Order Placement
- tsl.order_placement(tradingsymbol: str, exchange: str, quantity: int, price: int, trigger_price: int, order_type: str, transaction_type: str, trade_type: str, disclosed_quantity=0, after_market_order=False, validity=‘DAY’, amo_time=‘OPEN’, bo_profit_value=None, bo_stop_loss_value=None) → str
- Arguments:
- tradingsymbol (str): The trading symbol (e.g., ‘NIFTY 21 NOV 23300 CALL’).
- exchange (str): The exchange (e.g., ‘NFO’, ‘MCX’, ‘NSE’).
- quantity (int): The number of contracts to buy/sell.
- price (int): The price at which to place the order.
- trigger_price (int): The trigger price for stop orders.
- order_type (str): Type of order (‘MARKET’, ‘LIMIT’, ‘STOPLIMIT’, ‘STOPMARKET’).
- transaction_type (str): Type of transaction (‘BUY’ or ‘SELL’).
- trade_type (str): Type of trade (‘MIS’, ‘MARGIN’, ‘MTF’, ‘CO’, ‘BO’, ‘CNC’).
- disclosed_quantity (int, optional): Quantity disclosed to the market (default is 0).
- after_market_order (bool, optional): Whether it is an after-market order (default is False).
- validity (str, optional): Validity of the order (‘DAY’, ‘IOC’).
- amo_time (str, optional): AMO time (‘PRE_OPEN’, ‘OPEN’, ‘OPEN_30’, ‘OPEN_60’) if after-market order.
- bo_profit_value (float, optional): Profit value for BO orders (default is None).
- bo_stop_loss_value (float, optional): Stop loss value for BO orders (default is None).
- Returns:
- str: The order ID if the order is placed successfully, or None if there was an error.
orderid = tsl.order_placement('ACC','NSE', 1, 0, 0, 'MARKET', 'BUY', 'MIS')
orderid = tsl.order_placement('CRUEDOIL DEC FUT','MCX', 1, 4567, 0, 'LIMIT', 'BUY', 'CNC')
Also do refer the below: