Learn Algo Trading with Python | Codes | Youtube Series

Hello @Tradehull_Imran Sir
Kabhi - kabhi ye error aa rha hai :point_down:

Exception at calling ltp as {'status': 'failure', 'remarks': "('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))", 'data': ''}
Traceback (most recent call last):
  File "c:/Users/VINAY/Desktop/Smart traders/my code base test.py", line 64, in <module>
    index_ltp      = tsl.get_ltp_data(names = ['NIFTY DEC FUT'])['NIFTY DEC FUT']

Please help

Hi, @Tradehull_Imran & @RahulDeshpande ,

Sir, When New Youtube series , will be uploaded. In that Videos , Please explain, How to cancel TP/SL Orders , ( if TP or SL executed ) , and how to remove that stock from Traded watchlist . Also please cover Trailing Stop Loss.

Till then, Is there any way to use Bracket order for Multiple Stocks…?

1 Like

combied_chart[‘combined_volume’] = ce_chart[‘volume’]+pe_chart[‘volume’]

1 Like

it is running on system so logically it should stop

1 Like

@Tradehull_Imran Bangalore chalenge aap ? :stuck_out_tongue:

2 Likes

Workshop by @Tradehull_Imran has begun :smiley:

2 Likes

How did you manage to resolve this Issue?
I am facing the same !

shall we join online / watch? @Tradehull_Imran

1 Like

Sir @Tradehull_Imran When I request one-minute historical data for Nifty, I encounter this type of error.


D:\Python\1.0\10. Session10- 4th Live Algo>py Nifty_data.py
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-21.csv
Got the instrument file
Error processing GMRINFRA: No expiry date found for GMRINFRA
[0] > d:\python\1.0\10. session10- 4th live algo\nifty_data.py(20)()
→ Nifty_Data = tsl.get_historical_data( tradingsymbol=“NIFTY”, exchange=“NSE”, timeframe=“1”)
(Pdb++) Nifty_Data
*** NameError: name ‘Nifty_Data’ is not defined
(Pdb++) Nifty_Data = tsl.get_historical_data( tradingsymbol=“NIFTY”, exchange=“NSE”, timeframe=“1”)
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-907’, ‘error_type’: ‘Data_Error’, ‘error_message’: ‘System is unable to fetch data due to incorrect parameters or no data present’}, ‘data’: {‘errorType’: ‘Data_Error’, ‘errorCode’: ‘DH-907’, ‘errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}
(Pdb++)


Please inform early :sob: this time @RahulDeshpande
Bangalore or Hyderabad both are fine for me (even mumbai also) :grinning:

1 Like

Hi Rahul
I am Suraj who attended the offline algo training at your main office on 21 Dec 2024 could you share the link where I can get all the basic codes (building blocks) ?
thanks

Hello Everyone
@Tradehull_Imran

Sir, I am trying to get RSI of Index on 5 min time frame using the code but getting error

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

Client details

client_code = “”
token_id = “”

Initialize Tradehull

tsl = Tradehull(client_code, token_id)

available_balance = tsl.get_balance()
leveraged_margin = available_balance5
max_trades = 2
per_trade_margin = (leveraged_margin/max_trades)
max_loss = (available_balance
1)/100*-1

watchlist = [“NIFTY”,‘BANKNIFTY’,‘NIFTYIT’,‘NIFTYAUTO’,‘NIFTYFMCG’]
traded_wathclist =

for index_exchange in watchlist:
time.sleep(1)

    chart_1          = tsl.get_historical_data(tradingsymbol = index_exchange,exchange = 'NSE',timeframe="1")
    chart_5          = tsl.get_historical_data(tradingsymbol = index_exchange,exchange = 'NSE',timeframe="5") # this call has been updated to get_historical_data call, 
    chart_15         = tsl.get_historical_data(tradingsymbol = index_exchange,exchange = 'NSE',timeframe="15") # this call has been updated to get_historical_data call,

    if (chart_1 is None) or (chart_5 is None) :
        continue

    if (chart_1.empty) or (chart_5.empty):
        continue

    if (chart_15.empty) or (chart_15.empty):
        continue

    if (chart_15 is None) or (chart_15 is None) :
        continue


    # Conditions that are on 1 minute timeframe
    chart_5['rsi'] = talib.RSI(chart_5['close'], timeperiod=14) #pandas
    cc_5           = chart_5.iloc[-1]  #pandas  completed candle of 5 min timeframe
     
    print(stock_name, "RSI on 5 Min Time Frame is", cc_5['rsi'] )

