Learn Algo Trading with Python | Codes | Youtube Series

Hello @Tradehull_Imran ,

To execute trailing sl in my existing order, I am canceling previous SL and re-executing new SL. Here I found some code issue in Dhan_Tradehull_V2.py file

sl_orderid = '72241216240721'
new_sl_id = tsl.cancel_order(sl_orderid) 

Traceback (most recent call last):
  File "c:\Projects\Algo Trading (Dhan)\TS1_Total_Analysis\Dhan_Tradehull_V2.py", line 1421, in cancel_order
    response = self.xts1.cancel_order(appOrderID=OrderID,orderUniqueIdentifier='123abc',clientID=self.client_code)
AttributeError: 'Tradehull' object has no attribute 'xts1'


What is this xts1 object and orderUniqueIdentifier=‘123abc’?

Please look into this.

Thanks,
Sudip Nath

This is because symbol name change for GMRINFRA → GMRAIRPORT. In your “Dhan_Tradehull_V2.py”, search GMRINFRA and replace with GMRAIRPORT. Hope this should resolve your issue.

1 Like

SAME ISSUE I AM FACING IN ORDER MODIFICATION FOR SL TRAILLING, @Tradehull_Imran SIR PLEASE CHECK THE ISSUE

@SUDIP_NATH U CAN MODIFY UR CODE TO THIS

tsl.Dhan.cancel_order(sL_orderid)

BUT FOR MY ERROR ITS STILL COMPLICATED

Hello Sir @Tradehull_Imran & aijaz
please help me in this, check live modification if its working at ur side or not.
even its placing new order continually but not modifying order (the same order)

i have tried all 3 its not working can any one help me in this please

1.
stoploss_orderid = tsl.Dhan.modify_order(stoploss_orderid, "STOPLIMIT", QTY, price, trigger, "MIS")

2.
stoploss_orderid = tsl.modify_order(stoploss_orderid, "STOPLIMIT", QTY, price, trigger, "MIS")

3.
stoploss_orderid = tsl.modify_order(stoploss_orderid, "STOPLIMIT", QTY, price, trigger)

error:
2024-12-16 12:22:12,164 - INFO - Buy Order Placed. Order ID: 12241216236708
2024-12-16 12:22:12,504 - INFO - Order Status: PENDING
2024-12-16 12:25:26,122 - INFO - Order Status: TRADED
2024-12-16 12:25:27,322 - INFO - Stop Loss Order Placed. Order ID: 102241216485008
2024-12-16 12:25:28,311 - INFO - Buy Price: 148.5, Current Price: 147.9, Target: 168.5, Stop Loss: 138.8
2024-12-16 12:35:00,014 - ERROR - Error in fetching order details or status: Traceback (most recent call last):
File “C:\Users\DELL\AppData\Local\Temp\ipykernel_11976\3384396219.py”, line 157, in
stoploss_orderid = tsl.Dhan.modify_order(stoploss_orderid, “STOPLIMIT”, QTY, new_sl_price - 1, new_sl_price, “MIS”)
TypeError: modify_order() missing 2 required positional arguments: ‘disclosed_quantity’ and ‘validity’

2024-12-16 12:35:00,265 - INFO - Order Status: TRADED
2024-12-16 12:35:01,564 - INFO - Stop Loss Order Placed. Order ID: 12241216245508
2024-12-16 12:35:02,502 - ERROR - Error in fetching order details or status: Traceback (most recent call last):
File “C:\Users\DELL\AppData\Local\Temp\ipykernel_11976\3384396219.py”, line 157, in
stoploss_orderid = tsl.Dhan.modify_order(stoploss_orderid, “STOPLIMIT”, QTY, new_sl_price - 1, new_sl_price, “MIS”)
TypeError: modify_order() missing 2 required positional arguments: ‘disclosed_quantity’ and ‘validity’

