Home Article Historical Data Fetch Smart Api Historical Data Fetch Smart Api Software Technique Web Technique All Computer Language and Computer Language Practice Computer Educa March 27, 2025 0 Comments Share: Facebook Twitter Google+ Pinterest Whatsapp TREDING NIFTY SYMBALTOKEN-26000 , BANKNIFTY - SYMBALTOKEN-26009 from SmartApi import SmartConnect # or from SmartApi.smartConnect import SmartConnect import pyotp import pandas as pd from logzero import logger from datetime import datetime # API credentials and initialization api_key = 'nxnnxvvyI' username = 'M9737378378' pwd = '7466' # Initialize SmartConnect instance smartApi = SmartConnect(api_key) try: # Generate OTP using TOTP token token = "7FUK65PnscjKSLJDKNKFDDKFLDLNVN" totp = pyotp.TOTP(token).now() except Exception as e: logger.error("Invalid Token: The provided token is not valid.") raise e # Correlation ID (optional) correlation_id = "abcde" # Generate session for login data = smartApi.generateSession(username, pwd, totp) # Check the status of the login response if data['status'] == False: logger.error("Login failed: ", data) else: # Retrieve JWT token and refresh token after successful login authToken = data['data']['jwtToken'] refreshToken = data['data']['refreshToken'] # Fetch the feed token for real-time data feedToken = smartApi.getfeedToken() # Fetch the user profile details res = smartApi.getProfile(refreshToken) # Generate a new token using the refresh token smartApi.generateToken(refreshToken) # Extract exchanges information from user profile response exchanges = res['data']['exchanges'] logger.info(f"Exchanges: {exchanges}") # Get today's date dynamically today = datetime.today().strftime('%Y-%m-%d') # Define your historicParam with today's date historicParam = { "exchange": "NFO", # Exchange (NSE in this case) "symboltoken": "53846", # Token for the symbol (e.g., stock) "interval": "FIVE_MINUTE", # Interval (e.g., ONE_MINUTE, ONE_DAY, etc.) "fromdate": f"{today} 14:00", # Start date and time (today's date) "fromdate": f"{today} 15:05", "todate": f"{today} 14:05" # End date and time (today's date, market close time) "todate": f"{today} 15:30" } # Assuming exchangeTokens is a required parameter, find the correct exchangeToken # Find the exchange token for the relevant exchange and symbol. exchangeToken = exchanges[0] # Get exchange token; you may need to pick the right one # You can construct a parameter for 'exchangeTokens' if it's a list or dictionary. # Example of the 'exchangeTokens' argument that could be passed to the API exchangeTokens = { "symbol": historicParam["symboltoken"], "exchange": historicParam["exchange"], "exchangeToken": exchangeToken, # Pass the exchange token for the symbol "tradingsymbol": "SBIN-EQ" # Example tradingsymbol for the symbol } try: # Now, use getCandleData instead of getMarketData candle_data = smartApi.getCandleData(historicParam) # Log the raw response for debugging purposes logger.info(f"Raw Response: {candle_data}") # Log the response from the API if candle_data['status']: # Assuming candle_data['data'] contains the relevant candlestick data # Convert the raw response into a DataFrame df = pd.DataFrame(candle_data['data'], columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume']) # Log the DataFrame or perform any processing you want logger.info(f"Candle Data:\n{df.head()}") # Display first few rows # Convert 'Date' to datetime format df['Date'] = pd.to_datetime(df['Date']) # Set 'Date' as the index of the DataFrame df.set_index('Date', inplace=True) # Example: Plotting data (e.g., closing prices) df['Close'].plot(title=f"Candle Data for Symbol: {historicParam['tradingsymbol']}") # To display the DataFrame in a more readable format (rows and columns) logger.info(f"Formatted Candle Data:\n{df}") else: logger.error(f"Failed to fetch candle data: {candle_data}") except Exception as e: logger.error(f"Error fetching candle data: {str(e)}") Copy Copied Text: You Might Also Like Post a Comment
No comments