自主AI交易系统

QuantAgent是一个基于Claude AI的自主加密货币交易系统,通过6小时迭代反馈循环持续研究和优化交易策略,在Revolut X交易所进行交易。

  • by NawafSheikh
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 greenm8rix/QuantAgent-Claude-Revolutx-MCP

使用说明

QuantAgent-自主AI交易系统

由Claude AI支持的自我改进的自主交易代理

特性 • 系统流程 • 建筑 • 设置 • 用法 • 策略


概述

QuantAgent是一个自主的加密货币交易系统,它使用Claude AI不断研究、开发、测试和优化交易策略。它交易 革命X 通过6小时的迭代反馈循环,交流和自我提高。

┌─────────────────────────────────────────────────────────────────────────────┐
│                         QUANT AGENT SYSTEM FLOW                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   1. STARTUP                    2. CHECK STRATEGIES                         │
│   ┌──────────────┐              ┌──────────────────┐                        │
│   │  index.ts    │─────────────▶│ winners.json     │                        │
│   │  main()      │              │ has strategies?  │                        │
│   └──────────────┘              └────────┬─────────┘                        │
│                                     NO   │   YES                            │
│                                 ┌────────┴────────┐                         │
│                                 ▼                 ▼                         │
│   3. ITERATION              ┌──────────────────────────┐                    │
│   ┌──────────────┐          │  4. START EXECUTOR       │                    │
│   │ Spawn Claude │          │  ┌────────────────────┐  │                    │
│   │ - Analyze    │          │  │ Load winners.json  │  │                    │
│   │ - Research   │─────────▶│  │ Start trading loop │  │                    │
│   │ - Create     │          │  │ Check exits/entries│  │                    │
│   │ - Test       │          │  └────────────────────┘  │                    │
│   │ - Register   │          └──────────────────────────┘                    │
│   └──────────────┘                      │                                   │
│         ▲                               │                                   │
│         │         5. MAIN LOOP          ▼                                   │
│         │         ┌─────────────────────────────────┐                       │
│         │         │ Every 60 seconds:               │                       │
│         │         │ - Print status                  │                       │
│         │         │ - Check if 6 hours elapsed      │                       │
│         └─────────│ - If yes: stop executor,        │                       │
│                   │   run iteration, restart        │                       │
│                   └─────────────────────────────────┘                       │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

特性

自主操作

  • 自我提升:Claude AI每6小时分析一次性能并制定新策略
  • 迭代学习:损失阈值(13.5%)触发自动策略优化
  • 24/7交易:通过内置的崩溃恢复功能持续运行

模块化战略系统

  • 热交换策略:通过添加/删除策略 winners.json
  • 多时间范围:15米、1小时、4小时间隔的测试策略
  • 自动注册:克劳德在制作中增加了传球策略

风险管理

  • 基于动态ATR的SL/TP:适应每种策略类型的市场波动
  • 冷却系统:连续2次止损后暂停30分钟
  • 位置限制:最多10个职位,5%的职位规模
  • 每日损失限额:每日最大提款20%

系统流程

完整的执行流程

┌─────────────────────────────────────────────────────────────────────────────┐
│                           STARTUP SEQUENCE                                  │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                        src/index.ts :: main()                               │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  1. Parse CLI args (run | backtest | iterate | execute | status)      │  │
│  │  2. new QuantAgent()                                                  │  │
│  │     ├─ loadState() → Read agent_state.json                           │  │
│  │     └─ recoverFromStuckState() → Reset if mode=iterate/backtest      │  │
│  │  3. Register SIGINT/SIGTERM handlers                                  │  │
│  │  4. Execute command (default: "run")                                  │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                     QuantAgent::run() [Line 660]                            │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  1. Check winners.json exists and has strategies                      │  │
│  │     ├─ NO strategies → runIteration() first                          │  │
│  │     └─ Has strategies → Continue                                      │  │
│  │  2. startExecution() → Launch Executor                                │  │
│  │  3. Enter MAIN LOOP (every 60 seconds)                                │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘

主控制回路

┌─────────────────────────────────────────────────────────────────────────────┐
│                    MAIN LOOP (Every 60 seconds)                             │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
              ┌─────────────────────┴─────────────────────┐
              ▼                                           ▼
┌───────────────────────────┐               ┌───────────────────────────┐
│ Check: 6 hours elapsed?   │               │     printStatus()         │
│ now - lastIteration >     │               │                           │
│ 21,600,000 ms             │               │  • Mode                   │
└───────────┬───────────────┘               │  • Uptime                 │
            │                               │  • Iterations             │
    YES     │                               │  • Total PnL              │
            ▼                               │  • Positions              │
