How rohan1090/trading_workstation works
1. What this repo is
- Trading Workstation is a terminal-first Python trading platform for strategy development, backtesting, paper trading, and live execution.
- The architecture is centered on one strategy code path that can run unchanged across modes: backtest, paper, and live.
2. Primary control plane
- The main entry point is the tw CLI in src/trading_workstation/cli.py.
- bootstrap.py wires together configuration, providers, execution adapters, runtime state, persistence, and optional TUI depending on the selected mode.
3. Core domain boundary
- The models/ package defines broker-agnostic Pydantic types for market data, orders, positions, accounts, signals, and backtest results.
- This is the main boundary that keeps strategies and runtime logic independent from Schwab, Alpaca, Yahoo, or any fake/test implementation.
4. Strategy layer
- Strategies live under strategies/ and are dynamically loaded via src/trading_workstation/strategy/loader.py.
- A strategy implements the BaseStrategy contract and interacts only through StrategyContext, which is read-only and exposes recent bars, latest quotes, positions, account state, and logging.
- Strategies emit TargetIntent objects; they do not submit orders directly.
5. Runtime orchestration
- runtime/engine.py is the central orchestrator for live and paper modes.
- Its cycle is: fetch market data, invoke strategy callbacks, convert intents into orders, submit through the execution adapter, update runtime state, and publish events.
- runtime/state.py holds the mutable trading state, while runtime/events.py provides the synchronous event bus used for observability and UI updates.
- runtime/scheduler.py provides timed execution and optional market-hours awareness.
6. Market data providers
- providers/ abstracts quote, bar, and option-chain retrieval behind a common MarketDataProvider.
- The concrete providers are Schwab OAuth/API, Yahoo Finance fallback, and deterministic fake data for tests/demo.
- Provider selection is automatic, so architecture-wise the data source is swappable without changing strategy code.
7. Execution adapters
- execution/ abstracts order submission behind ExecutionAdapter.
- The main adapters are fake simulated fills, Alpaca paper trading, and Schwab live trading.
- execution/router.py chooses the adapter based on mode, while live_schwab.py adds safety guardrails such as dry-run defaults, kill switch, and order/session/value limits.
8. Backtesting subsystem
- backtest/engine.py runs strategies over historical bars and simulates fills through fills.py.
- metrics.py computes performance measures like return, drawdown, Sharpe, win rate, and profit factor.
- reports.py writes backtest artifacts and CLI summaries, typically into data/artifacts/.
- This subsystem is separate from live runtime but reuses the same strategy and model abstractions.
9. Persistence and audit trail
- persistence/journal.py provides an append-only JSONL trade journal for intents, orders, and fills.
- persistence/sqlite_store.py stores operational data locally in SQLite, including orders, fills, positions, equity snapshots, and events.
- Both are fed from the event/state stream, making persistence an observer rather than a trading dependency.
10. TUI and observability
- tui/app.py is a Textual-based terminal UI with multiple screens for watchlist, symbol detail, option chain, strategy status, orders, account, and logs.
- The TUI reads from RuntimeState and subscribes to the EventBus; it does not call broker APIs directly.
- Presenters and widgets handle formatting and visualization, while the runtime remains the source of truth.
11. Configuration and environment
- Static configuration lives in YAML under configs/, with profile overrides for backtest, paper, and live modes plus a symbols watchlist.
- Environment variables supply credentials and live-trading settings, especially for Schwab and Alpaca.
- config/loader.py and config/models.py validate and normalize this configuration into typed settings.
12. Safety and testing emphasis
- Live trading is explicitly protected by default-dry-run behavior and guardrails in the Schwab executor.
- The repo includes extensive unit tests for the strategy loader, runtime engine, event bus, execution routing, providers, backtest engine, persistence, and TUI presenters.
- Architecturally, the tests reinforce the same boundary structure: strategy, runtime, provider, execution, persistence, and UI are all independently verified.
Main entry points: bootstrap.py Bootstrap · runtime/engine.py Runtime engine · backtest/engine.py Backtest engine · providers Market providers
Components 27
Control plane
Entry points and bootstrap wiring
Domain
Strategy contracts and shared models
- Core models · Broker-agnostic data structures for market data, orders, positions, accounts, signals, and results.
src/trading_workstation/models - Strategy contract · Base strategy interface and read-only context used by strategy code.
src/trading_workstation/strategy/base.py - Strategy loader · Discovers and loads strategy implementations dynamically.
src/trading_workstation/strategy/loader.py - Example strategies · Sample strategies demonstrating the strategy contract.
strategies/example_sma_cross.py
Runtime
Live/paper orchestration and state
- Runtime engine · Coordinates fetch, strategy callback, intent conversion, execution, state updates, and events.
src/trading_workstation/runtime/engine.py - Runtime state · In-memory trading state shared across the runtime and UI.
src/trading_workstation/runtime/state.py - Event bus · Synchronous event stream for observability and UI updates.
src/trading_workstation/runtime/events.py - Scheduler · Timed execution and market-hours-aware scheduling.
src/trading_workstation/runtime/scheduler.py
Data & execution
Market data sources and order adapters
- Market providers · Swappable market data providers for bars, quotes, and option chains.
src/trading_workstation/providers - Schwab data · Schwab-backed market data provider.
src/trading_workstation/providers/schwab.py - Yahoo fallback · Fallback provider for public market data.
src/trading_workstation/providers/yahoo_fallback.py - Fake data · Deterministic provider for tests and demos.
src/trading_workstation/providers/fake.py - Execution router · Chooses the execution backend for backtest, paper, or live mode.
src/trading_workstation/execution/router.py - Fake fills · Simulated order fills used for testing and non-live runs.
src/trading_workstation/execution/fake.py - Paper adapter · Alpaca paper-trading execution adapter.
src/trading_workstation/execution/paper_alpaca.py - Live Schwab · Schwab live-trading adapter with guardrails and safety limits.
src/trading_workstation/execution/live_schwab.py
Backtesting
Historical simulation and reporting
- Backtest engine · Runs strategies over historical bars and simulates fills.
src/trading_workstation/backtest/engine.py - Metrics · Computes performance statistics such as return, drawdown, Sharpe, win rate, and profit factor.
src/trading_workstation/backtest/metrics.py - Reports · Writes backtest artifacts and CLI summaries.
src/trading_workstation/backtest/reports.py
Persistence
Audit trail and local storage
- Trade journal · Append-only JSONL journal for intents, orders, and fills.
src/trading_workstation/persistence/journal.py - SQLite store · Local operational store for orders, fills, positions, equity snapshots, and events.
src/trading_workstation/persistence/sqlite_store.py
TUI
Terminal UI and presentation
- Terminal UI · Textual-based application shell for watchlist, strategy, orders, account, option chain, and logs.
src/trading_workstation/tui/app.py - Presenters · Formatting and visualization helpers for UI screens and widgets.
src/trading_workstation/tui/presenters/formatters.py
Config
Typed configuration loading
- Config loader · Loads and normalizes profile and environment-based configuration.
src/trading_workstation/config/loader.py - Config models · Typed configuration definitions and validation models.
src/trading_workstation/config/models.py
Connections 35
- tw CLI → Bootstrap: starts · CLI hands off to bootstrap for mode-specific assembly.
- Bootstrap → Config loader: loads · Bootstrap loads configuration before wiring subsystems.
- Bootstrap → Strategy loader: loads strategies · Bootstrap resolves the selected strategy implementation.
- Bootstrap → Market providers: selects data · Bootstrap wires the market data provider.
- Bootstrap → Execution router: selects execution · Bootstrap chooses the execution adapter for the mode.
- Bootstrap → Runtime engine: starts runtime · Bootstrap launches live or paper orchestration.
- Bootstrap → Backtest engine: starts backtest · Bootstrap launches historical simulation when requested.
- Bootstrap → Terminal UI: optional UI · Bootstrap starts the terminal UI when enabled.
- Config loader → Config models: validates · Loaded settings are normalized into typed models.
- Strategy loader → Strategy contract: instantiates · Loaded strategies must conform to the base contract.
- Example strategies → Strategy contract: implements · Example strategies demonstrate the shared strategy interface.
- Strategy contract → Core models: uses types · Strategies exchange domain objects through the shared model boundary.
- Runtime engine → Market providers: fetches market data · Runtime asks the provider for the latest market inputs.
- Runtime engine → Strategy contract: invokes · Runtime calls strategy logic through the standard contract.
- Runtime engine → Runtime state: updates · Runtime mutates the canonical in-memory trading state.
- Runtime engine → Event bus: publishes · Runtime emits events for observability and UI consumers.
- Runtime engine → Execution router: submits intents · Runtime converts intents into orders via the execution layer.
- Runtime engine → Scheduler: ticks · Scheduler drives timed engine cycles.
- Market providers → Schwab data: backed by · Schwab is the primary market data source.
- Market providers → Yahoo fallback: fallback · Yahoo acts as a fallback source.
- Market providers → Fake data: test source · Fake provider supports tests and demo runs.
- Execution router → Fake fills: routes to · Fake execution is used for simulation and tests.
- Execution router → Paper adapter: routes to · Paper mode uses the Alpaca adapter.
- Execution router → Live Schwab: routes to · Live mode uses the Schwab adapter.
- Backtest engine → Core models: reuses types · Backtesting shares the same market and order models.
- Backtest engine → Fake fills: simulates fills · Backtest fill behavior is handled by the simulation layer.
- Backtest engine → Metrics: computes · Backtest output is summarized by metrics calculations.
- Backtest engine → Reports: writes reports · Results are emitted as artifacts and summaries.
- Runtime state → Trade journal: observed by · State and intent streams are journaled for auditability.
- Runtime state → SQLite store: persisted to · Operational snapshots are stored locally in SQLite.
- Event bus → Terminal UI: feeds UI · The UI subscribes to runtime events.
- Runtime state → Terminal UI: read by · The UI renders current trading state without broker access.
- Terminal UI → Presenters: formats with · Screens use presenters for display formatting.
- Live Schwab → Core models: uses types · Execution adapters operate on shared broker-agnostic models.
- Schwab data → Core models: uses types · Provider output is normalized into the shared domain boundary.