from Dhan_Tradehull_V2 import Tradehull
from api_helper import ShoonyaApiPy
import logging
import pyotp
import requests
import warnings
warnings.filterwarnings(“ignore”)
import xlwings as xw
import numpy as np
import os
import pandas as pd
import time
import datetime
import pdb
#enable dbug to see request and responses
logging.basicConfig(level=logging.DEBUG)
#start of our program
api = ShoonyaApiPy()
#credentials
user = “FA915”
pwd = “Mehul@1271”
token = “OMJQMOQI7KR7272AGYBO547KOSZV7376”
vc = “FA91534_U”
app_key = “ded6e3f430c6883ed576268ded8c0ffd”
imei = “abc12”
#make the api call
ret = api.login(userid=user, password=pwd, twoFA=pyotp.TOTP(token).now(), vendor_code=vc, api_secret=app_key,imei=imei)
print(ret)
client_code = “1101067561”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMzOTk0MTc2LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMTA2NzU2MSJ9.ugGqy1BVEA28tJClFJZyVAORQVMwQsKrWB8NFpC01uUrPlTMJzN0coE7jC7j-2sUE8o9TnWgGlL6oX5UX”
tsl = Tradehull(client_code, token_id)
if not os.path.exists(“call put mix algo.xlsm”):
try:
wb = xw.Book()
wb.sheets.add(“hi hello”)
wb.save(“call put mix algo.xlsm”)
wb.close()
except Exception as e:
print(f"Error Creating Excel File: {e}")
wb = xw.Book(“call put mix algo.xlsm”)
sector1 = wb.sheets(“hi hello”)
##--------------------------------- for nifty index chart history cal ---------------------#
#nifty_chart = tsl.get_historical_data(tradingsymbol=“NIFTY”,exchange=“INDEX”,timeframe=“5”)
#nifty_chart.set_index(‘timestamp’, inplace=True)
#print(nifty_chart)
#sector1.range(“A216”).value=nifty_chart
##------------------------------------------------------------------------------#
#--------------------------------- for nifty index chart ---------------------#
nifty_chart = tsl.get_intraday_data(tradingsymbol=“NIFTY”,exchange=“INDEX”,timeframe=2)
nifty_chart.set_index(‘timestamp’, inplace=True)
#print(nifty_chart)
#------------------------------------------------------------------------------#
#pdb.set_trace()
#--------------------------------- for ATM STRIKE NAME -----------------------#
second_row_data = nifty_chart.iloc[0]
#print(second_row_data)
close_for_atm = second_row_data[“close”]
#print(close_for_atm)
rounded_close_atm = round(close_for_atm / 50) * 50
#print(rounded_close_atm)
sector1.range(“A1”).value=“INDEX”
sector1.range(“A2”).value=“NIFTY 50”
sector1.range(“B1”).value=“ATM STRIKE NAME”
sector1.range(“B2”).value=rounded_close_atm
#------------------------------------------------------------------------------#
#-------------------------------- call strike name for dhan ------------------#
watchlist_call =
call_strike = f"NIFTY 12 DEC {rounded_close_atm} CALL"
#print(call_strike)
sector1.range(“C1”).value=“DHAN STRIKE NAME”
sector1.range(“C2”).value = call_strike
watchlist_call.append(call_strike)
print(watchlist_call)
#--------------------------------
#-------------------------------- call trade name for shoonya ------------------#
call_trade_name = f"NIFTY12DEC24C{rounded_close_atm}"
#print(call_trade_name)
sector1.range(“D1”).value=“SHOONYA TRADE NAME”
sector1.range(“D2”).value = call_trade_name
#---------------------------------
#-------------------------------- call hedge trade name for shoonya ------------------#
call_trade_hedge_name = f"NIFTY12DEC24C{rounded_close_atm+100}"
#print(call_trade_hedge_name)
sector1.range(“E1”).value =“SHOONYA TRADE HEDGE NAME”
sector1.range(“E2”).value = call_trade_hedge_name
#--------------------------------
#-------------------------------- put strike name for dhan ------------------#
watchlist_put =
put_strike = f"NIFTY 12 DEC {rounded_close_atm} PUT"
#print(put_strike)
#sector1.range(“C1”).value=“DHAN STRIKE NAME”
sector1.range(“C3”).value = put_strike
watchlist_put.append(put_strike)
print(watchlist_put)
#---------------------------------
#-------------------------------- put trade name for shoonya ------------------#
put_trade_name = f"NIFTY12DEC24P{rounded_close_atm}"
#print(put_trade_name)
#sector1.range(“D1”).value=“PUT TRADE NAME”
sector1.range(“D3”).value = put_trade_name
#---------------------------------
#-------------------------------- put hedge trade name for shoonya ------------------#
put_trade_hedge_name = f"NIFTY12DEC24P{rounded_close_atm-100}"
#print(put_trade_hedge_name)
#sector1.range(“E1”).value =“PUT TRADE HEDGE NAME”
sector1.range(“E3”).value = put_trade_hedge_name
#--------------------------------
#pdb.set_trace()
#-----------------------call side appended data -------------------------#
call_traded =
call_traded_timestame =
call_trades_order_price =
call_traded_sl =
call_sl_hit =
call_sl_hit_timestamp =
#-----------------------call side appended data -------------------------#
put_traded =
put_traded_timestame =
put_trades_order_price =
put_traded_sl =
put_sl_hit =
put_sl_hit_timestamp =
while True:
time.sleep(1)
current_time = datetime.datetime.now().time()
print(current_time)
if current_time < datetime.time(9, 21):
print(“wait for market to start”, current_time)
continue
if (current_time > datetime.time(15, 15)) :
print("Market is over, Bye Bye see you tomorrow", current_time)
break
#pdb.set_trace()
#time.sleep(60)
for name in watchlist_call:
print(name)
print(f"[{current_time}] Processing {name}...")
try:
##--------------------------------for historical data trade-------------------------------------------------#
## Fetch intraday data
#chart_call = tsl.get_historical_data(tradingsymbol=name, exchange='NFO', timeframe="5")
##print(chart_call)
##---------------------------------------------------------------------------------#
#------------------------------- for live trade --------------------------------------#
#Fetch intraday data
chart_call = tsl.get_intraday_data(tradingsymbol=name, exchange='NFO', timeframe=2)
#print(chart_call)
#---------------------------------------------------------------------------------#
# Calculate typical price and VWAP
chart_call['typical_price'] = (chart_call['high'] + chart_call['low'] + chart_call['close']) / 3
chart_call['vwap'] = np.cumsum(chart_call['typical_price'] * chart_call['volume']) / np.cumsum(chart_call['volume'])
# Push the chart data to the specified range
sector1.range("A25").value = chart_call
# Get the last three candles
second_candle_call = chart_call.iloc[-3]
first_candle_call = chart_call.iloc[-2]
live_candle_call = chart_call.iloc[-1]
#print(second_candle_call)
#print(first_candle_call)
#print(live_candle_call)
# Update ranges in sector1 with candle data
sector1.range("A4").value = "CALL"
sector1.range("B5").options(transpose=True).value = second_candle_call
sector1.range("B7").options(transpose=True).value = first_candle_call
sector1.range("B9").options(transpose=True).value = live_candle_call
# Conditions
c1 = second_candle_call['close'] < second_candle_call['vwap']
c2 = first_candle_call['close'] < first_candle_call['vwap']
c3 = live_candle_call['open'] < live_candle_call['vwap']
c4 = live_candle_call['close'] < live_candle_call['vwap']
c5 = first_candle_call['close'] < second_candle_call['low']
c6 = first_candle_call['close'] < second_candle_call['low']
c7 = live_candle_call['close'] < first_candle_call['high']
c_sl = live_candle_call['open'] > second_candle_call['high']
# Print conditions and time for debugging/logging
print(f"[{current_time}] Conditions: c1={c1}, c2={c2}, c3={c3}, c4={c4}, c5={c5}, c6={c6}, c7={c7}, c_sl={c_sl}")
except Exception as e:
print(f"[{current_time}] Error processing {name}: {e}")
if c1 and c2 and c3 and c4 and c5 and c6 and c7 and name not in call_traded:
#ret_place_mkt_order = api.place_order(buy_or_sell='B', product_type='M',exchange='NFO', tradingsymbol= call_trade_hedge_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
#ret_place_mkt_order = api.place_order(buy_or_sell='S', product_type='M',exchange='NFO', tradingsymbol= call_trade_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
call_traded_timestame.append(live_candle_call['timestamp'])
sector1.range("J10").value = call_traded_timestame
call_traded.append(name)
sector1.range("K10").value = call_traded
call_trades_order_price.append(live_candle_call['open'])
sector1.range("L10").value = call_trades_order_price
call_traded_sl.append(second_candle_call['high'])
sector1.range("M10").value = call_traded_sl
print(call_traded_timestame)
print(call_traded)
print(call_trades_order_price)
print(call_traded_sl)
print(f"[{current_time}] trade pad gaya call me thoda ruko")
time.sleep(120)
if name in call_traded and live_candle_call['close'] > call_traded_sl:
call_sl_hit_timestamp.append(live_candle_call['timestamp'])
print(call_sl_hit_timestamp)
call_sl_hit.append(live_candle_call['close'])
print(call_sl_hit)
#ret_place_mkt_order = api.place_order(buy_or_sell='B', product_type='M',exchange='NFO', tradingsymbol= call_trade_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
#ret_place_mkt_order = api.place_order(buy_or_sell='S', product_type='M',exchange='NFO', tradingsymbol= call_trade_hedge_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
del call_traded_timestame[:]
del call_traded[:]
del call_trades_order_price[:]
del call_traded_sl[:]
#pdb.set_trace()
for name in watchlist_put:
print(name)
print(f"[{current_time}] Processing {name}...")
try:
##--------------------------------for historical data trade-------------------------------------------------#
## Fetch intraday data
#chart_call = tsl.get_historical_data(tradingsymbol=name, exchange='NFO', timeframe="5")
##print(chart_call)
##---------------------------------------------------------------------------------#
#--------------------------------for live trade --------------------------------------------------------------#
# Fetch intraday data
chart_put = tsl.get_intraday_data(tradingsymbol=name, exchange='NFO', timeframe=2)
#print(chart_put)
#---------------------------------------------------------------------------------------#
# Calculate typical price and VWAP
chart_put['typical_price'] = (chart_put['high'] + chart_put['low'] + chart_put['close']) / 3
chart_put['vwap'] = np.cumsum(chart_put['typical_price'] * chart_put['volume']) / np.cumsum(chart_put['volume'])
# Push the chart data to the specified range
sector1.range("K25").value = chart_put
# Get the last three candles
second_candle_put = chart_put.iloc[-3]
first_candle_put = chart_put.iloc[-2]
live_candle_put = chart_put.iloc[-1]
#print(second_candle_put)
#print(first_candle_put)
#print(live_candle_put)
# Update ranges in sector1 with candle data
sector1.range("A11").value = "PUT"
sector1.range("B12").options(transpose=True).value = second_candle_put
sector1.range("B14").options(transpose=True).value = first_candle_put
sector1.range("B16").options(transpose=True).value = live_candle_put
# Conditions
p1 = second_candle_put['close'] < second_candle_put['vwap']
p2 = first_candle_put['close'] < first_candle_put['vwap']
p3 = live_candle_put['open'] < live_candle_put['vwap']
p4 = live_candle_put['close'] < live_candle_put['vwap']
p5 = first_candle_put['close'] < second_candle_put['low']
p6 = first_candle_put['close'] < second_candle_put['low']
p7 = live_candle_put['close'] < first_candle_put['high']
p_sl = live_candle_put['open'] > second_candle_put['high']
# Print conditions and time for debugging/logging
print(f"[{current_time}] Conditions: p1={p1}, p2={p2}, p3={p3}, p4={p4}, p5={p5}, p6={p6}, p7={p7}, p_sl={p_sl}")
except Exception as e:
print(f"[{current_time}] Error processing {name}: {e}")
if p1 and p2 and p3 and p4 and p5 and p6 and p7 and name not in put_traded:
#ret_place_mkt_order = api.place_order(buy_or_sell='B', product_type='M',exchange='NFO', tradingsymbol= put_trade_hedge_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
#ret_place_mkt_order = api.place_order(buy_or_sell='S', product_type='M',exchange='NFO', tradingsymbol= put_trade_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
put_traded_timestame.append(live_candle_put['timestamp'])
sector1.range("J11").value = put_traded_timestame
put_traded.append(name)
sector1.range("K11").value = put_traded
put_trades_order_price.append(live_candle_put['open'])
sector1.range("L11").value = put_trades_order_price
put_traded_sl.append(second_candle_put['high'])
sector1.range("M11").value = put_traded_sl
print(put_traded_timestame)
print(put_traded)
print(put_trades_order_price)
print(put_traded_sl)
print(f"[{current_time}] trade pad gaya put me thoda ruko")
time.sleep(120)
if name in put_traded and live_candle_put['close'] > put_traded_sl:
put_sl_hit_timestamp.append(live_candle_put['timestamp'])
print(put_sl_hit_timestamp)
put_sl_hit.append(live_candle_put['close'])
print(put_sl_hit)
#ret_place_mkt_order = api.place_order(buy_or_sell='B', product_type='M',exchange='NFO', tradingsymbol= put_trade_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
#ret_place_mkt_order = api.place_order(buy_or_sell='S', product_type='M',exchange='NFO', tradingsymbol= put_trade_hedge_name,quantity=25, discloseqty=0,price_type='MKT', price=0,trigger_price=None,retention='DAY', remarks='my_order_001')
del put_traded_timestame[:]
del put_traded[:]
del put_trades_order_price[:]
del put_traded_sl[:]
print(current_time)
#pdb.set_trace()
```
YE CODE COMPLETE HE ORDER BHI PLACE KARTA HE LEKIN DHAN API ME SE OHLC DAT A FETCH ME ERROR AA JATA HE
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-10.csv
Got the instrument file
ERROR:root:Error at getting start date as If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Users\admin-pc\Desktop\MEHUL DAILY NOTE\STOCK SUDH\Dhan_Tradehull_V2.py”, line 218, in get_start_date
df = pd.DataFrame(ohlc[‘data’])
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 709, in init
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 481, in dict_to_mgr
return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 115, in arrays_to_mgr
index = _extract_index(arrays)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 645, in _extract_index
raise ValueError(“If using all scalar values, you must pass an index”)
ValueError: If using all scalar values, you must pass an index
If using all scalar values, you must pass an index
ERROR:root:Exception in Getting OHLC data as If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Users\admin-pc\Desktop\MEHUL DAILY NOTE\STOCK SUDH\Dhan_Tradehull_V2.py”, line 298, in get_intraday_data
df = pd.DataFrame(ohlc[‘data’])
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 709, in init
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 481, in dict_to_mgr
return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 115, in arrays_to_mgr
index = _extract_index(arrays)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 645, in _extract_index
raise ValueError(“If using all scalar values, you must pass an index”)
ValueError: If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Users\admin-pc\Desktop\MEHUL DAILY NOTE\STOCK SUDH\Dhan_Tradehull_V2.py”, line 298, in get_intraday_data
df = pd.DataFrame(ohlc[‘data’])
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 709, in init
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 481, in dict_to_mgr
return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 115, in arrays_to_mgr
index = _extract_index(arrays)
File “C:\Users\admin-pc\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 645, in _extract_index
raise ValueError(“If using all scalar values, you must pass an index”)
ValueError: If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Users\admin-pc\Desktop\MEHUL DAILY NOTE\STOCK SUDH\call put mix algo.py”, line 57, in
nifty_chart.set_index(‘timestamp’, inplace=True)
AttributeError: ‘NoneType’ object has no attribute ‘set_index’
[Finished in 8.6s]Preformatted text
IS KA KUCH HO SAKTA HE KYA