Skip to content

tonimaxx/build-wealth-with-code

Repository files navigation

Build Wealth with Code

Automated trading systems for developers — stock, options, and crypto.

Companion code for the O'Reilly-style book Build Wealth with Code by Toni Maxx. Every code excerpt in the book is a slice of a file in this repository — clone it, run it, extend it.

Status — v1.0. Paper-only by default. Stock momentum is the only strategy with live order routing wired today. Live routing for covered calls, CSPs, iron condors, and the multi-strategy executor ships in v1.2 (see Roadmap). Phase 8 Node.js bot is deferred to v1.4 and may be dropped if nobody asks for it.


Badges

Python 3.12+ License: MIT CI Tests Coverage Code style: black Lint: ruff pre-commit

Alpaca ccxt Anthropic TradingView Streamlit Postgres Redis Flask


Why this exists

Most "trading bot" repos are toys, abandoned, or hidden behind paywalls. This one ships a real, opinionated, paper-first system that maps 1:1 to the book's chapters. Every numeric threshold has a pydantic validator. Every order has an idempotent UUID. The kill switch is a single file you can touch from your phone over SSH.

Positioning is narrow on purpose. This is not an HFT framework, not a research notebook, not a backtest playground — it's the production-shaped reference architecture a working developer can clone, run on their laptop today, and graduate to a small VPS tomorrow.


Architecture

flowchart LR
    subgraph Sources[Data sources]
      A1[Alpaca]
      A2[Tradier]
      A3[ccxt exchanges]
      A4[yfinance]
    end
    subgraph Strategy[Strategy layer]
      S1[Screeners / Scanners]
      S2[Executors]
    end
    subgraph Routing[Risk + routing]
      R1[Rationale gate<br/>Claude]
      R2[Idempotent<br/>order router]
      R3[Kill switch<br/>file probe]
    end
    B[Broker / Exchange]
    DB[(Postgres + Redis)]
    UI[Streamlit dashboard]
    TV[TradingView alert] -.-> WH[Flask webhook]
    Sources --> S1 --> S2 --> R1 --> R2
    R3 --> R2
    WH --> R2
    R2 --> B
    R2 --> DB
    DB --> UI
Loading
flowchart LR
    P[paper] --> A[advisory<br/>AI logs only]
    A --> E[enforcing<br/>AI can block]
    E --> L[live]
    classDef barrier fill:#fee,stroke:#c33,color:#000
    P -.->|barrier 1: edit .env<br/>BWC_MODE=live| L
    P -.->|barrier 2: --confirm-live flag| L
    P -.->|barrier 3: kill switch armed| L
Loading

Quickstart

Three minutes from a fresh clone to a screener producing real signals on real market data — no broker credentials required.

git clone https://github.com/tonimaxx/build-wealth-with-code
cd build-wealth-with-code
uv sync --all-extras
uv run python quickstart/01_first_screener.py

Expected output (numbers vary by trading day):

Build Wealth with Code — Quickstart 01
Scanning 30 large-cap U.S. stocks for momentum signals...
Source: yfinance daily bars (no credentials needed)

       Momentum candidates (4)
┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┓
┃ Symbol ┃   Close ┃ RSI(14) ┃ Vol ratio ┃ $Volume  ┃
┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━┩
│ NVDA   │ $145.32 │    71.4 │     1.83x │ $24,118M │
│ AVGO   │ $1762.0 │    68.9 │     1.52x │  $7,201M │
└────────┴─────────┴─────────┴───────────┴──────────┘

✓ Screener ran end-to-end on real market data.

An empty table is a valid outcome — momentum is rare in chop. For the credentialed path (Alpaca paper, Postgres, Tradier chains, crypto exchanges), see docs/SETUP.md.


What's in here

build-wealth-with-code/
├── bwc/                    # Shared package: config, db, kill switch, retry, notifications
│   ├── brokers/alpaca.py   # Paper-only TradingClient wrapper
│   └── data/               # Tradier options chain fetcher (with offline fixture fallback)
├── strategies/
│   ├── infrastructure/     # Backtest, walk-forward, Monte Carlo, paper executor, Greeks
│   ├── stock/              # Momentum + mean reversion        — Ch 4–5
│   ├── options/            # Pricer, IV, POP, CC/CSP/IC       — Ch 2, 6, 7, 13
│   └── crypto/             # Momentum, grid, DCA, arbitrage   — Ch 8–9
├── bots/
│   ├── python_bot/         # CLI executor + order router      — Ch 12
│   ├── pinescript/         # TradingView Pine v5 strategies   — Ch 11
│   ├── webhook_listener/   # Flask + Redis webhook bridge     — Ch 11
│   ├── dashboard/          # Streamlit monitoring (5 tabs)    — Ch 10
│   └── nodejs_bot/         # ⬜ Deferred to v1.4
├── db/                     # Postgres schema + migrations
├── tools/                  # Daily review, attribution, sensitivity, tax export
├── deploy/                 # systemd units, nginx, Healthchecks.io
├── tests/                  # 434 tests, mirrors strategies layout
├── quickstart/             # 30-day plan day-1 examples       — Ch 15
└── docs/                   # SETUP, BROKER_SETUP_ALPACA, CRYPTO_SETUP, DEPLOYMENT, TROUBLESHOOTING