2024-12-16 12:35:02,761 - INFO - Order Status: TRADED
2024-12-16 12:35:03,969 - INFO - Stop Loss Order Placed. Order ID: 42241216501508
2024-12-16 12:35:04,907 - ERROR - Error in fetching order details or status: Traceback (most recent call last):
File “C:\Users\DELL\AppData\Local\Temp\ipykernel_11976\3384396219.py”, line 157, in
stoploss_orderid = tsl.Dhan.modify_order(stoploss_orderid, “STOPLIMIT”, QTY, new_sl_price - 1, new_sl_price, “MIS”)
TypeError: modify_order() missing 2 required positional arguments: ‘disclosed_quantity’ and ‘validity’

@Aijaz_Ahmad

hi sir

D:\algo\Lab test\Dhan codebase>py buy_sell.py
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-16.csv
Got the instrument file
AVAILABLE BALANCE = 5144.61
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-904’, ‘error_type’: ‘Rate_Limit’, ‘error_message’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}, ‘data’: {‘errorType’: ‘Rate_Limit’, ‘errorCode’: ‘DH-904’, ‘errorMessage’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}}
[0] > d:\algo\lab test\dhan codebase\buy_sell.py(100)()
→ index_chart[‘ema8’] = talib.EMA(index_chart[‘close’], timeperiod=8)
(Pdb++)

Try this

tsl.Dhan.cancel_order

1 Like

Hi @Himansshu_Joshi,

See the error itself says which arguments are missing i.e. ‘disclosed_quantity’ & ‘validity’ these 2 are required for modifying the order.

Try this:

stoploss_orderid = tsl.Dhan.modify_order(stoploss_orderid, “STOPLIMIT”, QTY, new_sl_price - 1, new_sl_price, “MIS”, disclosed_quantity=‘0’, validity=‘Day’)

1 Like

Hi Sir @Tradehull_Imran Sir,

Following is the code to get combined Premium:
But it’s showing error sir. Please correct .

import pdb
import time
from datetime import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib

client_code = “xxxxxx”
token_id = “xxxxxxxxxx”
tsl = Tradehull(client_code,token_id)

call_list = [‘NIFTY 19 DEC 24100 CALL’, ‘NIFTY 19 DEC 24100 PUT’]

while True:

current_time = datetime.now()
print(f"Current Time: {current_time}")

ltp_data = tsl.get_ltp_data(names=call_ist)

ce_ltp = ltp_data.get['NIFTY 19 DEC 24100 CALL',0]
pe_ltp = ltp_data.get['NIFTY 19 DEC 24100 PUT',0]

atm_combined_premium = (round(ce_ltp + pe_ltp),1)

print(f"ATM Combined Premium: {atm_combined_premium}")


time.sleep(0.5)

ERROR: name call_list is not defined.
Correct me sir

I am wirking on API Upgrade folder sir.

Hello @Tradehull_Imran Sir
Take profit = stop loss * 1.5(risk : revard=1 :1.5) kya hamne shi likha sir
:point_down: please guide

 # Define Take Profit Target (e.g., 1.5 times stop-loss points)
take_profit_price = trade_info['sl'] + (abs(trade_info['sl'] - index_ltp) * 1.5)

tk_profit = index_ltp >= take_profit_price  # Take profit for long positions

tk_profit = index_ltp <= take_profit_price  # Take profit for short positions

Hi sir @Tradehull_Imran sir,
Following code in getting Historical data is also giving error sir.
CODE

import pdb
import time
from datetime import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib

client_code = “xxxxxx”
token_id = “xxxxxxxxxx”
tsl = Tradehull(client_code,token_id)

data_day = tsl.get_historical_data(tradingsymbol = ‘BANKNIFTY’,exchange = ‘INDEX’,timeframe=“DAY”)
data_5 = tsl.get_historical_data(tradingsymbol = ‘BANKNIFTY’,exchange = ‘INDEX’,timeframe=“5”)

