Trading_server / app_simple.py
DakshGoyal1506's picture
Upload 20 files
f1331a5 verified
Raw History Blame Contribute Delete
13 kB
import gradio as gr
import os
import asyncio
import threading
import time
from util import css, js, Color
import pandas as pd
from trading_floor import names, lastnames, short_model_names
import plotly.express as px
from accounts import Account
from database import read_log
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Simplified version for Hugging Face Spaces
# Since we can't easily run multiple MCP servers, we'll simulate the trading environment
mapper = {
"trace": Color.WHITE,
"agent": Color.CYAN,
"function": Color.GREEN,
"generation": Color.YELLOW,
"response": Color.MAGENTA,
"account": Color.RED,
}
# Global flag for simulation
simulation_running = False
def start_simulation():
"""Start the trading simulation in demo mode"""
global simulation_running
if simulation_running:
return "Simulation is already running"
simulation_running = True
# Initialize demo accounts with some sample data
try:
for name in names:
account = Account.get(name)
# Add some sample transactions and portfolio history
if len(account.portfolio_value_time_series) == 0:
# Add initial portfolio value
account.portfolio_value_time_series.append([time.strftime("%Y-%m-%d %H:%M:%S"), 10000])
return "βœ… Demo simulation started! The AI traders are now active with demo data."
except Exception as e:
return f"❌ Error starting simulation: {str(e)}"
def stop_simulation():
"""Stop the trading simulation"""
global simulation_running
simulation_running = False
return "πŸ›‘ Simulation stopped"
def reset_accounts():
"""Reset all accounts to initial state"""
try:
# Import and use the reset functionality
from reset import reset_all_accounts
reset_all_accounts()
return "πŸ”„ All accounts have been reset to initial state"
except Exception as e:
return f"❌ Error resetting accounts: {str(e)}"
class Trader:
def __init__(self, name: str, lastname: str, model_name: str):
self.name = name
self.lastname = lastname
self.model_name = model_name
self.account = Account.get(name)
def reload(self):
self.account = Account.get(self.name)
def get_title(self) -> str:
return f"<div style='text-align: center;font-size:34px;'>{self.name}<span style='color:#ccc;font-size:24px;'> ({self.model_name}) - {self.lastname}</span></div>"
def get_strategy(self) -> str:
try:
return self.account.get_strategy()
except:
return "Loading strategy..."
def get_portfolio_value_df(self) -> pd.DataFrame:
try:
df = pd.DataFrame(self.account.portfolio_value_time_series, columns=["datetime", "value"])
if len(df) > 0:
df["datetime"] = pd.to_datetime(df["datetime"])
return df
except:
return pd.DataFrame(columns=["datetime", "value"])
def get_portfolio_value_chart(self):
df = self.get_portfolio_value_df()
if len(df) == 0:
# Return empty chart if no data
fig = px.line(title="No portfolio data available yet")
fig.update_layout(
height=300,
paper_bgcolor="#bbb",
plot_bgcolor="#dde",
margin=dict(l=40, r=20, t=40, b=40)
)
return fig
fig = px.line(df, x="datetime", y="value", title=f"{self.name}'s Portfolio Value")
margin = dict(l=40, r=20, t=40, b=40)
fig.update_layout(
height=300,
margin=margin,
xaxis_title="Time",
yaxis_title="Portfolio Value ($)",
paper_bgcolor="#bbb",
plot_bgcolor="#dde",
)
fig.update_xaxes(tickformat="%m/%d", tickangle=45, tickfont=dict(size=8))
fig.update_yaxes(tickfont=dict(size=8), tickformat=",.0f")
return fig
def get_holdings_df(self) -> pd.DataFrame:
"""Convert holdings to DataFrame for display"""
try:
holdings = self.account.get_holdings()
if not holdings:
return pd.DataFrame(columns=["Symbol", "Quantity"])
df = pd.DataFrame(
[{"Symbol": symbol, "Quantity": quantity} for symbol, quantity in holdings.items()]
)
return df
except:
return pd.DataFrame(columns=["Symbol", "Quantity"])
def get_transactions_df(self) -> pd.DataFrame:
"""Convert transactions to DataFrame for display"""
try:
transactions = self.account.list_transactions()
if not transactions:
return pd.DataFrame(columns=["Timestamp", "Symbol", "Quantity", "Price", "Rationale"])
return pd.DataFrame(transactions)
except:
return pd.DataFrame(columns=["Timestamp", "Symbol", "Quantity", "Price", "Rationale"])
def get_portfolio_value(self) -> str:
"""Calculate total portfolio value based on current prices"""
try:
portfolio_value = self.account.calculate_portfolio_value() or 10000.0
pnl = self.account.calculate_profit_loss(portfolio_value) or 0.0
color = "green" if pnl >= 0 else "red"
emoji = "⬆" if pnl >= 0 else "⬇"
return f"<div style='text-align: center;background-color:{color};color:white;padding:10px;border-radius:5px;'><span style='font-size:32px'>${portfolio_value:,.0f}</span><span style='font-size:24px'>&nbsp;&nbsp;&nbsp;{emoji}&nbsp;${pnl:,.0f}</span></div>"
except:
return "<div style='text-align: center;background-color:gray;color:white;padding:10px;border-radius:5px;'><span style='font-size:32px'>$10,000</span><span style='font-size:24px'>&nbsp;&nbsp;&nbsp;➑&nbsp;$0</span></div>"
def get_logs(self, previous=None) -> str:
try:
logs = read_log(self.name, last_n=10)
response = ""
for log in logs:
timestamp, log_type, message = log
color = mapper.get(log_type, Color.WHITE).value
response += f"<span style='color:{color}'>{timestamp} : [{log_type}] {message}</span><br/>"
if not logs:
response = f"<span style='color:{Color.CYAN.value}'>No trading activity yet. Start the simulation to begin trading!</span><br/>"
response = f"<div style='height:200px; overflow-y:auto; background-color:#f0f0f0; padding:10px; border-radius:5px;'>{response}</div>"
if response != previous:
return response
return gr.update()
except:
return f"<div style='height:200px; overflow-y:auto; background-color:#f0f0f0; padding:10px; border-radius:5px;'><span style='color:{Color.CYAN.value}'>Waiting for trading data...</span></div>"
class TraderView:
def __init__(self, trader: Trader):
self.trader = trader
self.portfolio_value = None
self.chart = None
self.holdings_table = None
self.transactions_table = None
def make_ui(self):
with gr.Column():
gr.HTML(self.trader.get_title())
with gr.Row():
self.portfolio_value = gr.HTML(self.trader.get_portfolio_value)
with gr.Row():
self.chart = gr.Plot(
self.trader.get_portfolio_value_chart, container=True, show_label=False
)
with gr.Row(variant="panel"):
self.log = gr.HTML(self.trader.get_logs)
with gr.Row():
self.holdings_table = gr.Dataframe(
value=self.trader.get_holdings_df,
label="Holdings",
headers=["Symbol", "Quantity"],
row_count=(3, "dynamic"),
col_count=2,
max_height=200,
elem_classes=["dataframe-fix-small"],
)
with gr.Row():
self.transactions_table = gr.Dataframe(
value=self.trader.get_transactions_df,
label="Recent Transactions",
headers=["Timestamp", "Symbol", "Quantity", "Price", "Rationale"],
row_count=(3, "dynamic"),
col_count=5,
max_height=200,
elem_classes=["dataframe-fix"],
)
# Refresh timer - slower for Hugging Face Spaces
timer = gr.Timer(value=10)
timer.tick(
fn=self.refresh,
inputs=[],
outputs=[
self.portfolio_value,
self.chart,
self.holdings_table,
self.transactions_table,
],
show_progress="hidden",
queue=False,
)
# Log timer
log_timer = gr.Timer(value=5)
log_timer.tick(
fn=self.trader.get_logs,
inputs=[self.log],
outputs=[self.log],
show_progress="hidden",
queue=False,
)
def refresh(self):
self.trader.reload()
return (
self.trader.get_portfolio_value(),
self.trader.get_portfolio_value_chart(),
self.trader.get_holdings_df(),
self.trader.get_transactions_df(),
)
def create_ui():
"""Create the main Gradio UI for the trading simulation"""
traders = [
Trader(trader_name, lastname, model_name)
for trader_name, lastname, model_name in zip(names, lastnames, short_model_names)
]
trader_views = [TraderView(trader) for trader in traders]
with gr.Blocks(
title="AI Trading Simulation",
css=css,
js=js,
theme=gr.themes.Default(primary_hue="sky"),
fill_width=True
) as ui:
gr.Markdown("# πŸ€– AI Trading Simulation Dashboard")
gr.Markdown("""
### Real-time AI agents trading with different strategies and models
**About this demo:** This simulation features AI trading agents with different personalities and strategies:
- **Warren (Patience)**: Conservative, long-term focused
- **George (Bold)**: Aggressive, high-risk strategies
- **Ray (Systematic)**: Data-driven, algorithmic approach
- **Cathie (Crypto)**: Innovation and crypto focused
Each agent uses different AI models (GPT-4, DeepSeek, Gemini, Grok) and makes autonomous trading decisions.
""")
# Control panel
with gr.Row():
with gr.Column(scale=1):
start_btn = gr.Button("πŸš€ Start Demo Simulation", variant="primary", size="lg")
stop_btn = gr.Button("πŸ›‘ Stop Simulation", variant="secondary")
reset_btn = gr.Button("πŸ”„ Reset Accounts", variant="stop")
with gr.Column(scale=2):
status_output = gr.Textbox(
label="System Status",
value="Welcome! Click 'Start Demo Simulation' to begin watching AI traders in action.",
interactive=False,
lines=3
)
# Connect buttons to functions
start_btn.click(
fn=start_simulation,
outputs=status_output
)
stop_btn.click(
fn=stop_simulation,
outputs=status_output
)
reset_btn.click(
fn=reset_accounts,
outputs=status_output
)
gr.Markdown("---")
# Trading dashboard
with gr.Row():
for trader_view in trader_views:
trader_view.make_ui()
gr.Markdown("""
---
### πŸ“Š How it works:
1. **Start the simulation** to activate the AI traders
2. **Watch the portfolio values** change as agents make decisions
3. **Monitor the logs** to see real-time trading activity and reasoning
4. **Check holdings and transactions** to understand each agent's strategy
*Note: This is a demo version running with simulated data. The full version connects to real market data and uses live MCP servers.*
""")
return ui
if __name__ == "__main__":
ui = create_ui()
ui.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
show_error=True
)