Strategies shipped

# Strategy Chapter Status Path
1 Stock momentum 4 ✅ screener + executor + bot wired strategies/stock/momentum_*.py
2 Stock mean reversion 5 🟡 scanner only, no executor strategies/stock/mean_reversion_scanner.py
3 Covered call 6 🟡 scanner shipped; live routing pending strategies/options/covered_call_scanner.py
4 Cash-secured put 6 🟡 scanner shipped; live routing pending strategies/options/csp_scanner.py
5 Iron condor 6 🟡 builder shipped; live routing pending strategies/options/iron_condor_builder.py
6 Multi-strategy portfolio 7 ⬜ executor + position_manager pending (v1.2/v1.3) bots/python_bot/
7 Crypto momentum 9 ✅ shipped strategies/crypto/momentum_scanner.py
8 Grid 9 ✅ shipped strategies/crypto/grid_trader.py
9 DCA 9 ✅ shipped strategies/crypto/dca_bot.py
10 Arbitrage 9 ✅ paper-only shipped strategies/crypto/arbitrage_bot.py
11 Options volatility 13 ⬜ math ready, strategy modules pending (v1.3) strategies/options/

⚠️ Safety architecture

  • Paper-only default. BWC_MODE=paper blocks every live order at the config layer.
  • Three barriers to go live. Edit .env to BWC_MODE=live, pass --confirm-live on the CLI, and arm the kill switch.
  • Kill switch. touch /tmp/BWC_HALT (configurable). Checked before every order placement.
  • Idempotent order IDs. Every order carries a UUID client_order_id; retries never duplicate.
  • Rationale gate (optional). Claude as a strict risk officer for live trades above a notional threshold. Off by default. Three modes: disabled / advisory / enforcing. Fail-safe defaults to flag, never approve — network down ≠ trade approved.
  • Pydantic validators on every numeric config field. Bad config fails on import, not at runtime.
  • Pre-commit gitleaks scans for accidentally committed secrets.

Stack

Layer Tools
Language Python 3.12 · TypeScript (Node bot, deferred)
Package manager uv (Python) · pnpm (Node, deferred)
Market data alpaca-py · ccxt · yfinance · Tradier (options chains)
Storage Postgres 16 · Redis 7
Compute / UI Streamlit · Flask · gunicorn
AI guardrail Anthropic Claude Haiku 4.5 (default; overridable)
Strategy DSL TradingView Pine Script v5
Math py-vollib · scipy · pandas-ta · vectorbt
Infra systemd · nginx · Healthchecks.io
Dev ruff · black · pytest · mypy · pre-commit · gitleaks

🧭 Roadmap

Trigger-driven, not date-driven. Full detail in docs/ROADMAP.md (Section 0).

Version Trigger to start Scope
v1.1 After first 5 readers actually run the code Reactive bug-fix · real fixtures replace synthetic · doc clarifications. ~1–2 days.
v1.2 After stock momentum runs paper 30 days without surprises Live order routing for CC/CSP/IC · roll_engine · position_manager · mean_reversion_executor · trailing_stop · regime_detector. ~1 week.
v1.3 Once the basic loop has proven itself Bot polish: streaming · multi-strategy registry · circuit breaker · correlation monitor · attribution · options vol screeners (high/low IV, calendar, VIX sizer). ~3–5 days.
v1.4 Only if a reader actually asks for Node.js Phase 8 Node.js crypto bot. Killed from plan if no demand within 3 months.
v2 ≥3 of 5 trigger conditions met (see v2-backlog.md) AI-native rewrite. Earliest 6 months out.

📚 Documentation

Doc Purpose
docs/SETUP.md Full setup walkthrough, including optional Anthropic gate
docs/BROKER_SETUP_ALPACA.md Alpaca paper account creation
docs/CRYPTO_SETUP.md Coinbase, Kraken, Binance.US setup
docs/DEPLOYMENT.md VPS deployment with systemd + nginx + Healthchecks
docs/TROUBLESHOOTING.md Common errors and fixes

Companion book: Build Wealth with Code by Toni Maxx.


🧪 Project numbers

  • 434 / 434 tests passing
  • 87 % coverage on target areas (10 files at 100 %)
  • 11 strategies documented in the book
  • 152 tracked files
  • Pre-commit drift checker keeps docs/ROADMAP.md ↔ code in sync

Contributing

  • Issues welcome — bug reports, feature requests, and "I tried to run this and..." reports all help.
  • PRs welcome on the v1.1+ punch list (see PLAN Section 0).
  • Discussion: GitHub Discussions on the repo.

License

MIT. Attribution preferred.


About the author

Toni Maxx — 40+ years in technology. Author of Build Wealth with Code. GitHub: @tonimaxx.


Disclaimer

Educational software. Not investment advice. Trading involves risk of loss, including total loss of capital. Paper-trade for at least 30 days before any live capital. Past backtest performance does not predict future results. See the book's Appendix C and the LICENSE file for the full statement.

About

Companion code for the book Build Wealth with Code. Automated trading systems for developers — stock, options, crypto. Paper-only by default.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages