# braedonsaunders/homerun architecture

> Architecture diagram of the GitHub repository braedonsaunders/homerun, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-05). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/braedonsaunders/homerun
- Repository: https://github.com/braedonsaunders/homerun

## Overview

1. **Overall shape**
   - Homerun is a full-stack trading platform centered on a Python backend and a React/TypeScript frontend.
   - The backend is the system of record and runtime controller; the frontend is an operational console for editing, validating, backtesting, monitoring, and executing strategies and data sources.

2. **Backend API layer**
   - `backend/main.py` boots a FastAPI application.
   - Route modules under `backend/api/` partition the surface by domain: strategies, data sources, traders, discovery, news, weather, AI, ML, simulation, settings, workers, and execution/orchestration.
   - WebSocket support is part of the backend API, not a separate service, and is used for live UI updates and real-time state distribution.

3. **Persistent core and schema evolution**
   - PostgreSQL is the main persistence layer, accessed asynchronously through SQLAlchemy models in `backend/models/`.
   - Alembic migrations in `backend/alembic/versions/` show heavy schema evolution around strategy/version management, data-source records, trader state, discovery profiles, live trading state, notifications, and ML/AI artifacts.
   - This indicates the architecture is DB-driven: runtime behavior, configuration, and history are mostly stored rather than hardcoded.

4. **Strategy runtime as a first-class subsystem**
   - Strategies live in `backend/services/strategies/` and are implemented as Python classes with lifecycle methods such as detection, evaluation, and exit logic.
   - `backend/services/strategy_runtime.py`, `strategy_loader.py`, `strategy_sdk.py`, and `strategy_versioning.py` form the machinery for loading strategies from the DB, hot-reloading them, validating them, and running them against markets and events.
   - Strategies consume market data, source records, and events, then emit opportunities/signals into the rest of the system.

5. **Data source ingestion pipeline**
   - Custom and built-in data sources are managed through `backend/services/data_source_*` modules.
   - The runtime pattern is fetch → transform → normalize → upsert into stored records, with SDK support for writing custom sources in Python.
   - Sources can be RSS, REST, WebSockets, Chainlink, Binance, Twitter/X, or custom Python, and they feed both direct strategy reads and event-driven updates.

6. **Eventing and live state propagation**
   - `backend/services/event_bus.py`, `event_dispatcher.py`, `signal_bus.py`, and `runtime_signal_queue.py` provide the internal pub/sub and queueing layer.
   - Background workers and strategy runtimes subscribe to data-source updates, market refreshes, and operational events.
   - The frontend receives live state over WebSockets, which means UI panels are driven by event streams rather than polling alone.

7. **Worker-based background processing**
   - `backend/workers/` contains separate worker processes for scanner, discovery, news, weather, events, traders, market universe, reconciliation, Cortex, and SLO/monitoring tasks.
   - These workers are the execution boundary for periodic, streaming, and reconciliation jobs; they keep the API responsive and separate long-running market processing from request handling.
   - The architecture is intentionally horizontally decomposed by concern rather than as one monolithic loop.

8. **Trading and execution pipeline**
   - Trading is handled by `backend/services/trader_orchestrator/` plus adjacent execution services like `live_execution_service.py`, `live_execution_adapter.py`, `fill_monitor.py`, and `trading_proxy.py`.
   - The lifecycle is multi-stage: detect → evaluate → preflight/risk gate → arm → execute → monitor/reconcile.
   - Execution targets include paper/simulation and live venues such as Polymarket and Kalshi, with venue-specific logic abstracted behind adapters and orchestrator policies.

9. **Risk, sizing, and safety controls**
   - Risk management is not peripheral; it is embedded in the execution path through decision gates, exposure limits, inventory checks, liquidity checks, Kelly sizing, token circuit breakers, and order verification.
   - Separate validation and maintenance services support safe enabling, disabling, and cleanup of strategies/traders.
   - This forms a hard boundary between signal generation and trade placement.

