Learn Algo Trading with Python | Codes | Youtube Series

Thanks for the comment. I also want to share my viewpoints as part of the discussion. I will post that soon.

[https://www.youtube.com/watch?v=Lb70i1zdolw]

Advanced Algo Trading Series | Episode 5: Testing Your Algo | Part 2

another very useful video which continuation of Episode 5 part 1

Thank you @Tradehull_Imran sir

2 Likes

@Tradehull_Imran sir,
In tutorials, trades are executed intraday. If I want to switch to positional trading, what changes should I make to my strategy? Could you please guide us on adapting my algo-program for positional trades? This will help us back-test it for longer timeframes too.

n Sir, I can’t thank you enough, and I genuinely mean that!

1 Like

Advanced Algo Trading Series | Episode 5: Testing Your Algo | Part 2

Hi, @Rahul @RahulDeshpande
I have found not sync situation on this video
screen share is lagging but what sir telling that is proper

please try to check from 5mins and onwards

@Tradehull_Imran Hello Sir, i just started today, and i am stuck as i cannot fetch historical data. i have checked the thread and downloaded the latest codebase, websocket and tradehull .py files but still stuck.


cmd error:
Microsoft Windows [Version 10.0.19045.5555]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>py “Dhan_codebase usage.py”
Codebase Version 2.8 : Solved - Strike Selection Issue
-----Logged into Dhan-----
reading existing file all_instrument 2025-03-09.csv
Got the instrument file
{‘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’}}
Traceback (most recent call last):
File “C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull_V2.py”, line 569, in get_intraday_data
raise Exception(ohlc)
Exception: {‘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’}}
{‘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’}}
Traceback (most recent call last):
File “C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull_V2.py”, line 569, in get_intraday_data
raise Exception(ohlc)
Exception: {‘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’}}
available_balance 9875.96
Traceback (most recent call last):
File “Dhan_codebase usage.py”, line 24, in
ltp1 = tsl.get_ltp(‘ACC’)
AttributeError: ‘Tradehull’ object has no attribute ‘get_ltp’

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>previous_hist_data = tsl.get_historical_data(‘ACC’,‘NSE’,12)
‘previous_hist_data’ is not recognized as an internal or external command,
operable program or batch file.

Advanced Algo Trading Series | Episode 5: Testing Your Algo | Part 2

@Tradehull_Imran sir, One another question

You have mentioned we can take another API for test to make it faster
My question
Another API means another account require, Am I right sir ?
So how can we mentation two login simultaneously with shareable files.

Thank you sir

@Danish_Ansari
For codebase use new approach as given below:

  1. Install codebase using pip install Dhan-Tradehull
  2. Verify codebase is installed properly pip show Dhan-Tradehull
  3. Import into your code from Dhan_Tradehull import Tradehull
  4. Remove from Dhan_Tradehull_V2 import Tradehull from your code

Let us know if you still face the issue.

1 Like

@Subhajitpanja
Yes, you will need more accounts and subscription to Data API.
One simple approach could be:

  1. You can declare separate “client code” and “access token” for data related operation and order execution related operations.
  data_client_id = "1234"
  data_access_token = "xyz"
  order_client_id = "6789"
  order_access_token "abcd"

  tsl_data = Tradehull(data_client_id, data_access_token)
  tsl_order = Tradehull(order_client_id, order_access_token)
  1. Modify your code to use tsl_order for order execution related operations and getting balance operations. This way orders will be executed in same account where you are maintaining balance.
  2. Duplicate your finalised algo code file
  3. Change only data_client_id and data_access_token variable values in 2nd code file to use 2nd account data api
  4. Also, split watchlist into two parts and then use first watchlist in first code file and 2nd part in 2nd code file.
  5. Then open two separate command prompt on your system and execute Code 1 and Code 2 file.
  6. You can also create additional variable called code file name and maintain it as new column in order book excel. This will help you to track from which code file order was executed.

Complex approach is there are parallelism techniques in Python using which you can execute code using multi threading technique to improve performance. So using this you can do your stuff using single code file.

2 Likes

@Subhajitpanja Please find below code examples for different types of order:

order_type:

  • MARKET: Market Order
  • LIMIT: Limit Order
  • STOPMARKET: Stop Loss Order
  • BO: Bracket Order

trade_type:

  • MIS: Intraday orders
  • CNC: Delivery orders

Market Order:

tsl.place_order(
    tradingsymbol="RELIANCE",
    exchange="NSE",
    transaction_type="BUY",
    quantity=10,
    order_type="MARKET",
    trade_type="CNC"
)

Limit Order

tsl.place_order(
    tradingsymbol="TCS",
    exchange="NSE",
    transaction_type="SELL",
    quantity=5,
    order_type="LIMIT",
    trade_type="CNC",
    price=3500.00
)

