i get this bug in my code can ou fix and output only the lines i need to replace?
  File "/home/rz1/Desktop/solana_trading_agent/main.py", line 497, in <module>
    agent_ui = TerminalTradingAgentUI()
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/rz1/Desktop/solana_trading_agent/main.py", line 108, in __init__
    self.layout = self.create_layout()
                  ^^^^^^^^^^^^^^^^^^^^
  File "/home/rz1/Desktop/solana_trading_agent/main.py", line 199, in create_layout
    dashboard_panel = self.render_dashboard_panel()
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/rz1/Desktop/solana_trading_agent/main.py", line 243, in render_dashboard_panel
    if self.trading_agents:
       ^^^^^^^^^^^^^^^^^^^
AttributeError: 'TerminalTradingAgentUI' object has no attribute 'trading_agents'

my code:
import sys
import threading
import queue
import time
import termios
import tty
import select
import os
import json
from collections import deque
from datetime import datetime
from rich.console import Console
from rich.layout import Layout
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.live import Live
from rich.align import Align
from rich import box

import openai
from openai import OpenAI
from trading_agent import TradingAgent, Config  # Import the TradingAgent and Config classes

# Initialize OpenAI client using environment variable
openai.api_key = os.environ.get('OPENAI_API_KEY', 'YOUR_OPENAI_API_KEY')

console = Console()

# Queues for thread-safe communication
log_queue = queue.Queue()
chat_queue = queue.Queue()

# Define the terminal settings for non-blocking input
class NonBlockingInput:
    def __init__(self):
        self.fd = sys.stdin.fileno()
        self.original_attrs = termios.tcgetattr(self.fd)
        tty.setcbreak(self.fd)

    def get_key(self):
        dr, dw, de = select.select([sys.stdin], [], [], 0)
        if dr:
            return sys.stdin.read(1)
        return None

    def restore(self):
        termios.tcsetattr(self.fd, termios.TCSADRAIN, self.original_attrs)