10. **Discovery, wallets, and trader intelligence**
   - There is a distinct discovery layer for finding and scoring wallets/traders, centered around wallet tracking, clustering, network analysis, and copy-trading logic.
   - Services such as `wallet_discovery.py`, `wallet_intelligence.py`, `trader_data_access.py`, `traders_copy_trade_signal_service.py`, and `trader_hot_state.py` support this subsystem.
   - It feeds trader-oriented opportunities into the shared signal and execution stack, but with its own profiling, ranking, and runtime state.

11. **AI and research subsystem**
   - `backend/services/ai/` contains LLM provider abstraction, agent/memory/tooling, market analysis, news sentiment, and opportunity judging.
   - The Cortex-related modules and AI route surface suggest a self-contained research/assistant layer that can read platform state, call tools, and write outputs back into the system.
   - The AI layer is integrated with the domain model rather than acting as a standalone chat feature.

12. **Specialized vertical workflows**
   - News, weather, crypto, events, and market-monitoring each have their own service subtrees and orchestration modules.
   - Examples include `news/workflow_orchestrator.py`, `weather/workflow_orchestrator.py`, `crypto_service.py`, `market_monitor.py`, and `scanner.py`.
   - These are domain pipelines that normalize external signals into the same opportunity/data/event backbone used by strategies and traders.

13. **Frontend architecture**
   - The frontend is a React app in `frontend/src/`, with feature panels for strategies, traders, discovery, news intelligence, AI, ML models, markets, settings, and trading.
   - API access is encapsulated in `frontend/src/services/`, while live updates are handled through hooks such as WebSocket and realtime invalidation.
   - UI state is organized around operational views, not generic CRUD screens, reflecting the backend’s domain-centric architecture.

14. **Operational tooling and environment**
   - The repo includes launcher scripts, Docker/Postgres setup, CI workflows, tests, and migration tooling, showing that the project is meant to run as a locally deployable platform with reproducible infrastructure.
   - The desktop launcher and `scripts/infra/` helpers indicate a “single-command” local environment, while tests cover runtime, execution, simulation, data ingestion, and UI-integrated behaviors.
   - For an architecture diagram, the key deployment boundary is: external data/venue providers on the edge, backend services/workers in the middle, PostgreSQL as state, and the React dashboard as the operator console.

