Event-driven algorithmic trading system that turns market data into decisions and orders using behavioral signals, configurable risk controls, and pluggable policies (rules-based or LLM-driven). The system can run in a single cycle for ad‑hoc evaluation or as a scheduler loop for continuous operation.
- Behavioral signals from price/volume history
- News & sentiment analysis with lexicon-based scoring
- Calendar-aware trading with earnings/Fed/holiday blackouts
- Risk gate with position sizing and exposure limits
- Paper and live trading support (Alpaca + simulator broker)
- Policy layer: TradingAgents engine, rules-based, or LLM-backed decisions
- Order execution with optional limit orders and cooldowns
- Decision + order logging to a local SQLite database
.
├── README.md
├── config.yaml
├── .env.example
├── pyproject.toml
├── src
│ ├── main.py
│ ├── scheduler.py
│ ├── agent
│ │ └── policy.py
│ ├── data
│ │ ├── market_data.py
│ │ ├── news_data.py # News fetching (Alpha Vantage + RSS)
│ │ └── calendar_data.py # Earnings/Fed/holiday calendar
│ ├── execution
│ │ ├── alpaca_broker.py
│ │ ├── broker_interface.py
│ │ └── simulator_broker.py
│ ├── features
│ │ ├── behavioral_features.py
│ │ └── sentiment.py # Lexicon-based sentiment scoring
│ ├── observability
│ │ └── logging.py
│ ├── risk
│ │ ├── position_sizing.py
│ │ └── risk_gate.py
│ └── storage
│ ├── db.py
│ └── models.py
├── tests
│ ├── test_position_sizing.py
│ ├── test_risk_gate.py
│ ├── test_sentiment.py # Sentiment analysis tests
│ └── test_calendar.py # Calendar blackout tests
├── tools
│ ├── smoke.py
│ └── audit.py # System wiring audit
└── TradingAgents
└── ...
- Python 3.11+
uvorpip
git clone <your-repo-url>
cd GPTtradeInstall dependencies:
uv sync
# or
pip install -e .Copy environment template:
cp .env.example .envKey knobs you can tune:
trading_mode:paperorlive(execution mode selector).ENABLE_LIVE_TRADING: hard safety switch for live orders.symbols: list of tickers to trade.decision_interval_minutes: cadence for scheduler loop.lookback_days: (optional) OHLCV history window used for features.max_position_pct: max equity per position (fraction).max_gross_exposure_pct: cap on total exposure (fraction).max_daily_loss_pct: daily loss stop (fraction).max_trades_per_day: throttle for order count.cooldown_minutes: minimum wait between trades per symbol.cost_buffer: slippage/fee buffer used in sizing/validation.policy_type:tradingagents,rules, orllm.llm.model,llm.endpoint,llm.temperature: LLM policy settings.news_enabled: include news features when enabled.use_limit_orders: toggle market vs limit orders.limit_order_offset: percent offset from mid/last for limit orders.stale_order_timeout_seconds: cancel orders past this age.enable_shorts,enable_leverage: additional risk toggles.logging.*: log level, outputs, rotation settings.
Environment variables in .env can override sensitive items (API keys, live-trading token, etc.).
Single cycle:
python -m main --onceScheduler loop:
python -m mainDry run (no orders submitted):
python -m main --dry-runcd src && PYTHONPATH=. pytest ../tests -v| Test File | Description |
|---|---|
test_integration.py |
Full cycle integration with rules/LLM policies, SQLite persistence, correlation IDs |
test_scheduler_autonomy.py |
Scheduler iteration control, graceful shutdown, dry-run mode |
test_no_prompting.py |
Enforces no input() calls, static source scan for interactive patterns |
test_offline.py |
Runs with network blocked, verifies LLM fallback works offline |
test_risk_gate.py |
Risk constraint unit tests (PDT, position limits, kill switch) |
test_position_sizing.py |
Signal-based sizing, short blocking, max position constraints |
Quick verification that the system runs end-to-end in simulator mode:
cd src && python ../tools/smoke.py
# Verbose mode:
cd src && python ../tools/smoke.py --verboseGitHub Actions workflow runs on push/PR:
- Installs dependencies
- Runs full pytest suite
- Runs smoke test
- Autonomous: No human input required - tests fail if
input()is called - Offline: Simulator tests work without network/API keys
- Deterministic: Seeded random generators for reproducible results
- Isolated: Temporary SQLite databases per test
- Live trading is blocked unless
ENABLE_LIVE_TRADING=trueand a validLIVE_TRADING_CONFIRMATION_TOKENis provided in.env. - Use paper trading by default and verify positions, limits, and order behavior before enabling live trading.
- Review
max_daily_loss_pct, exposure limits, andmax_trades_per_daybefore going live.
Scheduler/CLI
│
▼
TradingSystem (main loop)
│
├─ MarketData (Alpaca/Yahoo)
├─ BehavioralFeatureCalculator
├─ Policy (Rules or LLM)
├─ RiskGate + PositionSizer
├─ Broker (Simulator or Alpaca)
└─ Storage (SQLite)
At each cycle, the system pulls market data, computes behavioral features, makes policy decisions, applies risk gates and sizing, then submits or simulates orders and persists decisions and executions.
The system supports two LLM providers for the AI-based trading policy:
# config.yaml
llm_provider: 'openai'
llm_model: 'gpt-4o-mini'Set OPENAI_API_KEY in your environment.
# config.yaml
llm_provider: 'gemini'
llm_model: 'gemini-2.0-flash'Set GEMINI_API_KEY in your environment.
Note: If no API key is set, the system falls back to the rules-based policy.
TradingAgents is a sophisticated multi-agent framework that can be used as the primary decision engine. When enabled, it orchestrates multiple specialized agents (market analysts, researchers, risk managers) in a debate-style architecture to reach trading decisions.
-
TradingAgents is included in the repository at
./TradingAgents/. No additional cloning required. -
Install TradingAgents dependencies:
pip install -r TradingAgents/requirements.txt- Configure in config.yaml:
policy_type: 'tradingagents'
llm_provider: 'openai' # or 'google' or 'anthropic'
llm_model: 'gpt-4o-mini'
tradingagents_max_debate_rounds: 1 # optional- Market Analyst: Analyzes price data and technical indicators
- News Analyst: Processes news and sentiment
- Fundamentals Analyst: Reviews financial statements
- Social Media Analyst: Monitors social sentiment
- Bull/Bear Researchers: Debate investment thesis
- Risk Manager: Evaluates risk/reward
- Trader: Makes final decision after debate
TradingAgents is a REQUIRED dependency when policy_type: tradingagents. The system will:
- Verify TradingAgents is available at startup
- Refuse to start if TradingAgents cannot be loaded
- No silent fallback to rules-based policy
Run the inspection tool to verify your TradingAgents setup:
python tools/inspect_tradingagents.py| Issue | Solution |
|---|---|
TradingAgentsNotFoundError |
Ensure TradingAgents folder exists in project root |
| Import errors | Run pip install -r TradingAgents/requirements.txt |
| LLM errors | Verify OPENAI_API_KEY or GEMINI_API_KEY is set |
A local FastAPI server provides read-only monitoring endpoints.
# config.yaml
enable_web: true
web_host: '127.0.0.1'
web_port: 8000- GET /health - Health check
- GET /status - Current system status
- GET /decisions - Recent trading decisions
- GET /orders - Recent orders
- GET /positions - Current positions
- GET /logs/recent - Recent log entries
curl http://127.0.0.1:8000/health
curl http://127.0.0.1:8000/statusGet real-time alerts via Discord webhook.
- Create a Discord webhook in your server
- Configure in config.yaml or environment:
enable_discord: true
discord_webhook_url: 'https://discord.com/api/webhooks/...'Or set DISCORD_WEBHOOK_URL env var.
- Trade signals submitted
- Orders filled
- Risk gate blocks
- Kill switch triggered
- Large price moves (configurable threshold)
notify_on_trade: true
notify_on_risk_blocks: true
notify_on_large_move: true
large_move_threshold_pct: 3.0
notify_on_kill_switch: trueThe system integrates news headlines into trading decisions using a deterministic lexicon-based sentiment scorer.
- News Fetching: Headlines are fetched via Alpha Vantage API (if key provided) or RSS feeds (fallback)
- Sentiment Scoring: Each headline is scored using a financial lexicon (~60 positive, ~60 negative terms)
- Feature Generation: Sentiment features are computed and passed to the policy
- Decision Integration: The RulesPolicy amplifies/dampens signals based on sentiment alignment
| Feature | Description |
|---|---|
sentiment_score |
-1.0 to 1.0 aggregate sentiment from headlines |
news_volume |
Normalized count of recent headlines (0-1) |
major_news_flag |
1.0 if high volume or strong sentiment |
news_weight |
Position sizing multiplier (0.5-1.5) |
# config.yaml
news_enabled: true
alpha_vantage_api_key: 'your-key' # Optional, uses RSS if not setOr set ALPHA_VANTAGE_API_KEY in your .env file.
- Aligned sentiment: If trend and sentiment agree, signal strength is amplified by up to 50%
- Conflicting sentiment: If trend and sentiment disagree, signal is dampened by 50%
- Major news: Confidence is adjusted when major news is present
The system tracks earnings dates, Fed meetings, and market holidays to avoid trading during high-uncertainty periods.
| Event Type | Behavior |
|---|---|
| Earnings | Configurable window (default: 2 days before, 1 day after) |
| Fed Meeting Days | Full trading day of FOMC announcements |
| Market Holidays | US market holidays (system won't trade) |
During blackouts, the risk gate enforces "reduce-only" mode by default:
- New positions are blocked
- Reducing/closing existing positions is allowed
- Set
blackout_reduce_only: falsein config to block all trades
# config.yaml
earnings_blackout_days_before: 2
earnings_blackout_days_after: 1
blackout_reduce_only: true
# Manual earnings dates (optional)
earnings_dates:
AAPL: ['2025-01-30', '2025-04-24']
MSFT: ['2025-01-28', '2025-04-22']- Fed Meetings: 2024-2026 FOMC announcement dates pre-loaded
- Holidays: US market holidays 2024-2026 pre-loaded
Verify that all components are properly wired:
uv run python tools/audit.pyThis checks:
- All modules import correctly
- Sentiment features are computed
- Calendar flags are generated
- Risk gate handles blackouts
- Main.py has all components wired