Hello @Tradehull_Imran
Sir If if people_intrested > required_people_intrested:
print(“BUILD LIVE ALGO”)
Thanks
Hello @Tradehull_Imran
Sir If if people_intrested > required_people_intrested:
print(“BUILD LIVE ALGO”)
Thanks
Hi @Tradehull_Imran
The “required_people_interested” has to be >16. If yes, then you will…
“red_circle GO LIVE SESSION ON YOUTUBE”
"red_circle BUILD ALGO LIVE "
“red_circle LIVE QUESTIONS AND ANSWER IMPLEMENTATION”
However, I would suggest one small change…
If interest_level_of_current_participants >100%:
print(“@Tradehull_Imran may make an exception to the above rule and still do a live session on youtube/build algo live/live q&a”)
Hi @Tradehull_Imran, Thank you for your help. I’ll check again today.
Thanks
Thank you for your kind words @Tradehull_Imran. Coming from an Algo trading expert like you, Its a big motivation for a novice like me.
@Tradehull_Imran Sir really need your help, what i am doing wrong here …i am able to place order in equity but not for options …why?
Hi @Kishore007
Dhan_Tradehull_V2 has no function for get_position
now if you want to check if you have bought/sold the position in this case we need to implement trade_info dictionary
see : https://youtu.be/wlQWSLzp_UI?si=LC7lZmWat_K-3JdI&t=2685
I am adding pseudocode for it, do make the changes accordingly.
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")
#-----------------------------------------------------------------------------------
client_code = "11"
token_id = "11"
tsl = Tradehull(client_code,token_id)
#----------------------------------------------------------------------------------
available_balance = tsl.get_balance()
leveraged_margin = available_balance*5
max_trades = 20
per_trade_margin = (leveraged_margin/max_trades)
max_loss = available_balance * -0.09 # max loss of 9%
#-----------------------------------------------------------------------------------------
watchlist = ['GOLDPETAL DEC FUT']
traded_wathclist = []
#-----------------------------------------------------------------------------------------------------
trade_info = {"stock_name":None, "qty":None, "entry_orderid":None, "direction":None}
while True:
live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 18):
print("Wait for market to start", current_time)
time.sleep(1)
continue
if (current_time > datetime.time(23, 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 see you tomorrow", current_time)
break
for stock_name in watchlist:
time.sleep(2)
print(f"Scanning {stock_name}")
# Conditions that are on 1 minute timeframe -------------------------------------------
chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='MCX', timeframe="1")
pervious_candle = chart_1.iloc[-2]
no_repeat_order = stock_name not in traded_wathclist
# rsi ------------------------ apply indicators--------------------------------------
# Buy when rsi crosses above 55 and sell when rsi crosses below 45
# Ensure chart_1 has sufficient rows
if len(chart_1) <= 15:
print(f"Not enough data for {stock_name}. Skipping.")
continue
# Calculate RSI and drop NaN values
chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14)
chart_1['prev_rsi'] = chart_1['rsi'].shift(1)
chart_1.dropna(subset=['rsi', 'prev_rsi'], inplace=True)
# Add crossover columns
chart_1['uptrend_cross'] = (chart_1['prev_rsi'] <= 55) & (chart_1['rsi'] > 55)
chart_1['downtrend_cross'] = (chart_1['prev_rsi'] >= 45) & (chart_1['rsi'] < 45)
# Ensure the columns exist in the completed candle
cc_1 = chart_1.iloc[-2] # Second-to-last row
if 'uptrend_cross' not in cc_1 or 'downtrend_cross' not in cc_1:
print(f"Missing crossover columns for {stock_name}. Skipping.")
continue
# Access crossover values
uptrend_1 = cc_1['uptrend_cross']
downtrend_1 = cc_1['downtrend_cross']
print(f"Uptrend: {uptrend_1}, Downtrend: {downtrend_1}")
# Supertrend for Exit from open position -------------------------- apply indicators-----------------------------------
indi = ta.supertrend(chart_1['high'], chart_1['low'], chart_1['close'], 10, 1)
chart_1 = pd.concat([chart_1, indi], axis=1, join='inner')
cc_1 = chart_1.iloc[-2] #pandas completed candle of 1 min timeframe
exit_sell = cc_1['close'] > cc_1['SUPERT_10_1.0']
exit_buy = cc_1['close'] < cc_1['SUPERT_10_1.0']
# BUY conditions ------------------------------------------------------------------------------
breakout_b1 = ((pervious_candle['close'] - pervious_candle['open']) / pervious_candle['open']) * 100 # percentage change
breakout_b2 = pervious_candle['volume'] > 0.2 * chart_1['volume'].mean()
if uptrend_1 and breakout_b2 and (0.01 <= breakout_b1 <= 0.4) and no_repeat_order:
print(stock_name, "is in uptrend, Buy this script")
lot_size = tsl.get_lot_size(stock_name)
# Place buy order-------------------------------------------------------------------------
entry_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
traded_wathclist.append(stock_name)
trade_info['stock_name'] = stock_name
trade_info['qty'] = lot_size
trade_info['entry_orderid'] = entry_orderid
trade_info['direction'] = "BUY"
# SELL conditions -----------------------------------------------------------------------------
breakout_s1 = ((pervious_candle['close'] - pervious_candle['open']) / pervious_candle['open']) * 100 # percentage change
breakout_s2 = pervious_candle['volume'] > 0.2 * chart_1['volume'].mean()
if downtrend_1 and breakout_s2 and (-0.4 <= breakout_s1 <= -0.01) and no_repeat_order:
print(stock_name, "is in downtrend, Sell this script")
lot_size = tsl.get_lot_size(stock_name)
# Place sell order-------------------------------------------------------------------------
entry_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'SELL', 'MIS')
traded_wathclist.append(stock_name)
# Exit conditions based on Supertrend indicator----------------------------------------------------
for stock_name in traded_wathclist:
time.sleep(2)
print(f"Checking exit conditions for {stock_name}")
# Fetch updated 1-minute chart
chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='MCX', timeframe="1")
# Apply Supertrend indicator again
indi = ta.supertrend(chart_1['high'], chart_1['low'], chart_1['close'], 10, 1)
chart_1 = pd.concat([chart_1, indi], axis=1, join='inner')
cc_1 = chart_1.iloc[-2] # Get the completed candle
# Exit conditions
exit_sell = cc_1['close'] > cc_1['SUPERT_10_1.0']
exit_buy = cc_1['close'] < cc_1['SUPERT_10_1.0']
# Check for existing positions to square off
position = trade_info['direction']
if position == 'BUY' and exit_buy:
print(f"Exiting BUY position for {stock_name}")
exit_orderid = tsl.order_placement(stock_name, 'MCX', position['lot_size'], 0, 0, 'MARKET', 'SELL', 'MIS')
traded_wathclist.remove(stock_name)
elif position == 'SELL' and exit_sell:
print(f"Exiting SELL position for {stock_name}")
exit_orderid = tsl.order_placement(stock_name, 'MCX', position['lot_size'], 0, 0, 'MARKET', 'BUY', 'MIS')
traded_wathclist.remove(stock_name)
But trade_info will only work for a single script,
as of now I have not taught how to manage multiple positions with all the details.
I will take this topic in next live lecture This week.
There were many upgraded along the way , do check below sequence for practice
use below code for order placement into options
tsl.order_placement(ce_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
for video tutorial see : https://youtu.be/wlQWSLzp_UI?si=ZF5z38v2pnl_S2Xj&t=2472
Thankyou sir,
Awaiting for live session, sir…
BANKNIFTY DEC FUT Buy CALL
Order Exited {‘options_name’: ‘BANKNIFTY 24 DEC 52300 CALL’, ‘qty’: 15, ‘sl’: 944.9, ‘CE_PE’: ‘CE’, ‘entry_price’: 944.9, ‘Trailed’: ‘yes_I_have_trailed’, ‘entry_orderid’: ‘42241127396413’}
BUY NIFTY DEC FUT 12:00:11.177718 False True False cc_1 2024-11-27 12:00:00+05:30
SELL NIFTY DEC FUT 12:00:11.177718 False True False cc_1 2024-11-27 12:00:00+05:30
Order Exited {‘options_name’: ‘BANKNIFTY 24 DEC 52300 CALL’, ‘qty’: 15, ‘sl’: 944.9, ‘CE_PE’: ‘CE’, ‘entry_price’: 944.9, ‘Trailed’: ‘yes_I_have_trailed’, ‘entry_orderid’: ‘42241127396413’}
BUY BANKNIFTY DEC FUT 12:00:11.177718 True True True cc_1 2024-11-27 12:00:00+05:30
SELL BANKNIFTY DEC FUT 12:00:11.177718 False True False cc_1 2024-11-27 12:00:00+05:30
BANKNIFTY DEC FUT Buy CALL
BUY NIFTY DEC FUT 12:00:23.511704 False True False cc_1 2024-11-27 12:00:00+05:30
SELL NIFTY DEC FUT 12:00:23.511704 False True False cc_1 2024-11-27 12:00:00+05:30
Order Exited {‘options_name’: ‘BANKNIFTY 24 DEC 52300 CALL’, ‘qty’: 15, ‘sl’: 52422.25, ‘CE_PE’: ‘CE’, ‘entry_price’: 978.0, ‘Trailed’: ‘yes_I_have_trailed’, ‘entry_orderid’: ‘22241127378613’}
BUY BANKNIFTY DEC FUT 12:00:23.511704 True True True cc_1 2024-11-27 12:00:00+05:30
SELL BANKNIFTY DEC FUT 12:00:23.511704 False True False cc_1 2024-11-27 12:00:00+05:30
BANKNIFTY DEC FUT Buy CALL
BUY NIFTY DEC FUT 12:00:35.661303 False True False cc_1 2024-11-27 12:00:00+05:30
SELL NIFTY DEC FUT 12:00:35.661303 False True False cc_1 2024-11-27 12:00:00+05:30
Order Exited {‘options_name’: ‘BANKNIFTY 24 DEC 52300 CALL’, ‘qty’: 15, ‘sl’: 52422.25, ‘CE_PE’: ‘CE’, ‘entry_price’: 993.95, ‘Trailed’: ‘yes_I_have_trailed’, ‘entry_orderid’: ‘22241127380013’}
BUY BANKNIFTY DEC FUT 12:00:35.661303 True True True cc_1 2024-11-27 12:00:00+05:30
SELL BANKNIFTY DEC FUT 12:00:35.661303 False True False cc_1 2024-11-27 12:00:00+05:30
BANKNIFTY DEC FUT Buy CALL
BUY NIFTY DEC FUT 12:00:48.302710 False True False cc_1 2024-11-27 12:00:00+05:30
SELL NIFTY DEC FUT 12:00:48.302710 False True False cc_1 2024-11-27 12:00:00+05:30
Order Exited {‘options_name’: ‘BANKNIFTY 24 DEC 52400 CALL’, ‘qty’: 15, ‘sl’: 52422.25, ‘CE_PE’: ‘CE’, ‘entry_price’: 949.9, ‘Trailed’: ‘yes_I_have_trailed’, ‘entry_orderid’: ‘42241127399413’}
hi,
get_historical_data method is not working from Dhan_tradehull.py, i have passed the following parameters from my temp.py
import talib
import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
tsl = Tradehull(client_code,token_id) # tradehull_support_library
previous_hist_data = tsl.get_historical_data(‘HDFCBANK’,‘NSE’,12)
print(previous_hist_data)
OHLC Response: {‘status’: ‘failure’, ‘remarks’: “expiry_code value must be [‘0’,‘1’,‘2’,‘3’]”, ‘data’: ‘’}
Invalid OHLC data or missing.
Please help. how can it we resolved
Exception at calling ltp as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: None, ‘error_type’: None, ‘error_message’: None}, ‘data’: {‘data’: {‘805’: ‘Too many requests. Further requests may result in the user being blocked.’}, ‘status’: ‘failed’}}
Traceback (most recent call last):
File “/Users/parveenchugh/latest/strategy1.py”, line 44, in
current_price = ltp_data[‘NIFTY 28 NOV 24300 PUT’]
~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: ‘NIFTY 28 NOV 24300 PUT’
Do find updated code, I have made changes in buy side
Added up4 for entry
up4 = trade_info['traded'] is None
For trailing the code says
price_has_moved_20_pct = index_ltp_value > (trade_info['entry_price'] * 1.2)
Notice your entry is in options , so entry price is around Rs 993.95 and index ltp is around 52350 # Note I have taken example rates
so price_has_moved_20_pct condition equates to = (52350 > (993.95*1.2)) which will always be True
when the condition becomes True, below code sets stoploss to entry price (993.95)
if price_has_moved_20_pct and position_has_not_been_trailed:
trade_info['sl'] = trade_info['entry_price']
and the SL hit condition becomes True, because code is comparing index_ltp to options ltp, which is always True
sl_hit = index_ltp_value < trade_info['sl']
tg_hit = index_ltp_value < cc5_2['SUPERT_10_3.0']
Which leads to immdeiate SL exit
Important:
As of now work only with single script and trade_info,
as of now I have not taught how to manage multiple positions with all the details.
I will take this topic in next live lecture This week.
Also till then do work with a test account
Also we can review this code in live lecture also,
CODE
import pdb
import traceback
import time
import datetime
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import pandas_ta as ta
import talib
import warnings
warnings.filterwarnings("ignore")
# ---------------for Dhan login ----------------
client_code = ""
token_id = ""
tsl = Tradehull(client_code, token_id)
available_balance = tsl.get_balance()
print("Available Balance:", available_balance)
# Define the symbols to trade
symbols = ['NIFTY DEC FUT']
traded = "no"
trade_info = {"options_name": None, "qty": None, "sl": None, "CE_PE": None, "entry_price": None, "Trailed": None, "entry_orderid": None, "traded":None}
while True:
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 20):
print("Wait for market to start", current_time)
continue
if current_time > datetime.time(23, 25):
print("Market is over, Bye Bye see you tomorrow", current_time)
break
for index_name in symbols:
index_chart = tsl.get_historical_data(tradingsymbol=index_name, exchange='NFO', timeframe="15")
time.sleep(3)
index_chart_5 = tsl.get_historical_data(tradingsymbol=index_name, exchange='NFO', timeframe="5")
index_ltp = tsl.get_ltp_data(names=[index_name])
if index_chart.empty or index_chart_5.empty:
time.sleep(60)
continue
index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)
supertrend = ta.supertrend(index_chart_5['high'], index_chart_5['low'], index_chart_5['close'], 10, 3)
index_chart_5 = pd.concat([index_chart_5, supertrend], axis=1, join='inner')
cc_1 = index_chart.iloc[-1]
cc_2 = index_chart.iloc[-2]
cc_3 = index_chart.iloc[-3]
cc5_2 = index_chart_5.iloc[-2]
# ---------------------------- BUY ENTRY CONDITIONS ----------------------------
up1 = cc_2['rsi'] > 60
up2 = cc_3['rsi'] < 60
up3 = cc_2['high'] < cc_1['close']
up4 = trade_info['traded'] is None
print(f"BUY {index_name}\t{current_time}\t{up1}\t{up2}\t{up3}\tcc_1 {str(cc_1['timestamp'])}")
# ---------------------------- SELL ENTRY CONDITIONS ----------------------------
dt1 = cc_2['rsi'] < 40
dt2 = cc_3['rsi'] > 40
dt3 = cc_2['low'] > cc_1['close']
dt4 = ???
print(f"SELL {index_name}\t{current_time}\t{dt1}\t{dt2}\t{dt3}\tcc_1 {str(cc_1['timestamp'])}\n")
expiry = '24-12-2024' if 'BANKNIFTY' in index_name else '26-12-2024'
if up1 and up2 and up3 and up4:
print(index_name, "Buy CALL")
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying=index_name.split()[0], Expiry=expiry)
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.update({"options_name": ce_name, "qty": lot_size, "sl": cc_2['low'], "CE_PE": "CE", "entry_orderid": entry_orderid, "traded":"yes_I_have_entered_position"})
time.sleep(1)
trade_info['entry_price'] = tsl.get_executed_price(orderid=trade_info['entry_orderid'])
if dt1 and dt2 and dt3:
print(index_name, "Buy PUT")
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying=index_name.split()[0], Expiry=expiry)
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.update({"options_name": pe_name, "qty": lot_size, "sl": cc_2['high'], "CE_PE": "PE", "entry_orderid": entry_orderid})
time.sleep(1)
trade_info['entry_price'] = tsl.get_executed_price(orderid=trade_info['entry_orderid'])
if traded == "yes":
long_position = trade_info['CE_PE'] == "CE"
short_position = trade_info['CE_PE'] == "PE"
# Check if LTP is a dictionary or an integer and extract the correct value
index_ltp_value = index_ltp.get(index_name) if isinstance(index_ltp, dict) else index_ltp
if index_ltp_value is None:
print(f"Failed to get LTP for {index_name}")
continue
# Ensure comparison is with the correct type
price_has_moved_20_pct = index_ltp_value > (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_value < trade_info['sl']
tg_hit = index_ltp_value < cc5_2['SUPERT_10_3.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')
# if you want re-entry to happen, unblock below code
# trade_info = {"options_name": None, "qty": None, "sl": None, "CE_PE": None, "entry_price": None, "Trailed": None, "entry_orderid": None, "traded":None}
check this link : Learn Algo Trading with Python | Codes | Youtube Series - #1065 by Tradehull_Imran
The code was calling data too fast
See this link : Learn Algo Trading with Python | Codes | Youtube Series - #860 by Tradehull_Imran
Hi
@Tradehull_Imran
I am glad and appreciate for your back-to-back support
Thank You Very much
Thanks sir, now change time.sleep(5) for slow data
class DhanHQMock:
pass
def get_live_data(url):
return 120
api = DhanHQMock()
required_people_intrested = (100 // 6)
url = “Learn Algo Trading with Python | Codes | Youtube Series”
people_intrested = get_live_data(url)
if people_intrested > required_people_intrested:
print(“ BUILD ALGO LIVE SESSION ON YOUTUBE”)
print(“ LIVE QUESTIONS AND ANSWER IMPLEMENTATION”)
else:
print(“Wait ”) i mean to say supper interested to continue learning with @Tradehull_Imran
There’s only one video that remains in this series!
Are you all excited for it ?
Sir, I’m excited for the remaining video and looking forward to the next one more series.This will keep our community members engaged and help them gain more expertise while fostering a user-friendly experience through continuous interaction. Request keep the same teacher for next series.