Main entry points: [`backend/api/routes.py`](https://github.com/braedonsaunders/homerun/blob/main/backend/api/routes.py) (API Routes), [`backend/services/event_bus.py`](https://github.com/braedonsaunders/homerun/blob/main/backend/services/event_bus.py) (Event Bus), [`frontend/src/App.tsx`](https://github.com/braedonsaunders/homerun/blob/main/frontend/src/App.tsx) (React App), [`backend/services/trader_orchestrator/session_engine.py`](https://github.com/braedonsaunders/homerun/blob/main/backend/services/trader_orchestrator/session_engine.py) (Trader Orchestrator)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_g_backend["Backend"]
  node_n_main["API App<br/>FastAPI entrypoint<br/>[main.py]"]
  node_n_routes["API Routes<br/>HTTP surface<br/>[routes.py]"]
  node_n_ws(("WebSocket Hub<br/>live updates<br/>[websocket.py]"))
  node_n_strategy_runtime["Strategy Runtime<br/>strategy engine"]
  node_n_data_sources["Data Sources<br/>ingestion pipeline"]
  node_n_event_bus(("Event Bus<br/>pubsub core<br/>[event_bus.py]"))
  node_n_trader_orch["Trader Orchestrator<br/>execution controller<br/>[session_engine.py]"]
  node_n_risk{{"Risk Gates<br/>safety controls<br/>[risk_manager.py]"}}
  node_n_execution["Execution Service<br/>venue execution"]
  node_n_discovery["Discovery Stack<br/>wallet intelligence"]
  node_n_ai["AI Layer<br/>LLM/agent tools<br/>[agent.py]"]
  node_n_verticals["Domain Pipelines<br/>news/weather/market"]
  node_n_workers["Workers<br/>background processes<br/>[runner.py]"]
end

subgraph group_g_frontend["Frontend"]
  node_n_front_app["React App<br/>frontend shell<br/>[App.tsx]"]
  node_n_panels["Ops Panels<br/>feature views"]
  node_n_client["API Client<br/>service layer<br/>[api.ts]"]
  node_n_ws_hook(("Realtime Hook<br/>ui sync<br/>[useWebSocket.ts]"))
end

subgraph group_g_data["State"]
  node_n_models[("Models<br/>ORM schema<br/>[database.py]")]
  node_n_migrations["Migrations<br/>schema evolution"]
end

node_n_main -->|"mounts"| node_n_routes
node_n_main -->|"serves"| node_n_ws
node_n_routes -->|"controls"| node_n_strategy_runtime
node_n_routes -->|"manages"| node_n_data_sources
node_n_routes -->|"orchestrates"| node_n_trader_orch
node_n_routes -->|"serves"| node_n_discovery
node_n_routes -->|"exposes"| node_n_ai
node_n_routes -->|"exposes"| node_n_verticals
node_n_strategy_runtime -->|"publishes"| node_n_event_bus
node_n_data_sources -->|"publishes"| node_n_event_bus
node_n_event_bus -->|"feeds"| node_n_ws
node_n_event_bus -->|"consumed by"| node_n_workers
node_n_trader_orch -->|"gated by"| node_n_risk
node_n_trader_orch -->|"executes via"| node_n_execution
node_n_discovery -->|"publishes"| node_n_event_bus
node_n_ai -->|"reads/writes"| node_n_models
node_n_verticals -->|"feeds"| node_n_event_bus
node_n_workers -->|"persists"| node_n_models
node_n_models -->|"evolves via"| node_n_migrations
node_n_front_app -->|"renders"| node_n_panels
node_n_front_app -->|"uses"| node_n_client
node_n_front_app -->|"subscribes"| node_n_ws_hook
node_n_client -->|"calls"| node_n_routes
node_n_ws_hook -->|"connects"| node_n_ws

click node_n_main "https://github.com/braedonsaunders/homerun/blob/main/backend/main.py"
click node_n_routes "https://github.com/braedonsaunders/homerun/blob/main/backend/api/routes.py"
click node_n_ws "https://github.com/braedonsaunders/homerun/blob/main/backend/api/websocket.py"
click node_n_strategy_runtime "https://github.com/braedonsaunders/homerun/blob/main/backend/services/strategy_runtime.py"
click node_n_data_sources "https://github.com/braedonsaunders/homerun/blob/main/backend/services/data_source_runner.py"
click node_n_event_bus "https://github.com/braedonsaunders/homerun/blob/main/backend/services/event_bus.py"
click node_n_trader_orch "https://github.com/braedonsaunders/homerun/blob/main/backend/services/trader_orchestrator/session_engine.py"
click node_n_risk "https://github.com/braedonsaunders/homerun/blob/main/backend/services/trader_orchestrator/risk_manager.py"
click node_n_execution "https://github.com/braedonsaunders/homerun/blob/main/backend/services/live_execution_service.py"
click node_n_discovery "https://github.com/braedonsaunders/homerun/blob/main/backend/services/wallet_discovery.py"
click node_n_ai "https://github.com/braedonsaunders/homerun/blob/main/backend/services/ai/agent.py"
click node_n_verticals "https://github.com/braedonsaunders/homerun/blob/main/backend/services/news/workflow_orchestrator.py"
click node_n_workers "https://github.com/braedonsaunders/homerun/blob/main/backend/workers/runner.py"
click node_n_models "https://github.com/braedonsaunders/homerun/blob/main/backend/models/database.py"
click node_n_migrations "https://github.com/braedonsaunders/homerun/blob/main/backend/alembic/versions/202602130001_baseline_schema.py"
click node_n_front_app "https://github.com/braedonsaunders/homerun/blob/main/frontend/src/App.tsx"
click node_n_panels "https://github.com/braedonsaunders/homerun/blob/main/frontend/src/components/StrategiesPanel.tsx"
click node_n_client "https://github.com/braedonsaunders/homerun/blob/main/frontend/src/services/api.ts"
click node_n_ws_hook "https://github.com/braedonsaunders/homerun/blob/main/frontend/src/hooks/useWebSocket.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_n_main,node_n_routes,node_n_ws,node_n_strategy_runtime,node_n_data_sources,node_n_event_bus,node_n_trader_orch,node_n_risk,node_n_execution,node_n_discovery,node_n_ai,node_n_verticals,node_n_workers toneBlue
class node_n_front_app,node_n_panels,node_n_client,node_n_ws_hook toneAmber
class node_n_models,node_n_migrations toneMint
```

## Components

### Backend

FastAPI API, domain services, workers, and persistence-backed runtime.

- [API App](https://github.com/braedonsaunders/homerun/blob/main/backend/main.py): FastAPI entrypoint · Boots the backend application and mounts the HTTP/WebSocket surface. · `backend/main.py`
- [API Routes](https://github.com/braedonsaunders/homerun/blob/main/backend/api/routes.py): HTTP surface · Domain-partitioned route modules for strategies, traders, data, AI, discovery, and execution. · `backend/api/routes.py`
- [WebSocket Hub](https://github.com/braedonsaunders/homerun/blob/main/backend/api/websocket.py): live updates · Pushes real-time state and events to the UI. · `backend/api/websocket.py`
- [Strategy Runtime](https://github.com/braedonsaunders/homerun/blob/main/backend/services/strategy_runtime.py): strategy engine · Loads, versions, validates, and executes DB-backed strategies. · `backend/services/strategy_runtime.py`
- [Data Sources](https://github.com/braedonsaunders/homerun/blob/main/backend/services/data_source_runner.py): ingestion pipeline · Fetches, transforms, normalizes, and stores external market/data feeds. · `backend/services/data_source_runner.py`
- [Event Bus](https://github.com/braedonsaunders/homerun/blob/main/backend/services/event_bus.py): pubsub core · Internal signal, queue, and dispatcher layer for runtime propagation. · `backend/services/event_bus.py`
- [Trader Orchestrator](https://github.com/braedonsaunders/homerun/blob/main/backend/services/trader_orchestrator/session_engine.py): execution controller · Coordinates detect→gate→execute→monitor lifecycle for trading. · `backend/services/trader_orchestrator/session_engine.py`
- [Risk Gates](https://github.com/braedonsaunders/homerun/blob/main/backend/services/trader_orchestrator/risk_manager.py): safety controls · Decision gates, sizing, exposure, verification, and order safety checks. · `backend/services/trader_orchestrator/risk_manager.py`
- [Execution Service](https://github.com/braedonsaunders/homerun/blob/main/backend/services/live_execution_service.py): venue execution · Live and simulated execution adapters, fills, monitoring, and venue abstraction. · `backend/services/live_execution_service.py`
- [Discovery Stack](https://github.com/braedonsaunders/homerun/blob/main/backend/services/wallet_discovery.py): wallet intelligence · Wallet discovery, clustering, scoring, and copy-trade signal generation. · `backend/services/wallet_discovery.py`
- [AI Layer](https://github.com/braedonsaunders/homerun/blob/main/backend/services/ai/agent.py): LLM/agent tools · Cortex and assistant services for analysis, tools, prompts, and model integration. · `backend/services/ai/agent.py`
- [Domain Pipelines](https://github.com/braedonsaunders/homerun/blob/main/backend/services/news/workflow_orchestrator.py): news/weather/market · Specialized workflows for news, weather, crypto, scanning, and market monitoring. · `backend/services/news/workflow_orchestrator.py`
- [Workers](https://github.com/braedonsaunders/homerun/blob/main/backend/workers/runner.py): background processes · Separate worker processes for scanner, discovery, news, weather, traders, reconciliation, and monitoring. · `backend/workers/runner.py`

### Frontend

React operator console and API client layer.

- [React App](https://github.com/braedonsaunders/homerun/blob/main/frontend/src/App.tsx): frontend shell · Operator-facing React application for monitoring and control. · `frontend/src/App.tsx`
- [Ops Panels](https://github.com/braedonsaunders/homerun/blob/main/frontend/src/components/StrategiesPanel.tsx): feature views · Strategy, trader, discovery, news, AI, ML, settings, and trading views. · `frontend/src/components/StrategiesPanel.tsx`
- [API Client](https://github.com/braedonsaunders/homerun/blob/main/frontend/src/services/api.ts): service layer · Frontend API wrappers for backend domains and state mutation. · `frontend/src/services/api.ts`
- [Realtime Hook](https://github.com/braedonsaunders/homerun/blob/main/frontend/src/hooks/useWebSocket.ts): ui sync · WebSocket and invalidation hooks for live UI updates. · `frontend/src/hooks/useWebSocket.ts`

### State

Database schema, models, and migrations that hold platform state.

- [Models](https://github.com/braedonsaunders/homerun/blob/main/backend/models/database.py): ORM schema · Async SQLAlchemy models for market, opportunity, and platform state. · `backend/models/database.py`
- [Migrations](https://github.com/braedonsaunders/homerun/blob/main/backend/alembic/versions/202602130001_baseline_schema.py): schema evolution · Alembic history for strategy, trader, discovery, execution, and AI/ML tables. · `backend/alembic/versions/202602130001_baseline_schema.py`

## Connections

- API App → API Routes: mounts · Application startup attaches the domain route surface.
- API App → WebSocket Hub: serves · The backend exposes live update channels alongside HTTP endpoints.
- API Routes → Strategy Runtime: controls · Strategy endpoints create, validate, backtest, and execute strategy lifecycles.
- API Routes → Data Sources: manages · Routes configure and inspect external data sources.
- API Routes → Trader Orchestrator: orchestrates · Routes expose trader lifecycle and execution controls.
- API Routes → Discovery Stack: serves · Discovery routes surface wallet and trader intelligence.
- API Routes → AI Layer: exposes · AI routes provide agent, model, and research surfaces.
- API Routes → Domain Pipelines: exposes · Domain workflows for news, weather, crypto, and scanning are routed here.
- Strategy Runtime → Event Bus: publishes · Strategy outcomes and runtime state are emitted into internal signals.
- Data Sources → Event Bus: publishes · Ingested updates are normalized and broadcast to downstream consumers.
- Event Bus → WebSocket Hub: feeds · Shared events are pushed through WebSockets to the operator UI.
- Event Bus → Workers: consumed by · Background jobs subscribe to internal signals and queues.
- Trader Orchestrator → Risk Gates: gated by · Execution passes through safety, sizing, and preflight checks.
- Trader Orchestrator → Execution Service: executes via · The orchestrator sends orders and monitors fills through execution services.
- Discovery Stack → Event Bus: publishes · Wallet and trader intelligence emits signals into the shared runtime.
- AI Layer → Models: reads/writes · AI features are backed by persisted models and platform state.
- Domain Pipelines → Event Bus: feeds · Specialized pipelines normalize domain events into the common backbone.
- Workers → Models: persists · Workers update runtime, reconciliation, and domain state in the database.
- Models → Migrations: evolves via · Database schema is shaped by repeated Alembic migrations.
- React App → Ops Panels: renders · The React shell composes the major operational panels.
- React App → API Client: uses · UI components call backend APIs through a shared client layer.
- React App → Realtime Hook: subscribes · The frontend receives live state through WebSocket hooks.
- API Client → API Routes: calls · Frontend client modules map to the backend route surface.
- Realtime Hook → WebSocket Hub: connects · Realtime UI state is synchronized over backend WebSockets.
