
最近,美国AI实验室nof1ai发起了一场引人瞩目的实验——给六个顶级AI模型(Claude、DeepSeek、Gemini、GPT-5、Grok和通义千问)各发1万美金,让它们在真实的加密货币永续合约市场上较量。这不是模拟盘,而是真金白银的实战。实验结果令人意外:国产AI DeepSeek一直领先,而GPT-5和Gemini双双翻车。这场竞赛最大的价值在于,团队将使用到的一些提示词、数据结构、决策流程全部开源,为我们提供了研究AI量化交易的绝佳范本。

本文将基于这个公开的架构,详细拆解一个AI量化交易工作流的每个节点、每个逻辑,帮助你理解AI是如何在真实市场中做出交易决策的。
这个AI量化交易系统采用经典的”感知-决策-执行”三段式架构,整个工作流由多个核心节点组成:

核心节点说明: 1. 定时触发器 - 系统心跳,每3分钟触发一次 2. 参数重置 - 账户状态监控与性能统计 3. 市场数据获取 - 多维度数据获取与指标计算 4. 持仓数据获取 - 当前持仓状态追踪 5. 数据合并 - 整合账户与市场信息 6. AI智能体 - 核心决策引擎 7. 交易执行 - 信号解析与订单处理
让我们逐一深入剖析每个节点的设计逻辑。
定时触发器是整个工作流的启动器,类似于人体的心跳,周期性地驱动系统运转。
设计考量: - 3分钟周期:平衡数据新鲜度与API调用限制 - 固定间隔:确保策略执行的稳定性和可预测性
这是一个关键的状态管理节点,负责初始化、追踪和计算账户的各项核心指标。
// 设置币安模拟交易所API基础地址
api_base = "https://testnet.binancefuture.com"
exchange.SetBase(api_base)
// 初始化检查 - 首次运行时设置基准值
if (_G('invoketime') === null) {
_G('invoketime', 0);
_G('STARTTIME', Date.now());
const initAccount = exchange.GetAccount();
_G('initmoney', initAccount.Equity);
}
// 累计调用次数
const invoketime = _G('invoketime') + 1;
_G('invoketime', invoketime);
// 计算运行时长(分钟)
const duringtime = Math.floor((Date.now() - _G('STARTTIME')) / 60000);
// 获取当前账户信息
const currentAccount = exchange.GetAccount();
const currentAccountValue = currentAccount.Equity;
// 计算总收益率
const initMoney = _G('initmoney');
const totalReturnPercent = ((currentAccountValue - initMoney) / initMoney * 100).toFixed(2);
// 记录收益到系统日志
LogProfit(currentAccountValue - initMoney, "&")
// 返回5个核心指标
return [{
json: {
invoketime: invoketime,
duringtime: duringtime,
totalReturnPercent: totalReturnPercent + '%',
availableCash: currentAccount.Balance.toFixed(2),
currentAccountValue: currentAccountValue.toFixed(2)
}
}];
{
"invoketime": 42, // 系统调用次数
"duringtime": 126, // 运行时长(分钟)
"totalReturnPercent": "3.45%", // 总收益率
"availableCash": "10345.67", // 可用资金
"currentAccountValue": "10345.00" // 账户总价值
}
_G()函数实现跨周期的数据持久化initmoney作为收益计算的基准LogProfit()函数将收益实时反馈到系统图表这是整个系统的”眼睛”,负责采集、处理和计算市场的各类数据与技术指标。
市场数据采集节点的功能可以分为三个层次:
// 解析币种列表
const coins = $vars.coinList ?
($vars.coinList.includes(',') ? $vars.coinList.split(',') : [$vars.coinList]) : [];
if (coins.length === 0) {
return {};
}
// 为每个币种获取市场数据
const allCoinsData = {};
for (let i = 0; i < coins.length; i++) {
const coin = coins[i].trim();
try {
allCoinsData[coin] = getMarketDataForCoin(coin);
} catch (e) {
allCoinsData[coin] = { error: e.toString() };
}
}
return { data: allCoinsData };
function getMarketDataForCoin(symbol) {
// 切换到对应币种的永续合约
exchange.SetCurrency(symbol + "_USDT");
exchange.SetContractType("swap");
// 获取3分钟和4小时K线数据
const kline3m = exchange.GetRecords(60 * 3); // 3分钟周期
const kline4h = exchange.GetRecords(60 * 60 * 4); // 4小时周期
// 数据有效性检查
if (!kline3m || kline3m.length < 50 || !kline4h || kline4h.length < 50) {
return { error: "K线数据不足" };
}
// 计算3分钟周期技术指标
const ema20_3m = TA.EMA(kline3m, 20); // 20周期指数移动平均
const macd_3m = TA.MACD(kline3m, 12, 26, 9); // MACD指标
const rsi7_3m = TA.RSI(kline3m, 7); // 7周期RSI
const rsi14_3m = TA.RSI(kline3m, 14); // 14周期RSI
// 计算4小时周期技术指标
const ema20_4h = TA.EMA(kline4h, 20); // 20周期EMA
const ema50_4h = TA.EMA(kline4h, 50); // 50周期EMA
const macd_4h = TA.MACD(kline4h, 12, 26, 9); // MACD指标
const rsi14_4h = TA.RSI(kline4h, 14); // 14周期RSI
const atr3_4h = TA.ATR(kline4h, 3); // 3周期ATR(波动率)
const atr14_4h = TA.ATR(kline4h, 14); // 14周期ATR
// 获取最新K线和最近10根K线
const latest3m = kline3m[kline3m.length - 1];
const latest4h = kline4h[kline4h.length - 1];
const recent10_3m = kline3m.slice(-10);
const recent10_4h = kline4h.slice(-10);
// 计算平均成交量
const volumes4h = recent10_4h.map(k => k.Volume);
const avgVolume4h = volumes4h.reduce((a, b) => a + b, 0) / volumes4h.length;
// 返回结构化数据...
}
双时间框架策略: - 3分钟短周期:捕捉短期波动,用于精确入场和出场时机 - 4小时长周期:判断大趋势方向,避免逆势交易
这种多时间框架分析是专业量化交易的标准配置,相当于给AI同时提供”显微镜”和”望远镜”两种视角。
return {
symbol: symbol,
current_price: latest3m.Close,
current_ema20: ema20_3m[ema20_3m.length - 1],
current_macd: macd_3m[2][macd_3m[2].length - 1],
current_rsi_7: rsi7_3m[rsi7_3m.length - 1],
funding_rate: fundingRate,
intraday_3min: {
mid_prices: recent10_3m.map(k => k.Close),
ema_20_series: recent10_3m.map((k, i) => ema20_3m[ema20_3m.length - 10 + i]),
macd_series: recent10_3m.map((k, i) => macd_3m[2][macd_3m[2].length - 10 + i]),
rsi_7_series: recent10_3m.map((k, i) => rsi7_3m[rsi7_3m.length - 10 + i]),
rsi_14_series: recent10_3m.map((k, i) => rsi14_3m[rsi14_3m.length - 10 + i])
},
longer_term_4hour: {
ema_20: ema20_4h[ema20_4h.length - 1],
ema_50: ema50_4h[ema50_4h.length - 1],
atr_3: atr3_4h[atr3_4h.length - 1],
atr_14: atr14_4h[atr14_4h.length - 1],
current_volume: latest4h.Volume,
average_volume: avgVolume4h,
macd_series: recent10_4h.map((k, i) => macd_4h[2][macd_4h[2].length - 10 + i]),
rsi_14_series: recent10_4h.map((k, i) => rsi14_4h[rsi14_4h.length - 10 + i])
}
};
1. EMA(指数移动平均线) - 作用:判断趋势方向和支撑/阻力位 - 价格在EMA20上方 → 短期看涨 - EMA20上穿EMA50 → 黄金交叉,买入信号
2. MACD(平滑异同移动平均线) - 作用:判断动量和趋势转折 - MACD柱状图由负转正 → 动量转强 - DIF线上穿DEA线 → 金叉信号
3. RSI(相对强弱指标) - 作用:判断超买超卖 - RSI > 70 → 超买,可能回调 - RSI < 30 → 超卖,可能反弹
4. ATR(真实波动幅度) - 作用:衡量市场波动率,用于调整止损距离
持仓数据获取节点负责追踪每个币种的当前持仓状态,为AI提供完整的仓位信息。
function getAllPositions() {
// 获取当前账户权益
const curequity = exchange.GetAccount().Equity;
// 获取币种列表
const coins = $vars.coinList ?
($vars.coinList.includes(',') ? $vars.coinList.split(',') : [$vars.coinList]) : [];
// 计算每个币种的风险金额 = 账户权益 / 币种数量
const risk_usd = coins.length > 0 ? curequity / coins.length : 0;
// 获取所有实际持仓
const rawPositions = exchange.GetPositions();
// 创建持仓映射表 (币种符号 -> 持仓对象)
const positionMap = {};
if (rawPositions && rawPositions.length > 0) {
for (let pos of rawPositions) {
if (pos.Amount && Math.abs(pos.Amount) > 0) {
// 提取币种符号 (如 BTC_USDT.swap -> BTC)
const coinSymbol = pos.Symbol.replace('_USDT.swap', '')
.replace('.swap', '')
.replace('_USDT', '');
positionMap[coinSymbol] = pos;
}
}
}
// 为每个币种创建position信息
const allPositions = [];
for (let i = 0; i < coins.length; i++) {
const coin = coins[i].trim();
const pos = positionMap[coin];
if (pos) {
// 有持仓的情况 - 构建完整持仓信息
// 获取止盈止损订单ID
const { tpOrderId, slOrderId } = getTPSLOrderIds(pos.Symbol, currentPrice, pos.Type);
// 获取退出计划
const exitPlan = _G(`exit_plan_${pos.Symbol}`) || {
profit_target: null,
stop_loss: null,
invalidation_condition: ""
};
allPositions.push({
symbol: coin,
quantity: Math.abs(pos.Amount), // 持仓数量
entry_price: pos.Price, // 入场价格
current_price: currentPrice, // 当前价格
liquidation_price: /* 强平价格计算 */,
unrealized_pnl: _N(pos.Profit, 2), // 未实现盈亏
leverage: pos.MarginLevel || 1, // 杠杆倍数
exit_plan: exitPlan, // 退出计划
confidence: exitPlan?.confidence || null,
risk_usd: risk_usd, // 风险金额
sl_oid: slOrderId, // 止损订单ID
tp_oid: tpOrderId, // 止盈订单ID
wait_for_fill: false,
entry_oid: pos.Info?.posId || -1,
notional_usd: _N(Math.abs(pos.Amount) * currentPrice, 2)
});
} else {
// 没有持仓的情况 - 所有字段设为null
allPositions.push({
symbol: coin,
quantity: null, // 关键字段:null表示无持仓
entry_price: null,
current_price: null,
liquidation_price: null,
unrealized_pnl: null,
leverage: null,
exit_plan: null,
confidence: null,
risk_usd: risk_usd, // 仍然返回risk_usd用于开仓计算
sl_oid: null,
tp_oid: null,
wait_for_fill: false,
entry_oid: null,
notional_usd: null
});
}
}
return allPositions;
}
const positions = getAllPositions();
return {positions};
quantity字段的关键作用:
- quantity = null:无持仓,AI可以考虑开仓
- quantity ≠ null:有持仓,AI只能持有或平仓,不能加仓
这个设计避免了”金字塔式加仓”的风险,确保每个币种只有一个活跃仓位。
将市场数据和持仓数据合并成AI决策所需的完整上下文。
// 获取输入数据
const inputData = $input.all();
// 第一个输入是市场数据,第二个是持仓数据
const marketData = inputData[0].json.data;
const positions = inputData[1].json;
// 返回整理后的数据
return [{
json: {
marketData: marketData,
positions: positions
}
}];
简洁高效的数据整合,为AI提供统一的数据接口。
这是整个系统的核心——AI决策引擎。它接收完整的市场和账户信息,输出具体的交易指令。