The error is
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-907’, ‘error_type’: ‘Data_Error’, ‘error_message’: ‘System is unable to fetch data due to incorrect parameters or no data present’}, ‘data’: {‘errorType’: ‘Data_Error’, ‘errorCode’: ‘DH-907’, ‘errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}

Where I am doing wrong , please help

Hi@ Imran sir,
Please provide an algorithm code that will implement both a Call Buy strategy and a Put Buy strategy simultaneously. When a Call Buy signal is received, the algorithm should execute a call buy, and when a Put Buy signal is received, it should execute a put buy and simultaneously SL, TG, will work and both will work in intraday."

“Sir, I got this code from ChatGPT; please create a complete code based on it according to your expertise.” see …

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()

Hi @Zee2Zahid

check below code, for taking entry based on option chart



index_bc1 = index_chart['rsi'] > 60


if index_bc1:

	
	ce_name, pe_name, ce_ITM_price, pe_ITM_price = tsl.ITM_Strike_Selection(Underlying='BANKNIFTY', Expiry=0, ITM_count=10) # dynamically select an ITM strike 
	options_chart = tsl.get_historical_data(tradingsymbol = ce_name, exchange = 'NFO',timeframe="5")

	indi          = ta.supertrend(options_chart['high'], options_chart['low'], options_chart['close'], 10, 2)
	options_chart = pd.concat([options_chart, indi], axis=1, join='inner')

	lot_size   = tsl.get_lot_size(tradingsymbol = ce_name)
	optios_bc1 = options_completed_candle['SUPERTd_10_2.0'] == 1

	options_completed_candle = options_chart.iloc[-1]

	if optios_bc1:
		entry_orderid  = tsl.order_placement(tradingsymbol=ce_name ,exchange='NFO', quantity=lot_size, price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')
		sl_orderid     = tsl.order_placement(tradingsymbol=ce_name ,exchange='NFO', quantity=lot_size, price=29, trigger_price=30, order_type='STOPLIMIT', transaction_type='SELL', trade_type='MIS')





1 Like

Hi @Rajashekhar_Rangappa

The historical data code for BFO seems to be working fine.

do use the latest codebase link : Dhan_Tradehull_V2.py - Google Drive

Hi @Himansshu_Joshi
I am not clear on the question,

but on high level understating on the question

we can use this code, to place sliced orders
also now the order_ids variable will give all the list of orders that have been placed

(Pdb++) order_ids = tsl.place_slice_order(tradingsymbol="NIFTY 26 DEC 23950 CALL",exchange="NFO",transaction_type="BUY",quantity=5000,order_type="LIMIT",trade_type="MIS",price=60)
(Pdb++) order_ids
['22241223302627', '52241223303927', '12241223294727']
(Pdb++)

Hi @Aijaz_Ahmad

It seems the code is sending wrong values in fetching historical data
maybe, the name is incorrect or expired or the exchange may be incorrect

do check all the input parameters used in historical api all by printing them , also send the code being used

do use the latest codebase link : Dhan_Tradehull_V2.py - Google Drive

Update: RESLOVED in 2.3.

@Tradehull_Imran
I’m getting

Exception in Getting OHLC data as single positional indexer is out-of-bounds

for same line of code
chart = tsl.get_historical_data("SENSEX DEC FUT", "BFO", "5")

I’m on

Codebase Version 2.2 : Rate Limits

1 Like

Hi @Qaisar

Below code seems to be working fine on my end


entry_orderid  = tsl.order_placement(tradingsymbol='SENSEX 27 DEC 78600 CALL' ,exchange='BFO', quantity=600, price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')

do use the latest codebase : Dhan_Tradehull_V2.py - Google Drive

Also let me know if it works after that

Hi @Rajashekhar_Rangappa

Codebase Version 2.2 : Rate Limits is older version

do use the latest codebase link : Dhan_Tradehull_V2.py - Google Drive

Also let me know if it works after that