options_data = tsl.get_historical_data(tradingsymbol = ‘NIFTY 19 DEC 24000 CALL’,exchange = ‘NFO’,timeframe=“5”)

options_data[‘ema30’] = talib.EMA(options_data[‘close’], timeperiod=30)

print(data_day)
print(data_5)
print(options_data)

pdb.set_trace()


ERROR:
options_data[‘ema30’] = talib.EMA(options_data[‘close’], timeperiod=30)

‘NoneType’ object is not subscriptable

Please check it sir.

Hi @Tradehull_Imran Sir,

now i am stuck at Bulk order , please suggest what i can do in it, if want to place 5000qty how i can do it?

suggestion required for:

  1. Bulk order Management
  2. As my codes fetch order id to manage entry, sl , sl trailing & target but only for 1 order id. How it will manage multiple order ids for the same management.
# Constants
TRADING_SYMBOL = "NIFTY 19 DEC 25200 CALL"
QTY = 25 #Lot Qty
BUYING_TRIGGER = 120  # Price Lower
BUYING_LIMIT_PRICE = BUYING_TRIGGER + 0.50 #Higher in case of buy
STOP_LOSS_OFFSET = 138.8
TARGET_OFFSET = 2
EXCHANGE = "NFO"
ORDER_TYPE = "STOPLIMIT"
SLTRAIL_STEP = 1  # SL trails by ₹1 for every ₹1 increase in price
PROFIT_LOCK_POINT = 15  # Lock profit after 15 points
VALIDITY = "DAY"  # No Need to Change it

# Initialize Tradehull
tsl = Tradehull(CLIENT_CODE, TOKEN_ID)