AI智能体的决策依赖于两类提示词:
1. 系统提示词(System Message): - 来源:NOF1网站未公布,根据结果反推得出 - 作用:定义AI的角色、行为规则和决策框架,相当于AI的”操作手册” - 特点:固定不变,每次调用都相同 - 位置:在AI模型调用时作为系统消息传入
2. 用户提示词(Text Prompt): - 来源:NOF1网站公布获取 - 作用:提供动态的市场数据和账户状态,相当于AI的”实时信息输入” - 特点:每次调用都不同,包含最新的市场数据和持仓信息 - 位置:在AI模型调用时作为用户消息传入
这种”固定规则+动态数据”的双提示词架构,让AI既有稳定的决策框架,又能根据实时市场做出灵活响应。
系统提示词定义了AI的行为规则和决策框架,可以分为四个核心部分:
## HARD CONSTRAINTS
### Position Limits
- Tradable coins: {{$vars.coinList}}
- Maximum {{$vars.coinList.split(',').length}} concurrent positions
- No pyramiding or adding to existing positions
- Must be flat before re-entering a coin
### Risk Management
- Maximum risk per trade: 5% of account value
- Leverage range: 5x to 40x
- Minimum risk-reward ratio: 2:1
- Every position must have:
- Stop loss (specific price level)
- Profit target (specific price level)
- Invalidation condition (format: "If price closes below/above [PRICE] on a [TIMEFRAME] candle")
设计哲学: - 位置限制:每个币种持单向仓位,强制分散风险 - 禁止加仓:避免”摊平成本”的陷阱 - 风险上限:单笔交易最多冒5%账户价值的风险 - 风险回报比:至少2:1,意味着盈利目标至少是止损距离的2倍
## DECISION FRAMEWORK
### Identifying Position Status
A coin has an **active position** if `quantity` is NOT null.
A coin has **no position** if `quantity` is null.
### For Coins WITH Active Positions
Check each position in this order:
1. Invalidation condition triggered? → Close immediately
2. Stop loss or profit target hit? → Close
3. Technical setup still valid? → Hold
4. If uncertain → Hold (trust your exit plan)
Available signals: "hold" or "close" ONLY
### For Coins WITHOUT Positions
Only consider if:
- Current active positions < 6
- Available cash > $1000
- You see a high-probability setup
Available signal: "entry" ONLY
逻辑清晰度: - 严格区分”有持仓”和”无持仓”两种状态 - 有持仓时只能选择”持有”或”平仓” - 无持仓时只能选择”开仓”或”跳过” - 这种设计避免了AI产生逻辑冲突的指令
{
"BTC": {
"trade_signal_args": {
"coin": "BTC",
"signal": "entry|hold|close",
"profit_target": 115000.0,
"stop_loss": 112000.0,
"invalidation_condition": "If price closes below 112500 on a 3-minute candle",
"leverage": 15,
"confidence": 0.75,
"risk_usd": 624.38,
"justification": "Reason for this decision"
}
}
}
字段说明:
- signal:交易信号(entry/hold/close)
- profit_target:止盈价格
- stop_loss:止损价格
- invalidation_condition:失效条件(自然语言描述)
- leverage:杠杆倍数(5-40)
- confidence:AI对这个信号的信心(0-1)
- risk_usd:愿意承担的风险金额
- justification:决策理由(用于审计和调试)
## THINKING PROCESS
Before outputting JSON, think through your decisions step by step:
1. Identify position status for each coin
2. Review coins WITH active positions
3. Review coins WITHOUT positions
4. Output final decisions in JSON
这种”思维链”(Chain of Thought)提示让AI先分析再输出,提高决策的稳定性和可解释性。
来源说明:用户提示词使用模板语法动态注入实时数据。
用户提示词在每次调用时都会根据最新的市场状态和账户信息动态生成:
It has been {{ duringtime }} minutes since you started trading.
The current time is {{ $now.toISO() }}
You've been invoked {{ invoketime }} times.
ALL OF THE PRICE OR SIGNAL DATA BELOW IS ORDERED: OLDEST - NEWEST
Timeframes note: Unless stated otherwise in a section title, intraday series
are provided at 3 minute intervals. If a coin uses a different interval, it is
explicitly stated in that coin's section.
**CURRENT MARKET STATE FOR ALL COINS**
{{ JSON.stringify(marketData) }}
**HERE IS YOUR ACCOUNT INFORMATION & PERFORMANCE**
Current Total Return (percent): {{ totalReturnPercent }}
Available Cash: {{ availableCash }}
Current Account Value: {{ currentAccountValue }}
Current live positions & performance:
{{ JSON.stringify(positions) }}
这个设计让AI每次都能获得完整的决策上下文:
时间感知
duringtime分钟)$now.toISO())invoketime次)市场数据(来自”市场数据获取”节点)
账户状态(来自”参数重置”节点)
totalReturnPercent)availableCash)currentAccountValue)持仓详情(来自”持仓数据获取”节点)
┌─────────────────────────────────────────────────────────────┐
│ AI模型调用时刻 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 系统提示词(固定) │
│ ┌────────────────────────────────────────────┐ │
│ │ You are an expert cryptocurrency trader... │ │
│ │ ## HARD CONSTRAINTS │ │
│ │ - Maximum 6 positions │ │
│ │ - Risk per trade: 5% max │ │
│ │ ## DECISION FRAMEWORK │ │
│ │ - For coins WITH positions: hold/close │ │
│ │ - For coins WITHOUT positions: entry │ │
│ │ ## OUTPUT FORMAT │ │
│ │ - JSON with trade_signal_args │ │
│ └────────────────────────────────────────────┘ │
│ ↓ │
│ 用户提示词(动态,每次不同) │
│ ┌────────────────────────────────────────────┐ │
│ │ Running for 126 minutes, invoked 42 times │ │
│ │ Current Total Return: 3.45% │ │
│ │ Available Cash: $10,345.67 │ │
│ │ │ │
│ │ Market Data: │ │
│ │ { │ │
│ │ "BTC": { │ │
│ │ "current_price": 67234.5, │ │
│ │ "current_ema20": 67150.2, │ │
│ │ "current_macd": -141.87, │ │
│ │ "current_rsi_7": 52.93, │ │
│ │ "intraday_3min": {...}, │ │
│ │ "longer_term_4hour": {...} │ │
│ │ }, │ │
│ │ "ETH": {...}, ... │ │
│ │ } │ │
│ │ │ │
│ │ Positions: │ │
│ │ [ │ │
│ │ { │ │
│ │ "symbol": "BTC", │ │
│ │ "quantity": 0.5, │ │
│ │ "entry_price": 66800.0, │ │
│ │ "unrealized_pnl": 217.25, │ │
│ │ "exit_plan": { │ │
│ │ "stop_loss": 66000.0, │ │
│ │ "profit_target": 68500.0 │ │
│ │ } │ │
│ │ }, │ │
│ │ { │ │
│ │ "symbol": "ETH", │ │
│ │ "quantity": null, // 无持仓 │ │
│ │ ... │ │
│ │ } │ │
│ │ ] │ │
│ └────────────────────────────────────────────┘ │
│ ↓ │
│ AI模型处理和推理 │
│ ↓ │
│ AI输出(JSON格式) │
│ ┌────────────────────────────────────────────┐ │
│ │ { │ │
│ │ "BTC": { │ │
│ │ "trade_signal_args": { │ │
│ │ "signal": "hold", │ │
│ │ "justification": "Position valid..." │ │
│ │ } │ │
│ │ }, │ │
│ │ "ETH": { │ │
│ │ "trade_signal_args": { │ │
│ │ "signal": "entry", │ │
│ │ "profit_target": 2800.0, │ │
│ │ "stop_loss": 2600.0, │ │
│ │ "leverage": 15, │ │
│ │ "risk_usd": 833.33, │ │
│ │ "justification": "Bullish setup..." │ │
│ │ } │ │
│ │ } │ │
│ │ } │ │
│ └────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
↓
传递给"交易执行"节点
这种双提示词架构的优势:
这是工作流的”手”,负责将AI的决策翻译成实际的交易所订单,并持续监控止盈止损条件。
交易执行节点分为五个功能模块:
// ========== 工具函数 ==========
function parseAIOutput(output) {
try {
// 清理输出中的代码块标记
const cleaned = output.replace(/```[a-z]*\n?/gi, '').trim();
const start = cleaned.indexOf('{');
const end = cleaned.lastIndexOf('}');
return JSON.parse(cleaned.substring(start, end + 1));
} catch (e) {
return {};
}
}
// 主逻辑
const signals = parseAIOutput($input.first().json.output);
Log(signals)
异常处理: - 捕获JSON解析错误 - 清理AI输出中的markdown格式 - 防止因AI输出格式问题导致整个系统崩溃
// 获取交易对精度信息
function getPrecision(coin) {
try {
const symbol = coin + '_USDT.swap';
const markets = exchange.GetMarkets();
if (markets && markets[symbol]) {
return {
price: markets[symbol].PricePrecision || 0,
amount: markets[symbol].AmountPrecision || 0,
minQty: markets[symbol].MinQty || 5
};
}
return { price: 0, amount: 0, minQty: 5 };
} catch (e) {
Log(`⚠️ 获取${coin}精度失败,使用默认值`);
return { price: 0, amount: 0, minQty: 5 };
}
}
// 计算仓位大小
function calculateQuantity(entryPrice, stopLoss, riskUsd, leverage, precision) {
const riskPerContract = Math.abs(entryPrice - stopLoss);
if (riskPerContract <= 0) return 0;
// 基于风险金额计算数量
const quantity = riskUsd / riskPerContract;
// 限制最大仓位 = (账户余额 × 杠杆 / 6) / 入场价格
const maxQuantity = (exchange.GetAccount().Balance * leverage / 6) / entryPrice;
let finalQuantity = Math.min(quantity, maxQuantity);
// 应用精度和最小数量限制
if (precision) {
finalQuantity = _N(finalQuantity, precision.amount);
if (finalQuantity < precision.minQty) {
Log(`⚠️ 计算数量 ${finalQuantity} 小于最小下单量 ${precision.minQty}`);
return 0;
}
}
return finalQuantity;
}
仓位计算公式:
风险距离 = |入场价格 - 止损价格|
仓位大小 = 风险金额 ÷ 风险距离
最大仓位 = (账户余额 × 杠杆 ÷ 6) ÷ 入场价格
最终仓位 = min(仓位大小, 最大仓位)
这种计算方式确保: - 无论价格高低,风险金额始终恒定 - 止损被触发时,损失正好是预设的风险金额 - 不会因为杠杆过大导致仓位过重
function executeEntry(coin, args) {
exchange.SetCurrency(coin + '_USDT');
exchange.SetContractType("swap");
const ticker = exchange.GetTicker();
if (!ticker) return;
const currentPrice = ticker.Last;
if (!validateEntry(coin, currentPrice, args.profit_target, args.stop_loss)) return;
const leverage = args.leverage || 10;
exchange.SetMarginLevel(leverage);
precision = getPrecision(coin);
quantity = calculateQuantity(currentPrice, args.stop_loss, args.risk_usd, leverage, precision);
if (quantity <= 0) {
Log(`⚠️ ${coin}:计算数量无效,跳过开仓`);
return;
}
const isLong = args.profit_target > args.stop_loss;
exchange.SetDirection(isLong ? "buy" : "sell");
const orderId = isLong ? exchange.Buy(-1, quantity) : exchange.Sell(-1, quantity);
if (orderId) {
Sleep(1000);
Log(`✅ ${coin}:开${isLong ? '多' : '空'} 数量=${quantity} 杠杆=${leverage}x 精度=${precision.amount}`);
} else {
Log(`❌ ${coin}:开仓失败`, precision.amount);
}
}
function executeClose(coin) {
exchange.SetCurrency(coin + '_USDT');
exchange.SetContractType("swap");
// 取消所有挂单
const orders = exchange.GetOrders();
orders?.forEach(o => exchange.CancelOrder(o.Id));
// 获取持仓信息
const pos = exchange.GetPositions().find(p =>
p.Symbol.includes(coin) && Math.abs(p.Amount) > 0
);
if (!pos) return;
const isLong = pos.Type === PD_LONG || pos.Type === 0;
const precision = getPrecision(coin);
// 对平仓数量应用精度
const closeAmount = _N(Math.abs(pos.Amount), precision.amount);
exchange.SetDirection(isLong ? "closebuy" : "closesell");
const orderId = isLong ?
exchange.Sell(-1, closeAmount) :
exchange.Buy(-1, closeAmount);
if (orderId) {
Log(`✅ ${coin}:平${isLong ? '多' : '空'}成功,数量=${closeAmount}`);
_G(`exit_plan_${coin}_USDT.swap`, null);
}
}
function monitorPosition(coin) {
exchange.SetCurrency(coin + '_USDT');
exchange.SetContractType("swap");
const pos = exchange.GetPositions().find(p =>
p.Symbol.includes(coin) && Math.abs(p.Amount) > 0
);
if (!pos) return;
const ticker = exchange.GetTicker();
if (!ticker) return;
const isLong = pos.Type === PD_LONG || pos.Type === 0;
const currentPrice = ticker.Last;
// 计算盈亏比例
const pnl = (currentPrice - pos.Price) * (isLong ? 1 : -1) / pos.Price;
// 获取退出计划
const exitPlan = _G(`exit_plan_${coin}_USDT.swap`);
if (!exitPlan?.profit_target || !exitPlan?.stop_loss) {
// 如果没有设置退出计划,使用默认值
if (pnl >= 0.03) return closePosition(coin, pos, isLong, "止盈", pnl);
if (pnl <= -0.01) return closePosition(coin, pos, isLong, "止损", pnl);
return;
}
// 检查止盈条件
const shouldTP = isLong ?
currentPrice >= exitPlan.profit_target :
currentPrice <= exitPlan.profit_target;
// 检查止损条件
const shouldSL = isLong ?
currentPrice <= exitPlan.stop_loss :
currentPrice >= exitPlan.stop_loss;
if (shouldTP) return closePosition(coin, pos, isLong, "止盈", pnl);
if (shouldSL) return closePosition(coin, pos, isLong, "止损", pnl);
}
function closePosition(coin, pos, isLong, reason, pnl) {
const precision = getPrecision(coin);
const closeAmount = _N(Math.abs(pos.Amount), precision.amount);
exchange.SetDirection(isLong ? "closebuy" : "closesell");
isLong ? exchange.Sell(-1, closeAmount) : exchange.Buy(-1, closeAmount);
Log(`${reason === '止盈' ? '✅' : '❌'} ${coin} ${reason} ${(pnl*100).toFixed(2)}%`);
_G(`exit_plan_${coin}_USDT.swap`, null);
}
为方便了解AI交易运行逻辑,将AI交易信号分析和持仓状态进行可视化呈现。

系统同时使用3分钟和4小时两个周期,这不是简单的数据冗余:
案例场景: - 4小时图显示BTC在上升趋势中(价格在EMA20上方) - 3分钟图出现回调(价格短期下跌) - 决策:这是”趋势中的回调”,是加仓机会而非风险信号
双周期配合: - 4小时判断方向(做多还是做空) - 3分钟寻找入场点(何时进场)
单笔最大风险 = 账户价值 ÷ 币种数量
最多6个持仓 = 理论最大总风险30%
实际最大风险 < 30%(不会同时触发6个止损)
止损距离 = |入场价 - 止损价| / 入场价
典型设置:2-5%
结合杠杆:10x杠杆下,5%价格波动 = 50%本金波动
示例:"如果价格在3分钟K线上收盘低于$66500"
作用:即使止损没触发,技术形态破坏也要离场
为什么要求JSON格式? - 结构化数据易于解析 - 避免自然语言的歧义 - 便于自动化验证和处理
为什么强制字段一致性? - 确保所有信号包含相同的字段结构 - 简化解析代码逻辑 - 避免因字段缺失导致的错误
无法处理突发事件
固定周期的局限
杠杆风险
AI模型的稳定性
引入新闻情绪分析
动态调整触发频率
多模型投票机制
增加回测验证
这个AI量化交易系统展示了如何将大语言模型应用于实际的金融交易场景。其核心优势在于:
关键启示: - AI不是万能的,需要严格的约束和规则 - 风险管理比预测准确率更重要 - 系统的可靠性比策略的复杂度更关键
希望这篇详细的技术拆解能帮助你理解AI量化交易的运作逻辑,并在自己的实践中做出更明智的决策。
完整源码与实盘记录: - 发明者量化平台:https://www.fmz.com/strategy/512685 - 实盘地址:https://www.fmz.com/robot/623016 - 可替换不同AI模型、调整提示词、选择交易币种
风险提示: - 本文仅供技术学习,不构成投资建议 - 加密货币交易风险极高,可能导致本金全部损失 - 务必在充分测试后再使用真实资金