- Python 75.7%
- HTML 23.9%
- Dockerfile 0.3%
- Shell 0.1%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
All checks were successful
CI Pipeline / Lint, Type Check & Test (push) Successful in 1m39s
|
||
| .forgejo/workflows | ||
| docs | ||
| scripts | ||
| src/trading_system | ||
| tests | ||
| .env.example | ||
| .gitignore | ||
| AGENTS.md | ||
| ARCHITECTURE.md | ||
| docker-compose.coolify.yaml | ||
| docker-compose.yaml | ||
| docker-entrypoint.sh | ||
| Dockerfile | ||
| HANDOFF.md | ||
| MANIFEST.in | ||
| pyproject.toml | ||
| README.md | ||
| renovate.json | ||
| ROADMAP.md | ||
Automated Stock Trading Platform
An institutional-grade, modular, automated stock trading platform in Python, starting with Alpaca's Paper Trading sandbox and designed for multi-timeframe swing and intraday strategies.
The system is architected around a strict Safety First ("Iron Gate") philosophy: strategies are completely decoupled from broker execution, every signal must pass pre-trade risk checks and circuit breakers, and all decisions are recorded to an immutable audit trail.
Tip
Switching Computers or Resuming Work? Read
HANDOFF.mdfor the complete developer handoff guide, environment setup, test verification commands, and operational roadmap.
Key Highlights
- Decoupled Architecture: Strict unidirectional pipeline:
Market Data -> Strategy (Signals) -> Risk Engine (Orders) -> Execution Router -> Broker. - Safety First ("The Iron Gate"): Hardcoded paper-trading defaults, dual-flag live locks, automatic drawdown circuit breakers (-2% daily cap), fat-finger price collars, and an emergency multi-channel Kill Switch.
- Multi-Source Market Data Engine: Alpaca Market Data v2 (IEX real-time feed for paper/live trading),
yfinancefor deep historical daily backfills, and an embeddedDuckDB+ Parquet local caching lake. - Financial-Grade Audit Trail: Append-only event store (DuckDB + JSONL) tracking all market events, signals, risk evaluations, and execution fills with deterministic correlation IDs.
- Real-Time & Executive Alerts: Discord Webhooks for instant fill and circuit-breaker alerts; planned Zoho Mail integration (SMTP/API) for scheduled end-of-day executive P&L summaries.
- Forgejo CI Integration: Native Forgejo Actions pipeline (
.forgejo/workflows/ci.yaml) paired with a local diagnostic utility (scripts/forgejo_ci.py) for instantaneous automated CI failure triage.
System Architecture
flowchart TD
subgraph DataEngine ["Market Data Engine"]
AlpacaData[Alpaca Market Data v2 (IEX)]
YFinance[yfinance Historical Ingestor]
DataNormalizer[Bar & Tick Normalizer]
DuckDBCache[(DuckDB / Parquet Store)]
AlpacaData --> DataNormalizer
YFinance --> DataNormalizer
DataNormalizer --> DuckDBCache
end
subgraph StrategyEngine ["Alpha & Strategy Engine"]
Indicators[Technical Indicators (EMA, RSI, ATR)]
StrategyBase[BaseStrategy]
SwingStrategy[Swing Strategy Modules]
DuckDBCache --> Indicators
Indicators --> StrategyBase
StrategyBase --> SwingStrategy
end
subgraph RiskEngine ["Risk Engine (The Iron Gate)"]
Signals[SignalEvent]
PreTradeCheck[Pre-Trade Risk Validator]
DrawdownGuard[Daily Max Drawdown Check]
PositionSizer[Risk-Adjusted Sizing]
KillSwitch[Emergency Kill Switch]
SwingStrategy --> Signals
Signals --> PreTradeCheck
PreTradeCheck --> DrawdownGuard
DrawdownGuard --> PositionSizer
KillSwitch -.-> PreTradeCheck
end
subgraph ExecutionEngine ["Execution & Broker"]
OrderRouter[Order Router]
PaperBroker[Alpaca Paper Sandbox]
LiveBroker[Alpaca Live (Locked)]
PositionSizer --> OrderRouter
OrderRouter -->|TRADING_MODE=paper| PaperBroker
OrderRouter -.->|TRADING_MODE=live| LiveBroker
end
subgraph StorageAndAudit ["Audit & Observability"]
AuditLedger[(Append-Only Audit Ledger)]
DiscordAlerts[Discord Webhooks]
ZohoAlerts[Zoho Mail Digests]
Signals -.-> AuditLedger
PreTradeCheck -.-> AuditLedger
OrderRouter -.-> AuditLedger
AuditLedger --> DiscordAlerts
AuditLedger -.-> ZohoAlerts
end
Project Structure
stock-trading/
├── .forgejo/
│ └── workflows/
│ └── ci.yaml # Forgejo Actions CI pipeline
├── .env.example # Environment variables template
├── .gitignore # Excludes secrets, caches, and parquet lake
├── AGENTS.md # Agent guidelines, safety rules, and code quality
├── ARCHITECTURE.md # In-depth architectural specification
├── ROADMAP.md # Multi-phase project roadmap & tracker
├── README.md # This file
├── pyproject.toml # Project dependencies and tool configurations
├── scripts/
│ └── forgejo_ci.py # Forgejo CI log reader & triage utility
├── src/
│ └── trading_system/
│ ├── config/ # Type-safe settings via pydantic-settings
│ ├── core/ # Base events, models, and domain types
│ ├── data/ # Alpaca, yfinance, and DuckDB storage
│ ├── strategies/ # Alpha generators and technical indicators
│ ├── risk/ # Sizing, circuit breakers, and kill switch
│ ├── execution/ # Alpaca broker client and order routing
│ ├── portfolio/ # Shadow ledger and reconciliation loop
│ ├── storage/ # Parquet lake and DuckDB audit store
│ └── notifications/ # Discord webhooks and Zoho email dispatcher
└── tests/
├── conftest.py # Shared test fixtures and mock broker
├── unit/ # Unit tests for strategies, risk, and math
└── integration/ # Integration tests with Alpaca sandbox
Quick Start & Setup
1. Prerequisites
- Python 3.12 or higher
- Git
- Alpaca Paper Trading Account (Free at alpaca.markets)
2. Environment Setup
Clone the repository and set up a virtual environment:
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
Configuration & Secrets Management
Secrets and configuration are strictly segregated between Forgejo Actions (CI) and your Local Workstation:
1. Forgejo Actions (CI Secrets)
In Forgejo Actions, secrets are never stored in files. Instead, add them directly in your Forgejo repository UI:
- Navigate to: Settings -> Actions -> Secrets (in your Forgejo repository).
- Click Add Secret for each parameter:
APCA_API_KEY_ID: Your Alpaca Paper API KeyAPCA_API_SECRET_KEY: Your Alpaca Paper Secret KeyDISCORD_WEBHOOK_URL: (Optional) Discord webhook for build/test alertsFORGEJO_TOKEN: (Optional) Personal access token if needed by custom action steps
The CI workflow (.forgejo/workflows/ci.yaml) automatically maps ${{ secrets.* }} into the runner's environment variables.
2. Local Development (Your Machine)
For local testing and running scripts/forgejo_ci.py, you can provide secrets in either of two ways:
- Option A (Shell Environment Variables - Recommended):
export FORGEJO_TOKEN="your_personal_access_token" export APCA_API_KEY_ID="your_alpaca_key" export APCA_API_SECRET_KEY="your_alpaca_secret" - Option B (Local Git-Ignored
.env):cp .env.example .env # Edit .env with your credentials (never committed to git)
Tip
scripts/forgejo_ci.pyautomatically detects your Forgejo URL and repository path fromgit remote get-url origin. You only need to pass or exportFORGEJO_TOKEN!
4. Running Quality Checks
# Run linter & formatter checks
ruff check .
ruff format --check .
# Run static type checking
mypy src
# Run test suite
pytest
Command-Line Operations (trading-system)
The platform includes an interactive CLI entrypoint (trading-system or python -m trading_system.cli) for monitoring and emergency control. See docs/cli_reference.md for full documentation.
1. 24/7 Production Daemon
# Run 24/7 background daemon coordinating market hours, live streaming, risk, & execution
trading-system run
# Run with custom symbol universe or single cycle for testing
trading-system run --symbols "AAPL,MSFT,NVDA" --once
2. Pre-Flight System Diagnostics
# Run comprehensive environment, broker, and storage diagnostics
trading-system check
# Quick diagnostic check or test Discord connectivity
trading-system check --quick --ping-discord
3. Operations Dashboard & Telemetry Portal
# Launch internal web operations portal (FastAPI + Tailwind CSS + Chart.js)
trading-system dashboard --host 0.0.0.0 --port 8555
4. Account & Market Status
trading-system status
Displays real-time account NAV, liquid cash, buying power, intraday dollar/percentage P&L, market clock, active positions, and kill switch state.
5. Emergency Kill Switch
# Cancel all open/unfilled broker orders immediately
trading-system kill --reason "Manual intervention"
# Cancel all open orders AND liquidate all active stock positions
trading-system kill --flatten --reason "Emergency market liquidation"
6. Reset Kill Switch
# Disengage the emergency lock file once verified
trading-system reset-kill-switch
7. Event-Driven Backtesting
# Run swing momentum backtest on AAPL for the past 365 days
trading-system backtest --symbol AAPL --strategy swing --timeframe 1d --days 365 --show-trades
# Backtest with custom capital allocation and slippage
trading-system backtest --symbol AAPL --cash 100000 --allocation 0.25 --slippage-bps 10.0
Forgejo CI Integration
When pushing to your self-hosted Forgejo instance, Forgejo Actions automatically executes .forgejo/workflows/ci.yaml.
If a CI workflow fails, you can immediately inspect the failed step and logs locally without leaving your terminal:
# 1. Add your Forgejo details to .env or environment:
# FORGEJO_URL="https://forgejo.yourdomain.com"
# FORGEJO_REPO="owner/stock-trading"
# FORGEJO_TOKEN="your_personal_access_token"
# 2. Inspect latest CI run status:
python scripts/forgejo_ci.py --status
# 3. Fetch logs for any failed jobs:
python scripts/forgejo_ci.py --failed
Roadmap
Development is organized across nine structured phases:
- Phase 0: Architecture, Documentation & Scaffolding (Completed)
- Phase 1: Risk Architecture, Long-Term Data Storage & Safeguards Specification (Completed)
- Phase 2: Broker Integration & Execution Sandbox (Alpaca Paper) (Completed)
- Phase 3: Market Data Ingestion & DuckDB Parquet Lake (Completed)
- Phase 3.5: Operational Hardening & Real-World Safeguards (The 7 Issues) (Completed)
- Phase 4: Strategy Framework & Event-Driven Backtesting (Completed)
- Phase 5: Risk Management & Order Execution Engine (Completed)
- Phase 5.5: 24/7 Production Deployment & NAS Infrastructure Prep (Completed)
- Phase 6: 24/7 Unraid NAS Daemon Lifecycle, Automation & Production Telemetry (Completed)
- Phase 7: Internal Strategy Operations Dashboard & Telemetry Portal (Completed)
Deployment Guides:
See ROADMAP.md for detailed milestone checklists and ARCHITECTURE.md for deep technical specifications.