┌───────────────────────────┐               │  • Daily PnL              │
│  stopExecution()          │               └───────────────────────────┘
│  runIteration()           │                           │
│  startExecution()         │                           │
└───────────────────────────┘                           │
            │                                           │
            └─────────────────┬─────────────────────────┘
                              │
                              ▼
                    ┌─────────────────────┐
                    │ await setTimeout    │
                    │ (60000 ms)          │
                    │ → Loop again        │
                    └─────────────────────┘

迭代流程(克劳德战略开发)

┌─────────────────────────────────────────────────────────────────────────────┐
│                QuantAgent::runIteration() [Line 520]                        │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
        ┌───────────────────────────┼───────────────────────────┐
        ▼                           ▼                           ▼
┌────────────────┐        ┌────────────────┐        ┌────────────────┐
│ Set mode =     │        │ iterationCount │        │ lastIteration  │
│ "iterate"      │        │ ++             │        │ = Date.now()   │
└────────────────┘        └────────────────┘        └────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                  buildIterationPrompt() [Line 423]                          │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  COLLECTS DATA FOR CLAUDE:                                            │  │
│  │                                                                       │  │
│  │  loadIterationHistory()   → results/iteration_*_notes.md (last 3)    │  │
│  │  loadLatestResults()      → top_strategies.json (top 10)             │  │
│  │  analyzeTradeHistory()    → positions.json history                   │  │
│  │  fetchMarketData()        → API: Live prices for 10 symbols          │  │
│  │  loadParamHistory()       → param_history.json (last 20)             │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                    SPAWN CLAUDE CLI [Lines 543-597]                         │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  spawn("claude", ["--dangerously-skip-permissions", "--print"])       │  │
│  │  stdin.write(prompt) → Send full prompt                               │  │
│  │  stdin.end()                                                          │  │
│  │                                                                       │  │
│  │  CLAUDE AUTONOMOUSLY:                                                 │  │
│  │    • Reads src/strategies/_base/strategy-interface.ts                │  │
│  │    • Analyzes trade history and market data                          │  │
│  │    • Creates/edits src/strategies/*.ts files                         │  │
│  │    • Tests with: npx tsx src/quick-backtest.ts <file> <symbol>       │  │
│  │    • Updates winners.json if strategy passes                         │  │
│  │    • Saves notes to results/iteration_N_notes.md                     │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
                    ┌───────────────────────────┐
                    │  on("close"):             │
                    │  • Save to claude_output_ │
                    │    N.txt                  │
                    │  • Set mode = "idle"      │
                    │  • saveState()            │
                    └───────────────────────────┘

执行者交易循环

┌─────────────────────────────────────────────────────────────────────────────┐
│                   Executor::run() [Line 906]                                │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
        ┌───────────────────────────┼───────────────────────────┐
        ▼                           ▼                           ▼
┌────────────────────┐    ┌────────────────────┐    ┌────────────────────┐
│ loadModularStrate- │    │ loadExistingState  │    │ getBalance()       │
│ gies() [L402]      │    │ () [L804]          │    │ [L466]             │
│                    │    │                    │    │                    │
│ Read winners.json  │    │ • getBalances()    │    │ API call or        │
│ For each entry:    │    │ • getActiveOrders  │    │ simulated          │
│  • import(file)    │    │                    │    │                    │
│  • Validate        │    └────────────────────┘    └────────────────────┘
│  • Store in Map    │
│  • Add symbols     │
└────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                  EXECUTOR LOOP (Every 5 minutes) [L931-968]                 │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                    ┌───────────────┴───────────────┐
                    ▼                               ▼
        ┌───────────────────────┐       ┌───────────────────────┐
        │   checkExits()        │       │   checkEntries()      │
        │   [Line 714]          │       │   [Line 763]          │
        │                       │       │                       │
        │ For each position:    │       │ For each symbol:      │
        │  • Get current price  │       │  • Skip if has pos    │
        │  • Check SL hit       │       │  • generateSignal()   │
        │  • Check TP hit       │       │  • If buy/sell:       │
        │  • Check signal exit  │       │    openPosition()     │
        └───────────────────────┘       └───────────────────────┘
                    │                               │
                    └───────────────┬───────────────┘
                                    ▼
                    ┌───────────────────────────┐
                    │ Check loss threshold      │
                    │ If < -13.5%:              │
                    │   invokeIterator()        │
                    └───────────────────────────┘
                                    │
                                    ▼
                    ┌───────────────────────────┐
                    │ await setTimeout          │
                    │ (5 * 60 * 1000)           │
                    │ → Loop again              │
                    └───────────────────────────┘

信号生成和位置管理

┌─────────────────────────────────────────────────────────────────────────────┐
│               generateSignal(symbol) [Line 491]                             │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  For each strategy in modularStrategies:                              │  │
│  │    if strategy.symbols.includes(symbol):                              │  │
│  │      • rateLimit() → 2s delay                                        │  │
│  │      • fetchHistoricalData(symbol, interval, 100)                    │  │
│  │      • strategy.analyze(candles) → Signal                            │  │
│  │      • if signal !== "hold" → return signal                          │  │
│  │  return "hold"                                                        │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│               openPosition(symbol, side, balance) [Line 536]                │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  1. Check cooldown (skip if on cooldown)                              │  │
│  │  2. Get order book price                                              │  │
│  │  3. Validate price slippage (< 2%)                                   │  │
│  │  4. calculateDynamicSLTP(price, atr, strategyId)                     │  │
│  │     ├─ detectStrategyType() → scalping|trend|momentum|etc            │  │
│  │     ├─ Get RISK_PROFILES[strategyType]                               │  │
│  │     └─ Calculate SL/TP with ATR multipliers                          │  │
│  │  5. api.placeOrder()                                                  │  │
│  │  6. positions.set(symbol, position)                                   │  │
│  │  7. savePositions() → positions.json                                  │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│               closePosition(symbol, reason) [Line 663]                      │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │  1. Get exit price from order book                                    │  │
│  │  2. api.placeOrder() (opposite side)                                  │  │
│  │  3. Calculate PnL                                                      │  │
│  │  4. addToTradeHistory() → Track for Claude analysis                  │  │
│  │  5. Update cooldown if stop_loss                                      │  │
│  │  6. positions.delete(symbol)                                          │  │
│  │  7. savePositions()                                                    │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘

建筑

文件结构

quant-agent/
├── src/
│   ├── index.ts                 # MAIN ENTRY POINT - Orchestrator
│   │   ├── QuantAgent class     # Main controller
│   │   ├── loadTradeHistory()   # Read positions.json history
│   │   ├── analyzeTradeHistory()# Calculate win rates, failing strategies
│   │   ├── fetchMarketData()    # Get live prices for symbols
│   │   ├── loadParamHistory()   # Parameter experiment tracking
│   │   ├── buildIterationPrompt()# Build prompt for Claude
│   │   └── runIteration()       # Spawn Claude process
│   │
│   ├── executor.ts              # LIVE TRADING ENGINE
│   │   ├── Executor class       # Trading controller
│   │   ├── loadModularStrategies()# Load from winners.json
│   │   ├── generateSignal()     # Get buy/sell/hold from strategies
│   │   ├── openPosition()       # Enter trades with dynamic SL/TP
│   │   ├── closePosition()      # Exit trades, track history
│   │   ├── checkExits()         # Monitor SL/TP/signal reversals
│   │   ├── checkEntries()       # Scan for new entry signals
│   │   └── calculateDynamicSLTP()# ATR-based risk calculation
│   │
│   ├── quick-backtest.ts        # FAST STRATEGY TESTER
│   │   ├── runBacktest()        # Simulate strategy on candles
│   │   └── main()               # CLI: npx tsx quick-backtest.ts <file> <symbol> <interval>
│   │
│   ├── strategies/              # MODULAR STRATEGY SYSTEM
│   │   ├── _base/
│   │   │   └── strategy-interface.ts  # Strategy interface definition
│   │   │       ├── Strategy interface
│   │   │       ├── Signal type ("buy" | "sell" | "hold")
│   │   │       ├── RiskProfile interface
│   │   │       ├── BaseStrategy class
│   │   │       └── calculateSLTP() helper
│   │   │
│   │   ├── index.ts             # AUTO-LOADER
│   │   │   ├── loadAllStrategies()    # Scan directories
│   │   │   ├── getStrategy(id)        # Get by ID
│   │   │   └── listStrategyIds()      # List all
│   │   │
│   │   ├── winners.json         # ACTIVE STRATEGIES REGISTRY
│   │   │
│   │   ├── momentum/            # Momentum strategies
│   │   │   ├── rsi-reversal.ts
│   │   │   ├── ema-crossover-momentum.ts
│   │   │   ├── rsi-bb-volume-confluence.ts
│   │   │   ├── macd-divergence.ts
│   │   │   ├── squeeze-momentum-breakout.ts
│   │   │   ├── tsi-momentum.ts
│   │   │   ├── schaff-trend-cycle.ts
│   │   │   └── supertrend-follower.ts
│   │   │
│   │   ├── mean-reversion/      # Mean reversion strategies
│   │   │   └── volume-weighted-mean-reversion.ts
│   │   │
│   │   ├── trend/               # Trend following strategies
│   │   │   └── ichimoku-cloud-trend.ts
│   │   │
│   │   └── composite/           # Multi-indicator strategies
│   │       ├── multi-indicator-confluence.ts
│   │       └── market-structure-momentum.ts
│   │
│   ├── indicators/
│   │   └── index.ts             # Technical indicators library
│   │       ├── sma(), ema()
│   │       ├── rsi(), macd()
│   │       ├── bollingerBands()
│   │       ├── atr(), adx()
│   │       ├── stochastic(), cci()
│   │       └── vwap(), volume analysis
│   │
│   └── utils/
│       └── revolut-api.ts       # REVOLUT X API WRAPPER
│           ├── signRequest()          # Ed25519 authentication
│           ├── apiRequest()           # Authenticated API calls
│           ├── getBalances()          # GET /balances
│           ├── getOrderBook()         # GET /order-book/{symbol}
│           ├── getActiveOrders()      # GET /orders/active
│           ├── placeOrder()           # POST /orders
│           ├── cancelOrder()          # DELETE /orders/{id}
│           └── fetchHistoricalData()  # GET /candles/{symbol}
│
├── agent_state.json             # Persistent state (mode, iteration count)
├── positions.json               # Active positions & trade history
├── top_strategies.json          # Backtest results for reference
├── param_history.json           # Parameter experiment log
│
└── results/                     # Iteration outputs
    ├── claude_output_N.txt      # Raw Claude output
    └── iteration_N_notes.md     # Claude's analysis notes

数据流

┌──────────────────┐     ┌──────────────────┐     ┌──────────────────┐
│  agent_state.json│     │  positions.json  │     │  winners.json    │
│                  │     │                  │     │                  │
│  • mode          │     │  • positions[]   │     │  • strategies[]  │
│  • lastIteration │     │  • history[]     │     │    • file        │
│  • iterationCount│     │  • dailyPnL      │     │    • symbols[]   │
│  • startTime     │     │  • updatedAt     │     │    • interval    │
└────────┬─────────┘     └────────┬─────────┘     └────────┬─────────┘
         │                        │                        │
         │ Read/Write             │ Read/Write             │ Read
         │ by index.ts            │ by executor.ts         │ by executor.ts
         │                        │                        │
         │                        │ Read by index.ts       │ Write by
         │                        │ (analyzeTradeHistory)  │ Claude iteration
         ▼                        ▼                        ▼

┌──────────────────┐     ┌──────────────────┐     ┌──────────────────┐
│top_strategies.   │     │ param_history.   │     │ results/*.txt    │
│json              │     │ json             │     │                  │
│                  │     │                  │     │  • claude_output │
│  • strategyId    │     │  • strategyId    │     │  • iteration_    │
│  • symbol        │     │  • params        │     │    notes.md      │
│  • metrics       │     │  • result        │     │                  │
└────────┬─────────┘     └────────┬─────────┘     └────────┬─────────┘
         │                        │                        │
         │ Read by index.ts       │ Read by index.ts       │ Write by
         │ (context for Claude)   │ (buildIterationPrompt) │ index.ts

设置

先决条件

  • Node.js 18+
  • 具有API访问权限的Revolut X帐户
  • 已安装Claude Code CLI(npm install -g @anthropic-ai/claude-code)

安装

# Clone the repository
git clone https://github.com/greenm8rix/QuantAgent-Claude-Revolutx-MCP.git
cd QuantAgent-Claude-Revolutx-MCP

# Install dependencies
npm install

配置

创建环境变量或编辑 src/utils/revolut-api.ts:

const API_KEY = "your_revolut_x_api_key";
const PRIVATE_KEY_PATH = "/path/to/your/private.pem";

为Revolut X生成私钥:

openssl genpkey -algorithm ed25519 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem

上传 public.pem 到Revolut X API设置。


用法

开始自主交易

# Run the full autonomous system (recommended)
npm run live
# or
npx tsx src/index.ts run

这将:

  1. 负载获胜策略来自 winners.json
  2. 启动执行者(实时交易)
  3. 每60秒监控一次性能
  4. 每6小时运行一次Claude迭代
  5. 从碰撞中自动恢复

手动操作

# Run single iteration only (Claude creates/improves strategies)
npx tsx src/index.ts iterate

# Start execution only (no iterations)
npx tsx src/index.ts execute

# Check current status
npx tsx src/index.ts status

# Quick backtest a strategy
npx tsx src/quick-backtest.ts momentum/rsi-reversal.ts BTC-USD 15

# Run executor standalone
npx tsx src/executor.ts

仪表盘

# Start web dashboard (port 3001)
npx tsx src/dashboard.ts

策略

策略接口

所有策略都实现了此接口:

interface Strategy {
  id: string;                    // Unique identifier
  name: string;                  // Human-readable name
  description: string;           // What it does
  category: "momentum" | "mean_reversion" | "trend" | "scalping" | "composite";

  initialize?(candles: Candle[]): Promise<void>;  // Optional setup
  analyze(candles: Candle[]): Promise<Signal>;    // Main logic
  getMetadata(): StrategyMetadata;                // Metadata
  getRiskProfile(): RiskProfile;                  // Risk params
  getSuggestedSLTP(price, atr, side): SuggestedSLTP;
}

type Signal = "buy" | "sell" | "hold";

制定战略

// src/strategies/momentum/my-strategy.ts
import { BaseStrategy } from "../_base/strategy-interface.js";
import type { Signal } from "../_base/strategy-interface.js";
import type { Candle } from "../../indicators/index.js";
import * as ind from "../../indicators/index.js";

class MyStrategy extends BaseStrategy {
  id = "my-strategy-v1";
  name = "My Custom Strategy";
  description = "RSI oversold bounce strategy";
  category = "momentum" as const;

  async analyze(candles: Candle[]): Promise<Signal> {
    const rsi = ind.rsi(candles, 14);
    const lastRsi = rsi[rsi.length - 1];

    if (lastRsi < 30) return "buy";
    if (lastRsi > 70) return "sell";
    return "hold";
  }
}

export default new MyStrategy();

注册策略

增添 src/strategies/winners.json:

{
  "strategies": [
    {
      "file": "momentum/my-strategy.ts",
      "symbols": ["BTC-USD", "ETH-USD"],
      "interval": 15,
      "notes": "My strategy notes"
    }
  ]
}

测试策略

npx tsx src/quick-backtest.ts momentum/my-strategy.ts BTC-USD 60

通过标准:

  • 5+笔交易
  • 45%+胜率
  • 0.5+夏普比率
  • 正总PnL

风险管理

策略类型风险概况

类型 SL范围 TP范围 ATR乘数(SL/TP)
头皮 0.5-2% 0.8-3% 1.0倍/1.5倍
趋势 2-8% 4-20% 2.0倍/4.0倍
平均逆转率 1-4% 1.5-6% 1.5x/2.0倍
动量 1.5-5% 3-12% 1.5倍/3.0倍
突破 1-4% 3-15% 1.2倍/3.5倍

冷却系统

在同一交易品种+策略上连续2次止损后:

  • 30分钟交易暂停
  • 重置下一笔盈利交易

损失阈值

当每日损失超过13.5%时:

  1. 暂停所有新条目
  2. 生成Claude迭代器(冷却1小时)
  3. 克劳德分析出了什么问题
  4. 创建/修改策略
  5. 恢复交易

位置限制

  • 最大位置:10
  • 头寸大小:余额的5%
  • 每日损失限额:20%

API 参考

Revolut X API函数

// Get account balances
getBalances(): Promise<Balance[]>

// Get order book
getOrderBook(symbol: string, limit?: number): Promise<OrderBook>

// Get historical candles
fetchHistoricalData(symbol: string, interval: number, limit?: number): Promise<Candle[]>

// Place order
placeOrder(clientOrderId, symbol, side, type, options): Promise<Order>

// Cancel order
cancelOrder(orderId: string): Promise<void>

// Get active orders
getActiveOrders(): Promise<Order[]>

贡献

  1. 分叉存储库
  2. 创建功能分支(git checkout -b feature/amazing-strategy)
  3. 提交您的更改(git commit -m 'Add amazing strategy')
  4. 推到分支(git push origin feature/amazing-strategy)
  5. 打开拉取请求

免责声明

此软件仅用于教育目的。

  • 加密货币交易涉及巨大的损失风险
  • 过去的表现并不能保证未来的结果
  • 永远不要用你输不起的钱交易
  • 这不是财务建议

许可证

MIT许可证-请参阅 许可证 了解详情。


使用Claude AI+Revolut X构建