No description
  • Python 75.7%
  • HTML 23.9%
  • Dockerfile 0.3%
  • Shell 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
John Parkhurst 9fcf22c865
All checks were successful
CI Pipeline / Lint, Type Check & Test (push) Successful in 1m39s
Error Fix
2026-11-13 01:09:33 -05:00
.forgejo/workflows fix(ci): use HTTP POST for Coolify automated deploy webhook 2026-10-29 17:52:46 -04:00
docs feat(config): add TRADING_SYMBOLS environment variable to configure active universe 2026-10-29 18:19:18 -04:00
scripts feat(phase-2): alpaca broker client, iron gate settings, kill switch, and CLI 2026-10-26 17:25:08 -04:00
src/trading_system Error Fix 2026-11-13 01:09:33 -05:00
tests Error Fix 2026-11-13 01:09:33 -05:00
.env.example feat(config): add TRADING_SYMBOLS environment variable to configure active universe 2026-10-29 18:19:18 -04:00
.gitignore feat(data): implement Phase 3 market data lake, DuckDB catalog, and ingestion adapters 2026-10-27 17:58:29 -04:00
AGENTS.md feat: phase 0 scaffoliding, architecture, and paramerizing forgejo CI 2026-10-25 14:55:10 -04:00
ARCHITECTURE.md feat(risk,execution): implement Phase 5 RiskManager, PortfolioTracker shadow ledger, and OrderRouter 2026-10-27 19:56:33 -04:00
docker-compose.coolify.yaml fix(killswitch): resolve directory mount lock collision and improve dashboard error handling 2026-10-30 14:28:55 -04:00
docker-compose.yaml fix(config): sanitize TRADING_SYMBOLS and fix container volume permissions 2026-10-30 14:54:29 -04:00
docker-entrypoint.sh fix(orchestrator): add cold-start auto-warmup, broker fill sync, and timeframe alignment 2026-10-31 20:58:19 -04:00
Dockerfile perf: reduce off-hours CPU and RAM footprint across container and web portal 2026-11-05 00:26:24 -05:00
HANDOFF.md docs: update roadmap and handoff guide with cold-start warmup and 137 test count 2026-10-31 21:00:06 -04:00
MANIFEST.in fix(dashboard): package HTML templates and add container runtime fallback paths 2026-10-29 17:45:01 -04:00
pyproject.toml fix(dashboard): package HTML templates and add container runtime fallback paths 2026-10-29 17:45:01 -04:00
README.md docs: test automated CI deployment webhook 2026-10-29 17:50:17 -04:00
renovate.json Add renovate.json 2026-11-08 00:17:14 +00:00
ROADMAP.md feat(journal): add full pagination backfill and automated fill reconciler 2026-11-03 17:50:43 -05:00

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.md for 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), yfinance for deep historical daily backfills, and an embedded DuckDB + 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:

  1. Navigate to: Settings -> Actions -> Secrets (in your Forgejo repository).
  2. Click Add Secret for each parameter:
    • APCA_API_KEY_ID: Your Alpaca Paper API Key
    • APCA_API_SECRET_KEY: Your Alpaca Paper Secret Key
    • DISCORD_WEBHOOK_URL: (Optional) Discord webhook for build/test alerts
    • FORGEJO_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.py automatically detects your Forgejo URL and repository path from git remote get-url origin. You only need to pass or export FORGEJO_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.