Learn Algo Trading with Python | Codes | Youtube Series

Hi @CHETAN_99

Did this error happened after the SL / Tg was hit.

Also do use this code … for managing orderbook error

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 requests
import os
from playsound import playsound

# ------------------------------ DHAN API LOGIN SETUP ------------------------------
client_code = "1102790337"
token_id    = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM3NTIzMDg4LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMjc5MDMzNyJ9.UWD34xX9VHFQ9ULmjhiufvqp-jzrDXFpKKOLVj0ix6wDVxOUZDmScAiQc-TBN_-TDT7wZl5AjLsFMFiuwrVciQ"

tsl = Tradehull(client_code, token_id)

watchlist = ["IDEA", "ONGC"]
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 = []

# Calculate current loss
my_loss = 0
max_loss = -150

# Maximum allowed open positions
max_open_positions = 2

# ---------------------------- TELEGRAM ALERT FUNCTION ------------------------------
bot_token = ""
receiver_chat_id = ""

# ---------------------------- FUNCTION TO GET LIVE DATA ------------------------------
live_Trading.range("A2:Z100").value = None
completed_orders_sheet.range("A2:Z100").value = None

for name in watchlist:
    orderbook[name] = single_order.copy()

# ------------------------------ SOUND FUNCTION ------------------------------
def play_sound():
    winsound.Beep(9500, 500)

# ------------------------------- QTY FUNCTION ------------------------------
def calculate_trade_quantity(balance, risk_per_trade, stock_price):
    risk_amount = balance * risk_per_trade
    quantity = risk_amount // stock_price
    return max(5, int(quantity))

# ------------------------------ MAIN ALGO ------------------------------
while True:
    live_pnl = tsl.get_live_pnl()
    current_time = datetime.datetime.now().time()

    if current_time < datetime.time(9, 30):
        print(f"Wait for market to start Chetan", current_time)
        time.sleep(1)
        continue

    if current_time > datetime.time(14, 45):
        order_details = tsl.cancel_all_orders()
        print(f"Market over Closing all trades !! Bye Bye See you Tomorrow Chetan", current_time)
        break

    if my_loss <= int(max_loss) and tsl.cancel_all_orders == "yes" and tsl.kill_switch == 'ON':
        print("Max loss reached! Cancelling all orders and stopping trading.")
        tsl.cancel_all_orders()
        break

    print("\n started while Loop \n")

    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_1 = tsl.get_historical_data(
                tradingsymbol=name.upper(),
                exchange='NSE',
                timeframe='5'
            )
            chart_1['upperband'], chart_1['middleband'], chart_1['lowerband'] = talib.BBANDS(chart_1['close'], timeperiod=20, nbdevup=1.5, nbdevdn=1.5, matype=0)

            # Define index for the latest candle
            index = len(chart_1) - 1  # Last index in the DataFrame

            # Reference the latest two candles (previous and current)
            alert_candle = chart_1.iloc[index - 1]  # Second last candle (previous candle)
            letest_candle = chart_1.iloc[index]  # Last candle (current candle)

            # BUY ENTRY CONDITION
            bc1 = alert_candle['close'] < alert_candle['lowerband']
            bc6 = orderbook[name]['traded'] is None

            # SELL ENTRY CONDITION
            sc1 = alert_candle['close'] > alert_candle['upperband']
            sc6 = orderbook[name]['traded'] is None

        except Exception as e:
            print(e)
            continue

        if bc1 and bc6:
            print("buy ", name, "\t")

            margin_available = tsl.get_balance()
            margin_required = alert_candle['close'] / 5.0  # LEVERAGE AMOUNT

            if margin_available < margin_required:
                print(f"Less margin, not taking order: margin_available is {margin_available} and margin_required is {margin_required} for {name}")
                continue

            # Calculating the quantity to trade
            stock_price = alert_candle['close']  # Use the close price of the alert candle as the stock price
            risk_per_trade = 0.06  # Risk 6%
            trade_quantity = calculate_trade_quantity(
                balance=margin_available, risk_per_trade=risk_per_trade, stock_price=stock_price
            )

            orderbook[name]['name'] = name
            orderbook[name]['date'] = str(current_time.date())
            orderbook[name]['entry_time'] = str(current_time.time())[:8]
            orderbook[name]['buy_sell'] = "BUY"
            orderbook[name]['qty'] = trade_quantity

            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'])

                # Stop-loss and target calculations
                stop_loss_amount = alert_candle['high'] - alert_candle['low']
                stop_loss_price = orderbook[name]['entry_price'] - stop_loss_amount
                target_profit_price = orderbook[name]['entry_price'] + (4 * stop_loss_amount)

                orderbook[name]['sl'] = round(stop_loss_price, 2)
                orderbook[name]['tg'] = round(target_profit_price, 2)

                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)

                max_open_positions += 1

            except Exception as e:
                print(e)

        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"
                    tg_hit = ltp > orderbook[name]['tg']
                except Exception as e:
                    print(e)

                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"

                        # TELEGRAM MESSAGE
                        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] = single_order.copy()

                    except Exception as e:
                        print(e)

                if tg_hit:
                    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'] = "Bought_TG_hit"

                        # TELEGRAM MESSAGE
                        message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                        message = f"TG_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] = single_order.copy()


                        winsound.Beep(1500, 10000)

                    except Exception as e:
                        print(e)