Skip to main content

The LLM-native trading framework. Write a prompt. Backtest it. Ship it live.

Project description

PrettyGoodTrader (pgt)

PyPI Python 3.11+ License: MIT CI Coverage Tests

The LLM-native trading framework. Write a prompt. Backtest it. Ship it live.

One codebase. Paper mode → backtest → live — no rewrite, no compromise.


What is PGT?

PGT is a production-grade Python framework that puts an LLM at the center of every trading decision. You define your strategy in plain language. The AI monitors markets, researches signals, debates its own positions, then routes orders through a risk engine before touching a broker.

It is not a signal library. It is not a wrapper around an exchange API. It is an autonomous trading brain you configure with prompts and deploy in minutes.

pip install pretty-good-trader
pgt init       # generates .env template
pgt doctor     # validates all connections
pgt run --dry-run
╭──────────────────────────────────────────────╮
│  🟢  PAPER MODE ACTIVE — no real orders      │
╰──────────────────────────────────────────────╯

[10:31:02] Monitor   AAPL  urgency=0.84  → RESEARCH triggered
[10:31:09] Research  found 3 bullish catalysts, 1 risk factor
[10:31:22] Decision  BUY 8 shares @ ~$188.40  confidence=0.91
[10:31:22] Risk      APPROVED  position=3.8% portfolio  drawdown=1.2%
[10:31:22] Paper     Order placed: AAPL BUY 8 @ market  ✓

Why PGT?

Framework LLM-native Backtest/live parity Live trading Plugin system Cost
PGT ✅ Any LiteLLM model ✅ Identical code path ✅ Multi-broker ✅ Built-in ~$5/day
Freqtrade ❌ OHLCV rules Low
TradingAgents ✅ Multi-agent ❌ Research only Varies
NautilusTrader ❌ Code strategies ✅ Rust-grade parity Low
ai-hedge-fund ✅ Agent personas ❌ No live Varies
Jesse ❌ Code strategies Low

Architecture

┌──────────────────────────────────────────────────────────────┐
│                        SCHEDULER                             │
│              (market-hours aware, async)                     │
└──────────────────────┬───────────────────────────────────────┘
                       │
          ┌────────────▼─────────────┐
          │  MONITOR  — Tier 1       │  cheap fast model (grok-3-mini-fast)
          │  "is there a signal?"    │  runs every cycle
          └────────────┬─────────────┘
                       │  urgency ≥ threshold
          ┌────────────▼─────────────┐
          │  RESEARCH — Tier 2       │  web search + BM25 reflection memory
          │  "what does the data     │  SearXNG + Firecrawl (self-hosted)
          │   actually say?"         │
          └────────────┬─────────────┘
                       │
          ┌────────────▼─────────────┐
          │  DEBATER  — optional     │  adversarial bull vs. bear debate
          │  "challenge the thesis"  │  fires on high-urgency signals
          └────────────┬─────────────┘
                       │
          ┌────────────▼─────────────┐
          │  DECISION — Tier 3       │  reasoning model (grok-4)
          │  "BUY / SELL / HOLD?"    │  structured JSON output
          └────────────┬─────────────┘
                       │
          ┌────────────▼─────────────┐
          │  RISK ENGINE — 7 checks  │  position limits · daily drawdown
          │                          │  duplicate orders · max notional
          └────────────┬─────────────┘
                       │  APPROVED
          ┌────────────▼─────────────────────────────┐
          │           BROKER ADAPTER                  │
          │  Alpaca · Kraken · CCXT (100+ exchanges)  │
          └───────────────────────────────────────────┘

Quickstart

1. Install

pip install pretty-good-trader          # core
pip install pretty-good-trader[alpaca]  # + Alpaca US equities
pip install pretty-good-trader[kraken]  # + Kraken crypto
pip install pretty-good-trader[ccxt]    # + 100+ exchanges

2. Configure

pgt init  # writes .env with inline cost annotations

Minimal .env for paper trading on Alpaca:

# LLM — any LiteLLM-compatible provider
XAI_API_KEY=your_xai_key
MONITOR_MODEL=xai/grok-3-mini-fast
RESEARCH_MODEL=xai/grok-3-fast
DECISION_MODEL=xai/grok-4

# Broker
ALPACA_API_KEY=your_alpaca_key
ALPACA_SECRET_KEY=your_alpaca_secret
ALPACA_BASE_URL=https://paper-api.alpaca.markets

# Safety
PAPER=true  # set to false only when ready for live

3. Verify

pgt doctor
✓  XAI_API_KEY        valid
✓  Alpaca connection   paper endpoint reachable
✓  SearXNG            http://localhost:8080 OK
✓  SQLite logger       data/pgt.db writable
✓  Risk engine         7/7 checks loaded
All systems go.

4. Run

pgt run --dry-run    # safe — no orders, full AI pipeline
pgt run              # paper mode (PAPER=true)
pgt run --confirm-live  # live mode gate (10s countdown)

Backtest

Same prompt, same pipeline, simulated data:

pgt backtest run --start 2024-01-01 --end 2024-12-31 --plot
  PGT Backtest — 2024  (grok-4 · Alpaca US equities)
  ════════════════════════════════════════════════════
  Sharpe ratio   1.84      Win rate    61.3%
  Total return  +31.2%     Max DD      -8.4%
  Avg trade      +0.9%     Trades         87

  Equity curve
  120 ┤                                          ╭──╮
  115 ┤                              ╭──╮       ╭╯  ╰─
  110 ┤                   ╭──╮      ╭╯  ╰──╮   ╭╯
  105 ┤         ╭──╮     ╭╯  ╰─────╯       ╰───╯
  100 ┤─────────╯  ╰─────╯
       Jan      Mar       Jun        Sep        Dec

