@Algo_trading @Tradehull_Imran I made a code for importing data and could find a program which is working for different timeframe and for several days. But the only issue is matching the actual time. The timestamp does not match fully -
import requests
import pandas as pd
from datetime import datetime, timedelta, time as dt_time
import os
import time
# Configuration
API_URL = "https://api.dhan.co/v2/charts/intraday"
ACCESS_TOKEN = "" # Replace with your actual token
MCX_TRADING_HOURS = {
'start': dt_time(9, 0),
'end': dt_time(23, 55)
}
def fetch_trading_data(security_id, exchange_segment, instrument_type,
days_back=30, interval="60"):
"""Fetch precise trading hours data for specified days"""
end_date = datetime.now()
start_date = end_date - timedelta(days=days_back)
# Prepare request
headers = {
"access-token": ACCESS_TOKEN,
"Content-Type": "application/json",
"Accept": "application/json"
}
payload = {
"securityId": security_id,
"exchangeSegment": exchange_segment,
"instrument": instrument_type,
"interval": interval,
"oi": False,
"fromDate": start_date.strftime("%Y-%m-%d"),
"toDate": end_date.strftime("%Y-%m-%d")
}
try:
print(f"\nFetching {days_back} days of data...")
response = requests.post(API_URL, json=payload, headers=headers, timeout=10)
if response.status_code != 200:
print(f"API Error: {response.status_code} - {response.text}")
return None
data = response.json()
if not data:
print("No data returned from API")
return None
# Create DataFrame with precise timestamps
df = pd.DataFrame(data)
# Generate exact trading period timestamps
trading_days = pd.bdate_range(start_date, end_date) # Business days only
trading_periods = []
for day in trading_days:
current_time = datetime.combine(day, MCX_TRADING_HOURS['start'])
end_time = datetime.combine(day, MCX_TRADING_HOURS['end'])
while current_time <= end_time:
trading_periods.append(current_time)
current_time += timedelta(minutes=int(interval))
# Ensure we have matching timestamps
if len(df) <= len(trading_periods):
df['timestamp'] = trading_periods[:len(df)]
else:
print("Warning: Data exceeds expected trading periods")
df = df.iloc[:len(trading_periods)] # Trim excess data
df['timestamp'] = trading_periods
df.set_index('timestamp', inplace=True)
return df
except Exception as e:
print(f"Error: {str(e)}")
return None
if __name__ == "__main__":
# Parameters - adjust as needed
security_id = "437994" # SILVERMIC
exchange_segment = "MCX_COMM"
instrument_type = "FUTCOM"
interval = "15"
# Select time period (30, 60, 90, or 120 days)
days_options = [30, 60, 90, 120]
selected_days = 90 # Default - change this value as needed
print(f"Fetching {selected_days} days of precise trading data for {security_id}...")
data = fetch_trading_data(security_id, exchange_segment,
instrument_type, selected_days, interval)
if data is not None:
# Verify trading hours
data = data.between_time(MCX_TRADING_HOURS['start'], MCX_TRADING_HOURS['end'])
print(f"\nSuccessfully fetched {len(data)} trading periods")
print(f"Date range: {data.index.min().date()} to {data.index.max().date()}")
print(f"Trading hours: {MCX_TRADING_HOURS['start']} to {MCX_TRADING_HOURS['end']}")
# Save to CSV
os.makedirs('trading_data', exist_ok=True)
filename = f"trading_data/{security_id}_{selected_days}days_{interval}min.csv"
try:
data.to_csv(filename)
print(f"\nData saved to {filename}")
# Show samples
print("\nFirst trading day:")
print(data.head(10))
print("\nLast trading day:")
print(data.tail(10))
except Exception as e:
print(f"\nError saving file: {str(e)}")
else:
print("\nFailed to fetch trading data")
Can anyone help in this…