Stop Loss Order

tsl.place_order(
    tradingsymbol="INFY",
    exchange="NSE",
    transaction_type="BUY",
    quantity=10,
    order_type="STOPMARKET",
    trade_type="MIS",
    trigger_price=1500.00
)

Bracket Order

tsl.place_order(
    tradingsymbol="SBIN",
    exchange="NSE",
    transaction_type="BUY",
    quantity=10,
    order_type="LIMIT",
    trade_type="BO",
    price=500.00,
    bo_profit_value=10.00,
    bo_stop_loss_Value=5.00
)

Cancel Specific Order

order_id = '12241210603927'
order_status = tsl.cancel_order(OrderID=order_id)

Cancel All Orders

order_details = tsl.cancel_all_orders()
2 Likes

still same issue.


error:
Microsoft Windows [Version 10.0.19045.5555]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>py “Dhan_codebase usage.py”
Codebase Version 2.8 : Solved - Strike Selection Issue
-----Logged into Dhan-----
reading existing file all_instrument 2025-03-09.csv
Got the instrument file
{‘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’}}
Traceback (most recent call last):
File “C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py”, line 569, in get_intraday_data
raise Exception(ohlc)
Exception: {‘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’}}
{‘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’}}
Traceback (most recent call last):
File “C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py”, line 569, in get_intraday_data
raise Exception(ohlc)
Exception: {‘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’}}
available_balance 9875.96
Traceback (most recent call last):
File “Dhan_codebase usage.py”, line 24, in
ltp1 = tsl.get_ltp(‘ACC’)
AttributeError: ‘Tradehull’ object has no attribute ‘get_ltp’

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>previous_hist_data = tsl.get_historical_data(‘ACC’,‘NSE’,12)
‘previous_hist_data’ is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>

@Siddhesh_Amrute @Tradehull_Imran Also I observed that this message appears when i run websocket “Disconnected from WebSocket feed.” and then it fetch LTP but only once, if i need fresh LTP or LTP for a new script i add in excel then i need to run codebase and websocket again.


cmd output:
Microsoft Windows [Version 10.0.19045.5555]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>py Dhan_websocket.py
Reading existing file all_instrument 2025-03-09.csv
Watchlist changed. Reconnecting the feed…
Disconnected from WebSocket feed.
Authorizing…
Authorization successful!
13:56:48.348871: LTP Received
13:56:48.520723: LTP Received
13:56:48.583220: LTP Received
13:56:48.723835: LTP Received
13:56:48.864450: LTP Received
13:56:49.005065: LTP Received
13:56:49.067562: LTP Received
13:56:49.223802: LTP Received
13:56:49.364419: LTP Received
13:56:49.426913: LTP Received
13:56:49.567528: LTP Received
13:56:49.630024: LTP Received
13:56:49.770642: LTP Received
13:56:49.926878: LTP Received
13:56:50.067493: LTP Received
13:56:50.208108: LTP Received
13:56:50.364348: LTP Received
13:56:50.489340: LTP Received
13:56:50.645579: LTP Received
13:56:50.692452: LTP Received
13:56:50.833069: LTP Received
13:56:50.973682: LTP Received
13:56:51.129922: LTP Received
13:56:51.192418: LTP Received
13:56:51.333033: LTP Received
13:56:51.379906: LTP Received
13:56:51.536144: LTP Received
13:56:51.598640: LTP Received
13:56:51.739255: LTP Received
13:56:51.801752: LTP Received
13:56:51.942367: LTP Received
13:56:52.004863: LTP Received
13:56:52.161101: LTP Received
13:56:52.207974: LTP Received
13:56:52.348589: LTP Received
13:56:52.504828: LTP Received
13:56:52.645444: LTP Received
13:56:52.801683: LTP Received
13:56:52.942298: LTP Received
13:56:53.098538: LTP Received
13:56:53.239155: LTP Received
13:56:53.379771: LTP Received
13:56:53.520391: LTP Received
13:56:53.661000: LTP Received
13:56:53.723498: LTP Received
13:56:53.864111: LTP Received
13:56:54.004726: LTP Received
13:56:54.067223: LTP Received
13:56:54.207837: LTP Received
13:56:54.270335: LTP Received
13:56:54.410951: LTP Received
13:56:54.567191: LTP Received
13:56:54.707804: LTP Received
13:56:54.864044: LTP Received
13:56:54.926540: LTP Received
13:56:55.067154: LTP Received
13:56:55.207770: LTP Received

Advanced Algo Trading Series | Episode 5: Testing Your Algo | Part 2

@Tradehull_Imran Sir, I have one more question.

Due to margin problems, you are canceling the order and waiting to update the margin using the sleep method.

Is there an alternative to the sleep method?

I would like to check whether the previous margin has increased or not after canceling the stop loss.

