Eid Mubarak @Tradehull_Imran Sir.
Hello @Tradehull_Imran ,
I am using Codebase Version 3 and I am getting this error while using ATM_Strike_Selection function.
Code:
atm_ce_strike, atm_pe_strike, strike = tsl.ATM_Strike_Selection("BANKNIFTY", 1)
Error:
Please support to resolve this error.
Dear Imran Ali Sir, Wish you and your family a very happy Ramzan, with blessed life of hundred years, with all happiness, good health, peace, prosperity fulfilling all your endeavors.
VBR Prasad
@Tradehull_Imran I was edited this code for equity
but iam getting only qty ??? my code is correct or not please help me
import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as ta
import xlwings as xw
import winsound
import sqn_lib
client_code = â1000728206â
token_id = âeyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzQ1Mzg1MjQyLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTAwMDcyODIwNiJ9.e10wS0hlk9DwEFw-MHH_FxFhmO_I7C05RDxhXgGcEpN2a8OpwyUGWcSZxmi3Q-CxTUOscaBTaPkQNfxzlxtwEAâ
tsl = Tradehull(client_code,token_id)
opening_balance = tsl.get_balance()
base_capital = 1205.02
market_money = opening_balance - base_capital
beacuse I am loosing money, so I have 0 market money, and I can take risk on the current opening balance and not on the base capital
if (market_money < 0):
market_money = 0
base_capital = opening_balance
market_money_risk = (market_money1)/100
base_capital_risk = (base_capital0.5)/100
max_risk_for_today = base_capital_risk + market_money_risk
max_order_for_today = 2
risk_per_trade = (max_risk_for_today/max_order_for_today)
atr_multipler = 3
risk_reward = 3
watchlist = [âTATACONSUMâ,âKOTAKBANKâ,âAPOLLOHOSPâ,âONGCâ,âICICIBANKâ,âTATAMOTORSâ,âHINDUNILVRâ,âJIOFINâ,âSBILIFEâ,âHDFCLIFEâ,âAXISBANKâ,âBELâ,âNESTLEINDâ,âITCâ,âBHARTIARTLâ,âSUNPHARMAâ,âCOALINDIAâ,âJSWSTEELâ,âHDFCBANKâ,âEICHERMOTâ,âSBINâ,âBAJAJFINSVâ,âRELIANCEâ,âLTâ,âGRASIMâ,âASIANPAINTâ,âTECHMâ,âNTPCâ,âBAJFINANCEâ,âTITANâ,âTATASTEELâ,âULTRACEMCOâ,âTCSâ,âHEROMOTOCOâ,âADANIPORTSâ,âBAJAJ-AUTOâ,âDRREDDYâ,âHINDALCOâ,âPOWERGRIDâ,âMARUTIâ,âADANIENTâ,âTRENTâ,âINFYâ,âHCLTECHâ,âZOMATOâ,âM&Mâ,âCIPLAâ,âSHRIRAMFINâ,âWIPROâ,âINDUSINDBKâ]
single_order = {ânameâ:None, âdateâ:None , âentry_timeâ: None, âentry_priceâ: None, âbuy_sellâ: None, âqtyâ: None, âslâ: None, âexit_timeâ: None, âexit_priceâ: None, âpnlâ: None, âremarkâ: None, âtradedâ:None}
orderbook = {}
wb = xw.Book(âLive Trade Data.xlsxâ)
live_Trading = wb.sheets[âLive_Tradingâ]
completed_orders_sheet = wb.sheets[âcompleted_ordersâ]
reentry = âyesâ #âyes/noâ
completed_orders =
bot_token = â7746461948:AAHR7MQSe40UA9jMZuw7-u2XhvBpwwR1ozQâ
receiver_chat_id = â1570007384â
live_Trading.range(âA2:Z100â).value = None
completed_orders_sheet.range(âA2:Z100â).value = None
for name in watchlist:
orderbook[name] = single_order.copy()
while True:
print("starting while Loop \n\n")
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 15):
print(f"Wait for market to start", current_time)
time.sleep(1)
continue
live_pnl = tsl.get_live_pnl()
max_loss_hit = live_pnl < (max_risk_for_today*-1)
market_over = current_time > datetime.time(15, 15)
if max_loss_hit or market_over:
order_details = tsl.cancel_all_orders()
print(f"Market over Closing all trades !! Bye Bye See you Tomorrow", current_time)
pdb.set_trace()
break
all_ltp = tsl.get_ltp_data(names = watchlist)
for name in watchlist:
orderbook_df = pd.DataFrame(orderbook).T
live_Trading.range('A1').value = orderbook_df
completed_orders_df = pd.DataFrame(completed_orders)
completed_orders_sheet.range('A1').value = completed_orders_df
current_time = datetime.datetime.now()
print(f"Scanning {name} {current_time}")
try:
chart = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="5")
chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
indi = ta.supertrend(chart['high'], chart['low'], chart['close'], 7, 3)
chart = pd.concat([chart, indi], axis=1, join='inner')
sqn_lib.sqn(df=chart, period=21)
chart['market_type'] = chart['sqn'].apply(sqn_lib.market_type)
chart['atr'] = talib.ATR(chart['high'], chart['low'], chart['close'], timeperiod=14)
cc = chart.iloc[-2]
no_of_orders_placed = orderbook_df[orderbook_df['qty'] > 0].shape[0] + completed_orders_df[completed_orders_df['qty'] > 0].shape[0]
# buy entry conditions
bc1 = cc['rsi'] > 1
bc2 = cc['SUPERTd_7_3.0'] == 1
bc3 = cc['market_type'] != "neutral"
bc4 = no_of_orders_placed < 5
bc5 = orderbook[name]['traded'] is None
except Exception as e:
print(e)
continue
if bc1 and bc2 and bc3 and bc4 and bc5:
print("buy ", name, "\t")
margin_avialable = tsl.get_balance()
margin_required = cc['close']/4.5
if margin_avialable < margin_required:
print(f"Less margin, not taking order : margin_avialable is {margin_avialable} and margin_required is {margin_required} for {name}")
continue
# ce_name, pe_name, ce_otm_strike, pe_otm_strike = tsl.OTM_Strike_Selection(Underlying='NIFTY', Expiry=0, OTM_count=2)
# lot_size = tsl.get_lot_size(tradingsymbol = ce_name)
# options_chart = tsl.get_historical_data(tradingsymbol = ce_name,exchange = 'NFO',timeframe="5")
# options_chart['atr'] = talib.ATR(options_chart['high'], options_chart['low'], options_chart['close'], timeperiod=14)
rc_chart = chart.iloc[-1]
orderbook[name]['name'] = name
# orderbook[name]['options_name'] = ce_name
orderbook[name]['date'] = str(current_time.date())
orderbook[name]['entry_time'] = str(current_time.time())[:8]
orderbook[name]['max_holding_time'] = datetime.datetime.now() + datetime.timedelta(hours=2)
orderbook[name]['buy_sell'] = "BUY"
sl_points = rc_chart['atr']*atr_multipler
orderbook[name]['qty'] = 1 #int(int((risk_per_trade*0.7)/sl_points))
try:
entry_orderid = tsl.order_placement(tradingsymbol=name ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')
orderbook[name]['entry_orderid'] = entry_orderid
orderbook[name]['entry_price'] = tsl.get_executed_price(orderid=orderbook[name]['entry_orderid'])
orderbook[name]['sl'] = round(orderbook[name]['entry_price'] - sl_points, 1) # 99
orderbook[name]['tsl'] = orderbook[name]['sl']
price = orderbook[name]['sl'] - 0.05
sl_orderid = tsl.order_placement(tradingsymbol=name ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=orderbook[name]['sl'], order_type='STOPMARKET', transaction_type ='SELL', trade_type='MIS')
orderbook[name]['sl_orderid'] = sl_orderid
orderbook[name]['traded'] = "yes"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"Entry_done {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
except Exception as e:
print(e)
pdb.set_trace(header= "error in entry order")
if orderbook[name]['traded'] == "yes":
bought = orderbook[name]['buy_sell'] == "BUY"
if bought:
try:
ltp = all_ltp[name]
sl_hit = tsl.get_order_status(orderid=orderbook[name]['sl_orderid']) == "TRADED"
holding_time_exceeded = datetime.datetime.now() > orderbook[name]['max_holding_time']
current_pnl = round((ltp - orderbook[name]['entry_price'])*orderbook[name]['qty'],1)
except Exception as e:
print(e)
pdb.set_trace(header = "error in sl order cheking")
if sl_hit:
try:
orderbook[name]['exit_time'] = str(current_time.time())[:8]
orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=orderbook[name]['sl_orderid'])
orderbook[name]['pnl'] = round((orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty'],1)
orderbook[name]['remark'] = "Bought_SL_hit"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"SL_HIT {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
if reentry == "yes":
completed_orders.append(orderbook[name])
orderbook[name] = None
except Exception as e:
print(e)
pdb.set_trace(header = "error in sl_hit")
if holding_time_exceeded and (current_pnl < 0):
try:
tsl.cancel_order(OrderID=orderbook[name]['sl_orderid'])
time.sleep(2)
square_off_buy_order = tsl.order_placement(tradingsymbol=orderbook[name]['name'] ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=0, order_type='MARKET', transaction_type='SELL', trade_type='MIS')
orderbook[name]['exit_time'] = str(current_time.time())[:8]
orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=square_off_buy_order)
orderbook[name]['pnl'] = (orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty']
orderbook[name]['remark'] = "holding_time_exceeded_and_I_am_still_facing_loss"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"holding_time_exceeded_and_I_am_still_facing_loss {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
if reentry == "yes":
completed_orders.append(orderbook[name])
orderbook[name] = None
winsound.Beep(1500, 10000)
except Exception as e:
print(e)
pdb.set_trace(header = "error in tg_hit") # Testing changes. sadhasd ajsdas dbna sdb abs da sd asd abs d asd
chart_name = orderbook[name]['name']
chart = tsl.get_historical_data(tradingsymbol = chart_name,exchange = 'NSE',timeframe="5")
chart['atr'] = talib.ATR(chart_name['high'], chart_name['low'], chart_name['close'], timeperiod=14)
rc_chart = chart.iloc[-1]
sl_points = rc_chart['atr']*atr_multipler
chart_ltp = tsl.get_ltp_data(names = chart_name)[chart_name]
tsl_level = chart_ltp - sl_points
if tsl_level > orderbook[name]['tsl']:
trigger_price = round(tsl_level, 1)
price = trigger_price - 0.05
tsl.modify_order(order_id=orderbook[name]['sl_orderid'],order_type="STOPLIMIT",quantity=25,price=price,trigger_price=trigger_price)
orderbook[name]['tsl'] = tsl_level
# order_ids = tsl.place_slice_order(tradingsymbol=âNIFTY 19 DEC 24400 CALLâ, exchange=âNFOâ,quantity=10000, transaction_type=âBUYâ,order_type=âLIMITâ,trade_type=âMISâ,price=0.05)
@Tradehull_Imran
My first algo is live today. Thank you for your support and teaching us about Algo Trading.
You explained most of the concepts very well.
@Dhan - Thank you for organising such wonderful youtube series.
Here is glimpse of my live Algo:
Thanks!
Hi @Tradehull_Imran and @Dhan ,
I want to calculate margin utilised in my Delta Neutral Option Selling Strategy.
margin = tsl.margin_calculator(tradingsymbol=scrip_name, exchange=âNFOâ, quantity=quantity, price=price, transaction_type=transaction_type, trade_type=âMARGINâ, trigger_price=0)[âtotalMarginâ]
For sold legs it showing margin requirement much higher according to naked option selling.
When we execute strategies buy OTM legs first and then sell ATM legs in this case margin requirement is much lesser. How can I get these margin values using programming.
I need this info to calculate overall margin required for strategy and then decide number of lots accordingly.
Please assist me on this.
Thanks!
No change is required in the ALGO, the codebase is just upgraded.
Refer the below link for more details:
Dhan-Tradehull ¡ PyPI
Hi @Qaisar ,
Make sure Dhan-TradeHull file is not present in the same folder. Else not it will use the previous version.
Just FYI⌠NIFTY got executed w/o any issue today also. I think itâs not related to version.
Hi @Akshay_Bawane ,
You can use the below code :
name = 'NIFTY 03 APR 23200 CALL'
quote_data = tsl.get_quote_data(name)
quote_data[name]['depth']['buy']
quote_data[name]['depth']['sell']
Hi @rohit2312 ,
The code seems to be working fine:
Make sure you have subscribed to Data API, and verify if you are able to fetch the historical data.
Hi @Lekhini ,
Hereâs how you can fetch LTP for a stock,
ltp = tsl.get_ltp_data(['ACC'])
ltp_acc = ltp['ACC']
Make sure you have subscribed to Data API.
Hi @Jagrut_Nemade ,
The code seems to be working fine âŚ
Kindly use the upgraded 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:
Refer the below pypi link for more details:
https://pypi.org/project/Dhan-Tradehull/
Hi @Manish1 ,
Currently Dhan supports only 5 days historical data for 1 hour timeframe. You can use âDAYâ timeframe to get more data.
Hi @Rajeev_Kallur ,
Consider the below scenario:
entry_price = 100 # Sold at âš100
trailing_sl = 120 # Initial stop-loss
trail_step = 5 # Move SL by âš5 as price drops
min_trail_gap = 10 # Trail only after âš10 profit
while True:
ltp = get_live_option_price(symbol)
profit = entry_price - ltp
# Trailing logic
if profit >= min_trail_gap:
new_sl = ltp + trail_step
if new_sl < trailing_sl:
trailing_sl = new_sl
print(f"Trailed SL to âš{trailing_sl}")
Hi @Aijaz_Ahmad ,
We will check on this.
@Tradehull_Imran Where can I find the Dhan_Tradehull_V3 script?
Hi @Siddhesh_Amrute,
Wonderful⌠best luck, coloring the console output, would have an extra effectâŚ
Hi @Siddhesh_Amrute ,
Congratulations⌠you started.
I am still version 2 & 3. as it does not have any reference doc.
Can u share your contact number or call me @7042367771 wanted to seek some help.
Regards
Thank you @Tradehull_Imran