Skip to content

Repository files navigation

πŸ€– SEMANTIC SIGNAL LLM (LLM Trader)

An autonomous AI trading agent that reads charts, remembers outcomes, sharpens its strategy in real time, and can search its own codebase using vector semantics.

Python 3.13 License: MIT GitHub Stars

🌐 Public Landing Page β€” Interactive architecture overview & system showcase
πŸ“Š Live Dashboard β€” Watch the neural trading brain in action
πŸ“– Interactive Web Story & Tech | GitHub Article Document β€” Read the 9-month development story
πŸ’¬ Join the Discord


πŸ’‘ Paper trading by default. A real exchange execution service (llm_trader_executor) is currently in testing β€” it consumes this bot's decisions and places live CCXT orders. Coming soon. Stay tuned.


Quick Start

git clone https://github.com/qrak/LLM_trader.git && cd LLM_trader
python -m venv .venv && source .venv/bin/activate  # or .venv\Scripts\Activate.ps1 on Windows
pip install -r requirements.txt
cp keys.env.example keys.env  # add your API keys (DEEPSEEK_API_KEY / GOOGLE_STUDIO_API_KEY / OPENROUTER_API_KEY)
python start.py               # dashboard at http://localhost:8000
Detailed setup for Windows, Linux, macOS β†’

Platform-specific scripts live in scripts/:

Script Purpose
scripts/start_script_main.ps1 Start the bot (Windows)
scripts/start_script_main_linux.sh Start the bot (Linux)
scripts/start_script_main_macos.sh Start the bot (macOS)
scripts/run_all_tests.sh Run full test suite in .venv
scripts/query_trade_history.py CLI utility to inspect SQLite trade history
scripts/rotate_journals.py Auto-rotate AI agent journal files (runs on startup)

Runtime Controls

Key Action
a Force analysis β€” run immediate market check
d Toggle dashboard on/off
h Help β€” show available commands
q Quit β€” graceful shutdown with state preservation

System Requirements

Component Minimum Recommended
Python 3.13+ 3.14+
RAM 4 GB 8+ GB
Disk 2 GB 5+ GB (logs + trade data)
CPU 2 cores 4+ cores (Ryzen 5700G+)
GPU Not required Not required
OS Windows 10+, Linux, macOS Linux (WSL2)
Internet Required (API calls) Required

Features

  • 🧠 Brain with Memory β€” ChromaDB vector store retains trade experiences, semantic rules, system rejections, and confidence statistics. Past outcomes are retrieved by similarity to current market conditions and injected into every LLM prompt.

  • πŸ“ˆ Vision AI Chart Analysis β€” Generates 4K PNG candlestick charts with indicators, sends them to a multimodal LLM (DeepSeek V4.1 Flash) for visual pattern recognition. Chart-pattern code was dropped because the AI reads charts better than hardcoded rules.

  • πŸ”„ Reflection Engine β€” After every N closed trades, the system synthesizes best-practice rules, anti-patterns, and AI-mistake rules with surprise ratio annotation β€” high-surprise outcomes are flagged so the LLM discounts lucky/unlucky noise. Rules persist in vector memory and influence future decisions. The bot learns from its own outcomes.

  • 🧠 VectorMemoryRulesMixin β€” Semantic rule lifecycle management with decay scoring, evidence-weighted ranking, contradiction tracking, and surprise-ratio annotation. Rules are soft-ranked by similarity, evidence quality, timeframe freshness, and contradiction count β€” no hard pruning on age alone.

  • βœ… Claim Validation β€” Every LLM response is cross-checked against computed indicators. Reported trend strength is compared against actual ADX; pattern quality is replaced by a deterministic scorer. No blind trust in AI numeric claims.

  • πŸ“° RAG News Engine β€” Aggregates crypto news from free RSS feeds (CoinDesk, CoinTelegraph, Decrypt, CryptoSlate) with optional Crawl4AI enrichment, plus fundamentals from DeFiLlama and CoinGecko.

  • πŸ“Š Live Dashboard β€” FastAPI + WebSocket real-time SPA at 0.0.0.0:8000 (or semanticsignal.qrak.org). Nine tabs with brain activity, last prompt/response, position state, performance stats, news, market data, and memory bank.

  • πŸ›‘οΈ Risk Pipeline β€” Pre-execution guard chain (symbol whitelist, max position size, cooldown) + dynamic SL/TP scaling with minimum 1.5 R:R enforced. Soft exits at candle close, hard exits at configurable intervals against live ticker price.

  • πŸ”„ Multi-Provider AI Routing β€” Primary: DeepSeek V4.1 Flash (deepseek-flash, native chart vision). Fallback chain through Google Gemini / OpenRouter / LM Studio. Chart vision support on every provider that allows it.

  • πŸ§ͺ 1,380+ Tests β€” Fully mocked test suite covering LLM output corruption, async races, rate-limit backoff, vector-DB boundaries, friction-reporting, closed-loop feedback, AST code indexing, and positional market types (spot / perpetual futures).

  • πŸ€– Multi-Agent AI Development β€” Eight specialized AI agents (Supervisor 🧠 + Bolt ⚑, Palette 🎨, Sentinel πŸ›‘οΈ, Refactor ✨, Concise βœ‚οΈ, Smoke Tests πŸ”₯, Bugfixer πŸ›) coordinate via a Supervisor 🧠. Each agent writes journal entries to .ai/ β€” the project's collective memory. Journals auto-rotate on startup.