I’m not sure if there is a subscribe or event listener like concept in Python that I can use instead of sleep.

I prefer to avoid sleep because if the margin doesn’t update within a specific time due to issues like network glitches, it could cause problems. Additionally, if the margin updates in real-time, my program would run faster.

Thank you sir

@Siddhesh_Amrute
Thanks so much

probably @Tradehull_Imran already discussed this to some previous videos. thanks to remind me again :pray:t2:

@Siddhesh_Amrute Super concept waow

Although the @Dhan is already increasing their Data API rate limits, I have another idea for added caution. We can use an additional API as a backup. If we ever hit the data API limit for any reason, we can send a Telegram message and switch to the second API.

@Tradehull_Imran sir

2 Likes

@Siddhesh_Amrute ,

Bahut Badhiya… such information will be very useful.
Entry Oder-

entry_order_id = tsl.order_placement(
option_symbol, 
"NFO", 
client_qty, 
0, 
0, 
"MARKET", 
direction, 
"MIS")

SL Order- BTW can you tell me whether my SL Order is right or wrong…?
I hv used order type as “SL-M”

sl_order_id = tsl.order_placement(
option_symbol, 
"NFO", 
client_qty, 
0, 
sl_price, 
"**SL-M**", 
"SELL" if direction == "BUY" else "BUY", 
"MIS")

@Tradehull_Imran
i am getting error code DH-907. Not able to fix this can u please. Not able to understand where I am going wrong. How do if fix this. Looking forward to your response.

Error:
C:\1. Fujitsu Data\Python_SR\Dhan_Algo>py Dhan_EQ.py
Codebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-03-09.csv
Got the instrument file
{‘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’}}
Traceback (most recent call last):
File “C:\Users\sanje\AppData\Local\Programs\Python\Python38\lib\site-packages\Dhan_Tradehull\Dhan_Tradehull.py”, line 525, in get_intraday_data
raise Exception(ohlc)
Exception: {‘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’}}
Traceback (most recent call last):
File “Dhan_EQ.py”, line 62, in
chart[‘rsi’] = talib.RSI(chart[‘close’], timeperiod = 14)
TypeError: ‘NoneType’ object is not subscriptable

My Script
from dhanhq import dhanhq
from Dhan_Tradehull import Tradehull
import mibian
import datetime
import numpy as np
import pandas as pd
import traceback
import pytz
import requests
import pdb
import os
import time
import json
from pprint import pprint
import logging
import warnings
from typing import Tuple, Dict
from collections import Counter
import urllib.parse
import talib
import datetime

Login Details

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

client_id = “xxxxxxxxxx”

access_token = “xxxxxxxxxx”

dhan = dhanhq(“client_id”,“access_token”)

