You can not execute it on terminal. You need to edit your python code file and save it before executing.
Comment or remove lines from line no 32-38.
print(data)
print("ACC_ltp")
print(historical_data)
sir i checked and your codes are running but previous codes in youtube series are not working anymore.
where can i get all the new codes, I wasted whole weekend stuck with old codes thinking i am doing something wrong.
is there any one stop solution where i can get all the latest versions of codebase, tradehull or websocket and codes? i have been checking this thread for the same but it is pretty long thread and i dont know new versions shared here are for everyone or only for the requester purpose.
@Danish_Ansari
Once you are done with basic algo series you can watch Advance Algo series at:
Learn Advanced Algo Trading Series
In new series we are not using websocket for LTP or not using code base as well.
Please watch Advance series as well.
Hi @Danish_Ansari ,
Verify that when you run pip show Dhan-Tradehull
, the latest version is 3.0.6.
Also remove from Dhan_Tradehull_V2 import Tradehull
from your code and replace with from Dhan_Tradehull import Tradehull
previous_hist_data = tsl.get_historical_data(‘ACC’,‘NSE’,12)
In the code 12
is not a supported timeframe to fetch the historical data. supported timeframes are :
- ‘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
Also it seems the ltp call must be replaced with
tsl.get_ltp_data(names=['ACC', 'NIFTY'])
Hi @Danish_Ansari ,
It seems you are still using the old files, make sure in the folder you have your main file, no other support files are available such as Dhan-Tradehull-V2
or ‘Dhan-Tradehull’.
Hi @Danish_Ansari ,
Do update to our latest codebase version 3.0.6:
- Open Command Prompt: Press Win, type cmd, and press Enter.
- Install Dhan-Tradehull: Run
pip install Dhan-Tradehull
- Confirm the installation by running
pip show Dhan-Tradehull
Guide to use the updated codebase:
Video reference :
Refer the below pypi link for more details:
https://pypi.org/project/Dhan-Tradehull/
Hi @phani_m ,
You can use the below code to fetch today’s OHLC data:
data = tsl.get_historical_data('TCS', 'NSE', '1')
today_data = data[pd.to_datetime(data['timestamp']).dt.date == pd.Timestamp.today().date()]
Hi @SANJEEV_RANJAN ,
chart = tsl.get_intraday_data(stock_name,‘NSE’,2)
In the code 2
is not a supported timeframe. Supported timeframes include:
- 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
refer the link for more details:
https://pypi.org/project/Dhan-Tradehull/
@Tradehull_Imran Sir,
This happens sometimes
@Tradehull_Imran heartily appreciate your prompt responses to my other queries. Kindly guide with the following SL coding, somehow something is wrong is what i feel.
# -----------------------------
# New Stop-Loss & Trade Management Functions
# -----------------------------
TRAILING_POINTS = {
"MIDCPNIFTY": 10,
"NIFTY": 20,
"BANKNIFTY": 30,
"BANKEX": 30,
"FINNIFTY": 30,
"SENSEX": 50
}
def monitor_trade_sl(trade_details, trade_signal):
entry_time = datetime.now()
buy_price = trade_details['entry_price']
# Set initial SL at buy_price - 10
current_sl = buy_price - 10
rich_log(f"[{trade_details['symbol']}] Initial SL set at: {current_sl}", style="bold blue")
csv_log_event("SL Management", {'symbol': trade_details['symbol'], 'price': current_sl, 'details': "Initial SL set (buy price - 10)"})
while not shutdown_flag:
elapsed = (datetime.now() - entry_time).total_seconds() / 60.0
ltp_data = tsl.get_ltp_data(names=[trade_details['option']])
current_ltp = ltp_data.get(trade_details['option'], 0)
# Check if LTP has risen sufficiently to update SL to buy_price + 2
if current_ltp >= (buy_price + 7) and current_sl < (buy_price + 2):
current_sl = buy_price + 2
try:
response = tsl.modify_forever(
order_id=trade_details['order_id'],
order_flag="SINGLE",
order_type="STOPLIMIT",
leg_name="STOP_LOSS_LEG",
quantity=int(trade_details.get('quantity', LOT_SIZES.get(trade_details['symbol'], 1))),
price=float(current_sl),
trigger_price=float(current_sl + 1),
disclosed_quantity=0,
validity="DAY"
)
rich_log(f"[{trade_details['symbol']}] Attempted SL update to buy price+2: {current_sl} | API response: {response}", style="bold green")
except Exception as e:
rich_log(f"Exception in modify_forever (buy price+2): {e}", style="bold red")
# Calculate trailing stop
trailing_value = TRAILING_POINTS.get(trade_details['symbol'], 20)
new_sl = current_ltp - trailing_value
# Update SL if the new computed SL is higher than the current SL
if new_sl > current_sl:
current_sl = new_sl
try:
response = tsl.modify_forever(
order_id=trade_details['order_id'],
order_flag="SINGLE",
order_type="STOPLIMIT",
leg_name="STOP_LOSS_LEG",
quantity=int(trade_details.get('quantity', LOT_SIZES.get(trade_details['symbol'], 1))),
price=float(current_sl),
trigger_price=float(current_sl + 1),
disclosed_quantity=0,
validity="DAY"
)
rich_log(f"[{trade_details['symbol']}] Trailing SL updated to: {current_sl} | API response: {response}", style="bold green")
except Exception as e:
rich_log(f"Exception in modify_forever (trailing): {e}", style="bold red")
# Auto exit after 40 minutes
if elapsed >= 40:
rich_log(f"[{trade_details['symbol']}] Auto-exit after 40 minutes.", style="bold yellow", panel=True, title="Exit Signal")
csv_log_event("Exit Trigger", {'symbol': trade_details['symbol'], 'price': current_ltp, 'details': "Auto-exit after 40 minutes"})
exit_trade(trade_details)
break
time.sleep(0.5)
return f"Stopped monitoring SL for {trade_details['symbol']}."
def exit_trade(trade_details):
exch = exchange_mapping.get(trade_details['symbol'], "NFO")
quantity = trade_details.get('quantity', LOT_SIZES.get(trade_details['symbol'], 1))
exit_order = tsl.order_placement(
tradingsymbol=trade_details['option'],
exchange=exch,
quantity=quantity,
price=0,
trigger_price=0,
order_type="MARKET",
transaction_type="SELL",
trade_type="MIS"
)
rich_log(f"[{trade_details['symbol']}] Exit order placed. Sell order ID: {exit_order}", style="bold red", panel=True, title="Trade Exit")
csv_log_event("Exit Order", {'symbol': trade_details['symbol'], 'price': "", 'details': f"Initial exit order placed. Order ID: {exit_order}"})
filled_qty = 0
timeout = 1
start_time = time.time()
while filled_qty < quantity and (time.time() - start_time) < timeout:
order_status_str = tsl.get_order_status(orderid=exit_order)
if not order_status_str.strip():
rich_log("Order status response is empty.", style="bold red")
order_status = {}
else:
try:
order_status = json.loads(order_status_str)
except Exception as e:
rich_log(f"Error parsing order status: {e}", style="bold red")
order_status = {}
filled_qty = order_status.get("filled_quantity", 0)
if filled_qty < quantity:
time.sleep(1)
else:
break
if filled_qty < quantity:
remaining_qty = quantity - filled_qty
rich_log(f"[{trade_details['symbol']}] Partial fill detected. Remaining qty: {remaining_qty}. Reattempting exit.", style="bold yellow", panel=True, title="Partial Fill")
csv_log_event("Partial Fill Exit Reattempt", {'symbol': trade_details['symbol'], 'price': "", 'details': f"Remaining qty: {remaining_qty}"})
second_exit_order = tsl.order_placement(
tradingsymbol=trade_details['option'],
exchange=exch,
quantity=remaining_qty,
price=0,
trigger_price=0,
order_type="MARKET",
transaction_type="SELL",
trade_type="MIS"
)
rich_log(f"[{trade_details['symbol']}] Second exit order placed. Sell order ID: {second_exit_order}", style="bold red", panel=True, title="Trade Exit")
csv_log_event("Exit Order", {'symbol': trade_details['symbol'], 'price': "", 'details': f"Second exit order placed. Order ID: {second_exit_order}"})
global open_trades
if trade_details in open_trades:
open_trades.remove(trade_details)
return f"Exit process complete for {trade_details['symbol']}."
Hi Sir, How/Where to get string of latest stock names in any index e.g. NIFTY, BANKNIFTY etc. to be added to a watchlist, example watchlist below? From where do I get list of latest stock names for below nifty 50 watchlist? Thanks!
Blockquote
watchlist = [‘ADANIPORTS’, ‘NATIONAL_SBIN’, ‘TATASTEEL’, ‘BALMLAWRIE’ ,‘BAJAJFINSV’, ‘RELIANCE’, ‘TCS’, ‘JSWSTEEL’, ‘HCLTECH’, ‘TECHM’, ‘NTPC’, ‘BHARTIARTL’, ‘WIPRO’, ‘BAJFINANCE’, ‘INDUSINDBK’, ‘KOTAKBANK’, ‘HINDALCO’, ‘ULTRACEMCO’, ‘AXISBANK’, ‘M&M’, ‘MARUTI’, ‘HEROMOTOCO’, ‘EICHERMOT’, ‘COALINDIA’, ‘TITAN’, ‘UPL’, ‘HINDUNILVR’, ‘ITC’, ‘NESTLEIND’, ‘APOLLOHOSP’, ‘ICICIBANK’, ‘GRASIM’, ‘BRITANNIA’, ‘ASIANPAINT’, ‘POWERGRID’, ‘SBILIFE’, ‘ONGC’]
@Tradehull_Imran , Hi Sir I am trying to build an below strategy. Can you please help with it?
Strategy Description:
Find the ATM strick for NIFTY at 9:17AM
Do not consider 9:15 AM candle as trigger candle.
First Condition (Entry Signal):
If the price closes below the VWAP on the 2-minute candle called as trigger candle.
On the next 2-minute candle, if the price closes below the first candle (which closed below the VWAP), enter a short position.
Stop-Loss:
Place the stop-loss at the high of the first candle (the one that closed below the VWAP).
Trailing Stop:
If the price moves 25 points below the entry (for a sell), adjust the stop-loss to break-even (i.e., the cost to cost level), so you don’t risk any loss if the price reverses.
@Tradehull_Imran How can I get the open interest (OI) for both the put and call options of a specific strike price? Also, how can I find the strike price?
i get the option chain but i am unable to convert into the proper df @Tradehull_Imran please guide me
Hi @Subhajitpanja ,
we can store our orderbook data using pickle… and next day when we run the program again the previous day orderbook will be read again…
this way we will keep on updating our orderbook… and store it in pickle before closing the program for the day.
pickle example : Understanding Python Pickling with example - GeeksforGeeks
also we use pickle so as to save the dictionary of orderbook and next day when we read it we get the dictionary output back.
if we try to do it in .txt/xlsx the the dictionary structure will be corrupted.
let me know if any further doubts
Hi @Subhajitpanja ,
yes another account will be required for the second api… this is because the rate limits are on account level
adding @Hardik for same , to check if above statement is True.
use below code to access 2 accounts api in same code
from Dhan_Tradehull import Tradehull
client_code_1 = "1102790XXX"
token_id_1 = "eyJ0eXAiOiJKV1Qw"
tsl_1 = Tradehull(client_code_1,token_id_1)
client_code_2 = "??"
token_id_2 = "??"
tsl_2 = Tradehull(client_code_2,token_id_2)