Spaces:
Build error
Build error
Denis Mbugua commited on
Commit Β·
dc93bbc
1
Parent(s): 4c2987e
R eupload changes
Browse filesFiles changed (3)
- app.py+69-9
- trading_floor.py+39-2
- util.py+4
1233 unmodified lines7891011127 unmodified lines202122232425154 unmodified lines1801811821831841851861871881891901911921931941951961971981991 unmodified line201202203204205206207208209import gradio as grfrom util import css, js, Colorimport pandas as pd3 unmodified linesfrom database import read_logimport threadingfrom trading_floor import run_every_n_minutesimport asyncioimport os7 unmodified lines}class Trader:def __init__(self, name: str, lastname: str, model_name: str):self.name = name154 unmodified linesprint(f"Error creating directory {MEMORY_DIR}: {e}")raisedef start_trading_floor():"""Run trading floor in a separate thread"""# 1. Ensure the directory is readysetup_directories()# 2. Proceed with running the agentsasyncio.run(run_every_n_minutes())# Start trading floor in background threadtrading_thread = threading.Thread(target=start_trading_floor, daemon=True)trading_thread.start()# Main UI constructiondef create_ui():"""Create the main Gradio UI for the trading simulation"""traders = [Trader(trader_name, lastname, model_name)1 unmodified line]trader_views = [TraderView(trader) for trader in traders]with gr.Blocks(title="Traders", css=css, js=js, theme=gr.themes.Default(primary_hue="sky"), fill_width=True) as ui:with gr.Row():for trader_view in trader_views:trader_view.make_ui()12343 unmodified lines8910111213147 unmodified lines2223242526272829154 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342351 unmodified line237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269from hmac import trans_36import gradio as grfrom util import css, js, Colorimport pandas as pd3 unmodified linesfrom database import read_logimport threadingfrom trading_floor import run_every_n_minutesfrom util import stop_eventimport asyncioimport os7 unmodified lines}trading_thread = Noneclass Trader:def __init__(self, name: str, lastname: str, model_name: str):self.name = name154 unmodified linesprint(f"Error creating directory {MEMORY_DIR}: {e}")raisedef stop_trading_thread():global trading_threadif trading_thread is None or not trading_thread.is_alive():return "π Trading floor is not running."print("Stopping trading floor...")# 1. Set the stop signalstop_event.set()# 2. Wait for the thread to finish its current task and exit the loop safelytrading_thread.join(timeout=10) # Wait up to 10 seconds for graceful exitif trading_thread.is_alive():return "β Trading floor thread failed to stop gracefully within 10 seconds."else:trading_thread = None # Clear the variablereturn "β Trading floor stopped successfully."def start_trading_floor_and_thread():global trading_thread# check is thead is runningif trading_thread is not None and trading_thread.is_alive():return "β οΈ Trading floor is already running."# Reset the stop event and create directorystop_event.clear()setup_directories()# 3. Define the thread's target function (wrapper to pass the event)def target_wrapper():# The target function now correctly passes the stop_eventasyncio.run(run_every_n_minutes())# 4. Create and start the threadtrading_thread = threading.Thread(target=target_wrapper, daemon=True)trading_thread.start()return "π Trading floor started."# Main UI constructiondef create_ui():"""Create the main Gradio UI for the trading simulation"""print(f"Stop event {stop_event.is_set()}")traders = [Trader(trader_name, lastname, model_name)1 unmodified line]trader_views = [TraderView(trader) for trader in traders]# stop_btn = gr.Button("Stop Trading Floor", variant="stop")# stop_btn.click(fn=lambda: stop_trading_floor(), inputs=[], outputs=[])with gr.Blocks(title="Traders", css=css, js=js, theme=gr.themes.Default(primary_hue="sky"), fill_width=True) as ui:with gr.Row():start_btn = gr.Button("Start Trading Floor π", variant="primary")stop_btn = gr.Button("Stop Trading Floor π", variant="stop")# Add Status Outputthread_status = gr.Textbox(label="Thread Status", value="Ready to start.", interactive=False)# Link buttons to functionsstart_btn.click(fn=start_trading_floor_and_thread,outputs=[thread_status],show_progress="hidden")stop_btn.click(fn=stop_trading_thread,outputs=[thread_status],show_progress="hidden")with gr.Row():for trader_view in trader_views:trader_view.make_ui()
1231 unmodified line567891028 unmodified lines3940414243444546474849505152from traders import Traderfrom typing import Listimport asyncio1 unmodified linefrom agents import add_trace_processorfrom market import is_market_openfrom dotenv import load_dotenvimport osload_dotenv(override=True)28 unmodified linesasync def run_every_n_minutes():add_trace_processor(LogTracer())traders = create_traders()while True:if RUN_EVEN_WHEN_MARKET_IS_CLOSED or is_market_open():await asyncio.gather(*[trader.run() for trader in traders])else:print("Market is closed, skipping run")await asyncio.sleep(RUN_EVERY_N_MINUTES * 60)if __name__ == "__main__":12341 unmodified line678910111228 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import threadingfrom traders import Traderfrom typing import Listimport asyncio1 unmodified linefrom agents import add_trace_processorfrom market import is_market_openfrom dotenv import load_dotenvfrom util import stop_eventimport osload_dotenv(override=True)28 unmodified linesasync def run_every_n_minutes():"""Runs trading agents every N minutes, cooperatively stopping when signaled."""add_trace_processor(LogTracer())traders = create_traders()# Create an asyncio Event to link the thread signal to the loopasync_stop_event = asyncio.Event()# Function to set the asyncio event from the thread's loopdef stop_callback():# This function runs in the context of the running asyncio loopif stop_event.is_set():async_stop_event.set()else:# Re-schedule this check if the event hasn't been setloop = asyncio.get_running_loop()loop.call_later(1, stop_callback)# Start the periodic check for the threading.Eventloop = asyncio.get_running_loop()loop.call_later(1, stop_callback)while not async_stop_event.is_set():if RUN_EVEN_WHEN_MARKET_IS_CLOSED or is_market_open():print("Running trade cycle...")# Run agentsawait asyncio.gather(*[trader.run() for trader in traders])else:print("Market is closed, skipping run")# Wait for the next interval OR the stop signaltry:# Wait for the interval, but be interruptible by async_stop_event.set()await asyncio.wait_for(async_stop_event.wait(), timeout=RUN_EVERY_N_MINUTES * 60)except asyncio.TimeoutError:# Timeout hit, continue to the next iterationcontinueexcept Exception:# The async_stop_event was set, or another issue occurredbreakprint("Agent trading loop terminated safely.")if __name__ == "__main__":
12345from enum import Enumcss = """.positive-pnl {color: green !important;123456789from enum import Enumimport threadingstop_event = threading.Event()css = """.positive-pnl {color: green !important;
app.py+69-9
trading_floor.py+39-2
util.py+4