DEV Community

qrak
qrak

Posted on

Stop Trading Like It's 1999: I Built an Autonomous, Vision-Capable Crypto Bot with Python 3.13 🚀

`How I "Vibe Coded" an asyncio-first trading engine that bridges the gap between technical indicators and human-scale market context.

In the world of algorithmic trading, we've been stuck in a loop. We rely on RSI, MACD, and Bollinger Bands—mathematical formulas designed for an era before high-frequency sentiment and global AI reasoning. While these indicators are foundational, they are blind to context.

A human trader doesn't just buy because an RSI hits 30. They look at the shape of the wedge, they read the fear in the headlines, and they interpret the "vibe" of the order book.

I wanted to build a bot that doesn't just calculate—it reasons.

Meet LLM_Trader v2: An autonomous, vision-capable trading engine that turns market data, news, and chart context into structured BUY/SELL/HOLD/UPDATE decision.

LLM Trader Dashboard
LLM_Trader v2 in action.

🏗️ The Architecture: A "Brain" for the Markets

Most AI bots fail because they simply dump raw numbers into a prompt. LLM_Trader v2 uses a sophisticated multi-stage pipeline designed for confluence:

  1. The Muscles (Market Data): Using ccxt, the bot aggregates data from 5+ major exchanges (Binance, KuCoin, Gate.io, MEXC, Hyperliquid). But it doesn't stop at price—it analyzes:

    • Technical Indicators: (Custom engine, built from scratch without pandas-ta).
    • Order book depth & spread analysis.
    • Trade flow (Buy/Sell ratio, trade velocity).
    • Funding rates for perpetual futures.
    • OHLCV across 7 timeframes: 4H, 12H, 24H, 3D, 7D, 30D, 365D.
  2. The Eyes (Vision Engine): The bot renders a ~150 candlestick chart using Plotly, optimized for AI pattern recognition. This image is sent directly to Vision models (Gemini Flash) for visual pattern analysis—because sometimes, a chart pattern is worth a thousand RSI readings.

  3. The Ears (RAG Engine): Real-time news via CryptoCompare, processed with wtpsplit for neural sentence segmentation. The bot extracts key facts and numbers, filtering noise to give the LLM a "ground truth" of current events—not just headlines, but data-rich sentences.

  4. The Brain (Model Manager): All this context—textual data, visual charts, news snippets, and market metrics—is orchestrated by a model manager that toggles between Google Gemini, Claude (via OpenRouter), or local models via LM Studio.

đź§  From "Chat" to "Execution": The PositionExtractor

(New Feature in v2)
The magic isn't just in the prompt—it's in the parsing. I built a robust PositionExtractor that doesn't just "guess" what the AI wants. It uses standardized REGEX patterns to consistently extract:

  • Action: BUY / SELL / HOLD / CLOSE
  • Confidence: HIGH / MEDIUM / LOW (mapped to position sizing)
  • Rationale: A structured explanation that is logged for future "Trading Brain" learning.

📊 What the AI Actually Sees (Real Example)

Here's a glimpse of what gets sent to the AI for a single analysis cycle:

`yaml
TRADING CONTEXT:

  • Symbol: BTC/USDC
  • Current Price: $87,499
  • Fear & Greed Index: 24 (Extreme Fear) - 7 day history

MARKET OVERVIEW:

  • Total Market Cap: $3.88T | BTC Dominance: 56.52%
  • Order Book Imbalance: +0.180 (Moderate Buy Pressure)
  • Buy/Sell Ratio: 0.16 (Strong Selling)

TECHNICAL ANALYSIS (4h):

  • RSI: 46.65 | MACD Histogram: +112.46
  • ADX: 12.86 | Stochastic: 60.02/73.78
  • Death Cross Active (20 SMA < 50 SMA)
  • TTM Squeeze: Extreme Low Volatility
  • Volume Spike: 2.55x average

WEEKLY MACRO (200W SMA):

  • Trend: Bullish (100% confidence)
  • Cycle Phase: Early Bull Market
  • Distance from 200W SMA: +46.2%

