Home Article GET- LTP DATA FETCH GET- LTP DATA FETCH Software Technique Web Technique All Computer Language and Computer Language Practice Computer Educa March 21, 2025 0 Comments Share: Facebook Twitter Google+ Pinterest Whatsapp TREDING NIFTY SYMBALTOKEN-26000 , BANKNIFTY - SYMBALTOKEN-26009 import time import pandas as pd from flask import Flask, jsonify, render_template_string from SmartApi import SmartConnect import pyotp from logzero import logger import threading # Initialize Flask app app = Flask(__name__) # API credentials api_key = 'SDyI' username = 'M5234537' pwd = '746346' # Initialize SmartConnect API smartApi = SmartConnect(api_key) # Store latest LTP data latest_data = {} def generate_totp(token): """Generate TOTP for authentication.""" try: return pyotp.TOTP(token).now() except Exception as e: logger.error("Invalid Token: The provided token is not valid.") raise e def login_to_api(): """Generate session and login to API.""" token = "7FSJDJKJDKLIIUEYBNJDKKDKMMM" # Your TOTP secret key totp = generate_totp(token) try: data = smartApi.generateSession(username, pwd, totp) if not data['status']: logger.error(f"Error: {data['message']}") return None return data['data'] except Exception as e: logger.error(f"Error during login: {e}") return None def fetch_symbol_data(exchange, tradingsymbol, symboltoken): """Fetch symbol data using exchange, trading symbol, and symbol token.""" try: return smartApi.ltpData(exchange, tradingsymbol, symboltoken) except Exception as e: logger.error(f"Error fetching symbol data: {e}") return None def update_ltp_data(): """Continuously fetch LTP data and store it.""" global latest_data session_data = login_to_api() if not session_data: logger.error("Login failed, could not fetch tokens.") return exchange = "NFO" tradingsymbol = "NIFTY03APR2523650CE" symboltoken = "54753" while True: ltp_data = fetch_symbol_data(exchange, tradingsymbol, symboltoken) if ltp_data: latest_data = { "timestamp": pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S'), "exchange": exchange, "symbol": tradingsymbol, "ltp": ltp_data['data']['ltp'], "open": ltp_data['data']['open'], "high": ltp_data['data']['high'], "low": ltp_data['data']['low'], "close": ltp_data['data']['close'] } logger.info(f"Updated LTP Data: {latest_data}") time.sleep(0.1) # Fetch new data every 0.1 seconds @app.route('/ltp', methods=['GET']) def get_ltp(): """API endpoint to get the latest LTP data.""" return jsonify(latest_data) @app.route('/') def index(): """Serve the HTML page that displays LTP data.""" html_content = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real-Time LTP Data</title> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } table, th, td { border: 1px solid #ddd; } th, td { padding: 10px; text-align: center; } th { background-color: #4CAF50; color: white; } td { background-color: #f9f9f9; } #ltp { color: darkblue; /* Dark blue for LTP text */ font-weight: bold; } .timestamp { color: #888; } </style> <script> function fetchLTPData() { fetch('/ltp') .then(response => response.json()) .then(data => { document.getElementById("timestamp").innerText = data.timestamp; document.getElementById("exchange").innerText = data.exchange; document.getElementById("symbol").innerText = data.symbol; document.getElementById("ltp").innerText = data.ltp; document.getElementById("open").innerText = data.open; document.getElementById("high").innerText = data.high; document.getElementById("low").innerText = data.low; document.getElementById("close").innerText = data.close; }) .catch(error => console.error('Error fetching LTP data:', error)); } // Fetch data every 1 second setInterval(fetchLTPData, 1000); </script> </head> <body> <h1>Real-Time LTP Data</h1> <table> <thead> <tr> <th>Timestamp</th> <th>Exchange</th> <th>Symbol</th> <th>LTP</th> <th>Open</th> <th>High</th> <th>Low</th> <th>Close</th> </tr> </thead> <tbody> <tr> <td id="timestamp" class="timestamp">Loading...</td> <td id="exchange">Loading...</td> <td id="symbol">Loading...</td> <td id="ltp">Loading...</td> <td id="open">Loading...</td> <td id="high">Loading...</td> <td id="low">Loading...</td> <td id="close">Loading...</td> </tr> </tbody> </table> </body> </html> ''' return render_template_string(html_content) # Run LTP fetching in a separate thread threading.Thread(target=update_ltp_data, daemon=True).start() if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True) Copy Copied Text: You Might Also Like Post a Comment
No comments