Hi @CHETAN_99
Mostly the orderbook variable seems to be None.
send complete code for checking.
Do send the code as well for checking.
It seems TA-lib had some issues while installation,
Do reinstall again for talib
use these files these are updated.
Also do make sure that python 3.8.0 is being used
Hi @Kanha_Meher
Need more info on this.
Do send the complete code and the codebase code that has been used,
use below code
atm, option_chain = tsl.get_option_chain(Underlying="NIFTY", exchange="INDEX", expiry=0, num_strikes=30)
pcr_value = option_chain['PE OI'].sum() / option_chain['CE OI'].sum()
and use this codebase file : Dhan_Tradehull_V2.py - Google Drive
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 = “”
token_id = “”
tsl = Tradehull(client_code, token_id)
watchlist = [“HDFCBANK”, “ICICIBANK”]
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 bc2 and bc3 and bc4 and bc5 and bc6:
print("buy ", name, "\t")
margin_available = tsl.get_balance()
margin_required = alert_candle['close']/5.0 # LEVRAGE 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 MASSAGE
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] = None
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 MASSAGE
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] = None
winsound.Beep(1500, 10000)
except Exception as e:
print(e)[quote="Tradehull_Imran, post:2150, topic:32718, full:true"]
Hi @CHETAN_99
Mostly the orderbook variable seems to be None.
send complete code for checking.
[/quote]
@Tradehull_Imran Sir
Please include the following in the algo:
If the first trade hits the target, no more trades for the day.
If the first trade hits the stop-loss, allow up to 2 more trade opportunities.
Thank you for your guidance!
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)
thanks sir
OMG,
Hi, @Subhajitpanja , What a Robust Trading Plan, I think it will be very difficult to code for Higher highs and Lower Lows, or Trendline. @Tradehull_Imran, Need your Suggestions, Sir.
@Tradehull_Imran , Superb sir, I think, I cannot contribute at this moment because it don’t have perfect strategy with at least 50% win ratio… Basically I am a Level based trader ( Support and Resistance ), Currently I am trying Range Break out,
Nifty 50 Stocks with 0.75 % , up or down in 1st 5 min. candle of the day
Range :- 9.45 to 10.15 ( Mark Highs and Lows )
Time Frame is 5 mins.
Buy :- when currently candle is above the high and volume should be 2 times of the average volume.
Sell :- when currently candle is Below the low and volume should be 2 times of the average volume.
TP/SL :- 0.5 %
@Tradehull_Imran Hi sir it’s been a great learning from you, thankyou so much for the beautiful content on youtube.
sir actually i was trying to implement your learning and also subscribed to data api of dhan but sir after running “codebaseusage.py” file- I’m getting this error.
@Tradehull_Imran Hello sir, after running websocket.py on command prompt, I am getting this error. please help to solve this error. ie not getting any data on excel file.
Hi, @Kishore007, I have watched respected @Tradehull_Imran sir video
where sir try to create open source project. I just spellbound on that 2nd point sir suggested us to give some Idea only for now. As well as also mentioned one strategy 4-5 years at least it should work maybe after that it will not work.
I am also programmer to some other language. So I was thinking scene then if I create most basic strategy does not matter how many people will use it still it should be still unique as long run. I need some very raw strategy people can use and mix there own blend. but pillar should be like this only as long as stock market will be there
Suppose on your back test you are taking Daily I am taking 5 mins
you are back testing 5year on some stocks I am testing 1 years on some other stocks.
Sir will give us the ultimate answer
I just asked below things to Microsoft co-pilot
can I create higher high candle breakout with python programing
Absolutely, you can create a program to identify higher high candle breakouts using Python. To help you get started, here’s a general outline of the steps involved:
- Import Libraries: You’ll need libraries like
pandas
,numpy
, andmatplotlib
for data manipulation and visualization. If you’re dealing with stock data,yfinance
can be useful. - Download or Load Data: You can use APIs like Yahoo Finance to fetch historical stock data, or you can load your own dataset.
- Calculate Highs and Lows: Extract the ‘High’ and ‘Low’ values from your data.
- Identify Higher Highs and Breakouts:
- A “higher high” occurs when the price reaches a new high compared to the previous high.
- A breakout can be identified when the price moves above a certain resistance level.
- Visualization: Plot the data to visualize the breakouts.
Here’s a simple example to get you started:
python
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Download historical data for a stock
stock = yf.download('AAPL', start='2022-01-01', end='2023-01-01')
# Calculate rolling high
stock['Rolling_High'] = stock['High'].rolling(window=20).max()
# Identify higher highs
stock['Higher_High'] = stock['High'] > stock['Rolling_High'].shift(1)
# Plotting
plt.figure(figsize=(12, 6))
plt.plot(stock['Close'], label='Close Price')
plt.plot(stock['Rolling_High'], label='Rolling High (20 days)')
plt.scatter(stock.index, stock['Close'][stock['Higher_High']], label='Higher High', color='red', marker='^')
plt.legend()
plt.show()
This script will download historical data for Apple Inc. (AAPL) and identify higher highs in the price. The yfinance
library fetches the data, and pandas
handles the data manipulation.
Now I am concentrating only study about technical analysis. If I don’t know that very well I can not do proper code. Maybe within next year I also try to be part of Imran sir open source project.
Thank you
Hi @Kishore007
Higher highs and Lower Lows, or Trendline… these can be done.
pandas makes it easier to work on it
Hi @Kishore007
Added… +1
WebSocket is a old method we used to get LTP… now we have upgraded to a easier solution…
apply below solution