Architecture

flowchart TB
    subgraph Data["Data Sources"]
        EX["Exchanges (CCXT) β†’ OHLCV + Order Book + Trade Flow"]
        NEWS["RSS Feeds + Crawl4AI"]
        FUND["CoinGecko + DeFiLlama + Alternative.me"]
    end
    subgraph Analysis["Analysis Engine"]
        TC["Technical Calculator<br/>50+ indicators"]
        PE["Pattern Engine<br/>Deterministic indicator patterns"]
        CG["Chart Generator<br/>4K PNG with SMA/RSI/Volume"]
        RAG["RAG Engine<br/>News relevance scoring"]
    end
    subgraph Brain["🧠 Brain Layer"]
        VM["Vector Memory<br/>ChromaDB (3 collections)<br/>Experiences + Rules +<br/>Blocked Trades"]
        REFL["Reflection Engine<br/>Rules from closed trades"]
        CTX["Context Builder<br/>Similarity retrieval +<br/>surprise ratio + confidence calibration"]
    end
    subgraph Execution["Paper Execution"]
        RP["Risk Manager<br/>SL/TP, sizing, R:R,<br/>friction tracking"]
        GP["Guard Pipeline<br/>Symbol β†’ Size β†’ Cooldown"]
        STRAT["Trading Strategy<br/>ExitMonitor +<br/>PositionStatusMonitor"]
    end
    Data --> Analysis
    Analysis --> Brain
    Brain --> AI["AI Provider<br/>(DeepSeek / Gemini / OpenRouter / LM Studio)"]
    AI --> RP --> GP --> STRAT
    STRAT -.->|Closed trade feedback| Brain
    CVI -.->|Indexes source| Analysis
    CVI -.->|Indexes source| Brain
    QUERY --> CVI
Loading

Key Files

Path Role
start.py Entry point β€” 8-stage dependency injection, ChromaDB + CoinGecko cache + journal rotation
src/app.py CryptoTradingBot β€” main async loop, ticker fetch, analysis orchestration
src/trading/brain.py TradingBrainService β€” context assembly, experience recording, reflection triggers
src/trading/vector_memory.py ChromaDB interface β€” trade experiences, semantic rules, blocked trades, embedding cache
src/trading/vector_memory_rules.py VectorMemoryRulesMixin β€” semantic rule lifecycle: decay scoring, evidence ranking, surprise ratio
src/analyzer/analysis_engine.py Market analysis orchestration β€” indicators, chart, RAG, LLM call
src/managers/provider_orchestrator.py AI provider fallback chain with retry logic
src/managers/risk_manager.py Dynamic SL/TP, position sizing, friction tracking
src/managers/post_mortem_repository.py AI-written post-mortem after every closed trade
src/trading/trading_strategy.py Position lifecycle, guard enforcement, exit monitoring
src/analyzer/prompts/template_manager.py System prompt construction with falsification-based invalidation step
src/analyzer/trend_validator.py Cross-checks LLM-reported trend strength against computed ADX
src/analyzer/pattern_quality_scorer.py Deterministic pattern quality scoring replacing LLM's self-reported score
src/notifiers/notifier.py Discord notifications with message expiration tracking
scripts/rotate_journals.py Auto-rotation of AI agent journal files