DETECTED PATTERNS:

  • MACD bull cross 9 bars ago
  • Stochastic bull cross in oversold (12 bars ago)
  • MACD Bullish Divergence (64 bars ago)
  • Volume spike 2.55x average (NOW)

NEWS CONTEXT:

  • "Bitcoin Soars Past $89,000 Milestone..."
  • "Crypto Shorts Liquidated: $64M Wiped Out..." `

The AI synthesizes all of this—plus a chart image and its previous analysis—into a structured JSON decision with confluence scoring.

đź§  Multi-Model Intelligence & Local Privacy

One of the biggest upgrades in v2 is Provider Resilience. If Google's API is down, the bot automatically falls back to OpenRouter. If you want 100% privacy, it connects to LM Studio, allowing you to run the entire reasoning layer on your own hardware.

Currently supported models:

  • Any model with Google API (Flash, Pro, 2.5, 3.0)
  • Any model (preferred vision models) via OpenRouter
  • Any local model via LM Studio

🧬 Persistent Learning: The Trading Brain

Here's where it gets interesting. LLM_Trader v2 doesn't just trade—it learns. After every closed trade, the bot analyzes its performance and distills lessons into a persistent TradingBrain:

  • Confidence Calibration: Tracks win rates by confidence level. If "HIGH confidence" trades have a 0% win rate, the AI sees this and adjusts.
  • Distilled Insights: Stores lessons like "SL too tight (1.4%) caused early exit. Consider 1.5–2% minimum in Sideways + Weak Trend + Low Vol."
  • Factor Performance: Tracks which confluence factors (volume support, trend alignment) correlate with wins.
  • Time Decay: Recent insights weighted higher (0.95 per week), so the bot adapts to changing regimes.

This feedback loop means the bot genuinely improves over time.

📡 Discord Integration (Already Live)

Real-time signals delivered straight to your Discord server:

  • Trade notifications (BUY/SELL/CLOSE with reasoning)
  • Position status updates
  • Message tracking for cleanup
  • Configurable via config.ini

⚙️ The Tech Stack

Built with an "Asyncio-First" approach in Python 3.13:

  • Language: Python 3.13 (asyncio-first)
  • Data Aggregation: ccxt (5+ exchanges)
  • Charting: Plotly + Kaleido
  • Technical Indicators: Custom engine with numpy, pandas, numba, scipy
  • NLP/Segmentation: wtpsplit (backed by torch)
  • Market Data: CoinGecko API (global metrics, dominance, DeFi)
  • Sentiment: Fear & Greed Index (7-day history) (alternative.me)
  • Persistence: JSON-based Trading Brain
  • Notifications: Discord.py

🚀 Get Started (Open Source & Beta)

The project is in BETA and configured for Paper Trading. Watch the bot make decisions without risking a dollar.

  1. Clone & Install
    bash
    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
    pip install -r requirements.txt

  2. Configure Your Keys
    Copy keys.env.example to keys.env and add your API keys (Google AI, OpenRouter, CryptoCompare, CoinGecko).

  3. Customize Your Strategy (config.ini)
    The bot is fully configurable via config/config.ini. You can switch AI providers, change timeframes, or enable/disable Discord integration without touching the code.

    `ini
    [ai_providers]

    Options: "local", "googleai", "openrouter", "all"

    provider = googleai

    Base URL for local LM Studio instance

    lm_studio_base_url = http://localhost:1234/v1
    lm_studio_model = local-model

    OpenRouter

    openrouter_base_url = https://openrouter.ai/api/v1
    openrouter_base_model = google/gemini-2.0-flash-exp:free

    Google AI Studio

    google_studio_model = gemini-3-flash-preview

    [general]
    crypto_pair = BTC/USDC
    timeframe = 4h
    candle_limit = 999
    ai_chart_candle_limit = 150
    discord_bot = false
    `

  4. Launch the Engine
    bash
    python start.py

đź’¬ Join the Community

Trading is better with friends (and more AI).

Disclaimer: This software is for educational purposes. Crypto trading involves high risk. Always paper trade first.
`

Top comments (0)