使用说明
交易机器人服务器
使用Bun构建的用于加密货币交易自动化的高性能模型上下文协议(MCP)服务器。该项目为多种加密货币资产提供实时市场数据收集、技术分析和自动交易执行功能。
目录
特性
- 实时市场数据:获取加密货币资产的实时市场价格和历史数据
- 技术分析:计算多个时间范围内的技术指标(RSI、MACD、布林带等)
- 自动交易:使用可配置的置信度执行多头、空头、持有和收盘_
- 多资产支持:交易BTC、ETH、SOL和HYPE(可扩展到其他交易品种)
- 位置跟踪:监控和检索未平仓交易头寸
- LLM集成:利用人工智能模型进行智能交易分析和决策
- 高性能:基于Bun运行时构建,性能比Node.js快3倍
先决条件
必需
可选的
- MCP检查员 -用于调试和监视服务器行为
- API证书 -适用于您的交易平台(币安、Kraken等)
安装
步骤1:克隆或创建项目
# If starting fresh
bun init trading-bot-server
cd trading-bot-server
# Or clone existing project
git clone <your-repo-url>
cd trading-bot-server
步骤2:安装依赖项
bun install
这将安装在您的 package.json,包括:
- MCP协议依赖性
- 市场数据客户端
- 交易执行库
- 分析工具
配置
设置环境变量
创建一个 .env 项目根目录中的文件,其中包含以下必需变量:
# CRITICAL: Required for all operations
PRIVATE_API_KEY=your_private_api_key_here
EXCHANGE_API_KEY=your_exchange_api_key
EXCHANGE_SECRET_KEY=your_exchange_secret_key
# Optional: Server Configuration
SERVER_PORT=3000
LOG_LEVEL=info
TRADING_MODE=simulation
获取您的API私钥
- 登录 转到您的交易平台帐户
- 导航 设置API管理或安全
- 创建新的API密钥 具有以下权限:
- 读取市场数据
- 读取账户余额
- 创建订单
- 取消订单
- 复制私钥 并将其添加到您的
.env文件 - 保护您的密钥 -永不承诺
.env到版本控制
环境安全
始终添加 .env 你的 .gitignore:
echo ".env" >> .gitignore
echo ".env.local" >> .gitignore
echo "*.key" >> .gitignore
运行服务器
基本执行
bun run server.ts
服务器将从默认端口启动,并开始监听MCP协议连接。
使用自定义配置运行
# Run with specific environment file
export $(cat .env.production | xargs)
bun run server.ts
# Run in development mode with hot reload
bun run --watch server.ts
# Run with increased memory allocation
bun run --smol server.ts
验证服务器状态
启动后,您应该看到类似于以下内容的输出:
✓ Trading Bot Server initialized
✓ Market data provider connected
✓ MCP server listening on port 3000
✓ Ready for connections
带检查器的调试模式
使用MCP检查器进行调试
MCP检查器为调试和测试MCP服务器提供了一个可视化界面。这对于以下方面来说是无价的:
- 测试工具函数调用
- 检查服务器响应
- 调试交易执行逻辑
- 监控实时数据流
安装
# Install MCP Inspector globally
npm install -g @modelcontextprotocol/inspector
# or
bun add -g @modelcontextprotocol/inspector
与Inspector一起运行
# Method 1: Using bunx (Bun's package runner)
bunx @modelcontextprotocol/inspector bun server.ts
# Method 2: Using installed inspector
mcp-inspector bun server.ts
# Method 3: Direct execution with inspector output
bun run --inspect server.ts
检查器界面
运行后,检查员将提供:
- 工具浏览器 -查看所有可用工具及其参数
- 请求/响应查看器 -查看实时API调用和响应
- 错误跟踪 -监控并调试出现的错误
- 性能指标 -查看执行时间和资源使用情况
检查员工作流程示例
# 1. Start inspector
bunx @modelcontextprotocol/inspector bun server.ts
# 2. Open browser to localhost:3000 (inspector UI)
# 3. Test market data retrieval
# - Select "get_market_data" tool
# - Input: {"symbol": "BTC"}
# - View response in real-time
# 4. Test trade execution
# - Select "execute_trade" tool
# - Input: {"symbol": "BTC", "action": "LONG", "quantity": 1, "confidence": 0.85}
# - Monitor execution and response
API 参考
可用工具
1. get_market_data
检索指定加密货币符号的当前市场价格和数据。
参数:
symbol(字符串,必填):交易符号-BTC,ETH,SOL,或HYPE
答复:
{
"symbol": "BTC",
"price": 45250.50,
"change24h": 2.35,
"volume": 28450000000,
"timestamp": 1698825600000
}
2. get_technical_indicators
计算指定时间段和符号的技术分析指标。
参数:
symbol(字符串,必填):交易符号period(字符串,必填):时间段-5m(5分钟)或4h(4小时)
答复:
{
"symbol": "BTC",
"period": "5m",
"rsi": 65.42,
"macd": 245.30,
"bollingerBands": {
"upper": 46000,
"middle": 45250,
"lower": 44500
}
}
3. get_open_positions
检索所有当前未平仓的交易头寸。
答复:
{
"positions": [
{
"symbol": "BTC",
"side": "LONG",
"quantity": 0.5,
"entryPrice": 44000,
"currentPrice": 45250.50,
"pnl": 625.25,
"pnlPercent": 1.42
}
]
}
4. execute_trade
使用指定的参数和置信水平执行交易操作。
参数:
symbol(字符串,必填):交易符号action(string,必填):交易行为-LONG,SHORT,HOLD,或CLOSE_ALLquantity(数字,必填):以基础货币表示的交易数量confidence(数字,必填):置信水平(0.0-1.0)reasoning(string,必填):交易决策的解释
答复:
{
"status": "executed",
"orderId": "ORD_1698825650_BTC",
"symbol": "BTC",
"action": "LONG",
"quantity": 0.5,
"executionPrice": 45250.50,
"timestamp": 1698825650000
}
5. request_ai_trading_bot
向人工智能交易机器人MCP服务器发送请求,以收集数据、分析市场并自主执行交易。
参数:
symbol(字符串,必填):要分析的交易品种
答复:
{
"status": "processing",
"analysis": {
"trend": "bullish",
"strength": 0.85,
"recommendation": "LONG"
},
"tradeExecuted": true,
"orderId": "ORD_1698825650_BTC"
}
使用示例
示例1:获取市场数据
// Get current BTC price and market data
const response = await server.tools.get_market_data({
symbol: "BTC"
});
console.log(`BTC Price: $${response.price}`);
console.log(`24h Change: ${response.change24h}%`);
示例2:分析技术指标
// Get 5-minute technical indicators for ETH
const indicators = await server.tools.get_technical_indicators({
symbol: "ETH",
period: "5m"
});
console.log(`RSI: ${indicators.rsi}`);
console.log(`Bollinger Bands Upper: ${indicators.bollingerBands.upper}`);
示例3:执行交易
// Execute a LONG trade on SOL
const tradeResult = await server.tools.execute_trade({
symbol: "SOL",
action: "LONG",
quantity: 10,
confidence: 0.75,
reasoning: "Strong bullish signal from RSI crossover"
});
console.log(`Order ID: ${tradeResult.orderId}`);
console.log(`Status: ${tradeResult.status}`);
示例4:检查空缺职位
// Get all open positions
const positions = await server.tools.get_open_positions();
positions.forEach(position => {
console.log(`${position.symbol}: ${position.side} ${position.quantity}`);
console.log(`P&L: $${position.pnl} (${position.pnlPercent}%)`);
});
示例5:使用AI Bot进行自主交易
// Request AI bot to analyze and trade HYPE
const aiTrade = await server.tools.request_ai_trading_bot({
symbol: "HYPE"
});
console.log(`Analysis: ${aiTrade.analysis.trend}`);
console.log(`Trade Executed: ${aiTrade.tradeExecuted}`);
组件详细信息
| 组件 | 用途 | 技术 |
|---|---|---|
| MCP协议处理程序 | 管理客户端连接 | @modelcontextprotocol/sdk |
| 市场数据服务 | 获取实时价格 | REST API+WebSocket |
| 技术分析 | 计算指标 | 自定义TA库 |
| 贸易执行人 | 提交订单以进行交换 | exchange API SDK |
| 职位管理 | 跟踪活跃交易 | 数据库/内存存储 |
| AI/LLM集成 | 自主分析 | 外部LLM API |
演出
Bun运行时优势
Bun比Node.js提供了显著的性能改进:
| 度量 | Node.js | Bun | 改进 |
|---|---|---|---|
| 软件包安装 | 45秒 | 8秒 | 5.6倍快 |
| TypeScript编译 | 2.3秒 | 0.1秒 | 快23倍 |
| HTTP吞吐量 | 19039请求/秒 | 59026请求/秒 | 快3.1倍 |
| WebSocket消息 | 435099消息/秒 | 2536227消息/秒 | 快5.8倍 |
| 数据库查询 | 14522 q/s | 28571 q/s | 快1.97倍 |
优化提示
- 使用Bun的内置打包器 为了更快的构建
- 启用缓存 用于市场数据查询
- 批量交易操作 以减少API调用
- 实施速率限制 遵守外汇限额
- 监控内存使用情况 随着
bun run --smol适用于受限环境
故障排除
问题:“找不到PRIVATE_API_KEY”
解决方案:
# Verify .env file exists in project root
ls -la .env
# Verify variable is set
grep PRIVATE_API_KEY .env
# Reload environment
source .env
bun run server.ts
问题:端口3000上的“连接被拒绝”
解决方案:
# Check if port is already in use
lsof -i :3000
# Kill existing process
kill -9 <PID>
# Run on different port
PORT=3001 bun run server.ts
问题:检查员未启动
解决方案:
# Update inspector to latest version
bun add -g @modelcontextprotocol/inspector@latest
# Try direct inspector command
mcp-inspector --help
# Alternative: Use Bun's built-in debugger
bun run --inspect-brk server.ts
问题:API密钥身份验证失败
解决方案:
# Verify API key format and encoding
echo $PRIVATE_API_KEY | wc -c
# Test API key with direct request
curl -H "Authorization: Bearer $PRIVATE_API_KEY" \
https://api.example.com/account
# Check for whitespace issues
PRIVATE_API_KEY=$(echo $PRIVATE_API_KEY | xargs)
问题:内存使用率高
解决方案:
# Run with memory constraints
bun run --smol server.ts
# Monitor memory
ps aux | grep server.ts
# Implement position cleanup
# Add periodic garbage collection
setInterval(() => {
if (global.gc) global.gc();
}, 60000);
问题:市场数据API利率限制
解决方案:
# Implement exponential backoff
# Add request queuing
# Reduce polling frequency
# Consider upgrading API subscription tier
开发工作流程
热重载开发
bun run --watch server.ts
运行测试
bun test
生产大楼
bun build --target bun server.ts --outfile dist/server.js
Docker部署
FROM oven/bun:latest
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY server.ts .
ENV NODE_ENV=production
EXPOSE 3000
CMD ["bun", "run", "server.ts"]
安全最佳实践
- 永不承诺
.env文件 包含API密钥 - 使用特定于环境的秘密 用于生产
- 实施速率限制 防止滥用
- 验证所有输入 来自外部来源
- 使用HTTPS 在生产部署中
- 旋转API键 定期
- 监控可疑活动 关于交易账户
- 实现请求签名 用于交易执行
贡献
为该项目做出贡献:
- 创建要素分支
- 进行更改
- 与检查员一起进行彻底测试
- 提交拉取请求
许可证
[在此处添加您的许可证]
支持
对于问题、疑问或功能请求:
- GitHub问题:在存储库中创建问题
- 文档:检查文档文件夹
- 调试:使用
bunx @modelcontextprotocol/inspector bun server.ts