# Main trading logic
try:
    # Place the entry (buy) order
    buy_entry_orderid = tsl.order_placement(
        TRADING_SYMBOL,
        EXCHANGE,
        QTY,
        BUYING_LIMIT_PRICE,
        BUYING_TRIGGER,
        ORDER_TYPE,
        "BUY",
        "MIS",
        legName="ENTRY_LEG"
    )
    logging.info(f"Buy Order Placed. Order ID: {buy_entry_orderid}")
    time.sleep(0.2)

    while True:
        try:
            # Fetch order status
            order_status = tsl.get_order_status(orderid=buy_entry_orderid)
            logging.info(f"Order Status: {order_status}")
            time.sleep(1)

            if order_status == "PENDING":
                # Monitor stop-loss offset
                current_market_price_dict = tsl.get_ltp_data(names=[TRADING_SYMBOL])
                current_market_price = current_market_price_dict.get(TRADING_SYMBOL)

                if current_market_price and current_market_price <= STOP_LOSS_OFFSET:
                    logging.warning(
                        f"Market price {current_market_price} is below stop-loss offset {STOP_LOSS_OFFSET}. Canceling order."
                    )
                    tsl.Dhan.cancel_order(buy_entry_orderid)
                    logging.info(f"Order {buy_entry_orderid} canceled. Stopping algorithm.")
                    break

            elif order_status == "TRADED":
                buy_price = tsl.get_order_detail(orderid=buy_entry_orderid).get("price")
                target_price = buy_price + TARGET_OFFSET
                stop_loss_price = STOP_LOSS_OFFSET
                sl_limit_price = stop_loss_price - 1
                profit_locked = False  # To track if profit lock has started
                last_sl_price = stop_loss_price  # Track the last stop-loss price

                # Place the initial stop-loss order
                stoploss_orderid = tsl.order_placement(
                    TRADING_SYMBOL,
                    EXCHANGE,
                    QTY,
                    sl_limit_price,
                    stop_loss_price,
                    "STOP_LOSS",
                    "SELL",
                    "MIS",
                    legName="STOP_LOSS_LEG"
                )
                logging.info(f"Stop Loss Order Placed. Order ID: {stoploss_orderid}")
                time.sleep(0.1)

                # Monitor for target price or stop-loss adjustment
                while True:
                    current_market_price_dict = tsl.get_ltp_data(names=[TRADING_SYMBOL])
                    current_market_price = current_market_price_dict.get(TRADING_SYMBOL)

                    if not current_market_price:
                        logging.error("Failed to fetch current market price.")
                        continue

                    if current_market_price >= target_price:
                        # Cancel the stop-loss order
                        tsl.Dhan.cancel_order(stoploss_orderid)
                        logging.info(f"Stop Loss Order {stoploss_orderid} canceled.")

                        # Place the target sell order
                        sell_entry_orderid = tsl.order_placement(
                            TRADING_SYMBOL,
                            EXCHANGE,
                            QTY,
                            0,
                            0,
                            "MARKET",
                            "SELL",
                            "MIS",
                            legName="TARGET_LEG"
                        )
                        logging.info(f"Target reached. Selling {TRADING_SYMBOL} at market price. Sell Order ID: {sell_entry_orderid}")
                        break

                    # Lock profit after PROFIT_LOCK_POINT
                    elif not profit_locked and current_market_price >= buy_price + PROFIT_LOCK_POINT:
                        profit_locked = True
                        new_sl_price = buy_price + 1  # Lock profit at Buy Price + 1
                        stoploss_orderid = tsl.Dhan.modify_order(
                            CLIENT_CODE,
                            stoploss_orderid,
                            "STOP_LOSS",
                            legName="STOP_LOSS_LEG",
                            quantity=QTY,
                            price=new_sl_price - 1,
                            disclosedQuantity=0,
                            triggerPrice=new_sl_price,
                            validity="DAY"
                        )
                        last_sl_price = new_sl_price
                        logging.info(f"Profit locked. Stop Loss set to {new_sl_price}")

                    # Trail stop-loss after profit lock
                    elif profit_locked and current_market_price >= last_sl_price + SLTRAIL_STEP:
                        new_sl_price = last_sl_price + SLTRAIL_STEP
                        stoploss_orderid = tsl.Dhan.modify_order(
                            CLIENT_CODE,
                            stoploss_orderid,
                            "STOP_LOSS",
                            legName="STOP_LOSS_LEG",
                            quantity=QTY,
                            price=new_sl_price - 1,
                            disclosedQuantity=0,
                            triggerPrice=new_sl_price,
                            validity="DAY"
                        )
                        last_sl_price = new_sl_price
                        logging.info(f"Trailing Stop Loss updated to {new_sl_price}")

                    logging.info(
                        f"Buy Price: {buy_price}, Current Price: {current_market_price}, Target: {target_price}, Stop Loss: {last_sl_price}"
                    )
                    time.sleep(0.2)

                break

        except Exception as e:
            logging.error(f"Error in fetching order details or status: {traceback.format_exc()}")
            time.sleep(0.2)

except Exception as e:
    logging.error(f"Unexpected error: {traceback.format_exc()}")

Folks we were thinking to host a offline workshop this Saturday in Dhan Office hosted by @Tradehull_Imran Sir.

Who all of you are from Mumbai? We would be happy to host you all.

1 Like

Hi @Rahul, Hope people from other cities will be able to join online / see the recording.
Thanks

1 Like

hi@tradehull imran,
“Sir, I got this code from ChatGPT; please create a complete code based on it according to your expertise.”( call / put buying simultaneously srategy … pls sir help me … This code is difficult to understand )

import time
import random # For simulating signals; replace with actual data feed

class TradingBot:
def init(self):
self.positions = # Keeps track of open positions

def execute_call_buy(self, price, stop_loss, target):
    print(f"Executing CALL BUY at {price}, SL: {stop_loss}, TG: {target}")
    self.positions.append({
        'type': 'CALL',
        'entry_price': price,
        'stop_loss': stop_loss,
        'target': target
    })