Testing

# Full suite (1,380+ tests)
pytest tests/ -q

# Focused
pytest tests/test_ticker_retry.py tests/test_brain_integration.py -q

# Linting
ruff check src tests start.py
Test area Count Notes
Core trading ~500 Signals, orders, exits, risk, post-mortem
Vector memory ~180 ChromaDB operations, rules, scoring, embedding cache
Dashboard / brain router ~120 Decision pathways, admin endpoints, WS streaming
RAG / news / fundamentals ~160 RSS, Crawl4AI, news database, market data
Provider orchestration ~100 Fallback chain, retries, model pricing
Executor bridge ~60 Decision forwarding, dead letters, HTTP client

Configuration

Key settings in config/config.ini:

Setting Default Description
crypto_pair BTC/USDC Trading pair
timeframe 4h Analysis candle timeframe
provider googleai AI provider (googleai, openrouter, deepseek, lmstudio)
demo_quote_capital 10000 Simulated capital
max_position_size 0.10 Max position as fraction of capital
stop_loss_type hard hard (interval check) or soft (candle close)
stop_loss_interval_minutes 15 Hard exit check interval

Required API keys in keys.env:

Variable Required For
GOOGLE_STUDIO_API_KEY Yes Google AI Studio provider
GOOGLE_STUDIO_PAID_API_KEY If used Paid tier Google AI
OPENROUTER_API_KEY If used Secondary AI provider
DEEPSEEK_API_KEY If used DeepSeek official API provider
BOT_TOKEN_DISCORD If used Discord notifications
MAIN_CHANNEL_ID If used Discord notification channel
COINGECKO_API_KEY No Market metrics (rate limit boost)
HF_TOKEN No HuggingFace model access

Multi-Agent AI Development

The codebase uses a Supervisor + 7 specialized agents pattern for AI-assisted development:

Agent Emoji Scope Journal
Supervisor 🧠 Orchestrator β€” reads all journals, delegates to the right specialist .ai/supervisor.md
Bolt ⚑ Performance β€” caching, async patterns, I/O, numpy, hot paths .ai/journal.md
Palette 🎨 UX & Accessibility β€” dashboard HTML/CSS/JS, ARIA, responsive design .ai/palette-journal.md
Sentinel πŸ›‘οΈ Security β€” auth, CSP, rate limiting, XSS, input validation .ai/sentinel-journal.md
Refactor ✨ Clean Code β€” isinstance chains, DRY violations, DI enforcement .ai/refactor-journal.md
Concise βœ‚οΈ Code Line Reduction β€” DRY abstractions, mixins, dispatch tables .ai/concise-journal.md
Smoke Tests πŸ”₯ Fast Pre-Flight β€” syntax compilation, targeted unit tests, linter gates (< 5s) .ai/smoketest-journal.md
Bugfixer πŸ› Bugs & Regressions β€” verifying changes, running full suite .ai/bugfixing-journal.md

Journals auto-rotate on startup via scripts/rotate_journals.py. The full architecture blueprint lives in AGENTS.md.


Roadmap

πŸ”„ Live Trading β€” Real exchange order execution via llm_trader_executor β€” currently in testing

  • ⏳ Multiple Trading Agent Personalities β€” Conservative, aggressive, contrarian, trend-following strategists (aspirational)
  • ⏳ Multi-Model Consensus β€” "Council of Models" architecture for collective decision-making (aspirational)

Disclaimer

NOT FINANCIAL ADVICE. This software is experimental and in BETA. A real exchange execution service is in testing β€” use with caution. No warranty provided. Use at your own risk.

License

MIT

About

LLM-powered Crypto Trading Framework with Vision AI chart analysis, real-time Neural Engine, and a live monitoring dashboard at semanticsignal.qrak.org. Features memory-augmented reasoning and professional risk metrics.

Topics

Resources

Contributing

Stars

128 stars

Watchers

2 watching

Forks

Used by

Contributors

Languages