Thank you @Dev
I tried this. but not worked. I think there maybe error at some other place.
my code are as below:-----
import pandas as pd
import logging
import asyncio
import time
from datetime import datetime, timedelta
from dhanhq import dhanhq, marketfeed
from dhanhq.dhanhq import dhanhq
from dhanhq.marketfeed import DhanFeed
from pathlib import Path
from webbrowser import open as web_open
Constants
client_id = 1208340001-------
access_token = “eyJ0eXAiOiJKV1QiLCJ”
subscription_code = marketfeed.Ticker
HIGH_RANGE = 22040
LOW_RANGE = 22025
PROFIT_BOOKING_THRESHOLD = 100
START_TIME = “09:20:00”
END_TIME = “15:30:00”
Configure logging
logging.basicConfig(level=logging.DEBUG)
Functions
def atm_strike(spot_price):
“”"
Calculate the At-The-Money (ATM) strike price based on the spot price.
Args:
spot_price (float): The current spot price.
Returns:
int: The ATM strike price.
"""
if spot_price % 100 < 25:
return int(spot_price / 100) * 100
elif spot_price % 100 >= 25 or spot_price % 100 < 75:
return int(spot_price / 100) * 100 + 50
else:
return int(spot_price / 100) * 100 + 100
def get_symbol_name(symbol, expiry, strike, strike_type):
“”"
Generate the symbol name for an instrument.
Args:
symbol (str): The symbol name.
expiry (str): The expiry date.
strike (int): The strike price.
strike_type (str): The type of option (CE or PE).
Returns:
str: The generated symbol name.
"""
return f"{symbol}-{expiry}-{strike}-{strike_type}"
def get_instrument_token():
“”"
Retrieve instrument tokens from a CSV file.
Returns:
dict: A dictionary mapping symbols to instrument tokens.
“”"
df = pd.read_csv(‘api-scrip-master.csv’)
token_dict = {}
for _, row in df.iterrows():
trading_symbol = row[‘SEM_TRADING_SYMBOL’]
exm_exch_id = row[‘SEM_EXM_EXCH_ID’]
if trading_symbol not in token_dict:
token_dict[trading_symbol] = {}
token_dict[trading_symbol][exm_exch_id] = row.to_dict()
return token_dict
def main():
# Initialize DhanHQ client
dhan = dhanhq(client_id=client_id, access_token=access_token)
# Get instrument tokens
token_dict = get_instrument_token()
# Define instruments
symbol = 'NIFTY'
expiry = 'May2024'
# Initialize position flags
ce_position = False
pe_position = False
# Initialize profit booking variables
last_ce_ltp = None
last_pe_ltp = None
ce_profit_booked = False
pe_profit_booked = False
while True:
# Get current time
current_time = datetime.now().strftime("%H:%M:%S")
# Check if within trading hours
if START_TIME <= current_time <= END_TIME:
# Get Nifty LTP
nifty_ltp = dhan.intraday_minute_data(
security_id=token_dict,
exchange_segment='NSE_FNO',
instrument_type='OPTIDX'
)
logging.info(f"Nifty LTP: {nifty_ltp}")
# Check if profit booking condition is met for CE
if ce_position and last_ce_ltp is not None and nifty_ltp - last_ce_ltp >= PROFIT_BOOKING_THRESHOLD and not ce_profit_booked:
logging.info("Profit booking for CE triggered")
# Perform profit booking logic for CE here
ce_profit_booked = True
# Check if profit booking condition is met for PE
if pe_position and last_pe_ltp is not None and last_pe_ltp - nifty_ltp >= PROFIT_BOOKING_THRESHOLD and not pe_profit_booked:
logging.info("Profit booking for PE triggered")
# Perform profit booking logic for PE here
pe_profit_booked = True
# Update last CE LTP for next iteration
last_ce_ltp = nifty_ltp if ce_position else last_ce_ltp
# Update last PE LTP for next iteration
last_pe_ltp = nifty_ltp if pe_position else last_pe_ltp
# Check if LTP crosses above high range
if nifty_ltp > HIGH_RANGE:
if not ce_position:
# Enter CE
atm_strike_price = atm_strike(nifty_ltp)
ce_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'CE')]['NSE']['SEM_SMST_SECURITY_ID']
dhan.place_order(security_id=ce_id, exchange_segment=dhan.NSE, transaction_type=dhan.BUY, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
ce_position = True
# Exit PE if entered
if pe_position:
pe_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'PE')]['NSE']['SEM_SMST_SECURITY_ID']
dhan.place_order(security_id=pe_id, exchange_segment=dhan.NSE, transaction_type=dhan.SELL, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
pe_position = False
# Check if LTP crosses below low range
elif nifty_ltp < LOW_RANGE:
if not pe_position:
# Enter PE
atm_strike_price = atm_strike(nifty_ltp)
pe_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'PE')]['NSE']['SEM_SMST_SECURITY_ID']
dhan.place_order(security_id=pe_id, exchange_segment=dhan.NSE, transaction_type=dhan.BUY, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
pe_position = True
# Exit CE if entered
if ce_position:
ce_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'CE')]['NSE']['SEM_SMST_SECURITY_ID']
dhan.place_order(security_id=ce_id, exchange_segment=dhan.NSE, transaction_type=dhan.SELL, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
ce_position = False
# Sleep for a while before checking again
time.sleep(1)
if name == “main”:
main()