Hello! I wish to get the OHLC Data for the current minute along with the marketfeed.Ticker data. I am trying to fetch the same with a chron job to the minute intraday OHLC Data API but not able to still figure out.
import asyncio
import requests
from dhanhq import marketfeed
import nest_asyncio # For resolving active event loop conflicts in Jupyter
# Apply nest_asyncio to avoid conflicts in nested event loops
nest_asyncio.apply()
# Dhan Client ID and Access Token (Replace with your credentials)
access_token = ###
client_id = ###
# Function to fetch live ticker data and 1-minute OHLC data
async def fetch_ticker_and_ohlc_data():
# Map exchange names to Dhan constants
exchange_map = {
"NSE_EQ": marketfeed.NSE,
}
# User input for exchange name and security ID
exchange_name = input("Enter Exchange Name (e.g., NSE_EQ, BSE_EQ, NSE_FNO, MCX): ").strip().upper()
security_id = input("Enter Security ID: ").strip()
if exchange_name not in exchange_map:
print("Invalid Exchange Name. Please try again.")
return
# Set up instruments for Ticker Data
instruments = [
(exchange_map[exchange_name], security_id, marketfeed.Ticker)
]
version = "v2" # API version
try:
# Initialize market feed connection for live ticker data
data = marketfeed.DhanFeed(client_id, access_token, instruments, version)
print(f"Fetching Live Ticker Data and Minute OHLC Data for {security_id} on {exchange_name}...")
await data.connect()
while True:
# Get live ticker data
response = data.get_data()
if response:
print(f"Ticker Data: {response}")
# Fetch 1-minute OHLC Data from the Dhan API
ohlc_data = get_ohlc_data(security_id, exchange_name)
if ohlc_data:
print(f"1-Minute OHLC Data: {ohlc_data}")
# Sleep for 1 second to prevent spamming the API
await asyncio.sleep(1)
except Exception as e:
print(f"An error occurred: {e}")
finally:
await data.disconnect()
print("Connection closed.")
# Function to fetch 1-minute OHLC data from Dhan API
def get_ohlc_data(security_id, exchange_name):
url = "https://api.dhan.co/v2/charts/intraday"
payload = {
"securityId": security_id,
"exchangeSegment": exchange_name,
"instrument": "INDEX", # Use "INDEX" or adjust based on your security type
"interval": "1", # 1 minute interval
"fromDate": "2024-11-01", # Replace with the actual 'from' date (YYYY-MM-DD)
"toDate": "2024-11-26", # Replace with the actual 'to' date (YYYY-MM-DD)
}
headers = {
'access-token': access_token,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
return response.json() # Return the OHLC data in JSON format
else:
print(f"Error fetching OHLC data: {response.status_code}")
return None
# Run the async function
if __name__ == "__main__":
asyncio.run(fetch_ticker_and_ohlc_data())