⏱️ 阅读时间:约10分钟
✨ 关注我们获取更多量化知识干货
项目介绍
Nof1 AI Agent跟单系统是一个基于Node.js和TypeScript开发的命令行工具,专门用于跟踪nof1.ai平台上的AI Agent交易信号,并自动在币安合约市场执行相应的交易操作。该系统支持实时监控7个不同的AI量化交易Agent,包括GPT-5、Gemini 2.5 Pro、DeepSeek Chat v3.1等业界顶尖的人工智能模型。
系统的核心价值在于它能够自动识别并执行四种关键的交易信号:
-
新开仓信号:当AI Agent建立新仓位时自动跟单 -
平仓信号:当AI Agent平仓时自动跟单 -
换仓信号:检测到entry_oid变化时,先平旧仓再开新仓 -
止盈止损信号:当价格达到预设的盈利目标或止损点时自动平仓
系统架构
Nof1 AI Agent跟单系统采用了模块化的设计架构,各个组件职责明确,协同工作:
CLI层 (index.ts)
↓
命令处理器 (commands/)
↓
API分析器 (scripts/analyze-api.ts)
↓
核心服务层 (services/)
├── ApiClient:与Nof1 API通信
├── FollowService:跟单核心逻辑
├── PositionManager:仓位管理
├── RiskManager:风险控制
├── FuturesCapitalManager:资金管理
├── TradingExecutor:交易执行
├── OrderHistoryManager:订单历史管理
└── BinanceService:与币安API交互
这种分层架构确保了系统的可维护性和可扩展性,同时也便于开发者理解和修改代码。
快速上手
使用Nof1 AI Agent跟单系统非常简单,只需几个步骤即可开始您的AI量化交易之旅:
1. 环境准备与安装
首先确保您的系统已安装Node.js (版本≥18.0.0)和npm,然后执行以下命令:
# 克隆项目并安装依赖
git clone https://github.com/terryso/nof1-tracker.git
cd nof1-tracker
npm install && npm run build
# 配置环境变量
cp .env.example .env
2. 配置币安API密钥
编辑.env文件,填入您的币安API密钥(必须启用合约交易权限):
BINANCE_API_KEY=your_binance_api_key_here
BINANCE_API_SECRET=your_binance_api_secret_here
BINANCE_TESTNET=true # 推荐新手先使用测试网
3. 开始跟单交易
# 查看可用的AI Agent
npm start -- agents
# 风险控制模式测试(只观察不执行)
npm start -- follow deepseek-chat-v3.1 --risk-only
# 实际跟单交易
npm start -- follow gpt-5
# 持续监控(每30秒检查一次)
npm start -- follow gpt-5 --interval 30
核心代码解析
让我们深入系统的核心代码,了解跟单逻辑是如何实现的:
1. 跟单命令处理器
在src/commands/follow.ts中,系统通过handleFollowCommand函数处理跟单命令:
export async function handleFollowCommand(agentName: string, options: CommandOptions): Promise<void> {
const services = initializeServices(true);
applyConfiguration(services.analyzer, options);
console.log(`🤖 Starting to follow agent: ${agentName}`);
// 获取跟单计划
const followOptions = {
totalMargin: options.totalMargin,
profitTarget: options.profit,
autoRefollow: options.autoRefollow,
marginType: options.marginType || 'CROSSED'
};
const followPlans = await services.analyzer.followAgent(agentName, followOptions);
// 处理每个跟单计划
for (let i = 0; i < followPlans.length; i++) {
await processFollowPlan(followPlans[i], services, options, i);
}
}
2. 跟单核心逻辑
在src/services/follow-service.ts中,followAgent方法实现了跟单的核心逻辑:
async followAgent(
agentId: string,
currentPositions: Position[],
options?: FollowOptions
): Promise<FollowPlan[]> {
// 1. 清理孤立的挂单
await this.positionManager.cleanOrphanedOrders();
// 2. 重建上次仓位状态
const previousPositions = this.rebuildLastPositionsFromHistory(agentId, currentPositions);
// 3. 检测仓位变化
const changes = await this.detectPositionChanges(currentPositions, previousPositions || [], options);
// 4. 处理每种变化
const followPlans: FollowPlan[] = [];
for (const change of changes) {
const plans = await this.handlePositionChange(change, agentId, options);
followPlans.push(...plans);
}
return followPlans;
}
3. 仓位变化检测
系统通过OID(订单ID)变化来检测不同的交易信号:
private async detectPositionChanges(
currentPositions: Position[],
previousPositions: Position[],
options?: FollowOptions
): Promise<PositionChange[]> {
const changes: PositionChange[] = [];
const currentPositionsMap = new Map(currentPositions.map(p => [p.symbol, p]));
const previousPositionsMap = new Map(previousPositions.map(p => [p.symbol, p]));
for (const [symbol, currentPosition] of currentPositionsMap) {
const previousPosition = previousPositionsMap.get(symbol);
if (!previousPosition) {
// 新仓位
if (currentPosition.quantity !== 0) {
changes.push({
symbol,
type: 'new_position',
currentPosition,
previousPosition
});
}
} else {
// 检查 entry_oid 变化(换仓)
if (previousPosition.entry_oid !== currentPosition.entry_oid && currentPosition.quantity !== 0) {
changes.push({
symbol,
type: 'entry_changed',
currentPosition,
previousPosition
});
} else if (previousPosition.quantity !== 0 && currentPosition.quantity === 0) {
// 仓位已平
changes.push({
symbol,
type: 'position_closed',
currentPosition,
previousPosition
});
}
}
}
return changes;
}
高级功能
Nof1系统还提供了两个非常实用的高级功能:
1. 盈利目标退出
用户可以设置自定义盈利目标,当仓位达到指定盈利百分比时自动平仓退出:
# 当盈利达到30%时自动平仓
npm start -- follow gpt-5 --profit 30
2. 自动重新跟单
在盈利退出的基础上,可选择自动重新跟单功能:
# 盈利30%退出后,自动重新跟单
npm start -- follow gpt-5 --profit 30 --auto-refollow
风险控制
为了确保交易安全,系统提供了多重风险控制机制:
1. 价格容忍度检查
系统会检查当前价格与入场价格的差异,如果超过设定的容忍度则不会执行交易:
# 设置价格容忍度为1%
npm start -- follow deepseek-chat-v3.1 --price-tolerance 1.0
2. 订单去重机制
通过订单历史管理器,系统能够自动识别并跳过已处理的订单,防止重复执行:
isOrderProcessed(entryOid: number, symbol: string): boolean {
const isProcessed = this.historyData.processedOrders.some(
order => order.entryOid === entryOid && order.symbol === symbol
);
return isProcessed;
}
3. 孤立挂单清理
系统会在每次轮询时自动清理没有对应仓位的止盈止损单,避免意外触发:
async cleanOrphanedOrders(): Promise<{
success: boolean;
cancelledOrders: number;
errors: string[];
}> {
// 获取所有开放订单和仓位
const allOpenOrders = await this.binanceService.getOpenOrders();
const allPositions = await this.binanceService.getAllPositions();
// 识别并取消孤立的挂单
// ...
}
盈利统计
系统还提供了强大的盈利统计功能,帮助用户分析交易表现:
# 查看总盈利情况
npm start -- profit
# 查看最近7天的盈利
npm start -- profit --since 7d
# 仅查看当前仓位的浮动盈亏
npm start -- profit --unrealized-only
实战案例
让我们通过一个实际案例来演示系统的使用:
# 1. 查看可用的AI Agent
npm start -- agents
# 输出:
# 🤖 Available agents: buynhold_btc, claude-sonnet-4-5, deepseek-chat-v3.1, gpt-5, gemini-2.5-pro, grok-4, qwen3-max
# 2. 风险控制模式测试
npm start -- follow deepseek-chat-v3.1 --risk-only
# 输出:
# 🤖 Starting to follow agent: deepseek-chat-v3.1
# 🎯 Found agent deepseek-chat-v3.1 (marker: 138) with 6 positions
#
# 1. BTCUSDT - ENTER
# Side: BUY
# Type: MARKET
# Quantity: 0.050000
# Leverage: 20x
# Entry Price: 109538
# Reason: New position opened by deepseek-chat-v3.1 (OID: 210131632249)
# ⚠️ Risk Score: 100/100
# 🚨 Warnings: High risk score
# 💰 Price Check: Entry $109538 vs Current $109550
# 📏 Price Difference: 0.01% (Tolerance: 1%)
# ✅ Price Tolerance: Price difference 0.01% is within tolerance 1%
# ❌ Risk assessment: FAILED - Trade skipped
# 3. 实际跟单交易
npm start -- follow deepseek-chat-v3.1
# 输出:
# 🤖 Starting to follow agent: deepseek-chat-v3.1
# 🎯 Found agent deepseek-chat-v3.1 (marker: 138) with 6 positions
#
# 1. BTCUSDT - ENTER
# Side: BUY
# Type: MARKET
# Quantity: 0.050000
# Leverage: 20x
# Entry Price: 109538
# Reason: New position opened by deepseek-chat-v3.1 (OID: 210131632249)
# ⚠️ Risk Score: 100/100
# 🚨 Warnings: High risk score
# 💰 Price Check: Entry $109538 vs Current $109550
# 📏 Price Difference: 0.01% (Tolerance: 1%)
# ✅ Price Tolerance: Price difference 0.01% is within tolerance 1%
# ✅ Risk assessment: PASSED
# 🔄 Executing trade...
# ✅ Connected to Binance API (Server time: 1701234567890)
# 💰 Account Balance Information:
# Total Wallet Balance: 1000.00 USDT
# Available Balance: 950.00 USDT
# 🔄 Executing trade: BTCUSDT BUY 0.05 (Leverage: 20x)
# ✅ Leverage set to 20x for BTCUSDT
# ✅ Order executed successfully:
# Order ID: 123456789
# Symbol: BTCUSDT
# Status: FILLED
# Price: 109545
# Quantity: 0.05
# ✅ Trade executed successfully!
# 📝 Order ID: 123456789
# 💾 Saving order to history: BTCUSDT (OID: 210131632249)
# ✅ Saved processed order: BTCUSDT BUY 0.05 (OID: 210131632249)
总结
Nof1 AI Agent跟单系统通过其强大的功能和优雅的设计,供了完善的风险控制机制和盈利统计功能,确保用户能够在控制风险的前提下追求收益。
项目地址
https://github.com/terryso/nof1-tracker
关注【魔方量化】,带你玩转开源量化交易!

