File size: 13,044 Bytes
f1331a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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
    )