Status: BETA / Research Edition
Note: This is the public research branch. It is frequently experimentally updated. The stable production version runs privately.
Autonomous, asyncio-first trading bot that turns market + news + chart context into structured BUY/SELL/HOLD decisions.
๐ Live Dashboard โ Real-time view of the neural trading brain
graph TD
subgraph Data Sources
Ex["Exchanges (CCXT)"] --> |OHLCV/Trades| DC(Market Data Collector)
News[CryptoCompare] --> |Articles| RAG(RAG Engine)
Sent[Alternative.me] --> |Fear & Greed| DC
DeFi[DefiLlama] --> |TVL/Fundamentals| RAG
end
subgraph Analysis Core
DC --> |Market Data| TC[Technical Calculator]
DC --> |Price History| PA[Pattern Analyzer]
DC --> |Candles| CG[Chart Generator]
RAG --> |News Context| CB[Context Builder]
%% Orchestration / Assembly
TC --> |Indicators| PB[Prompt Builder]
PA --> |Patterns| PB
CB --> |RAG Context| PB
CG --> |Chart Image| PB
PB --> |System & User Prompt| MM{Model Manager}
end
subgraph AI Processing
%% Provider Selection Logic (Sequential / Fallback)
MM -.-> |Primary| Google["Google Gemini (Text + Vision)"]
MM -.-> |Fallback or Direct| OR["OpenRouter (Text + Vision)"]
MM -.-> |Pay-per-request| BR["BlockRun.AI (x402 Micropayments)"]
MM -.-> |Local| Local["LM Studio (Text Only)"]
Google --> |Response| ARP[Analysis Result Processor]
OR --> |Response| ARP
BR --> |Response| ARP
Local --> |Response| ARP
end
subgraph Execution ["Execution (Paper Only)"]
ARP --> |JSON Signal| TS[Trading Strategy]
TS --> |Simulated Order| DP[Data Persistence]
TS --> |Notification| DN["Notifier: Discord / Console"]
end
- ChromaDB Vector Store: All trade statistics computed on-demand from rich metadata stored in the vector databaseโno JSON files needed.
- Semantic Trade Retrieval: Past trades are retrieved based on semantic similarity to current market conditions (Trend, ADX, Volatility, RSI, MACD, Volume, Bollinger Bands, Weekend/Weekday, Fear & Greed Sentiment, Order Book Pressure).
- Key Insights Flow: Each trade stores the high-level reasoning generated by the AI at entry. When a trade closes, the system automatically retrieves the original entry reasoning to store it as a "Key Insight" in the vector memory, ensuring historical consistency even if intermediate updates occurred.
- Adaptive Thresholds: The system continuously learns optimal thresholds (ADX, R/R, confidence) from historical vector data without manual tuning.
- Performance Bucketing: Granular analysis of performance by ADX levels (LOW/MED/HIGH) and confluence factors (Trend Alignment, Momentum, Volume Support).
- Real-Time Aggregation: Statistics (confidence calibration, ADX performance, confluence factors) are computed directly from the vector store when needed, with smart caching.
- Rich Per-Trade Metadata: Each trade stores 15+ fields including RSI, ADX, ATR, SL/TP distances, R/R ratio, MAE/MFE, and confluence factor scores.
- Context-Aware AI: The AI sees: "In similar conditions (High ADX + Bullish), we won 80% of trades with avg P&L +4.2%" derived from semantic vector search.
- Temporal Awareness: Every trade stores
timestampandmarket_regimemetadata, enabling time-windowed queries like "What worked in the last Bull Run?" - Decay Engine: Recency-weighted retrieval using exponential decay (90-day half-life). Recent trades are prioritized over ancient history.
- Hybrid Scoring: Results ranked by
similarity * 0.7 + recency * 0.3for optimal context relevance. - Automated Reflection Loop: Every 10 trades, the brain automatically synthesizes patterns from recent wins/losses into persistent Semantic Rules.
- Positive Rules: Generated when at least 5 wins follow a consistent regime/ADX pattern.
- Anti-Patterns: Generated when at least 3 losses share a similar trait, flagging them as "
โ ๏ธ AVOID" patterns for future analysis.
- Self-Learning Rules: Semantic rules are stored persistently in a dedicated ChromaDB collection and injected into AI prompts to enforce learned behavior (e.g., "MANDATORY: If win rate <50%, reduce confidence").
- Multi-Provider Support:
- Google Gemini: Configurable model selection. Default:
gemini-3-flash-preview(Temp 1.0, TopK 64, Thinking Level: high). Supports Agentic Vision (code execution for precise image analysis on Flash+). - OpenRouter: Access to frontier models. Default:
google/gemini-3-flash-previewwithdeepseek/deepseek-r1:freeas fallback. - BlockRun.AI: Pay-per-request access to 28+ AI models (ChatGPT, Claude, Gemini, etc.) via x402 micropayments on the Base blockchain. No subscriptions needed. Uses a dedicated local wallet for signing โ funds never leave your machine.
- LM Studio: Local LLM support via
lm_studio_base_urlfor fully offline inference.
- Google Gemini: Configurable model selection. Default:
- Fallback Logic: Automatically switches providers if the primary fails:
Google AI โ OpenRouter โ BlockRun โ Local. - Vision-Assisted Trading: Generates technical charts with indicators and sends them to vision-capable models (e.g., Gemini Flash) for visual pattern confirmation.
- News Aggregator: Requires a CryptoCompare API Key. The free tier typically offers ~150k lifetime requests, sufficient for continuous bot operation.
- Smart Relevance Scoring: Uses keyword density, category matching, and coin-specific heuristics to filter noise and prioritize data-rich content.
- Lead Paragraph Extraction: Extracts coherent lead paragraphs from articles following the "Inverted Pyramid" structure, preserving narrative flow and context.
- DefiLlama Fundamentals: Fetches TVL and on-chain fundamentals at a configurable interval (default: every 15 minutes) for DeFi context.
- Configurable Limits: Adjustable token limits, article counts, and news feed sources to manage context window and data quality.
- Multi-Exchange Aggregation: Fetches data via
ccxtfrom 5+ exchanges:- Binance, KuCoin, Gate.io, MEXC, Hyperliquid
- Comprehensive Data:
- OHLCV Candles (1m to 1w)
- Order Book Depth & Spread Analysis
- Recent Trade Flow (Buyer/Seller Pressure)
- Funding Rates (for Perpetual Futures)
- Cross-Platform Single-Instance Locking: Prevents multiple instances from running concurrently, protecting against API rate limit bans and state corruption.
- Graceful Shutdown Management: Dedicated manager handles SIGINT (Ctrl+C) and SIGTERM, ensuring all trade data is persisted before exit.
- Safety Confirmation: Optional GUI confirmation (via PyQt6) or console prompts when attempting to shut down.
- Realistic Capital Tracking: Dynamic compounding of trading capital based on realized P&L. No static initial capital assumptions.
- Advanced Performance Metrics: Real-time calculation of Sharpe Ratio, Sortino Ratio, Max Drawdown, and Profit Factor.
- Currency-Agnostic P&L: Tracks profits and losses accurately in the relevant quote currency (e.g., USDC, ETH, BTC).
- Vision-Assisted Trading: Generates technical charts with indicators and sends them to vision-capable models (e.g., Gemini Flash) for visual pattern confirmation.
- Weekend Awareness: Automatic detection of weekend trading with explicit warnings about lower volume/liquidity and manipulation risks.
- Brain Visualization: Interactive network graph showing trade sequences (BUY โ UPDATE โ CLOSE) using Vis.js with physics-based layout and automatic stabilization.
- Performance Chart: Equity curve with zoom/pan controls, trade markers (BUY/CLOSE annotations), and ApexCharts integration.
- Live Statistics: Real-time stats display (Win Rate, P&L%, Capital, Trades) pulled from trading history.
- Vector Memory Database: Full ChromaDB visualization with sortable columns (Date, Similarity, P&L, Confidence, Outcome), experience table, and win rate breakdowns.
- Thought Stream: View last AI prompt and response with markdown rendering and copy-to-clipboard.
- Visual Cortex: Displays generated technical charts with lightbox for full-screen viewing.
- Neural State Panel: Shows current trend sentiment, confidence level, and recommended action.
- Position Details: Real-time position monitoring with entry price, duration, P&L gauges, and confluence factors.
- Interactive Panel System:
- Fullscreen Mode: Expand any panel to fullscreen with proper chart/network resizing.
- Collapsible Panels: Minimize panels to save screen space with responsive sibling expansion.
- WebSocket Real-Time Updates: Live connection status indicator and auto-reconnection.
- Local LLM Support (LM Studio Integrated)
- Vision Analysis (Chart Image Generation & Processing)
- RAG News Relevance Scoring
- Vector Memory System (ChromaDB + Semantic Search)
- Discord Integration (Real-time signals, positions, and performance stats)
- Interactive CLI (Hotkeys for manual control)
- Web Dashboard: Real-time visualization of synaptic pathways and neural state.
- BlockRun.AI Integration: Pay-per-request AI access via x402 micropayments.
- DefiLlama Fundamentals: On-chain TVL context in the RAG pipeline.
- Multiple Trading Agent Personalities: Diverse strategist personalities (conservative, aggressive, contrarian, trend-following) that engage in cross-agent reasoning to refine market entry/exit precision.
- Multi-Model Consensus Decision-Making: A "Council of Models" architecture where specialized agentsโVisual Cortex Analyst (chart vision), Technical Specialist (indicators), Sentiment Scout (news/macro), and Memory Historian (vector experiences)โcollaborate to reach a final consensus signal.
- Live Trading: Execution Layer integration for verified order placement.
- Concurrent Multi-Asset Analysis: Scaling the engine to analyze 10+ coins simultaneously, leveraging parallel LLM execution for broad market coverage.
- Python 3.13+
- LM Studio (Optional โ for local offline inference)
# Clone repo
git clone https://github.com/qrak/LLM_trader.git
cd LLM_trader
# Setup Virtual Environment
python -m venv .venv
.venv\Scripts\Activate.ps1
# Install Dependencies
pip install -r requirements.txt
# For development (linting, testing tools)
pip install -r requirements-dev.txtStep 1 โ API Keys: Copy keys.env.example to keys.env and fill in your credentials.
# Required: At least one AI provider
OPENROUTER_API_KEY=your_key_here
GOOGLE_STUDIO_API_KEY=your_key_here # Free tier
GOOGLE_STUDIO_PAID_API_KEY=your_key_here # Paid tier (higher rate limits)
# Optional but Recommended
CRYPTOCOMPARE_API_KEY=your_key_here # ~150k lifetime free requests
COINGECKO_API_KEY=your_key_here # Free Demo key: ~30 req/min vs ~10 public
# BlockRun.AI (x402 micropayments โ Base chain wallet private key)
# WARNING: Use a dedicated wallet with minimal funds only.
# BLOCKRUN_WALLET_KEY=0x0000...Step 2 โ Bot Config: Copy config/config.ini.example to config/config.ini. The defaults are ready to run, but key sections are explained below.
[ai_providers]
# Options: "local", "googleai", "openrouter", "blockrun", "all"
# "all" enables automatic fallback: Google โ OpenRouter โ BlockRun โ Local
provider = googleai
google_studio_model = gemini-3-flash-preview
openrouter_base_model = google/gemini-3-flash-preview
openrouter_fallback_model = deepseek/deepseek-r1:free
blockrun_model = deepseek/deepseek-reasoner
lm_studio_base_url = http://localhost:1234/v1
[general]
crypto_pair = BTC/USDC
timeframe = 4h
[model_config]
# Critical for Gemini 3 Flash Preview
google_temperature = 1.0
google_thinking_level = high # minimal | low | medium | high
google_code_execution = false # Agentic Vision (Flash+ only, Google API only)
[dashboard]
host = 0.0.0.0 # Use 127.0.0.1 for local-only access
port = 8000
enable_cors = false
[demo_trading]
demo_quote_capital = 10000 # Simulated starting capital
transaction_fee_percent = 0.00075 # 0.075% limit order fee๐ก See
config/config.ini.examplefor the full reference โ it documents every setting including[rag],[exchanges],[cooldowns], and[debug]sections.
python start.py # Reads all settings from config/config.ini| Key | Action |
|---|---|
a |
Force Analysis: Run immediate market check |
h |
Help: Show available commands |
q |
Quit: Gracefully shutdown the bot |
The dashboard will be available at http://localhost:8000 (or the host/port configured in config.ini).
- Discord: Join our community for live signals, development chat, and support.
- GitHub Issues: Report bugs or suggest new features.
EDUCATIONAL USE ONLY. This software is currently in BETA and configured for PAPER TRADING. No real financial transactions are executed. The authors are not responsible for any financial decisions made based on this software.
- Vicky (1bcMax): Implementation of BlockRun.AI provider and x402 payment integration.
Licensed under the PolyForm Noncommercial License 1.0.0. See LICENSE.md for details.