class TerminalTradingAgentUI:
    def __init__(self):
        # Configuration Fields with defaults
        self.config_fields = {
            "llm_api_key": os.environ.get('OPENAI_API_KEY', 'YOUR_OPENAI_API_KEY'),
            "llm_model": "gpt-4o-mini",
            "api_key": "your_api_key",
            "api_secret": "your_api_secret",
            "coin_list": 'SOL/USDT,SRM/USDT,RAY/USDT,KIN/USDT,FIDA/USDT',
            "interval": "5m",
            "base_trade_amount": "10",
            "stop_loss_percent": "2",
            "take_profit_percent": "5",
            "position_check_interval": "60",
        }
        self.should_exit = False

        # Assign log_queue and chat_queue to instance variables
        self.log_queue = log_queue
        self.chat_queue = chat_queue

        # Initialize UI State
        self.focus_order = [
            "chat_input",
            "llm_api_key",
            "api_key",
            "api_secret",
            "coin_list",
            "interval",
            "base_trade_amount",
            "stop_loss_percent",
            "take_profit_percent",
            "position_check_interval",
            "apply_button",
            "start_agent_button",
            "stop_agent_button",
            "agent_list"
        ]
        self.current_focus_index = 0  # Start with chat_input
        self.in_edit_mode = False
        self.edit_field = None
        self.input_buffer = ""
        self.chat_input = ""

        # Popup State
        self.show_popup = False
        self.popup_type = None  # 'edit', 'confirm', 'input'
        self.popup_field = None
        self.edit_buffer = ""

        # Chat and Logs
        self.chat_history = deque(maxlen=100)
        self.logs = deque(maxlen=100)

        # Initialize NonBlockingInput
        self.nbi = NonBlockingInput()

        # Initialize layout
        self.layout = self.create_layout()

        # Initialize agents list
        self.trading_agents = []
        self.agent_threads = []
        self.agent_focus_index = 0

        # Start log and chat handlers
        self.log_thread = threading.Thread(target=self.handle_logs, daemon=True)
        self.log_thread.start()
        self.chat_thread = threading.Thread(target=self.handle_chat, daemon=True)
        self.chat_thread.start()

        # Ensure at least one agent (agent0) is initialized
        self.initialize_default_agent()

        # Start background threads
        self.input_thread = threading.Thread(target=self.handle_inputs, daemon=True)
        self.input_thread.start()
        self.dashboard_update_thread = threading.Thread(target=self.update_dashboard_loop, daemon=True)
        self.dashboard_update_thread.start()

    def initialize_default_agent(self):
        # Create a default agent (agent0) and set it to running
        agent_config = Config()
        agent_config.api_key = self.config_fields["api_key"]
        agent_config.api_secret = self.config_fields["api_secret"]
        agent_config.llm_api_key = self.config_fields["llm_api_key"]
        agent_config.llm_model = self.config_fields["llm_model"]
        if isinstance(self.config_fields["coin_list"], list):
            agent_config.coin_list = [self.config_fields["coin_list"][0]]
        else:
            agent_config.coin_list = [self.config_fields["coin_list"].split(',')[0]]
        agent_config.interval = self.config_fields["interval"]
        agent_config.interval_seconds = self.get_interval_seconds(agent_config.interval)
        agent_config.base_trade_amount = float(self.config_fields["base_trade_amount"])
        agent_config.stop_loss_percent = float(self.config_fields["stop_loss_percent"])
        agent_config.take_profit_percent = float(self.config_fields["take_profit_percent"])
        agent_config.position_check_interval = int(self.config_fields["position_check_interval"])

        default_agent = TradingAgent(agent_config, log_queue=self.log_queue, chat_queue=self.chat_queue)
        default_agent.running = True  # Start agent0
        agent_thread = threading.Thread(target=default_agent.run, daemon=True)
        agent_thread.start()
        self.trading_agents.append(default_agent)
        self.agent_threads.append(agent_thread)
        self.agent_focus_index = 0
        self.log_queue.put(("log", "Default agent started."))

    def mask_api_key(self, key):
        if key and len(key) >= 12:
            return f"{key[:4]}****{key[-4:]}"
        elif key and len(key) > 8:
            return f"{key[:4]}{'*' * (len(key)-8)}{key[-4:]}"
        elif key:
            return "*" * len(key)
        return key

    def create_layout(self):
        layout = Layout()

        # Define the main areas
        layout.split(
            Layout(name="header", size=3),
            Layout(name="body", ratio=1),
            Layout(name="footer", size=3)
        )

        # Header
        header_text = Text("Terminal Trading Agent Dashboard", style="bold white on blue")
        header_panel = Panel(Align.center(header_text), style="bold blue", box=box.ROUNDED)
        layout["header"].update(header_panel)

        # Body split into sidebar, main, and right pane
        layout["body"].split_row(
            Layout(name="sidebar", size=40),
            Layout(name="main", ratio=1),
            Layout(name="right_pane", size=40)
        )

        # Sidebar - Configuration
        config_panel = self.render_config_panel()
        layout["sidebar"].update(config_panel)

        # Main Area - Dashboard and Chat
        layout["main"].split(
            Layout(name="dashboard", ratio=3),
            Layout(name="chat_area", ratio=1)
        )

        # Dashboard Panel
        dashboard_panel = self.render_dashboard_panel()
        layout["main"]["dashboard"].update(dashboard_panel)

        # Chat Area Panel
        chat_area_panel = self.render_chat_area_panel()
        layout["main"]["chat_area"].update(chat_area_panel)

        # Right Pane split into Logs and Wallet
        layout["right_pane"].split(
            Layout(name="logs", ratio=1),
            Layout(name="wallet", ratio=1)
        )

        # Logs Panel
        logs_panel = self.render_logs_panel()
        layout["right_pane"]["logs"].update(logs_panel)

        # Wallet Panel
        wallet_panel = self.render_wallet_panel()
        layout["right_pane"]["wallet"].update(wallet_panel)

        # Chat Input Area at the bottom
        chat_input_panel = self.render_chat_input_panel()
        layout["footer"].update(chat_input_panel)

        return layout

    def render_chat_area_panel(self):
        chat_content = "\n".join([msg for msg in self.chat_history])
        chat_panel = Panel(Align.left(chat_content), title="Chat", border_style="bold yellow", box=box.ROUNDED)
        return chat_panel

    def render_dashboard_panel(self):
        dashboard_table = Table(expand=True, box=box.SIMPLE_HEAVY)
        dashboard_table.add_column("ID", justify="center")
        dashboard_table.add_column("Coin Pair", justify="center")
        dashboard_table.add_column("Status", justify="center")
        dashboard_table.add_column("Timer", justify="center")
        dashboard_table.add_column("Last Operation", justify="center")
        dashboard_table.add_column("Interval", justify="center")
        dashboard_table.add_column("Control", justify="center")

        rotating_frames = ['-', '\\', '|', '/']

        if self.trading_agents:
            for idx, agent in enumerate(self.trading_agents):
                # Status with rotating animation
                if agent.running:
                    frame = rotating_frames[int(time.time() * 2) % len(rotating_frames)]
                    status = f"[bold green]{frame} Running[/bold green]"
                else:
                    status = f"[cyan]Idle[/cyan]"

                # Timer display
                time_remaining = max(0, agent.next_action_time - time.time()) if agent.running else 0
                timer_display = time.strftime('%H:%M:%S', time.gmtime(time_remaining))

                # Last operation
                last_op = agent.last_operation

                # Coin pair
                coin_pair = ", ".join(agent.config.coin_list)

                # Interval
                interval = f"{agent.config.interval_seconds} sec"

                # Control buttons
                if self.focus_order[self.current_focus_index] == "agent_list" and self.agent_focus_index == idx:
                    control = "[underline yellow]<P>/<S>[/underline yellow]"
                    agent_id_style = "[underline bold yellow]"
                else:
                    control = "<P>/<S>"
                    agent_id_style = ""
                control += " (Play/Pause/Stop)"

                dashboard_table.add_row(
                    f"{agent_id_style}{idx}{'' if agent_id_style == '' else '[/underline bold yellow]'}",
                    coin_pair,
                    status,
                    timer_display,
                    last_op,
                    interval,
                    control
                )
        else:
            dashboard_table.add_row("No agents running.", "", "", "", "", "", "")

        dashboard_panel = Panel(Align.center(dashboard_table), title="Agent Dashboard", border_style="bold green", box=box.ROUNDED)
        return dashboard_panel

    def render_logs_panel(self):
        logs_content = "\n".join([msg for msg in list(self.logs)[-20:]])
        logs_panel = Panel(Align.left(logs_content), title="Logs", border_style="bold blue", box=box.ROUNDED)
        return logs_panel

    def render_wallet_panel(self):
        if self.trading_agents:
            current_agent = self.trading_agents[self.agent_focus_index]
            wallet_info = current_agent.wallet
            wallet_address = wallet_info.get('address', 'N/A')
            pnl = wallet_info.get('pnl', 'N/A')
            balance = wallet_info.get('balance', {})
            wallet_content = Text(f"Agent ID: {self.agent_focus_index}\nWallet Address: {wallet_address}\nPnL: {pnl}\n\nBalances:\n")
            for coin, amount in balance.items():
                wallet_content.append(f"{coin}: {amount}\n")
            wallet_panel = Panel(Align.left(wallet_content), title="Wallet", border_style="bold magenta", box=box.ROUNDED)
        else:
            wallet_panel = Panel(Align.center("No agents running."), title="Wallet", border_style="bold magenta", box=box.ROUNDED)
        return wallet_panel

    def render_chat_input_panel(self):
        cursor = "|" if int(time.time() * 2) % 2 == 0 else " "  # Simple blinking cursor
        display_input = self.chat_input + cursor if self.focus_order[self.current_focus_index] == "chat_input" else self.chat_input
        chat_input_table = Table.grid(padding=(1,2))
        chat_input_table.add_column(justify="left", ratio=1)
        chat_input_table.add_column(justify="left", ratio=4)
        chat_input_table.add_row(
            Text(">> ", style="bold green"),
            Text(display_input, style="bold green")
        )
        chat_input_panel = Panel(chat_input_table, border_style="bold magenta", box=box.ROUNDED)
        return chat_input_panel

    def render_config_panel(self):
        config_table = Table.grid(expand=True, padding=(1, 2))
        config_table.add_column(justify="left", ratio=2)
        config_table.add_column(justify="left", ratio=3)

        for field, value in self.config_fields.items():
            if field.endswith("key") or field.endswith("secret"):
                display_value = self.mask_api_key(value) if value and value != "Not Set" else value
            else:
                display_value = str(value)

            if self.show_popup and self.popup_type == 'edit' and self.popup_field == field:
                display_value = self.edit_buffer + "|"

            if self.focus_order[self.current_focus_index] == field:
                config_table.add_row(
                    f"[bold cyan]{field.replace('_', ' ').upper()}:[/bold cyan]",
                    f"[underline bold yellow]{display_value}[/underline bold yellow]"
                )
            else:
                config_table.add_row(
                    f"[bold cyan]{field.replace('_', ' ').upper()}:[/bold cyan]",
                    display_value
                )

        # Add Apply and Control buttons at the bottom of the sidebar
        apply_button_label = "[bold magenta]<Apply Settings>"
        if self.focus_order[self.current_focus_index] == "apply_button":
            apply_button_label = "[underline bold yellow]<Apply Settings>[/underline bold yellow]"

        start_agent_button_label = "[bold green]<Start Agent>"
        if self.focus_order[self.current_focus_index] == "start_agent_button":
            start_agent_button_label = "[underline bold yellow]<Start Agent>[/underline bold yellow]"

        stop_agent_button_label = "[bold red]<Stop Agent>"
        if self.focus_order[self.current_focus_index] == "stop_agent_button":
            stop_agent_button_label = "[underline bold yellow]<Stop Agent>[/underline bold yellow]"

        config_table.add_row("", "")
        config_table.add_row(apply_button_label, "")
        config_table.add_row(start_agent_button_label, "")
        config_table.add_row(stop_agent_button_label, "")

        config_panel = Panel(config_table, title="Configuration", border_style="bold green", box=box.ROUNDED)

        # If popup is active, overlay it
        if self.show_popup:
            if self.popup_type == 'edit':
                field_label = self.popup_field.replace('_', ' ').upper()
                current_value = self.config_fields[self.popup_field]
                popup_content = Text(f"Edit {field_label}\n\nCurrent Value: {current_value}\n\nEnter new value:", style="bold white")
                popup = Panel(
                    Align.left(popup_content),
                    title="Edit Field",
                    border_style="bold yellow",
                    box=box.ROUNDED
                )
                config_panel = Panel(
                    Align.center(popup),
                    border_style="bold yellow",
                    box=box.SIMPLE
                )
            elif self.popup_type == 'confirm':
                popup_content = Text(self.edit_buffer, style="bold white")
                popup = Panel(
                    Align.center(popup_content),
                    title="Confirmation",
                    border_style="bold yellow",
                    box=box.ROUNDED
                )
                config_panel = Panel(
                    Align.center(popup),
                    border_style="bold yellow",
                    box=box.SIMPLE
                )
            elif self.popup_type == 'input':
                popup_content = Text(self.edit_buffer, style="bold white")
                popup = Panel(
                    Align.left(popup_content),
                    title="Input Required",
                    border_style="bold yellow",
                    box=box.ROUNDED
                )
                config_panel = Panel(
                    Align.center(popup),
                    border_style="bold yellow",
                    box=box.SIMPLE
                )

        return config_panel

    # Rest of the methods in TerminalTradingAgentUI (handle_inputs, handle_logs, handle_chat, etc.)

    def handle_logs(self):
        while not self.should_exit:
            try:
                msg_type, message = self.log_queue.get(timeout=1)
                timestamp = time.strftime("[%H:%M:%S]")
                if msg_type == "log":
                    self.logs.append(f"{timestamp} {message}")
                elif msg_type == "error":
                    self.logs.append(f"{timestamp} [bold red]{message}[/bold red]")
                elif msg_type == "warning":
                    self.logs.append(f"{timestamp} [bold yellow]{message}[/bold yellow]")
                self.update_logs_panel()
            except queue.Empty:
                pass

    def handle_chat(self):
        while not self.should_exit:
            try:
                msg_type, message = self.chat_queue.get(timeout=1)
                if msg_type == "assistant":
                    self.chat_history.append(f"Assistant: {message}")
                elif msg_type == "agent":
                    self.chat_history.append(f"Agent: {message}")
                self.update_chat_area_panel()
            except queue.Empty:
                pass

    def handle_inputs(self):
        # Implement the input handling logic
        pass  # (Include the full method in your implementation)

    def update_logs_panel(self):
        self.layout["right_pane"]["logs"].update(self.render_logs_panel())

    def update_chat_area_panel(self):
        self.layout["main"]["chat_area"].update(self.render_chat_area_panel())

    def update_dashboard_panel(self):
        self.layout["main"]["dashboard"].update(self.render_dashboard_panel())
        self.layout["right_pane"]["wallet"].update(self.render_wallet_panel())

    def update_config_panel(self):
        self.layout["sidebar"].update(self.render_config_panel())

    def update_chat_input_panel(self):
        self.layout["footer"].update(self.render_chat_input_panel())

    def run(self):
        with Live(self.layout, refresh_per_second=10, screen=True) as live:
            while not self.should_exit:
                try:
                    live.update(self.layout)
                    time.sleep(0.1)
                except KeyboardInterrupt:
                    self.should_exit = True
        self.nbi.restore()
        console.print("[bold red]Application has exited.[/bold red]")

    def get_interval_seconds(self, interval_str):
        units = {'m': 60, 'h': 3600, 'd': 86400}
        try:
            return int(interval_str[:-1]) * units[interval_str[-1]]
        except:
            return 300  # Default to 5 minutes

    def process_command(self, command):
        # Implement the command processing logic
        pass  # (Include the full method in your implementation)

    def chat_handler(self, user_input):
        # Implement the chat handling logic
        pass  # (Include the full method in your implementation)

    # Additional methods as required...

    def update_dashboard_loop(self):
        while not self.should_exit:
            self.update_dashboard_panel()
            time.sleep(0.5)

if __name__ == "__main__":
    try:
        agent_ui = TerminalTradingAgentUI()
        agent_ui.run()
    except KeyboardInterrupt:
        sys.exit(0)