watchlist = [
“TITAGARH”, “RELIANCE”, “SRF”, “APOLLOTYRE”, “IRFC”, “MANAPPURAM”, “CAMS”, “TIINDIA”, “ATGL”, “ADANIENSOL”,
“BERGEPAINT”, “DEEPAKNTR”, “GODREJCP”, “DMART”, “TATAMOTORS”, “BAJAJ-AUTO”, “BEL”, “COFORGE”, “HINDALCO”,
“HDFCLIFE”, “HFCL”, “NBCC”, “UPL”, “BRITANNIA”, “SOLARINDS”, “COLPAL”, “NATIONALUM”, “POONAWALLA”, “HAL”,
“NESTLEIND”, “JIOFIN”, “TORNTPHARM”, “HAVELLS”, “ABCAPITAL”, “UNIONBANK”, “EICHERMOT”, “TATASTEEL”, “BHARTIARTL”,
“MFSL”, “ADANIPORTS”, “ULTRACEMCO”, “RBLBANK”, “TATACONSUM”, “LTF”, “KOTAKBANK”, “MARICO”, “LUPIN”, “TVSMOTOR”,
“GRASIM”, “VEDL”, “CGPOWER”, “BHARATFORG”, “LICHSGFIN”, “SJVN”, “AXISBANK”, “INDIANB”, “GLENMARK”, “ACC”,
“BANDHANBNK”, “PIDILITIND”, “CROMPTON”, “CESC”, “TATATECH”, “TORNTPOWER”, “DIVISLAB”, “TATACHEM”, “ASTRAL”,
“HEROMOTOCO”, “AMBUJACEM”, “BALKRISIND”, “IEX”, “VOLTAS”, “MARUTI”, “TCS”, “SBIN”, “NMDC”, “MUTHOOTFIN”, “IGL”,
“ABFRL”, “BAJFINANCE”, “DLF”, “DABUR”, “ONGC”, “PNB”, “TATAELXSI”, “MCX”, “EXIDEIND”, “ADANIENT”, “ICICIPRULI”,
“RAMCOCEM”, “BIOCON”, “HDFCBANK”, “CIPLA”, “ASIANPAINT”, “JSL”, “JSWSTEEL”, “SUPREMEIND”, “ASHOKLEY”, “IRCTC”,
“IREDA”, “CHOLAFIN”, “MRF”, “MOTHERSON”, “BAJAJFINSV”, “POLYCAB”, “LICI”, “ICICIBANK”, “YESBANK”, “HDFCAMC”,
“UNITDSPR”, “LT”, “HINDCOPPER”, “SUNPHARMA”, “BOSCHLTD”, “COALINDIA”, “HUDCO”, “ITC”, “ADANIGREEN”, “HINDUNILVR”,
“M&M”, “WIPRO”, “ZYDUSLIFE”, “CANBK”, “SHREECEM”, “PERSISTENT”, “SBICARD”, “CYIENT”, “DRREDDY”, “BANKINDIA”,
“APLAPOLLO”, “ABB”, “SBILIFE”, “ALKEM”, “JINDALSTEL”, “OIL”, “GRANULES”, “NHPC”, “LTTS”, “BANKBARODA”,
“IDFCFIRSTB”, “TECHM”, “POLICYBZR”, “INDUSTOWER”, “PHOENIXLTD”, “ICICIGI”, “SYNGENE”, “BHEL”, “INDHOTEL”,
“TATAPOWER”, “IOC”, “SONACOMS”, “PIIND”, “TATACOMM”, “FEDERALBNK”, “BSOFT”, “DALBHARAT”, “CHAMBLFERT”, “JUBLFOOD”,
“APOLLOHOSP”, “PAGEIND”, “VBL”, “OBEROIRLTY”, “NCC”, “IRB”, “ANGELONE”, “SIEMENS”, “SAIL”, “POWERGRID”,
“AARTIIND”, “NAUKRI”, “PETRONET”, “CONCOR”, “PFC”, “TITAN”, “PATANJALI”, “IIFL”, “M&MFIN”, “PEL”, “GMRAIRPORT”,
“AUROPHARMA”, “TRENT”, “LAURUSLABS”, “BSE”, “JSWENERGY”, “HCLTECH”, “BPCL”, “AUBANK”, “RECLTD”, “INFY”,
“HINDPETRO”, “MPHASIS”, “MAXHEALTH”, “KPITTECH”, “IDEA”, “DELHIVERY”, “CDSL”, “KEI”, “SHRIRAMFIN”, “GAIL”,
“CUMMINSIND”, “PRESTIGE”, “NTPC”, “NYKAA”, “JKCEMENT”, “ESCORTS”, “INDIGO”, “LTIM”, “LODHA”, “DIXON”,
“GODREJPROP”, “PAYTM”, “OFSS”, “ZOMATO”, “INDUSINDBK”, “MGL”, “KALYANKJIL”
]

for stock_name in watchlist:
chart = tsl.get_intraday_data(stock_name,‘NSE’,2)
chart[‘rsi’] = talib.RSI(chart[‘close’], timeperiod = 14)

# Last Completed/Closed Candle - pandas
lcc = chart.iloc[-2]

uptrend = lcc['rsi'] > 60
downtrend = lcc['rsi'] < 40

if uptrend:
    print(stock_name,"uptrend")
if downtrend:
    print(stock_name,"downtrend")


print(stock_name)
pdb.set_trace()
2 Likes

@Tradehull_Imran Facing the problem in live market as well.

cmd:
C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>py “Dhan_codebase usage.py”
Codebase Version 2.8 : Solved - Strike Selection Issue
-----Logged into Dhan-----
This BOT Is Picking New File From Dhan
Got the instrument file
available_balance 597.95
Traceback (most recent call last):
File “Dhan_codebase usage.py”, line 24, in
ltp1 = tsl.get_ltp(‘ACC’)
AttributeError: ‘Tradehull’ object has no attribute ‘get_ltp’

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>previous_hist_data = tsl.get_historical_data(‘ACC’,‘NSE’,12)
‘previous_hist_data’ is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Danish\Desktop\Algotrading\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>

@Danish_Ansari
Looks like you are not calling correct function to get ltp. Try below code instead of your ltp logic.

data = tsl.get_ltp_data(names=['ACC', 'NIFTY'])
ACC_ltp = data["ACC"]
NIFTY_ltp = data["NIFTY"]

For Historical data try below code:
historical_data = tsl.get_historical_data(tradingsymbol='ACC', exchange='NSE', timeframe="1")

You can select timeframe parameter value from below options based on your requirement:

  • ‘1’ for 1-minute candles
  • ‘5’ for 5-minute candles
  • ‘15’ for 15-minute candles
  • ‘25’ for 25-minute candles
  • ‘60’ for 60-minute candles
  • ‘DAY’ for daily candles
1 Like


still not working