from dhanhq import dhanhq
import pandas as pd
import time
Initialize the DhanHQ client
dhan = dhanhq(client_id=“****”, access_token=“********”)
Define constants
SECURITY_ID = “500670” # PFC stock security ID
EXCHANGE = “NSE_EQ”
PRODUCT_TYPE = “INTRA”
ORDER_TYPE = “MARKET”
VALIDITY = “DAY”
EMA_PERIOD = 10
QUANTITY = 1 # Define the quantity to trade
Define date range for data fetch
FROM_DATE = “2024-09-11”
TO_DATE = “2025-01-06”
Fetch intraday minute data with date range
def get_intraday_minute_data():
response = dhan.intraday_minute_data(
security_id=SECURITY_ID,
exchange_segment=EXCHANGE,
instrument_type=“EQUITY”,
from_date=FROM_DATE,
to_date=TO_DATE,
interval=“1” # 1-minute timeframe
)
if response[“status”] != “success”:
raise Exception(“Error fetching intraday minute data”)
data = pd.DataFrame(response[“data”])
data.columns = [“timestamp”, “open”, “high”, “low”, “close”, “volume”]
data[“timestamp”] = pd.to_datetime(data[“timestamp”], unit=“ms”)
return data
Function to calculate EMA manually using Pandas
def calculate_ema(data, period):
return data[‘close’].ewm(span=period, adjust=False).mean()
Main trading loop
def trading_loop():
position = None # None, “long”, or “short”
while True:
try:
# Fetch intraday data
data = get_intraday_minute_data()
# Calculate EMA manually using Pandas
data['ema'] = calculate_ema(data, EMA_PERIOD)
latest_candle = data.iloc[-1]
# Check if the current position needs to be exited
if position == "long" and latest_candle['low'] <= latest_candle['ema']:
# Close the long position (place sell order)
response = dhan.place_order(
security_id=SECURITY_ID,
exchange_segment=EXCHANGE,
transaction_type=dhan.SELL,
quantity=QUANTITY,
order_type=ORDER_TYPE,
product_type=PRODUCT_TYPE,
price=0
)
position = None
print("Closed long position", response)
elif position == "short" and latest_candle['high'] >= latest_candle['ema']:
# Close the short position (place buy order)
response = dhan.place_order(
security_id=SECURITY_ID,
exchange_segment=EXCHANGE,
transaction_type=dhan.BUY,
quantity=QUANTITY,
order_type=ORDER_TYPE,
product_type=PRODUCT_TYPE,
price=0
)
position = None
print("Closed short position", response)
# Determine if a new position should be opened
if position is None:
# Decide position logic based on EMA (manual)
if latest_candle['close'] < latest_candle['ema'] and latest_candle['high'] < latest_candle['ema'] and latest_candle['low'] < latest_candle['ema']:
# Short position (place sell order)
response = dhan.place_order(
security_id=SECURITY_ID,
exchange_segment=EXCHANGE,
transaction_type=dhan.SELL,
quantity=QUANTITY,
order_type=ORDER_TYPE,
product_type=PRODUCT_TYPE,
price=0
)
position = "short"
print("Opened short position", response)
elif latest_candle['close'] > latest_candle['ema'] and latest_candle['high'] > latest_candle['ema'] and latest_candle['low'] > latest_candle['ema']:
# Long position (place buy order)
response = dhan.place_order(
security_id=SECURITY_ID,
exchange_segment=EXCHANGE,
transaction_type=dhan.BUY,
quantity=QUANTITY,
order_type=ORDER_TYPE,
product_type=PRODUCT_TYPE,
price=0
)
position = "long"
print("Opened long position", response)
except Exception as e:
print(f"Error: {e}")
# Wait for the next minute
time.sleep(60)
if name == “main”:
trading_loop()
here is my code its showing error
ERROR:root:Exception in dhanhq>>intraday_minute_data: interval value must be [‘1’,‘5’,‘15’,‘25’,‘60’]
Error: Error fetching intraday minute data
plz help me solve this