def execute_put_buy(self, price, stop_loss, target):
    print(f"Executing PUT BUY at {price}, SL: {stop_loss}, TG: {target}")
    self.positions.append({
        'type': 'PUT',
        'entry_price': price,
        'stop_loss': stop_loss,
        'target': target
    })

def manage_positions(self, current_price):
    for position in self.positions[:]:  # Iterate over a copy of the list
        entry_price = position['entry_price']
        stop_loss = position['stop_loss']
        target = position['target']

        if position['type'] == 'CALL':
            if current_price >= target:
                print(f"CALL Target Hit: Exiting at {current_price}")
                self.positions.remove(position)
            elif current_price <= stop_loss:
                print(f"CALL Stop Loss Hit: Exiting at {current_price}")
                self.positions.remove(position)

        elif position['type'] == 'PUT':
            if current_price <= target:
                print(f"PUT Target Hit: Exiting at {current_price}")
                self.positions.remove(position)
            elif current_price >= stop_loss:
                print(f"PUT Stop Loss Hit: Exiting at {current_price}")
                self.positions.remove(position)

def simulate_signals(self):
    """Simulates signal generation for demonstration purposes."""
    signals = []

    # Simulate random signal generation
    if random.random() > 0.5:  # 50% chance of generating a Call signal
        signals.append(('CALL', random.uniform(100, 200)))

    if random.random() > 0.5:  # 50% chance of generating a Put signal
        signals.append(('PUT', random.uniform(100, 200)))

    return signals

def run(self):
    """Main loop for trading bot."""
    while True:
        # Simulate receiving market data
        current_price = random.uniform(100, 200)  # Replace with live market price
        print(f"Current Price: {current_price}")

        # Simulate signal generation
        signals = self.simulate_signals()

        # Handle signals
        for signal_type, price in signals:
            stop_loss = price * 0.98  # Example: 2% stop loss
            target = price * 1.02    # Example: 2% target

            if signal_type == 'CALL':
                self.execute_call_buy(price, stop_loss, target)
            elif signal_type == 'PUT':
                self.execute_put_buy(price, stop_loss, target)

        # Manage open positions
        self.manage_positions(current_price)

        # Wait for the next iteration
        time.sleep(1)  # Replace with appropriate interval

if name == “main”:
bot = TradingBot()
bot.run()

I am from Thane and would like to attend the offline class. however, I just came into contact with the tradehull program and not yet completed it. would it be a problem if i have not yet used tradehull?

I was using previously shared api (marketfeed & other) but was unable to get ltp easily.

1 Like

Yes, It;s a good idea. Please do make it sir.

1 Like

Title: Help Needed: KeyError and UnboundLocalError in Python Trading Script

Hi everyone,

I’m running into an issue while working on my Python trading algorithm. I’ve attached a screenshot of both the error and the relevant part of the code.

Errors I’m Getting

  1. KeyError: ‘NIFTY’ occurs when I try to access ltp_data['Underlying'] in the ATM_Strike_Selection function.
  2. UnboundLocalError: local variable ‘strike’ referenced before assignment happens after the first error when I try to use the strike variable.

Code Context:

Here is the line where the issue originates:

ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='12-12-2024')

I suspect ltp_data['Underlying'] is missing the key 'NIFTY' or returning None. However, I’m not sure why or how to fix it.


What I’ve Tried:

  1. Debugging ltp_data to see its content.
  2. Verifying that 'NIFTY' exists before calling the function.

I still couldn’t resolve the issue. Could someone guide me on how to debug this further or help fix these errors?

Any suggestions or advice would be greatly appreciated!
@Tradehull_Imran

Hi, Even i was facing this issue…its due to rate limits…pls replace the codebase with this latest version

1 Like

@sammed_patil can you try

ce_strike, pe_strike, ce_ITM_price, pe_ITM_price = tsl.ITM_Strike_Selection(“XXX”, “XXX”, 3)

1 Like