Bracket Order Code for Dhan

Can I get Bracket Order code for Dhan for trading in equity and fno

Hi @Karun149 ,

Refer the below code :

# For Equity
bo_orderid = tsl.order_placement(tradingsymbol = 'ACC', exchange = 'NSE', quantity = 1, price = 0, trigger_price = 0, order_type = 'MARKET', transaction_type = 'BUY', trade_type = 'BO', bo_profit_value=5, bo_stop_loss_value=5)

# For FNO
bo_orderid = tsl.order_placement(tradingsymbol = 'NIFTY 08 MAY 22400', exchange = 'NFO', quantity = 1, price = 0, trigger_price = 0, order_type = 'MARKET', transaction_type = 'BUY', trade_type = 'BO', bo_profit_value=5, bo_stop_loss_value=5)

Order in FNO is not getting placed

Hi @Karun149 ,

Can you share your code?

Error is - This BOT Is Picking New File From Dhan
Got the instrument file
— Signal Check —
CE: NIFTY 22 MAY 24800 CALL, Close=125.4, RSI=60.6, ADX=27.8, ATR=6.6
PE: NIFTY 22 MAY 24800 PUT, Close=124.8, RSI=47.1, ADX=13.9, ATR=6.1
:white_check_mark: Signal Generated: BUY CE | Strike=NIFTY 22 MAY 24800 CALL | Close=125.4 | RSI=60.6 | ADX=27.8 | ATR=6.6
:x: Exception: order_placement() got an unexpected keyword argument ‘bo_stop_loss_value’

Code is - # Setup logging
logging.basicConfig(level=logging.INFO, format=‘%(asctime)s %(levelname)s: %(message)s’)

executed_strikes = set()

Fetch indicator function

def get_indicator_data(symbol: str):
try:
response = tsl.get_historical_data(tradingsymbol=symbol, exchange=‘NFO’, timeframe=‘1’)
data = response[1] if isinstance(response, tuple) else response
if not isinstance(data, pd.DataFrame) or data.empty or ‘timestamp’ not in data.columns:
return None

    df = data.copy()
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    df.set_index('timestamp', inplace=True)
    df['rsi'] = ta.rsi(df['close'], length=14)
    adx = ta.adx(df['high'], df['low'], df['close'], length=14)
    df['adx'] = adx['ADX_14']
    df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
    latest = df.iloc[-1]
    return {
        "symbol": symbol,
        "timestamp": latest.name.strftime("%Y-%m-%d %H:%M"),
        "close": round(latest['close'], 1),
        "rsi": round(latest['rsi'], 1),
        "adx": round(latest['adx'], 1),
        "atr": round(latest['atr'], 1)
    }
except Exception as e:
    logging.error(f"Indicator error: {e}")
    return None

Main loop

while True:
now = datetime.now().time()
if now < dt_time(9, 30) or now > dt_time(23, 15):
print(“Outside trading hours. Sleeping…”)
time.sleep(60)
continue

try:
    ce_symbol, pe_symbol, _ = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
    ce_data = get_indicator_data(ce_symbol)
    pe_data = get_indicator_data(pe_symbol)

    if ce_data and pe_data:
        print("--- Signal Check ---")
        print(f"CE: {ce_data['symbol']}, Close={ce_data['close']}, RSI={ce_data['rsi']}, ADX={ce_data['adx']}, ATR={ce_data['atr']}")
        print(f"PE: {pe_data['symbol']}, Close={pe_data['close']}, RSI={pe_data['rsi']}, ADX={pe_data['adx']}, ATR={pe_data['atr']}")
        valid_ce = ce_data["rsi"] > 60 and ce_data["adx"] > 25
        valid_pe = pe_data["rsi"] > 60 and pe_data["adx"] > 25

        if valid_ce or valid_pe:
            trade_data = ce_data if valid_ce else pe_data
            signal = "BUY CE" if valid_ce else "BUY PE"
            print(f"✅ Signal Generated: {signal} | Strike={trade_data['symbol']} | Close={trade_data['close']} | RSI={trade_data['rsi']} | ADX={trade_data['adx']} | ATR={trade_data['atr']}")

            strike_symbol = trade_data["symbol"]
            if strike_symbol in executed_strikes:
                print("⚠️ Skipping: Same strike already traded.")
                time.sleep(10)
                continue

            lot_size = tsl.get_lot_size(tradingsymbol=strike_symbol)
            atr = trade_data["atr"]
            quantity = max(1, int(lot_size / atr))

            # Place BO order
            bo_order = tsl.order_placement(
                tradingsymbol=strike_symbol,
                exchange='NFO',
                quantity=quantity,
                price=0,
                trigger_price=0,
                order_type='MARKET',
                transaction_type='BUY',
                trade_type='BO',
                bo_profit_value=5,  # You can set this dynamically if needed
                bo_stop_loss_value=5  # You can set this dynamically if needed
            )
            bo_order_id = bo_order.get("order_id") or bo_order.get("data", {}).get("order_id")
            print(f"🛒 BO Market Order Placed. ID: {bo_order_id}")

            executed_strikes.add(strike_symbol)
            print("✅ Trade completed. Ready for next signal.")

except Exception as e:
    logging.error(f"Error: {e}")
    print(f"❌ Exception: {e}")

time.sleep(15)

Hi @Karun149 ,

Replace the below code:

bo_order = tsl.order_placement(
                tradingsymbol=strike_symbol,
                exchange='NFO',
                quantity=quantity,
                price=0,
                trigger_price=0,
                order_type='MARKET',
                transaction_type='BUY',
                trade_type='BO',
                bo_profit_value=5,  # You can set this dynamically if needed
                bo_stop_loss_Value=5  # You can set this dynamically if needed
            )