import gradio as gr import pyotp from api_helper import ShoonyaApiPy import threading import time from collections import deque import pandas as pd import plotly.graph_objects as go import traceback import asyncio import datetime # Global variables crudeoilm_ltp = None ce_ltp = None pe_ltp = None current_strike = None strike_interval = 50 # Adjust if CRUDEOILM has a different strike interval ce_token = None pe_token = None # Initialize lock for thread safety data_lock = threading.Lock() # Deque to store historical data for the chart MAX_POINTS = 500 historical_data = deque(maxlen=MAX_POINTS) # Event to signal when we're connected and subscribed api_ready = threading.Event() # Create a global FigureWidget for the Plotly chart fig_widget = go.FigureWidget() # New global variable to store the latest data latest_data = {"premium": None, "time": None, "strike": None} # Global API instance api = ShoonyaApiPy() # CRUDEOILM expiry dates expiry_dates = [ datetime.datetime.strptime("17/09/24", "%d/%m/%y").date(), datetime.datetime.strptime("17/10/24", "%d/%m/%y").date(), datetime.datetime.strptime("15/11/24", "%d/%m/%y").date(), datetime.datetime.strptime("16/12/24", "%d/%m/%y").date() ] def run_api(): global crudeoilm_ltp, ce_ltp, pe_ltp, current_strike, ce_token, pe_token # Credentials user = 'FA28777' pwd = 'Ebgc@D55' factor2 = pyotp.TOTP('445KIV2355QM5266QJ557MA55P77V763').now() vc = 'FA28777_U' app_key = 'd23f2af8135baf5a67ec90cd2d8c6ebf' imei = 'abc1234' try: print("Attempting to log in...") ret = api.login(userid=user, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei) print(f"Login response: {ret}") if 'stat' not in ret or ret['stat'] != 'Ok': print(f"Login failed. Response: {ret}") return def event_handler_feed_update(tick_data): global crudeoilm_ltp, ce_ltp, pe_ltp, current_strike, ce_token, pe_token print(f"Received tick data: {tick_data}") if 'lp' in tick_data and 'tk' in tick_data: token = tick_data['tk'] ltp = float(tick_data['lp']) with data_lock: if token == get_crudeoilm_token(): crudeoilm_ltp = ltp new_strike = get_atm_strike(crudeoilm_ltp) if new_strike != current_strike: update_subscriptions(api, current_strike, new_strike) current_strike = new_strike elif token == ce_token: ce_ltp = ltp elif token == pe_token: pe_ltp = ltp def open_callback(): print("WebSocket connection opened.") api_ready.set() api.start_websocket(order_update_callback=lambda x: None, subscribe_callback=event_handler_feed_update, socket_open_callback=open_callback) print("Subscribing to CRUDEOILM...") api.subscribe([f"MCX|{get_crudeoilm_token()}"]) print("Subscribed to CRUDEOILM.") while True: time.sleep(1) except Exception as e: print(f"An error occurred in run_api: {str(e)}") traceback.print_exc() def get_crudeoilm_token(): # Replace with actual CRUDEOILM token return "430107" # This is a placeholder, replace with the correct token def get_atm_strike(crudeoilm_value): return round(crudeoilm_value / strike_interval) * strike_interval def get_option_tokens(strike): global ce_token, pe_token expiry_date = get_next_expiry() ce_symbol = f"CRUDEOILM{expiry_date}C{strike}" pe_symbol = f"CRUDEOILM{expiry_date}P{strike}" ce_result = api.searchscrip('MCX', ce_symbol) pe_result = api.searchscrip('MCX', pe_symbol) if ce_result['stat'] == 'Ok' and pe_result['stat'] == 'Ok': ce_token = ce_result['values'][0]['token'] pe_token = pe_result['values'][0]['token'] print(f"Fetched tokens - CE: {ce_token}, PE: {pe_token}") return ce_token, pe_token else: print(f"Error fetching tokens for strike {strike}") return None, None def get_next_expiry(): today = datetime.date.today() next_expiry = min(date for date in expiry_dates if date >= today) return next_expiry.strftime("%d%b%y").upper() def update_subscriptions(api, old_strike, new_strike): global ce_token, pe_token if old_strike: api.unsubscribe([f"MCX|{ce_token}", f"MCX|{pe_token}"]) ce_token, pe_token = get_option_tokens(new_strike) if ce_token and pe_token: api.subscribe([f"MCX|{ce_token}", f"MCX|{pe_token}"]) def get_combined_premium(): if not api_ready.is_set(): return "Waiting for API connection..." with data_lock: if ce_ltp is not None and pe_ltp is not None and current_strike is not None: combined_premium = ce_ltp + pe_ltp current_time = pd.Timestamp.now(tz='Asia/Kolkata') historical_data.append({"time": current_time, "premium": combined_premium, "strike": current_strike}) return f"CRUDEOILM: {crudeoilm_ltp:.2f} | Strike: {current_strike} | Combined Premium: {combined_premium:.2f}" else: return f"Waiting for LTP updates... CRUDEOILM: {crudeoilm_ltp}, CE: {ce_ltp}, PE: {pe_ltp}, Strike: {current_strike}" def create_chart(): df = pd.DataFrame(list(historical_data)) if df.empty: fig_widget.data = [] return fig_widget x_range = fig_widget.layout.xaxis.range if fig_widget.layout.xaxis.range else None y_range = fig_widget.layout.yaxis.range if fig_widget.layout.yaxis.range else None with fig_widget.batch_update(): fig_widget.data = [] fig_widget.layout.annotations = [] fig_widget.add_trace(go.Scatter(x=df['time'], y=df['premium'], mode='lines', name='Premium', line=dict(color='orange'))) fig_widget.update_layout( title=f"CRUDEOILM ATM Premiums (Current Strike: {current_strike})", height=500, margin=dict(l=50, r=50, t=50, b=50), xaxis_title="Time", yaxis_title="Net Premium", template="plotly_dark", xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, label="1m", step="minute", stepmode="backward"), dict(count=10, label="10m", step="minute", stepmode="backward"), dict(count=30, label="30m", step="minute", stepmode="backward"), dict(count=1, label="1h", step="hour", stepmode="backward"), dict(step="all") ]), font=dict(color="orange"), bgcolor="black" ), rangeslider=dict(visible=True), type="date", range=x_range, tickformat='%H:%M:%S', tickmode="auto", showgrid=False ), yaxis=dict(range=y_range, showgrid=False), ) if not df.empty: current_premium = df['premium'].iloc[-1] current_time = df['time'].iloc[-1] fig_widget.add_annotation( x=current_time, y=current_premium, text=f"{current_premium:.2f}", showarrow=True, arrowhead=1, ax=20, ay=-40, font=dict(size=12, color="orange"), bgcolor="black", bordercolor="orange", borderwidth=1 ) return fig_widget latest_data = {} async def continuous_data_update(): global latest_data while True: premium_info = get_combined_premium() # Make sure this function works synchronously if "Combined Premium:" in premium_info: crudeoilm, strike, premium = premium_info.split("|") crudeoilm_value = float(crudeoilm.split(":")[1].strip()) strike_value = int(strike.split(":")[1].strip()) premium_value = float(premium.split(":")[1].strip()) latest_data = { "premium": premium_value, "time": pd.Timestamp.now(tz='Asia/Kolkata'), "strike": strike_value, "crudeoilm": crudeoilm_value } # Sleep for 1 second between updates await asyncio.sleep(1) async def main(): # Run the data update task await continuous_data_update() if __name__ == "__main__": # Start the event loop and run the main coroutine asyncio.run(main()) def update_chart(): global historical_data, latest_data if latest_data["premium"] is not None: historical_data.append(latest_data) return create_chart() # Start the API thread thread = threading.Thread(target=run_api, daemon=True) thread.start() # Create Gradio interface with gr.Blocks(css=".gradio-container {background-color: black; color: white;}") as demo: gr.Markdown("# CRUDEOILM ATM Premiums Tracker", elem_id="premium-header") crudeoilm_display = gr.Textbox(label="Current CRUDEOILM Value", elem_id="crudeoilm-display") strike_display = gr.Textbox(label="Current ATM Strike", elem_id="strike-display") output = gr.Textbox(label="Current Premium", elem_id="premium-display") chart = gr.Plot(label="Premium Chart", value=fig_widget) async def update_data(): premium_info = get_combined_premium() crudeoilm_value = latest_data.get("crudeoilm", "N/A") strike_value = latest_data.get("strike", "N/A") fig = update_chart() return f"{crudeoilm_value:.2f}" if isinstance(crudeoilm_value, float) else crudeoilm_value, \ str(strike_value), \ premium_info, \ fig demo.load(update_data, outputs=[crudeoilm_display, strike_display, output, chart], every=60) # Start the continuous update in the background asyncio.create_task(continuous_data_update()) # Launch Gradio app demo.queue().launch(share=True)