Dear Imran Sir @Tradehull_Imran
Help with Stoploss and Order placement in My Option trade
import pdb
import os
import time
import datetime
import re # Importing regex library to extract strike price
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib
from prettytable import PrettyTable # Import PrettyTable
from plyer import notification # Import plyer notification module
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import xlwings as xw
import copy
# Initialize the API
client_code = "1104020944"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzQyOTk4MjM2LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwNDAyMDk0NCJ9.4WMNjQ4OZT1ahceJVa1p1aMFPs4TWeM93IA8CQwV6hW6RR_dIwrTR4yG_i84GQFLwroiZJj2nXblJLYyLEV6vQ"
tsl = Tradehull(client_code, token_id)
# Select ITM-ATM-OTM strike options
CE_symbol_name, PE_symbol_name, CE_ITM_price, PE_ITM_price = tsl.ITM_Strike_Selection(Underlying='NIFTY', Expiry=0, ITM_count=1)
watchlist = [CE_symbol_name, PE_symbol_name]
# Define order structure
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(r"E:\Dhan Algo\1. Api Upgrade\1. Api Upgrade\Finally\Nifty_Live.xlsx")
live_Trading = wb.sheets['Live_Trading']
completed_orders_sheet = wb.sheets['completed_orders']
live_Trading.range("A2:Z100").value = None
completed_orders_sheet.range("A2:Z100").value = None
completed_orders = []
reentry = "yes" # "yes/no"
for stock_name in watchlist:
orderbook[stock_name] = single_order.copy()
# Start checking market conditions
while True:
current_time = datetime.datetime.now() # Get current time
live_pnl = tsl.get_live_pnl() # Fetch live PnL
# # Market open condition
# if current_time.time() < datetime.time(9, 16):
# print("⏳ Waiting for market to start...", current_time)
# time.sleep(4) # Wait 60 seconds before checking again
# continue
# # Market close condition or stop loss reached
# if current_time.time() > datetime.time(15, 20):
# tsl.kill_switch('ON')
# tsl.cancel_all_orders()
# print("🔴 Market is over, Bye Bye! See you tomorrow!", current_time)
# break
# Get the latest LTP (Last Traded Price) data for the watchlist
all_ltp = tsl.get_ltp_data(names=watchlist)
for stock_name in watchlist:
# Convert orderbook to DataFrame and update live trading sheet
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
# Loop through each stock in the watchlist
for stock_name in watchlist:
time.sleep(0.4)
print("📈 Checking:", stock_name)
try:
# Fetch historical OHLC (Open, High, Low, Close) data
chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='NFO', timeframe='1')
if chart_1 is None or chart_1.empty:
print(f"Exception in Getting OHLC data as Check the Tradingsymbol or Exchange for {stock_name}")
continue
# Calculate technical indicators
chart_1['adx'] = talib.ADX(chart_1['high'], chart_1['low'], chart_1['close'], timeperiod=14)
chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14)
# Fetch latest data (second last candle)
cc_1 = chart_1.iloc[-2]
current_price = cc_1['close'] # Extract Strike Price
# Display data in a formatted table using PrettyTable
table = PrettyTable()
# Define the table columns
table.field_names = ["Timestamp", "Current Price", "RSI", "ADX"]
# Add rows to the table
table.add_row([
cc_1['timestamp'], current_price, f"{cc_1['rsi']:.2f}", f"{cc_1['adx']:.2f}" # Ensure there are 4 values
])
# Print the table
print(table)
# Define conditions for a valid buy signal
adx_condition = cc_1['adx'] > 10
rsi_condition = cc_1['rsi'] > 50
no_repeat_order = orderbook[stock_name]['traded'] is None
except Exception as e:
print(e)
continue
# Buy Condition Check
if adx_condition and rsi_condition and no_repeat_order:
print("✅", stock_name, "meets buy conditions, placing order")
orderbook[stock_name] = {} # Initialize the orderbook entry for the stock_name
orderbook[stock_name]['name'] = stock_name
orderbook[stock_name]['date'] = str(current_time.date())
orderbook[stock_name]['entry_time'] = str(current_time.time())[:8]
orderbook[stock_name]['buy_sell'] = "BUY"
orderbook[stock_name]['qty'] = 75
try:
# Place the entry order
entry_orderid = tsl.order_placement(stock_name, 'NFO', orderbook[stock_name]['qty'], 0, 0, 'MARKET', 'BUY', 'MIS')
orderbook[stock_name]['entry_orderid'] = entry_orderid
orderbook[stock_name]['entry_price'] = tsl.get_executed_price(orderid=entry_orderid)
# Place Target / Stoploss order
orderbook[stock_name]['tg'] = round(orderbook[stock_name]['entry_price'] * 1.05, 1)
orderbook[stock_name]['sl'] = round(orderbook[stock_name]['entry_price'] * 0.95, 1)
sl_orderid = tsl.order_placement(stock_name, 'NFO', orderbook[stock_name]['qty'], 0, orderbook[stock_name]['sl'], 'STOPLIMIT', 'SELL', 'MIS')
orderbook[stock_name]['sl_orderid'] = sl_orderid
orderbook[stock_name]['traded'] = "yes"
# Add stock to traded list to prevent duplicate orders
traded_watchlist.append(stock_name)
except Exception as e:
print(f"Error placing order for {stock_name}: {e}")
continue
if orderbook[stock_name]['traded'] == "yes":
bought = orderbook[stock_name]['buy_sell'] == "BUY"
if bought:
try:
ltp = all_ltp(stock_name)
sl_hit = tsl.get_order_status(orderid=orderbook[stock_name]['sl_orderid']) == "TRADED"
tg_hit = ltp > orderbook[stock_name]['tg']
except Exception as e:
print(e)
# pdb.set_trace(header = "error in sl order cheking")
continue
if sl_hit:
try:
orderbook[stock_name]['exit_time'] = str(current_time.time())[:8]
orderbook[stock_name]['exit_price'] = tsl.get_executed_price(orderid=orderbook[stock_name]['sl_orderid'])
orderbook[stock_name]['pnl'] = round((orderbook[stock_name]['exit_price'] - orderbook[stock_name]['entry_price']) * orderbook[stock_name]['qty'], 1)
orderbook[stock_name]['remark'] = "Bought_SL_hit"
if reentry == "yes":
completed_orders.append(orderbook[stock_name])
orderbook[stock_name] = None
except Exception as e:
print(e)
# pdb.set_trace(header = "error in sl_hit")
continue
if tg_hit:
try:
tsl.cancel_order(OrderID=orderbook[stock_name]['sl_orderid'])
time.sleep(2)
square_off_buy_order = tsl.order_placement(orderbook[stock_name]['stock_name'], 'NFO', orderbook[stock_name]['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
orderbook[stock_name]['exit_time'] = str(current_time.time())[:8]
orderbook[stock_name]['exit_price'] = tsl.get_executed_price(orderid=square_off_buy_order)
orderbook[stock_name]['pnl'] = round((orderbook[stock_name]['exit_price'] - orderbook[stock_name]['entry_price']) * orderbook[stock_name]['qty'], 1)
orderbook[stock_name]['remark'] = "Bought_Target_hit"
if reentry == "yes":
completed_orders.append(orderbook[stock_name])
orderbook[stock_name] = None
except Exception as e:
print(e)
# pdb.set_trace(header = "error in tg_hit")
continue
Following is Error
✅ NIFTY 13 MAR 22500 PUT meets buy conditions, placing order
'Got exception in place_order as {'status': 'failure', 'remarks': {'error_code': 'DH-906', 'error_type': 'Order_Error', 'error_message': 'Limit Price Out Of Range, Price Should Be In Range 57.60 - 86.40.'}, 'data': {'errorType': 'Order_Error', 'errorCode': 'DH-906', 'errorMessage': 'Limit Price Out Of Range, Price Should Be In Range 57.60 - 86.40.'}}
Error placing order for NIFTY 13 MAR 22500 PUT: name 'traded_watchlist' is not defined
'dict' object is not callable
My Algo place Order Successfully buy Without Stoploss and without target order.
Need help with this. I gone through all of your training videos but cant find solution for this.