#!/usr/bin/env python3 """ Premium Trading Dashboard - Clean Structure """ import os import sys import pandas as pd import gradio as gr import plotly.graph_objects as go import plotly.express as px from datetime import datetime, timedelta, timezone import logging import requests import time import nltk # Import dependencies with fallback try: from alpaca.trading.client import TradingClient from alpaca.trading.requests import GetOrdersRequest, GetPortfolioHistoryRequest from alpaca.trading.enums import OrderStatus from alpaca.data.timeframe import TimeFrame from alpaca.data.historical import StockHistoricalDataClient ALPACA_AVAILABLE = True except ImportError: ALPACA_AVAILABLE = False try: from textblob import TextBlob from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer SENTIMENT_AVAILABLE = True except ImportError: SENTIMENT_AVAILABLE = False # API Keys API_KEY = os.getenv('ALPACA_API_KEY', 'PK2FD9B2S86LHR7ZBHG1') SECRET_KEY = os.getenv('ALPACA_SECRET_KEY', 'QPmGPDgbPArvHv6cldBXc7uWddapYcIAnBhtkuBW') VM_API_URL = os.getenv('VM_API_URL', 'http://34.56.193.18:8090') # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("🚀 Starting Premium Trading Dashboard...") # Download NLTK data try: nltk.download('punkt', quiet=True) nltk.download('vader_lexicon', quiet=True) logger.info("✅ NLTK data downloaded") except: logger.warning("⚠️ NLTK download failed") # Initialize clients trading_client = None if ALPACA_AVAILABLE: try: trading_client = TradingClient(api_key=API_KEY, secret_key=SECRET_KEY) logger.info("✅ Alpaca client initialized") except: logger.warning("⚠️ Alpaca client failed") # Simple functions for testing def get_account_info(): """Get account information""" if not trading_client: return { 'portfolio_value': 100000, 'buying_power': 25000, 'cash': 25000, 'day_change': 1250, 'equity': 100000 } try: account = trading_client.get_account() return { 'portfolio_value': float(account.portfolio_value), 'buying_power': float(account.buying_power), 'cash': float(account.cash), 'day_change': float(account.portfolio_value) - float(account.last_equity), 'equity': float(account.equity) } except Exception as e: logger.error(f"Account error: {e}") return {'error': str(e)} def refresh_account_overview(): """Refresh account overview""" logger.info("🔄 Refreshing account overview...") info = get_account_info() if 'error' in info: return "Error", "Error", "Error", "Error", "Error" return ( f"${info['portfolio_value']:,.2f}", f"${info['buying_power']:,.2f}", f"${info['cash']:,.2f}", f"${info['day_change']:+,.2f}", f"${info['equity']:,.2f}" ) def create_simple_chart(): """Create a simple chart""" import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[10, 11, 12, 13, 14], mode='lines+markers', name='Portfolio Value' )) fig.update_layout( title="Sample Portfolio Chart", xaxis_title="Time", yaxis_title="Value ($)" ) return fig def get_sample_data(): """Get sample IPO data""" return """

📈 Recent IPO Investments

Symbol Investment P&L
RDDT $1,000 +$150
PLTR $1,000 -$50
""" def execute_command(command): """Execute terminal command""" logger.info(f"Executing: {command}") return f"$ {command}\nCommand executed successfully! ✅\n(This is a demo response)" def create_dashboard(): """Create the main dashboard""" logger.info("🎨 Creating dashboard interface...") # ALL components must be defined inside this context with gr.Blocks(title="🚀 Premium Trading Dashboard", theme=gr.themes.Soft()) as demo: logger.info("🖼️ Inside Blocks context") # Header gr.HTML("""

🚀 Premium Trading Dashboard

Real-time IPO Trading with Sentiment Analysis

""") with gr.Tabs(): # Portfolio Overview Tab with gr.Tab("📊 Portfolio Overview"): gr.Markdown("## 💼 Account Summary") with gr.Row(): portfolio_value = gr.Textbox(label="💰 Portfolio Value", interactive=False) buying_power = gr.Textbox(label="💳 Buying Power", interactive=False) cash = gr.Textbox(label="💵 Cash", interactive=False) day_change = gr.Textbox(label="📈 Day Change", interactive=False) equity = gr.Textbox(label="🏦 Total Equity", interactive=False) refresh_overview_btn = gr.Button("🔄 Refresh Overview", variant="primary", size="lg") gr.Markdown("## 📈 Portfolio Performance") portfolio_chart = gr.Plot(label="Portfolio Value Over Time") # IPO Discoveries Tab with gr.Tab("🔍 IPO Discoveries"): gr.Markdown("## 🎯 IPO Analytics") ipo_data = gr.HTML(get_sample_data()) refresh_ipo_btn = gr.Button("🔄 Refresh IPO Data", variant="primary") # Investment Performance Tab with gr.Tab("💰 Investment Performance"): gr.Markdown("## 📊 P&L Analysis") investment_table = gr.HTML(get_sample_data()) refresh_performance_btn = gr.Button("🔄 Refresh Performance", variant="primary") # VM Terminal Tab with gr.Tab("💻 VM Terminal"): gr.Markdown("## 🖥️ Remote Terminal") command_input = gr.Textbox(label="Command", placeholder="Enter command...") execute_btn = gr.Button("▶️ Execute", variant="primary") terminal_output = gr.Textbox(label="Output", lines=10, interactive=False) # Event Handlers - ALL INSIDE the Blocks context logger.info("🔗 Setting up event handlers...") # Portfolio tab events refresh_overview_btn.click( fn=refresh_account_overview, outputs=[portfolio_value, buying_power, cash, day_change, equity] ) # IPO tab events refresh_ipo_btn.click( fn=get_sample_data, outputs=[ipo_data] ) # Performance tab events refresh_performance_btn.click( fn=get_sample_data, outputs=[investment_table] ) # Terminal events execute_btn.click( fn=execute_command, inputs=[command_input], outputs=[terminal_output] ) # Initial data load demo.load( fn=refresh_account_overview, outputs=[portfolio_value, buying_power, cash, day_change, equity] ) demo.load( fn=create_simple_chart, outputs=[portfolio_chart] ) demo.queue() logger.info("✅ Event handlers configured successfully") logger.info("✅ Dashboard created successfully") return demo if __name__ == "__main__": try: demo = create_dashboard() logger.info("✅ Dashboard created successfully!") logger.info("🚀 Launching dashboard server...") demo.launch() logger.info("✅ Dashboard launched successfully!") except Exception as e: logger.error(f"❌ Dashboard failed: {e}") raise