Compare models in parallel:

pgt backtest run --compare --models xai/grok-4,claude/claude-opus-4-6,openai/gpt-4o
  ┌──────────────────┬────────┬──────────┬───────────┬────────┐
  │ Model            │ Sharpe │ Return   │ Win rate  │ Trades │
  ├──────────────────┼────────┼──────────┼───────────┼────────┤
  │ grok-4           │   1.84 │  +31.2%  │   61.3%   │     87 │
  │ claude-opus-4-6  │   1.61 │  +26.8%  │   58.7%   │     94 │
  │ gpt-4o           │   1.43 │  +22.1%  │   55.2%   │    102 │
  └──────────────────┴────────┴──────────┴───────────┴────────┘

Supported Brokers & Exchanges

Connector Asset classes Status
Alpaca US equities, ETFs Stable
Kraken Crypto spot · xStocks (tokenized equities) Stable
Binance Spot · Perpetuals Stable (via CCXT)
Bybit Spot · Perpetuals · Inverse Stable (via CCXT)
OKX Spot · Futures · Options Stable (via CCXT)
Hyperliquid Perpetuals Stable (via CCXT)
Gate.io Spot · Futures Stable (via CCXT)
+ 100 others Via CCXT
PaperEngine Any of the above Stable

Plugin Ecosystem

from pgt import TradingEngine
from pgt.plugins import TelegramPlugin, PrometheusPlugin

engine = TradingEngine(
    plugins=[
        TelegramPlugin(token="...", chat_id="..."),
        PrometheusPlugin(port=9090),
    ]
)
Plugin What it does
TelegramPlugin Trade alerts, signals, daily P&L summaries — with chat_id whitelist
DiscordPlugin Same via Discord webhook
PrometheusPlugin /metrics on port 9090 — importable Grafana dashboard included
Custom Subclass PGTPlugin ABC — 5 hooks, no-op defaults

Cost-Optimized AI Pipeline

PGT runs a 3-tier model strategy proven in production:

Tier Model Runs on Typical cost
Monitor grok-3-mini-fast Every cycle ~$0.002
Research grok-3-fast On signal only ~$0.04
Decision grok-4 (reasoning) On signal only ~$0.15

At 48 cycles/day (every 30 min, market hours), base cost is < $5/day. Models are swappable per tier via env vars — use Claude, GPT-4o, or local Ollama with no code changes.


Memory & Learning

PGT learns from every trade without retraining:

  • ReflectionMemory — stores trade outcomes as text, retrieves relevant lessons via BM25Plus at research time. Zero API cost, fully offline.
  • SessionMemory — cooldown tracking and recent order deduplication, persisted across restarts via SQLite.
  • AnnotationMemory — human-in-the-loop: annotate past cycles via pgt replay --annotate, injected into future research context.
pgt reflections --search "tech earnings miss"
# → retrieves past trade notes matching the query, highlighted

CLI Reference

pgt init                      Generate .env template
pgt doctor [--fix]            Health check (auto-repair optional)
pgt run [--dry-run]           Run AI pipeline
pgt run --confirm-live        Live trading gate (10s countdown)
pgt status [--watch]          Portfolio dashboard, auto-refreshing
pgt cost [--forecast]         API spend + 30-day projection
pgt backtest run              Run backtest
pgt backtest run --compare    Multi-model parallel comparison
pgt reflections --search      BM25 search through trade memory
pgt replay <cycle_id>         Inspect past cycle in Rich panel
pgt replay <cycle_id> --annotate  Add human annotation
pgt cycles [--cycle-id <id>]  Browse cycle log
pgt logs                      Tail SQLite log
pgt docker up/down            Manage self-hosted service stack

Self-Hosted Stack

Full infrastructure via Docker Compose:

docker compose up -d

Includes: SearXNG (private web search) · Firecrawl (page scraping) · PGT engine · Prometheus · Grafana (pre-configured dashboard) · Redis (rate limit cache)


Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pretty_good_trader-0.1.0.tar.gz (109.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pretty_good_trader-0.1.0-py3-none-any.whl (65.7 kB view details)

Uploaded Python 3

File details

Details for the file pretty_good_trader-0.1.0.tar.gz.

File metadata

  • Download URL: pretty_good_trader-0.1.0.tar.gz
  • Upload date:
  • Size: 109.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for pretty_good_trader-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ef8f533cbccf47a2f745df5cc2cc756dedc6d01fc910f975ab39576a24a643c2
MD5 1feb97c0d2cb21e40ce964ccae4e728a
BLAKE2b-256 ef9ddd53e1521b54918d7f951335de59411faf8102e95609efbfd714d942d00a

See more details on using hashes here.

File details

Details for the file pretty_good_trader-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pretty_good_trader-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7a79ac3d094f48358cd4cb995e16c4013d251c6f220c3c34e9c549eab813caec
MD5 510704be2ba36840c27972c533d5fcdf
BLAKE2b-256 8d34630fe6e8b072b608c598ace8c409fdc7b0f3a9f352f96c4ecf5be2b4a543

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page